# Retrieving eye-space position from depth buffer?

Apologies for asking a question that’s been asked several times before in various forms, but…how do I reconstruct the eye-space coordinates of a pixel given its corresponding raw depth buffer value?

Here’s my current, incorrect code (based on the docs for gluUnproject):

``````// BAD CODE -- DOESN'T WORK!!!

// Sample the depth buffer (stored as float32 data)
float rawDepth = texture2D(depthTex, texCoord.xy).r;

// Construct clip-space position using gl_FragCoord, raw
// depth value, and the GL viewport
vec4 clipPos = vec4(
2.0 * (gl_FragCoord.x - viewport.x) / viewport.z - 1.0,
2.0 * (gl_FragCoord.y - viewport.y) / viewport.w - 1.0,
2.0 * rawDepth - 1.0,
1.0
);

// Multiply by inverse projection matrix to get
// eye-space position
vec4 eyePos = matInverseProj * clipPos;

``````

But this doesn’t seem to work 100%. Am I missing a perspective divide by W somewhere? Do I need to pre-process the raw depth value before using it in the formula for clipPos?

Thanks!

• cort

Yes, only at the end, add:

eyePos = eyePos/eyePos.w;

Yup, that did the trick. Thanks!

Just one thing to watch out for, usually reading the depth value directly from a depth texture often gives wonky results for lighting calculations (the case is much less so using a Float32 buffer as you are)… when doing differed shading, I’d recommend storing eyePos_z (i.e. store linear z), and you can extract eyePos_x and eyePos_y from it. The wonkiness comes from the perspective divide.

This topic was automatically closed 183 days after the last reply. New replies are no longer allowed.