shader_type canvas_item;

uniform sampler2D SCREEN_TEXTURE : hint_screen_texture, filter_linear_mipmap;

// Radius in pixels
uniform float blur_radius : hint_range(0.0, 32.0) = 8.0;
// Number of samples in each direction
uniform int samples : hint_range(1, 20) = 6;
// 0 = no blur, 1 = fully blurred
uniform float blur_strength : hint_range(0.0, 1.0) = 0.6;
// Optional slight dimming of background
uniform float dim_amount : hint_range(0.0, 0.5) = 0.1;

void fragment() {
    vec4 original = textureLod(SCREEN_TEXTURE, SCREEN_UV, 0.0);

    vec2 pixel = SCREEN_PIXEL_SIZE * blur_radius;

    vec4 blurred = vec4(0.0);
    int count = 0;

    for (int x = -samples; x <= samples; x++) {
        for (int y = -samples; y <= samples; y++) {
            vec2 offset = vec2(float(x), float(y)) * pixel;
            blurred += textureLod(SCREEN_TEXTURE, SCREEN_UV + offset, 0.0);
            count++;
        }
    }

    blurred /= float(count);

    // Blend between original and blurred
    vec4 color = mix(original, blurred, blur_strength);

    // Slight dimming, if wanted
    color.rgb *= (1.0 - dim_amount);

    COLOR = color;
}