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

typedef struct
{
    int direction;
} fxVars;

constant vec4 deltaTransTable[9] = {
    vec4(-2.,2.,0.,.0),
    vec4( 0.,2.,0.,.0),
    vec4( 2.,2.,0.,.0),
    vec4(-2.,0.,0.0,.0),
    vec4( 0.,0.,0.0,.0),
    vec4( 2.,0.,0.0,.0),
    vec4(-2.,-2.,0.,.0),
    vec4( 0.,-2.,0.,.0),
    vec4( 2.,-2.,0.,.0)
};

constant vec4 transOffsetTable[9] = {
    vec4(-2.,2.,0.0,.0),
    vec4( 0.,2.,0.0,.0),
    vec4( 2.,2.,0.0,.0),
    vec4(-2.,0.,0.0,.0),
    vec4( 0.,0.,0.0,.0),
    vec4( 2.,0.,0.0,.0),
    vec4(-2.,-2.,0.,.0),
    vec4( 0.,-2.,0.,.0),
    vec4( 2.,-2.,0.,.0)
};




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.normPos=in[vertexID].pos.xy;


    vec4 deltaTrans=deltaTransTable[vars.direction];
    vec4 transOffsetIn=transOffsetTable[vars.direction];
    vec4 transOffsetOut=vec4(0.,0.,0.0,.0);

    mat4 translation=mat4(
                          1.0, 0.0, 0.0, 0.00,
                          0.0, 1.0, 0.0, 0.00,
                          0.0, 0.0, 1.0, 0.00,
                          0.0, 0.0, 0.0, 1.00);


    vec4 tmpPos=vec4(in[vertexID].pos.xyz,1.0)*uniforms.worldViewProj;
    if(uniforms.transitionState==0)
    {
        transOffsetIn-=deltaTrans*uniforms.transitionProgress;

        translation[0][3]+=transOffsetIn.x;
        translation[1][3]+=transOffsetIn.y;
        translation[2][3]+=transOffsetIn.z;
    }
    else if(uniforms.transitionState==2)
    {
        transOffsetOut-=deltaTrans*uniforms.transitionProgress;

        translation[0][3]+=transOffsetOut.x;
        translation[1][3]+=transOffsetOut.y;
        translation[2][3]+=transOffsetOut.z;
    }
    out.position=tmpPos*translation;

    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)]])
{
    float4 outColor = getColor(inputTex0, input.tex1);
    float alpha = u.baseAlpha;
#ifdef USE_MASK
    outColor.a *= float(inputTexMask.sample(linearSampler, input.texMask).a);
#endif
    multiplyOpacity(outColor, alpha);
    return outColor;
}
