#version 120

// Bloom settings
#define BLOOM_ENABLED 1 // Enable bloom effect [0 1]
#define BLOOM_THRESHOLD 0.8 // Brightness threshold for bloom [0.5 0.6 0.7 0.8 0.9 1.0]
#define BLOOM_DILATION 1 // Dilation radius for connecting distant pixels [0 1 2 3]

uniform sampler2D colortex0; // Scene color
uniform float viewWidth;
uniform float viewHeight;

/* RENDERTARGETS:2 */

varying vec2 texcoord;

// Extract bright areas for bloom
vec3 extractBrightAreas(vec3 color) {
    #if BLOOM_ENABLED == 0
    return vec3(0.0);
    #endif
    
    float brightness = dot(color, vec3(0.299, 0.587, 0.114));
    
    // For pencil drawings, we want to bloom light/bright areas, not dark lines
    if (brightness > BLOOM_THRESHOLD) {
        float bloomFactor = smoothstep(BLOOM_THRESHOLD, 1.0, brightness);
        return color * bloomFactor;
    }
    
    return vec3(0.0);
}

// Dilate bright areas to improve connectivity for distant objects
vec3 dilateBrightAreas(sampler2D tex, vec2 texcoord) {
    #if BLOOM_DILATION == 0
    return extractBrightAreas(texture2D(tex, texcoord).rgb);
    #endif
    
    vec2 pixelSize = vec2(1.0 / viewWidth, 1.0 / viewHeight);
    vec3 maxBright = vec3(0.0);
    
    // Check center pixel first
    vec3 centerBright = extractBrightAreas(texture2D(tex, texcoord).rgb);
    maxBright = max(maxBright, centerBright);
    
    // Check neighboring pixels in a cross pattern for dilation
    for (int x = -BLOOM_DILATION; x <= BLOOM_DILATION; x++) {
        for (int y = -BLOOM_DILATION; y <= BLOOM_DILATION; y++) {
            if (x == 0 && y == 0) continue; // Skip center, already checked
            
            vec2 offset = vec2(float(x), float(y)) * pixelSize;
            vec3 neighborColor = texture2D(tex, texcoord + offset).rgb;
            vec3 neighborBright = extractBrightAreas(neighborColor);
            
            // Use maximum brightness to create connectivity
            maxBright = max(maxBright, neighborBright);
        }
    }
    
    return maxBright;
}

void main() {
	vec3 sceneColor = texture2D(colortex0, texcoord).rgb;
    // Extract and dilate bright areas for better connectivity
    //vec3 brightAreas = dilateBrightAreas(colortex0, texcoord); //may not use
	vec3 brightAreas = extractBrightAreas(sceneColor);
	
    gl_FragData[0] = vec4(brightAreas, 1.0);
}