/* -----------------------------------------------------------------------------
	GSFramework
	Copyright 2001-2013 Emmanuel Julien. All Rights Reserved.
----------------------------------------------------------------------------- */


		#include "bih/bih.h"

		using namespace GS;
		using namespace GS::BIH;


//------------------------------------------------------------------------------
uint				Tree::IntersectNode(Node *node, MinMax &mm, uint *iarray, uint max)
{
	uint count = 0;

	if	(node->axis == 3)
	{
		if	(node->count > max)
			return 0;

		Memory::Copy(iarray, (uint *)node->p, sizeof(uint) * node->count);
		return node->count;
	}
	else
	{
		if	(mm.mx[node->axis] > node->split[1])
		{
			MinMax sub_mm = mm;
			if	(node->split[1] > sub_mm.mn[node->axis])
				sub_mm.mn[node->axis] = node->split[1];

			uint added = IntersectNode(&((Node *)node->p)[1], sub_mm, iarray/* + count*/, max);
			max -= added; count += added;
		}
		if	(mm.mn[node->axis] < node->split[0])
		{
			MinMax sub_mm = mm;
			if	(node->split[0] < sub_mm.mx[node->axis])
				sub_mm.mx[node->axis] = node->split[0];

			uint added = IntersectNode(&((Node *)node->p)[0], sub_mm, iarray + count, max);
			/*max -= added;*/ count += added;
		}
	}
	return count;
}
uint				Tree::Intersect(MinMax &in_mm, uint *iarray, uint max)
{
	if	(root.IsNull() || !in_mm.TestOverlap(minmax))
		return 0;
	return IntersectNode(root, in_mm, iarray, max);
}
//------------------------------------------------------------------------------
