precision highp float;

uniform float u_strength;
uniform float u_phase;

uniform float u_waveScale;
uniform vec2 u_uvSize;
varying vec2 v_texCoord;
varying vec2 v_diffTexCoord;

void main()
{
    vec4 attCol = texture2D(CC_Texture3, v_diffTexCoord);
    
    vec4 dispCol= vec4(0.0);
    vec2 coord = vec2(0.0);
    vec2 noiseUV = vec2(0.0);
    vec2 noiseWave = vec2(0.0);
    
    //Waviness
    
    if(attCol.b> 0.1){
        float scale = attCol.r;
        noiseUV = mod(v_texCoord * u_waveScale, 1.0);
        
        noiseUV.y = mod(noiseUV.y - u_phase, 1.0);
        noiseWave = texture2D(CC_Texture2, noiseUV).xy;
        
        noiseWave = noiseWave - 0.5;
        noiseWave.x =0.0;
        noiseWave.y += 0.25; //hardcoded offset to make guille happy
        noiseWave *= u_strength;// * step(0.1, scale);
        noiseWave.y *= scale;
    }
    else{
        if( (attCol.r+attCol.a) > 0.1){
            float scaleH = attCol.r;
            float scaleV = attCol.a;
            
            noiseUV = mod(v_texCoord * u_waveScale, 1.0);
            
            noiseUV.y = mod(noiseUV.y - u_phase, 1.0);
            noiseWave = texture2D(CC_Texture2, noiseUV).xy;
            noiseWave = noiseWave - 0.5;
            noiseWave.y += 0.25; //hardcoded offset to make guille happy
            noiseWave *= u_strength;// * step(0.1, scale);
            noiseWave.x *= scaleH;
            noiseWave.y *= scaleV;
        }
    }
    
    
    coord =clamp(v_diffTexCoord + noiseWave, vec2(0.0) , 0.999 * u_uvSize);
    dispCol = texture2D(CC_Texture1, coord);
    gl_FragColor = dispCol;
}