Search code examples
openglglslopengl-3depth-testing

Force depth test against a specific depth value, instead of fragment's actual depth


I want to draw some primitives behind everything that wrote to the depth buffer by using glDepthFunc(GL_EQUAL) and writing to every pixel that has a depth of 1.0 (the highest and default value)

However, for this to work I have to ignore the calculated Z-depth on my primitives, forcing them to test as if it were 1.0 for all of them.

What would be the easiest way to force all fragments in a specific draw to test as having a z-depth of 1.0 regardless of the actual z-depth calculated in the vertex shader?


Solution

  • If you want that all fragments have a depth of 1.0, the you've to ensure, that the z component of the normalized device coordinate is 1.0.
    The normalized device coordinate is calculated by a perspective divide form the clip coordinate (think about that as gl_Position.xyz / gl_Position.w).

    Set gl_Position.z equal gl_Position.w, after the clip coordinate is set, that causes that gl_Position.z / gl_Position.w is 1.0:

    gl_Position.z = gl_Position.w; 
    

    But note, the depth of a fragment can also be set in the fragment shader, by assigning a value to gl_FragDepth:
    (Of course this prevents that the Early Fragment Test can take place)

    gl_FragDepth = 1.0;