Shader "Hidden/BPR/ApplyDepthCutoff"
{
	Properties
	{
		_DepthTex ("Depth Texture", 2D) = "white" {}
	}
	SubShader
	{
		Tags
		{
			"Queue" = "Geometry-1"
			"IgnoreProjector" = "True"
			"RenderType" = "Opaque"
		}

		//ZTest Off
		ZWrite On
		ColorMask RGBA

		Pass
		{
			CGPROGRAM
			#pragma glsl
			#pragma target 3.0

			#pragma multi_compile __ CLIP_FAR

			#pragma vertex vert
			#pragma fragment frag
			
			#include "UnityCG.cginc"

			struct appdata
			{
				float4 vertex : POSITION;
				float2 uv : TEXCOORD0;
			};

			struct v2f
			{
				float2 uv : TEXCOORD0;
				float4 vertex : SV_POSITION;
			};

			struct frag_out
			{
				float4 color : COLOR;
				float depth : DEPTH;
			};

			sampler2D _DepthTex;
			float4 _DepthTex_ST;
			float _MaxDist;
			float _PlayerScale;

			v2f vert (appdata v)
			{
				v2f o;
				o.vertex = UnityObjectToClipPos(v.vertex);
				o.uv = TRANSFORM_TEX(v.uv, _DepthTex);
				return o;
			}
			inline float LinearEyeDepthToOutDepth(float z)
			{
				return (1 - _ZBufferParams.w * z) / (_ZBufferParams.z * z);
			}
			frag_out frag (v2f i)
			{
				frag_out o;

				fixed4 col = tex2D(_DepthTex, i.uv);

#ifdef CLIP_FAR
				clip(0.999 - col.r);
#endif

				float dist = col.r * _MaxDist * _PlayerScale;
				o.depth = LinearEyeDepthToOutDepth(dist);
				o.color = 0;

				return o;
			}
			ENDCG
		}
	}
}
