
#include "metalShaderTypes.h"
#include "alpha.h"

typedef struct
{
    float4 burnColor;
} fxVars;

float rand (vec2 co)
{
    return fract(sin(dot(co.xy ,vec2(12.9898,78.233))) * 43758.5453);
}

float Gaussian(float p, float center, float c)
{
    return 0.575 * exp(- pow((p - center) / c, 2.));
}

#define PI 3.1415926535897932384626433832795
float cosCurve(float p)
{
    return 0.5 * (cos(2.0*PI * (p - 0.5)) + 1.0);
}

vertex vertexOut vertexFunc(uint vertexID [[ vertex_id ]],const device txShaderVers* in[[ buffer(0) ]],constant txShaderUniforms& uniforms[[ buffer(3) ]],constant fxVars& vars[[ buffer(2)]])
{
    vertexOut out;

    out.position=in[vertexID].pos*uniforms.worldViewProj;

    out.tex1=in[vertexID].tex1;
    out.tex2=in[vertexID].tex2;
    out.texMask=in[vertexID].texMask;
    return out;
}

fragment float4 fragmentFunc(vertexOut input [[stage_in]]
                             ,texture2d<half> inputTex0 [[ texture(0) ]]
                             ,texture2d<half> inputTex1 [[ texture(1) ]]
                             ,texture2d<half> inputTexMask [[ texture(2) ]]
                             ,constant txShaderUniforms& u[[ buffer(2) ]]
                             ,constant subFXVars& subVars[[buffer(3)]]
                             ,constant fxVars& vars[[ buffer(1)]])
{
    vec2 p = input.tex1;
    vec2 p2 = input.tex2;

    float c = cos(0.575 * cosCurve(u.transitionProgressLinear * (1. + cosCurve(u.transitionProgressLinear) * Gaussian(u.transitionProgressLinear * rand(p), 0.5, 0.5))));
    float c2 = cos(0.575 * cosCurve(u.transitionProgressLinear * (1. + cosCurve(u.transitionProgressLinear) * Gaussian(u.transitionProgressLinear * rand(p2), 0.5, 0.5))));
    vec2 d = p * c;
    vec2 d2 = p2 * c2;

    vec4 colorA=getColor(inputTex0,d);
    vec4 colorB=getColor(inputTex1,d2);
    float4 outColor;
    mixColor(outColor, colorB, colorA, u.transitionProgressLinear);

#ifdef USE_MASK
    multiplyOpacity(outColor, float(inputTexMask.sample(linearSampler, input.texMask).a));
#endif

    return outColor;
}
