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

#version 330

#include "alpha.h"

uniform sampler2DRect inputTex;
uniform sampler2DRect maskTex;
uniform int numSides;
uniform float centerX;
uniform float centerY;

in vec2 fsTexture;
in vec2 fsMaskTexture;
in vec2 fsPosition;
in vec2 fsTextureSize;
in float fsTime;
uniform float uBlendValue=1.0;

out vec4 outColor;

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

void main(void)
{
    vec4 color = texture(inputTex, fsTexture);
    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 = sides*a/3.1416;
    uv.y = sin(sides*r+fsTime) + sides/10.0*cos(fsTime+7.0*a);
    uv.x = 0.5*(uv.x+1.0)*fsTextureSize.x;
    uv.y = 0.5*(uv.y+1.0)*fsTextureSize.y;
    uv.x = InBound(uv.x, 0., fsTextureSize.x)?uv.x:fsTexture.x;
    uv.y = InBound(uv.y, 0., fsTextureSize.y)?uv.y:fsTexture.y;

    outColor = texture(inputTex, uv);
    float w = .5+.5*(sin(fsTime+sides*r) + sides/10.0*cos(fsTime+sides*a));
    multiplyOpacity(outColor, w);

    float blendValue=uBlendValue;
#ifdef USE_MASK
    blendValue*=texture(maskTex,fsMaskTexture).a;
#endif
    mixColor(outColor, color, outColor, blendValue);
}
