shader_type canvas_item;

// Récupère l'image rendue par la caméra 3D (Godot 4)
uniform sampler2D screen_texture : hint_screen_texture, repeat_disable, filter_nearest;

// Taille du "pinceau" (plus c'est grand, plus l'effet peinture est fort)
uniform int radius : hint_range(1, 10) = 4;

void fragment() {
    vec2 uv = SCREEN_UV;
    vec2 tex_size = vec2(textureSize(screen_texture, 0));
    vec2 texel = 1.0 / tex_size;

    // Nombre de pixels analysés par quadrant
    float n = float((radius + 1) * (radius + 1));

    // Moyennes (m) et Variances (s) pour les 4 quadrants
    vec3 m0 = vec3(0.0), m1 = vec3(0.0), m2 = vec3(0.0), m3 = vec3(0.0);
    vec3 s0 = vec3(0.0), s1 = vec3(0.0), s2 = vec3(0.0), s3 = vec3(0.0);
    vec3 c;

    // Quadrant 0 (Haut Gauche)
    for (int j = -radius; j <= 0; ++j) {
        for (int i = -radius; i <= 0; ++i) {
            c = texture(screen_texture, uv + vec2(float(i), float(j)) * texel).rgb;
            m0 += c; s0 += c * c;
        }
    }
    // Quadrant 1 (Haut Droite)
    for (int j = -radius; j <= 0; ++j) {
        for (int i = 0; i <= radius; ++i) {
            c = texture(screen_texture, uv + vec2(float(i), float(j)) * texel).rgb;
            m1 += c; s1 += c * c;
        }
    }
    // Quadrant 2 (Bas Droite)
    for (int j = 0; j <= radius; ++j) {
        for (int i = 0; i <= radius; ++i) {
            c = texture(screen_texture, uv + vec2(float(i), float(j)) * texel).rgb;
            m2 += c; s2 += c * c;
        }
    }
    // Quadrant 3 (Bas Gauche)
    for (int j = 0; j <= radius; ++j) {
        for (int i = -radius; i <= 0; ++i) {
            c = texture(screen_texture, uv + vec2(float(i), float(j)) * texel).rgb;
            m3 += c; s3 += c * c;
        }
    }

    float min_var = 1e+6; // Valeur de base très haute
    vec3 final_color = vec3(0.0);
    float var;

    // Calcul pour le Q0
    m0 /= n; s0 = abs(s0 / n - m0 * m0); var = s0.r + s0.g + s0.b; 
    if (var < min_var) { min_var = var; final_color = m0; }
    
    // Calcul pour le Q1
    m1 /= n; s1 = abs(s1 / n - m1 * m1); var = s1.r + s1.g + s1.b; 
    if (var < min_var) { min_var = var; final_color = m1; }
    
    // Calcul pour le Q2
    m2 /= n; s2 = abs(s2 / n - m2 * m2); var = s2.r + s2.g + s2.b; 
    if (var < min_var) { min_var = var; final_color = m2; }
    
    // Calcul pour le Q3
    m3 /= n; s3 = abs(s3 / n - m3 * m3); var = s3.r + s3.g + s3.b; 
    if (var < min_var) { min_var = var; final_color = m3; }

    COLOR = vec4(final_color, 1.0);
}