//
// Fragment shader for Kaleidoscope effect
//
// Author: Shirley Carter
//
// updated for RVFX system
//

#version 330

#include "alpha.h"

uniform sampler2DRect inputTex;
uniform sampler2DRect maskTex;
uniform float uBlendValue=1.0;
uniform int numSides;
uniform float centerX;
uniform float centerY;

in vec2 fsTexture;
in vec2 fsMaskTexture;
in vec2 fsPosition;
in vec2 fsTextureSize;
in float fsTime;

out vec4 outColor;

bool InBound(float x, float a, float b)
{
    return (x > a && x<=b);
}

void main(void)
{
    vec2 p=fsPosition-vec2(centerX*2.,centerY*2.);

    float r = length(p);
    float a = atan(p.y, p.x);
    float tau = 2.0 * 3.1416;
    float sides=float(numSides);
    a = mod(a, tau/sides);
    a = abs(a - tau/sides/2.0);

    vec2 uv;

    uv.x = r *cos(a) + 0.5+fsTime;
    uv.y = r *sin(a) + 0.5+fsTime;

    uv = 0.5*uv*fsTextureSize;

    uv.x = InBound(uv.x, 0., fsTextureSize.x)?uv.x:fsTexture.x;
    uv.y = InBound(uv.y, 0., fsTextureSize.y)?uv.y:fsTexture.y;

    vec4 texel=texture(inputTex,fsTexture);
    outColor =  texture(inputTex,uv);
    float blendValue=uBlendValue;
#ifdef USE_MASK
    blendValue*=texture(maskTex,fsMaskTexture).a;
#endif
    mixColor(outColor, texel, outColor, blendValue);
}
