// 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.Lights
{
    /// <summary>
    /// Defines common function for direct lights
    /// </summary>
    shader LightUtil
    {
        // Code from "Moving Frostbite to Physically Based Rendering"  Rousiers, Charles De Lagarde, Sébastien p32
        float SmoothDistanceAttenuation(float squaredDistance, float lightInvSquareRadius) 
        {
	        float factor = squaredDistance * lightInvSquareRadius;
	        float smoothFactor = saturate(1.0f - factor * factor);
	        return smoothFactor * smoothFactor;
        }

        float GetDistanceAttenuation(float lightVectorLength, float lightInvSquareRadius)
        {
	        float d2 = lightVectorLength * lightVectorLength;
	        float attenuation = 1.0 / (max(d2 , 0.01 * 0.01));
	        attenuation *= SmoothDistanceAttenuation(d2, lightInvSquareRadius);
	        return attenuation;
        } 

        float GetAngularAttenuation(float3 lightVector, float3 lightDirection, float lightAngleScale, float lightAngleOffset)
        {
	        // On the CPU
	        // float lightAngleScale = 1.0f / max (0.001f, (cosInner - cosOuter));
	        // float lightAngleOffset = -cosOuter * angleScale;
	        float cd = dot(lightDirection, lightVector);
	        float attenuation = saturate(cd * lightAngleScale + lightAngleOffset);
	        // smooth the transition
	        attenuation *= attenuation;
	        return attenuation;
        }
    };
}
