I'm currently trying to implement a fragment shader that discards all fragments that have a great distance to the current depth value. The wished for effect: clipping decals. All fragments near to a wall get rendered. All fragments that are overlaping should get discard.
My setup is as follows:
1. Render the scene into a framebuffer object with a depth buffer attached.
2. Load the depth buffer as texture into the fragment shader.
3. Render the decals
In the fragment shader I have now two depth values, one from gl_FragCoord and one from the texture. Let calls them: fragDepth and textDepth.
float fragDepth = gl_FragCoord.z;
float textDepth = texture2D( depth_texture, gl_FragCoord.xy ).r;
So far, so good. But the next step fails (flickering/does not what it should):
float depthDiff = textDepth - fragDepth;
float threshold = 0.005;
if( depthDiff > threshold )
{
discard;
}
I'm assuming this fails due to precision issues (?)
What is the best way to proceed? Linearize the depth values? Or am I here completly on the wrong path?