// 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.
namespace Stride.Rendering.Materials
{
    /// <summary>
    /// Material glossiness map (for a metal flakes layer)
    /// </summary>
    shader MaterialSurfaceGlossinessMapMetalFlakes<bool TInvert> : MaterialSurfaceGlossinessMap<TInvert>,
                                                                   Transformation,
                                                                   PositionStream4
    {
        compose ComputeColor surfaceToEyeDistanceFactor;

        override void Compute()
        {
            var metalFlakesGlossiness = streams.matGlossiness;

            // Compute base glossiness
            base.Compute();

            var distanceFactor = surfaceToEyeDistanceFactor.Compute().r;

            // Correct both glossiness factor (to avoid aliasing and unrealistic values)
            float normalLength = length(streams.matNormal);
            //streams.matGlossiness =  normalLength * streams.matGlossiness / (normalLength + streams.matGlossiness * (1.0f - normalLength));
            metalFlakesGlossiness = normalLength * metalFlakesGlossiness / (normalLength + metalFlakesGlossiness * (1.0f - normalLength));

            // Interpolate the factors using the surface to camera distance
            float LOD = saturate(distance(Eye.xyz, streams.PositionWS.xyz) * distanceFactor);

            streams.matGlossiness = lerp(metalFlakesGlossiness, streams.matGlossiness, LOD);
        }
    };
}
