//precision highp float;

uniform vec2 u_cellUVSize;
uniform vec2 u_gridUVSize;

varying vec2 v_texCoord;
varying vec2 v_neighbours[8];

void main()
{
    vec2 snappedCellTexCoord = (floor(v_texCoord / u_cellUVSize ) + 0.5 ) * u_cellUVSize * u_gridUVSize;
    vec4 cellCol = texture2D(CC_Texture1, snappedCellTexCoord);
    vec4 cellAtt = texture2D(CC_Texture2, snappedCellTexCoord);
    vec4 cellAtt2 = texture2D(CC_Texture3, snappedCellTexCoord);
    //if noiseSelector == 1 then waviness is preferred
    //This is based on cell color
    //    float noiseSelector = step (0.01,cellCol.a);
    float waviness = cellAtt2.r;
    float wavinessH = waviness;
    float wavinessV = waviness;
    
    if (waviness > 0.1) {
        float left = step(0.1, texture2D(CC_Texture3, v_neighbours[0]).r);
        float right= step(0.1, texture2D(CC_Texture3, v_neighbours[1]).r);
        float down = step(0.1, texture2D(CC_Texture3, v_neighbours[2]).r);
        
        float rightDown  = step(0.1, texture2D(CC_Texture3, v_neighbours[3]).r);
        float leftDown = step(0.1, texture2D(CC_Texture3, v_neighbours[4]).r);
        
        float rightUp  = step(0.1, texture2D(CC_Texture3, v_neighbours[6]).r);
        float leftUp = step(0.1, texture2D(CC_Texture3, v_neighbours[7]).r);
        
        float up = step(0.1, texture2D(CC_Texture3, v_neighbours[5]).r) ;
        
        wavinessH = waviness * left * right * leftDown * rightDown * leftUp * rightUp;
        wavinessV = waviness * down * up;
    }
    
    float edge = cellCol.a * 1.0 - step(0.1, texture2D(CC_Texture1, v_neighbours[5]).a);
    edge *= step(0.1,waviness);
    wavinessH = mix(wavinessH,waviness, edge);
    
    //wave mask, material mask, fluid edge mask, heat distortion
    //gl_FragColor = vec4(waviness * noiseSelector, cellAtt.a, step(0.1, edge),waviness * (1.0-noiseSelector));
    
    //mask > 0.7 is for water rendering > 200
    //0.4 < mask < 0.7 is for foreground rendering ~128
    //0 is for normal particle rendering 0
    float mask = step (0.7, cellAtt.a);
    gl_FragColor = vec4(wavinessH, mask, step(0.1, edge), wavinessV);
} 
