Depth testing
Depth Buffer
- stores depth values which are used to determine which fragment is in front
- stores information per fragment and it has the same size as color buffer
- automatically created by the windowing system, most systems 24-bit
Depth Testing:
- depth testing is done in screen space after the fragment shader has run
- when enable, OpenGL tests the depth value of a fragment against the content of the depth buffer:
- if PASS, fragment is rendered and the depth buffer is updated with the new depth value (z-value)
- if FAIL, fragment is discarded
<aside>
💡 Today most GPUs support a hardware feature called early depth testing. Early depth testing allows the depth test to run before the fragment shader runs. Whenever it is clear a fragment isn't going to be visible (it is behind other objects) we can prematurely discard the fragment.
</aside>
Z-Fighting:
<aside>
💡 A common visual artifact may occur when two planes or triangles are so closely aligned to each other that the depth buffer does not have enough precision to figure out which one of the two shapes is in front of the other. The result is that the two shapes continually seem to switch order which causes weird glitchy patterns. This is called z-fighting, because it looks like the shapes are fighting over who gets on top

</aside>
- The first and most important trick is never place objects too close to each other in a way that some of their triangles closely overlap. By creating a small offset between two objects you can completely remove z-fighting between the two objects
- The second trick is to set the near plane as far as possible.
- Another great trick at the cost of some performance is to use a higher precision depth buffer. Most depth buffers have a precision of 24 bits, but most GPUs nowadays support 32 bit depth buffers, increasing the precision by a significant amount.
Questions:
- how are depth values being calculated in the first place?
glDepthMask(GL_FALSE);
→ How does this work? If we don’t update the depth buffer, then how does it figure out what’s in front?