//
// Fragment shader for vignette photo effect
//
// Author: Jeff Brown
//
//


#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 vec3 fsPosition;
in float cosTime1;
in float cosTime2;
in float cosTime3;
in vec2 fsTime;

out vec4 outColor;

const float PI = 3.1415926;

vec2 rotate(float a, vec2 p)
{
    return vec2(cos(a) * p.x + sin(a) * p.y,
                cos(a) * p.y - sin(a) * p.x);
}
float starsLayer(vec2 p)
{
    p *= vec2(4.0, 3.0);
    return clamp(1e-2 / abs(cos(p.x) * sin(p.y)) * cos(p.x + PI * 0.5) * sin(p.y + PI * 0.5), 0.0, 1.0);
}
vec3 stars(vec2 p)
{
    vec2 p2 = floor(p * 100.0) / 100.0;

    float b = fract(atan(p2.y, p2.x) / PI * 10.0 + length(p2) * 3.0 * cosTime1 + cosTime2 * 2.0);

    b = smoothstep(0.4, 0.5, b) - smoothstep(0.9, 1.0, b);

    b *= (0.8 + 0.2 * cos(p.y * 200.0 * PI)) * (0.95 + 0.05 * cosTime3);

    return vec3(b) * 0.1 + vec3(starsLayer(rotate(-0.9, p * 4.0) + fsTime) * 0.1 +
                                starsLayer(rotate(0.1, p + fsTime)) +
                                starsLayer(rotate(1.0, p * 2.0 + fsTime))) * vec3(1.0, 1.2, 1.3) * 0.5;
}

float vignette(vec2 p)
{
    return 1.0 - (p.x * p.x * p.x * p.x  + p.y * p.y * p.y * p.y) * 0.5;
}

void main(void)
{
    vec3 starColor= stars(fsPosition.xy) * smoothstep(0.0, 0.4, length(fsPosition.xy));
    starColor *= vignette(fsPosition.xy);

    vec4 texColor = texture(inputTex, fsTexture);
#ifdef PRE_MULT
    divideAlpha(texColor);
#endif
    //    outColor=mix(texColor,vec4(starColor,1.0),blendValue);
    outColor=texColor;
    float blendValue2=uBlendValue;
#ifdef USE_MASK
    blendValue2*=texture(maskTex,fsMaskTexture).a;
#endif
    outColor.rgb+=starColor*blendValue;
    outColor.rgb=mix(texColor.rgb,outColor.rgb,blendValue2);
#ifdef PRE_MULT
    multiplyAlpha(outColor);
#endif
}

