I have a raymarching shader which computes the location of a hit on the scene in world space.
float3 worldPos = ... ;
I can verify that the world position is right, because the position of everything renders correctly, even in stereoscopic rendering.
Now I'm trying to convert this to clip space so that I can write the right value into the Z-buffer. I initially thought it would be like this:
float4 clipPos = mul(UNITY_MATRIX_VP, float4(worldPos, 1.0)); output.depth = clipPos.z / clipPos.w;
But this turns out to be completely wrong:
What is the correct way to get the right Z value?
Tinkering with it a bit, I started trying random multiplication factors:
float4 clipPos = mul(UNITY_MATRIX_VP, float4(worldPos, 1.0)); output.depth = clipPos.z * 100 / clipPos.w;
This turns out to look exactly right in the editor:
But it looks wrong in the game view. This, however, looks right in the game view:
float4 clipPos = mul(UNITY_MATRIX_VP, float4(worldPos, 1.0)); output.depth = clipPos.z * 96 / clipPos.w;
I assume that the difference is somehow due to the settings on the different cameras. So now I'm trying to figure out: what is the correct way to do this, to get the right value irrespective of the camera?
I'm trying to render this as the scene skybox.
If I render the same thing onto a cube, the generated depth values appear to be correct. Is there a different value in
UNITY_MATRIX_VP when rendering the skybox, which results in the wrong result?
How far away is the skybox actually? Everyone just says "it's infinitely far", but that's nonsense - if it were really infinitely far, the world position of every point on the thing would be infinity, and transforming that to view space and clip space would also give infinity.