compute distance from depth value

given a depth value taken from a depth texture I want to calculate the actual distance of a texel to the camera. the documentation tells me:

http://unity3d.com/support/documentation/Components/SL-DepthTextures.html

Pixel values in the depth texture
range from 0 to 1 with a nonlinear
distribution. Precision is usually 24
or 16 bits, depending on depth buffer
used. When reading from depth texture,
a high precision value in 0…1 range
is returned. If you need to get
distance from the camera, or otherwise
linear value, you should compute that
manually.

my question is how to compute that manually.

According to this nice post, the zbuffer values are ditributed like this:

a = zFar / ( zFar - zNear )
b = zFar * zNear / ( zNear - zFar )
z = distance from the eye to the object

z_buffer_value =  a + b / z 

If you reverse the calculation you will get:

z = b / (z_buffer_value-a)

I’m not sure if that’s right for all hardware out there but if the article isn’t completely wrong it should work. Don’t expect a good precision since the stored value is non linear and those calculations won’t help to make the result more accurate :wink: At least it should produce a value near the original distance.

edit

the documentation states that there are some macros that compute the distance for you. Read the page carefully, i guess DECODE_EYEDEPTH is what you want.

If you just need a single point distance and not inside a shader you should use a Raycast instead :wink: