//
// Fragment shader for Ripple effect (from Center)
//
// Author: Shirley - converted to rvfx - jb
//
//


#version 330

#include "alpha.h"

uniform sampler2DRect inputTex;
uniform sampler2DRect maskTex;
uniform float blendValue;
uniform float uBlendValue=1.0;

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

out vec4 outColor;

const float PI = 3.1415926535897932;

//speed
const float speed = 0.2;
const float speed_x = 0.3;
const float speed_y = 0.3;

// geometry
const float intensity = 3.;
const int steps = 8;
const float frequency = 4.0;
const int angle = 7; // better when a prime

// reflection and emboss
const float delta = 20.;
const float intence = 400.;
const float emboss = 0.3;

//---------- crystals effect

float col(vec2 coord)
{
    float delta_theta = 2.0 * PI / float(angle);
    float col = 0.0;
    float theta = 0.0;

    for (int i = 0; i < steps; i++)
    {
        vec2 adjc = coord;
        theta = delta_theta*float(i);
        adjc.x += cos(theta)*fsTime*speed + fsTime * speed_x;
        adjc.y -= sin(theta)*fsTime*speed - fsTime * speed_y;
        col = col + cos( (adjc.x*cos(theta) - adjc.y*sin(theta))*frequency)*intensity;
    }

    return cos(col);
}


void main(void)
{
    vec2 c1 = fsNormalizedUV;
    vec2 c2 = fsNormalizedUV;
    float cc1 = col(c1);

    c2.x += 64.0;
    float dx = emboss*(cc1-col(c2))/delta;

    c2.x = fsNormalizedUV.x;
    c2.y += 39.0;
    float dy = emboss*(cc1-col(c2))/delta;

    c1.x += dx;
    c1.y += dy;
    //  c1.y = -c1.y;

    float alpha = 1.+dot(dx,dy)*intence;

    //    vec2 uv=clamp(c1,vec2(0.0,0.0),vec2(1.0,1.0))*fsTextureSize;
    vec2 uv=c1*=fsTextureSize;

    vec4 texel=texture(inputTex,fsTexture);
    vec4 texColor=texture(inputTex,uv);

#ifdef PRE_MULT
    divideAlpha(texColor);
#endif
    outColor.rgb = texColor.rgb * alpha;
    outColor.a = texColor.a;
#ifdef PRE_MULT
    multiplyAlpha(outColor);
#endif

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