#version 330

#include "alpha.h"

uniform sampler2DRect inputTex;
uniform sampler2DRect inputTex1;
uniform float transitionProgress=1.0;
uniform float transitionProgressLinear=1.0;
uniform float transitionAlpha=1.0;
uniform int transitionState;
uniform float baseAlpha=1.0;
uniform sampler2DRect maskTex;
in vec2 fsMaskTexture;
uniform float scale=1.0;


in vec2 fsTexture;
in vec2 fsTexture2;
in vec2 fsTextureNormalized;
in vec2 fsTextureNormalized2;
in vec2 fsTextureSize;
in vec2 fsTextureSize2;

out vec4 outColor;

//hash and noise from ShaderToy

float hash(vec2 p)
{
    p  = 50.0*fract( p*0.3183099 + vec2(0.71,0.113));
    return -1.0+2.0*fract( p.x*p.y*(p.x+p.y) );
}

float noise( in vec2 p )
{
    vec2 i = floor( p );
    vec2 f = fract( p );

    vec2 u = f*f*(3.0-2.0*f);

    return mix( mix( hash( i + vec2(0.0,0.0) ),
                    hash( i + vec2(1.0,0.0) ), u.x),
               mix( hash( i + vec2(0.0,1.0) ),
                   hash( i + vec2(1.0,1.0) ), u.x), u.y);
}

//basic idea came from ShaderToy "Fade&Smoke" but that used another texture to guide the transition
//modified it to use a grayscale "noise" image that we generate
//several different variations of this effect can be generated by modifying the transition image.

void main()
{
    vec4 newColor = texture(inputTex, fsTexture);
    vec4 oldColor = texture(inputTex1, fsTexture2);

    vec2 p=fsTextureNormalized2;
    vec2 uv2 = p*vec2(fsTextureSize2.x/fsTextureSize2.y,1.0);

    float f = 0.0;
    f = noise( scale*uv2 );
    f = 0.5 + 0.5*f;

    f *= smoothstep( 0.0, 0.005, abs(p.x-0.0) );

    vec2 uv0 = (fsTextureNormalized*2.0 - 1.0) * 0.5;
    float length0 = sqrt(dot(uv0, uv0));
    float time = transitionProgress * 150.0;
    float mask = 1.0 - clamp(length0 * 100.0 - (time*(f*0.5+0.5)),0.0,1.0);

    outColor=mix(oldColor,newColor,mask);

    // outColor.rgb=vec3(f,f,f); //use this to look at noise image being used for mixing the old/new textures
#ifdef USE_MASK
    multiplyOpacity(outColor, texture(maskTex, fsMaskTexture).a);
#endif
}
