From 3a5dd0490c7c9be0277ecee31b1bb2de58637608 Mon Sep 17 00:00:00 2001 From: Kyle Isom Date: Sun, 4 Aug 2019 23:29:56 -0700 Subject: [PATCH] Add cross product. --- include/wrmath/geom/vector.h | 19 +++++++++++++++++++ test/vector_test.cc | 27 +++++++++++++++++++++++++-- 2 files changed, 44 insertions(+), 2 deletions(-) diff --git a/include/wrmath/geom/vector.h b/include/wrmath/geom/vector.h index 2af42c7..89e39fb 100644 --- a/include/wrmath/geom/vector.h +++ b/include/wrmath/geom/vector.h @@ -15,6 +15,7 @@ namespace wr { namespace geom { + /** * Vector provides a standard interface for dimensionless fixed-size * vectors. Once instantiated, they cannot be modified. Note that while @@ -203,6 +204,24 @@ public: } + /** + * Compute the cross product of two vectors. This is only defined + * over three-dimensional vectors. + * @param other Another 3D vector. + * @return The cross product vector. + */ + Vector + cross(const Vector &other) + { + assert(N == 3); + return Vector { + (this->arr[1] * other.arr[2]) - (other.arr[1] * this->arr[2]), + -((this->arr[0] * other.arr[2]) - (other.arr[0] * this->arr[2])), + (this->arr[0] * other.arr[1]) - (other.arr[0] * this->arr[1]) + }; + } + + /** * Perform vector addition with another vector. * @param other The vector to be added. diff --git a/test/vector_test.cc b/test/vector_test.cc index 15b4932..e880558 100644 --- a/test/vector_test.cc +++ b/test/vector_test.cc @@ -172,7 +172,7 @@ TEST(Vector3FloatTests, ParallelOrthogonalVectors) } -TEST(Vector3FloatTests, Projections) +TEST(Vector4FloatTests, Projections) { geom::Vector4f a {3.009, -6.172, 3.692, -2.510}; geom::Vector4f b {6.404, -9.144, 2.759, 8.718}; @@ -184,6 +184,17 @@ TEST(Vector3FloatTests, Projections) } +TEST(Vector3FloatTests, CrossProduct) +{ + geom::Vector3f a {8.462, 7.893, -8.187}; + geom::Vector3f b {6.984, -5.975, 4.778}; + geom::Vector3f c {-11.2046, -97.6094, -105.685}; + + c.setEpsilon(0.001); + EXPECT_EQ(c, a.cross(b)); +} + + TEST(Vector3DoubleTests, Magnitude) { geom::Vector3d v3d{1.0, -2.0, 3.0}; @@ -302,7 +313,7 @@ TEST(Vector3DoubleTests, ParallelOrthogonalVectors) } -TEST(Vector3DoubleTests, Projections) +TEST(Vector4DoubleTests, Projections) { geom::Vector4d a {3.009, -6.172, 3.692, -2.510}; geom::Vector4d b {6.404, -9.144, 2.759, 8.718}; @@ -314,6 +325,18 @@ TEST(Vector3DoubleTests, Projections) } +TEST(Vector3DoubleTests, CrossProduct) +{ + geom::Vector3d a {8.462, 7.893, -8.187}; + geom::Vector3d b {6.984, -5.975, 4.778}; + geom::Vector3d c {-11.2046, -97.6094, -105.685}; + + c.setEpsilon(0.001); // double trouble + EXPECT_EQ(c, a.cross(b)); +} + + + int main(int argc, char **argv) {