Position Reconstruction from Depth by inverting Perspective Projection

Posted by user1294203 on Game Development See other posts from Game Development or by user1294203
Published on 2012-06-20T16:06:26Z Indexed on 2012/06/20 21:26 UTC
Read the original article Hit count: 266

I had some trouble reconstructing position from depth sampled from the depth buffer. I use the equivalent of gluPerspective in GLM. The code in GLM is:


template  
GLM_FUNC_QUALIFIER detail::tmat4x4 perspective
(
    valType const & fovy, 
    valType const & aspect, 
    valType const & zNear, 
    valType const & zFar
)
{
    valType range = tan(radians(fovy / valType(2))) * zNear;    
    valType left = -range * aspect;
    valType right = range * aspect;
    valType bottom = -range;
    valType top = range;

    detail::tmat4x4 Result(valType(0));
    Result[0][0] = (valType(2) * zNear) / (right - left);
    Result[1][2] = (valType(2) * zNear) / (top - bottom);
    Result[2][3] = - (zFar + zNear) / (zFar - zNear);
    Result[2][4] = - valType(1);
    Result[3][5] = - (valType(2) * zFar * zNear) / (zFar - zNear);
    return Result;
}

There doesn't seem to be any errors in the code. So I tried to invert the projection, the formula for the z and w coordinates after projection are:

enter image description here

and dividing z' with w' gives the post-projective depth (which lies in the depth buffer), so I need to solve for z, which finally gives:

enter image description here

Now, the problem is I don't get the correct position (I have compared the one reconstructed with a rendered position). I then tried using the respective formula I get by doing the same for this Matrix. The corresponding formula is:

enter image description here

For some reason, using the above formula gives me the correct position. I really don't understand why this is the case. Have I done something wrong? Could someone enlighten me please?

© Game Development or respective owner

Related posts about math

Related posts about depth-buffer