/* vector.c: vectoren */

#include <math.h>

#include "vector.h"
#include "Memory.h"
#include "debug.h"

#ifdef BETTER_MEMMAN
static STORAGE *vectorStor = (STORAGE *)NULL;
#define NEWVECTOR()  	(VECTOR *)New(sizeof(VECTOR), &vectorStor)
#define DISPOSEVECTOR(ptr) Dispose((unsigned char *)(ptr), &vectorStor)
#else /*BETTER_MEMMAN*/
#define NEWVECTOR()	(VECTOR *)Alloc(sizeof(VECTOR))
#define DISPOSEVECTOR(ptr) Free((char *)ptr, sizeof(VECTOR))
#endif /*BETTER_MEMMAN*/

static int TotalVectors = 0;

/* creeert een vector met gegeven componenten */
VECTOR *VectorCreate(float x, float y, float z)
{	
	VECTOR *vector;

	vector = NEWVECTOR();

	vector->x = x;
	vector->y = y;
	vector->z = z;

	TotalVectors++;

	return vector;
}

/* vernietigt een vector */
void VectorDestroy(VECTOR *vector)
{
	DISPOSEVECTOR(vector);

	TotalVectors--;
}

/* copieert de vector en geeft een wijzer naar de gecreeerde copij terug */
VECTOR *VectorCopy(VECTOR *vector)
{
	VECTOR *newvector;

	newvector = NEWVECTOR();
	*newvector = *vector;
	return newvector;
}

float VectorNormalize(VECTOR *vector)
{
	float norm;

	norm = VECTORNORM(*vector);
	if (norm < EPSILON)
		return norm;

	VECTORSCALEINVERSE(norm, *vector, *vector);
	return norm;
}

/*
 * Find the "dominant" part of the vector (eg patch-normal).  This
 * is used to turn the point-in-polygon test into a 2D problem.
 */
int VectorDominantCoord(VECTOR *v)
{
	VECTOR anorm;
	float indexval;

	anorm.x = fabs(v->x);
	anorm.y = fabs(v->y);
	anorm.z = fabs(v->z);
	indexval = MAX(anorm.y, anorm.z);
	indexval = MAX(anorm.x, indexval);

	return (indexval == anorm.x ? XNORMAL :
		(indexval == anorm.y ? YNORMAL : ZNORMAL));
}


