Math

Chuck Smith edited this page 2026-11-25 01:11:18 +00:00 · 1 commit

Math library: keep DirectXMath or switch? (issue #6)

Status: decided and done (2026-11-17). The user took the recommendation (section 5): own storage types, a faster rotate3() and Frustum, DirectXMath stays behind math::. What was done: section 6. The benchmark is in Prototypes/MathBench/ (opt-in, CMake only).

1. Where the engine is

  • SIMD math goes through math:: (Engine/Utilities/MathSimd.h, #6's first step, 2026-11-11): math::vec / math::mat and about 35 thin forwarders to DirectXMath. 18 files use them; Tools/check_math_usage.py keeps DirectXMath out of everything else. The most used are load/store (112 calls), then clamp, quat_from_euler, cos, normalize3, inverse, mul, cross3, rotate3.
  • The storage types are DirectXMath's structs (math::v3 = DirectX::XMFLOAT3, m4x4 = XMFLOAT4X4, ...), about 300 uses (v3 167, m4x4 51, v4 34, v2 28, ...), also in the structs shared with HLSL (CommonTypes.hlsli), whose layout the shader build checks against C++ (ShaderLayoutCheck.cpp, #17).
  • The game API sees DirectXMath: GameEntity.h, which game scripts force-include, preprocesses to about 142,000 lines; about 48,000 of them are DirectXMath and the compiler's SIMD headers.
  • Conventions (pinned by UnitTests/MathTests.cpp): row vectors, row-major matrices with the translation in the last row, quaternions (x, y, z, w), Euler angles (pitch, yaw, roll) applied roll, pitch, yaw, right-handed view and projection, depth 0 to 1, reversed Z.

2. What was measured

The engine's kernels over 100,000 items, single thread, Release (clang 23, -O3 -mavx2 -mfma), Ryzen 9 5900X, median of 50 rounds, 3 runs. Every candidate reads and writes the same plain structs in the engine's conventions, converting at the edges where its own convention differs, and is compared with DirectXMath's results.

  • DirectXMath (jun2026) through the engine's math:: API: today's code.
  • GLM 1.0.3 with its SSE paths (GLM_FORCE_INTRINSICS and GLM_FORCE_DEFAULT_ALIGNED_GENTYPES; without the aligned types GLM's inverse and matrix product are scalar: 18 and 8 ns).
  • rtm 2.4.0 (Realtime Math).
  • Own SSE prototype (Prototypes/MathBench/OwnMath.h, about 250 lines): the engine's math:: API on SSE4.1 + FMA, only the functions the kernels need.
ns per item world matrix (S, R, T) 4x4 inverse local frame sphere vs 6 planes world * view-proj quaternion from Euler
DirectXMath 4.3-4.5 8.1-8.6 13.8-14.5 5.7-6.0 1.5-1.7 6.1-6.4
GLM (aligned SSE) 3.1-3.3 6.5-6.8 11.6-12.3 5.3-5.6 1.5-1.7 23.8-24.7
rtm 3.1-3.7 8.6-10.0 9.8-11.1 3.7-3.9 2.3-3.0 13.8-14.6
own (SSE), first version 3.1-3.3 6.9-7.3 8.7-9.9 5.3-5.6 2.3-2.4 22.6-23.9
own, tuned (below) 3.1-3.2 6.8-7.2 8.6-9.1 1.0-1.1 1.5-1.6 5.8-6.1

Tuning the own prototype (asked by the user, same day) took three changes, each a known technique:

  • Quaternion from Euler: one 4-wide sine/cosine (range reduction to [-pi/2, pi/2], then the minimax polynomials DirectXMath uses) and the quaternion assembled with SIMD, instead of six std::sin/std::cos calls: 22.7 → 5.8 ns, and closer to the exact value (6e-8 from DirectXMath's result instead of 2-3e-7).
  • Matrix product: two rows per 256-bit register (AVX2), as DirectXMath does: 2.3 → 1.5 ns.
  • Culling: a Frustum with its six planes stored transposed (the x of four planes in one register, ...), so a sphere is tested against four planes per instruction: 5.3 → 1.0 ns, the same visible spheres.

The rotation (local frame 8.7 ns) and the inverse already led. The same techniques would also speed up today's math:: forwarders on DirectXMath (it already has the first two; the frustum layout and the faster rotate3() are library-independent).

Results agree: the same visible spheres (35,467 of 100,000) everywhere, identical matrix products; the rest differs by float rounding (about 1e-7, the inverse 1.4e-5 relative).

DirectXMath GLM rtm own
Vectors / matrix layout row vectors, row-major: the engine's column vectors; same bytes, products written in the other order (vp * world, T * R * S) row vectors, row-major: the engine's ours
Traps for the engine's conventions none quat(w, x, y, z) takes w first; quat(euler) composes in another order; the SIMD paths need aligned types, which change vec3/vec4 size and alignment (not the HLSL layout) quat_from_euler() uses its own axes (X forward, Z up); left-handed camera functions only; no 3x4 → 4x4 conversion none (but every function is ours to get right)
Engine functions it lacks none (today's) none right-handed view/projection, reversed Z all, plus a NEON path and a scalar fallback
ARM (NEON) yes partial yes to write
constexpr storage constructors partial partial all we want
License, maintenance MIT, Microsoft, release jun2026 MIT (or "Happy Bunny"), last release 2025-12 MIT, one maintainer, release 2026-11 ours
Headers 1.4 MB 3.2 MB 1.6 MB about 500 lines today (Math*.h)
Linux <sal.h> stub fine fine fine

Compile time doesn't separate them: each costs 0.4-1 s for a file that uses it, mostly the compiler's SIMD headers.

3. What the numbers say

  1. No library is faster across the board as it comes; a tuned own one is (row "own, tuned"). Untuned, Each kernel's winner differs, by up to 1.5x, and the differences are single functions, not designs: DirectXMath's XMVector3Rotate (two quaternion products) makes its local frame the slowest (14 ns); the cross-product formula (v + w t + q x t) gives 9 ns in the own prototype and rtm. DirectXMath wins the Euler conversion (6 ns) because it computes sine and cosine with its own vector polynomial; the others call std::sin/std::cos six times. All of it is fixable, with DirectXMath underneath or without it.
  2. Switching to GLM or rtm buys no measurable speed; an own library buys up to 1.6x on the local frame (the transform systems' largest cost) and 5.6x on culling (mostly the layout), at the price of writing and keeping it: about 35 functions plus the new ones, tests per function, and a NEON path and a scalar fallback for ARM (not a target today: Windows and Linux on x64).
  3. The data layout matters more than the library. Plain scalar code for the sphere test (1.3 ns, GLM without SIMD types) beat every SIMD version (3.7-6 ns): one 4-wide dot product per plane is a poor use of SIMD. Fast culling tests 8 spheres per instruction from arrays of x, y, z and radius (the ECS chunks give those) with AVX2; that's library-independent and belongs to #3/#52.
  4. DirectXMath fits the engine's conventions exactly; rtm almost (row vectors, but left-handed cameras); GLM is the most error-prone for this engine (column vectors, w-first constructor, a different Euler order, and its fast path changes type layouts that HLSL shares).
  5. What DirectXMath still costs us is not speed but its types: XMFLOAT3 and friends are the engine's storage types, so they reach the HLSL-shared structs, reflection (#41 will describe component fields) and every game script's compile (a third of GameEntity.h's preprocessed lines).

4. Options

  • A. Keep DirectXMath behind math:: (today), and fix the measured slow spots in the forwarders.
  • B. A + own storage types: math::v2/v3/v4/m3x3/m4x4/... become the engine's own structs (named members, constexpr, same size and layout, so the HLSL layout check still passes); MathSimd.h loads and stores them. DirectXMath stays the SIMD implementation only. A later switch of that implementation is then one file.
  • C. Switch to rtm: rewrite MathSimd.h on rtm, plus own right-handed camera functions (B's storage types too).
  • D. Switch to GLM: as C, with the convention traps of section 2.
  • E. Own SIMD library: rewrite MathSimd.h on SSE/AVX2 (+ NEON and a scalar fallback when ARM matters), with tests per function. With B's storage types first, it can go function by function: each forwarder replaced and checked against DirectXMath's result in UnitTests/MathTests.cpp, DirectXMath dropped when the last one goes.

5. Recommendation and the decisions for the user

Both serious paths start the same way, so the recommendation is a first step and a decision about the second:

Step 1 (recommended either way): own storage types and the measured fixes.

  • math::v2/v3/v4/m3x3/m4x4/... become the engine's own structs (named members, constexpr, same size and layout: the HLSL layout check guards the shared ones). DirectXMath stays an implementation detail of MathSimd.h.
  • math::rotate3() with the cross-product formula (local frames 14 → about 9 ns) and a math::Frustum with transposed planes for culling (about 1 ns per sphere), each with a test against today's results.

Step 2, the decision: who implements math:: afterwards.

  • Keep DirectXMath (B): mature, maintained, NEON included, exactly the engine's conventions. After step 1 the own prototype's remaining lead is the world matrix (3.1 vs 4.3 ns, 1.4x) and the inverse (6.9 vs 8.1 ns, 1.2x).
  • Own, function by function (E): replace a forwarder with own SSE/AVX2 code when it's worth it, each checked against DirectXMath's result in UnitTests/MathTests.cpp; drop DirectXMath when the last one goes. Costs: about 35 functions, their tests, and a NEON path and a scalar fallback if ARM ever matters. Gains: full control, constexpr, no <sal.h> stub, no DirectXMath in game scripts.
  • GLM and rtm aren't recommended: no speed gain over either path, and the convention traps of section 2.

The user decided (2026-11-17, "do the recommendation"): step 1, and B for step 2. Decision 3 waits for #41/#52.

  1. Step 1: own storage types, rotate3() and Frustum (recommended).
  2. Step 2: keep DirectXMath behind math:: (B), or replace it function by function with own code (E). Both are reasonable: B is less to own, E is measurably faster on the world matrix and inverse, and its first functions would be those. My recommendation: B now, and revisit E when a profile shows math:: in the frame.
  3. Whether game scripts should stop seeing DirectXMath entirely (also math::vec): the script API would return storage types instead of math::vec (transform::Component::calculate_*()), a small game API change. With #41/#52's game API, not now (with E it happens by itself).

Not a decision here: SoA culling of 8 spheres at once from ECS chunks (AVX2) goes to #3/#52.

6. Done (2026-11-17)

  • Own storage types (Engine/Utilities/MathTypes.h): v2, v2a, v3, v3a, v4, v4a, u32v2-u32v4, s32v2-s32v4, m3x3, m4x4, m4x4a are plain aggregates with DirectXMath's size and alignment (checked by static_asserts in MathSimd.h, and the shader build's layout check for the HLSL-shared ones). The matrices' members are _11 ... _44 (row-major, like HLSL); there is no m[4][4]. MathTypes.h no longer includes DirectXMath; math::vec and math::mat moved to MathSimd.h. load()/store() std::bit_cast between the two (the same code at -O3: the benchmark's numbers didn't move).
  • Differences from DirectXMath's structs that touched code: no constructor from a const float * (write the three values), v3a is no longer a v3 (DirectXMath derives one from the other), and m4x4a is no longer an m4x4 (transform::get_transform_matrices() has an m4x4a overload for the HLSL structs). Designated initializers now work (math::v3{.x = 1.f}).
  • math::rotate3() uses the cross-product form; the result's w is 0 as before. Tested against the rotation matrix.
  • math::Frustum, make_frustum(planes), intersects(frustum, sphere): planes stored transposed. Tested against a plane-by-plane test. No caller yet: CPU culling is #3's.
  • Measured (the engine's math:: in Prototypes/MathBench, ns per item): local frame 13.8 → 12.4, culling 5.7 → 1.2 (the same visible spheres). The local frame doesn't reach the prototype's 8.7: the rest is math::normalize3() (three per item), which keeps DirectXMath's handling of zero-length and infinite vectors. A normalize without it would be a new, separate function, if a profile ever asks for it.
  • Checked: Linux clang (Debug, Release) and GCC (CI build job), clang-tidy (ci.sh tidy), ci.sh checks, UnitTests 168 (Release 170), GraphicsTests 21; Windows VM: 4 configurations, 8 EngineTest variants, UnitTests Debug + Release, the renderer test on D3D12 and Vulkan.

Pages 19

View all

Clone this repository