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

#version 450

layout (constant_id = 0) const int group = 0;
layout (constant_id = 1) const int bugihfa = 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 { sfpvec4 bottom_blob_data[]; };
layout (binding = 1) writeonly buffer top_blob { sfpvec4 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;

    int group;
} 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;

    const int channels_g = psc(c) * 4 / psc(group);

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

    ivec4 z4 = (gz4 % psc(group)) * channels_g + (gz4 / psc(group));

    ivec4 v_offset = (z4 / 4) * psc(cstep) + gy * psc(w) + gx;

    // v = v4[lane]

    afpvec4 vr = buffer_ld4(bottom_blob_data, v_offset.r);
    afpvec4 vg = buffer_ld4(bottom_blob_data, v_offset.g);
    afpvec4 vb = buffer_ld4(bottom_blob_data, v_offset.b);
    afpvec4 va = buffer_ld4(bottom_blob_data, v_offset.a);

    ivec4 lane4 = z4 % 4;

    afpvec4 v;
#if NCNN_fp16_arithmetic
    if (bugihfa == 1)
    {
        if (lane4.r == 0) v.r = vr.r;
        if (lane4.r == 1) v.r = vr.g;
        if (lane4.r == 2) v.r = vr.b;
        if (lane4.r == 3) v.r = vr.a;
        if (lane4.g == 0) v.g = vg.r;
        if (lane4.g == 1) v.g = vg.g;
        if (lane4.g == 2) v.g = vg.b;
        if (lane4.g == 3) v.g = vg.a;
        if (lane4.b == 0) v.b = vb.r;
        if (lane4.b == 1) v.b = vb.g;
        if (lane4.b == 2) v.b = vb.b;
        if (lane4.b == 3) v.b = vb.a;
        if (lane4.a == 0) v.a = va.r;
        if (lane4.a == 1) v.a = va.g;
        if (lane4.a == 2) v.a = va.b;
        if (lane4.a == 3) v.a = va.a;
    }
    else
#endif
    {
        v = afpvec4(vr[lane4.r], vg[lane4.g], vb[lane4.b], va[lane4.a]);
    }

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

    buffer_st4(top_blob_data, gi, v);
}
