#include "core.fsh"
#include "pixel_codec.fsh"

uniform highp sampler2D texUnit; // PM: polygon mileages


#ifdef mileage_alpha_size_5
const int size = 5;
#endif

uniform float alphaMileages[size];
uniform lowp float alphaValues[size];

uniform lowp vec4 colors[10]; // 和RouteColorMaxSize保持一致
uniform float colorTransLength;

uniform lowp vec4 mainColor; // 默认颜色
uniform float useMainColor; // 是否使用默认颜色

uniform float alphaRatio;

uniform lowp vec4 viewport;
uniform highp float maxPM; // max polygon mileage

in highp vec2 uv_f;
flat in vec2 colorSecMileage;
flat in ivec4 colorFlags;

layout(location = 0) out vec4 fragColor;

void main()
{
    
    float mileage_f = uv_f.y;

    
    vec2 uv_pm = vec2(gl_FragCoord.xy - viewport.xy) / viewport.zw;
    vec4 frag_pm = texture(texUnit, uv_pm);
    if (frag_pm.x + frag_pm.y + frag_pm.z + frag_pm.w < 0.01) {
        discard;
    }
    
    float pm = DecodeFloatRGBA(frag_pm); // pm during [0.01, 0.99]
    highp float ori_pm = ((pm - 0.01) / 0.98) * maxPM;
    if (mileage_f < ori_pm) {
        discard;
    }
    
    // 颜色过渡
    bool useSingleColor = (useMainColor > 0.5);
    vec4 color = useSingleColor ? mainColor : colors[colorFlags.y];
    bool needTrans = !useSingleColor && colorFlags.x > 0;
    if (needTrans) {
        float transLength = min(colorTransLength, (colorSecMileage.y - colorSecMileage.x) * 0.5);

        float transMileage = mileage_f < colorSecMileage.x + transLength ? colorSecMileage.x : colorSecMileage.y;

        float ratio = smoothstep(transMileage - transLength, transMileage + transLength, mileage_f);

        if (mileage_f < colorSecMileage.x + transLength)
            color = mix(colors[colorFlags.w], color, ratio);
        else
            color = mix(color, colors[colorFlags.z], ratio);
    }
    
    
    int index = 0;
    for (int i = 0; i < size; ++i)
        if (mileage_f > alphaMileages[i] - 0.01)
            index = i;
    
    float mixAlpha = alphaValues[index];
    if(mixAlpha < -0.1) // 只有过渡区域会走到if分支里
    {
        float ratio = smoothstep(alphaMileages[index], alphaMileages[index + 1], mileage_f);
        mixAlpha = mix(alphaValues[index-1], alphaValues[index+1], ratio);
    }
    
    fragColor = vec4(color.xyz, color.w * mixAlpha * alphaRatio);
}

