
#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;
    vec2 p2 = input.tex2;
    kaleidoscopeTransform(p, u.transitionProgressLinear, power, speed);

    vec4 colorA = getColor(inputTex0, input.tex1);
    vec4 colorB = getColor(inputTex1, input.tex2);
    vec4 colorA2 = getColor(inputTex0, p);
    vec4 colorB2 = getColor(inputTex1, p2);

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

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

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

#ifndef PRE_MULT
    divideAlpha(outColor);
#endif

    return outColor;
}
