/** SGX

The   sss    gggg x   x   
     s      g      x x    Engine
      sss   g  gg   x
         s  g   g  x x          Copyright 1995-2009.
     ssss    gggg x   x         Steven Goodwin. All Rights Reserved.
    
This version has been released under the GNU Public License v2.0.

Please see the license files for details.

File: sgx/src/sgx/graphics/mesh/animmesh.cpp

*/

#include "sgx/core/core.hpp"
#include "sgx/graphics/graphics.hpp"
#include "sgx/filesystem/filesystem.hpp"

// TODO: Place a factory in the graphics engine,
// so that every mesh/anim is loaded by the platform-specific
// code, eliminated the need of a Convert process


CAnimatedMesh*
CAnimatedMesh::load(const sgxString &filename)
{
CSGXFile fp(filename);
CAnimatedMesh *pMesh = NULL;

	if (fp.open()) {
		sgxString s;
		fp.readLine(s);
		if (s == "md2") {
			pMesh = new CSGXAnimatedMeshMD2(filename);
			fp.readLine(s);
			if (s != "") {
				pMesh->setAnimationFrameRate(sgxAtof(s));
			}
		}

		fp.close();

		// Generic data is loaded here.
		//...and then converted by the platform-specific
		// chunk here. (if it exists)
		CSGXGraphicsEngine::get()->convertAnimatedMesh(*pMesh);
	} 

	return pMesh;
}


CAnimatedMesh::CAnimatedMesh() :
m_bTransition(FALSE),
m_bPlaying(FALSE),
m_fFrameRate(1/15.0f)
{
}

CAnimatedMesh::~CAnimatedMesh() {
	pauseAnimation();
}

void
CAnimatedMesh::update(const tREAL32 telaps)
{
	if (m_bPlaying) {
		CSGXGraphicsEngine::get()->updateAnimatedMesh(*this, telaps);
	}
}

void
CAnimatedMesh::draw(const sgxMatrix43 &transform) const
{
	CSGXGraphicsEngine::get()->drawAnimatedMesh(*this, transform);
}


void
CAnimatedMesh::startAnimation(const tUINT32 animIndex) {
	m_iCurrentAnim = animIndex;
	resumeAnimation();
}

void	
CAnimatedMesh::startTransitionAnimation(const tUINT32 animIndex) {
	m_bTransition = TRUE;
	m_iTransitionAnim = animIndex;
}

void
CAnimatedMesh::setAnimationFrameRate(const tREAL32 rateFPS) {
	m_fFrameRate = 1.0f / rateFPS;
}

void
CAnimatedMesh::pauseAnimation() {
	m_bPlaying = FALSE;
}

void
CAnimatedMesh::resumeAnimation() {
	m_bPlaying = TRUE;
}

tBOOL
CAnimatedMesh::isAnimationPlaying() {
	return m_bPlaying;
}

tUINT32
CAnimatedMesh::getCurrentAnimation() {
	return m_iCurrentAnim;
}
