#ifndef Magnum_Math_Matrix_h #define Magnum_Math_Matrix_h /* This file is part of Magnum. Copyright © 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019 Vladimír Vondruš Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /** @file * @brief Class @ref Magnum::Math::Matrix, alias @ref Magnum::Math::Matrix2x2, @ref Magnum::Math::Matrix3x3, @ref Magnum::Math::Matrix4x4 */ #include "Magnum/Math/RectangularMatrix.h" namespace Magnum { namespace Math { namespace Implementation { template struct MatrixDeterminant; template constexpr Vector valueOrIdentityVector(Sequence, const RectangularMatrix& other) { return {(col < otherSize && row < otherSize ? other[col][row] : col == row ? T{1} : T{0})...}; } template constexpr Vector valueOrIdentityVector(const RectangularMatrix& other) { return valueOrIdentityVector(typename Implementation::GenerateSequence::Type(), other); } } /** @brief Square matrix @tparam size Matrix size @tparam T Data type See @ref matrix-vector for brief introduction. @configurationvalueref{Magnum::Math::Matrix} @see @ref Matrix2x2, @ref Matrix3x3, @ref Matrix4x4 */ template class Matrix: public RectangularMatrix { public: enum: std::size_t { Size = size /**< Matrix size */ }; /** * @brief Default constructor * * Equivalent to @ref Matrix(IdentityInitT, T). */ constexpr /*implicit*/ Matrix() noexcept: RectangularMatrix{typename Implementation::GenerateSequence::Type(), Vector(T(1))} {} /** * @brief Identity constructor * * Creates an identity matrix. @p value allows you to specify value on * diagonal. */ constexpr explicit Matrix(IdentityInitT, T value = T(1)) noexcept: RectangularMatrix{typename Implementation::GenerateSequence::Type(), Vector(value)} {} /** @copydoc RectangularMatrix::RectangularMatrix(ZeroInitT) */ constexpr explicit Matrix(ZeroInitT) noexcept: RectangularMatrix{ZeroInit} {} /** @copydoc RectangularMatrix::RectangularMatrix(NoInitT) */ constexpr explicit Matrix(NoInitT) noexcept: RectangularMatrix{NoInit} {} /** @brief Construct matrix from column vectors */ template constexpr /*implicit*/ Matrix(const Vector& first, const U&... next) noexcept: RectangularMatrix(first, next...) {} /** @brief Construct matrix with one value for all elements */ constexpr explicit Matrix(T value) noexcept: RectangularMatrix{typename Implementation::GenerateSequence::Type(), value} {} /** * @brief Construct matrix from another of different type * * Performs only default casting on the values, no rounding or * anything else. Example usage: * * @snippet MagnumMath.cpp Matrix-conversion */ template constexpr explicit Matrix(const RectangularMatrix& other) noexcept: RectangularMatrix(other) {} /** @brief Construct matrix from external representation */ template::from(std::declval()))> constexpr explicit Matrix(const U& other): RectangularMatrix(Implementation::RectangularMatrixConverter::from(other)) {} /** * @brief Construct matrix by slicing or expanding another of a different size * * If the other matrix is larger, takes only the first @cpp size @ce * columns and rows from it; if the other matrix is smaller, it's * expanded to an identity (ones on diagonal, zeros elsewhere). */ template constexpr explicit Matrix(const RectangularMatrix& other) noexcept: Matrix{typename Implementation::GenerateSequence::Type(), other} {} /** @brief Copy constructor */ constexpr /*implicit*/ Matrix(const RectangularMatrix& other) noexcept: RectangularMatrix(other) {} /** * @brief Whether the matrix is orthogonal * * The matrix is orthogonal if its transpose is equal to its inverse: @f[ * Q^T = Q^{-1} * @f] * @see @ref transposed(), @ref inverted(), * @ref Matrix3::isRigidTransformation(), * @ref Matrix4::isRigidTransformation() */ bool isOrthogonal() const; /** * @brief Trace of the matrix * * @f[ * tr(A) = \sum_{i=1}^n a_{i,i} * @f] */ T trace() const { return RectangularMatrix::diagonal().sum(); } /** @brief Matrix without given column and row */ Matrix ij(std::size_t skipCol, std::size_t skipRow) const; /** * @brief Determinant * * Returns `0` if the matrix is noninvertible and `1` if the matrix is * orthogonal. Computed recursively using Laplace's formula: @f[ * \det(A) = \sum_{j=1}^n (-1)^{i+j} a_{i,j} \det(A^{i,j}) * @f] @f$ A^{i, j} @f$ is matrix without i-th row and j-th column, see * @ref ij(). The formula is expanded down to 2x2 matrix, where the * determinant is computed directly: @f[ * \det(A) = a_{0, 0} a_{1, 1} - a_{1, 0} a_{0, 1} * @f] */ T determinant() const { return Implementation::MatrixDeterminant()(*this); } /** * @brief Inverted matrix * * Computed using Cramer's rule: @f[ * A^{-1} = \frac{1}{\det(A)} Adj(A) * @f] * See @ref invertedOrthogonal(), @ref Matrix3::invertedRigid() and * @ref Matrix4::invertedRigid() which are faster alternatives for * particular matrix types. * @see @ref Algorithms::gaussJordanInverted() * @m_keyword{inverse(),GLSL inverse(),} */ Matrix inverted() const; /** * @brief Inverted orthogonal matrix * * Equivalent to @ref transposed(), expects that the matrix is * orthogonal. @f[ * A^{-1} = A^T * @f] * @see @ref inverted(), @ref isOrthogonal(), * @ref Matrix3::invertedRigid(), * @ref Matrix4::invertedRigid() */ Matrix invertedOrthogonal() const { CORRADE_ASSERT(isOrthogonal(), "Math::Matrix::invertedOrthogonal(): the matrix is not orthogonal:" << Corrade::Utility::Debug::Debug::newline << *this, {}); return RectangularMatrix::transposed(); } #ifndef DOXYGEN_GENERATING_OUTPUT /* Reimplementation of functions to return correct type */ Matrix operator*(const Matrix& other) const { return RectangularMatrix::operator*(other); } template RectangularMatrix operator*(const RectangularMatrix& other) const { return RectangularMatrix::operator*(other); } Vector operator*(const Vector& other) const { return RectangularMatrix::operator*(other); } Matrix transposed() const { return RectangularMatrix::transposed(); } MAGNUM_RECTANGULARMATRIX_SUBCLASS_IMPLEMENTATION(size, size, Matrix) #endif private: friend struct Implementation::MatrixDeterminant; /* Implementation for RectangularMatrix::RectangularMatrix(const RectangularMatrix&) */ template constexpr explicit Matrix(Implementation::Sequence, const RectangularMatrix& other) noexcept: RectangularMatrix{Implementation::valueOrIdentityVector(other)...} {} }; /** @brief 2x2 matrix Convenience alternative to `Matrix<2, T>`. See @ref Matrix for more information. @see @ref Magnum::Matrix2x2, @ref Magnum::Matrix2x2d */ #ifndef CORRADE_MSVC2015_COMPATIBILITY /* Multiple definitions still broken */ template using Matrix2x2 = Matrix<2, T>; #endif /** @brief 3x3 matrix Convenience alternative to `Matrix<3, T>`. See @ref Matrix for more information. Note that this is different from @ref Matrix3, which contains additional functions for transformations in 2D. @see @ref Magnum::Matrix3x3, @ref Magnum::Matrix3x3d */ #ifndef CORRADE_MSVC2015_COMPATIBILITY /* Multiple definitions still broken */ template using Matrix3x3 = Matrix<3, T>; #endif /** @brief 4x4 matrix Convenience alternative to `Matrix<4, T>`. See @ref Matrix for more information. Note that this is different from @ref Matrix4, which contains additional functions for transformations in 3D. @see @ref Magnum::Matrix4x4, @ref Magnum::Matrix4x4d */ #ifndef CORRADE_MSVC2015_COMPATIBILITY /* Multiple definitions still broken */ template using Matrix4x4 = Matrix<4, T>; #endif MAGNUM_MATRIX_OPERATOR_IMPLEMENTATION(Matrix) #ifndef DOXYGEN_GENERATING_OUTPUT #define MAGNUM_MATRIX_SUBCLASS_IMPLEMENTATION(size, Type, VectorType) \ VectorType& operator[](std::size_t col) { \ return static_cast&>(Matrix::operator[](col)); \ } \ constexpr const VectorType operator[](std::size_t col) const { \ return VectorType(Matrix::operator[](col)); \ } \ VectorType row(std::size_t row) const { \ return VectorType(Matrix::row(row)); \ } \ \ Type operator*(const Matrix& other) const { \ return Matrix::operator*(other); \ } \ template RectangularMatrix operator*(const RectangularMatrix& other) const { \ return Matrix::operator*(other); \ } \ VectorType operator*(const Vector& other) const { \ return Matrix::operator*(other); \ } \ \ Type transposed() const { return Matrix::transposed(); } \ constexpr VectorType diagonal() const { return Matrix::diagonal(); } \ Type inverted() const { return Matrix::inverted(); } \ Type invertedOrthogonal() const { \ return Matrix::invertedOrthogonal(); \ } namespace Implementation { template struct MatrixDeterminant { T operator()(const Matrix& m) { T out(0); /* Using ._data[] instead of [] to avoid function call indirection on debug builds (saves a lot, yet doesn't obfuscate too much) */ for(std::size_t col = 0; col != size; ++col) out += ((col & 1) ? -1 : 1)*m._data[col]._data[0]*m.ij(col, 0).determinant(); return out; } }; /* This is not *critically* needed here (the specializations for 2x2 and 1x1 are technically enough to make things work), but together with the raw data access it speeds up the debug build five times, so I think it's worth to have it */ template struct MatrixDeterminant<3, T> { constexpr T operator()(const Matrix<3, T>& m) const { /* Using ._data[] instead of [] to avoid function call indirection on debug builds (saves a lot, yet doesn't obfuscate too much) */ return m._data[0]._data[0]*((m._data[1]._data[1]*m._data[2]._data[2]) - (m._data[2]._data[1]*m._data[1]._data[2])) - m._data[0]._data[1]*(m._data[1]._data[0]*m._data[2]._data[2] - m._data[2]._data[0]*m._data[1]._data[2]) + m._data[0]._data[2]*(m._data[1]._data[0]*m._data[2]._data[1] - m._data[2]._data[0]*m._data[1]._data[1]); } }; template struct MatrixDeterminant<2, T> { constexpr T operator()(const Matrix<2, T>& m) const { /* Using ._data[] instead of [] to avoid function call indirection on debug builds (saves a lot, yet doesn't obfuscate too much) */ return m._data[0]._data[0]*m._data[1]._data[1] - m._data[1]._data[0]*m._data[0]._data[1]; } }; template struct MatrixDeterminant<1, T> { constexpr T operator()(const Matrix<1, T>& m) const { /* Using ._data[] instead of [] to avoid function call indirection on debug builds (saves a lot, yet doesn't obfuscate too much) */ return m._data[0]._data[0]; } }; template struct StrictWeakOrdering>: StrictWeakOrdering> {}; } #endif template bool Matrix::isOrthogonal() const { /* Using ._data[] instead of [] to avoid function call indirection on debug builds (saves a lot, yet doesn't obfuscate too much) */ /* Normality */ for(std::size_t i = 0; i != size; ++i) if(!RectangularMatrix::_data[i].isNormalized()) return false; /* Orthogonality */ for(std::size_t i = 0; i != size-1; ++i) for(std::size_t j = i+1; j != size; ++j) if(dot(RectangularMatrix::_data[i], RectangularMatrix::_data[j]) > TypeTraits::epsilon()) return false; return true; } template Matrix Matrix::ij(const std::size_t skipCol, const std::size_t skipRow) const { Matrix out{NoInit}; /* Using ._data[] instead of [] to avoid function call indirection on debug builds (saves a lot, yet doesn't obfuscate too much) */ for(std::size_t col = 0; col != size-1; ++col) for(std::size_t row = 0; row != size-1; ++row) out._data[col]._data[row] = RectangularMatrix:: _data[col + (col >= skipCol)] ._data[row + (row >= skipRow)]; return out; } template Matrix Matrix::inverted() const { Matrix out{NoInit}; const T _determinant = determinant(); /* Using ._data[] instead of [] to avoid function call indirection on debug builds (saves a lot, yet doesn't obfuscate too much) */ for(std::size_t col = 0; col != size; ++col) for(std::size_t row = 0; row != size; ++row) out._data[col]._data[row] = (((row+col) & 1) ? -1 : 1)*ij(row, col).determinant()/_determinant; return out; } }} #endif