Z-value to world-space distance ?

Let’s imagine i have a ray passing through the center of the screen. It is defined by an origin (the center of the screen, in world space), a direction (the direction the camera is “looking at”, in world space);

Now, say i read back the Z-value from the depth buffer, for the exact center of the screen.

This Z value corresponds to a distance D along the ray passing through the center of the screen.

Given Z, i want to calculate D as precisely as possible… does anybody know the formula for computing values in the Z buffer (probably based on D and the ZNear/Zfar values? haven’t found anything in the spec).



Check out the GLU commands gluProject and gluUnproject etc. Should help. Note: you need the entire projection matrix for correct calculation (only ZNear/ZFar does not suffice). Also, note that things like PolygonOffset affects the values of the Z buffer, so you should not use it if you need accurate values.

Dorbie’s solution should work for your specific problem (the center of the screen), I believe. How about the geometrical distance to points that are not at the center of the screen? “Distance correct fog” comes to mind…

Thanks Dorbie, that was exactly what i was looking for.


Marcus, that gives you eye z anywhere on the screen. Converting this to distance is simple trig if you have the location and frustum.