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

typedef struct
{
    float4 burnColor;
} 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 fsMix;
    if(u.transitionProgress<=.5)
        fsMix=u.transitionProgress*2.;
    else
        fsMix=(1.-u.transitionProgress)*2.;

    vec2 p = input.tex1;
    vec2 p2 = input.tex2;
    
    float T = u.transitionProgress;

    float S0 = 1.0;
    float S1 = 250.0;
    float S2 = 1.0;

    // 2 segments, 1/2 each
    float Half = 0.5;

    float PixelSize = ( T < Half ) ? mix( S0, S1, T / Half ) : mix( S1, S2, (T-Half) / Half );

    vec2 D = PixelSize / float2(inputTex0.get_width(),inputTex0.get_height());
    vec2 D2 = PixelSize / float2(inputTex1.get_width(),inputTex1.get_height());

    // remap UV from 0...1 to -0.5...+0.5 to make the mosaic pattern converge torwards the image center
    vec2 UV = ( p + vec2( -0.5 ) ) / D;
    vec2 UV2 = ( p2 + vec2( -0.5 ) ) / D2;

    // don't forget to remap coords back to 0...1 after ceil()
    vec2 Coord = clamp( D * ( ceil( UV + vec2( -0.5 ) ) ) + vec2( 0.5 ), vec2( 0.0 ), vec2( 1.0 ) );
    vec2 Coord2 = clamp( D2 * ( ceil( UV2 + vec2( -0.5 ) ) ) + vec2( 0.5 ), vec2( 0.0 ), vec2( 1.0 ) );

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

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

    return outColor;
}
