/*
 * Copyright (c) 2008-2009 Bill Whitacre http://rampancy.g0dsoft.com
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
*/

#include "aabb.h"

void aabb_resolve_order(aabb *box)
{
	aabb tempbox;
	tempbox=*box;

	box->a.x=tempbox.a.x<tempbox.b.x?tempbox.a.x:tempbox.b.x;
	box->a.y=tempbox.a.y<tempbox.b.y?tempbox.a.y:tempbox.b.y;
	box->b.x=tempbox.b.x<tempbox.a.x?tempbox.a.x:tempbox.b.x;
	box->b.y=tempbox.b.y<tempbox.a.y?tempbox.a.y:tempbox.b.y;
}

int aabb_is_aabb_overlapping(aabb box1,aabb box2)
{
	rat_real x_int,y_int;
	
	x_int=box1.a.x<box2.b.x?box2.a.x-box1.b.x:box1.a.x-box2.b.x;
	y_int=box1.a.y<box2.b.y?box2.a.y-box1.b.y:box1.a.y-box2.b.y;

	return x_int<0&&y_int<0;
}
void rat_points_bounding_box(vector2 *pts,unsigned int numpts,aabb *bbox)
{
	register unsigned int i;

	bbox->a=pts[0];
	bbox->b=pts[0];

	for (i=1; i<numpts; i++)
	{
		bbox->a.x=pts[i].x<bbox->a.x?pts[i].x:bbox->a.x;
		bbox->a.y=pts[i].y<bbox->a.y?pts[i].y:bbox->a.y;
		bbox->b.x=pts[i].x>bbox->b.x?pts[i].x:bbox->b.x;
		bbox->b.y=pts[i].y>bbox->b.y?pts[i].y:bbox->b.y;
	}
}

void aabb_init(aabb *box)
{
	box->a.x=0;
	box->a.y=0;
	box->b.x=0;
	box->b.y=0;
}

void aabb_set(aabb *box,vector2 a,vector2 b,int resolveorder)
{
	box->a=a;
	box->b=b;
	if (resolveorder) aabb_resolve_order(box);
}

rat_real aabb_width(aabb box)
{
	rat_real abw=box.b.x-box.a.x;
	return abw>0?abw:-abw;
}

rat_real aabb_height(aabb box)
{
	rat_real abh=box.b.y-box.a.y;
	return abh>0?abh:-abh;
}

rat_real aabb_area(aabb box)
{
	return aabb_width(box)*aabb_height(box);
}

int aabb_is_point_inside(aabb box,vector2 point)
{
	return point.x<=box.b.x&&point.x>=box.a.x&&point.y<=box.b.y&&point.y>=box.a.y;
}

int aabb_is_aabb_inside(aabb box1,aabb box2)
{
	return box1.a.x>=box2.a.x&&box1.b.x<=box2.b.x&&box1.a.y>=box2.a.y&&box1.b.y<=box2.b.y;
}

