#version 450

layout(push_constant) uniform pc {
    mat4 model;
    mat4 view;
    mat4 proj;
} ubo;

#define MAX_INSTANCES 1024

struct InstanceData
{
    vec3 pos;
    vec3 rot;
    float scale;
    uint texture_id;
};

layout(binding = 0) uniform InstanceUniformBuffer {
    InstanceData instances[MAX_INSTANCES];
};

layout(location = 0) in vec3 inPosition;
layout(location = 1) in vec3 inColor;
layout(location = 2) in vec2 inTexCoord;

layout(location = 0) out vec3 fragColor;
layout(location = 1) out vec2 fragTexCoord;
layout(location = 2) out uint outInstanceTextureId;


void main()
{
    InstanceData instance = instances[gl_InstanceIndex];
    mat4 gRotMat;
    mat3 mx, my, mz;

    // rotate around x
    float s = sin(instance.rot.x + 0);
    float c = cos(instance.rot.x + 0);

    mx[0] = vec3(1, 0.0, 0.0);
    mx[1] = vec3(0, c, -s);
    mx[2] = vec3(0.0, s, c);

    // rotate around y
    s = sin(instance.rot.y + 0);
    c = cos(instance.rot.y + 0);

    my[0] = vec3(c, 0.0, s);
    my[1] = vec3(0.0, 1.0, 0.0);
    my[2] = vec3(-s, 0.0, c);

    // rot around z
    s = sin(instance.rot.z + 0);
    c = cos(instance.rot.z + 0);

    mz[0] = vec3(c, -s, 0.0);
    mz[1] = vec3(s, c, 0.0);
    mz[2] = vec3(0.0, 0.0, 1);

    mat3 rotMat = mz * my * mx;

    s = sin(instance.rot.y + 0);
    c = cos(instance.rot.y + 0);
    gRotMat[0] = vec4(c, 0.0, s, 0.0);
    gRotMat[1] = vec4(0.0, 1.0, 0.0, 0.0);
    gRotMat[2] = vec4(-s, 0.0, c, 0.0);
    gRotMat[3] = vec4(0.0, 0.0, 0.0, 1.0);

    vec4 locPos = vec4(inPosition.xyz * rotMat, 1.0);
    vec4 pos = vec4((locPos.xyz * instance.scale) + instance.pos, 1.0);

    gl_Position = ubo.proj * ubo.view * ubo.model * pos;

    fragColor = inColor;
    fragTexCoord = inTexCoord;
    outInstanceTextureId = instance.texture_id;
}
