World-position from view-space position... yes, again :(

Really I read all the articles (position from depth etc.) and tried all the built-in shader uniforms and their inverses and their inverse transposes and read the previous threads and I still can’t get the world-position from view-space position, it should be so freaking simple… pulease, someone HALP… :smile:

I am in post-process and each pixel has a view-space (aka clip-space aka eye-space aka camera-space) position with x,y,z all ranging exactly from -1 to 1. No matter the camera rotation or positioning or field-of-view or draw-distance, in cam-space/view-space, all pixels are in the [-1…1] range for every rendered frame. For z of course everything less 0 is behind the camera so pixels effectively range camPos.z from 0…1.

So this is just bog-standard view-space, no magic, nothing special. I’m passing into the shader the camera’s cameraToWorldMatrix and that really should be enough and handle perspective divide and viewer rotation and what not and everything, shouldn’t it? Because cam-space is -1…1 always, and world-space is -infinity…infinity.

Well doesn’t work for me. What’s the deal and why do I keep hearing about “inverse view-projection” matrices etc. I have valid and double-triple-checked 3D coordinates in one space [-1…1] and the documented cam2world matrix should be enough to translate them into valid 3D coordinates in the desired goal space. Drives me bonkers!.. :mrgreen:

You’re wanting world space positions from your depth texture yeah? (If I misinterpreted, this should still help you with the transformations anyway)
In your shader…

// Returns World Position of a pixel from clip-space depth map..

float depth = tex2D(_CameraDepthTexture, texcoord.xy);
// H is the viewport position at this pixel in the range -1 to 1.
float4 H = float4((texcoord.x) * 2 - 1, (texcoord.y) * 2 - 1, depth, 1.0);
float4 D = mul(_ViewProjectInverse, H);
D /= D.w;

For OpenGL, you need to invert the texcoord.y.
You’ll also need to pass the _ViewProjectInverse matrix to your shader as well —

<yourMaterial>.SetMatrix("_ViewProjectInverse", (camera.projectionMatrix * camera.worldToCameraMatrix).inverse);

P.S: Pretty sure I snagged these snippets from a post by Aubergine a while ago, so props :slight_smile:

Crazily enough seems to totally work, as long as I make sure z is remapped from my depth-channel’s 0…1 range (not using _CameraDepthTexture here) back to -1…1! Thanks ever so freaking much, BEAM. Mad karma to come your way! Man I sure am beaming now :stuck_out_tongue: