Different approaches to compute depth of a model

Hi. I want to realize if UNITY_TRANSFER_DEPTH, UNITY_output_DEPTH macros are different from sampling depth texture using screen position?
Also I can compute the world position of the model and then get the distance between the model and the camera.

Yes, these are very different from sampling the depth texture … because they don’t do anything at all.

Here’s those macros in the UnityCG.cginc file where they’re defined:

// Legacy; used to do something on platforms that had to emulate depth textures manually. Now all platforms have native depth textures.
#define UNITY_TRANSFER_DEPTH(oo)
// Legacy; used to do something on platforms that had to emulate depth textures manually. Now all platforms have native depth textures.
#define UNITY_OUTPUT_DEPTH(i) return 0

There are a lot of ways to get the depth, but there’s also lots of different types of depth, or things that people refer to as depth. Can you describe or show examples of what you’re looking to do? Are you looking for depth or distance? Are you trying to match the non-linear value from a depth buffer / depth texture or linear world space unit value?

1 Like

Do you mean z distance,when you say depth, right?
Therefore, yes, the total distance is different from depth(z distance).
I want to know the standard approach to get depth(z distance with linear world space unit value) for specific models.
UNITY_TRANSFER_DEPTH(oo)
UNITY_OUTPUT_DEPTH(i)
Are they legacy?

Yes.

If you’re in the vertex shader, then:
COMPUTE_EYEDEPTH(outVar);

If you’re in the fragment shader, either pass that value from the vertex to the fragment, or calculate it manually from the world position … that macro is really just:
outVar = -UnityObjectToViewPos(v.vertex).z

And UnityObjectToViewPos is:
return mul(UNITY_MATRIX_V, mul(unity_ObjectToWorld, float4(pos.xyz, 1.0))).xyz;

So in the fragment shader, if you have the world position:
float linearDepth = -mul(UNITY_MATRIX_V, float4(worldPos.xyz, 1.0)).z;

Alternatively, if you have a “viewDir” value you’re passing from the vertex to the fragment, just grab the -viewDir.z. (Also, viewDir shouldn’t be normalized in the vertex shader if you are doing that, it doesn’t interpolate properly if it’s normalized before the fragment shader.)

2 Likes

So we need depth texture only for image effects. Thanks

Image effects, and if you want to compare the depth of the current object to the depth of opaque objects in the scene (like for soft particles, or water).

1 Like

Which Unity version is this?

Unity 2018.2

I think they did something until a late 5 / early 2017 version.

1 Like