#version 330 core
in vec4 vertex_color;
out vec4 fragColor;

uniform float light_mode_hist;

uniform vec4 visible_hist;
uniform vec4 visible_hist2;
uniform vec4 visible_hist3;

uniform sampler2D tex;

float get_pdf(float channel) {
    return texture(tex, vec2(vertex_color.y, 1/64. + channel/32.)).x;
}

vec4 get_pdf4(float ch0) {
    return vec4(get_pdf(ch0), get_pdf(ch0+1.), get_pdf(ch0+2.), get_pdf(ch0+3.));
}

void main() {
    vec4 pdf = get_pdf4(0.);
    vec4 mask = visible_hist*0.7*step(1.-vertex_color.xxxx, pdf);

    // Implement alpha composite passes
    float lm = 1.-0.5*light_mode_hist;
    vec4 pix = vec4(lm, lm, 0., 1.) * mask.x;
    pix = vec4(0., 0.75*lm, lm, 1.) * mask.y + (1.-mask.y) * pix;
    pix = vec4(lm, 0., lm, 1.) * mask.z + (1.-mask.z) * pix;
    pix = vec4(0., 0.94*lm, 0.313*lm, 1.) * mask.w + (1.-mask.w) * pix;

    vec4 pdf2 = get_pdf4(4.);
    mask = visible_hist2*0.7*step(1.-vertex_color.xxxx, pdf2);
    pix = vec4(lm, 0.5*lm, 0., 1.) * mask.x + (1.-mask.x) * pix;
    pix = vec4(lm, 0., 0., 1.) * mask.y + (1.-mask.y) * pix;
    pix = vec4(0.75*lm, 0., lm, 1.) * mask.z + (1.-mask.z) * pix;
    pix = vec4(lm, lm, lm, 1.) * mask.w + (1.-mask.w) * pix;

    vec4 pdf3 = get_pdf4(8.);
    mask = visible_hist3*0.7*step(1.-vertex_color.xxxx, pdf3);
    pix = vec4(lm, 0.5*lm, 0., 1.) * mask.x + (1.-mask.x) * pix;
    pix = vec4(lm, 0., 0., 1.) * mask.y + (1.-mask.y) * pix;
    pix = vec4(0.75*lm, 0., lm, 1.) * mask.z + (1.-mask.z) * pix;
    pix = vec4(lm, lm, lm, 1.) * mask.w + (1.-mask.w) * pix;

    fragColor = pix;
}
