Search code examples
fragmentglsl

Sharing variables in fragment shader GLSL


I have tried this fragment shader.

But the result is unexpected.

void main() {
    float test;
    if(gl_FragCoord.x == 300.0) {
        test = 1.0;
    }

    gl_FragColor = vec4(test, 1, 1, 1);
} 

This program makes all fragments white colored. But it's unexpected because shaders run asynchronously for each fragment.

Note that the colour is dependent to value of test in the if block. For example, if I change it to 0 it will fill all frags with lightblue.

I had expected it to just fill fragments with x=300. How can I do it?


Solution

  • This code exhibits undefined behavior, since you never initialize test.

    Furthermore, even if you did, the condition itself will almost certainly never be fulfilled. gl_FragCoord is not required to be an integer, so you're doing floating-point equality. The system is not required to provide exact values, so such equality tests will almost certainly fail.