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

#version 450

layout (constant_id = 0) const int stride = 0;
layout (constant_id = 1) const int mode = 0;

#define shape_constant_id_offset 2
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 c = 0;
layout (constant_id = shape_constant_id_offset + 4) const int cstep = 0;

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

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

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

    int outdims;
    int outw;
    int outh;
    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) || gz >= psc(outc))
        return;

    ivec4 gz4 = gz * 8 + ivec4(0, 1, 2, 3);
    ivec4 gzz4 = gz4 + 4;

    ivec4 z4;
    ivec4 zi4;
    ivec4 zz4;
    ivec4 zii4;
    if (mode == 0)
    {
        z4 = gz4 / (stride * stride);
        zi4 = gz4 % (stride * stride);
        zz4 = gzz4 / (stride * stride);
        zii4 = gzz4 % (stride * stride);
    }
    else // if (mode == 1)
    {
        z4 = gz4 % psc(c);
        zi4 = gz4 / psc(c);
        zz4 = gzz4 % psc(c);
        zii4 = gzz4 / psc(c);
    }
    ivec4 y4 = gy * stride + zi4 / stride;
    ivec4 x4 = gx * stride + zi4 % stride;
    ivec4 yy4 = gy * stride + zii4 / stride;
    ivec4 xx4 = gx * stride + zii4 % stride;

    ivec4 v_offset = z4 * psc(cstep) + y4 * psc(w) + x4;
    ivec4 vv_offset = zz4 * psc(cstep) + yy4 * psc(w) + xx4;

    int gi = gz * psc(outcstep) + gy * psc(outw) + gx;

    buffer_cp1to8(top_blob_data, gi, bottom_blob_data, v_offset, vv_offset);
}
