// Copyright 2019 Tencent
// SPDX-License-Identifier: BSD-3-Clause

#version 450

layout (constant_id = 0) const int ndim = 0;

#define shape_constant_id_offset 1
layout (constant_id = shape_constant_id_offset + 0) const int dims = 0;
layout (constant_id = shape_constant_id_offset + 1) const int w = 0;
layout (constant_id = shape_constant_id_offset + 2) const int h = 0;
layout (constant_id = shape_constant_id_offset + 3) const int d = 0;
layout (constant_id = shape_constant_id_offset + 4) const int c = 0;
layout (constant_id = shape_constant_id_offset + 5) const int cstep = 0;

layout (constant_id = shape_constant_id_offset + 6) const int outdims = 0;
layout (constant_id = shape_constant_id_offset + 7) const int outw = 0;
layout (constant_id = shape_constant_id_offset + 8) const int outh = 0;
layout (constant_id = shape_constant_id_offset + 9) const int outd = 0;
layout (constant_id = shape_constant_id_offset + 10) const int outc = 0;
layout (constant_id = shape_constant_id_offset + 11) const int outcstep = 0;

layout (binding = 0) readonly buffer bottom_blob { sfp bottom_blob_data[]; };
layout (binding = 1) writeonly buffer top_blob { sfp top_blob_data[]; };

layout (push_constant) uniform parameter
{
    int dims;
    int w;
    int h;
    int d;
    int c;
    int cstep;

    int outdims;
    int outw;
    int outh;
    int outd;
    int outc;
    int outcstep;
} p;

void main()
{
    int gx = int(gl_GlobalInvocationID.x);
    int gy = int(gl_GlobalInvocationID.y);
    int gz = int(gl_GlobalInvocationID.z);

    if (gx >= psc(outw) || gy >= psc(outh) * psc(outd) || gz >= psc(outc))
        return;

    int i;
    if (ndim == 1) i = gx;
    if (ndim == 2) i = gy * psc(outw) + gx;
    if (ndim == 3) i = gz * psc(outh) * psc(outw) + gy * psc(outw) + gx;
    if (ndim == 4) i = gz * psc(outd) * psc(outh) * psc(outw) + gy * psc(outw) + gx;

    int x;
    int y;
    int z;

    if (psc(dims) == 1)
    {
        z = 0;
        y = 0;
        x = i;
    }
    else if (psc(dims) == 2)
    {
        z = 0;
        y = i / psc(w);
        x = i % psc(w);
    }
    else if (psc(dims) == 3)
    {
        int size = psc(w) * psc(h);

        z = i / size;
        y = i % size / psc(w);
        x = i % size % psc(w);
    }
    else // if (psc(dims) == 4)
    {
        int size = psc(w) * psc(h) * psc(d);
        int dsize = psc(w) * psc(h);

        z = i / size;
        int yd = i % size / dsize;
        int yh = i % size % dsize / psc(w);
        x = i % size % dsize % psc(w);

        y = yd * psc(h) + yh;
    }

    int v_offset = z * psc(cstep) + y * psc(w) + x;

    int gi;
    if (ndim == 1) gi = gx;
    if (ndim == 2) gi = gy * psc(outw) + gx;
    if (ndim == 3 || ndim == 4) gi = gz * psc(outcstep) + gy * psc(outw) + gx;

    buffer_cp1(top_blob_data, gi, bottom_blob_data, v_offset);
}
