Image Effect linear depth

Hello,

I’m currently writing an image effect and need the linear depth for view space position reconstruction.

I render depth and normals with

camera.depthTextureMode = DepthTextureMode.DepthNormals;

And I’m reconstructing view space position with

R5_clipRange = float4(_ProjectionParams.y, _ProjectionParams.z, _ProjectionParams.y * _ProjectionParams.z, _ProjectionParams.z - _ProjectionParams.y);
			
float GetDistance (in sampler2D depthNormalSampler, in float2 texCoord)
{
	return DecodeFloatRG(tex2D(depthNormalSampler, texCoord).zw) * R5_clipRange.w;
}

float3 GetViewPos (in sampler2D depthNormalSampler, in fixed2 texCoord)
{
	float depth = (R5_clipRange.y - R5_clipRange.z / (GetDistance(depthNormalSampler, texCoord) + R5_clipRange.x)) / R5_clipRange.w;
	vec4 pos = vec4(texCoord.x, texCoord.y, depth, 1.0);
	pos.xyz = pos.xyz * 2.0 - 1.0;
	pos = mul(_InverseProjectionMatrix, pos);
	return pos.xyz / pos.w;
}

But for this i need the linear depth [0…1]. But it looks like the depth unity is providing isn’t linear. I already tried Linear01Depth but this just outputs black. is there a better way to reconstruct view space position in unity instead of using my method which needs linear depth?

greets

C0dR

linear depth, i assume you mean distance from camera to pixel? That’s just one line using distance. confused

Not entirely sure whether this is the same thing or whether it will help, but it seems to draw the depth if you place the shader on an object. However, it uses:

camera.depthTextureMode = DepthTextureMode.Depth;

The depth it gets in the fragment shader should be linear. Although, make sure your scale of the scene is not really small as I think the depth value is based on the camera’s clipping planes so scene with really small scale would render a lot of black.

Shader "Custom/Render depth buffer" {
SubShader {
    Tags { "RenderType"="Opaque" }
	    Pass {
	        Fog { Mode Off }
		    CGPROGRAM
		    #pragma vertex vert
		    #pragma fragment frag
		    #include "UnityCG.cginc"

		    sampler2D _CameraDepthTexture;
		    float4 _CameraDepthTexture_ST;

		    struct v2f {
		        float4 vertex : POSITION;
		        float2 texcoord : TEXCOORD0;
		    };


		    v2f vert( v2f v ) {
		        v2f o;
		        o.vertex = mul(UNITY_MATRIX_MVP, v.vertex);
		        o.texcoord = TRANSFORM_TEX(v.texcoord, _CameraDepthTexture);
		        return o;
		    }

		    half4 frag(v2f i) : COLOR
		    {
		        float depth = tex2D (_CameraDepthTexture, i.texcoord);
		        depth = LinearEyeDepth (depth);

		        return depth;
		    }
		    ENDCG
	    }
	}
FallBack Off
}