From 5866f779154a4f982961b641b8905031e95373ab Mon Sep 17 00:00:00 2001 From: NADAL Jean-Baptiste Date: Fri, 2 Feb 2024 14:50:07 +0100 Subject: [PATCH] [FEAT] Add identity matrix --- raytracing/src/matrix.cpp | 20 ++++++++++++++++++++ raytracing/src/matrix.h | 3 +++ tests/03_matrix.cpp | 23 +++++++++++++++++++++++ 3 files changed, 46 insertions(+) diff --git a/raytracing/src/matrix.cpp b/raytracing/src/matrix.cpp index 8e9f0b5..755d3e3 100644 --- a/raytracing/src/matrix.cpp +++ b/raytracing/src/matrix.cpp @@ -58,6 +58,12 @@ Matrix::Matrix(uint8_t a_rows, uint8_t a_cols) : m_rows(a_rows), m_cols(a_cols) /* ------------------------------------------------------------------------- */ +Matrix::Matrix(const Matrix &an_other) : m_rows(an_other.m_rows), m_cols(an_other.m_cols), m_data(an_other.m_data) +{ +} + +/* ------------------------------------------------------------------------- */ + Matrix::Matrix(const std::initializer_list> &a_values) : m_rows(a_values.size()), m_cols(a_values.size()) { @@ -167,6 +173,20 @@ const Tuple Matrix::operator*(const Tuple &a_tuple) const /* ------------------------------------------------------------------------- */ +Matrix Matrix::identity(void) +{ + Matrix the_identity = { + {1, 0, 0, 0}, + {0, 1, 0, 0}, + {0, 0, 1, 0}, + {0, 0, 0, 1} + }; + + return the_identity; +} + +/* ------------------------------------------------------------------------- */ + bool Matrix::validate_dimensions(const std::initializer_list> &a_values) const { for (const auto &the_row : a_values) diff --git a/raytracing/src/matrix.h b/raytracing/src/matrix.h index 17cdd4f..c6fc741 100644 --- a/raytracing/src/matrix.h +++ b/raytracing/src/matrix.h @@ -43,6 +43,7 @@ namespace Raytracer public: Matrix(void); Matrix(uint8_t a_rows, uint8_t a_cols); + Matrix(const Matrix &an_other); Matrix(const std::initializer_list> &a_values); uint8_t rows(void); @@ -56,6 +57,8 @@ namespace Raytracer const Matrix operator*(const Matrix &a_matrix) const; const Tuple operator*(const Tuple &a_tuple) const; + static Matrix identity(void); + private: bool validate_dimensions(const std::initializer_list> &a_values) const; diff --git a/tests/03_matrix.cpp b/tests/03_matrix.cpp index 5d383fa..0ca4959 100644 --- a/tests/03_matrix.cpp +++ b/tests/03_matrix.cpp @@ -171,3 +171,26 @@ TEST_CASE("[Matrix] a matrix multiplied by a tuple", "[Matrix]") REQUIRE((a * b) == Tuple(18, 24, 33, 1)); } + +/* ------------------------------------------------------------------------- */ + +TEST_CASE("[Matrix] Multiplying a matrix by the identity matrix", "[Matrix]") +{ + Matrix a = { + {0, 1, 2, 4}, + {1, 2, 4, 8}, + {2, 4, 8, 16}, + {4, 8, 16, 32} + }; + + REQUIRE((a * Matrix::identity()) == a); +} + +/* ------------------------------------------------------------------------- */ + +TEST_CASE("[Matrix] Multiplying the identity matrix by a tuple", "[Matrix]") +{ + Tuple a(1, 2, 3, 4); + + REQUIRE((Matrix::identity() * a) == a); +}