Search code examples
opengl-esfragment-shaderopengl-es-3.0depth-testing

Doing a per-fragment DEPTH_TEST in OpenGL


I can toggle depth testing on/off in OpenGL using glEnable( GL_DEPTH_TEST ); But this switches the test on/off for the entire draw call.

I would like to control the test on a per-fragment basis.

This is to achieve the following effect: in a chess-board pattern, half the pixels of the primitive are potentially occluded, but the other half are always drawn, even if there is an occluding object in the frame-buffer that is nearer to the camera.

To illustrate, see this example where only half the pixels of the pyramid are potentially occluded by the box in front of it.

Note that the red box is drawn first, and is already in the frame-buffer when the green pyramid is drawn.

Also note: I will draw the object with the special depth test last, so the case where the red box is drawn first would not happen.

For my purposes, all objects drawn this way are convex and will never occlude itself.

illustration of the effect

I know how to get a chessboard pattern in my fragment shader:

                float xm2 = mod( gl_FragCoord.x, 2.0 );
                float ym2 = mod( gl_FragCoord.y, 2.0 );
                if ( int(xm2) != int(ym2) )
                        discard;

But in my case, I don't want to flat out discard on a per-fragment basis, I just want the depth test toggled on a per-fragment basis.

I am targeting OpenGL-ES 3.0.


Solution

  • This is easily achieved by drawing the (red) mesh twice:

    • First draw it normally, all fragments, with depth test enabled.
    • Next draw it again, without depth-test, and discarding half the fragments.

    The solution was prompted by the comment made by @derhass.