// DumpMeshTEP.cpp: implementation of the CDumpMeshTEP class.
//
//////////////////////////////////////////////////////////////////////

#include "DumpMeshTEP.h"

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

CDumpMeshTEP::CDumpMeshTEP()
{

}

CDumpMeshTEP::~CDumpMeshTEP()
{

}

int CDumpMeshTEP::callback(INode *lpNode)
{
	cleanup();

	return TREE_CONTINUE;
}

void CDumpMeshTEP::cleanup()
{
	if (m_phyMod && m_phyExport)
	{
		if (m_mcExport)
		{
			m_phyExport->ReleaseContextInterface(m_mcExport);
			m_mcExport = NULL;
        }
        
		m_phyMod->ReleaseInterface(I_PHYINTERFACE, m_phyExport);
		m_phyMod = NULL;
		
		m_phyExport = NULL;
	}
}

int CDumpMeshTEP::InodeOfPhyVectex(int nVertex)
{
	int nNode = 0;

	IPhyVertexExport* pVtxExport = m_mcExport->GetVertexInterface(nVertex);
	if (pVtxExport)
	{
		//need to check if vertex has blending
		if (pVtxExport->GetVertexType() & BLENDED_TYPE)
		{
			// 
		}
		else 
		{
			INode* pNode = ((IPhyRigidVertex *) pVtxExport)->GetNode();
			nNode = GetIndexOfINode(pNode);
		}

		m_mcExport->ReleaseVertexInterface(pVtxExport);
	}

	return nNode;
}

// Determine is the node has negative scaling.
// This is used for mirrored objects for example. They have a negative scale factor
// so when calculating the normal we should take the vertices counter clockwise.
// If we don't compensate for this the objects will be 'inverted'.
BOOL CDumpMeshTEP::TMNegParity(Matrix3 &m)
{
	return (DotProd(CrossProd(m.GetRow(0), m.GetRow(1)), m.GetRow(2)) < 0.0) ? TRUE:FALSE;
}

Point3 CDumpMeshTEP::Pt3GetRVertexNormal(RVertex *lpRVertex, DWORD smGroupFace)
{
	// Lookup the appropriate vertex normal, based on smoothing group.
	int nNormalCounts = lpRVertex->rFlags & NORCT_MASK;
	if (nNormalCounts == 1)
	{
		return lpRVertex->rn.getNormal();
	}
	else
	{
		for (int i=0; i<nNormalCounts; i++)
		{
			if (lpRVertex->ern[i].getSmGroup() & smGroupFace)
				break;
		}

		if (i >= nNormalCounts) 
		{
			i = 0;
		}

		return lpRVertex->ern[i].getNormal();
	}
}
