Haydn V. Harach
Haydn V. Harach

Reputation: 1275

Reconstructing position from depth buffer - missing Z?

I'm implementing deferred shading in my OpenGL app, and rather than waste waaay too much memory storing position information, I want to reconstruct the view-space position in the fragment shader using information from the depth buffer. It appears as though I have correct x/y, though I'm not completely sure, but I know that my z information is out the window. Here's the part of the fragment shader responsible for reconstructing the position:

vec3 reconstructPositionWithMat(void)
{
    float depth = texture2D(depthBuffer, texCoord).x;
    depth = (depth * 2.0) - 1.0;
    vec2 ndc = (texCoord * 2.0) - 1.0;
    vec4 pos = vec4(ndc, depth, 1.0);
    pos = matInvProj * pos;
    return vec3(pos.xyz / pos.w);
}

matInvProj is the inverse of my projection matrix (calculated on the CPU and uploaded as a uniform mat4). When I try to render my position information (fragColor = vec4(position, 1.0);), the screen is black in the lower-left corner, red in the lower-right corner, green in the upper-left corner, and yellow in the upper-right corner. This is roughly what I would expect to see if my depth was uniformly 0.0 across the entire scene, which it obviously should not be.

What am I doing wrong?

Upvotes: 2

Views: 1239

Answers (1)

Haydn V. Harach
Haydn V. Harach

Reputation: 1275

I found out the problem, I was simply interpreting the data wrong. By rendering it as (fragColor = vec4(position.xy, -(position.z + 1.0), 1.0)) the results were as I expected them to. In addition, when I compared it to the buffer's position (0.5 + (reconstructedPos - bufferPos)), my scene ended being mostly gray, except for far away regions where depth precision was an issue, which is what I expected from correct reconstruction results.

Upvotes: 0

Related Questions