precision highp float;
#define iChannel0 inputImageTexture
#define texture(a,b) texture2D(a,fract(b))
#define fragColor gl_FragColor
varying highp vec2 textureCoordinate;
varying highp vec2 textureCoordinate2;

uniform sampler2D inputImageTexture;
uniform sampler2D inputImageTexture2;

uniform highp float iTime;

uniform highp vec2 iResolution;

highp vec2 fragCoord = textureCoordinate * iResolution;

void main() {
    highp vec2 uv = textureCoordinate;
    // sample zbuffer (in linear eye space) at the current shading point
    float zr = 1.0 - texture(iChannel0, uv).x;

    // sample neighbor pixels
    float ao = 0.0;
    for( int i=0; i<8; i++ )
    {
        // get a random 2D offset vector
        highp vec2 off = -1.0 + 2.0*texture(iChannel1, (fragCoord.xy + 23.71*float(i))/vec2(256.)).xz;
        // sample the zbuffer at a neightbor pixel (in a 16 pixel radious)
        float z = 1.0-texture( iChannel0, (fragCoord.xy + floor(off*16.0))/iResolution.xy).x;
        // accumulate occlusion if difference is less than 0.1 units
        ao += clamp( (zr-z)/0.1, 0.0, 1.0);
    }
    // average down the occlusion
    ao = clamp( 1.0 - ao/8.0, 0.0, 1.0 );

    highp vec3 col = vec3(ao);

    // uncomment this one out for seeing AO with actual image/zbuffer
    //col *= texture( iChannel0, fragCoord.xy / iResolution.xy ).xyz;

    fragColor = vec4(col,1.0);
}