Mik*_*ant 0 opengl glsl fragment-shader
好的,所以我有一个非常大的正方形(网格),我用三角形组成,然后应用高度图来碰撞它.我现在要做的是获得网格线.我已经找到了一种方法来做到这一点,但这会导致片段着色器中的33个if语句仅用于x,然后另外33个用于y.我被告知我可以使用我现在正在做的事情并稍微不同地实现它(使用一些GLSL函数)只需要1或2个if语句.这是我目前的代码(并非所有代码都已完成,但可以让您了解我在做什么.)
#version 330
uniform sampler2D texture;
in vec2 texCoord;
layout (location=0) out vec4 fragColour;
void main(void) {
vec4 newColor;
vec2 line = texCoord * 32; // makes texCoords easier to number (as divided by 32 in the C++array)
if(line.x > 0 && line.x < 0.9)
{
newColor = vec4(1.0,1.0,1.0,1.0);
}
else if(line.x > 1 && line.x < 1.9)
{
newColor = vec4(1.0,1.0,1.0,1.0);
}
else if(line.x > 2 && line.x < 2.9)
{
newColor = vec4(1.0,1.0,1.0,1.0);
}
else if(line.x > 3 && line.x < 3.9)
{
newColor = vec4(1.0,1.0,1.0,1.0);
}
else if(line.x > 4 && line.x < 4.9)
{
newColor = vec4(1.0,1.0,1.0,1.0);
}
else if(line.x > 5 && line.x < 5.9)
{
newColor = vec4(1.0,1.0,1.0,1.0);
}
else if(line.x > 6 && line.x < 6.9)
{
newColor = vec4(1.0,1.0,1.0,1.0);
}
else if(line.x > 7 && line.x < 7.9)
{
newColor = vec4(1.0,1.0,1.0,1.0);
}
else if(line.x > 8 && line.x < 8.9)
{
newColor = vec4(1.0,1.0,1.0,1.0);
}
else if(line.x > 9 && line.x < 9.9)
{
newColor = vec4(1.0,1.0,1.0,1.0);
}
else if(line.x > 10 && line.x < 10.9)
{
newColor = vec4(1.0,1.0,1.0,1.0);
}
else if(line.x > 11 && line.x < 11.9)
{
newColor = vec4(1.0,1.0,1.0,1.0);
}
else if(line.x > 12 && line.x < 12.9)
{
newColor = vec4(1.0,1.0,1.0,1.0);
}
else if(line.x > 13 && line.x < 13.9)
{
newColor = vec4(1.0,1.0,1.0,1.0);
}
else if(line.x > 14 && line.x < 14.9)
{
newColor = vec4(1.0,1.0,1.0,1.0);
}
else if(line.x > 15 && line.x < 15.9)
{
newColor = vec4(1.0,1.0,1.0,1.0);
}
else if(line.x > 16 && line.x < 16.9)
{
newColor = vec4(1.0,1.0,1.0,1.0);
}
else if(line.x > 17 && line.x < 17.9)
{
newColor = vec4(1.0,1.0,1.0,1.0);
}
else if(line.x > 18 && line.x < 18.9)
{
newColor = vec4(1.0,1.0,1.0,1.0);
}
else if(line.x > 19 && line.x < 19.9)
{
newColor = vec4(1.0,1.0,1.0,1.0);
}
else if(line.x > 20 && line.x < 20.9)
{
newColor = vec4(1.0,1.0,1.0,1.0);
}
else if(line.x > 21 && line.x < 21.9)
{
newColor = vec4(1.0,1.0,1.0,1.0);
}
else if(line.x > 22 && line.x < 22.9)
{
newColor = vec4(1.0,1.0,1.0,1.0);
}
else if(line.x > 23 && line.x < 23.9)
{
newColor = vec4(1.0,1.0,1.0,1.0);
}
else if(line.x > 24 && line.x < 24.9)
{
newColor = vec4(1.0,1.0,1.0,1.0);
}
else
{
newColor = vec4(0.0,0.0,0.0,1.0);
}
fragColour = newColor;
}
Run Code Online (Sandbox Code Playgroud)
除非绝对必要,否则你不应该使用控制流(除了统一之外的东西)(至少这是我上次写一个glsl着色器时的标准建议).在您的情况下,不需要控制流程.使用step,smoothstep,mix和乘法避免控制流.
您的"if/else"代码段可以使用类似的(未经测试的代码)实现:
fragColor = mix(vec4(0.0, 0.0, 0.0, 0.0), vec4(1.0, 1.0, 1.0, 1.0), step(fract(line.x), 0.9));
或者使用纹理查找.纹理查找可能比数值计算更快,具体取决于硬件(和纹理大小)
请注意,使用"step"可能会在遥远的表面上产生锯齿状的非抗锯齿边缘和噪声/波纹图案."OpenGL橙皮书"("OpenGL着色语言")有一些例子可以解释如何处理它.但是,使用纹理查找可能更容易.首先,您可以尝试使用"smoothstep"而不是"step".
或者,您也可以简单地在实体渲染景观的顶部以线框模式重绘整个景观.