From 1ed11aa3db7edbcd59c5f0661e97d915afbab77b Mon Sep 17 00:00:00 2001 From: josh Date: Fri, 29 Dec 2023 12:32:17 -0500 Subject: [PATCH] Implement Mat3x3 Determinant, Inverse, Transpose methods --- src/J3ML/LinearAlgebra/Matrix3x3.cpp | 59 ++++++++++++++++++++++++++++ 1 file changed, 59 insertions(+) diff --git a/src/J3ML/LinearAlgebra/Matrix3x3.cpp b/src/J3ML/LinearAlgebra/Matrix3x3.cpp index 9a771d5..cf502d6 100644 --- a/src/J3ML/LinearAlgebra/Matrix3x3.cpp +++ b/src/J3ML/LinearAlgebra/Matrix3x3.cpp @@ -100,5 +100,64 @@ namespace LinearAlgebra { } + float Matrix3x3::Determinant() const { + const float a = elems[0][0]; + const float b = elems[0][1]; + const float c = elems[0][2]; + const float d = elems[1][0]; + const float e = elems[1][1]; + const float f = elems[1][2]; + const float g = elems[2][0]; + const float h = elems[2][1]; + const float i = elems[2][2]; + + // Aight, what the fuck? + return a*(e*i - f*h) + b*(f*g - d*i) + c*(d*h - e*g); + } + + Matrix3x3 Matrix3x3::Inverse() const { + // Compute the inverse directly using Cramer's rule + // Warning: This method is numerically very unstable! + float d = Determinant(); + + d = 1.f / d; + + Matrix3x3 i = { + d * (At(1, 1) * At(2, 2) - At(1, 2) * At(2, 1)), + d * (At(0, 2) * At(2, 1) - At(0, 1) * At(2, 2)), + d * (At(0, 1) * At(1, 2) - At(0, 2) * At(1, 1)), + + d * (At(1, 2) * At(2, 0) - At(1, 0) * At(2, 2)), + d * (At(0, 0) * At(2, 2) - At(0, 2) * At(2, 0)), + d * (At(0, 2) * At(1, 0) - At(0, 0) * At(1, 2)), + + d * (At(1, 0) * At(2, 1) - At(1, 1) * At(2, 0)), + d * (At(2, 0) * At(0, 1) - At(0, 0) * At(2,1)), + d * (At(0,0) * At(1, 1) - At(0, 1) * At(1, 0)) + }; + + return i; + } + + Matrix3x3 Matrix3x3::Transpose() const { + auto m00 = this->elems[0][0]; + auto m01 = this->elems[0][1]; + auto m02 = this->elems[0][2]; + + auto m10 = this->elems[1][0]; + auto m11 = this->elems[1][1]; + auto m12 = this->elems[1][2]; + + auto m20 = this->elems[2][0]; + auto m21 = this->elems[2][1]; + auto m22 = this->elems[2][2]; + + return { + m00, m10, m20, + m01, m11, m21, + m02, m12, m22 + } + } + }