#version 430

layout(binding=0, r32i) uniform iimage2D pardexFree;
layout(binding=1, r32i) uniform iimage2D pardexActive;
layout(binding=2, rgba32f) uniform image2D pardexAge;

layout(binding=0, offset=0) uniform atomic_uint ac_active;
layout(binding=1, offset=0) uniform atomic_uint ac_free;


uniform float partNum = 0.0;

ivec2 getTrip(int idt) {
    ivec2 triBufSize = imageSize(pardexFree);
    ivec2 trip;
    trip.y = idt/triBufSize.x;
    trip.x = idt-trip.y*triBufSize.x;
    return trip;
}

int getInd(ivec2 uvi) {
    return uvi.x+uvi.y*int(imageSize(pardexFree).x);
}

void main() {
    ivec2 uv = ivec2(gl_FragCoord.xy);

    ivec2 triBufSize = imageSize(pardexFree);
    int pid = uv.x+uv.y*triBufSize.x;

    if (pid >= partNum) { discard; return; }


    float age = imageLoad(pardexAge, uv).x;
    if (age <= 0.0) {
        // free
        uint c = atomicCounterIncrement(ac_free);
        imageStore(pardexFree, getTrip(int(c)), ivec4(getInd(uv)));
    } else {
        // active
        uint c = atomicCounterIncrement(ac_active);
        imageStore(pardexActive, getTrip(int(c)), ivec4(getInd(uv)+1));
    }

    discard; return;
}
