#include "Mix/Geometry/Plane.h"

namespace Mix{ namespace Geometry{

Plane::Plane( void ) :
d( 0.0f )
{
}

Plane::Plane( const Mix::Vector3& n, Float32 nd )
{
	normal = n;
	d = -nd;
}

Plane::Plane( const Mix::Vector3& p1, const Mix::Vector3& p2, const Mix::Vector3& p3 )
{
	Plane::Compute( p1, p2, p3, *this );
}

void Plane::Normalize( void )
{
	Float32 dist = ::sqrtf( normal.x * normal.x + normal.y * normal.y + normal.z * normal.z );

	if( MIX_FLOAT_IS_ZERO( dist ) == False )
	{
		Float32 invDist = ( 1.0f / dist );

		normal.x *= invDist;
		normal.y *= invDist;
		normal.z *= invDist;
		d *= invDist;
	}
	else
	{
		normal.x = 0.0f;
		normal.y = 0.0f;
		normal.z = 0.0f;
		d = 0.0f;
	}
}

void Plane::Compute( const Mix::Vector3& p1, const Mix::Vector3& p2, const Mix::Vector3& p3, Mix::Geometry::Plane& plane )
{
	Mix::Vector3 v1;
	Mix::Vector3 v2;

	v1 = p2 - p1;
	v2 = p3 - p1;

	plane.normal = Mix::Vector3::Cross( v1, v2 );
	plane.normal.Normalize();

	plane.d = -Mix::Vector3::Dot( plane.normal, p1 );
}

}}
