From 8f8f5ad0a284d341c3d4dfa24f7af8106e4feba8 Mon Sep 17 00:00:00 2001 From: hasufell Date: Sat, 10 May 2014 18:35:22 +0200 Subject: [PATCH] Add normalize_vector() function --- src/vec_math.c | 34 ++++++++++++++++++++++++++++++++++ src/vec_math.h | 1 + 2 files changed, 35 insertions(+) diff --git a/src/vec_math.c b/src/vec_math.c index b66f707..7444a52 100644 --- a/src/vec_math.c +++ b/src/vec_math.c @@ -20,6 +20,9 @@ #include "types.h" #include "vec_math.h" +#include +#include +#include #include #include @@ -51,6 +54,37 @@ bool vector_product(vector *a, vector *b, vector *c) return true; } +/** + * Normalize a vector into a unit vector + * of length 1. This function is aliasing safe. + * + * @param a vector + * @param b vector + * @return true/false for success/failure + */ +bool normalize_vector(vector *a, vector *b) +{ + if (!a || !b) + return false; + + vector a_tmp; + float vector_length; + + copy_vector(a, &a_tmp); + + vector_length = sqrt((a_tmp.x * a_tmp.x) + + (a_tmp.y * a_tmp.y) + (a_tmp.z * a_tmp.z)); + + if (errno == EDOM) + return false; + + b->x = a_tmp.x / vector_length; + b->y = a_tmp.y / vector_length; + b->z = a_tmp.z / vector_length; + + return true; +} + /** * Copy coordinates from vector a to vector b. * diff --git a/src/vec_math.h b/src/vec_math.h index 77923ec..ba3bbed 100644 --- a/src/vec_math.h +++ b/src/vec_math.h @@ -26,6 +26,7 @@ bool vector_product(vector *a, vector *b, vector *c); +bool normalize_vector(vector *a, vector *b); bool copy_vector(vector *a, vector *b);