#include "global.h"
#include "map_draw.h"
#include "collide.h"

#include "anim.h"

int actorMaintainAnimation(ACTOR *pActor)
{
	// CPW: increment frames etc.
	
	ANIM_ANIMATION *pAnimation = &pActor->animation;
	int i;

	for(i=0; i<(pAnimation->blendEnable?2:1); i++)
	{
		// CPW: process current (new) animation, then the old one (assuming blending's enabled)

		ANIM_DATA *pAD;
		ANIM_SEGMENT *pAS;
		int scaledAnimLength;

		pAD = pAnimation->animData + i;
		pAS = pAnimation->pSegments + pAD->segment;
		scaledAnimLength = pAS->scaledAnimLength;

		// CPW: inc/dec frame
		pAD->scaledFrameOffset += pAD->speed;

		// CPW: make sure anim counter stays within its limits
		if(pAD->scaledFrameOffset < 0)
		{
			if(pAD->loop)
				pAD->scaledFrameOffset += scaledAnimLength;
			else
				pAD->scaledFrameOffset = 0;
		}
		else
		{
			if(pAD->scaledFrameOffset >= scaledAnimLength)
			{
				if(pAD->loop)
					pAD->scaledFrameOffset -= scaledAnimLength;
				else
					pAD->scaledFrameOffset = scaledAnimLength-1;
			}
		}


		// CPW: LASTLY, work out the actual frame number
		pAD->actualFrame = (pAS->scaledStartFrame + pAD->scaledFrameOffset) >> 8;
	}

	
	if(pAnimation->blendEnable)
	{
		pAnimation->blendCounter += pAnimation->blendSpeed;
		if(pAnimation->blendCounter > 4096)
		{
			pAnimation->blendCounter = 4096;
		}

		psiSetKeyFrames2(pActor->psiData.object, pAnimation->animData[1].actualFrame,
							pAnimation->animData[0].actualFrame, pAnimation->blendCounter);
	}
	else
	{
		psiSetKeyFrames(pActor->psiData.object, pAnimation->animData[0].actualFrame);
	}
}

int actorSetAnimation(ACTOR *pActor, int animNum, char loop, char queue, int actualSpeed, char skipendframe, char blend)
{
	ANIM_DATA	tempAnimData;
	ANIM_ANIMATION	*pAnimation;

	pAnimation = pActor->pAnimation;

	if(blend && (pAnimation->blendCounter!=4096))
	{	// CPW: blending hasn't finished
		return ANIMATE_STILLBLENDING;
	}

	if((animNum < 0) || (animNum >= pAnimation->numSegments))
	{
		return ANIMATE_INVALIDANIMATION;
	}

	// CPW: make a backup of current anim state
	memcpy(&tempAnimData, pAnimation->animData + 0, sizeof(ANIM_DATA));

	pAnimation->blendEnable = blend;	// CPW: start it off blending (if that's been specified)
	pAnimation->blendCounter = 0;		// CPW: begin at the beginning, because that's the very best place to start
	
	pAnimation->animData[0].loop = loop;
	pAnimation->animData[0].segment = animNum;
	pAnimation->animData[0].speed = actualSpeed;	// CPW: remember, speed is scaled by 256
	pAnimation->animData[0].scaledFrameOffset = 0;
	pAnimation->animData[0].actualFrame = -1;

	memcpy(pAnimation->animData + 1, &tempAnimData, sizeof(ANIM_DATA));

	return ANIMATE_OK;
}
