opengl-esshaderfragment-shader

Weird fragment shader behaviour upon two conditions


I'm developing an Android app that uses OpenGL-ES, and recently I've ran into a very bizarre issue when coding in the fragment shader. I have my textures, and I'm trying to draw a pixel grid in them with the following code:

#type fragment
#version 300 es

precision mediump float;

uniform sampler2D uTexture;

in vec4 fColor;
in vec2 fTexCoordinate;

out vec4 color;

void main() {
    if (fColor.xyzw == vec4(0, 0, 0, 0)) {
        float x = fTexCoordinate.x;
        float y = fTexCoordinate.y;
        float targetX = round(x * 1000.0) / 1000.0;
        float targetY = round(y * 1000.0) / 1000.0;
        bool paintVertical = abs(x - targetX + 0.0001) < 0.0001;
        bool paintHorizontal = abs(y - targetY + 0.0001) < 0.0001;
        if (paintHorizontal) {
            color = vec4(1.0, 0.0, 0.0, 1.0);
            return;
        }
        color = texture(uTexture, fTexCoordinate);
    } else {
        color = fColor;
    }
}

When I run the program with this shader, the horizontal lines are perfectly drawn (they seem unaligned due to the distance): Red lines generated by the shader.

Now, if I replace if (paintHorizontal) with if (paintVertical), I also get a correct result:

Vertical lines.

But if I simply do both at the same time, with if (paintHorizontal || paintVertical), I get this weird result:

Unaligned lines.

What is going on here?


Solution

  • Almost certainly a precision issue, try precision highp float;.