// Copyright (c) .NET Foundation and Contributors (https://dotnetfoundation.org/ & https://stride3d.net) and Silicon Studio Corp. (https://www.siliconstudio.co.jp)
// Distributed under the MIT license. See the LICENSE.md file in the project root for more information.
shader SpriteBatchShader<bool TSRgb> : SpriteBase
{
    // -------------------------------------
    // streams
    // -------------------------------------
    stage stream float4 Color : COLOR;
    stage stream float4 ColorAdd : COLOR1;
    stage stream float Swizzle : BATCH_SWIZZLE;

    // -------------------------------------
    // VertexShader
    // -------------------------------------
    stage override void VSMain()
    {
        base.VSMain();
        if (TSRgb)
        {
            streams.Color = ColorUtility.ToLinear(streams.Color);
        }
    }

    // Shading of the sprite
    stage override float4 Shading()
    {
        // Because we use float input values we should allow certain threshold - lets fix it at 0.1

        // Alpha grayscale
        float4 swizzleColor = (abs(streams.Swizzle - 1) <= 0.1) ? base.Shading().rrrr : base.Shading();

        // Normal maps
        if (abs(streams.Swizzle - 2) <= 0.1)
        {
            // TODO This should change if we move the flags (reconstruct Z, etc) to the texture
            //  For now just assume the formula below is correct (works for 90% of teh cases)
            float nX = swizzleColor.r * 2 - 1;
            float nY = swizzleColor.g * 2 - 1;
            swizzleColor.a = 1;
            float nZ = 1 - sqrt(saturate(nX * nX + nY * nY));
            swizzleColor.b = nZ * 0.5f + 0.5f; // Don't forget that the Z-component is also in the range (-1, 1) so all normal textures have Blue channel above 0.5
        }

        // Opaque grayscale
        if (abs(streams.Swizzle - 3) <= 0.1)
        {
            swizzleColor.gb = swizzleColor.rr;
            swizzleColor.a = 1;
        }


        float4 finalColor = swizzleColor * streams.Color + streams.ColorAdd;
        return finalColor;
    }
};
