#include "SplitMeshNode.h"

bool SplitMeshNode::Initialise()
{
	bool currentStatus = true;

	_resourceManager = DirectXFramework::GetDXFramework()->GetResourceManager();
	_renderer = dynamic_pointer_cast<SubMeshRenderer>(_resourceManager->GetRenderer(L"SMR"));
	_mesh = _resourceManager->GetMesh(_modelName);
	if (_mesh == nullptr)
	{
		currentStatus = false;
	}
	else
	{			
		Add(AddMeshNode(_mesh->GetRootNode()));
	}

	if (currentStatus)
	{
		currentStatus = SceneGraph::Initialise();
	}

	if (currentStatus)
	{
		currentStatus = _renderer->Initialise();
	}

	return currentStatus;
}

void SplitMeshNode::Render(void)
{
	_renderer->SetRootChildren(GetChildren());
	_renderer->SetWorldTransformation(XMLoadFloat4x4(&_combinedWorldTransformation));
	_renderer->SetAmbientLight(DirectXFramework::GetDXFramework()->GetGlobalLighting()->GetAmbientLight());
	_renderer->SetDirectionalLight(DirectXFramework::GetDXFramework()->GetGlobalLighting()->GetDirectionalLightDirection(), DirectXFramework::GetDXFramework()->GetGlobalLighting()->GetDirectionalLightColor());
	_renderer->Render();
}

void SplitMeshNode::Shutdown(void)
{	
	_resourceManager->ReleaseMesh(_modelName);
	SceneGraph::Shutdown();
}

SceneNodePointer SplitMeshNode::AddMeshNode(shared_ptr<Node> node)
{
	unsigned int subMeshCount = (unsigned int)node->GetMeshCount();
	SceneNodePointer currentNodeGraph = make_shared<SceneGraph>(node->GetName());

	/*string nameString;
	for (char x : node->GetName())
	{
		nameString += x;
	}
	
	fileOut << string(depth, '-') + " " + nameString << endl;*/

	// Loop through all submeshes in the mesh
	for (unsigned int i = 0; i < subMeshCount; i++)
	{
		unsigned int meshIndex = node->GetMesh(i);
		shared_ptr<SubMesh> subMesh = _mesh->GetSubMesh(meshIndex);
		shared_ptr<Material> material = subMesh->GetMaterial();
		float opacity = material->GetOpacity();
		bool transparent = false;
		if (opacity < 1.0f)
		{
			transparent = true;
		}
		shared_ptr<SubMeshNode> subNode = make_shared<SubMeshNode>(node->GetName() + L"_" + to_wstring(i), subMesh, transparent);			
		currentNodeGraph->Add(subNode);
	}

	// Render the children
	unsigned int childrenCount = (unsigned int)node->GetChildrenCount();
	// Loop through all submeshes in the mesh, rendering them
	for (unsigned int i = 0; i < childrenCount; i++)
	{
		currentNodeGraph->Add(AddMeshNode(node->GetChild(i)));
	}

	return currentNodeGraph;
}