z-buffer and texture

Hi,

i am trying to get the depth values of all my scene in a texture. I copy the z-buffer in my texture, but all values are clamped to [0.0, 1.0] and my far clip plane is at 500. How can i get the real value in my system coordinate space of the depth (ie beetwen 0.1 and 500) ?

thanks.

I also want to know how to solve this problem, anyone can help us?

Why don’t you just multiply the z-value in the depth buffer by 500?

Actually it’s not that simple. The multiplication by 500 would be valid if the near plane is at 0.0 which is not the case in most situations.

glFrustum is defined as:

So the depth value stored in the depth buffer is:

( C * Zoriginal + D ) / (-Zoriginal)

=

-C - D / (Zoriginal)

To compute the original depth value:

  • read depth-value
  • add C
  • compute the inverse (reciprocal)
  • multiply by -D

NiCo

Thanks a lot,
I found another which is to use the function gluUnProject with the depth value.

Nico it’s very nice from you to help people, but let me correct some things you wrote. No offense intended. Just trying to make things a bit better.

The multiplication by 500 would be valid if the near plane is at 0.0 which is not the case in most situations.
This is true in orthographic view. But in perspective view, near=0 leads to nothing (all depth values get the same result, just like 1-bit depth buffer, which is pointless obviously).

In the matrix, the C and D values are in fact the opposite of what the picture shows, that is :
C = -(far+near)/(far-near)
D = -2farnear/(far-near)
It leads to negative Z values, so it’s common use to use the opposite Z in the end, but at this point it’s better to keep Z as negative since it’s not “the end” yet (see below).

To compute the original depth value:
- read depth-value
- add C
- compute the inverse (reciprocal)
- multiply by -D
In fact there is another transformation between eye Z and depth buffer : the viewport transformation. (see chapter 2.11.1 in OpenGL1.5 specifications).
If we ignore this transformation, things will go wrong, for instance compute Zoriginal from depth =0 with the aforementioned equation :

  • read depth-value –> 0
  • add C –> (f+n)/(f-n)
  • compute the inverse –> (f-n)/(f+n)
  • multiply by -D –> -(fn/(f-n))((f-n)/(f+n)) = -f*n/(f+n)
    And this is not the correct result.
    With perspective projection, the depth value 0 should correspond to Zoriginal=near.

I found another which is to use the function gluUnProject with the depth value
This might work pretty well for a single transformation, but if you have to deal with tons of depth computations, you might want to use your own conversion function because gluProject and gluUnproject are not very well optimized (since they take into account the general case for any kind of modelview/projection matrices)