#version 300 es
precision highp float;

uniform sampler2D uMainTex;
in vec2 v_originTexCoord;

uniform float uAspectRatio;
uniform vec4 uRectBounds;
uniform float uRectRadius;
uniform float uRectExpand;

out vec4 fragColor;

// 计算点到圆角矩形的有符号距离
float roundedRectSDF(vec2 position, vec2 center, vec2 size, float radius) {
    vec2 q = abs(position - center) - size + vec2(radius);
    return length(max(q, 0.0)) + min(max(q.x, q.y), 0.0) - radius;
}

void main() {
    // 将坐标转换为以矩形中心为原点的坐标系
    vec2 rectCenter = vec2(
        (uRectBounds.x + uRectBounds.y) * 0.5,
        (uRectBounds.w + uRectBounds.z) * 0.5
    );
    vec2 rectSize = vec2(
        (uRectBounds.y - uRectBounds.x) * 0.5,
        (uRectBounds.z - uRectBounds.w) * 0.5
    );

    vec2 position = vec2(v_originTexCoord.x, v_originTexCoord.y / uAspectRatio);
    
    // 计算SDF（注意这里直接传入所有参数）
    float d = roundedRectSDF(position, rectCenter, rectSize, uRectRadius);

    // 获取原始纹理颜色
    vec4 texColor = texture(uMainTex, v_originTexCoord);
    
    // 使用SDF进行裁剪：d < 0 表示在圆角矩形内部
    float mask = 1.0 - smoothstep(-0.002, 0.002, d);
    
    // 输出裁剪后的纹理颜色
    fragColor = vec4(texColor.rgb, texColor.a * mask);
}