/** \file VertexBones.cpp
 * \brief The implementation of the 'VertexBones' class.
 */

#include "VertexBones.h"
#include <list>

namespace OSkA
{
	VertexBones::VertexBones()
	{
		boneWeights.resize(0);
	}

	VertexBones::~VertexBones()
	{
		boneWeights.clear();
	}

	void VertexBones::addBone(int bone, float weight)
	{
		int oldSize=getBonesCount();
		if(bone >=oldSize)
		{
			boneWeights.resize(bone+1);
			for(int i=oldSize; i<getBonesCount(); i++)
				boneWeights[i]=0;
		}
		boneWeights[bone]=weight;
	}

	int VertexBones::getBonesCount()
	{
		return boneWeights.size();
	}

	float* VertexBones::getMaxWeights()
	{
		float* ret=new float[4];
		float* indices;
		if(getBonesCount()> 4)
		{
			indices=getMaxWeightsIndices();
			for(int i=0; i<4; i++)
			{
				ret[i]=boneWeights[indices[i]];
			}
		}
		else
		{
			int b;
			for(b=0; b<getBonesCount(); b++)
				ret[b]=boneWeights[b];
			for(; b<4; b++)
				ret[b]=0;
		}
		return ret;
	}

	float* VertexBones::getMaxWeightsIndices()
	{
		float* ret=new float[4];
		if(getBonesCount()> 4)
		{
			std::list<int> w;

			for(int i=0; i<getBonesCount(); i++)
				w.push_back(int(boneWeights[i]*10000)*100+i);
			w.sort();
			for(int i=0; i<4; i++)
			{
				ret[i]=w.back()%100;
				w.pop_back();
			}
		}
		else
		{
			int b;
			for(b=0; b<getBonesCount(); b++)
				ret[b]=b;
			for(; b<4; b++)
				ret[b]=0;
		}
		return ret;
	}
}