Reconstructing position from depth

I have been trying to understand ssao, and since it is a post-processing effect I need to construct a position from depth and texture position. My results is wrong and I cant understand why. Here is my function for the reconstruction

vec3 ToPos(vec2 uv) {
    float z=texture2D(depth,uv).x;
    if (z==0.) discard;
    vec4 P=vec4(uv*2.-1.,z*2.-1.,1.)*invVP;
    return P.xyz/P.w;
}

The depthmap iself is linear but I think the problem lies in the invVP matrix itself. It looks like this:

invVP=(projectionMatrix()*viewMatrix()):inverse()

I’m not sure if the range of the depthmap must be the same as the far plane i the camera() function.
Fragment part in depth shader:

float depth=max(1.-length(vPos-PlayerPos)/500.,0.);

This gives me a unwanted result. If someone could help me that would be great :slight_smile:

@MMGames - if you’re trying to calculate the inverse of the modelviewprojectionmatrix in Codea, this should do it

invVP = (modelMatrix()*viewMatrix()*projectionMatrix()):inverse()

Thx Ignatz, but I don’t think that is the problem. If I try to explain:

  1. I store the depth for every pixel in an image. Same as a shadowmap.

  2. InvVP becomes the matrix that will unproject the depth and its texturecoordinates from Screenspace to worldspace. I want the position of the depth.

  3. In the fragment part of the ssao-shader I transform the depth and the texturecoordinates into NDC (Normalized Device Coordinates). I multiply with the invVP (unprojecting my textureposition) and divide by w.
    Now I should have its worldposition!

  4. To check if this is right I use the same formula to calculate the depth of this pixel (if the unprojected position is correct the following should be the same as the depth image from 1.) and write it to gl_FragColor.

The problem is that this does not work. :-?

well, maybe it is because you are multiplying viewMatrix and projectionMatrix in the wrong order, viewMatrix comes first.

Are you sure? Whats the difference in 6*4*2 or 6*2*4 or whatever. the result is the same: 48. Its not cross product or anything, just plain multiplication …

@se24vad - no they’re not the same, try an example.

@se24vad Matrix multiplication is not associative. Order matters very much. Matrices represent transformations and in 2D and above, it matters which way round you do things. For example, rotating by 90 degrees followed by a reflection in the x-axis is very different to reflecting in the x-axis followed by rotating 90 degrees.

@Ignatz @LoopSpace thank you for clarifying. it really isnt, I was not aware till I tried, you both right!

@se24vad - 3D graphics math can be pretty hard and confusing if you aren’t a mathematician!

Well, thank you all. I have been playing with the matrices but no hope. Let’s see if I manage to fix it