Estella 0.113.0
A fast 2D and 3D game engine powered by WebAssembly and ECS
Loading...
Searching...
No Matches
Math.hpp
Go to the documentation of this file.
1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
16#pragma once
17
18// =============================================================================
19// GLM Configuration
20// =============================================================================
21
22// SIMD is enabled via the build flags (-msse2 -msimd128), not here: GLM auto-detects
23// __SSE2__ and vectorizes vec4/mat4 ops with unaligned load/store. We intentionally do
24// NOT define GLM_FORCE_DEFAULT_ALIGNED_GENTYPES — aligning would bloat vec3-heavy
25// components and change the ptr-layout ABI for marginal load-speed gain. See
26// docs/REARCH_SIMD.md and cmake/Emscripten.cmake (ES_MAIN_DISABLE_SIMD).
27#ifndef GLM_FORCE_RADIANS
28 #define GLM_FORCE_RADIANS
29#endif
30#ifndef GLM_FORCE_DEPTH_ZERO_TO_ONE
31 #define GLM_FORCE_DEPTH_ZERO_TO_ONE
32#endif
33#ifndef GLM_ENABLE_EXPERIMENTAL
34 #define GLM_ENABLE_EXPERIMENTAL
35#endif
36
37// =============================================================================
38// GLM Includes
39// =============================================================================
40
41#include <glm/glm.hpp>
42#include <glm/gtc/matrix_transform.hpp>
43#include <glm/gtc/type_ptr.hpp>
44#include <glm/gtc/quaternion.hpp>
45#include <glm/gtx/quaternion.hpp>
46#include <glm/gtx/euler_angles.hpp>
47
48namespace esengine {
49
50// =============================================================================
51// Math Namespace
52// =============================================================================
53
60namespace math {
61
62// =============================================================================
63// Constants
64// =============================================================================
65
67constexpr float PI = 3.14159265358979323846f;
68
70constexpr float TWO_PI = 2.0f * PI;
71
73constexpr float HALF_PI = 0.5f * PI;
74
76constexpr float DEG_TO_RAD = PI / 180.0f;
77
79constexpr float RAD_TO_DEG = 180.0f / PI;
80
82constexpr float EPSILON = 1e-6f;
83
84// =============================================================================
85// Angle Conversion
86// =============================================================================
87
93inline float toRadians(float degrees) {
94 return degrees * DEG_TO_RAD;
95}
96
102inline float toDegrees(float radians) {
103 return radians * RAD_TO_DEG;
104}
105
111inline glm::vec3 toRadians(const glm::vec3& degrees) {
112 return degrees * DEG_TO_RAD;
113}
114
120inline glm::vec3 toDegrees(const glm::vec3& radians) {
121 return radians * RAD_TO_DEG;
122}
123
124// =============================================================================
125// Interpolation
126// =============================================================================
127
141template<typename T>
142inline T lerp(const T& a, const T& b, float t) {
143 return a + t * (b - a);
144}
145
154template<typename T>
155inline T clamp(const T& value, const T& min, const T& max) {
156 return glm::clamp(value, min, max);
157}
158
159// =============================================================================
160// Comparisons
161// =============================================================================
162
170inline bool approxEqual(float a, float b, float epsilon = EPSILON) {
171 return std::abs(a - b) < epsilon;
172}
173
181inline bool approxEqual(const glm::vec3& a, const glm::vec3& b, float epsilon = EPSILON) {
182 return approxEqual(a.x, b.x, epsilon) &&
183 approxEqual(a.y, b.y, epsilon) &&
184 approxEqual(a.z, b.z, epsilon);
185}
186
187// =============================================================================
188// Projection Matrices
189// =============================================================================
190
201inline glm::mat4 ortho(float left, float right, float bottom, float top, float nearPlane, float farPlane) {
202 // _NO, spelled out: the build defines GLM_FORCE_DEPTH_ZERO_TO_ONE, and a
203 // projection that silently followed it would contradict the one convention
204 // ClipDepthRange states the engine builds for.
205 return glm::orthoRH_NO(left, right, bottom, top, nearPlane, farPlane);
206}
207
216inline glm::mat4 perspective(float fov, float aspect, float nearPlane, float farPlane) {
217 // See ortho: the engine's convention is stated, not inherited from a macro.
218 return glm::perspectiveRH_NO(fov, aspect, nearPlane, farPlane);
219}
220
228inline glm::mat4 lookAt(const glm::vec3& eye, const glm::vec3& center, const glm::vec3& up) {
229 return glm::lookAt(eye, center, up);
230}
231
232// =============================================================================
233// Matrix Decomposition
234// =============================================================================
235
248inline void decompose(const glm::mat4& matrix, glm::vec3& position, glm::vec3& rotation, glm::vec3& scale) {
249 // Extract position
250 position = glm::vec3(matrix[3]);
251
252 // Extract scale
253 scale.x = glm::length(glm::vec3(matrix[0]));
254 scale.y = glm::length(glm::vec3(matrix[1]));
255 scale.z = glm::length(glm::vec3(matrix[2]));
256
257 // Guard zero-scale axes: dividing by 0 produces NaN/Inf that propagates
258 // silently into Euler angles and corrupts every downstream transform.
259 const float sx = scale.x > EPSILON ? scale.x : EPSILON;
260 const float sy = scale.y > EPSILON ? scale.y : EPSILON;
261 const float sz = scale.z > EPSILON ? scale.z : EPSILON;
262
263 glm::mat3 rotMatrix(
264 glm::vec3(matrix[0]) / sx,
265 glm::vec3(matrix[1]) / sy,
266 glm::vec3(matrix[2]) / sz
267 );
268
269 rotation.x = std::atan2(rotMatrix[2][1], rotMatrix[2][2]);
270 rotation.y = std::atan2(-rotMatrix[2][0],
271 std::sqrt(rotMatrix[2][1] * rotMatrix[2][1] + rotMatrix[2][2] * rotMatrix[2][2]));
272 rotation.z = std::atan2(rotMatrix[1][0], rotMatrix[0][0]);
273}
274
288inline void decompose(const glm::mat4& matrix, glm::vec3& position, glm::quat& rotation, glm::vec3& scale) {
289 // Extract position
290 position = glm::vec3(matrix[3]);
291
292 // Extract scale
293 scale.x = glm::length(glm::vec3(matrix[0]));
294 scale.y = glm::length(glm::vec3(matrix[1]));
295 scale.z = glm::length(glm::vec3(matrix[2]));
296
297 // A planar reflection stays a Z rotation plus signed XY scale. This also
298 // keeps a collapsed axis from producing a non-unit rotation quaternion.
299 if (matrix[0].z == 0.0f && matrix[1].z == 0.0f && matrix[2].x == 0.0f && matrix[2].y == 0.0f) {
300 glm::vec2 direction{1.0f, 0.0f};
301 if (scale.x > EPSILON) {
302 direction = glm::vec2(matrix[0]) / scale.x;
303 if (matrix[0].x * matrix[1].y - matrix[0].y * matrix[1].x < 0.0f) scale.y = -scale.y;
304 } else if (scale.y > EPSILON) {
305 direction = glm::vec2(matrix[1].y, -matrix[1].x) / scale.y;
306 }
307 scale.z = matrix[2].z;
308 rotation = glm::quat_cast(glm::mat3(glm::vec3(direction, 0.0f),
309 glm::vec3(-direction.y, direction.x, 0.0f),
310 glm::vec3(0.0f, 0.0f, 1.0f)));
311 return;
312 }
313
314 // Quaternion conversion requires a proper rotation, not a reflection.
315 // Put the spatial reflection on one scale axis before converting the basis.
316 if (glm::determinant(glm::mat3(matrix)) < 0.0f) scale.x = -scale.x;
317
318 // Guard zero-scale axes to avoid NaN/Inf in the quaternion.
319 const float sx = std::abs(scale.x) > EPSILON ? scale.x : std::copysign(EPSILON, scale.x);
320 const float sy = scale.y > EPSILON ? scale.y : EPSILON;
321 const float sz = scale.z > EPSILON ? scale.z : EPSILON;
322
323 glm::mat3 rotMatrix(
324 glm::vec3(matrix[0]) / sx,
325 glm::vec3(matrix[1]) / sy,
326 glm::vec3(matrix[2]) / sz
327 );
328
329 rotation = glm::quat_cast(rotMatrix);
330}
331
332// =============================================================================
333// Quaternion Utilities
334// =============================================================================
335
345inline glm::quat eulerToQuat(const glm::vec3& euler) {
346 return glm::quat(euler);
347}
348
358inline glm::vec3 quatToEuler(const glm::quat& quat) {
359 return glm::eulerAngles(quat);
360}
361
367inline glm::quat eulerDegreesToQuat(const glm::vec3& degrees) {
368 return glm::quat(toRadians(degrees));
369}
370
376inline glm::vec3 quatToEulerDegrees(const glm::quat& quat) {
377 return toDegrees(glm::eulerAngles(quat));
378}
379
380// =============================================================================
381// Transform Matrix Construction
382// =============================================================================
383
395inline glm::mat4 compose(const glm::vec3& position, const glm::quat& rotation, const glm::vec3& scale) {
396 glm::mat4 result = glm::mat4(1.0f);
397 result = glm::translate(result, position);
398 result *= glm::mat4_cast(rotation);
399 result = glm::scale(result, scale);
400 return result;
401}
402
410inline glm::mat4 compose(const glm::vec3& position, const glm::vec3& rotation, const glm::vec3& scale) {
411 glm::mat4 result = glm::mat4(1.0f);
412 result = glm::translate(result, position);
413 result = glm::rotate(result, rotation.x, glm::vec3(1.0f, 0.0f, 0.0f));
414 result = glm::rotate(result, rotation.y, glm::vec3(0.0f, 1.0f, 0.0f));
415 result = glm::rotate(result, rotation.z, glm::vec3(0.0f, 0.0f, 1.0f));
416 result = glm::scale(result, scale);
417 return result;
418}
419
420} // namespace math
421} // namespace esengine
Math constants and utility functions.
Definition Math.hpp:60
glm::vec3 quatToEuler(const glm::quat &quat)
Converts quaternion to Euler angles (radians).
Definition Math.hpp:358
glm::mat4 lookAt(const glm::vec3 &eye, const glm::vec3 &center, const glm::vec3 &up)
Creates a look-at view matrix.
Definition Math.hpp:228
T lerp(const T &a, const T &b, float t)
Linear interpolation between two values.
Definition Math.hpp:142
float toRadians(float degrees)
Converts degrees to radians.
Definition Math.hpp:93
T clamp(const T &value, const T &min, const T &max)
Clamps a value between min and max.
Definition Math.hpp:155
constexpr float PI
Pi constant.
Definition Math.hpp:67
bool approxEqual(float a, float b, float epsilon=EPSILON)
Checks if two floats are approximately equal.
Definition Math.hpp:170
glm::quat eulerDegreesToQuat(const glm::vec3 &degrees)
Converts Euler angles (degrees) to quaternion.
Definition Math.hpp:367
constexpr float RAD_TO_DEG
Radians to degrees conversion factor.
Definition Math.hpp:79
constexpr float TWO_PI
Two times pi (full circle in radians).
Definition Math.hpp:70
glm::mat4 ortho(float left, float right, float bottom, float top, float nearPlane, float farPlane)
Creates an orthographic projection matrix.
Definition Math.hpp:201
glm::mat4 compose(const glm::vec3 &position, const glm::quat &rotation, const glm::vec3 &scale)
Constructs a transformation matrix from TRS components.
Definition Math.hpp:395
void decompose(const glm::mat4 &matrix, glm::vec3 &position, glm::vec3 &rotation, glm::vec3 &scale)
Decomposes a transformation matrix into components (Euler angles).
Definition Math.hpp:248
float toDegrees(float radians)
Converts radians to degrees.
Definition Math.hpp:102
constexpr float HALF_PI
Half pi (quarter circle in radians).
Definition Math.hpp:73
glm::mat4 perspective(float fov, float aspect, float nearPlane, float farPlane)
Creates a perspective projection matrix.
Definition Math.hpp:216
constexpr float EPSILON
Small epsilon for floating-point comparisons.
Definition Math.hpp:82
glm::vec3 quatToEulerDegrees(const glm::quat &quat)
Converts quaternion to Euler angles (degrees).
Definition Math.hpp:376
constexpr float DEG_TO_RAD
Degrees to radians conversion factor.
Definition Math.hpp:76
glm::quat eulerToQuat(const glm::vec3 &euler)
Converts Euler angles (radians) to quaternion.
Definition Math.hpp:345