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

typedef struct
{
    float4 burnColor;
} fxVars;

constant float speed=1.;
constant float angle=2.;
constant float power=2.;


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;
    kaleidoscopeTransform(p, u.transitionProgressLinear, power, speed);

    vec4 colorA = getColor(inputTex0, input.tex1);
#ifdef OPACITY_MASK
    vec4 texColor = colorA;
#endif
    vec4 colorA2 = getColor(inputTex0, p);

#ifndef PRE_MULT
    multiplyAlpha(colorA);
    multiplyAlpha(colorA2);
#endif

    vec4 colorB = colorA;
    multiplyOpacityPremultiplied(colorB, u.transitionAlpha);
    colorA = mix(colorA, colorA2, 1.0 - 2.0*abs(u.transitionProgressLinear - 0.5));
    vec4 outColor = mix(colorB, colorA, u.mix);

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

    float fsMix = u.transitionState == 2 ? 1.0 - u.transitionProgress : u.transitionProgress;
    float alpha = fsMix * u.baseAlpha;

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

    multiplyOpacityPremultiplied(outColor, alpha);

#ifndef PRE_MULT
    divideAlpha(outColor);
#endif

    return outColor;
}
