From ae23572b189e7b885aa148a17664e1eb18562ecc Mon Sep 17 00:00:00 2001 From: Sam Hocevar Date: Wed, 19 Jan 2011 20:33:36 +0000 Subject: [PATCH] Implement vector addition, subtraction etc. as well as euclidian distance. --- src/matrix.h | 42 ++++++++++++++++++++++++++++++++---------- 1 file changed, 32 insertions(+), 10 deletions(-) diff --git a/src/matrix.h b/src/matrix.h index fd26733b..ba90c6ae 100644 --- a/src/matrix.h +++ b/src/matrix.h @@ -16,29 +16,52 @@ #if !defined __DH_MATRIX_H__ #define __DH_MATRIX_H__ -#define OPERATORS(elems) \ - inline Vec##elems operator+(Vec##elems const &op) const \ +#include + +#define VECTOR_OP(elems, op) \ + inline Vec##elems operator op(Vec##elems const &val) const \ { \ Vec##elems ret; \ for (int n = 0; n < elems; n++) \ - ret[n] = (*this)[n] + op[n]; \ + ret[n] = (*this)[n] op val[n]; \ return ret; \ - } \ - \ - inline Vec##elems operator-(Vec##elems const &op) const \ + } + +#define SCALAR_OP(elems, op) \ + inline Vec##elems operator op(T const &val) const \ { \ Vec##elems ret; \ for (int n = 0; n < elems; n++) \ - ret[n] = (*this)[n] - op[n]; \ + ret[n] = (*this)[n] op val; \ return ret; \ } +#define OPERATORS(elems) \ + T& operator[](int n) { return *(&x + n); } \ + T const& operator[](int n) const { return *(&x + n); } \ + \ + VECTOR_OP(elems, -) \ + VECTOR_OP(elems, +) \ + VECTOR_OP(elems, *) \ + VECTOR_OP(elems, /) \ + \ + SCALAR_OP(elems, -) \ + SCALAR_OP(elems, +) \ + SCALAR_OP(elems, *) \ + SCALAR_OP(elems, /) \ + \ + inline float len() const \ + { \ + T acc = 0; \ + for (int n = 0; n < elems; n++) \ + acc += (*this)[n] * (*this)[n]; \ + return sqrtf((float)acc); \ + } + template struct Vec2 { Vec2() { x = y = 0; } Vec2(T _x, T _y) { x = _x; y = _y; } - T& operator[](int n) { return *(&x + n); } - T const& operator[](int n) const { return *(&x + n); } OPERATORS(2) @@ -53,7 +76,6 @@ template struct Vec3 { Vec3() { x = y = z = 0; } Vec3(T _x, T _y, T _z) { x = _x; y = _y; z = _z; } - T& operator[](int n) { return *(&x + n); } OPERATORS(3)