#include <IndexedUnitCube/IndexedUnitCube.hpp>

std::shared_ptr<Vk::Buffer> IndexedUnitCube::m_stagingBuffer;
std::shared_ptr<Vk::Buffer> IndexedUnitCube::m_indexBuffer;

static uint16_t indexedUnitCubeIndices[] = {
    0, 1, 2,
    2, 3, 0,

    4, 1, 0,
    0, 5, 4,

    2, 6, 7,
    7, 3, 2,

    4, 5, 7,
    7, 6, 4,

    0, 3, 7,
    7, 5, 0,

    1, 4, 2,
    2, 4, 6,
};

void IndexedUnitCube::init(std::shared_ptr<Vk::Device> device, Vk::CommandBuffer &cmdbuf)
{
    m_stagingBuffer = std::make_shared<Vk::Buffer>(
        device,
        sizeof(indexedUnitCubeIndices),
        VK_BUFFER_USAGE_TRANSFER_SRC_BIT,
        VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT
    );

    m_indexBuffer = std::make_shared<Vk::Buffer>(
        device,
        sizeof(indexedUnitCubeIndices),
        VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_INDEX_BUFFER_BIT,
        VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT
    );

    std::memcpy(m_stagingBuffer->hostdata(), indexedUnitCubeIndices, sizeof(indexedUnitCubeIndices));

    cmdbuf.transitionBufferToTransferDst(*m_indexBuffer);
    cmdbuf.copyBuffer(*m_stagingBuffer, 0, *m_indexBuffer, 0, sizeof(indexedUnitCubeIndices));
    cmdbuf.transitionBufferToDraw(*m_indexBuffer);
}

void IndexedUnitCube::finalize()
{
    m_stagingBuffer = nullptr;
}

void IndexedUnitCube::draw(Vk::CommandBuffer &cmdbuf, uint32_t instanceCount)
{
    cmdbuf.bindIndexBuffer(*m_indexBuffer, 0, VK_INDEX_TYPE_UINT16);
    cmdbuf.drawIndexed(sizeof(indexedUnitCubeIndices)/sizeof(uint16_t), instanceCount, 0, 0, 0);
}