#include "MLRHeaders.hpp"

//#############################################################################
//###### MLRIndexedTriMesh with color but no lighting one texture layer  ######
//#############################################################################

MLR_I_L_DT_TMesh::ClassData*
	MLR_I_L_DT_TMesh::DefaultData = NULL;

Stuff::DynamicArrayOf<ColorType>
	*MLR_I_L_DT_TMesh::litColors = NULL;

HGOSHEAP
	MLR_I_L_DT_TMesh::PrimitiveHeap = NULL;

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
void
	MLR_I_L_DT_TMesh::InitializeClass()
{
	Verify(!PrimitiveHeap);
	PrimitiveHeap = gos_CreateMemoryHeap("MLR_I_L_DT_TMesh", 0, MidLevelRenderer::PrimitiveHeap);
	Check_Pointer(PrimitiveHeap);

	Verify(!DefaultData);
	Verify(gos_GetCurrentHeap() == StaticHeap);
	DefaultData =
		new ClassData(
			MLR_I_L_DT_TMeshClassID,
			"MidLevelRenderer::MLR_I_L_DT_TMesh",
			MLR_I_C_DT_TMesh::DefaultData,
			(MLRPrimitiveBase::Factory)&Make
		);
	Register_Object(DefaultData);

	Verify(!litColors);
	litColors = new DynamicArrayOf<ColorType>(Limits::Max_Number_Vertices_Per_Mesh);
	Check_Object(litColors);
}

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
void
	MLR_I_L_DT_TMesh::TerminateClass()
{
	Check_Object(litColors);
	delete litColors;
	litColors = NULL;

	Unregister_Object(DefaultData);
	delete DefaultData;
	DefaultData = NULL;

	Check_Pointer(PrimitiveHeap);
	gos_DestroyMemoryHeap(PrimitiveHeap);
	PrimitiveHeap = NULL;
}

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
MLR_I_L_DT_TMesh::MLR_I_L_DT_TMesh(
	ClassData *class_data,
	MemoryStream *stream,
	int version
):
	MLR_I_C_DT_TMesh(class_data, stream, version)
{
	Check_Pointer(this);
	Check_Pointer(stream);

	switch(version)
	{
		case 1:
		case 2:
		{
			STOP(("This class got created only after version 2 !"));
		}
		break;
		default:
		{
			MemoryStreamIO_Read(stream, &normals);

			if (normals.GetLength()>Limits::Max_Number_Vertices_Per_Mesh)
			{
				normals.AssignData(normals.GetData(), Limits::Max_Number_Vertices_Per_Mesh);
			}
		}
		break;
	}
}

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
MLR_I_L_DT_TMesh::MLR_I_L_DT_TMesh(ClassData *class_data):
	MLR_I_C_DT_TMesh(class_data)
{
	Check_Pointer(this);
}

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
MLR_I_L_DT_TMesh::~MLR_I_L_DT_TMesh()
{
	Check_Object(this);
}

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
MLR_I_L_DT_TMesh*
	MLR_I_L_DT_TMesh::Make(
		MemoryStream *stream,
		int version
	)
{
	Check_Object(stream);

	gos_PushCurrentHeap(PrimitiveHeap);
	MLR_I_L_DT_TMesh *mesh = new MLR_I_L_DT_TMesh(DefaultData, stream, version);
	gos_PopCurrentHeap();

	return mesh;
}

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
void
	MLR_I_L_DT_TMesh::Save(MemoryStream *stream)
{
	Check_Object(this);
	Check_Object(stream);

	MLR_I_C_DT_TMesh::Save(stream);

	MemoryStreamIO_Write(stream, &normals);
}

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
bool
	MLR_I_L_DT_TMesh::Copy(MLR_I_L_DT_PMesh *pMesh)
{
	Check_Pointer(this);
	Check_Object(pMesh);

	int len;
	const Vector3D *_normals;

	MLR_I_C_DT_TMesh::Copy(pMesh);

	if(pMesh->dataStore!=NULL && pMesh->dataStore->normals.GetLength()>0)
	{
		pMesh->GetNormalData(&_normals, &len);
		dataStore->normals.SetLength(len);
		Mem_Copy(dataStore->normals.GetData(), _normals, len*sizeof(Vector3D), dataStore->normals.GetSize());
		SetNormalData(dataStore->normals.GetData(), len);
	}
	else
	{
		pMesh->GetNormalData(&_normals, &len);
		SetNormalData(_normals, len);
	}

	return true;
}

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
void
	MLR_I_L_DT_TMesh::SetNormalData(
		const Vector3D *data,
		int dataSize
	)
{
	Check_Object(this);
	if(dataSize==0)
	{
		normals.AssignData(NULL, 0);
		return;
	}

	Check_Pointer(data);

	Verify(coords.GetLength() == 0 || dataSize == coords.GetLength());
	Verify(colors.GetLength() == 0 || dataSize == colors.GetLength());
	Verify(texCoords.GetLength() == 0 || 2*dataSize == texCoords.GetLength());

	normals.AssignData(data, dataSize);
}

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
void
	MLR_I_L_DT_TMesh::GetNormalData(
		const Vector3D **data,
		int *dataSize
	)
{
	Check_Object(this); 
	*data = normals.GetData();
	*dataSize = normals.GetLength();
}

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
void
	MLR_I_L_DT_TMesh::SetColorData(
		const ColorType *data,
		int dataSize
	)
{
	Check_Object(this); 
	Check_Pointer(data);

	Verify(coords.GetLength() == 0 || dataSize == coords.GetLength());
	Verify(texCoords.GetLength() == 0 || 2*dataSize == texCoords.GetLength());

	colors.AssignData(data, dataSize);
}

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
void
	MLR_I_L_DT_TMesh::TestInstance() const
{
	Verify(IsDerivedFrom(DefaultData));
}

extern DWORD gEnableTextureSort, gEnableAlphaSort;

#define I_SAY_YES_TO_DUAL_TEXTURES
#define I_SAY_YES_TO_COLOR
#define I_SAY_YES_TO_LIGHTING

#define CLASSNAME MLR_I_L_DT_TMesh
#define CLASSNAMENOCOLOR MLR_I_DT_TMesh

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//	This include contains follwing functions:
//	void MLR_I_L_DT_TMesh::TransformNoClip(Matrix4D*, GOSVertexPool*);
//	int MLR_I_L_DT_TMesh::Clip(MLRClippingState, GOSVertexPool*);
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

#include <MLR\MLRTriangleClipping.hpp>

#undef I_SAY_YES_TO_DUAL_TEXTURES
#undef I_SAY_YES_TO_COLOR
#undef I_SAY_YES_TO_LIGHTING

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//	This include contains follwing functions:
//	void	Lighting (MLRLight**, int nrLights);
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

#include <MLR\MLRTriangleLighting.hpp>
#undef CLASSNAME
#undef CLASSNAMENOCOLOR

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
MLRShape*
	MidLevelRenderer::CreateIndexedTriIcosahedron_Color_Lit_2Tex(
		IcoInfo& icoInfo,
		MLRState *state,
		MLRState *state2
	)
{
	gos_PushCurrentHeap(ShapeHeap);
	MLRShape *ret = new MLRShape(20);
	Register_Object(ret);
	gos_PopCurrentHeap();

	gos_PushCurrentHeap(PrimitiveHeap);
	int i, j, k;
	long    nrTri = (long) ceil (icoInfo.all * pow (4, icoInfo.depth));
	Point3D v[3];

	if(3*nrTri >= Limits::Max_Number_Vertices_Per_Mesh)
	{
		nrTri = Limits::Max_Number_Vertices_Per_Mesh/3;
	}

	int uniquePoints = 0;
	for (k=0;k<20;k++)
	{
		triDrawn = 0;
		MLR_I_L_DT_TMesh *mesh = new MLR_I_L_DT_TMesh();
		Register_Object(mesh);

		DynamicArrayOf<Point3D> *coords = &mesh->dataStore->coords;
		Check_Object(coords);
		coords->SetLength(nrTri*3);

		DynamicArrayOf<BYTE> *index = &mesh->dataStore->index;
		Check_Object(index);
		index->SetLength(nrTri*3);

		DynamicArrayOf<Vector2DScalar> *texCoords = &mesh->dataStore->texCoords;
		Check_Object(texCoords);
		texCoords->SetLength(2*nrTri*3);

		DynamicArrayOf<ColorType> *colors = &mesh->dataStore->colors;
		Check_Object(colors);
		colors->SetLength(nrTri*3);

		DynamicArrayOf<Vector3D> *normals = &mesh->dataStore->normals;
		Check_Object(normals);
		normals->SetLength(nrTri*3);

// setup vertex position information
	    for (j=0;j<3;j++)
		{
			v[j].x = vdata[tindices[k][j]][0];
			v[j].y = vdata[tindices[k][j]][1];
			v[j].z = vdata[tindices[k][j]][2];
		}
		subdivide (coords->GetData(), v[0], v[1], v[2], icoInfo.depth, nrTri, icoInfo.radius);

		mesh->SetSubprimitiveLengths(NULL, nrTri);

		if(icoInfo.indexed==true)
		{
			uniquePoints = 1;
			Point3D *collapsedCoords = new Point3D [nrTri*3];
			Check_Pointer(collapsedCoords);

			collapsedCoords[0] = (*coords)[0];
			(*index)[0] = 0;

			for(i=1;i<nrTri*3;i++)
			{
				for(j=0;j<uniquePoints;j++)
				{
					if((*coords)[i] == collapsedCoords[j])
					{
						break;
					}
				}
				if(j==uniquePoints)
				{
					collapsedCoords[uniquePoints++] = (*coords)[i];
				}
				(*index)[i] = static_cast<BYTE>(j);
			}
			coords->AssignData(collapsedCoords, uniquePoints);
			mesh->SetCoordData(coords->GetData(), uniquePoints);
			Unregister_Pointer(collapsedCoords);
			delete [] collapsedCoords;
		
		}
		else
		{
			uniquePoints = nrTri*3;
			for(i=0;i<nrTri*3;i++)
			{
				(*index)[i] = static_cast<BYTE>(i);
			}
			mesh->SetCoordData(coords->GetData(), nrTri*3);
		}

		mesh->SetIndexData(index->GetData(), nrTri*3);

		mesh->FindFacePlanes();

		if(state == NULL)
		{
			for(i=0;i<2*uniquePoints;i++)
			{
				(*texCoords)[i] = Vector2DScalar(0.0f, 0.0f);
			}
		}
		else
		{
			state->SetMultiTextureMode(MLRState::MultiTextureLightmapMode);
			mesh->SetReferenceState(*state);
			state->SetMultiTextureMode(MLRState::MultiTextureOffMode);

			if(state->GetTextureHandle() > 0)
			{
				for(i=0;i<uniquePoints;i++)
				{
					(*texCoords)[i] = 
						Vector2DScalar(
							(1.0f + (*coords)[i].x)/2.0f,
							(1.0f + (*coords)[i].y)/2.0f
						);
					(*texCoords)[i+uniquePoints] = 
						Vector2DScalar(
							(1.0f + (*coords)[i].x)/2.0f,
							(1.0f + (*coords)[i].z)/2.0f
						);
				}
			}
			else
			{
				for(i=0;i<2*uniquePoints;i++)
				{
					(*texCoords)[i] = Vector2DScalar(0.0f, 0.0f);
				}
			}
		}
		mesh->SetTexCoordData(texCoords->GetData(), 2*uniquePoints);

		for(i=0;i<uniquePoints;i++)
		{
#if COLOR_AS_DWORD>0
			RGBAColor c(
				(1.0f + (*coords)[i].x)/2.0f,
				(1.0f + (*coords)[i].y)/2.0f,
				(1.0f + (*coords)[i].z)/2.0f,
				1.0f
			);
			(*colors)[i] = GOSCopyColor(&c);
#else
			(*colors)[i] = 
				RGBAColor(
					(1.0f + (*coords)[i].x)/2.0f,
					(1.0f + (*coords)[i].y)/2.0f,
					(1.0f + (*coords)[i].z)/2.0f,
					1.0f
				);
#endif
			(*normals)[i].Normalize((*coords)[i]);
		}
		mesh->SetNormalData(normals->GetData(), uniquePoints);
		mesh->SetColorData(colors->GetData(), uniquePoints);

		mesh->SetReferenceState(*state2, 1);

		ret->Add(mesh);
		mesh->DetachReference();
	}

	gos_PopCurrentHeap();
	return ret;
}