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

constant float4 toXYZ_R = float4(0.4124, 0.3576, 0.1805, 0.0);
constant float4 toXYZ_G = float4(0.2126, 0.7152, 0.0722, 0.0);
constant float4 toXYZ_B = float4(0.0193, 0.1192, 0.9505, 0.0);

typedef struct
{
    float frequency;
    float strobeLength;
    float strobeBlend;
    float randomness;
    float4 strobeColor;
} fxVars;

typedef struct
{
    float4 position [[position]];
    float2 tex1;
    float2 texMask;
    float2 normPos;
    float2 texSize;
    float fsStrobe;
} fsVertexOut;


vertex fsVertexOut vertexFunc(uint vertexID [[ vertex_id ]]
                              ,const device fxShaderVerts* in[[ buffer(0) ]]
                              ,texture2d<half> inputTex0 [[ texture(0) ]]
                              ,texture2d<half> inputTexMask [[ texture(1) ]]
                              ,constant fxGeneralUniforms& u[[ buffer(1) ]]
                              ,constant fxVars& vars[[ buffer(2)]])
{
    fsVertexOut out;
    
    out.normPos=in[vertexID].pos.xy*vec2(.5,-.5f);//+vec2(.5,.5);
    out.position=in[vertexID].pos;
    out.texSize=float2(inputTex0.get_width(),inputTex0.get_height());
    out.tex1=in[vertexID].tex1;
    out.texMask=in[vertexID].texMask;
    
    
    float strobe=abs(cos(u.globalTime*vars.frequency*31.41592653589793));
    float strobeRandom=floor((vars.frequency+1.0)*u.random);
    
    strobe=mix(strobe,strobeRandom,vars.randomness);
    if(strobe>(1.0-vars.strobeLength))
        out.fsStrobe=strobe;
    else
        out.fsStrobe=0.0;
    
    return out;
}

fragment float4 fragmentFunc(fsVertexOut input [[stage_in]]
                             ,texture2d<half> inputTex [[ texture(0) ]]
                             ,texture2d<half> inputTexMask [[ texture(1) ]]
                             ,constant fxGeneralUniforms& u[[ buffer(0) ]]
                             ,constant fxVars& vars[[ buffer(1)]])
{
    vec4 texel = getColor(inputTex, fsTexture);
#ifdef PRE_MULT
    divideAlpha(texel);
#endif


#ifdef LINEAR_16
    float4 strobeColor = float4(dot(toXYZ_R, vars.strobeColor), dot(toXYZ_G, vars.strobeColor), dot(toXYZ_B, vars.strobeColor), 1.0);
#else
    float4 strobeColor = vars.strobeColor;
#endif

    float4 outColor=vec4(mix(texel.rgb,strobeColor.rgb*u.nitsScale,input.fsStrobe*vars.strobeBlend),texel.a);
    float blendValue=u.blendValue;
#ifdef USE_MASK
    blendValue *= getColor(inputTexMask, input.texMask).a;
#endif
    outColor.rgb=mix(texel.rgb,outColor.rgb,blendValue);
#ifdef PRE_MULT
    multiplyAlpha(outColor);
#endif
    return outColor;
}
