Search code examples
androidopengl-esglsl

gl_FragCoord values always remain static


I'm trying to read gl_FragCoord x, y and z values and color my triangle according to them. The problem is my triangle always renders yellow.

As far as I understood gl_FragCoord is a variable that is passed down to pixel shader to describe the 'playheads' location, so I'm expecting for gl_FragCoord.x/y/z values to change and my triangle will get rendered with some kind of gradient, but it renders yellow. What am I missing?

Vertex shader:

uniform    mat4        uMVPMatrix;
attribute  vec4        vPosition;

void main() 
{
    gl_Position = uMVPMatrix * vPosition;
}

Pixel shader:

precision mediump float ;        

void main() 
{
    gl_FragColor = vec4( gl_FragCoord.x, gl_FragCoord.y, gl_FragCoord.z, 1 );
}

Solution

  • gl_FragCoord gives the fragment position in window pixel coordinates (window, not viewport!):

    gl_FragCoord is an input variable that contains the window relative coordinate (x, y, z, 1/w) values for the fragment.

    https://registry.khronos.org/OpenGL-Refpages/gl4/html/gl_FragCoord.xhtml

    Except for the bottom-left-most pixel of the screen, gl_FragCoord is >= 1.

    gl_FragColor expects a floating point value in the open range (0, 1), and clips values outside of that range. You'll need to subtract the screen coordinates of the origin of the viewport from gl_FragCoord, then divide the difference by the width/height of the viewport.