Skip to content

A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.

14.2 KB
Raw Blame
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
/**
 * @file    Math.hpp
 * @brief   Math utilities and GLM configuration for ESEngine
 * @details Provides GLM configuration, math constants, and utility functions
 *          for common game development operations including quaternion/euler
 *          conversions and matrix decomposition.
 *
 * @author  ESEngine Team
 * @date    2026
 *
 * @copyright Copyright (c) 2026 ESEngine Team
 *            Licensed under the Apache License, Version 2.0.
 */
#pragma once

// =============================================================================
// GLM Configuration
// =============================================================================

// SIMD is enabled via the build flags (-msse2 -msimd128), not here: GLM auto-detects
// __SSE2__ and vectorizes vec4/mat4 ops with unaligned load/store. We intentionally do
// NOT define GLM_FORCE_DEFAULT_ALIGNED_GENTYPES — aligning would bloat vec3-heavy
// components and change the ptr-layout ABI for marginal load-speed gain. See
// docs/REARCH_SIMD.md and cmake/Emscripten.cmake (ES_MAIN_DISABLE_SIMD).
#ifndef GLM_FORCE_RADIANS
    #define GLM_FORCE_RADIANS
#endif
#ifndef GLM_FORCE_DEPTH_ZERO_TO_ONE
    #define GLM_FORCE_DEPTH_ZERO_TO_ONE
#endif
#ifndef GLM_ENABLE_EXPERIMENTAL
    #define GLM_ENABLE_EXPERIMENTAL
#endif

// =============================================================================
// GLM Includes
// =============================================================================

#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>
#include <glm/gtc/quaternion.hpp>
#include <glm/gtx/quaternion.hpp>
#include <glm/gtx/euler_angles.hpp>

namespace esengine {

// =============================================================================
// Math Namespace
// =============================================================================

/**
 * @brief Math constants and utility functions
 *
 * @details Provides common mathematical constants and helper functions
 *          for angles, interpolation, matrix operations, etc.
 */
namespace math {

// =============================================================================
// Constants
// =============================================================================

/** @brief Pi constant */
constexpr float PI = 3.14159265358979323846f;

/** @brief Two times pi (full circle in radians) */
constexpr float TWO_PI = 2.0f * PI;

/** @brief Half pi (quarter circle in radians) */
constexpr float HALF_PI = 0.5f * PI;

/** @brief Degrees to radians conversion factor */
constexpr float DEG_TO_RAD = PI / 180.0f;

/** @brief Radians to degrees conversion factor */
constexpr float RAD_TO_DEG = 180.0f / PI;

/** @brief Small epsilon for floating-point comparisons */
constexpr float EPSILON = 1e-6f;

// =============================================================================
// Angle Conversion
// =============================================================================

/**
 * @brief Converts degrees to radians
 * @param degrees Angle in degrees
 * @return Angle in radians
 */
inline float toRadians(float degrees) {
    return degrees * DEG_TO_RAD;
}

/**
 * @brief Converts radians to degrees
 * @param radians Angle in radians
 * @return Angle in degrees
 */
inline float toDegrees(float radians) {
    return radians * RAD_TO_DEG;
}

/**
 * @brief Converts a vec3 of degrees to radians
 * @param degrees Euler angles in degrees
 * @return Euler angles in radians
 */
inline glm::vec3 toRadians(const glm::vec3& degrees) {
    return degrees * DEG_TO_RAD;
}

/**
 * @brief Converts a vec3 of radians to degrees
 * @param radians Euler angles in radians
 * @return Euler angles in degrees
 */
inline glm::vec3 toDegrees(const glm::vec3& radians) {
    return radians * RAD_TO_DEG;
}

// =============================================================================
// Interpolation
// =============================================================================

/**
 * @brief Linear interpolation between two values
 * @tparam T Value type (float, vec2, vec3, vec4, etc.)
 * @param a Start value
 * @param b End value
 * @param t Interpolation factor (0 = a, 1 = b)
 * @return Interpolated value
 *
 * @code
 * float val = math::lerp(0.0f, 10.0f, 0.5f); // 5.0f
 * glm::vec3 pos = math::lerp(startPos, endPos, t);
 * @endcode
 */
template<typename T>
inline T lerp(const T& a, const T& b, float t) {
    return a + t * (b - a);
}

/**
 * @brief Clamps a value between min and max
 * @tparam T Value type
 * @param value Value to clamp
 * @param min Minimum bound
 * @param max Maximum bound
 * @return Clamped value
 */
template<typename T>
inline T clamp(const T& value, const T& min, const T& max) {
    return glm::clamp(value, min, max);
}

// =============================================================================
// Comparisons
// =============================================================================

/**
 * @brief Checks if two floats are approximately equal
 * @param a First value
 * @param b Second value
 * @param epsilon Maximum difference threshold
 * @return True if |a - b| < epsilon
 */
inline bool approxEqual(float a, float b, float epsilon = EPSILON) {
    return std::abs(a - b) < epsilon;
}

/**
 * @brief Checks if two vec3s are approximately equal
 * @param a First vector
 * @param b Second vector
 * @param epsilon Maximum component difference threshold
 * @return True if all components are approximately equal
 */
inline bool approxEqual(const glm::vec3& a, const glm::vec3& b, float epsilon = EPSILON) {
    return approxEqual(a.x, b.x, epsilon) &&
           approxEqual(a.y, b.y, epsilon) &&
           approxEqual(a.z, b.z, epsilon);
}

// =============================================================================
// Projection Matrices
// =============================================================================

/**
 * @brief Creates an orthographic projection matrix
 * @param left Left boundary
 * @param right Right boundary
 * @param bottom Bottom boundary
 * @param top Top boundary
 * @param near Near plane distance
 * @param far Far plane distance
 * @return Orthographic projection matrix
 */
inline glm::mat4 ortho(float left, float right, float bottom, float top, float nearPlane, float farPlane) {
    // _NO, spelled out: the build defines GLM_FORCE_DEPTH_ZERO_TO_ONE, and a
    // projection that silently followed it would contradict the one convention
    // ClipDepthRange states the engine builds for.
    return glm::orthoRH_NO(left, right, bottom, top, nearPlane, farPlane);
}

/**
 * @brief Creates a perspective projection matrix
 * @param fov Field of view in radians
 * @param aspect Aspect ratio (width / height)
 * @param near Near plane distance
 * @param far Far plane distance
 * @return Perspective projection matrix
 */
inline glm::mat4 perspective(float fov, float aspect, float nearPlane, float farPlane) {
    // See ortho: the engine's convention is stated, not inherited from a macro.
    return glm::perspectiveRH_NO(fov, aspect, nearPlane, farPlane);
}

/**
 * @brief Creates a look-at view matrix
 * @param eye Camera position
 * @param center Point to look at
 * @param up World up vector
 * @return View matrix
 */
inline glm::mat4 lookAt(const glm::vec3& eye, const glm::vec3& center, const glm::vec3& up) {
    return glm::lookAt(eye, center, up);
}

// =============================================================================
// Matrix Decomposition
// =============================================================================

/**
 * @brief Decomposes a transformation matrix into components (Euler angles)
 * @param matrix The transformation matrix to decompose
 * @param position Output: extracted position
 * @param rotation Output: extracted Euler angles (radians)
 * @param scale Output: extracted scale factors
 *
 * @code
 * glm::vec3 pos, rot, scl;
 * math::decompose(transform, pos, rot, scl);
 * @endcode
 */
inline void decompose(const glm::mat4& matrix, glm::vec3& position, glm::vec3& rotation, glm::vec3& scale) {
    // Extract position
    position = glm::vec3(matrix[3]);

    // Extract scale
    scale.x = glm::length(glm::vec3(matrix[0]));
    scale.y = glm::length(glm::vec3(matrix[1]));
    scale.z = glm::length(glm::vec3(matrix[2]));

    // Guard zero-scale axes: dividing by 0 produces NaN/Inf that propagates
    // silently into Euler angles and corrupts every downstream transform.
    const float sx = scale.x > EPSILON ? scale.x : EPSILON;
    const float sy = scale.y > EPSILON ? scale.y : EPSILON;
    const float sz = scale.z > EPSILON ? scale.z : EPSILON;

    glm::mat3 rotMatrix(
        glm::vec3(matrix[0]) / sx,
        glm::vec3(matrix[1]) / sy,
        glm::vec3(matrix[2]) / sz
    );

    rotation.x = std::atan2(rotMatrix[2][1], rotMatrix[2][2]);
    rotation.y = std::atan2(-rotMatrix[2][0],
        std::sqrt(rotMatrix[2][1] * rotMatrix[2][1] + rotMatrix[2][2] * rotMatrix[2][2]));
    rotation.z = std::atan2(rotMatrix[1][0], rotMatrix[0][0]);
}

/**
 * @brief Decomposes a transformation matrix into components (quaternion)
 * @param matrix The transformation matrix to decompose
 * @param position Output: extracted position
 * @param rotation Output: extracted rotation as quaternion
 * @param scale Output: extracted scale factors
 *
 * @code
 * glm::vec3 pos, scl;
 * glm::quat rot;
 * math::decompose(transform, pos, rot, scl);
 * @endcode
 */
inline void decompose(const glm::mat4& matrix, glm::vec3& position, glm::quat& rotation, glm::vec3& scale) {
    // Extract position
    position = glm::vec3(matrix[3]);

    // Extract scale
    scale.x = glm::length(glm::vec3(matrix[0]));
    scale.y = glm::length(glm::vec3(matrix[1]));
    scale.z = glm::length(glm::vec3(matrix[2]));

    // A planar reflection stays a Z rotation plus signed XY scale. This also
    // keeps a collapsed axis from producing a non-unit rotation quaternion.
    if (matrix[0].z == 0.0f && matrix[1].z == 0.0f && matrix[2].x == 0.0f && matrix[2].y == 0.0f) {
        glm::vec2 direction{1.0f, 0.0f};
        if (scale.x > EPSILON) {
            direction = glm::vec2(matrix[0]) / scale.x;
            if (matrix[0].x * matrix[1].y - matrix[0].y * matrix[1].x < 0.0f) scale.y = -scale.y;
        } else if (scale.y > EPSILON) {
            direction = glm::vec2(matrix[1].y, -matrix[1].x) / scale.y;
        }
        scale.z = matrix[2].z;
        rotation = glm::quat_cast(glm::mat3(glm::vec3(direction, 0.0f),
                                            glm::vec3(-direction.y, direction.x, 0.0f),
                                            glm::vec3(0.0f, 0.0f, 1.0f)));
        return;
    }

    // Quaternion conversion requires a proper rotation, not a reflection.
    // Put the spatial reflection on one scale axis before converting the basis.
    if (glm::determinant(glm::mat3(matrix)) < 0.0f) scale.x = -scale.x;

    // Guard zero-scale axes to avoid NaN/Inf in the quaternion.
    const float sx = std::abs(scale.x) > EPSILON ? scale.x : std::copysign(EPSILON, scale.x);
    const float sy = scale.y > EPSILON ? scale.y : EPSILON;
    const float sz = scale.z > EPSILON ? scale.z : EPSILON;

    glm::mat3 rotMatrix(
        glm::vec3(matrix[0]) / sx,
        glm::vec3(matrix[1]) / sy,
        glm::vec3(matrix[2]) / sz
    );

    rotation = glm::quat_cast(rotMatrix);
}

// =============================================================================
// Quaternion Utilities
// =============================================================================

/**
 * @brief Converts Euler angles (radians) to quaternion
 * @param euler Euler angles in radians (pitch, yaw, roll / X, Y, Z)
 * @return Quaternion representing the rotation
 *
 * @code
 * glm::quat rot = math::eulerToQuat(glm::vec3(0, glm::radians(45.0f), 0));
 * @endcode
 */
inline glm::quat eulerToQuat(const glm::vec3& euler) {
    return glm::quat(euler);
}

/**
 * @brief Converts quaternion to Euler angles (radians)
 * @param quat The quaternion to convert
 * @return Euler angles in radians (pitch, yaw, roll / X, Y, Z)
 *
 * @code
 * glm::vec3 euler = math::quatToEuler(rotation);
 * @endcode
 */
inline glm::vec3 quatToEuler(const glm::quat& quat) {
    return glm::eulerAngles(quat);
}

/**
 * @brief Converts Euler angles (degrees) to quaternion
 * @param degrees Euler angles in degrees (pitch, yaw, roll / X, Y, Z)
 * @return Quaternion representing the rotation
 */
inline glm::quat eulerDegreesToQuat(const glm::vec3& degrees) {
    return glm::quat(toRadians(degrees));
}

/**
 * @brief Converts quaternion to Euler angles (degrees)
 * @param quat The quaternion to convert
 * @return Euler angles in degrees (pitch, yaw, roll / X, Y, Z)
 */
inline glm::vec3 quatToEulerDegrees(const glm::quat& quat) {
    return toDegrees(glm::eulerAngles(quat));
}

// =============================================================================
// Transform Matrix Construction
// =============================================================================

/**
 * @brief Constructs a transformation matrix from TRS components
 * @param position Translation
 * @param rotation Rotation as quaternion
 * @param scale Scale factors
 * @return The combined transformation matrix (T * R * S)
 *
 * @code
 * glm::mat4 model = math::compose(position, rotation, scale);
 * @endcode
 */
inline glm::mat4 compose(const glm::vec3& position, const glm::quat& rotation, const glm::vec3& scale) {
    glm::mat4 result = glm::mat4(1.0f);
    result = glm::translate(result, position);
    result *= glm::mat4_cast(rotation);
    result = glm::scale(result, scale);
    return result;
}

/**
 * @brief Constructs a transformation matrix from TRS components (Euler angles)
 * @param position Translation
 * @param rotation Rotation as Euler angles (radians)
 * @param scale Scale factors
 * @return The combined transformation matrix (T * R * S)
 */
inline glm::mat4 compose(const glm::vec3& position, const glm::vec3& rotation, const glm::vec3& scale) {
    glm::mat4 result = glm::mat4(1.0f);
    result = glm::translate(result, position);
    result = glm::rotate(result, rotation.x, glm::vec3(1.0f, 0.0f, 0.0f));
    result = glm::rotate(result, rotation.y, glm::vec3(0.0f, 1.0f, 0.0f));
    result = glm::rotate(result, rotation.z, glm::vec3(0.0f, 0.0f, 1.0f));
    result = glm::scale(result, scale);
    return result;
}

}  // namespace math
}  // namespace esengine