gl_FragDepth computation


I’ve got two seemingly stupid problems regarding depth writes in shader (the first one could very well go to the beginner’s section, but anyway)

1st (sillier):

From steve baker’s many-times referenced article about z-buffer, we have the following :

a = zFar / ( zFar - zNear )
b = zFar * zNear / ( zNear - zFar )
gl_FragDepth = a + (b / eyeZ)

But, since ‘a’ is positive & usually around 1, and ‘b’ negative, shouldn’t eyeZ be positive, in order to get a value less than 1.0? But eyeZ is always negative. So, in the above formula eyeZ should be positive, or my logic is dead wrong??


I have some quads for which I want to specify depth. I have some linear depth values in a texture, from 0.0 to 1.0, and I want to map them in order to recreate a virtual volume (cube), say with an extent cubeExt.

Now, when I render the quads, in the fragment shader I add cubeExt*sampledDepth to the eyeZ, and using the above formula, I compute & write gl_FragDepth. But the results are … wrong. The code is this :

float new_eyez = - (eyez - cubeExtent*sampledDepth);
a = zFar / ( zFar - zNear )
b = zFar * zNear / ( zNear - zFar )
gl_FragDepth = a + (b / new_eyez)

Is there anything wrong with the above?? (should be I guess)

Many thanks,

  1. Yes, if written this way eyeZ should be positive.
  2. Could you describe the results in more detail?

Distance and Z buffer can be converted with help of two values from the projection matrix:
Z = pm[3].z/(Zbuffer * -2.0 + 1.0 - pm[2].z)

In your case:

Zbuffer = (pm[3].z/ Z + pm[2].z -1.0)*-0.5

Thanks guys,

oc2k1 : shouldn’t the formula, if we replace the pm[3].z & pm[2].z with their variable equivalents (-2/(far - near), -(far + near)/(far - near)), result in the same formula I wrote initially? (Either it doesn’t, or I’ve forgotten maths)

Xmas : Actually I found and solved the problem, but another one (which I expected) appeared. I’m trying to pack the depth values along with transparency (its either opaque or not), but the mipmap generation unleashes hell to the values as I lose my 0-or-1 transparency. Any chance to pack 1-bit transparency with 7-bit depth values, in a mipmap friendly way?? (probably asking too much)

The ‘wanted’ look is like this :

The problem looks like this :
(in the outlines of objects the depth values are completely wrong, so they pop up front)

This topic was automatically closed 183 days after the last reply. New replies are no longer allowed.