#ifndef BOX_HXX
#define BOX_HXX

#include "Ray.hxx"

class Box
{
public:
	Vec3f min,max;

	Box() 
	{ 
		Clear(); 
	};

	inline void Extend(Vec3f a)
	{ 
		min = Min(a,min); 
		max = Max(a,max); 
	}

	inline void Clear()
	{ 
		min = Vec3f(Infinity,Infinity,Infinity); 
		max = Vec3f(-Infinity,-Infinity,-Infinity); 
	}

	inline void Extend(Box box)
	{
		Extend(box.min);
		Extend(box.max);
	}

	//Note: Return std::make_pair(FLT_MAX, -FLT_MAX), if no intersection
	//	has been found
	std::pair<float, float> Intersect(const Ray &ray)
	{
		float d0 = -FLT_MAX, d1 = FLT_MAX;

		if(fabs(ray.dir.x) > Epsilon)
		{
			d0 = (min.x - ray.org.x) / ray.dir.x;
			d1 = (max.x - ray.org.x) / ray.dir.x;
			if(d1 < d0)
				std::swap(d0, d1);
		}

		if(fabs(ray.dir.y) > Epsilon)
		{
			float t0, t1;
			t0 = (min.y - ray.org.y) / ray.dir.y;
			t1 = (max.y - ray.org.y) / ray.dir.y;
			if(t1 < t0)
				std::swap(t0, t1);
			d0 = max(d0, t0);
			d1 = min(d1, t1);
		}

		if(fabs(ray.dir.z) > Epsilon)
		{
			float t0, t1;
			t0 = (min.z - ray.org.z) / ray.dir.z;
			t1 = (max.z - ray.org.z) / ray.dir.z;
			if(t1 < t0)
				std::swap(t0, t1);
			d0 = max(d0, t0);
			d1 = min(d1, t1);
		}

		if(d1 < d0 || d0 == -FLT_MAX)
			return std::make_pair(FLT_MAX, -FLT_MAX);
		else
			return std::make_pair(d0, d1);
	}
};

#endif
