#include #include #include #include "vector_heap.h" Vector* vec_new(double x, double y, double z) { Vector* result = (Vector*) malloc(sizeof(Vector)); if (!result) { /* malloc failed */ return NULL; } result->x = x; result->y = y; result->z = z; return result; } Vector* vec_new_null() { return vec_new(0.0, 0.0, 0.0); } Vector* vec_mul_scalar(Vector* v, double scalar) { return vec_new(v->x * scalar, v->y * scalar, v->z * scalar); } double vec_mul_dot(Vector* first, Vector *second) { return first->x * second->x + first->y * second->y + first->z * second->z; } Vector* vec_mul_cross(Vector* first, Vector *second) { return vec_new(first->y * second->z - first->z * second->y, first->z * second->x - first->x * second->z, first->x * second->y - first->y * second->x); } Vector* vec_add(Vector* first, Vector *second) { return vec_new(first->x + second->x, first->y + second->y, first->z + second->z); } Vector* vec_sub(Vector* first, Vector *second) { return vec_new(first->x - second->x, first->y - second->y, first->z - second->z); } int vec_equals(Vector* first, Vector *second) { return (first->x == second->x) && (first->y == second->y) && (first->z == second->z); } #define MAX_LENGTH 128 char* vec_to_str(Vector* v) { char* result = (char*) malloc(MAX_LENGTH + 1); snprintf(result, MAX_LENGTH, "[ %.2f %.2f %.2f ]", v->x, v->y, v->z); return result; } void vec_print(Vector* v) { char* str = vec_to_str(v); printf("%s", str); free(str); } double vec_length(Vector* v) { return sqrt(v->x * v->x + v->y * v->y + v->z * v->z); } Vector* vec_norm(Vector* v) { double length = vec_length(v); if (length == 0.0) { /* no norm for a null vector */ return NULL; } return vec_new(v->x / length, v->y / length, v->z / length); } int vec_collinear(Vector* first, Vector* second) { Vector* cross = vec_mul_cross(first, second); Vector* null = vec_new_null(); int result = vec_equals(null, cross); free(cross); free(null); return result; }