Get depthbuffer information in vertex shader

Hello there,

Currently I have this line in the fragment shader to get the distance to depth buffer:

LinearEyeDepth(tex2Dproj(_CameraDepthTexture, UNITY_PROJ_COORD(i.screenPos)).r) - i.screenPos.w;

I would like to move this to the vertex shader. Is there a tex2Dproj compatible function I can use there, or any other method to retrieve information from the depth buffer in the vertex shader?

Thanks!

tex2Dproj is actually just a function that does this:

tex2D(_CameraDepthTexture, i.screenPos.xy / i.screenPos.w)

The UNITY_PROJ_COORD I think is just a special case for either the Vita or PS3 where it divides by the z component instead of w, and can be ignored these days.

However the problem is you can’t use tex2D in a vertex shader, you have to use tex2Dlod instead. Lucky it’s easy to replace it and do this:

LinearEyeDepth(tex2Dlod(_CameraDepthTexture, float4(i.screenPos.xy / i.screenPos.w, 0.0, 0.0)).r)

3 Likes

Thanks so much! That did the trick :slight_smile: