#version 100

precision highp float;

uniform sampler2D screenTexture;
uniform vec2 screenSize;
varying vec2 uv;

uniform float threshold;   //%0.8% 阈值
uniform float intensity;   //%2.0% 强度
uniform float radium;   //%15.0% 半径
uniform float sampleCount; //%4% 采样次数

vec2 getCuteCoord(vec2 coord) {
    return coord * screenSize;
}

vec4 getBloomOrigin(vec4 color, float zz) {
    float gray = dot(color.rgb, vec3(0.299, 0.587, 0.114));
    if (gray < 1.0 - zz) {
        color.rgb = vec3(0.);
    }
    return color;
}

vec3 bloom(int rad, float intensity, float zz) {
    vec3 sum = vec3(0.);
    for (int i = 0; i < 16; i++) {
        if (float(i)>=sampleCount) break;
        for (int j = 0; j < 16; j++) {
            if (float(j)>=sampleCount) break;
            vec2 offset = vec2(float(i) / float(sampleCount - 1.) - 0.5, float(j) / float(sampleCount - 1.) - 0.5)*radium*2.;
            sum += getBloomOrigin(texture2D(screenTexture, (uv * screenSize + offset) / screenSize), zz).rgb * (1. - (pow(offset.x, 2.0) + pow(offset.y, 2.0)) / (2. * pow(radium, 2.)));
        }
    }

    sum /= float((rad + 1) * (rad + 1));
    return sum * intensity*pow(16./sampleCount,2.);
}

void main() {
    vec2 uv=gl_FragCoord.st/screenSize;
    vec4 colora = texture2D(screenTexture, uv);
    vec3 color = colora.rgb;

    color += bloom(int(radium), intensity, threshold);
    gl_FragColor = vec4(color.rgb, colora.a);
}