OpenGL inverse depth calculation

Joe's picture

Using gluUnproject is perfectly adequate for telling where a mouse click went in a 3D world, but when you have a large number of depth points that you want to transform (like when you are using the depth map of a mesh to perform visibility calculations) then it is rather slow and unwieldy.

So I decided to do the inverse depth calculations myself. However I couldn't find anywhere the maths to do the conversion from the value you get from glreadpixels (which is a float in the range 0 to 1) to an actual depth value (i.e. the z value in camera co-ordinates). After spending far too long just messing around with stuff and searching the web, I sat down and actually worked it out and it's this:

    z = ( (2*zFar*zNear) / (zNear-zFar) ) / ( ((depth * 2)-1.0) - ((zFar+zNear) / (zFar-zNear)) )

where depth is the value you get from glreadpixels and z is the actual value you want.

Why can't they just put that in the docs somewhere?

Joe

Re: OpenGL inverse depth calculation

Hi...

Finally I find something in relation to this.
I have tried your equation and it works fine if the zFar/zNear relation is not big.
I tried it with zNear = 2, zFar = 4 and it seems to work ok, but if I begin moving the zFar plane backwards, it begins adding error to the real z.
Have you made any improvements to this equation?

Cheers,

Victor

Re: OpenGL inverse depth calculation

Joe's picture

Hi Victor,

I haven't made any improvements to it. Like I said, I simply reversed the maths in the documentation and this is what came out. Maybe there are some extra things I missed out that don't affect the ranges I am working in.

Try looking at the code for gluUnProject if this isn't working for you.

Joe

Post new comment

The content of this field is kept private and will not be shown publicly.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd> <p>
  • Lines and paragraphs break automatically.
  • You may quote other posts using [quote] tags.

More information about formatting options

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
Image CAPTCHA
Enter the characters shown in the image.