3D Math - Support Functions
From Wikiid
This algorithms described in this document rely on a set of simple geometry routines and structures:
Contents
Data types
struct Point { float x, y, z ; } ;
typedef Point Vector ;
struct Sphere { float radius ; Point center ; } ;
struct Triangle { Point a, b, c ; } ;
struct Plane { float A, B, C, D ; } ;
struct AxialBox { Point min, max ; } ;
struct Line { Point start ; Vector vec ; } ;
struct LineSeg { Point start ; Point end ; } ;
Normalize a vector
float Normalize ( Vector *dst, Vector *src )
{
float leng = sqrt ( Square ( src->x ) +
Square ( src->y ) +
Square ( src->z ) ) ;
if ( leng <= 0.0f )
{
dst->x = 0.0 ;
dst->y = 0.0 ;
dst->z = 1.0 ;
return 0.0 ;
}
float recip = 1.0f / leng ;
dst->x = src->x * recip ;
dst->y = src->y * recip ;
dst->z = src->z * recip ;
return leng ; /* Sometimes it's handy to know this value. */
}
Cross Product (aka Vector Product)
void CrossProduct ( Vector *dst, Vector *v1, Vector *v2 )
{
dst->x = v1->y * v2->z - v1->z * v2->y ;
dst->y = v1->z * v2->x - v1->x * v2->z ;
dst->z = v1->x * v2->y - v1->y * v2->x ;
}
Dot Product (aka Scalar Product)
float DotProduct ( Point *p1, Point *p2 )
{
return p1->x * p2->x + p1->y * p2->y + p1->z * p2->z ;
}
Square a number
float Square ( float x ) { return x * x ; } ;
The square of the distance between two points
float SqrDistancePt3 ( Point *p1, Point *p2 )
{
return Square ( p1->x - p2->x ) +
Square ( p1->y - p2->y ) +
Square ( p1->z - p2->z ) ;
}