/*
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at https://mozilla.org/MPL/2.0/.
 */

#include "UniformBuffer.hpp"
#include "ManagedBuffer.hpp"
#include "ResourceManager.hpp"
#include "Vulkan/VulkanDrawContext.hpp"
#include "Vulkan/Scene/VulkanShader.hpp"

namespace OpenVulkano::Vulkan
{
	void UniformBuffer::Init(ManagedBuffer::Ptr buffer, uint32_t frameOffset, uint32_t frameSize, vk::DescriptorSetLayout* descriptorSetLayout, const DescriptorSetLayoutBinding& binding, uint32_t setId)
	{
		m_buffer = std::move(buffer);
		m_frameOffset = frameOffset;

		const vk::DescriptorSetAllocateInfo descSetAllocInfo = { ResourceManager::INSTANCE->descriptorPool, 1, descriptorSetLayout };
		m_descriptorSet = m_buffer->allocation->device.allocateDescriptorSets(descSetAllocInfo)[0];
		vk::DescriptorBufferInfo bufferInfo = { m_buffer->buffer, 0, frameSize };
		vk::WriteDescriptorSet writeDescriptorSet = { m_descriptorSet, binding.bindingId, 0, 1 };
		writeDescriptorSet.descriptorType = static_cast<vk::DescriptorType>(binding.descriptorType);
		writeDescriptorSet.pBufferInfo = &bufferInfo;
		m_buffer->allocation->device.updateDescriptorSets(1, &writeDescriptorSet, 0, nullptr);
		m_setOffset = setId;
		m_dynamic = binding.descriptorType == DescriptorSetLayoutBinding::TYPE_UNIFORM_BUFFER_DYNAMIC || binding.descriptorType == DescriptorSetLayoutBinding::TYPE_STORAGE_BUFFER_DYNAMIC;
	}

	void UniformBuffer::Close()
	{ //TODO handle this better
		m_buffer->allocation->device.freeDescriptorSets(ResourceManager::INSTANCE->descriptorPool, 1, &m_descriptorSet);
		m_buffer = nullptr;
	}

	void UniformBuffer::Record(VulkanDrawContext* drawContext)
	{
		uint32_t frameOffset = m_frameOffset * drawContext->currentImageId;
		drawContext->commandBuffer.bindDescriptorSets(vk::PipelineBindPoint::eGraphics, drawContext->GetShader()->pipelineLayout, m_setOffset, m_setCount, &m_descriptorSet, (m_dynamic) ? 1 : 0, &frameOffset);
	}

	void UniformBuffer::Update(const void* data, uint32_t size, uint32_t bufferId) const
	{
		m_buffer->Copy(data, size, m_frameOffset * bufferId);
	}
}