How to calculate view-space position from screen-space position without matrix multiplication

StackOverflow https://stackoverflow.com/questions/23540799

  •  18-07-2023
  •  | 
  •  

Question

I am calculating the view-space position from the screen-space position inside of multiple light- and post-process-shaders. My current code is restoring the position using the inverse of the projection matrix:

float depth = depthBuffer.Sample(sampler, uv).x;
float4 temp = mul(float4(uv.x * 2 - 1, (1 - uv.y) * 2 - 1, depth, 1), inverseProjectionMatrix);
float3 viewSpacePosition = temp.xyz / temp.w;

As an optimization I would like to remove the matrix multiplication from my shader and restore the view-space position using variables like aspect, near-clip and far-clip.

Was it helpful?

Solution

You did not say how you are creating the perspective projection matrix, which is key information. I am not a D3D expert. Rather I know OpenGL.

So I can show you how to do this with the matrix that OpenGL gluPerspective produces. It has the form:

gluPerspective matrix

This matrix is for OpenGL column vectors. Your D3D code uses a row vector, so I'll assume the transpose. For convenience rename the non-zero terms and take the inverse:

gluPerspective simplified and inverted

Inverting symbolically with Wolfram Alpha (a nice tool for this sort of thing):

{{a,0,0,0},{0,b,0,0},{0,0,c,-1},{0,0,d,0}}^-1

We get:

inverse matrix expression

So if the point being multiplied is [x y z 1] as in your code, then the result you want is

[x/a y/b -1 (z+c)/d]

This is a 4d homogenous point. To get back to 3d, divide through x,y,z by w:

[(1/a)ux  (1/b)uy  -u]  where u = d / (z+c)

The (1/a) and (1/b) terms can of course be computed in advance. After that, you need one addition, one division, and four multiplications to finish the job.

This explanation could be off modulo some negative signs or other minor details due to differences between D3D and OpenGL coordinate systems that I'm unaware of.

Having said all this, I agree with the commenters who think this is not going to produce a meaningful speedup.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top