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

typedef struct
{
    float squareSize;
} fxVars;

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

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;
    out.normPos=in[vertexID].pos.xy*vec2(.5,.5f)+vec2(.5,.5);
    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)]])
{
    float progress=u.transitionProgressLinear;
    float revProgress = (1.0 - progress);
    float distFromEdges = min(progress, revProgress);

    vec4 texColor=getColor(inputTex0,input.tex1);
    vec4 texelA=mix(vec4(0,0,0,0),texColor,u.mix);
    vec4 texelB=mix(texColor,vec4(0,0,0,0),u.mix);
    float flickerSpeed = 60.0;

    vec2 seed = floor(input.tex1/vec2(.05,.05)) * floor(distFromEdges * flickerSpeed);

    float4 outColor;
    mixColor(outColor, texelB, texelA, u.transitionProgress);

#ifdef PRE_MULT
    divideAlpha(outColor);
#endif

    outColor.rgba += rand(seed) * distFromEdges * 0.5;

#ifdef OPACITY_MASK
    outColor.a = min(texColor.a, outColor.a);
#endif

#ifdef PRE_MULT
    multiplyAlpha(outColor);
#endif

    float alpha = u.baseAlpha;
#ifdef USE_MASK
    alpha *= float(inputTexMask.sample(linearSampler, input.texMask).a);
#endif
    multiplyOpacity(outColor, alpha);

    return outColor;
}
