
#version 430 core
out vec4 FragColor;

layout (location=0) uniform sampler2D image;
layout (location=1) uniform sampler2D dither;
layout (location=2) uniform vec4 resolution;

void main()
{
    // dithering texture organization:
    // x = 0 -> Palette 256 RGB values
    // x = 1 -> 256 (16x16) dither level
    // x = 128+ 15 bit - 5R 5G 5B - R = base color index (0-255), G = second color index (0-255), B = third color index (0-255)

    vec4 color = texelFetch(image, ivec2(ivec2(gl_FragCoord.xy/resolution.x)*resolution.x), 0);
    ivec3 vcol = clamp(ivec3(color.xyz*32), 0, 31);
    vec4 idx = texelFetch(dither, ivec2(((vcol.y & 0x7) << 5) + vcol.z, 128+(vcol.x << 2) + (vcol.y >>3)), 0);
    vec4 colx = texelFetch(dither, ivec2(idx.x, 0), 0);
    vec4 coly = texelFetch(dither, ivec2(idx.y, 0), 0);
    vec4 colz = texelFetch(dither, ivec2(idx.z, 0), 0);

    vec3 dx = colx.xyz - color.xyz;
    vec3 dy = coly.xyz - color.xyz;
    vec3 dz = colz.xyz - color.xyz;

    colx.w = dot(dx, dx);
    coly.w = dot(dy, dy);
    colz.w = dot(dz, dz);

    vec4 color1, color2;

    color1 = colx;
    color2 = coly;


    // if (colx.w < coly.w) {
    //     if (coly.w < colz.w) {
    //         color1 = colx;
    //         color2 = coly;
    //     }
    //     else if (colz.w < colx.w) {
    //         color1 = colz;
    //         color2 = colx;
    //     }
    //     else {
    //         color1 = colx;
    //         color2 = colz;
    //     }
    // }
    // else { // coly.w < colx.w
    //     if (colx.w < colz.w) {
    //         color1 = coly;
    //         color2 = colx;
    //     } else if (colz.w < coly.w) {
    //         color1 = colz;
    //         color2 = coly;
    //     } else {
    //         color1 = coly;
    //         color2 = colz;
    //     }
    // }

    float threshold = color1.w / (color1.w + color2.w);
    ivec2 dither_coord = ivec2(gl_FragCoord.xy/resolution.x) % 16;
    vec4 newcolor = (texelFetch(dither, ivec2(dither_coord.x*16 + dither_coord.y, 1), 0).x >= threshold)?color1:color2;



    FragColor = newcolor;
}