#version 300 es

precision mediump float;

in vec2 v_originTexCoord;

uniform sampler2D uMainTex;

out vec4 fragColor;

// 色相、饱和度、明度调节参数
uniform vec3 hsb;

vec3 rgb2hsl(vec3 color) {
    float max = max(color.r, max(color.g, color.b));
    float min = min(color.r, min(color.g, color.b));
    float h, s, l = (max + min) * 0.5;

    if (max == min) {
        h = s = 0.0;
    } else {
        float d = max - min;
        s = l > 0.5 ? d / (2.0 - max - min) : d / (max + min);
        if (max == color.r) {
            h = (color.g - color.b) / d + (color.g < color.b ? 6.0 : 0.0);
        } else if (max == color.g) {
            h = (color.b - color.r) / d + 2.0;
        } else {
            h = (color.r - color.g) / d + 4.0;
        }
        h /= 6.0;
    }

    return vec3(h, s, l);
}

float hue2rgb(float p, float q, float t) {
    if (t < 0.0) t += 1.0;
    if (t > 1.0) t -= 1.0;
    if (t < 1.0 / 6.0) return p + (q - p) * 6.0 * t;
    if (t < 1.0 / 2.0) return q;
    if (t < 2.0 / 3.0) return p + (q - p) * (2.0 / 3.0 - t) * 6.0;
    return p;
}

vec3 hsl2rgb(vec3 hsl) {
    float r, g, b;

    if (hsl.y == 0.0) {
        r = g = b = hsl.z;// achromatic
    } else {
        float q = hsl.z < 0.5 ? hsl.z * (1.0 + hsl.y) : hsl.z + hsl.y - hsl.z * hsl.y;
        float p = 2.0 * hsl.z - q;
        r = hue2rgb(p, q, hsl.x + 1.0 / 3.0);
        g = hue2rgb(p, q, hsl.x);
        b = hue2rgb(p, q, hsl.x - 1.0 / 3.0);
    }

    return vec3(r, g, b);
}

void main() {

    vec4 color = texture(uMainTex, v_originTexCoord);

    // Convert RGB to HSL
    vec3 hsl = rgb2hsl(color.rgb);

    hsl.x = mod(hsl.x + hsb.x, 1.0);// Adjust hue and wrap around
    hsl.y = clamp(hsl.y * hsb.y, 0.0, 1.0);// Adjust saturation
    hsl.z = clamp(hsl.z * hsb.z, 0.0, 1.0);// Adjust brightness (changed to multiplication)

    // Convert HSL back to RGB
    vec3 rgb = hsl2rgb(hsl);

    fragColor = vec4(rgb, color.a);
}