RSTools 3.1.0
Versatile C++20 utility library
Loading...
Searching...
No Matches
Matrix.hpp
Go to the documentation of this file.
1#pragma once
2
3#include "RST/maths/Utils.hpp"
5
6#include <cmath>
7#include <cstddef>
8#include <initializer_list>
9#include <limits>
10#include <ostream>
11#include <stdexcept>
12#include <utility>
13
14namespace RST::Maths {
18 template <typename T, size_t Rows, size_t Cols>
19 class Matrix {
20 public:
22 constexpr Matrix() noexcept {
23 for (size_t i = 0; i < Rows * Cols; ++i) {
24 m[i] = 0;
25 }
26 size_t min_dim = (Rows < Cols) ? Rows : Cols;
27 for (size_t i = 0; i < min_dim; i++) {
28 (*this)(i, i) = 1;
29 }
30 }
31
33 constexpr explicit Matrix(T value) noexcept {
34 for (size_t i = 0; i < Rows * Cols; ++i) m[i] = value;
35 }
36
39 constexpr Matrix(std::initializer_list<T> list) {
40 if (list.size() != Rows * Cols) {
41 throw std::invalid_argument("Invalid initializer list size for Matrix");
42 }
43 size_t i = 0;
44 for (auto val : list)
45 m[i++] = val;
46 }
47
49 constexpr T& operator[](size_t index) noexcept { return m[index]; }
50 constexpr const T& operator[](size_t index) const noexcept { return m[index]; }
52 constexpr T& operator()(size_t row, size_t col) noexcept { return m[row * Cols + col]; }
53 constexpr const T& operator()(size_t row, size_t col) const noexcept { return m[row * Cols + col]; }
54
55 [[nodiscard]] static constexpr size_t rows() noexcept { return Rows; }
56 [[nodiscard]] static constexpr size_t cols() noexcept { return Cols; }
57
59 [[nodiscard]] constexpr T* data() noexcept { return m; }
60 [[nodiscard]] constexpr const T* data() const noexcept { return m; }
61
62 [[nodiscard]] constexpr bool operator==(const Matrix&) const noexcept = default;
63
64 constexpr Matrix& operator+=(const Matrix& other) noexcept {
65 for (size_t i = 0; i < Rows * Cols; ++i) m[i] += other.m[i];
66 return *this;
67 }
68
69 constexpr Matrix& operator-=(const Matrix& other) noexcept {
70 for (size_t i = 0; i < Rows * Cols; ++i) m[i] -= other.m[i];
71 return *this;
72 }
73
74 constexpr Matrix& operator*=(T scalar) noexcept {
75 for (size_t i = 0; i < Rows * Cols; ++i) m[i] *= scalar;
76 return *this;
77 }
78
79 constexpr Matrix& operator*=(const Matrix& other) noexcept {
80 static_assert(Rows == Cols, "Only square matrices can be multiplied in place");
81 return *this = *this * other;
82 }
83
84 [[nodiscard]] constexpr Matrix<T, Rows, Cols> operator+(const Matrix<T, Rows, Cols>& other) const noexcept {
86 for (size_t i = 0; i < Rows * Cols; ++i) {
87 res.m[i] = m[i] + other.m[i];
88 }
89 return res;
90 }
91
92 [[nodiscard]] constexpr Matrix<T, Rows, Cols> operator-(const Matrix<T, Rows, Cols>& other) const noexcept {
94 for (size_t i = 0; i < Rows * Cols; ++i) {
95 res.m[i] = m[i] - other.m[i];
96 }
97 return res;
98 }
99
100 template <size_t P>
101 [[nodiscard]] constexpr Matrix<T, Rows, P> operator*(const Matrix<T, Cols, P>& other) const noexcept {
102 Matrix<T, Rows, P> res(0);
103 for (size_t i = 0; i < Rows; ++i) {
104 for (size_t j = 0; j < P; ++j) {
105 T sum = 0;
106 for (size_t k = 0; k < Cols; ++k) {
107 sum += (*this)(i, k) * other(k, j);
108 }
109 res(i, j) = sum;
110 }
111 }
112 return res;
113 }
114
115 [[nodiscard]] constexpr Matrix<T, Rows, Cols> operator*(T scalar) const noexcept {
117 for (size_t i = 0; i < Rows * Cols; ++i) {
118 res.m[i] = m[i] * scalar;
119 }
120 return res;
121 }
122
124 [[nodiscard]] constexpr Vector3D<T> transformPoint(const Vector3D<T>& p) const {
125 static_assert(Rows >= 3 && Cols >= 4, "Matrix must be at least 3x4 to transform a 3D point");
126 T res[3];
127 for (size_t i = 0; i < 3; ++i) {
128 res[i] = (*this)(i, 0) * p.getX() + (*this)(i, 1) * p.getY() + (*this)(i, 2) * p.getZ();
129 res[i] += (*this)(i, 3);
130 }
131 return Vector3D<T>{res[0], res[1], res[2]};
132 }
133
135 [[nodiscard]] constexpr Vector3D<T> transformDirection(const Vector3D<T>& d) const {
136 static_assert(Rows >= 3 && Cols >= 3, "Matrix must be at least 3x3 to transform a 3D direction");
137 T res[3];
138 for (size_t i = 0; i < 3; ++i) {
139 res[i] = (*this)(i, 0) * d.getX() + (*this)(i, 1) * d.getY() + (*this)(i, 2) * d.getZ();
140 }
141 return Vector3D<T>{res[0], res[1], res[2]};
142 }
143
144 [[nodiscard]] constexpr Matrix<T, Cols, Rows> transpose() const noexcept {
146 for (size_t i = 0; i < Rows; ++i) {
147 for (size_t j = 0; j < Cols; ++j) {
148 res(j, i) = (*this)(i, j);
149 }
150 }
151 return res;
152 }
153
155 [[nodiscard]] constexpr T determinant() const noexcept {
156 static_assert(Rows == Cols, "Only square matrices have a determinant");
157 const auto& a = *this;
158 if constexpr (Rows == 1) {
159 return a(0, 0);
160 } else if constexpr (Rows == 2) {
161 return a(0, 0) * a(1, 1) - a(0, 1) * a(1, 0);
162 } else if constexpr (Rows == 3) {
163 return a(0, 0) * (a(1, 1) * a(2, 2) - a(1, 2) * a(2, 1))
164 - a(0, 1) * (a(1, 0) * a(2, 2) - a(1, 2) * a(2, 0))
165 + a(0, 2) * (a(1, 0) * a(2, 1) - a(1, 1) * a(2, 0));
166 } else {
167 static_assert(std::is_floating_point_v<T>, "determinant() above 3x3 needs a floating-point type");
168 Matrix temp = *this;
169 T det = T(1);
170 for (size_t i = 0; i < Rows; ++i) {
171 size_t pivot = i;
172 for (size_t p = i + 1; p < Rows; ++p) {
173 if (abs(temp(p, i)) > abs(temp(pivot, i))) pivot = p;
174 }
175 if (temp(pivot, i) == T(0)) {
176 return T(0);
177 }
178 if (pivot != i) {
179 for (size_t c = 0; c < Cols; ++c) std::swap(temp(i, c), temp(pivot, c));
180 det = -det;
181 }
182 det *= temp(i, i);
183 for (size_t r = i + 1; r < Rows; ++r) {
184 const T f = temp(r, i) / temp(i, i);
185 for (size_t c = i; c < Cols; ++c) temp(r, c) -= f * temp(i, c);
186 }
187 }
188 return det;
189 }
190 }
191
194 [[nodiscard]] constexpr Matrix<T, Rows, Cols> inverse() const {
195 static_assert(Rows == Cols, "Only square matrices can be inverted");
196 Matrix<T, Rows, Cols> temp = *this;
198
199 for (size_t i = 0; i < Rows; ++i) {
200 size_t pivot = i;
201 for (size_t p = i + 1; p < Rows; ++p) {
202 if (abs(temp(p, i)) > abs(temp(pivot, i))) pivot = p;
203 }
204
205 if (abs(temp(pivot, i)) < std::numeric_limits<T>::epsilon()) {
206 throw std::runtime_error("Matrix is singular and cannot be inverted");
207 }
208
209 if (pivot != i) {
210 for (size_t c = 0; c < Cols; ++c) {
211 std::swap(temp(i, c), temp(pivot, c));
212 std::swap(inv(i, c), inv(pivot, c));
213 }
214 }
215
216 T factor = temp(i, i);
217 for (size_t c = 0; c < Cols; ++c) {
218 temp(i, c) /= factor;
219 inv(i, c) /= factor;
220 }
221
222 for (size_t j = 0; j < Rows; ++j) {
223 if (i != j) {
224 T f = temp(j, i);
225 for (size_t c = 0; c < Cols; ++c) {
226 temp(j, c) -= f * temp(i, c);
227 inv(j, c) -= f * inv(i, c);
228 }
229 }
230 }
231 }
232 return inv;
233 }
234
236 [[nodiscard]] static constexpr Matrix<T, Rows, Cols> translation(T x, T y, T z) noexcept {
237 static_assert(Rows >= 4 && Cols >= 4, "Matrix must be 4x4 or larger for 3D translation");
239 res(0, 3) = x;
240 res(1, 3) = y;
241 res(2, 3) = z;
242 return res;
243 }
244
245 [[nodiscard]] static constexpr Matrix<T, Rows, Cols> translation(const Vector3D<T>& v) noexcept {
246 return translation(v.getX(), v.getY(), v.getZ());
247 }
248
250 [[nodiscard]] static constexpr Matrix<T, Rows, Cols> scale(T sx, T sy, T sz) noexcept {
251 static_assert(Rows >= 3 && Cols >= 3, "Matrix must be 3x3 or larger for 3D scaling");
253 res(0, 0) = sx;
254 res(1, 1) = sy;
255 res(2, 2) = sz;
256 return res;
257 }
258
260 [[nodiscard]] static constexpr Matrix<T, Rows, Cols> scale(T s) noexcept {
261 return scale(s, s, s);
262 }
264 [[nodiscard]] static constexpr Matrix<T, Rows, Cols> shear(T sxy, T sxz, T syx, T syz, T szx, T szy) noexcept {
265 static_assert(Rows >= 3 && Cols >= 3, "Matrix must be 3x3 or larger for 3D shearing");
267 res(0, 1) = sxy;
268 res(0, 2) = sxz;
269 res(1, 0) = syx;
270 res(1, 2) = syz;
271 res(2, 0) = szx;
272 res(2, 1) = szy;
273 return res;
274 }
275
277 [[nodiscard]] static Matrix<T, Rows, Cols> rotationX(T angleRad) {
278 static_assert(Rows >= 3 && Cols >= 3, "Matrix must be 3x3 or larger for 3D rotation");
280 T c = std::cos(angleRad);
281 T s = std::sin(angleRad);
282 res(1, 1) = c;
283 res(1, 2) = -s;
284 res(2, 1) = s;
285 res(2, 2) = c;
286 return res;
287 }
288
290 [[nodiscard]] static Matrix<T, Rows, Cols> rotationY(T angleRad) {
291 static_assert(Rows >= 3 && Cols >= 3, "Matrix must be 3x3 or larger for 3D rotation");
293 T c = std::cos(angleRad);
294 T s = std::sin(angleRad);
295
296 res(0, 0) = c;
297 res(0, 2) = s;
298 res(2, 0) = -s;
299 res(2, 2) = c;
300
301 return res;
302 }
303
305 [[nodiscard]] static Matrix<T, Rows, Cols> rotationZ(T angleRad) {
306 static_assert(Rows >= 3 && Cols >= 3, "Matrix must be 3x3 or larger for 3D rotation");
308 T c = std::cos(angleRad);
309 T s = std::sin(angleRad);
310
311 res(0, 0) = c;
312 res(0, 1) = -s;
313 res(1, 0) = s;
314 res(1, 1) = c;
315
316 return res;
317 }
318
319 [[nodiscard]] static constexpr Matrix<T, Rows, Cols> identity() noexcept {
320 return Matrix<T, Rows, Cols>();
321 }
322
324 [[nodiscard]] static Matrix<T, 4, 4> ortho(T left, T right, T bottom, T top, T nearP = T(-1), T farP = T(1)) {
325 static_assert(Rows == 4 && Cols == 4, "ortho requires a 4x4 matrix");
326 Matrix<T, 4, 4> r(T(0));
327 r(0, 0) = T(2) / (right - left);
328 r(1, 1) = T(2) / (top - bottom);
329 r(2, 2) = -T(2) / (farP - nearP);
330 r(0, 3) = -(right + left) / (right - left);
331 r(1, 3) = -(top + bottom) / (top - bottom);
332 r(2, 3) = -(farP + nearP) / (farP - nearP);
333 r(3, 3) = T(1);
334 return r;
335 }
336
338 [[nodiscard]] static Matrix<T, 4, 4> perspective(T fovYDeg, T aspect, T nearP, T farP) {
339 static_assert(Rows == 4 && Cols == 4, "perspective requires a 4x4 matrix");
340 const T fovYRad = toRad(fovYDeg);
341 const T f = T(1) / std::tan(fovYRad / T(2));
342 Matrix<T, 4, 4> r(T(0));
343 r(0, 0) = f / aspect;
344 r(1, 1) = f;
345 r(2, 2) = (farP + nearP) / (nearP - farP);
346 r(2, 3) = (T(2) * farP * nearP) / (nearP - farP);
347 r(3, 2) = T(-1);
348 return r;
349 }
350
352 [[nodiscard]] static Matrix<T, 4, 4> lookAt(const Vector3D<T>& eye, const Vector3D<T>& center, const Vector3D<T>& up) {
353 static_assert(Rows == 4 && Cols == 4, "lookAt requires a 4x4 matrix");
354 Vector3D<T> z = (eye - center).normalized();
355 Vector3D<T> x = up.cross(z).normalized();
356 Vector3D<T> y = z.cross(x);
357 Matrix<T, 4, 4> r(T(0));
358 r(0,0)=x.getX(); r(0,1)=x.getY(); r(0,2)=x.getZ(); r(0,3)=-x.dot(eye);
359 r(1,0)=y.getX(); r(1,1)=y.getY(); r(1,2)=y.getZ(); r(1,3)=-y.dot(eye);
360 r(2,0)=z.getX(); r(2,1)=z.getY(); r(2,2)=z.getZ(); r(2,3)=-z.dot(eye);
361 r(3,3)=T(1);
362 return r;
363 }
364
365 private:
366 T m[Rows * Cols];
367 };
368
369 template <typename T> using Matrix4 = Matrix<T, 4, 4>;
370 template <typename T> using Matrix3 = Matrix<T, 3, 3>;
371
378
379 template <typename T, size_t Rows, size_t Cols>
380 std::ostream& operator<<(std::ostream& os, const Matrix<T, Rows, Cols>& mat) {
381 for (size_t i = 0; i < Rows; ++i) {
382 os << "[ ";
383 for (size_t j = 0; j < Cols; ++j) {
384 os << mat(i, j) << (j < Cols - 1 ? ", " : " ");
385 }
386 os << "]\n";
387 }
388 return os;
389 }
390}
Fixed-size matrix of Rows x Cols elements, stored in row-major order.
Definition Matrix.hpp:19
constexpr Matrix< T, Cols, Rows > transpose() const noexcept
Definition Matrix.hpp:144
constexpr bool operator==(const Matrix &) const noexcept=default
constexpr T & operator()(size_t row, size_t col) noexcept
Element at row and col.
Definition Matrix.hpp:52
constexpr Matrix() noexcept
Identity matrix.
Definition Matrix.hpp:22
static Matrix< T, Rows, Cols > rotationZ(T angleRad)
Rotation of angleRad radians around the Z axis.
Definition Matrix.hpp:305
constexpr Matrix & operator+=(const Matrix &other) noexcept
Definition Matrix.hpp:64
constexpr Matrix & operator-=(const Matrix &other) noexcept
Definition Matrix.hpp:69
constexpr const T & operator()(size_t row, size_t col) const noexcept
Definition Matrix.hpp:53
constexpr const T * data() const noexcept
Definition Matrix.hpp:60
static constexpr size_t cols() noexcept
Definition Matrix.hpp:56
static constexpr Matrix< T, Rows, Cols > scale(T s) noexcept
Uniform scaling matrix.
Definition Matrix.hpp:260
constexpr Matrix(T value) noexcept
Matrix with every element set to value.
Definition Matrix.hpp:33
static constexpr Matrix< T, Rows, Cols > translation(const Vector3D< T > &v) noexcept
Definition Matrix.hpp:245
constexpr Matrix & operator*=(const Matrix &other) noexcept
Definition Matrix.hpp:79
static constexpr size_t rows() noexcept
Definition Matrix.hpp:55
constexpr Matrix< T, Rows, Cols > inverse() const
Inverse of a square matrix.
Definition Matrix.hpp:194
static constexpr Matrix< T, Rows, Cols > translation(T x, T y, T z) noexcept
Translation matrix, 4x4 or larger.
Definition Matrix.hpp:236
constexpr const T & operator[](size_t index) const noexcept
Definition Matrix.hpp:50
static constexpr Matrix< T, Rows, Cols > scale(T sx, T sy, T sz) noexcept
Scaling matrix.
Definition Matrix.hpp:250
constexpr T & operator[](size_t index) noexcept
Element at index in row-major order.
Definition Matrix.hpp:49
constexpr Matrix< T, Rows, Cols > operator-(const Matrix< T, Rows, Cols > &other) const noexcept
Definition Matrix.hpp:92
constexpr T * data() noexcept
The elements in row-major order.
Definition Matrix.hpp:59
static constexpr Matrix< T, Rows, Cols > identity() noexcept
Definition Matrix.hpp:319
constexpr Matrix< T, Rows, Cols > operator*(T scalar) const noexcept
Definition Matrix.hpp:115
constexpr Matrix< T, Rows, P > operator*(const Matrix< T, Cols, P > &other) const noexcept
Definition Matrix.hpp:101
static Matrix< T, Rows, Cols > rotationX(T angleRad)
Rotation of angleRad radians around the X axis.
Definition Matrix.hpp:277
static Matrix< T, 4, 4 > lookAt(const Vector3D< T > &eye, const Vector3D< T > &center, const Vector3D< T > &up)
Right-handed view matrix of a camera at eye looking at center.
Definition Matrix.hpp:352
static Matrix< T, 4, 4 > ortho(T left, T right, T bottom, T top, T nearP=T(-1), T farP=T(1))
OpenGL-style orthographic projection.
Definition Matrix.hpp:324
constexpr Vector3D< T > transformDirection(const Vector3D< T > &d) const
Transforms a direction, ignoring the translation.
Definition Matrix.hpp:135
static Matrix< T, Rows, Cols > rotationY(T angleRad)
Rotation of angleRad radians around the Y axis.
Definition Matrix.hpp:290
constexpr Matrix & operator*=(T scalar) noexcept
Definition Matrix.hpp:74
constexpr Matrix< T, Rows, Cols > operator+(const Matrix< T, Rows, Cols > &other) const noexcept
Definition Matrix.hpp:84
static Matrix< T, 4, 4 > perspective(T fovYDeg, T aspect, T nearP, T farP)
OpenGL-style perspective projection, with a vertical field of view in degrees.
Definition Matrix.hpp:338
constexpr T determinant() const noexcept
Determinant of a square matrix; above 3x3, T must be a floating-point type.
Definition Matrix.hpp:155
constexpr Vector3D< T > transformPoint(const Vector3D< T > &p) const
Transforms a point, translation included.
Definition Matrix.hpp:124
static constexpr Matrix< T, Rows, Cols > shear(T sxy, T sxz, T syx, T syz, T szx, T szy) noexcept
Shearing matrix: sxy adds sxy * y to x, and so on.
Definition Matrix.hpp:264
constexpr Matrix(std::initializer_list< T > list)
Elements in row-major order.
Definition Matrix.hpp:39
Math helpers: constants, interpolation, random numbers, 2D and 3D vectors and matrices.
Definition Constants.hpp:5
constexpr T abs(T value) noexcept
Definition Utils.hpp:24
constexpr T toRad(T degrees) noexcept
Definition Utils.hpp:14
std::ostream & operator<<(std::ostream &os, const Matrix< T, Rows, Cols > &mat)
Definition Matrix.hpp:380
3D vector; arithmetic operators work component-wise, with a vector or a scalar.
Definition Vector.hpp:135
constexpr T getZ() const noexcept
Definition Vector.hpp:144
constexpr T dot(const Vector3D &v) const noexcept
Definition Vector.hpp:184
constexpr T getX() const noexcept
Definition Vector.hpp:142
constexpr Vector3D normalized() const noexcept
Definition Vector.hpp:205
constexpr T getY() const noexcept
Definition Vector.hpp:143
constexpr Vector3D cross(const Vector3D &v) const noexcept
Definition Vector.hpp:185