#version 300 es
precision highp float;

uniform sampler2D uMainTex;
uniform vec2 uSSize;
uniform int uIntensity;

in vec2 v_originTexCoord;
out vec4 fragColor;

// 常量定义
const float GRAY_RED = 0.299;
const float GRAY_GREEN = 0.587;
const float GRAY_BLUE = 0.114;

// 计算灰度值
float calculateGray(vec3 color) {
    return dot(color, vec3(GRAY_RED, GRAY_GREEN, GRAY_BLUE));
}

// 计算四个区域的采样坐标
void calculateSampleUVs(int i, int j, int K, out vec2 uv1, out vec2 uv2, out vec2 uv3, out vec2 uv4) {
    uv1 = v_originTexCoord + vec2(i-K, j-K)/uSSize.xy;
    uv2 = v_originTexCoord + vec2(i, j-K)/uSSize.xy;
    uv3 = v_originTexCoord + vec2(i-K, j)/uSSize.xy;
    uv4 = v_originTexCoord + vec2(i, j)/uSSize.xy;
}

// 计算四个区域的平均颜色
void calculateMeanColors(int K, out vec3 mean0, out vec3 mean1, out vec3 mean2, out vec3 mean3) {
    float sectorSize = float(K*K + 2*K + 1);
    mean0 = vec3(0.0);
    mean1 = vec3(0.0);
    mean2 = vec3(0.0);
    mean3 = vec3(0.0);

    for(int i = 0; i <= K; i++) {
        for(int j = 0; j <= K; j++) {
            vec2 uv1, uv2, uv3, uv4;
            calculateSampleUVs(i, j, K, uv1, uv2, uv3, uv4);
            
            mean0 += texture(uMainTex, uv1).rgb;
            mean1 += texture(uMainTex, uv2).rgb;
            mean2 += texture(uMainTex, uv3).rgb;
            mean3 += texture(uMainTex, uv4).rgb;
        }
    }

    mean0 /= sectorSize;
    mean1 /= sectorSize;
    mean2 /= sectorSize;
    mean3 /= sectorSize;
}

// 计算四个区域的方差
void calculateVariances(int K, vec3 mean0, vec3 mean1, vec3 mean2, vec3 mean3, out vec4 variances) {
    variances = vec4(0.0);
    vec4 means = vec4(calculateGray(mean0), calculateGray(mean1), 
                      calculateGray(mean2), calculateGray(mean3));

    for(int i = 0; i <= K; i++) {
        for(int j = 0; j <= K; j++) {
            vec2 uv1, uv2, uv3, uv4;
            calculateSampleUVs(i, j, K, uv1, uv2, uv3, uv4);

            vec4 grays = vec4(
                calculateGray(texture(uMainTex, uv1).rgb),
                calculateGray(texture(uMainTex, uv2).rgb),
                calculateGray(texture(uMainTex, uv3).rgb),
                calculateGray(texture(uMainTex, uv4).rgb)
            );

            vec4 diff = grays - means;
            variances += diff * diff;
        }
    }
}

void main() {
    int K = uIntensity;
    
    // 计算四个区域的平均颜色
    vec3 mean0, mean1, mean2, mean3;
    calculateMeanColors(K, mean0, mean1, mean2, mean3);
    
    // 计算四个区域的方差
    vec4 variances;
    calculateVariances(K, mean0, mean1, mean2, mean3, variances);
    
    // 选择方差最小的区域的颜色作为最终颜色
    float minVariance = min(variances.x, min(variances.y, min(variances.z, variances.w)));
    
    fragColor = vec4(
        minVariance == variances.x ? mean0 :
        minVariance == variances.y ? mean1 :
        minVariance == variances.z ? mean2 :
        minVariance == variances.w ? mean3 :
        (mean0 + mean1 + mean2 + mean3) * 0.25,
        1.0
    );
}