Shader "Custom/DepthFog"
{
    Properties
    {
        _MainTex("Main Texture", 2D) = "white" {}
        _FogColor("Fog Color", Color) = (0, 0, 0, 0)

        [Space]

        _DepthStart("Depth Start", Float) = 0
        _DepthDistance("Depth Distance", Float) = 0
    }

    SubShader
    {
        Tags{"RenderType" = "Opaque" "RenderPipeline" = "UniversalPipeline"}

        Stencil
        {
            Ref 5
            Comp NotEqual
            Pass Keep
            Fail Keep
            ZFail Keep
        }

        HLSLINCLUDE
        #include "Packages\com.unity.render-pipelines.universal\ShaderLibrary\Core.hlsl"
        #include "Packages\com.unity.render-pipelines.universal\ShaderLibrary\DeclareDepthTexture.hlsl"

        CBUFFER_START(UnityPerMaterial)
        float4 _FogColor;
        float _DepthStart;
        float _DepthDistance;
        CBUFFER_END

        TEXTURE2D(_MainTex);
        SAMPLER(sampler_MainTex);

        struct VertexInput
        {
            float4 pos : POSITION;
            float2 uv : TEXCOORD0;
        };

        struct VertexOutput
        {
            float4 pos : SV_POSITION;
            float2 uv : TEXCOORD0;
        };
        ENDHLSL

        Pass
        {
            HLSLPROGRAM
            #pragma vertex vert
            #pragma fragment frag

            VertexOutput vert(VertexInput i)
            {
                VertexOutput o;

                o.pos = TransformObjectToHClip(i.pos.xyz);
                o.uv = i.uv;

                return o;
            }

            float4 frag(VertexOutput i) : SV_Target
            {
                float depth = Linear01Depth(SAMPLE_TEXTURE2D(_CameraDepthTexture, sampler_CameraDepthTexture, i.uv), _ZBufferParams) * _ProjectionParams.z;
                depth = saturate((depth - _DepthStart) / _DepthDistance);

                float4 fog = _FogColor * depth;
                float4 screenColor = SAMPLE_TEXTURE2D(_MainTex, sampler_MainTex, i.uv);

                return lerp(screenColor, fog, depth);
            }
            ENDHLSL
        }
    }
}