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

typedef struct
{
    float zoom;
    float size;
    float colorSeparation;
} fxVars;

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)]])
{
    float inv = 1. - u.transitionProgressLinear;
    vec2 disp = vars.size*vec2(cos(vars.zoom*input.tex1.x), sin(vars.zoom*input.tex1.y));
    vec2 disp2=vars.size*vec2(cos(vars.zoom*input.tex2.x), sin(vars.zoom*input.tex2.y));

    vec4 colorIn=getColor(inputTex0,(input.tex1+inv*disp));

    float progress=u.transitionProgressLinear;
    vec4 colorOut;

    colorOut.r=getColor(inputTex1,(input.tex2+progress*disp2*(1.0-vars.colorSeparation))).r;
    colorOut.ga=getColor(inputTex1,(input.tex2+progress*disp2)).ga;
    colorOut.b=getColor(inputTex1,(input.tex2+progress*disp2*(1.0+vars.colorSeparation))).b;

#ifndef PRE_MULT
    multiplyAlpha(colorOut);
    multiplyAlpha(colorIn);
#endif
    float4 outColor=mix(colorOut,colorIn,u.transitionProgress);
#ifndef PRE_MULT
    divideAlpha(outColor);
#endif

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

    return outColor;
}
