Shader "UNSLOW/EffectPractice/MeshDissolve"
{
    Properties
    {
        _BaseColor ("Base Color", Color) = (0.35, 0.55, 0.7, 1)
        _EdgeColor ("Edge Color", Color) = (1, 0.55, 0.12, 1)
        _NoiseTex ("Dissolve Noise", 2D) = "gray" {}
        _Threshold ("Dissolve Threshold", Float) = -0.2
        _EdgeWidth ("Edge Width", Float) = 0.05
    }
    SubShader
    {
        Tags { "RenderType"="Opaque" "RenderPipeline"="UniversalPipeline" "Queue"="Geometry" }
        Pass
        {
            Name "ForwardLit"
            Tags { "LightMode"="UniversalForward" }
            HLSLPROGRAM
            #pragma vertex Vert
            #pragma fragment Frag
            #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Core.hlsl"
            #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Lighting.hlsl"

            TEXTURE2D(_NoiseTex);
            SAMPLER(sampler_NoiseTex);
            CBUFFER_START(UnityPerMaterial)
                float4 _BaseColor;
                float4 _EdgeColor;
                float _Threshold;
                float _EdgeWidth;
            CBUFFER_END

            struct Attributes { float4 positionOS : POSITION; float3 normalOS : NORMAL; };
            struct Varyings
            {
                float4 positionCS : SV_POSITION;
                float3 positionOS : TEXCOORD0;
                float3 normalWS : TEXCOORD1;
            };

            Varyings Vert(Attributes input)
            {
                Varyings output;
                output.positionCS = TransformObjectToHClip(input.positionOS.xyz);
                output.positionOS = input.positionOS.xyz;
                output.normalWS = TransformObjectToWorldNormal(input.normalOS);
                return output;
            }

            half4 Frag(Varyings input) : SV_Target
            {
                // UVのないMeshにも使えるよう、ローカル座標から模様を読む。
                float2 uv = input.positionOS.xz * 0.75 + 0.5;
                float noise = SAMPLE_TEXTURE2D_LOD(_NoiseTex, sampler_NoiseTex, uv, 0).r;
                float mask = input.positionOS.y * 0.5 + 0.2 * (noise - 0.5);
                float distanceToEdge = mask - _Threshold;
                clip(distanceToEdge);
                Light light = GetMainLight();
                half3 normal = normalize(input.normalWS);
                half3 diffuse = light.color * saturate(dot(normal, light.direction));
                half3 body = _BaseColor.rgb * (SampleSH(normal) + diffuse);
                half edge = 1 - smoothstep(0, _EdgeWidth, distanceToEdge);
                return half4(lerp(body, _EdgeColor.rgb, edge), 1);
            }
            ENDHLSL
        }
    }
}
