How do the mathematics in this depth retrieval function work? I assume it's converting from screen to world space. The terms look strikingly like those found in the projection matrix I ended up using in my CPU-side code:

This computes the negative of eye-space Z (so +near..+far) from window-space Z (0..1) with the assumptions: 1) a perspective projection was used for rendering, 2) glDepthRange == 0..1, and 3) w_eye == 1 (true for a point). Add a leading negative to it and it computes eye-space Z (i.e. -near..-far).

(No, I didn't just figure that out -- have read that and done it before :-)

Yeah, you can get this from the perspective projection matrix, which takes you from eye-space to clip-space. To get from clip-space to NDC space, divide by w. To get from NDC to window-space, shift/scale -1..1 to 0..1.

Here's the jist of it:

Code :

// First, multiply (0,0,z_eye,1) by projection matrix to get z_clip and w_clip), then just plug them into
// the following equation, as we'll do below:
z_ndc = z_clip / w_clip
z_ndc = [ z_eye*gl_ProjectionMatrix[2].z + gl_ProjectionMatrix[3].z ] / -z_eye