/* -----------------------------------------------------------------------------
	GSFramework
	Copyright 2001-2013 Emmanuel Julien. All Rights Reserved.
----------------------------------------------------------------------------- */


		#include "core/shader_tree_convert_static_texture_block_to_dynamic.h"
		#include "core/shader_block.h"
		#include "core/shader_tree.h"
		#include "core/material.h"

		using namespace GS::Core;


//------------------------------------------------------------------------------
static void		RecurseAndConvertInputs(ShaderBlock *block, const Material &m)
{
	for (uint n = 0; n < block->GetInputCount(); ++n)
		if	(ShaderBlock *input = block->GetInput(n))
		{
			if	(input->type == ShaderBlock::TypeTexture)
			{
				// Seek a channel in the material using this texture.
				TextureShaderBlock *t = (TextureShaderBlock *)input;

				for (uint i = 0; i < Material::max_texture_stage; ++i)
					if	(m.texstage[n].t == t->texture)
					{
						// Got a match, replace static texture by a material texture reference to this slot.
						if	(MaterialTextureShaderBlock *new_block = new MaterialTextureShaderBlock(i))
						{
							new_block->pos = input->pos;
							block->SetInput(n, new_block);
							_safe_delete(input);
							break;
						}
					}

				// Texture block has no input, end here.
			}
			else
				RecurseAndConvertInputs(input, m);
		}
}
void			GS::Core::ConvertStaticToDynamicTextureBlocks(ShaderTree &tree, const Material &m)
{
	for (uint n = 0; n < ShaderTree::SinkInvalid; ++n)
		if	(tree.sink[n] != NULL)
			RecurseAndConvertInputs(tree.sink[n], m);
}
//------------------------------------------------------------------------------
