Add vector reflection via a normal vector.

This commit is contained in:
Godzil
2020-02-17 15:56:08 +00:00
parent a8194169c5
commit aeb4669162
3 changed files with 26 additions and 1 deletions

View File

@@ -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

View File

@@ -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);
}

View File

@@ -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));
}