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

typedef struct
{
    float scale;
} fxVars;


vertex fxVertexOut 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)]])
{
    fxVertexOut out;

    out.normPos=in[vertexID].pos.xy;//*vec2(.5,.5f)+vec2(.5,.5);
    out.position=in[vertexID].pos;

    out.tex1=in[vertexID].tex1;
    out.texMask=in[vertexID].texMask;
    out.texSize=float2(inputTex0.get_width(),inputTex0.get_height());
    return out;
}

fragment float4 fragmentFunc(fxVertexOut input [[stage_in]]
                             ,texture2d<half> inputTex [[ texture(0) ]]
                             ,texture2d<half> inputTexMask [[ texture(1) ]]
                             ,constant fxGeneralUniforms& u[[ buffer(0) ]]
                             ,constant fxVars& vars[[ buffer(1)]])
{

    vec4 color = getColor(inputTex, fsTexture);

    float x=input.normPos.x;
    float y=-input.normPos.y;

    //Then transform to polar coordinates
    float ratio = min(input.texSize.x/input.texSize.y, input.texSize.y/input.texSize.x);
    float r = ratio*sqrt(x*x + y*y);
    float phi = atan2(y,x);//equivalent to atan2

    float t = 90.0;//mod( float( time ), 30000.0 ) / 1000.0; //0 - 30 seconds
    float fac =  abs( sin( t ) )*vars.scale + .125;//+1.5;/// 2.0 + 1.5;
    r = pow( r, fac );//fac );//magnifier

    //Map from polar to x, y
    x = r*cos( phi );
    y = r*sin( phi );
    vec2 uv;
    uv.x=x;
    uv.y=y;
    uv+=vec2(1.0,1.0);
    uv*=vec2(.5,.5f);
    // uv=clamp(uv,vec2(0.0,0.0),vec2(1.0,1.0));

    float4 outColor=getColor(inputTex,uv);
    float blendValue=u.blendValue;
#ifdef USE_MASK
    blendValue*=getColor(inputTexMask,input.texMask).a;
#endif
    mixColor(outColor, color, outColor, blendValue);
    return outColor;
}
