# DL Mathematical Operations Library ## Overview The `dl_math.h` header file provides a comprehensive mathematical library for 3D graphics programming in the Bella Engine SDK. It includes vector arithmetic, matrix operations, quaternion rotations, color manipulation, and geometric primitives - all the building blocks needed for 3D rendering, animation, and game development. This library is designed to be: - **Template-based**: Works with different numeric types (float, double, int) - **Header-only**: All functionality is in a single header file - **Efficient**: Optimized for performance-critical graphics applications - **Comprehensive**: Covers all essential 3D math operations ## Key C++ Concepts Used Before diving into the mathematical types, let's understand the C++ features used throughout this library: ### Templates Templates allow the same code to work with different data types. For example: ```cpp template struct VecT; ``` This defines a vector template that can have `N` dimensions and use scalar type `S`. ### Unions Unions allow different ways to access the same memory: ```cpp union { struct { S x, y, z; }; struct { S u, v, w; }; S comp[3]; }; ``` This lets you access the same data as `vec.x` or `vec.comp[0]`. ### Operator Overloading The library overloads mathematical operators to work intuitively: ```cpp Vec3f a = {1, 2, 3}; Vec3f b = {4, 5, 6}; Vec3f result = a + b; // Component-wise addition ``` ## Mathematical Constants The library provides mathematical and physical constants in two namespaces: ### Numeric Constants (`nc` namespace) ```cpp #include "dl_math.h" using namespace dl::math; // Basic mathematical constants double pi_value = nc::pi; // π (3.14159...) double tau_value = nc::tau; // 2π (6.28318...) double e_value = nc::e; // Euler's number (2.71828...) // Angle conversion double degrees = 45.0; double radians = degrees * nc::degPerRad; // Convert degrees to radians double back_to_degrees = radians * nc::radPerDeg; // Convert back // Precision constants for floating-point comparisons float epsilon_f = nc::epsilonF; // 1.0e-5f double epsilon_d = nc::epsilonD; // 10.0e-13 ``` ### Practical Example - Angle Conversion ```cpp // Convert angles for camera rotation float camera_yaw_degrees = 45.0f; float camera_yaw_radians = d2r(camera_yaw_degrees); // Helper function // Use in trigonometric functions float x_offset = cos(camera_yaw_radians); float z_offset = sin(camera_yaw_radians); ``` ## Vector Types Vectors represent directions, velocities, forces, or any multi-dimensional data. The library provides 2D, 3D, and 4D vectors. ### Vector Declarations ```cpp // Float vectors (most common for graphics) Vec2f position2d; // 2D vector Vec3f velocity; // 3D vector Vec4f color_rgba; // 4D vector // Double precision (for high accuracy) Vec2d precise_pos; // 2D double vector Vec3d world_coords; // 3D double vector // Integer vectors (for indices, grid positions) Vec2i grid_pos; // 2D integer vector Vec3i voxel_coords; // 3D integer vector ``` ### Creating Vectors ```cpp // Default initialization (all zeros) Vec3f zero_vector = Vec3f::zero; // Unit vectors (length = 1) Vec3f x_axis = Vec3f::unitX; // (1, 0, 0) Vec3f y_axis = Vec3f::unitY; // (0, 1, 0) Vec3f z_axis = Vec3f::unitZ; // (0, 0, 1) // Custom vectors Vec3f position = Vec3f::make(1.0f, 2.0f, 3.0f); Vec2f screen_pos = Vec2f::make(100.0f, 200.0f); // From array float coords[3] = {1.0f, 2.0f, 3.0f}; Vec3f from_array = Vec3f::make(coords); ``` ### Vector Operations ```cpp Vec3f a = Vec3f::make(1.0f, 2.0f, 3.0f); Vec3f b = Vec3f::make(4.0f, 5.0f, 6.0f); // Basic arithmetic Vec3f sum = a + b; // (5, 7, 9) Vec3f diff = a - b; // (-3, -3, -3) Vec3f scaled = a * 2.0f; // (2, 4, 6) Vec3f component_mult = a * b; // Component-wise: (4, 10, 18) // Vector-specific operations float dot_product = dot(a, b); // Scalar result: 32 Vec3f cross_product = cross(a, b); // Vector result: (-3, 6, -3) float length = norm(a); // Length/magnitude: ~3.74 Vec3f normalized = unit(a); // Unit vector in same direction // Check if vector is normalized bool is_unit = isUnit(normalized); // true ``` ## Vector Operations Visualization ************************************************* * * Vector Operations: * * a = (1, 2, 3) b = (4, 5, 6) * │ │ * ▼ ▼ * ┌─────────┐ ┌─────────┐ * │ a + b │ │ a × b │ * │ (5,7,9) │ │(-3,6,-3)│ * └─────────┘ └─────────┘ * │ │ * ▼ ▼ * ┌─────────┐ ┌─────────┐ * │ a · b │ │ |a| │ * │ 32 │ │ 3.74 │ * └─────────┘ └─────────┘ * ************************************************* [Figure [diagram]: Common vector operations showing addition, cross product, dot product, and magnitude calculations.] ### Practical Vector Examples #### 3D Movement and Physics ```cpp // Player movement Vec3f player_position = Vec3f::make(0.0f, 0.0f, 0.0f); Vec3f player_velocity = Vec3f::make(5.0f, 0.0f, 3.0f); // m/s float delta_time = 0.016f; // 60 FPS // Update position player_position = player_position + player_velocity * delta_time; // Apply gravity Vec3f gravity = Vec3f::make(0.0f, -9.81f, 0.0f); // m/s² player_velocity = player_velocity + gravity * delta_time; ``` #### Lighting Calculations ```cpp // Surface normal (normalized) Vec3f surface_normal = Vec3f::make(0.0f, 1.0f, 0.0f); // Light direction (from surface to light) Vec3f light_pos = Vec3f::make(10.0f, 10.0f, 5.0f); Vec3f surface_pos = Vec3f::make(0.0f, 0.0f, 0.0f); Vec3f light_dir = unit(light_pos - surface_pos); // Calculate lighting intensity float light_intensity = max(0.0f, dot(surface_normal, light_dir)); ``` ## Quaternions Quaternions provide a robust way to represent rotations without gimbal lock. They're essential for 3D rotations, especially in animation and physics. ### Understanding Quaternions A quaternion has four components (x, y, z, w): - `x, y, z`: Represent the rotation axis (as a vector) - `w`: Represents the amount of rotation ### Creating Quaternions ```cpp // Identity quaternion (no rotation) Quatf identity = Quatf::identity; // (0, 0, 0, 1) // Create from components Quatf custom = Quatf::make(0.0f, 0.707f, 0.0f, 0.707f); // Create from axis-angle Vec3f axis = Vec3f::unitY; // Rotate around Y-axis float angle = d2r(45.0f); // 45 degrees in radians Quatf rotation = qfromaa(axis, angle); ``` ### Quaternion Operations ```cpp Quatf q1 = qfromaa(Vec3f::unitY, d2r(45.0f)); // 45° around Y Quatf q2 = qfromaa(Vec3f::unitX, d2r(30.0f)); // 30° around X // Combine rotations (order matters!) Quatf combined = q1 * q2; // Apply rotation to a vector Vec3f original_vec = Vec3f::make(1.0f, 0.0f, 0.0f); Vec3f rotated_vec = q1 * original_vec; // Interpolate between rotations (for animation) float t = 0.5f; // 50% between rotations Quatf interpolated = slerp(q1, q2, t); // Spherical linear interpolation ``` ## Matrix Types Matrices are fundamental for transformations in 3D graphics. The library provides 3x3 and 4x4 matrices. ### Matrix Structure ```cpp // 3x3 matrix (for rotation and scale) Mat3f rotation_matrix; // 4x4 matrix (for full transformations including translation) Mat4f transform_matrix; ``` ### Matrix Access Patterns ```cpp Mat3f matrix = Mat3f::identity; // Access by component name float m00 = matrix.m00; // Top-left element float m11 = matrix.m11; // Center element float m22 = matrix.m22; // Bottom-right element // Access by column vectors Vec3f first_column = matrix.c0; Vec3f second_column = matrix.c1; Vec3f third_column = matrix.c2; // Semantic access for transformations Vec3f x_axis = matrix.xaxis; // X-axis direction Vec3f y_axis = matrix.yaxis; // Y-axis direction Vec3f z_axis = matrix.zaxis; // Z-axis direction ``` ### 4x4 Transformation Matrix ```cpp // Create a full transformation matrix Vec3f translation = Vec3f::make(10.0f, 5.0f, 0.0f); Mat3f rotation = /* some rotation matrix */; Mat4f transform = Mat4f::make( rotation.m00, rotation.m01, rotation.m02, translation.x, rotation.m10, rotation.m11, rotation.m12, translation.y, rotation.m20, rotation.m21, rotation.m22, translation.z, 0.0f, 0.0f, 0.0f, 1.0f ); ``` ## Color Types The library provides several color representations for different use cases. ### RGB Colors ```cpp // Float RGB (0.0 to 1.0 range) Rgbf red = Rgbf::red; // (1, 0, 0) Rgbf green = Rgbf::green; // (0, 1, 0) Rgbf blue = Rgbf::blue; // (0, 0, 1) Rgbf white = Rgbf::white; // (1, 1, 1) Rgbf black = Rgbf::black; // (0, 0, 0) // Custom colors Rgbf orange = Rgbf::make(1.0f, 0.5f, 0.0f); Rgbf purple = Rgbf::make(0.5f, 0.0f, 0.5f); // 8-bit RGB (0 to 255 range) Rgb8 pixel_color = Rgb8::make(255, 128, 64); ``` ### RGBA Colors (with Alpha) ```cpp // RGBA with transparency Rgbaf transparent_red = Rgbaf::make(1.0f, 0.0f, 0.0f, 0.5f); // 50% transparent Rgbaf opaque_blue = Rgbaf::make(0.0f, 0.0f, 1.0f, 1.0f); // Fully opaque // 8-bit RGBA Rgba8 ui_color = Rgba8::make(200, 100, 50, 180); // Semi-transparent orange ``` ## Transform Types Transform types (`XformT`) combine position, rotation, and scale into a single structure, making it easy to manage object transformations. ### Transform Structure ```cpp Xformf object_transform = Xformf::identity; // Access components Pos3f position = object_transform.position; // Translation Quatf rotation = object_transform.rotation; // Rotation (quaternion) Vec3f scale = object_transform.scale; // Scale factors ``` ### Creating Transforms ```cpp // Identity transform (no change) Xformf identity = Xformf::identity; // Custom transform Pos3f pos = Pos3f::make(10.0f, 5.0f, 0.0f); Quatf rot = qfromaa(Vec3f::unitY, d2r(45.0f)); Vec3f scale = Vec3f::make(2.0f, 1.0f, 1.0f); // 2x scale on X-axis Xformf custom = Xformf::make(pos, rot, scale); ``` ## Complete 3D Scene Setup Example ```cpp #include "dl_math.h" using namespace dl::math; class GameObject { public: Xformf transform; Vec3f velocity; Rgbf color; GameObject() : transform(Xformf::identity), velocity(Vec3f::zero), color(Rgbf::white) {} void update(float deltaTime) { // Apply velocity to position transform.position = transform.position + velocity * deltaTime; // Rotate object over time float rotation_speed = d2r(45.0f); // 45 degrees per second Quatf frame_rotation = qfromaa(Vec3f::unitY, rotation_speed * deltaTime); transform.rotation = transform.rotation * frame_rotation; } Mat4f getWorldMatrix() const { return transform.matrix(); } }; class Camera { public: Pos3f position; Quatf rotation; float fov; float near_plane; float far_plane; Camera() : position(Pos3f::make(0.0f, 5.0f, 10.0f)), rotation(Quatf::identity), fov(d2r(60.0f)), near_plane(0.1f), far_plane(1000.0f) {} void lookAt(Pos3f target) { Vec3f forward = unit(target - position); Vec3f world_up = Vec3f::unitY; Vec3f right = unit(cross(forward, world_up)); Vec3f up = cross(right, forward); // Create rotation matrix and convert to quaternion Mat3f rotation_matrix = Mat3f::make( right.x, up.x, -forward.x, right.y, up.y, -forward.y, right.z, up.z, -forward.z ); rotation = rotation_matrix.quaternion(); } Mat4f getViewMatrix() const { // Camera transform is inverse of object transform Xformf camera_transform = Xformf::make(position, rotation, Vec3f::one); return camera_transform.inverse().matrix(); } }; // Usage example void renderFrame() { // Create objects GameObject cube; cube.transform.position = Pos3f::make(0.0f, 0.0f, 0.0f); cube.color = Rgbf::red; cube.velocity = Vec3f::make(2.0f, 0.0f, 0.0f); // Create camera Camera camera; camera.lookAt(Pos3f::make(0.0f, 0.0f, 0.0f)); // Look at origin // Update objects float delta_time = 0.016f; // 60 FPS cube.update(delta_time); // Calculate matrices for rendering Mat4f view_matrix = camera.getViewMatrix(); Mat4f cube_world = cube.getWorldMatrix(); // Send to renderer... } ``` ## Best Practices ### 1. Choose Appropriate Types ```cpp // Use float for graphics (GPU prefers 32-bit) Vec3f vertex_position; Mat4f transformation_matrix; // Use double for high-precision calculations Vec3d world_coordinates; // For large worlds Pos3d precise_navigation; // For GPS-like accuracy // Use integer types for discrete data Vec2i pixel_coordinates; Vec3i voxel_indices; ``` ### 2. Normalize Vectors When Needed ```cpp // Always normalize direction vectors Vec3f movement_input = getUserInput(); // May not be normalized Vec3f movement_direction = unit(movement_input); // Check if vector needs normalization Vec3f some_vector = calculateSomeVector(); if (!isUnit(some_vector)) { some_vector = unit(some_vector); } ``` ### 3. Use Quaternions for Rotations ```cpp // Prefer quaternions over Euler angles to avoid gimbal lock Quatf object_rotation = Quatf::identity; // Combine rotations by multiplying quaternions Quatf additional_rotation = qfromaa(Vec3f::unitX, d2r(15.0f)); object_rotation = object_rotation * additional_rotation; // Use slerp for smooth rotation interpolation Quatf smooth_rotation = slerp(start_rotation, end_rotation, animation_t); ``` ### 4. Handle Floating-Point Precision ```cpp // Use epsilon comparisons for floating-point values float a = 0.1f + 0.1f + 0.1f; float b = 0.3f; if (equal(a, b)) { // Don't use a == b // Values are effectively equal } // Check for zero values Vec3f velocity = calculateVelocity(); if (zerolike(norm(velocity))) { // Object is effectively stationary } ``` ### 5. Performance Considerations ```cpp // Cache expensive calculations float reciprocal_length = 1.0f / norm(vector); // Cache division result Vec3f normalized = vector * reciprocal_length; // Use squared distances when possible float distance_sq = normSq(pos1 - pos2); // Avoid sqrt if (distance_sq < threshold_sq) { // Compare against squared threshold // Objects are close enough } ``` This comprehensive documentation should help you understand and effectively use the mathematical library in the Bella Engine SDK. The library provides all the essential building blocks for 3D graphics programming, from basic vector operations to complex transformations and lighting calculations.