//
// Lens Distortion
// Original code Shirley Carter
// Modified for rvfx - jrb
//

#version 330

#include "alpha.h"

uniform sampler2DRect inputTex;
uniform sampler2DRect maskTex;
uniform float lensSize;
uniform float colorDistort;
uniform float uBlendValue=1.0;

in vec2 fsTexture;
in vec2 fsMaskTexture;
in vec2 fsPosition;
in vec2 fsTextureSize;
in vec2 fsNormalizedUV;

out vec4 outColor;

void main(void)
{
    //////
    //Compute distortion
    float k  = -lensSize;//-0.15; //distortion coefficient
    float kcube = .5;//.15; //cubic distortion value
    float scale = .9;
    float dispersion = colorDistort*.01;
    float blurAmount = .5;

    //    float r2 = (x- .5) * (x-.5) + (y - .5) * (y-.5);
    float r2=length(fsPosition);

    //compute cubic distortion, if necessary
    float mult = -lensSize;
    if( kcube != 0.0 )
        mult = k + kcube * r2;

    float f= 1.0 + r2*r2 * mult;  //factor of distortion

    //chromatic aberration variable distortion depending on color
    vec2 tCoord = fsPosition; //x , y coord, not image coord
    vec3 eta = vec3(1.0+dispersion*8.0, 1.0+dispersion*3.0, 1.0+dispersion*1.0);//strong red distortion, weak green and blue

    vec2 rCoords = (f*eta.r)*scale*(tCoord.xy)+0.5;
    vec2 gCoords = (f*eta.g)*scale*(tCoord.xy)+0.5;
    vec2 bCoords = (f*eta.b)*scale*(tCoord.xy)+0.5;

    rCoords=clamp(rCoords,vec2(0.0,0.0),vec2(1.0,1.0))*fsTextureSize;
    gCoords=clamp(gCoords,vec2(0.0,0.0),vec2(1.0,1.0))*fsTextureSize;
    bCoords=clamp(bCoords,vec2(0.0,0.0),vec2(1.0,1.0))*fsTextureSize;
    vec4 texel=texture(inputTex,fsTexture);
    outColor=texture(inputTex,rCoords);
    outColor.g=texture(inputTex,gCoords).g;
    outColor.b=texture(inputTex,bCoords).b;
    float blendValue=uBlendValue;
#ifdef USE_MASK
    blendValue*=texture(maskTex,fsMaskTexture).a;
#endif
    mixColor(outColor, texel, outColor, blendValue);
}
