0
\$\begingroup\$

I'm using URP 10.6 and I found a wired problem. I use following code to sample the _CameraDepthTexture

float2 screenUV = input.positionCS.xy * rcp(_ScreenParams.xy);
half4 col = SAMPLE_TEXTURE2D(_CameraDepthTexture, sampler_ScreenTextures_linear_clamp, screenUV)

The input.positionCS is from o.positionCS = TransformObjectToHClip(v.positionOS) in vertex shader.

Then everything goes well. However, when I try to sample the _CameraOpaqueTexture with the same uv, everything goes wrong. There is nothing showing by using following code

float2 screenUV = input.positionCS.xy * rcp(_ScreenParams.xy);
half4 col = SAMPLE_TEXTURE2D(_CameraOpaqueTexture, sampler_CameraOpaqueTexture_linear_clamp, screenUV)

After long time searching, I realise that I need to use this snippet to make it work.

float2 screenUV = input.positionCS.xy * rcp(_ScreenParams.xy);
screenUV = screenUV * 0.5 + 0.5;
half4 col = SAMPLE_TEXTURE2D(_CameraOpaqueTexture, sampler_CameraOpaqueTexture_linear_clamp, screenUV)

Why must I do screenUV = screenUV * 0.5 + 0.5 before sampling _CameraOpaqueTexture while sampling _CameraDepthTexture doesn't need it?

\$\endgroup\$

1 Answer 1

0
\$\begingroup\$

The reason you need to adjust the screenUV coordinates by multiplying by 0.5 and adding 0.5 when sampling the _CameraOpaqueTexture is related to the texture coordinate conventions used in Unity's Universal Render Pipeline (URP).

In URP, the _CameraDepthTexture follows a normalized device coordinate (NDC) convention where the texture coordinates range from -1 to 1. Therefore, when sampling the depth texture, you can directly use the screenUV values as they are.

On the other hand, the _CameraOpaqueTexture follows a convention where the texture coordinates range from 0 to 1. In order to map the screenUV values to this texture coordinate range, you need to apply a transformation by multiplying by 0.5 and adding 0.5. This transformation scales and shifts the coordinates from the NDC range (-1 to 1) to the texture coordinate range (0 to 1), allowing proper sampling of the opaque texture.

Therefore, the adjustment of screenUV by screenUV = screenUV * 0.5 + 0.5 before sampling the _CameraOpaqueTexture is necessary to correctly map the NDC coordinates to the texture coordinate space used by the opaque texture in URP.

Source: Unity Doc on Cameras and depth textures

\$\endgroup\$
2
  • \$\begingroup\$ It makes sense. Do you find it from official documents? \$\endgroup\$ Commented Jun 22, 2023 at 10:12
  • \$\begingroup\$ @OtakuFitness yes, it is from docs.unity3d.com/Manual/SL-CameraDepthTexture.html. Should I add the link here or should I edit in my answer? um... i'll add both.. \$\endgroup\$ Commented Jun 22, 2023 at 18:00

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .