// Floralin/VertexColor: the mesh's vertex colors, lit by the main light and ambient (DESIGN.md §9).
// Palette colours: each vertex also carries, in UV0, which palette entries its colour blends and how much (packed as
// exact integers: u = base * 32 + tone, v = weight byte * 256 + tint byte), so the colour is rebuilt from the material's
// colour slots _C0.._C23 and the species can be recoloured by editing the material; a named palette is another material
// on the same mesh. With "Use palette" off, or on a vertex without a reference (v = 0 or u < 0), the baked vertex colour
// is used as it is. No textures. Floralin meshes are flat-shaded through their normals (three vertices per triangle), so
// a per-pixel Lambert term on the interpolated (per-face constant) normal gives faceted low-poly shading. The diffuse term
// is slightly wrapped (_Wrap) so faces turned just past the light fall off softly instead of to black, and faces turned
// away get light through them (_Translucency: thin leaves and petals are double-sided cards, so their back faces glow
// when the sun is behind them). The first SubShader is for URP and is SRP Batcher compatible (every pass declares the
// same UnityPerMaterial, so no UsePass of URP/Lit's passes, whose cbuffer differs); its lit pass receives main-light
// shadows (off with "Receive shadows") and screen-space ambient occlusion when the renderer has SSAO; besides it there
// are ShadowCaster, DepthOnly and DepthNormals (plants are in the camera depth/normals textures: SSAO, depth priming,
// soft particles). The second SubShader is for the built-in pipeline, per-vertex lit, with the VertexLit shadow caster.
Shader "Floralin/VertexColor"
{
    Properties
    {
        _BaseColor ("Tint", Color) = (1, 1, 1, 1)
        [Toggle] _UsePalette ("Use palette colours", Float) = 1
        [ToggleOff] _ReceiveShadows ("Receive shadows", Float) = 1
        _Wrap ("Light wrap", Range(0, 1)) = 0.2
        _Translucency ("Translucency", Range(0, 1)) = 0.35
        _C0 ("Colour 0", Color) = (1, 1, 1, 1)
        _C1 ("Colour 1", Color) = (1, 1, 1, 1)
        _C2 ("Colour 2", Color) = (1, 1, 1, 1)
        _C3 ("Colour 3", Color) = (1, 1, 1, 1)
        _C4 ("Colour 4", Color) = (1, 1, 1, 1)
        _C5 ("Colour 5", Color) = (1, 1, 1, 1)
        _C6 ("Colour 6", Color) = (1, 1, 1, 1)
        _C7 ("Colour 7", Color) = (1, 1, 1, 1)
        _C8 ("Colour 8", Color) = (1, 1, 1, 1)
        _C9 ("Colour 9", Color) = (1, 1, 1, 1)
        _C10 ("Colour 10", Color) = (1, 1, 1, 1)
        _C11 ("Colour 11", Color) = (1, 1, 1, 1)
        _C12 ("Colour 12", Color) = (1, 1, 1, 1)
        _C13 ("Colour 13", Color) = (1, 1, 1, 1)
        _C14 ("Colour 14", Color) = (1, 1, 1, 1)
        _C15 ("Colour 15", Color) = (1, 1, 1, 1)
        _C16 ("Colour 16", Color) = (1, 1, 1, 1)
        _C17 ("Colour 17", Color) = (1, 1, 1, 1)
        _C18 ("Colour 18", Color) = (1, 1, 1, 1)
        _C19 ("Colour 19", Color) = (1, 1, 1, 1)
        _C20 ("Colour 20", Color) = (1, 1, 1, 1)
        _C21 ("Colour 21", Color) = (1, 1, 1, 1)
        _C22 ("Colour 22", Color) = (1, 1, 1, 1)
        _C23 ("Colour 23", Color) = (1, 1, 1, 1)
    }

    SubShader
    {
        // Skipped without URP, so a Built-in build does not compile its URP includes.
        PackageRequirements { "com.unity.render-pipelines.universal" }
        Tags { "RenderType" = "Opaque" "RenderPipeline" = "UniversalPipeline" "Queue" = "Geometry" }

        Pass
        {
            Name "ForwardLit"
            Tags { "LightMode" = "UniversalForward" }
            Cull Back
            ZWrite On

            HLSLPROGRAM
            #pragma vertex Vert
            #pragma fragment Frag
            #pragma multi_compile_fog
            #pragma multi_compile _ _MAIN_LIGHT_SHADOWS _MAIN_LIGHT_SHADOWS_CASCADE _MAIN_LIGHT_SHADOWS_SCREEN
            #pragma multi_compile_fragment _ _SHADOWS_SOFT _SHADOWS_SOFT_LOW _SHADOWS_SOFT_MEDIUM _SHADOWS_SOFT_HIGH
            #pragma multi_compile_fragment _ _SCREEN_SPACE_OCCLUSION
            #pragma shader_feature_local_fragment _RECEIVE_SHADOWS_OFF
            #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Core.hlsl"
            #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Lighting.hlsl"

            CBUFFER_START(UnityPerMaterial)
                half4 _BaseColor;
                float _UsePalette;
                half _Wrap;
                half _Translucency;
                half4 _C0;
                half4 _C1;
                half4 _C2;
                half4 _C3;
                half4 _C4;
                half4 _C5;
                half4 _C6;
                half4 _C7;
                half4 _C8;
                half4 _C9;
                half4 _C10;
                half4 _C11;
                half4 _C12;
                half4 _C13;
                half4 _C14;
                half4 _C15;
                half4 _C16;
                half4 _C17;
                half4 _C18;
                half4 _C19;
                half4 _C20;
                half4 _C21;
                half4 _C22;
                half4 _C23;
            CBUFFER_END

            struct Attributes
            {
                float4 positionOS : POSITION;
                float3 normalOS : NORMAL;
                half4 color : COLOR;
                float2 paletteRef : TEXCOORD0;
            };

            // The vertex colour rebuilt from the material's palette slots (see the header), else the baked colour.
            half4 FloralinColor(half4 baked, float2 ref)
            {
                if (_UsePalette < 0.5 || ref.y < 0.5 || ref.x < -0.5) return baked;
                half4 slots[24] = { _C0, _C1, _C2, _C3, _C4, _C5, _C6, _C7, _C8, _C9, _C10, _C11, _C12, _C13, _C14, _C15, _C16, _C17, _C18, _C19, _C20, _C21, _C22, _C23 };
                float u = floor(ref.x + 0.5);
                float v = floor(ref.y + 0.5);
                float b = floor(u / 32.0);
                float t = u - b * 32.0;
                float wb = floor(v / 256.0);
                float tb = v - wb * 256.0;
                half4 c = lerp(slots[(int)clamp(b, 0.0, 23.0)], slots[(int)clamp(t, 0.0, 23.0)], wb / 255.0);
                c.rgb *= tb / 127.5;
                c.a = baked.a;
                return c;
            }


            struct Varyings
            {
                float4 positionCS : SV_POSITION;
                half4 color : COLOR;
                float3 positionWS : TEXCOORD0;
                half3 normalWS : TEXCOORD1;
                half fogFactor : TEXCOORD2;
            };

            Varyings Vert(Attributes input)
            {
                Varyings output;
                VertexPositionInputs position = GetVertexPositionInputs(input.positionOS.xyz);
                output.positionCS = position.positionCS;
                output.positionWS = position.positionWS;
                output.normalWS = TransformObjectToWorldNormal(input.normalOS);
                half4 color = FloralinColor(input.color, input.paletteRef);
                output.color = half4(color.rgb * _BaseColor.rgb, color.a * _BaseColor.a);
                output.fogFactor = ComputeFogFactor(position.positionCS.z);
                return output;
            }

            half4 Frag(Varyings input) : SV_Target
            {
                half3 normalWS = normalize(input.normalWS);
                float2 screenUV = GetNormalizedScreenSpaceUV(input.positionCS);
            #if defined(_MAIN_LIGHT_SHADOWS_SCREEN)
                float4 shadowCoord = float4(screenUV, 0.0, 1.0);
            #else
                float4 shadowCoord = TransformWorldToShadowCoord(input.positionWS);
            #endif
                Light light = GetMainLight(shadowCoord);
                AmbientOcclusionFactor ao = GetScreenSpaceAmbientOcclusion(screenUV);
                half shadow = light.shadowAttenuation * light.distanceAttenuation;
                half nl = dot(normalWS, light.direction);
                half diffuse = saturate((nl + _Wrap) / (1.0 + _Wrap));
                half through = saturate(-nl) * _Translucency;
                half3 direct = light.color * (diffuse + through) * shadow * ao.directAmbientOcclusion;
                half3 ambient = SampleSH(normalWS) * ao.indirectAmbientOcclusion;
                half4 color = half4(input.color.rgb * (direct + ambient), input.color.a);
                color.rgb = MixFog(color.rgb, input.fogFactor);
                return color;
            }
            ENDHLSL
        }

        Pass
        {
            Name "ShadowCaster"
            Tags { "LightMode" = "ShadowCaster" }
            ZWrite On
            ZTest LEqual
            ColorMask 0
            Cull Back

            HLSLPROGRAM
            #pragma vertex ShadowVert
            #pragma fragment ShadowFrag
            #pragma multi_compile_vertex _ _CASTING_PUNCTUAL_LIGHT_SHADOW
            #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Core.hlsl"
            #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Shadows.hlsl"

            CBUFFER_START(UnityPerMaterial)
                half4 _BaseColor;
                float _UsePalette;
                half _Wrap;
                half _Translucency;
                half4 _C0;
                half4 _C1;
                half4 _C2;
                half4 _C3;
                half4 _C4;
                half4 _C5;
                half4 _C6;
                half4 _C7;
                half4 _C8;
                half4 _C9;
                half4 _C10;
                half4 _C11;
                half4 _C12;
                half4 _C13;
                half4 _C14;
                half4 _C15;
                half4 _C16;
                half4 _C17;
                half4 _C18;
                half4 _C19;
                half4 _C20;
                half4 _C21;
                half4 _C22;
                half4 _C23;
            CBUFFER_END

            // Set by URP for the light whose shadow map is drawn (as in URP's ShadowCasterPass.hlsl).
            float3 _LightDirection;
            float3 _LightPosition;

            struct Attributes
            {
                float4 positionOS : POSITION;
                float3 normalOS : NORMAL;
            };

            float4 ShadowVert(Attributes input) : SV_POSITION
            {
                float3 positionWS = TransformObjectToWorld(input.positionOS.xyz);
                float3 normalWS = TransformObjectToWorldNormal(input.normalOS);
            #if _CASTING_PUNCTUAL_LIGHT_SHADOW
                float3 lightDirectionWS = normalize(_LightPosition - positionWS);
            #else
                float3 lightDirectionWS = _LightDirection;
            #endif
                float4 positionCS = TransformWorldToHClip(ApplyShadowBias(positionWS, normalWS, lightDirectionWS));
            #if UNITY_REVERSED_Z
                positionCS.z = min(positionCS.z, UNITY_NEAR_CLIP_VALUE);
            #else
                positionCS.z = max(positionCS.z, UNITY_NEAR_CLIP_VALUE);
            #endif
                return positionCS;
            }

            half4 ShadowFrag() : SV_Target
            {
                return 0;
            }
            ENDHLSL
        }

        Pass
        {
            Name "DepthOnly"
            Tags { "LightMode" = "DepthOnly" }
            ZWrite On
            ColorMask R
            Cull Back

            HLSLPROGRAM
            #pragma vertex DepthVert
            #pragma fragment DepthFrag
            #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Core.hlsl"

            CBUFFER_START(UnityPerMaterial)
                half4 _BaseColor;
                float _UsePalette;
                half _Wrap;
                half _Translucency;
                half4 _C0;
                half4 _C1;
                half4 _C2;
                half4 _C3;
                half4 _C4;
                half4 _C5;
                half4 _C6;
                half4 _C7;
                half4 _C8;
                half4 _C9;
                half4 _C10;
                half4 _C11;
                half4 _C12;
                half4 _C13;
                half4 _C14;
                half4 _C15;
                half4 _C16;
                half4 _C17;
                half4 _C18;
                half4 _C19;
                half4 _C20;
                half4 _C21;
                half4 _C22;
                half4 _C23;
            CBUFFER_END

            float4 DepthVert(float4 positionOS : POSITION) : SV_POSITION
            {
                return TransformObjectToHClip(positionOS.xyz);
            }

            half DepthFrag(float4 positionCS : SV_POSITION) : SV_Target
            {
                return positionCS.z;
            }
            ENDHLSL
        }

        Pass
        {
            Name "DepthNormals"
            Tags { "LightMode" = "DepthNormals" }
            ZWrite On
            Cull Back

            HLSLPROGRAM
            #pragma vertex DepthNormalsVert
            #pragma fragment DepthNormalsFrag
            #pragma multi_compile_fragment _ _GBUFFER_NORMALS_OCT
            #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Core.hlsl"

            CBUFFER_START(UnityPerMaterial)
                half4 _BaseColor;
                float _UsePalette;
                half _Wrap;
                half _Translucency;
                half4 _C0;
                half4 _C1;
                half4 _C2;
                half4 _C3;
                half4 _C4;
                half4 _C5;
                half4 _C6;
                half4 _C7;
                half4 _C8;
                half4 _C9;
                half4 _C10;
                half4 _C11;
                half4 _C12;
                half4 _C13;
                half4 _C14;
                half4 _C15;
                half4 _C16;
                half4 _C17;
                half4 _C18;
                half4 _C19;
                half4 _C20;
                half4 _C21;
                half4 _C22;
                half4 _C23;
            CBUFFER_END

            struct Attributes
            {
                float4 positionOS : POSITION;
                float3 normalOS : NORMAL;
            };

            struct Varyings
            {
                float4 positionCS : SV_POSITION;
                float3 normalWS : TEXCOORD0;
            };

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

            // The world-space normal, written as URP/Lit's DepthNormals pass does (octahedron-packed when the
            // renderer asks for it with _GBUFFER_NORMALS_OCT).
            half4 DepthNormalsFrag(Varyings input) : SV_Target
            {
                float3 normalWS = NormalizeNormalPerPixel(input.normalWS);
            #if defined(_GBUFFER_NORMALS_OCT)
                float2 octNormalWS = PackNormalOctQuadEncode(normalWS);
                float2 remappedOctNormalWS = saturate(octNormalWS * 0.5 + 0.5);
                half3 packedNormalWS = PackFloat2To888(remappedOctNormalWS);
                return half4(packedNormalWS, 0.0);
            #else
                return half4(normalWS, 0.0);
            #endif
            }
            ENDHLSL
        }
    }

    SubShader
    {
        Tags { "RenderType" = "Opaque" "Queue" = "Geometry" }

        Pass
        {
            Tags { "LightMode" = "ForwardBase" }
            Cull Back

            CGPROGRAM
            #pragma vertex Vert
            #pragma fragment Frag
            #include "UnityCG.cginc"
            #include "UnityLightingCommon.cginc"

            fixed4 _BaseColor;
            float _UsePalette;
            float _Wrap;
            float _Translucency;
            float4 _C0;
            float4 _C1;
            float4 _C2;
            float4 _C3;
            float4 _C4;
            float4 _C5;
            float4 _C6;
            float4 _C7;
            float4 _C8;
            float4 _C9;
            float4 _C10;
            float4 _C11;
            float4 _C12;
            float4 _C13;
            float4 _C14;
            float4 _C15;
            float4 _C16;
            float4 _C17;
            float4 _C18;
            float4 _C19;
            float4 _C20;
            float4 _C21;
            float4 _C22;
            float4 _C23;

            struct Attributes
            {
                float4 vertex : POSITION;
                float3 normal : NORMAL;
                fixed4 color : COLOR;
                float2 paletteRef : TEXCOORD0;
            };

            // The vertex colour rebuilt from the material's palette slots (see the header), else the baked colour.
            float4 FloralinColor(float4 baked, float2 ref)
            {
                if (_UsePalette < 0.5 || ref.y < 0.5 || ref.x < -0.5) return baked;
                float4 slots[24] = { _C0, _C1, _C2, _C3, _C4, _C5, _C6, _C7, _C8, _C9, _C10, _C11, _C12, _C13, _C14, _C15, _C16, _C17, _C18, _C19, _C20, _C21, _C22, _C23 };
                float u = floor(ref.x + 0.5);
                float v = floor(ref.y + 0.5);
                float b = floor(u / 32.0);
                float t = u - b * 32.0;
                float wb = floor(v / 256.0);
                float tb = v - wb * 256.0;
                float4 c = lerp(slots[(int)clamp(b, 0.0, 23.0)], slots[(int)clamp(t, 0.0, 23.0)], wb / 255.0);
                c.rgb *= tb / 127.5;
                c.a = baked.a;
                return c;
            }


            struct Varyings
            {
                float4 pos : SV_POSITION;
                fixed4 color : COLOR;
            };

            Varyings Vert(Attributes input)
            {
                Varyings output;
                half3 normalWS = UnityObjectToWorldNormal(input.normal);
                half nl = dot(normalWS, _WorldSpaceLightPos0.xyz);
                half diffuse = saturate((nl + _Wrap) / (1.0 + _Wrap)) + saturate(-nl) * _Translucency;
                half3 lit = _LightColor0.rgb * diffuse + ShadeSH9(half4(normalWS, 1));
                output.pos = UnityObjectToClipPos(input.vertex);
                float4 color = FloralinColor(input.color, input.paletteRef);
                output.color = fixed4(color.rgb * _BaseColor.rgb * lit, color.a * _BaseColor.a);
                return output;
            }

            fixed4 Frag(Varyings input) : SV_Target
            {
                return input.color;
            }
            ENDCG
        }

        UsePass "Legacy Shaders/VertexLit/SHADOWCASTER"
    }

    FallBack "Diffuse"
    CustomEditor "Floralin.Plants.Editor.PaletteShaderGUI"
}
