/*** CSpatialDivision class, Cristiaan Kop						 updated 21-01-2020 ***/
/*** ============================================================================== ***/
/*** NAMESPACE: Crealysm::WORLD (API independent)									***/
/*** cpp file with the CSpatialDivision class implementation (spatial division)		 ***/

#include "WORLD/cspatialdivision.h"
#include "WORLD/c3dmeshinst.h"
#include "PHYSMATH/cbasecollision.h"
#include <ceasylogging++.h>
#include "common/crealysm_text.h"


namespace Crealysm { namespace WORLD
{

/**************************************************************************************/
/***								CONSTRUCTOR										***/
/*** ==> usage: when creating a CSpatialDivision object								***/
/*** ==> makes the object 'valid'													***/
/**************************************************************************************/

CSpatialDivision::CSpatialDivision() : mNrDivisions(0)
{	
	mPartitions.clear();

	useQuadTree = true;
	// initialized using 'Create' taking valid C3dScene
}

/**************************************************************************************/
/***								DESTRUCTOR										***/
/*** ==> usage: when CSpatialDivision object is not needed anymore					***/
/*** ==> releases stuff, objects, memory etc. 										***/
/**************************************************************************************/

CSpatialDivision::~CSpatialDivision()
{
	// nothing yet
}

/**************************************************************************************/
/***									SETUP					 					***/
/*** ==> usage: to break the 3d scene up into partitions							***/
/*** ==> calls the private function to set everything up 							***/
/**************************************************************************************/

bool CSpatialDivision::Setup(const C3dScene &pScene, const uint pNumDivisions)
{
	mPartitions.clear();
	uint nrPartitions = 1;
	for(size_t i=0;i<pNumDivisions;++i) nrPartitions += static_cast<uint>(pow(4.0, static_cast<double>(i+1)));
	mPartitionsQ.reserve(nrPartitions);
	
	mNrDivisions = pNumDivisions;

	if(useQuadTree)
	{
		if(!CreatePartitionsQuadTree(pScene)) return false;
		AddLightDataToPartitionsQ(pScene, false);

	}
	else
	{
		mMinMeshInstPerPart = 5;
		if(!CreatePartitions(pScene)) return false;
		AddLightDataToPartitions(pScene, false);
	}
		

	CreateInstPartIds();

	if(useQuadTree) GetPartitionStatsQ();
	else GetPartitionStats();

	return true;
}

/**************************************************************************************/
/***							UPDATE DYNAMIC LIGHTS				  				***/
/*** ==> usage: to divide (updated) dynamic lights into the partitions				***/
/*** ==> updates the stored affected lights with the dynamic ones					***/
/**************************************************************************************/

void CSpatialDivision::UpdateDynamicLights(const C3dScene &pScene)
{
	AddLightDataToPartitions(pScene, true);
}

/**************************************************************************************/
/***								GET PARTITION ID		 		  				***/
/*** ==> usage: to retrieve the partition ID for a given mesh instance 				***/
/*** ==> searches the std::vector with instance IDs and returns matching index		***/
/**************************************************************************************/

uint CSpatialDivision::GetPartitionId(const uint pMeshInstId)
{
	uint index = 0;

	int pos = std::find(mMeshInstIds.begin(), mMeshInstIds.end(), pMeshInstId) - mMeshInstIds.begin();
	if(pos < static_cast<int>(mMeshInstIds.size()))
	{
		index = pos;
	}
	else return 0;

	return mMeshInstPartIds.at(index);
}




/**************************************************************************************/
/***							GET PARTITION STATS		 			  PRIVATE CONST	***/
/*** ==> usage: writes statistics on the division to the logger 					***/
/*** ==> min instances, max, average etc											***/
/**************************************************************************************/

void CSpatialDivision::GetPartitionStats() const
{
	uint avgInst = 0;
	uint tTotal = 0;

	PHYSMATH::CR_VECTOR3 totalExtents;
	PHYSMATH::CR_VECTOR3 minExtents = PHYSMATH::CR_VECTOR3(FLT_MAX);
	PHYSMATH::CR_VECTOR3 maxExtents = PHYSMATH::CR_VECTOR3(-FLT_MAX);

	for(size_t p=0;p<mPartitions.size();++p)
	{
		// AABB stats
		totalExtents += mPartitions.at(p).BV.AABBWorld.Extents;

		minExtents.x = min(minExtents.x, mPartitions.at(p).BV.AABBWorld.Extents.x);
		minExtents.y = min(minExtents.y, mPartitions.at(p).BV.AABBWorld.Extents.y);
		minExtents.z = min(minExtents.z, mPartitions.at(p).BV.AABBWorld.Extents.z);

		maxExtents.x = max(maxExtents.x, mPartitions.at(p).BV.AABBWorld.Extents.x);
		maxExtents.y = max(maxExtents.y, mPartitions.at(p).BV.AABBWorld.Extents.y);
		maxExtents.z = max(maxExtents.z, mPartitions.at(p).BV.AABBWorld.Extents.z);
		
		tTotal += static_cast<uint>(mPartitions.at(p).MeshInstances.size());
	}

	avgInst = tTotal / static_cast<uint>(mPartitions.size());

	// AABB stats
	totalExtents /= static_cast<float>(mPartitions.size());

	CLOG(DEBUG, "WORLD") << COMMON::debug_subdiv_nrdiv << mNrDivisions << " / " << static_cast<uint>(mPartitions.size());
	CLOG(DEBUG, "WORLD") << COMMON::debug_subdiv_inststat << avgInst;
	CLOG(DEBUG, "WORLD") << COMMON::debug_subdiv_dim << "(" << minExtents.x << "," << minExtents.y << "," << minExtents.z << ") / (" << maxExtents.x << "," << maxExtents.y << "," << maxExtents.z << ") / (" << totalExtents.x << "," << totalExtents.y << "," << totalExtents.z << ")"; //min/max/average XZ dimension per partition

	for(size_t p=0;p<mPartitions.size();++p) 
		CLOG(DEBUG, "WORLD") << COMMON::debug_subdiv_partstat.c_str() << p << ": " << mPartitions.at(p).MeshInstances.size() << " inst. AABB extents: " << mPartitions.at(p).BV.AABBWorld.Extents.x << "," << mPartitions.at(p).BV.AABBWorld.Extents.y << "," << mPartitions.at(p).BV.AABBWorld.Extents.z;
}

void CSpatialDivision::GetPartitionStatsQ() const
{
	uint avgInst = 0;
	uint tTotal = 0;

	PHYSMATH::CR_VECTOR3 totalExtents;
	PHYSMATH::CR_VECTOR3 minExtents = PHYSMATH::CR_VECTOR3(FLT_MAX);
	PHYSMATH::CR_VECTOR3 maxExtents = PHYSMATH::CR_VECTOR3(-FLT_MAX);

	for(size_t p=0;p<mPartitionsQ.size();++p)
	{
		// AABB stats
		totalExtents += mPartitionsQ.at(p).BV.AABBWorld.Extents;

		minExtents.x = min(minExtents.x, mPartitionsQ.at(p).BV.AABBWorld.Extents.x);
		minExtents.y = min(minExtents.y, mPartitionsQ.at(p).BV.AABBWorld.Extents.y);
		minExtents.z = min(minExtents.z, mPartitionsQ.at(p).BV.AABBWorld.Extents.z);

		maxExtents.x = max(maxExtents.x, mPartitionsQ.at(p).BV.AABBWorld.Extents.x);
		maxExtents.y = max(maxExtents.y, mPartitionsQ.at(p).BV.AABBWorld.Extents.y);
		maxExtents.z = max(maxExtents.z, mPartitionsQ.at(p).BV.AABBWorld.Extents.z);
		
		tTotal += static_cast<uint>(mPartitionsQ.at(p).MeshInstances.size());
	}

	avgInst = tTotal / static_cast<uint>(mPartitionsQ.size());

	// AABB stats
	totalExtents /= static_cast<float>(mPartitionsQ.size());

	CLOG(DEBUG, "WORLD") << COMMON::debug_subdiv_nrdiv << mNrDivisions << " / " << static_cast<uint>(mPartitionsQ.size());
	CLOG(DEBUG, "WORLD") << COMMON::debug_subdiv_inststat << avgInst;
	CLOG(DEBUG, "WORLD") << COMMON::debug_subdiv_dim << "(" << minExtents.x << "," << minExtents.y << "," << minExtents.z << ") / (" << maxExtents.x << "," << maxExtents.y << "," << maxExtents.z << ") / (" << totalExtents.x << "," << totalExtents.y << "," << totalExtents.z << ")"; //min/max/average XZ dimension per partition

	for(size_t p=0;p<mPartitionsQ.size();++p) 
		CLOG(DEBUG, "WORLD") << COMMON::debug_subdiv_partstat.c_str() << p << ": " << mPartitionsQ.at(p).MeshInstances.size() << " inst. AABB extents: " << mPartitionsQ.at(p).BV.AABBWorld.Extents.x << "," << mPartitionsQ.at(p).BV.AABBWorld.Extents.y << "," << mPartitionsQ.at(p).BV.AABBWorld.Extents.z;
}



void CSpatialDivision::GetPartitionSpecs(uint &pNrPartitions, uint &pMeshInstPerPartition, const uint pNrTotalMeshInst) const
{
	pNrPartitions = static_cast<uint>(std::pow(2.0, mNrDivisions));
	pMeshInstPerPartition = max(mMinMeshInstPerPart, pNrTotalMeshInst / pNrPartitions);

	if(pMeshInstPerPartition <= mMinMeshInstPerPart)
	{
		pNrPartitions = pNrTotalMeshInst / pMeshInstPerPartition;
		if(pNrPartitions != 0) pMeshInstPerPartition = pNrTotalMeshInst / pNrPartitions;
		else pMeshInstPerPartition = pNrTotalMeshInst;
	}
} 



/**************************************************************************************/
/***								CREATE PARTITIONS				 		PRIVATE	***/
/*** ==> usage: to subdivide the full 3d scene into partitions						***/
/*** ==> partitions will always fully encapsulate mesh instances, no intersections	***/
/**************************************************************************************/

bool CSpatialDivision::CreatePartitions(const C3dScene &pScene)
{
	mPartitions.clear();

	// sort on the 1st AXIS
	std::vector<uint> emptyIndex(0);	// full scene
	std::vector<uint> sortIndexX = SortMeshInstAABBAxis(pScene, 2, emptyIndex);	// 2 = Z AXIS

	uint nrPartitions = 0;
	uint instPerPartition = 0;

	GetPartitionSpecs(nrPartitions, instPerPartition, static_cast<uint>(pScene.GetNrMeshInst()));

	// get temporary partitions, only sorted on 1 AXIS
	std::vector<SCENE_PARTITION> tempPartitions;
	CreateFlatPartitions(tempPartitions, nrPartitions, instPerPartition, sortIndexX, false);
	
	// move to the 2nd AXIS and store final partitions
	for(size_t pz=0;pz<tempPartitions.size();++pz)
	{
		auto &partition = tempPartitions.at(pz);
		std::vector<uint> sortIndexZ = SortMeshInstAABBAxis(pScene, 0, partition.MeshInstances);	// 0 = X AXIS

		// create partitions
		GetPartitionSpecs(nrPartitions, instPerPartition, static_cast<uint>(partition.MeshInstances.size()));
		CreateFlatPartitions(mPartitions, nrPartitions, instPerPartition, sortIndexZ, true);
	}
	
	// calculate AABBs per all partitions + remove empty partitions
	for(size_t p=0;p<mPartitions.size();++p) CalcPartitionAABB(p, pScene);

	return true;
}

void CSpatialDivision::CreateFlatPartitions(std::vector<SCENE_PARTITION> &pPartitionsOut, const uint pNrPartitions, const uint pMeshInstPerPartition, const std::vector<uint> &pInstIndex, const bool pAppend)
{
	if(!pAppend) pPartitionsOut.clear();

	// full partitions
	uint currInst = 0;
	for(size_t p=0;p<pNrPartitions;++p)
	{
		pPartitionsOut.push_back(SCENE_PARTITION());
		for(size_t mi=0;mi<pMeshInstPerPartition;++mi)
		{
			pPartitionsOut.back().MeshInstances.push_back(pInstIndex.at(currInst));
			++currInst;
		}
	}
	// remainder
	uint remain = static_cast<uint>(pInstIndex.size()) - (pNrPartitions * pMeshInstPerPartition);
	if(remain > 0)
	{
		SCENE_PARTITION remainPart;
		for(size_t r=0;r<remain;++r)
		{
			remainPart.MeshInstances.push_back(pInstIndex.at(currInst));
			++currInst;
		}
		pPartitionsOut.push_back(remainPart);
	}
}



bool CSpatialDivision::CreatePartitionsQuadTree(const C3dScene &pScene)
{
	// full scene, no sorting
	SCENE_PARTITION_Q partFullScene;
	for(size_t i=0;i<pScene.GetNrMeshInst();++i) partFullScene.MeshInstances.push_back(i);

	mPartitionsQ.clear();
	mPartitionsQ.push_back(partFullScene);

	// apply subdivisions
	uint startIndex = 0;
	for(size_t sd=0;sd<mNrDivisions;++sd)
	{
		uint partsToDivide = static_cast<uint>(pow(4.0, static_cast<double>(sd)));
		for(size_t p=startIndex;p<startIndex+partsToDivide;++p)
		{
			if(!SubDivideAndAdd(mPartitionsQ.at(p), p, pScene)) return false; 
		}
		startIndex += partsToDivide;
	}

	// calculate AABBs per all partitions + remove empty partitions
	for(size_t p=0;p<mPartitionsQ.size();++p) CalcPartitionAABBQ(p, pScene);

	return true;
}

/**************************************************************************************/
/***							SUBDIVIDE AND ADD					 		PRIVATE	***/
/*** ==> usage: subdivides 1 partition into 4 child partitions (QuadTree)			***/
/*** ==> splits the mesh instances and adds a pointer of parent to child partitions ***/
/**************************************************************************************/

bool CSpatialDivision::SubDivideAndAdd(const SCENE_PARTITION_Q &pPartitionIn, const uint pParentIndex, const C3dScene &pScene)
{
	// input is parent with mesh instances
	std::vector<uint> parentSortedX = SortMeshInstAABBAxis(pScene, 0, pPartitionIn.MeshInstances);	// 0 = X AXIS
	uint splitX = parentSortedX.size() / 2;

	// temporary partitions with sort on X only
	SCENE_PARTITION tempX_first;
	SCENE_PARTITION tempX_second;

	for(size_t tA=0;tA<splitX;++tA)						tempX_first.MeshInstances.push_back(parentSortedX.at(tA));
	for(size_t tB=splitX;tB<parentSortedX.size();++tB)	tempX_second.MeshInstances.push_back(parentSortedX.at(tB));

	// sort the 2 temp partitions on Z
	tempX_first.MeshInstances = SortMeshInstAABBAxis(pScene, 2, tempX_first.MeshInstances);			// 2 = Z AXIS
	tempX_second.MeshInstances = SortMeshInstAABBAxis(pScene, 2, tempX_second.MeshInstances);		// 2 = Z AXIS

	// divide the 2 temp partitions into the 4 output partitions
	uint splitXfirst = tempX_first.MeshInstances.size() / 2;
	uint splitXsecond = tempX_second.MeshInstances.size() / 2;
	
	SCENE_PARTITION_Q tPart[4];
	for(size_t a=0;a<splitXfirst;++a) tPart[0].MeshInstances.push_back(tempX_first.MeshInstances.at(a));
	for(size_t b=splitXfirst;b<tempX_first.MeshInstances.size();++b) tPart[1].MeshInstances.push_back(tempX_first.MeshInstances.at(b));

	for(size_t c=0;c<splitXsecond;++c) tPart[2].MeshInstances.push_back(tempX_second.MeshInstances.at(c));
	for(size_t d=splitXsecond;d<tempX_second.MeshInstances.size();++d) tPart[3].MeshInstances.push_back(tempX_second.MeshInstances.at(d));

	// add to the partition vector and update ptr's
	for(size_t newPart=0;newPart<4;++newPart)
	{
		mPartitionsQ.push_back(tPart[newPart]);
		mPartitionsQ.back().SetParent(&mPartitionsQ.at(pParentIndex));
	}
	for(size_t p=0;p<4;++p)
	{
		uint childIndex = static_cast<uint>(mPartitionsQ.size()) - 4 + p;
		mPartitionsQ.at(pParentIndex).SetChild(p, &mPartitionsQ.at(childIndex));
	}
	return true;
}

/**************************************************************************************/
/***							CALC PARTITION AABB					 		PRIVATE	***/
/*** ==> usage: to calculate the fully encapsulating AABB for the instances			***/
/*** ==> finds the worldspace AABB for the instances in the partition				***/
/**************************************************************************************/

void CSpatialDivision::CalcPartitionAABB(uint pIndex, const C3dScene &pScene)
{
	PHYSMATH::CR_VECTOR3 tMax = (-FLT_MAX);
	PHYSMATH::CR_VECTOR3 tMin = (FLT_MAX);
	
	for(size_t mi=0;mi<mPartitions.at(pIndex).MeshInstances.size();++mi)
	{
		auto &instAABB = pScene.GetMeshInst(mPartitions.at(pIndex).MeshInstances.at(mi)).GetBV().AABBWorld;
		if(instAABB.Max.x > tMax.x) tMax.x = instAABB.Max.x;
		if(instAABB.Max.y > tMax.y) tMax.y = instAABB.Max.y;
		if(instAABB.Max.z > tMax.z) tMax.z = instAABB.Max.z;

		if(instAABB.Min.x < tMin.x) tMin.x = instAABB.Min.x;
		if(instAABB.Min.y < tMin.y) tMin.y = instAABB.Min.y;
		if(instAABB.Min.z < tMin.z) tMin.z = instAABB.Min.z;
	}
	
	mPartitions.at(pIndex).BV.AABBWorld.Min = tMin;
	mPartitions.at(pIndex).BV.AABBWorld.Max = tMax;
	mPartitions.at(pIndex).BV.AABBWorld.UpdateCenterExtents();
}

void CSpatialDivision::CalcPartitionAABBQ(uint pIndex, const C3dScene &pScene)
{
	PHYSMATH::CR_VECTOR3 tMax = (-FLT_MAX);
	PHYSMATH::CR_VECTOR3 tMin = (FLT_MAX);
	
	for(size_t mi=0;mi<mPartitionsQ.at(pIndex).MeshInstances.size();++mi)
	{
		auto &instAABB = pScene.GetMeshInst(mPartitionsQ.at(pIndex).MeshInstances.at(mi)).GetBV().AABBWorld;
		if(instAABB.Max.x > tMax.x) tMax.x = instAABB.Max.x;
		if(instAABB.Max.y > tMax.y) tMax.y = instAABB.Max.y;
		if(instAABB.Max.z > tMax.z) tMax.z = instAABB.Max.z;

		if(instAABB.Min.x < tMin.x) tMin.x = instAABB.Min.x;
		if(instAABB.Min.y < tMin.y) tMin.y = instAABB.Min.y;
		if(instAABB.Min.z < tMin.z) tMin.z = instAABB.Min.z;
	}
	
	mPartitionsQ.at(pIndex).BV.AABBWorld.Min = tMin;
	mPartitionsQ.at(pIndex).BV.AABBWorld.Max = tMax;
	mPartitionsQ.at(pIndex).BV.AABBWorld.UpdateCenterExtents();
}

/**************************************************************************************/
/***							ADD LIGHT DATA TO PARTITIONS		 		PRIVATE	***/
/*** ==> usage: to add static positional light IDs to the partitions				***/
/*** ==> stores the light IDs that affect the Bounding volume of the partitions		***/
/**************************************************************************************/

void CSpatialDivision::AddLightDataToPartitions(const C3dScene &pScene, const bool pDynamic)
{
	for(size_t p=0;p<mPartitions.size();++p)
	{
		auto &part = mPartitions.at(p);

		if(pDynamic) part.ResetLightsToStatic();

		// Pointlights
		for(size_t pl=0;pl<pScene.GetNrLightsPoint(false);++pl)
		{
			auto &pLight = pScene.GetLightPoint(pl);
			if(pLight.IsDynamic() == pDynamic)
			{
				if(PHYSMATH::CBaseCollision::AABBSphereIntersect(part.BV.AABBWorld, PHYSMATH::CR_SPHERE(pLight.GetTransform().CurrState.Pos, pLight.GetRange())))
				{
					part.PointLightsAffected.push_back(pl);
				}
			}
		}
		// Spotlights
		for(size_t sl=0;sl<pScene.GetNrLightsSpot(false);++sl)
		{
			auto &sLight = pScene.GetLightSpot(sl);
			if(sLight.IsDynamic() == pDynamic)
			{
				if(PHYSMATH::CBaseCollision::AABBSphereIntersect(part.BV.AABBWorld, PHYSMATH::CR_SPHERE(sLight.GetTransform().CurrState.Pos, sLight.GetRange())))
				{
					part.SpotLightsAffected.push_back(sl);
				}
			}
		}
		// Capsule lights
		for(size_t cl=0;cl<pScene.GetNrLightsCapsule(false);++cl)
		{
			auto &cLight = pScene.GetLightCapsule(cl);
			if(cLight.IsDynamic() == pDynamic)
			{
				if(PHYSMATH::CBaseCollision::AABBSphereIntersect(part.BV.AABBWorld, PHYSMATH::CR_SPHERE(cLight.GetTransform().CurrState.Pos, cLight.GetRange())))
				{
					part.CapsuleLightsAffected.push_back(cl);
				}
			}
		}

		// store static lights data
		if(!pDynamic) part.SaveLightsStatic();
	}
}

void CSpatialDivision::AddLightDataToPartitionsQ(const C3dScene &pScene, const bool pDynamic)
{
	for(size_t p=0;p<mPartitionsQ.size();++p)
	{
		auto &part = mPartitionsQ.at(p);

		if(pDynamic) part.ResetLightsToStatic();

		// Pointlights
		for(size_t pl=0;pl<pScene.GetNrLightsPoint(false);++pl)
		{
			auto &pLight = pScene.GetLightPoint(pl);
			if(pLight.IsDynamic() == pDynamic)
			{
				if(PHYSMATH::CBaseCollision::AABBSphereIntersect(part.BV.AABBWorld, PHYSMATH::CR_SPHERE(pLight.GetTransform().CurrState.Pos, pLight.GetRange())))
				{
					part.PointLightsAffected.push_back(pl);
				}
			}
		}
		// Spotlights
		for(size_t sl=0;sl<pScene.GetNrLightsSpot(false);++sl)
		{
			auto &sLight = pScene.GetLightSpot(sl);
			if(sLight.IsDynamic() == pDynamic)
			{
				if(PHYSMATH::CBaseCollision::AABBSphereIntersect(part.BV.AABBWorld, PHYSMATH::CR_SPHERE(sLight.GetTransform().CurrState.Pos, sLight.GetRange())))
				{
					part.SpotLightsAffected.push_back(sl);
				}
			}
		}
		// Capsule lights
		for(size_t cl=0;cl<pScene.GetNrLightsCapsule(false);++cl)
		{
			auto &cLight = pScene.GetLightCapsule(cl);
			if(cLight.IsDynamic() == pDynamic)
			{
				if(PHYSMATH::CBaseCollision::AABBSphereIntersect(part.BV.AABBWorld, PHYSMATH::CR_SPHERE(cLight.GetTransform().CurrState.Pos, cLight.GetRange())))
				{
					part.CapsuleLightsAffected.push_back(cl);
				}
			}
		}

		// store static lights data
		if(!pDynamic) part.SaveLightsStatic();
	}
}

/**************************************************************************************/
/***							CREATE INST PART IDS				 		PRIVATE	***/
/*** ==> usage: stores all mesh instances IDs and partition IDs for lookup 			***/
/*** ==> uses 2 different arrays with same index (SOA)								***/
/**************************************************************************************/

void CSpatialDivision::CreateInstPartIds()
{
	mMeshInstIds.clear();
	mMeshInstPartIds.clear();

	for(size_t p=0;p<mPartitions.size();++p)
	{
		auto &part = mPartitions.at(p);
		for(size_t mi=0;mi<part.MeshInstances.size();++mi)
		{
			mMeshInstIds.push_back(part.MeshInstances.at(mi));
			mMeshInstPartIds.push_back(p);
		}
	}
}

/**************************************************************************************/
/***							SORT MESHINST AABB AXIS						PRIVATE	***/
/*** ==> usage: to create the mesh intance indices sorted on a given axis  			***/
/*** ==> looks up the AABB center for that axis and returns the sorted indices		***/
/**************************************************************************************/

std::vector<uint> CSpatialDivision::SortMeshInstAABBAxis(const C3dScene &pScene, const uint pAxis, const std::vector<uint> pInstArray)
{
	std::vector<float> meshInstCenterAxis;
	std::vector<uint> sortIndex;

	if(pAxis > 2) return sortIndex;		// Invalid axis

	bool usesIndex = (pInstArray.size() != 0);
	size_t nrInst = pScene.GetNrMeshInst();
	if(usesIndex) nrInst = pInstArray.size();

	// store all instances AABB center - for requested axis
	for(size_t mi=0;mi<nrInst;++mi)
	{
		uint index = mi;
		if(usesIndex) index = pInstArray.at(mi);

		float tAxis = 0.0f;
		if(pAxis == 0) tAxis = pScene.GetMeshInst(index).GetBV().AABBWorld.Center.x;
		if(pAxis == 1) tAxis = pScene.GetMeshInst(index).GetBV().AABBWorld.Center.y;
		if(pAxis == 2) tAxis = pScene.GetMeshInst(index).GetBV().AABBWorld.Center.z;

		meshInstCenterAxis.push_back(tAxis);
		sortIndex.push_back(mi);
	}

	// sort the index, based on AABB ceneter X (low to high)
	std::sort(sortIndex.begin(), sortIndex.end(), [&](int a, int b)
	{ return meshInstCenterAxis[a] < meshInstCenterAxis[b]; } );

	// apply index if needed
	if(usesIndex)
	{
		std::vector<uint> result;
		for(size_t r=0;r<nrInst;++r)
		{
			result.push_back(pInstArray.at(sortIndex.at(r)));
		}
		return result;
	}
	return sortIndex;
}




/**************************************************************************************/
/***								GET NR PARTITIONS			 	  		 CONST ***/
/*** ==> usage: to retrieve the total number of partitions							***/
/*** ==> returns the size of the std::vector with partitions						***/
/**************************************************************************************/

uint CSpatialDivision::GetNrPartitions() const
{
	return mPartitions.size();
}

/**************************************************************************************/
/***								GET PARTITION			 		  		 CONST ***/
/*** ==> usage: to retrieve a reference to a certain partition						***/
/*** ==> returns const ref to requested partition, or partition 0 for invalid index	***/
/**************************************************************************************/

const SCENE_PARTITION& CSpatialDivision::GetPartition(const uint pIndex) const
{
	if(pIndex <= mPartitions.size()) return mPartitions.at(pIndex);
	return mPartitions.at(0);
}


SCENE_PARTITION_Q* CSpatialDivision::GetPartitionPtrQ(const uint pIndex)
{
	//return &mPartitions.at(0);
	if(pIndex <= mPartitionsQ.size()) return &mPartitionsQ.at(pIndex);
	return &mPartitionsQ.at(0);
}


}
}