precision highp float;
uniform vec2 u_lightDirection;
//0 vertical pass
//1 horizontal pass
uniform int u_side;
//Size of the oclussion map
uniform vec2 u_occlusionMapUVSize;
uniform vec2 u_VOcclusionSize;
uniform highp vec2 u_gridHalf;

//actual tex coord (not taking in account the POT factor)
varying vec2 v_texCoord;
//norm tex coords [-1:1]
varying vec2 v_normTexCoord;



#define RAY_SAMPLES 512.0
#define RAY_LENGTH 1.41

void main(void) {
    
    float distance = RAY_LENGTH;
    vec2 coords = vec2(0.0,0.0);
    vec2 sampleCoord = vec2(0.0, 0.0);
    
    if(u_side == 0){
        coords.y = 1.0;
        coords.x = v_texCoord.x;
    }else{
        coords.y = v_texCoord.x;
        coords.x=1.0 - step(0.0,u_lightDirection.x) ;
    }
    
    //Loops limits should be constant
    for (float y = 0.0; y < RAY_SAMPLES ; y += 0.1) {
        //float r = RAY_LENGTH * y / RAY_SAMPLES ;
        float halfDiag = length(u_VOcclusionSize) * 0.5;
        float r = y * halfDiag;
        
        
        
        sampleCoord = coords + u_lightDirection * r ;
        if(sampleCoord.x > 1.0 || sampleCoord.x < 0.0 || sampleCoord.y > 1.0 || sampleCoord.y < 0.0)
            break;

        //sampleCoord = floor(sampleCoord *2.0*u_gridHalf ) /2.0 / u_gridHalf;
        
        sampleCoord*= u_occlusionMapUVSize;
        

       //clamp coords to integer pixels
       // sampleCoord = floor(sampleCoord / u_VOcclusionSize) * u_VOcclusionSize;
        
        vec4 data = texture2D(CC_Texture1, sampleCoord);

        vec4 down = texture2D(CC_Texture1, sampleCoord - vec2(0.0,u_VOcclusionSize.y * 0.5 ));
        vec4 up = texture2D(CC_Texture1, sampleCoord + vec2(0.0,u_VOcclusionSize.y * 0.5 ));
        vec4 left = texture2D(CC_Texture1, sampleCoord - vec2(u_VOcclusionSize.y * 0.5, 0.0 ));
        vec4 right = texture2D(CC_Texture1, sampleCoord + vec2(u_VOcclusionSize.y * 0.5 , 0.0 ));


        float occ = data.a + data.a * down.a + data.a * up.a ; // + down.a;
        
        //smallest distance to occluder
        if(occ >0.1){
            distance = r  + 2.0* halfDiag;
            break;
        }
        //float solid = step(0.5, data.a);
        //distance = min(distance,mix(1.0, r , solid));
    }


    gl_FragColor = vec4(distance/RAY_LENGTH, distance/RAY_LENGTH, distance/RAY_LENGTH, 1.0);

    //gl_FragColor = vec4(0.5);
    

}
