#ifndef lint
static char *sccsid = "@(#)point.c	1.1 (Steve Hill) 3/9/90";
#endif

/* point.c
 *
 * Functions for creating, copying, freeing, and printing points.
 */

#include <stdio.h>

#include "basetype.h"
#include "error.h"
#include "malloc.h"
#include "matrix.h"
#include "point.h"


/* Point
 *
 * Allocate and initialise a point to (x, y, z).
 */

point_t *
Point(x, y, z)
real_t	x, y, z;
{
	point_t	*point;

	point = (point_t *) malloc(sizeof(point_t));

	if (point == PointNull)
		FatalError(__FILE__, __LINE__, "Point: Out of memory");

	point->x = x;
	point->y = y;
	point->z = z;

	return(point);
}


/* PointCopy
 *
 * Duplicate a point, and return pointer to new one.
 */

point_t *
PointCopy(point)
point_t	*point;
{
	if (point == PointNull)
		return(PointNull);

	return(Point(point->x, point->y, point->z));
}


/* PointLet
 *
 * Assign point2 to point1.
 */

point_t *
PointLet(point1, point2)
point_t	*point1, *point2;
{
	point1->x = point2->x;
	point1->y = point2->y;
	point1->z = point2->z;

	return(point2);
}


/* PointFree
 *
 * De-allocate a point.
 */

void
PointFree(point)
point_t	*point;
{
	if (point == PointNull)
		return;

	(void) free((char *) point);
}


/* PointPrint
 *
 * Print a point to a file.
 */

void
PointPrint(file, point)
FILE	*file;
point_t	*point;
{
	if (point == PointNull)
	{
		fprintf(file, "Null Point\n");
		return;
	}

	fprintf(file, "(%f, %f, %f)", point->x, point->y, point->z);
}


/* PointTransform
 *
 * Move a point using transformation matrix given.
 */

point_t *
PointTransform(point1, point2, matrix)
point_t		*point1, *point2;
matrix_t	*matrix;
{
	real_t	**array = matrix->matrix;

	if (point1 == PointNull)
		point1 = PointZero;

	point1->x = array[0][0] * point2->x + array[1][0] * point2->y +
		    array[2][0] * point2->z + array[3][0];

	point1->y = array[0][1] * point2->x + array[1][1] * point2->y +
		    array[2][1] * point2->z + array[3][1];

	point1->z = array[0][2] * point2->x + array[1][2] * point2->y +
		    array[2][2] * point2->z + array[3][2];

	return(point1);
}
