#version 430

layout(binding=0) uniform sampler2D tex;
layout(location = 0) out vec4 frag;
layout(location = 1) out vec4 frag2;

uniform float g_time;

precision highp float;
in highp vec2 coordG;

uniform float g_sourceW;
uniform float g_sourceH;
uniform float g_destW;
uniform float g_destH;

int fetchAndAdd(inout vec4 result, vec2 k) {
    vec4 v = texelFetch(tex, ivec2(k.x+0.0, k.y+0.0), 0);
    if (v.z > -999000.0) {
        result += v;
        return 1;
    }
    return 0;
}

void main() {
    vec4 result = vec4(0.0);
    vec2 k = 2.0*gl_FragCoord.xy*(g_sourceW-1)/g_sourceW;
    int count = 0;
    count += fetchAndAdd(result, vec2(k.x, k.y));
    count += fetchAndAdd(result, vec2(k.x+1.0, k.y));
    count += fetchAndAdd(result, vec2(k.x, k.y+1.0));
    count += fetchAndAdd(result, vec2(k.x+1.0, k.y+1.0));
    if (count>0) {
        result *= 1.0/float(count);
    }
    else {
        result.z = -999999.0;
    }

    //result.r = 1.0;
    frag = result;
}
