#version 460
#extension GL_GOOGLE_include_directive : enable
#include "ui-shared.glsl"

layout(push_constant) uniform PC {
    UIDispatchHeader hdr;
} pc;

layout(local_size_x = 8, local_size_y = 8, local_size_z = 1) in;

void main() {
    ivec2 screenPx;
    if (!uiResolveScreenPixel(pc.hdr, screenPx)) return;

    vec4 dst = imageLoad(uiImages[pc.hdr.outImage], screenPx);
    vec2 sp  = vec2(screenPx) + 0.5;

    for (uint i = 0u; i < pc.hdr.itemCount; ++i) {
        ImageItem it = LoadImageItem(pc.hdr.itemBuffer, i);

        vec2 lo = it.rect.xy;
        vec2 hi = it.rect.xy + it.rect.zw;
        if (sp.x < lo.x || sp.y < lo.y) continue;
        if (sp.x >= hi.x || sp.y >= hi.y) continue;

        vec2 t  = (sp - it.rect.xy) / it.rect.zw;
        vec2 uv = mix(it.uv.xy, it.uv.zw, t);

        uint texSlot  = it.slots.x;
        uint sampSlot = it.slots.y;

        vec4 sampled = texture(
            sampler2D(uiTextures[nonuniformEXT(texSlot)],
                      uiSamplers[nonuniformEXT(sampSlot)]),
            uv
        );
        vec4 src = sampled * it.tint;
        if (src.a <= 0.0) continue;
        dst = uiBlendOver(dst, src);
    }

    imageStore(uiImages[pc.hdr.outImage], screenPx, dst);
}
