#[compute]
#version 450

// Invocations in the (x, y, z) dimension
layout(local_size_x = 8, local_size_y = 8, local_size_z = 1) in;

// Our textures.
layout(r32f, set = 0, binding = 0) uniform restrict readonly image2D current_image;
layout(r32f, set = 1, binding = 0) uniform restrict writeonly image2D output_image;

// PushConstants
layout(push_constant, std430) uniform Params {
    ivec2 texture_size;
    float decay_factor;
    float dissipation_factor;
} params;

float get_dissipation_from(ivec2 uv) {
    float v = imageLoad(current_image, uv).r;
    // return v * params.dissipation_factor;
    return v;
}

ivec2 loop_position(ivec2 pos) {
    return pos % params.texture_size;
}

// The code we want to execute in each invocation
void main() {

    ivec2 uv = ivec2(gl_GlobalInvocationID.xy);

    float current_sum = 0.0;
    for (int i = -1; i <= 1; i++) {
        for (int j = -1; j <= 1; j++) {
            ivec2 kuv = loop_position(uv + ivec2(i,j));
            current_sum += get_dissipation_from(kuv);
        }
    }
    // ivec2 up_uv = loop_position(uv - ivec2(0, 1));
    // ivec2 down_uv = loop_position(uv + ivec2(0, 1));
    // ivec2 left_uv = loop_position(uv - ivec2(1, 0));
    // ivec2 right_uv = loop_position(uv + ivec2(1, 0));


    // Kill very old trails completely
    // if (new_v < 0.001) {
    //     new_v = 0;
    // }

    // new_v = clamp(new_v, 0, 1);

    // This is good when not using trail for showind as is.
    // https://github.com/Bleuje/physarum-36p/blob/main/bin/data/shaders/computeshader_deposit.glsl
    current_sum = current_sum / pow(3.0, 2.0);

    vec4 result = vec4(vec3(current_sum), 1.0);
    imageStore(output_image, uv, result);


}
