﻿Shader "SnapshotProHDRP/Halftone"
{
    HLSLINCLUDE

    #pragma target 4.5
    #pragma only_renderers d3d11 ps4 xboxone vulkan metal switch
	#pragma multi_compile __ USE_SCENE_TEXTURE_ON

    #include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Common.hlsl"
    #include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Color.hlsl"
    #include "Packages/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariables.hlsl"
    #include "Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/FXAA.hlsl"
    #include "Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/RTUpscale.hlsl"

    struct Attributes
    {
        uint vertexID : SV_VertexID;
        UNITY_VERTEX_INPUT_INSTANCE_ID
    };

    struct Varyings
    {
        float4 positionCS : SV_POSITION;
        float2 texcoord   : TEXCOORD0;
        UNITY_VERTEX_OUTPUT_STEREO
    };

    Varyings Vert(Attributes input)
    {
        Varyings output;
        UNITY_SETUP_INSTANCE_ID(input);
        UNITY_INITIALIZE_VERTEX_OUTPUT_STEREO(output);
        output.positionCS = GetFullScreenTriangleVertexPosition(input.vertexID);
        output.texcoord = GetFullScreenTriangleTexCoord(input.vertexID);
        return output;
    }

    // List of properties to control your post process effect
    TEXTURE2D_X(_InputTexture);

	TEXTURE2D(_HalftoneTexture);
	SAMPLER(sampler_HalftoneTexture);
	float _Softness;
	float _TextureSize;
	float2 _MinMaxLuminance;

	float4 _DarkColor;
	float4 _LightColor;

    float4 CustomPostProcess(Varyings input) : SV_Target
    {
        UNITY_SETUP_STEREO_EYE_INDEX_POST_VERTEX(input);

        uint2 positionSS = input.texcoord * _ScreenSize.xy;
		float3 col = LOAD_TEXTURE2D_X(_InputTexture, positionSS);

		float lum = saturate(Luminance(col.rgb));

		float2 halftoneUVs = positionSS / _TextureSize;
		float halftone = SAMPLE_TEXTURE2D(_HalftoneTexture, sampler_HalftoneTexture, halftoneUVs);
		halftone = lerp(_MinMaxLuminance.x, _MinMaxLuminance.y, halftone);

		float halftoneSmooth = fwidth(halftone) * _Softness;
		halftoneSmooth = smoothstep(halftone - halftoneSmooth, halftone + halftoneSmooth, lum);

#if USE_SCENE_TEXTURE_ON
		col = lerp(_DarkColor, col, halftoneSmooth);
#else
		col = lerp(_DarkColor, _LightColor, halftoneSmooth);
#endif

		return float4(col, 1.0f);
    }

    ENDHLSL

    SubShader
    {
        Pass
        {
            Name "Halftone"

            ZWrite Off
            ZTest Always
            Blend Off
            Cull Off

            HLSLPROGRAM
                #pragma fragment CustomPostProcess
                #pragma vertex Vert
            ENDHLSL
        }
    }
    Fallback Off
}
