#include "MLRHeaders.hpp"

extern DWORD gEnableLightMaps;

#define UV_TEST 0
#define SPEW_AWAY 0
//#define TOP_DOWN_ONLY

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

MLR_I_TMesh::ClassData*
	MLR_I_TMesh::DefaultData = NULL;
extern DynamicArrayOf<Vector2DScalar> *lightMapUVs;
extern DynamicArrayOf<Scalar> *lightMapSqFalloffs;

Stuff::DynamicArrayOf<BYTE>
	*MLR_I_TMesh::testList = NULL;

HGOSHEAP
	MLR_I_TMesh::PrimitiveHeap = NULL;

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

	Verify(!DefaultData);
	Verify(gos_GetCurrentHeap() == StaticHeap);
	DefaultData =
		new ClassData(
			MLR_I_TMeshClassID,
			"MidLevelRenderer::MLR_I_TMesh",
			MLRIndexedPrimitiveBase::DefaultData,
			(MLRPrimitiveBase::Factory)&Make
		);
	Register_Object(DefaultData);

	Verify(!testList);
	testList = new DynamicArrayOf<BYTE>(1024);
	Check_Object(testList);
}

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
void
	MLR_I_TMesh::TerminateClass()
{
	Check_Object(testList);
	delete testList;
	testList = NULL;

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

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

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
MLR_I_TMesh::MLR_I_TMesh(
	ClassData *class_data,
	MemoryStream *stream,
	int version
):
	MLRIndexedPrimitiveBase(class_data, stream, version)
{
	Check_Pointer(this);
	Check_Pointer(stream);
	Verify(temp_lengths.GetLength()==0);

	numOfTriangles = index.GetLength()/3;

	if(version<15)
	{
		facePlanes.SetLength(numOfTriangles);
		FindFacePlanes();
	}
	else
	{
		MemoryStreamIO_Read(stream, &facePlanes);
	}
}

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
MLR_I_TMesh::MLR_I_TMesh(ClassData *class_data):
	MLRIndexedPrimitiveBase(class_data)
{
	Check_Pointer(this);

	drawMode = SortData::TriIndexedList;
}

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

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

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

	return mesh;
}

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

	MLRIndexedPrimitiveBase::Save(stream);

	MemoryStreamIO_Write(stream, &facePlanes);
}

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

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
bool
	MLR_I_TMesh::Copy(MLR_I_PMesh *pMesh)
{
	Check_Object(this);
	Check_Object(pMesh);

	int len, len2;
	const BYTE *_subindex;
	const BYTE *_index;
	const Point3D *_coords;
	const Vector2DScalar *_texCoords;

	if(pMesh->dataStore!=NULL && pMesh->dataStore->coords.GetLength()>0)
	{
		pMesh->GetCoordData(&_coords, &len);
		dataStore->coords.SetLength(len);
		Mem_Copy(dataStore->coords.GetData(), _coords, len*sizeof(Point3D), dataStore->coords.GetSize());
		SetCoordData(dataStore->coords.GetData(), len);
	}
	else
	{
		pMesh->GetCoordData(&_coords, &len);
		SetCoordData(_coords, len);
	}

	pMesh->GetIndexData(&_index, &len);
	pMesh->GetSubprimitiveLengths(&_subindex, &len2);

	// Find number of indices first and allocate dataStore
	int i, j, k, l;
	for(i=0,k=0;i<len2;i++)
	{
		k += 3*(_subindex[i]-2);
	}		
	dataStore->index.SetLength(k);

	for(i=0,k=0,l=0;i<len2;i++)
	{
		for(j=2;j<_subindex[i];j++)
		{
			dataStore->index[k++] = _index[l];
			dataStore->index[k++] = _index[l+j-1];
			dataStore->index[k++] = _index[l+j];
		}
		l += _subindex[i];
	}
	SetIndexData(dataStore->index.GetData(), k);

	SetSubprimitiveLengths(NULL, k/3);

	facePlanes.SetLength(k/3);

	FindFacePlanes();

	
	if(pMesh->dataStore!=NULL && pMesh->dataStore->texCoords.GetLength()>0)
	{
		pMesh->GetTexCoordData(&_texCoords, &len);
		dataStore->texCoords.SetLength(len);
		Mem_Copy(dataStore->texCoords.GetData(), _texCoords, len*sizeof(Vector2DScalar), dataStore->texCoords.GetSize());
		SetTexCoordData(dataStore->texCoords.GetData(), len);
	}
	else
	{
		pMesh->GetTexCoordData(&_texCoords, &len);
		SetTexCoordData(_texCoords, len);
	}

	referenceState = pMesh->GetReferenceState();

	visibleIndexedVerticesKey = false;

	return true;
}

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
void
	MLR_I_TMesh::InitializeDrawPrimitive(BYTE vis, int parameter)
{
	MLRIndexedPrimitiveBase::InitializeDrawPrimitive(vis, parameter);

	if(parameter & 1)
	{
		ResetTestList();
	}
}

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
void
	MLR_I_TMesh::FindFacePlanes()
{
	Check_Object(this); 

	int i, j, numPrimitives = GetNumPrimitives();
	Vector3D v;

	Verify(index.GetLength() > 0);

	for(i=0,j=0;i<numPrimitives;++i,j+=3)
	{
		facePlanes[i].BuildPlane(
			coords[index[j]],
			coords[index[j+1]],
			coords[index[j+2]]
		);

		;
	}
}

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
int
	MLR_I_TMesh::FindBackFace(const Point3D& u, const Normal3D& n)
{
	Check_Object(this);

	MLR_RENDER("Backface::MLR_I_TMesh");
	Start_Timer(Find_Backface_Time);

	int ret = 0;
	BYTE *iPtr;
	Plane *p;

	if(numOfTriangles <= 0)
	{
		visible = 0;

		return 0;
	}

	p = &facePlanes[numOfTriangles-1];
	iPtr = testList->GetData();

	if(state.GetBackFaceMode() == MLRState::BackFaceOffMode)
	{
		ResetTestList();
		ret = 1;
	}
	else
	{
		memset(iPtr, 0, numOfTriangles);
		for(int i=numOfTriangles-1;i>=0;p--,i--)
		{
			if(p->GetDistanceTo(u)>= 0.0f)
			{
				iPtr[i] = (BYTE)(ret = 1);
			}
		}
	}

	visible = (BYTE)ret;

	FindVisibleVertices();

	Stop_Timer(Find_Backface_Time);

	return ret;
}

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
void
	MLR_I_TMesh::ResetTestList()
{
	int i, numPrimitives = GetNumPrimitives();
	BYTE *iPtr = testList->GetData();

	for(i=0;i<numPrimitives;i++,iPtr++)
	{
		*iPtr = 1;
	}

}

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
int
	MLR_I_TMesh::FindVisibleVertices()
{
	Check_Object(this);
	Verify(index.GetLength() > 0);

	int ret, i, j;
	const WORD *indices = reinterpret_cast<const WORD*>(index.GetData());

	for(i=0,j=0,ret=0;i<(numOfTriangles>>1);++i)
	{
		if((*testList)[i<<1] != 0)
		{
			(*visibleIndexedVertices)[(*(indices+j))&0xff] = 1;
			(*visibleIndexedVertices)[(*(indices+j))>>8] = 1;
			(*visibleIndexedVertices)[(*(indices+j+1))&0xff] = 1;
			ret = 1;
		}
		if((*testList)[(i<<1)+1] != 0)
		{
			(*visibleIndexedVertices)[(*(indices+j+1))>>8] = 1;
			(*visibleIndexedVertices)[(*(indices+j+2))&0xff] = 1;
			(*visibleIndexedVertices)[(*(indices+j+2))>>8] = 1;
			ret = 1;
		}
		j+=3;
	}

	if(numOfTriangles&1)
	{
		if((*testList)[numOfTriangles-1] != 0)
		{
			j <<= 1;
			(*visibleIndexedVertices)[index[j++]] = 1;
			(*visibleIndexedVertices)[index[j++]] = 1;
			(*visibleIndexedVertices)[index[j++]] = 1;
			ret = 1;
		}
	}

	visibleIndexedVerticesKey = true;

	return ret;
}

extern DWORD gEnableTextureSort, gEnableAlphaSort;

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
void
	MLR_I_TMesh::PaintMe(const ColorType *paintMe)
{
	Check_Object(this);

#if COLOR_AS_DWORD
	paintMeColorDW = *paintMe;
#else
	paintMeColorF = *paintMe;
	paintMeColorDW = GOSCopyColor(paintMe);
#endif
}

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/*
void
	MLR_I_TMesh::Transform(Matrix4D *mat)
{
	Check_Object(this);

	Verify(index.GetLength() > 0);
	int i, len = coords.GetLength();

	if(visibleIndexedVerticesKey == false)
	{
		FindVisibleVertices();
	}

	Stuff::Vector4D *v4d = transformedCoords.GetData();
	Stuff::Point3D *p3d = coords.GetData();
	MLRClippingState *cs = clipPerVertex.GetData();
	BYTE *viv = visibleIndexedVertices.GetData();

	for(i=0;i<len;i++,p3d++,v4d++,cs++,viv++)
	{
		if(*viv == 0)
		{
			continue;
		}
		
		v4d->Multiply(*p3d, *mat);
#ifdef LAB_ONLY
		Statistics::MLR_TransformedVertices++;
#endif

		cs->Clip4dVertex(v4d);
//
//--------------------------------------------------------
// I claims all vertices are in. lets check it. who knows
//--------------------------------------------------------
//
#ifdef LAB_ONLY
		if( (*cs)==0)
		{
#if defined(_ARMOR)
			if(ArmorLevel > 3)
			{
//
//--------------------------------------------------------
// I claims all vertices are in. lets check it. who knows
//--------------------------------------------------------
//
				Verify(v4d->x >= 0.0f && v4d->x <= v4d->w );
				Verify(v4d->y >= 0.0f && v4d->y <= v4d->w );
				Verify(v4d->z >= 0.0f && v4d->z <= v4d->w );
			}
#endif
			Statistics::MLR_NonClippedVertices++;
		}
		else
		{
			Statistics::MLR_ClippedVertices++;
		}
#endif
	}
}
*/

#undef I_SAY_YES_TO_DUAL_TEXTURES
#undef I_SAY_YES_TO_COLOR
#undef I_SAY_YES_TO_LIGHTING

#define CLASSNAME MLR_I_TMesh

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

#include <MLR\MLRTriangleClipping.hpp>

#undef CLASSNAME

//---------------------------------------------------------------------------
//
void
	MLR_I_TMesh::Lighting(MLRLight* const* lights, int nrLights, BYTE what)
{
	int i;
	MLRLightMap *lightMap;

	for(i=0;i<nrLights;i++)
	{
		if(lights[i]->GetIntensity() < Limits::LightThreshold)
		{
			continue;
		}

		lightMap = lights[i]->GetLightMap();

		if(lightMap!=NULL && (what&2))
		{
			MLR_RENDER("Lightmap Lighting::MLR_I_TMesh");
			Start_Timer(LightMap_Light_Time);
			LightMapLighting(lights[i]);
			Stop_Timer(LightMap_Light_Time);
		}
	}

}

//---------------------------------------------------------------------------
//
DWORD
	MLR_I_TMesh::CenterLighting(MLRLight* const* lights, int nrLights, BYTE what)
{
	int i;
	RGBAColor returnColor;

	if(nrLights==0)
	{
		returnColor = RGBAColor::White;
	}
	else
	{
		returnColor = RGBAColor(0.0f, 0.0f, 0.0f, 1.0f);

		for(i=0;i<nrLights;i++)
		{
			if(lights[i]->GetIntensity() < Limits::LightThreshold)
			{
				continue;
			}
			lights[i]->LightCenter(returnColor);
		}
	}

	return GOSCopyColor(&returnColor);
}

extern RGBAColor errorColor;
extern bool
	CheckForBigTriangles(DynamicArrayOf<Vector2DScalar> *lightMapUVs, int stride);

//---------------------------------------------------------------------------
//
void
	MLR_I_TMesh::LightMapLighting(MLRLight *light)
{
	int i, j, k, len = numOfTriangles;
	LinearMatrix4D matrix = LinearMatrix4D::Identity;
	Point3D lightPosInShape, hitPoint;
	UnitVector3D up, left, forward;
	bool lm;
	Scalar f, rhf, falloff = 1.0f, distance;

	MLRLightMap *lightMap = light->GetLightMap();

	if( (!lightMap) || (!gEnableLightMaps)  || lightMap->IsFull()==true)
	{
		return;
	}

	BYTE addedVertices = 0;
	BYTE addedIndicies = 0;

	Scalar bigUV = MLRState::GetMaxUV();
	int tooBig = 0;

	switch(light->GetLightType())
	{
		case MLRLight::PointLight:
		{
			Check_Object(lightMap);

			light->GetInShapePosition(lightPosInShape);

			for(i=0,j=0,k=0;i<len;i++,j += 3)
			{
				if((*testList)[i] == 0)
				{
					continue;
				}

				f = facePlanes[i].GetDistanceTo(lightPosInShape);
				
				lm = false;

				if(f>0.0f && Cast_Object(MLRInfiniteLightWithFalloff*, light)->GetFalloff(f, falloff) == true)
				{
					rhf = 1.0f/f;

					matrix = LinearMatrix4D::Identity;
					matrix.AlignLocalAxisToWorldVector(facePlanes[i].normal, Z_Axis, X_Axis, Y_Axis);
					matrix.GetLocalLeftInWorld(&left);
					matrix.GetLocalUpInWorld(&up);
					matrix.GetLocalForwardInWorld(&forward);
					Verify(Small_Enough(up*left));

		#if defined(_ARMOR)
					Scalar diff = forward*left;
					Verify(Small_Enough(diff));
					diff = up*forward;
					Verify(Small_Enough(diff));
		#endif

					Check_Object(&forward);
					hitPoint.Multiply(forward, -f);
					hitPoint+=lightPosInShape;

					tooBig = 0;
					for(k=0;k<3;k++)
					{
						Vector3D vec(coords[index[k+j]]);
						vec-=hitPoint;

						(*lightMapUVs)[k][0] = -(left*vec)*rhf;
						(*lightMapUVs)[k][1] = -(up*vec)*rhf;

						if(
							(*lightMapUVs)[k][0] >= -0.5f && (*lightMapUVs)[k][0] <= 0.5f &&
							(*lightMapUVs)[k][1] >= -0.5f && (*lightMapUVs)[k][1] <= 0.5f

						) 
						{
							lm = true;
						}

						if(
							bigUV > 0.0f &&
							(
								(*lightMapUVs)[k][0] < -bigUV || (*lightMapUVs)[k][0] > bigUV ||
								(*lightMapUVs)[k][1] < -bigUV || (*lightMapUVs)[k][1] > bigUV
							)
						) 
						{
							tooBig++;
						}
					}
				}
				else
				{
					continue;
				}

				if(tooBig==0 && (lm == true || CheckForBigTriangles(lightMapUVs, 3) == true))
				{
#if 0
					Vector3D vec(coords[index[j]]);
					SPEW(("micgaert", "\nvertex1 = %f,%f,%f", vec.x, vec.y, vec.z));
					vec = coords[index[j+1]];
					SPEW(("micgaert", "vertex2 = %f,%f,%f", vec.x, vec.y, vec.z));
					vec = coords[index[j+2]];
					SPEW(("micgaert", "vertex3 = %f,%f,%f", vec.x, vec.y, vec.z));
					vec = facePlanes[i].normal;
					SPEW(("micgaert", "normal = %f,%f,%f", vec.x, vec.y, vec.z));
					SPEW(("micgaert", "forward = %f,%f,%f", forward.x, forward.y, forward.z));
					SPEW(("micgaert", "distance = %f", f));
					SPEW(("micgaert", "light = %f,%f,%f", lightPosInShape.x, lightPosInShape.y, lightPosInShape.z));
					SPEW(("micgaert", "projection = %f,%f,%f", hitPoint.x, hitPoint.y, hitPoint.z));
#endif

					Scalar sq_falloff
						= falloff*falloff*light->GetIntensity();
					
					RGBAColor color;
					light->GetColor(color);

					color.red *= sq_falloff;
					color.green *= sq_falloff;
					color.blue *= sq_falloff;
					color.alpha = 1.0f;

					for(k=0;k<3;k++)
					{
						(*lightMapUVs)[k][0] += 0.5f;
						(*lightMapUVs)[k][1] += 0.5f;

						if(
							lightMap->AddIndex(addedIndicies++, addedVertices)==false ||
#if COLOR_AS_DWORD
							lightMap->AddVertex(addedVertices++, coords[index[k+j]], (*lightMapUVs)[k], GOSCopyColor(&color))==false
#else	//	COLOR_AS_DWORD
							lightMap->AddVertex(addedVertices++, coords[index[k+j]], (*lightMapUVs)[k], color)==false
#endif	//	COLOR_AS_DWORD
						)
						{
							return;
						}

						if(addedIndicies >= 252 && addedVertices > 0)
						{
							lightMap->AddMesh(referenceState.GetPriority()+1, addedVertices, addedIndicies);
							addedIndicies = 0;
							addedVertices = 0;
						}

		//				DEBUG_STREAM << k << " " << lightMapUVs[k][0] << " " << lightMapUVs[k][0] << "\n";
					}
				}
			}
		}
		break;
		case MLRLight::SpotLight:
		{
			int behindCount = 0, falloffCount = 0;

			Check_Object(lightMap);

			light->GetInShapePosition(matrix);
			lightPosInShape = matrix;

			Scalar tanSpeadAngle = Cast_Object(MLRSpotLight*, light)->GetTanSpreadAngle();

#ifndef TOP_DOWN_ONLY
			matrix.GetLocalLeftInWorld(&left);
			matrix.GetLocalUpInWorld(&up);
			matrix.GetLocalForwardInWorld(&forward);
#else
			forward = UnitVector3D(0.0f, -1.0f, 0.0);
			up = UnitVector3D(1.0f, 0.0f, 0.0);
			left = UnitVector3D(0.0f, 0.0f, 1.0);
#endif

			Verify(Small_Enough(up*left));

			for(i=0,j=0,k=0;i<len;i++,j += 3)
			{
				behindCount = 0;
				falloffCount = 0;

				if((*testList)[i] == 0)
				{
					continue;
				}

				lm = false;

				if(!facePlanes[i].IsSeenBy(lightPosInShape))
				{
					continue;
				}

#if SPEW_AWAY
				Scalar maxX, maxZ;
				Scalar minX, minZ;

				minX = maxX = coords[index[j]].x;
				minZ = maxZ = coords[index[j]].z;

				if(minX>coords[index[j+1]].x)
				{
					minX = coords[index[j+1]].x;
				}
				if(minX>coords[index[j+2]].x)
				{
					minX = coords[index[j+2]].x;
				}
				if(minZ>coords[index[j+1]].z)
				{
					minZ = coords[index[j+1]].z;
				}
				if(minX>coords[index[j+2]].z)
				{
					minZ = coords[index[j+2]].z;
				}
				if(maxX<coords[index[j+1]].x)
				{
					maxX = coords[index[j+1]].x;
				}
				if(maxX<coords[index[j+2]].x)
				{
					maxX = coords[index[j+2]].x;
				}
				if(maxZ<coords[index[j+1]].z)
				{
					maxZ = coords[index[j+1]].z;
				}
				if(maxX<coords[index[j+2]].z)
				{
					maxZ = coords[index[j+2]].z;
				}

				if(lightPosInShape.x > minX && lightPosInShape.x < maxX && lightPosInShape.z > minZ && lightPosInShape.z < maxZ)
				{
					SPEW(("micgaert", "On Target !!"));
				}
#endif

				tooBig = 0;
				for(k=0;k<3;k++)
				{
					Vector3D vec;
					Scalar oneOver;

					vec.Subtract(coords[index[k+j]], lightPosInShape);

#ifndef TOP_DOWN_ONLY
					distance = (vec*forward);
#else
					distance = -vec.y;
#endif

#if SPEW_AWAY
					SPEW(("micgaert", "vertex%d = %f,%f,%f", k, coords[index[k+j]].x, coords[index[k+j]].y, coords[index[k+j]].z));
					SPEW(("micgaert", "distance = %f", distance));
#endif
					if(distance > SMALL)
					{
						if(Cast_Object(MLRInfiniteLightWithFalloff*, light)->GetFalloff(distance, falloff) == false)
						{
							falloffCount++;
						}
						(*lightMapSqFalloffs)[k] = falloff*falloff*light->GetIntensity();

						oneOver
#if 0
							= 1.0f/(2.0f*distance*tanSpeadAngle);
#else
							= OneOverApproximate(2.0f*distance*tanSpeadAngle);
#endif
					}
					else
					{
						behindCount++;
						oneOver = 1.0f/50.0f;
						(*lightMapSqFalloffs)[k] = 0.0f;
#if SPEW_AWAY
						SPEW(("micgaert", "Behind"));
#endif
					}

#ifndef TOP_DOWN_ONLY
					(*lightMapUVs)[k][0] = (left*vec) * oneOver;
					(*lightMapUVs)[k][1] = -(up*vec) * oneOver;
#else
					(*lightMapUVs)[k][0] = vec.x * oneOver;
					(*lightMapUVs)[k][1] = -vec.z * oneOver;
#endif

#if SPEW_AWAY
					SPEW(("micgaert", "uv%d = %f,%f", k, (*lightMapUVs)[k][0], (*lightMapUVs)[k][1]));
#endif
					if(
						(*lightMapUVs)[k][0] >= -0.5f && (*lightMapUVs)[k][0] <= 0.5f &&
						(*lightMapUVs)[k][1] >= -0.5f && (*lightMapUVs)[k][1] <= 0.5f

					) 
					{
						lm = true;
					}
					if(
						bigUV > 0.0f &&
						(
							(*lightMapUVs)[k][0] < -bigUV || (*lightMapUVs)[k][0] > bigUV ||
							(*lightMapUVs)[k][1] < -bigUV || (*lightMapUVs)[k][1] > bigUV
							)

					) 
					{
						tooBig++;
					}
				}

				if(	
					tooBig == 0 
					&& behindCount < 3  
					&& falloffCount < 3 
 					&& ((lm == true)	|| CheckForBigTriangles(lightMapUVs, 3) == true)
				)
				{
					for(k=0;k<3;k++)
					{
						RGBAColor color;

						color.red = (*lightMapSqFalloffs)[k];
						color.green = (*lightMapSqFalloffs)[k];
						color.blue = (*lightMapSqFalloffs)[k];
						color.alpha = 1.0f;

						(*lightMapUVs)[k][0] += 0.5f;
						(*lightMapUVs)[k][1] += 0.5f;

						if(
							lightMap->AddIndex(addedIndicies++, addedVertices)==false ||
#if COLOR_AS_DWORD
							lightMap->AddVertex(addedVertices++, coords[index[k+j]], (*lightMapUVs)[k], GOSCopyColor(&color))==false
#else	//	COLOR_AS_DWORD
							lightMap->AddVertex(addedVertices++, coords[index[k+j]], (*lightMapUVs)[k], color)==false
#endif	//	COLOR_AS_DWORD
						)
						{
							return;
						}

						if(addedIndicies >= 252 && addedVertices > 0)
						{
							lightMap->AddMesh(referenceState.GetPriority()+1, addedVertices, addedIndicies);
							addedIndicies = 0;
							addedVertices = 0;
						}
					}
	#if SPEW_AWAY
					SPEW(("micgaert", "See the Light !"));
	#endif
				}
	#if SPEW_AWAY
				Vector3D vec = facePlanes[i].normal;
				SPEW(("micgaert", "normal = %f,%f,%f", vec.x, vec.y, vec.z));
				SPEW(("micgaert", "forward = %f,%f,%f", forward.x, forward.y, forward.z));
				SPEW(("micgaert", "left = %f,%f,%f", left.x, left.y, left.z));
				SPEW(("micgaert", "up = %f,%f,%f", up.x, up.y, up.z));
				SPEW(("micgaert", "light = %f,%f,%f\n", lightPosInShape.x, lightPosInShape.y, lightPosInShape.z));
	#endif
			}
		}
		break;
		case MLRLight::ProjectLight:
		{
			int behindCount = 0, falloffCount = 0;

			light->GetInShapePosition(lightPosInShape);

			MLRProjectLight *pLight = Cast_Object(MLRProjectLight*, light);
			static Point3D texUV[Limits::Max_Number_Vertices_Per_Mesh];

			Matrix4D m4;
			m4.Multiply(pLight->GetInversMatrix(), pLight->GetProjectMatrix());

			Vector4D v4;

			for(i=0;i<coords.GetLength();i++)
			{
				v4.Multiply(coords[i], m4);
				Scalar rhw = 1.0f/v4.w;

				texUV[i].x = v4.x*rhw;
				texUV[i].y = v4.y*rhw;
				texUV[i].z = v4.z*rhw;
			}

			for(i=0,j=0,k=0;i<len;i++,j += 3)
			{
				behindCount = 0;
				falloffCount = 0;

				if((*testList)[i] == 0)
				{
					continue;
				}

				lm = false;

				if(!facePlanes[i].IsSeenBy(lightPosInShape))
				{
					continue;
				}

				int tooBig = 0;
				for(k=0;k<3;k++)
				{
					(*lightMapUVs)[k][0] = texUV[index[k+j]][0];
					(*lightMapUVs)[k][1] = texUV[index[k+j]][1];

/*					if(
//						(*lightMapUVs)[k][0] >= -0.5f && (*lightMapUVs)[k][0] <= 0.5f &&
//						(*lightMapUVs)[k][1] >= -0.5f && (*lightMapUVs)[k][1] <= 0.5f
//					) 
					{
						lm = true;
					}
					if(
						(*lightMapUVs)[k][0] < -1.5f || (*lightMapUVs)[k][0] > 1.5f ||
						(*lightMapUVs)[k][1] < -1.5f && (*lightMapUVs)[k][1] > 1.5f

					) 
					{
						tooBig++;
					}
*/
					lm = true;
				}

				if(	
					tooBig == 0 &&
					behindCount == 0 && 
					falloffCount < 3 &&
					(lm == true || CheckForBigTriangles(lightMapUVs, 3) == true)
					)
				{
					for(k=0;k<3;k++)
					{
//						(*lightMapUVs)[k][0] += 0.5f;
//						(*lightMapUVs)[k][1] += 0.5f;

						if(
							lightMap->AddIndex(addedIndicies++, addedVertices)==false ||
#if COLOR_AS_DWORD
							lightMap->AddVertex(addedVertices++, coords[index[k+j]], (*lightMapUVs)[k], GOSCopyColor(&RGBAColor::White))==false
#else	//	COLOR_AS_DWORD
							lightMap->AddVertex(addedVertices++, coords[index[k+j]], (*lightMapUVs)[k], RGBAColor::White)==false
#endif	//	COLOR_AS_DWORD
						)
						{
							return;
						}

						if(addedIndicies >= 252 && addedVertices > 0)
						{
							lightMap->AddMesh(referenceState.GetPriority()+1, addedVertices, addedIndicies);
							addedIndicies = 0;
							addedVertices = 0;
						}
					}
				}
			}
		}
		break;
		case MLRLight::ShadowLight:
		break;
		default:
			STOP(("MLR_I_TMesh::LightMapLighting: What you want me to do ?"));
		break;
	}

	if(addedIndicies && addedVertices)
	{
		lightMap->AddMesh(referenceState.GetPriority()+1, addedVertices, addedIndicies);
	}
}


//---------------------------------------------------------------------------
//
MLRPrimitiveBase*
	MLR_I_TMesh::HurtMe(const Stuff::LinearMatrix4D& matrix, Stuff::Scalar radius, MLRTexture *tex)
{
	Check_Object(this); 

	if(referenceState.GetPriority()!=MLRState::DefaultPriority)
	{
		return NULL;
	}

	int behindCount = 0, falloffCount = 0;
	int i, j, k, nrOfPoints = 0;
	Point3D lightPosInShape, hitPoint;
	UnitVector3D up, left, forward;
	bool lm;
	Scalar distance;

	lightPosInShape = matrix;

	matrix.GetLocalLeftInWorld(&left);
	matrix.GetLocalUpInWorld(&up);
	matrix.GetLocalForwardInWorld(&forward);

	Verify(Small_Enough(up*left));

	Scalar oneOver = 1.0f/radius;
	Scalar bigUV = MLRState::GetMaxUV();

	for(i=0,j=0,k=0;i<numOfTriangles;i++,j += 3)
	{
		behindCount = 0;
		falloffCount = 0;

		lm = false;

		if(!facePlanes[i].IsSeenBy(lightPosInShape))
		{
			continue;
		}

		int	tooBig = 0;
		for(k=0;k<3;k++)
		{
			Vector3D vec;

			vec.Subtract(coords[index[k+j]], lightPosInShape);

			distance = (vec*forward);

			if(distance > SMALL)
			{

				(*lightMapUVs)[k][0] = (left*vec) * oneOver;
				(*lightMapUVs)[k][1] = -(up*vec) * oneOver;

#if SPEW_AWAY
				SPEW(("micgaert", "uv%d = %f,%f", k, (*lightMapUVs)[k][0], (*lightMapUVs)[k][1]));
#endif
				if(
					(*lightMapUVs)[k][0] >= -0.5f && (*lightMapUVs)[k][0] <= 0.5f &&
					(*lightMapUVs)[k][1] >= -0.5f && (*lightMapUVs)[k][1] <= 0.5f
				) 
				{
					lm = true;
				}
				if(
					bigUV > 0.0f &&
					(
						(*lightMapUVs)[k][0] < -bigUV || (*lightMapUVs)[k][0] > bigUV ||
						(*lightMapUVs)[k][1] < -bigUV || (*lightMapUVs)[k][1] > bigUV
					)
				) 
				{
					tooBig++;
				}
			}
			else
			{
				behindCount++;
			}
		}

		if(	
			tooBig == 0 
			&& behindCount == 0
			&& falloffCount == 0
			&& ((lm == true)	|| CheckForBigTriangles(lightMapUVs, 3) == true)
		)
		{
			for(k=0;k<3;k++,nrOfPoints++)
			{
				SetClipCoord(coords[index[k+j]], nrOfPoints);
				(*lightMapUVs)[k][0] += 0.5f;
				(*lightMapUVs)[k][1] += 0.5f;
				SetClipTexCoord((*lightMapUVs)[k], nrOfPoints);
			}
		}
	}

	if(nrOfPoints>0)
	{
		Verify(nrOfPoints%3==0);

		gos_PushCurrentHeap(PrimitiveHeap);
		MLR_I_TMesh *ret = new MLR_I_TMesh();
		Register_Object(ret);

		ret->FlashClipCoords(nrOfPoints);
		ret->FlashClipTexCoords(nrOfPoints);
		ret->TheIndexer(nrOfPoints);

		ret->SetSubprimitiveLengths(NULL, nrOfPoints/3);
		ret->FindFacePlanes();

		gos_PopCurrentHeap();

		MLRState state;

		state = referenceState;
		state.SetAlphaMode(MLRState::AlphaInvAlphaMode);
		state.SetPriority(referenceState.GetPriority()+1);
		state.SetTextureHandle(tex->GetTextureHandle());
		state.SetTextureWrapMode(MLRState::TextureClamp);

		ret->SetReferenceState(state);
		return ret;
	}

	return NULL;
}

void
	MLR_I_TMesh::DrawMyShadow(
		const Stuff::LinearMatrix4D& shadow_to_object,
		Stuff::UnitVector3D& sun_in_object,
		Stuff::Scalar radius,
		DWORD color
	)
{
	Check_Object(this);

	Point3D shadow_in_object(shadow_to_object);

	//
	//-----------------------------------------------------------------------
	// Get the forward, left, and up directions of the shadow relative to our
	// object
	//-----------------------------------------------------------------------
	//
	UnitVector3D forward, left, up;
	shadow_to_object.GetLocalForwardInWorld(&forward);
	shadow_to_object.GetLocalLeftInWorld(&left);
	shadow_to_object.GetLocalUpInWorld(&up);

	//
	//-----------------------------------------
	// Compute the offset of the plane equation
	//-----------------------------------------
	//
	Scalar offset = up*shadow_in_object;
	Scalar displacement = -1.0f/(sun_in_object*up);
	Scalar scale = 32.0f/radius;

	//
	//---------------------------------------------------------------------
	// Run thru each of the faces and find the ones that are visible to the
	// light source
	//---------------------------------------------------------------------
	//
	static gos_VERTEX pVertices[4000];
	int i, j, k, len = GetNumPrimitives();
	for(i=0,j=0,k=0;i<len;i++)
	{
		if(sun_in_object*facePlanes[i].normal < 0.0f)
		{

			//
			//----------------------------------------------
			// Project the first point unto the shadow plane
			//----------------------------------------------
			//
			const Point3D &p1 = coords[index[j++]];
			Scalar distance = up*p1 - offset;
			Vector3D projection;
			projection.AddScaled(p1, sun_in_object, displacement*distance);
			projection -= shadow_in_object;

			//
			//-------------------------------------------------------------
			// Convert this to the x-z coordinate of the vertex in terms of
			// the shadows left and forward axes
			//-------------------------------------------------------------
			//
			Scalar x, z;
			x = projection*left;
			z = projection*forward;

			//
			//--------------------------
			// Now set up the gos vertex
			//--------------------------
			//
			pVertices[k].x		= scale*x + 32.0f;
			pVertices[k].y		= scale*z + 32.0f;
			pVertices[k].z		= 0.5f;
			pVertices[k].rhw	= 1.0;
			pVertices[k].argb	= color;
			pVertices[k].frgb	= 0;
			pVertices[k].u		= 0.0f;
			pVertices[k++].v	= 0.0f;

			//
			//-------------------------
			// Project the second point
			//-------------------------
			//
			const Point3D &p2 = coords[index[j++]];
			distance = up*p2 - offset;
			projection.AddScaled(p2, sun_in_object, displacement*distance);
			projection -= shadow_in_object;

			x = projection*left;
			z = projection*forward;

			pVertices[k].x		= scale*x + 32.0f;
			pVertices[k].y		= scale*z + 32.0f;
			pVertices[k].z		= 0.5f;
			pVertices[k].rhw	= 1.0;
			pVertices[k].argb	= color;
			pVertices[k].frgb	= 0;
			pVertices[k].u		= 0.0f;
			pVertices[k++].v	= 0.0f;

			//
			//------------------------
			// Project the third point
			//------------------------
			//
			const Point3D &p3 = coords[index[j++]];
			distance = up*p3 - offset;
			projection.AddScaled(p3, sun_in_object, displacement*distance);
			projection -= shadow_in_object;

			x = projection*left;
			z = projection*forward;

			pVertices[k].x		= scale*x + 32.0f;
			pVertices[k].y		= scale*z + 32.0f;
			pVertices[k].z		= 0.5f;
			pVertices[k].rhw	= 1.0;
			pVertices[k].argb	= color;
			pVertices[k].frgb	= 0;
			pVertices[k].u		= 0.0f;
			pVertices[k++].v	= 0.0f;
		}
		else
		{
			j+=3;
		}
	}

	//
	//------------------------------------------------
	// If we have any triangles to draw, draw them now
	//------------------------------------------------
	//
	if(k>0)
	{
		MLR_RENDER("Draw Shadows");
		Start_Timer(Shadow_Time);
		gos_DrawTriangles( pVertices, k );
		Stop_Timer(Shadow_Time);
	}
}

//---------------------------------------------------------------------------
//
bool
	MLR_I_TMesh::CastRay(
		Line3D *line,
		Normal3D *normal
	)
{
	Check_Object(this);
	Check_Object(line);
	Check_Pointer(normal);

	//
	//---------------------------------------------------------------------
	// We have to spin through each of the polygons stored in the shape and
	// collide the ray against each
	//---------------------------------------------------------------------
	//
	int poly_start = 0;
	bool hit = false;
	for (int polygon=0; polygon<numOfTriangles; poly_start += 3,++polygon)
	{
		//
		//---------------------------------
		// See if the line misses the plane
		//---------------------------------
		//
		Scalar product;
		const Plane *plane = &facePlanes[polygon];
		Check_Object(plane);
		Scalar distance = line->GetDistanceTo(*plane, &product);
		if (distance < 0.0f || distance > line->m_length)
		{
			continue;
		}
		bool negate = false;
		if (product > -SMALL)
		{
			if (GetCurrentState().GetBackFaceMode() == MLRState::BackFaceOnMode)
			{
				continue;
			}
			negate = true;
		}

		//
		//-------------------------------------------
		// Figure out where on the plane the line hit
		//-------------------------------------------
		//
		Point3D impact;
		line->Project(distance, &impact);

		//
		//-------------------------------------------------------------------
		// We now need to find out which cardinal plane we should project the
		// triangle onto
		//-------------------------------------------------------------------
		//
		int s,t;
		Scalar nx = Abs(plane->normal.x);
		Scalar ny = Abs(plane->normal.y);
		Scalar nz = Abs(plane->normal.z);
		if (nx > ny)
		{
			if (nx > nz)
			{
				s = Y_Axis;
				t = Z_Axis;
			}
			else
			{
				s = X_Axis;
				t = Y_Axis;
			}
		}
		else if (ny > nz)
		{
			s = Z_Axis;
			t = X_Axis;
		}
		else
		{
			s = X_Axis;
			t = Y_Axis;
		}

		//
		//----------------------------------------
		// Initialize the vertex and leg variables
		//----------------------------------------
		//
		const Point3D *v1, *v2, *v3;
		v1 = &coords[index[poly_start]];
		v2 = &coords[index[poly_start+1]];
		v3 = &coords[index[poly_start+2]];

		//
		//---------------------------------------
		// Get the projection of the impact point
		//---------------------------------------
		//
		Scalar s0 = impact[s] - (*v1)[s];
		Scalar t0 = impact[t] - (*v1)[t];
		Scalar s1 = (*v2)[s] - (*v1)[s];
		Scalar t1 = (*v2)[t] - (*v1)[t];

		//
		//------------------------------------------------------------
		// For each triangle, figure out what the second leg should be
		//------------------------------------------------------------
		//
		bool local_hit = false;

		Check_Pointer(v3);
		Scalar s2 = (*v3)[s] - (*v1)[s];
		Scalar t2 = (*v3)[t] - (*v1)[t];

		//
		//--------------------------------
		// Now, see if we hit the triangle
		//--------------------------------
		//
		if (Small_Enough(s1))
		{
			Verify(!Small_Enough(s2));
			Scalar beta = s0 / s2;
			if (beta >= 0.0f && beta < 1.0f)
			{
				Verify(!Small_Enough(t1));
				Scalar alpha = (t0 - beta*t2) / t1;
				local_hit = (alpha >= 0.0f && alpha+beta <= 1.0f);
			}
		}
		else
		{
			Scalar beta = (t0*s1 - s0*t1);
			Scalar alpha = (t2*s1 - s2*t1);
			beta /= alpha;
			if (beta >= 0.0f && beta <= 1.0f)
			{
				alpha = (s0 - beta*s2) / s1;
				local_hit = (alpha >= 0.0f && alpha+beta <= 1.0f);
			}
		}

		//
		//
		//----------------------------------------------------
		// Handle the hit status, and move to the next polygon
		//----------------------------------------------------
		//
		if (local_hit)
		{
			hit = true;
			line->m_length = distance;
			if (negate)
				normal->Negate(plane->normal);
			else
				*normal = plane->normal;
			Verify(*normal * line->m_direction <= -SMALL);
		}
	}

	//
	//----------------------
	// Return the hit status
	//----------------------
	//
	return hit;
}

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
MLR_I_TMesh*
	MidLevelRenderer::CreateIndexedTriCube_NoColor_NoLit(
		Scalar half, 
		MLRState *state
	)
{
	gos_PushCurrentHeap(PrimitiveHeap);
	MLR_I_TMesh *ret = new MLR_I_TMesh();
	Register_Object(ret);

	DynamicArrayOf<Point3D> *coords = &ret->dataStore->coords;
	Check_Object(coords);
	coords->SetLength(8);

	(*coords)[0] = Point3D( half, -half,  half);
	(*coords)[1] = Point3D(-half, -half,  half);
	(*coords)[2] = Point3D( half, -half, -half);
	(*coords)[3] = Point3D(-half, -half, -half);
	(*coords)[4] = Point3D(-half,  half,  half);
	(*coords)[5] = Point3D( half,  half,  half);
	(*coords)[6] = Point3D( half,  half, -half);
	(*coords)[7] = Point3D(-half,  half, -half);

	ret->SetSubprimitiveLengths(NULL, 12);

	ret->SetCoordData(coords->GetData(), 8);

	DynamicArrayOf<BYTE> *index = &ret->dataStore->index;
	Check_Object(index);
	index->SetLength(6*3*2);

	(*index)[0] = 0;
	(*index)[1] = 2;
	(*index)[2] = 6;
	(*index)[3] = 0;
	(*index)[4] = 6;
	(*index)[5] = 5;

	(*index)[6] = 0;
	(*index)[7] = 5;
	(*index)[8] = 4;
	(*index)[9] = 0;
	(*index)[10] = 4;
	(*index)[11] = 1;

	(*index)[12] = 5;
	(*index)[13] = 6;
	(*index)[14] = 7;
	(*index)[15] = 5;
	(*index)[16] = 7;
	(*index)[17] = 4;

	(*index)[18] = 2;
	(*index)[19] = 3;
	(*index)[20] = 7;
	(*index)[21] = 2;
	(*index)[22] = 7;
	(*index)[23] = 6;

	(*index)[24] = 1;
	(*index)[25] = 4;
	(*index)[26] = 7;
	(*index)[27] = 1;
	(*index)[28] = 7;
	(*index)[29] = 3;

	(*index)[30] = 0;
	(*index)[31] = 1;
	(*index)[32] = 3;
	(*index)[33] = 0;
	(*index)[34] = 3;
	(*index)[35] = 2;

	ret->SetIndexData(index->GetData(), 6*3*2);

	ret->FindFacePlanes();

	DynamicArrayOf<Vector2DScalar> *texCoords = &ret->dataStore->texCoords;
	Check_Object(texCoords);
	texCoords->SetLength(8);

	(*texCoords)[0] = Vector2DScalar(0.0f, 0.0f);
	(*texCoords)[1] = Vector2DScalar(0.0f, 0.0f);
	(*texCoords)[2] = Vector2DScalar(0.0f, 0.0f);
	(*texCoords)[3] = Vector2DScalar(0.0f, 0.0f);

	(*texCoords)[4] = Vector2DScalar(0.0f, 0.0f);
	(*texCoords)[5] = Vector2DScalar(0.0f, 0.0f);
	(*texCoords)[6] = Vector2DScalar(0.0f, 0.0f);
	(*texCoords)[7] = Vector2DScalar(0.0f, 0.0f);

	if(state != NULL)
	{
		ret->SetReferenceState(*state);
		if(state->GetTextureHandle() > 0)
		{
			(*texCoords)[0] = Vector2DScalar(0.0f, 0.0f);
			(*texCoords)[1] = Vector2DScalar(1.0f, 0.0f);
			(*texCoords)[2] = Vector2DScalar(0.25f, 0.25f);
			(*texCoords)[3] = Vector2DScalar(0.75f, 0.25f);

			(*texCoords)[4] = Vector2DScalar(1.0f, 1.0f);
			(*texCoords)[5] = Vector2DScalar(0.0f, 1.0f);
			(*texCoords)[6] = Vector2DScalar(0.25f, 0.75f);
			(*texCoords)[7] = Vector2DScalar(0.75f, 0.75f);
		}
	}
	ret->SetTexCoordData(texCoords->GetData(), 8);

	gos_PopCurrentHeap();

	return ret;
}

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

	gos_PushCurrentHeap(MLR_I_TMesh::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_TMesh *mesh = new MLR_I_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(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);
			Check_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<uniquePoints;i++)
			{
				(*texCoords)[i] = Vector2DScalar(0.0f, 0.0f);
			}
		}
		else
		{
			mesh->SetReferenceState(*state);
			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
						);
				}
			}
			else
			{
				for(i=0;i<uniquePoints;i++)
				{
					(*texCoords)[i] = Vector2DScalar(0.0f, 0.0f);
				}
			}
		}
		mesh->SetTexCoordData(texCoords->GetData(), uniquePoints);

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

	gos_PopCurrentHeap();
	return ret;
}
