/*
 * 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 "Scene/SimpleDrawable.hpp"
#include "Scene/Material.hpp"
#include "Scene/UniformBuffer.hpp"
#include "VulkanGeometry.hpp"
#include "VulkanNode.hpp"
#include "Vulkan/VulkanDrawContext.hpp"
#include "Vulkan/Scene/VulkanUniformBuffer.hpp"
#include "VulkanTexture.hpp"

using namespace OpenVulkano::Scene;

namespace OpenVulkano::Vulkan
{
	void EncodeSimpleDrawable(Drawable* instance, Vulkan::VulkanDrawContext* drawContext)
	{
		SimpleDrawable* drawable = static_cast<SimpleDrawable*>(instance);
		Geometry* mesh = drawable->GetMesh();
		VulkanGeometry* renderGeo = static_cast<VulkanGeometry*>(mesh->renderGeo);
		if (!renderGeo) renderGeo = drawContext->renderer->GetResourceManager().PrepareGeometry(mesh);
		renderGeo->RecordBind(drawContext->commandBuffer);

		if (drawable->GetBuffer())
		{
			
			VulkanUniformBuffer* vkBuffer = static_cast<VulkanUniformBuffer*>(drawable->GetBuffer()->renderBuffer);
			if (!vkBuffer)
			{
				vkBuffer = drawContext->renderer->GetResourceManager().PrepareUniformBuffer(drawable->GetBuffer());
			}
			vkBuffer->Record(drawContext);
		}

		if (Material* material = drawable->GetMaterial())
		{
			if (Texture* texture = material->texture)
			{
				VulkanTexture* renderTexture = static_cast<VulkanTexture*>(texture->renderTexture);
				if (!renderTexture)
				{
					drawContext->renderer->GetResourceManager().PrepareMaterial(drawable->GetMaterial());
					renderTexture = static_cast<VulkanTexture*>(texture->renderTexture);
				}
				renderTexture->Record(drawContext);
			}
		}

		for(Node* node : instance->GetNodes())
		{
			if (!node->IsEnabled()) [[unlikely]] continue;
			drawContext->EncodeNode(node);
			renderGeo->RecordDraw(drawContext->commandBuffer);
		}
	}
}

namespace
{
	void* simpleDrawableVulkanEncoderReg = DrawEncoder::RegisterVulkanEncodeFunction<SimpleDrawable>(&OpenVulkano::Vulkan::EncodeSimpleDrawable);
}