Browse Source

Add vector reflection via a normal vector.

Godzil 4 years ago
parent
commit
aeb4669162
3 changed files with 26 additions and 1 deletions
  1. 1 1
      source/include/tuple.h
  2. 5 0
      source/tuple.cpp
  3. 20 0
      tests/tuple_test.cpp

+ 1 - 1
source/include/tuple.h

@@ -41,8 +41,8 @@ public:
     double magnitude();
     Tuple normalise();
     double dot(const Tuple &b);
-
     Tuple cross(const Tuple &b) const;
+    Tuple reflect(const Tuple &normal);
 };
 
 class Point: public Tuple

+ 5 - 0
source/tuple.cpp

@@ -33,4 +33,9 @@ Tuple Tuple::cross(const Tuple &b) const
                  this->z * b.x - this->x * b.z,
                  this->x * b.y - this->y * b.x,
                  0);
+}
+
+Tuple Tuple::reflect(const Tuple &normal)
+{
+    return *this - normal * 2 * this->dot(normal);
 }

+ 20 - 0
tests/tuple_test.cpp

@@ -181,3 +181,23 @@ TEST(TuplesTests, Cross_product_of_two_vector)
     ASSERT_EQ(a.cross(b), Vector(-1, 2, -1));
     ASSERT_EQ(b.cross(a), Vector(1, -2, 1));
 }
+
+TEST(TuplesTests, Reflecting_a_vector_approaching_at_45)
+{
+    Vector v = Vector(1, -1, 0); /* Vector */
+    Vector n = Vector(0, 1, 0); /* Normal */
+
+    Tuple r = v.reflect(n);
+
+    ASSERT_EQ(r, Vector(1, 1, 0));
+}
+
+TEST(TuplesTests, Reflecting_a_vector_off_a_slanted_surface)
+{
+    Vector v = Vector(0, -1, 0); /* Vector */
+    Vector n = Vector(sqrt(2)/2, sqrt(2)/2, 0); /* Normal */
+
+    Tuple r = v.reflect(n);
+
+    ASSERT_EQ(r, Vector(1, 0, 0));
+}