// MaterialLibrary.cpp: implementation of the CMaterialLibrary class.
//
//////////////////////////////////////////////////////////////////////

#include "MaterialLibrary.h"

//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////



CMaterialLibrary::CMaterialLibrary()
{

}

CMaterialLibrary::~CMaterialLibrary()
{
}

DWORD CMaterialLibrary::Lookup(CMaxMaterial material)
{
	int nIndex = -1;

	CMaxMaterial* pMaterial = (CMaxMaterial*) m_pBuffers;
	for (int i=0; i<m_nCounts; i++)
	{
		if (!strcmp(lpMaterial->GetName(), pMaterial->GetName()))
		{
			nIndex = i;
			break;
		}

		pMaterial ++;
	}

	if (nIndex == -1)
	{
		// count material
		nIndex = m_nCounts;
		m_nCounts ++;

		m_pBuffer = (LPMATERIAL) realloc( m_pMaterialList, sizeof( MATERIAL ) * m_iNumMaterials );
		if ( !m_pMaterialList )
			return -1;

		// Copy Material
		LPMATERIAL pMaterial = m_pMaterialList + iMaterialIndex;

		strcpy( pMaterial->szName, lpMaterial->szName );

		pMaterial->diffuse.r = lpMaterial->diffuse.r;
		pMaterial->diffuse.g = lpMaterial->diffuse.g;
		pMaterial->diffuse.b = lpMaterial->diffuse.b;
		pMaterial->diffuse.a = 1.0f;

		pMaterial->ambient.r = lpMaterial->ambient.r;
		pMaterial->ambient.g = lpMaterial->ambient.g;
		pMaterial->ambient.b = lpMaterial->ambient.b;
		pMaterial->ambient.a = 1.0f;

		pMaterial->specular.r = lpMaterial->specular.r;  
		pMaterial->specular.g = lpMaterial->specular.g;
		pMaterial->specular.b = lpMaterial->specular.b; 
		pMaterial->specular.a = 1.0f;

		pMaterial->shininess = lpMaterial->shininess;
		
		strcpy( pMaterial->szBitmapName, lpMaterial->szBitmapName );
	}

	return iMaterialIndex;
}

void CMaterialLibrary::Destroy()
{
	if (m_pBuffers)
	{
		free(m_pBuffers);
		m_pBuffers = NULL;
	}

	m_nCounts = 0;
}
