MaxMath SIMD Math Library for Unity

repository·master·Indexed 41 days ago

https://github.com/mrunbelievable92/maxmath

A high-performance SIMD math library for Unity and Unity.Burst that extends Unity.Mathematics. Version 3.1.0 provides a drop-in replacement with expanded primitive support (sbyte, ushort, ulong), wider SIMD vectors up to 256-bit, and exotic precision types like UInt128 and quadruple precision floats. Written with ARM and x86 hardware intrinsics, it includes comprehensive arithmetic, floating-point, integer, saturation, bitwise, and noise generation functions.

Tokens
3K
Snippets
2
Records
15
Agent score
1%

What's inside MaxMath

  1. Overview of MaxMath

    master

    MaxMath is a high-performance SIMD math library for Unity developers, built on top of Unity.Mathematics and optimized for Unity.Burst. It serves as a drop-in replacement/wrapper for Unity.Mathematics (as of version 3.0) while providing significantly more extensive functionality.

    Key capabilities include:

    • Expanded Primitive Support: Adds support for (s)byte, (u)short, and (u)long vectors and matrices.
    • Wider SIMD Vectors: Supports up to 256-bit vectors (e.g., byte32, short16, int8, float8) for full hardware utilization.
    • Exotic Precision: Includes (U)Int128 (scalar), 128-bit quadruple precision floats (scalar), and 8-bit quarter precision floats (scalar and vector).
    • Hardware Intrinsics: Written directly with ARM and x86 hardware intrinsics for optimal performance.
    • Burst Integration: Deeply integrated with Unity.Burst and LLVM, using semantic postconditions (Unity.Burst.CompilerServices.Hint.Assume()) to help the compiler propagate optimizations through opaque implementations.
  2. Optimize MaxMath performance

    master

    To achieve maximum performance with MaxMath, follow these architectural recommendations:

    • Use Dedicated Math Functions: Prefer using specific MaxMath operations (e.g., MaxMath.math.sin(x)) over composing equivalent expressions from primitive operators. MaxMath functions are optimized with SIMD intrinsics and communicate mathematical metadata (like value ranges) to the compiler that manual compositions cannot.
    • Prefer Explicit SIMD over Auto-Vectorization: Unlike Unity.Mathematics, scalar MaxMath.math functions may not always be auto-vectorized by LLVM. For performance-critical code, use explicit SIMD code with MaxMath vector types and load/store vectors directly using unsafe pointer operations.
    • Vector Width: Use vector types that occupy entire SIMD registers (128 or 256 bits) to assist LLVM optimization.
    • Boolean Data: Avoid declaring boolean vectors as temporary stack variables. Instead, use the internal mask[BITS]x[COLUMNS]x[ROWS] types. These are ref structs that are implicitly convertible to/from boolean vectors and matrices but avoid the conversion overhead.
  3. Why use MaxMath instead of Unity.Mathematics?

    master

    Starting with version 3.0, MaxMath is designed as a drop-in replacement for Unity.Mathematics. Developers should consider MaxMath over the standard library for the following reasons:

    • Bug Fixes: Addresses long-standing bugs in Unity.Mathematics, specifically regarding half precision types.
    • Active Maintenance: Unlike Unity.Mathematics, MaxMath is actively maintained with regular updates and community feedback loops.
    • Modern Hardware Optimization: MaxMath utilizes direct hardware intrinsics and is designed to leverage CoreCLR and newer C# features (like generalized shift operators) that Unity.Mathematics may not adopt.
    • Unified API: Using MaxMath eliminates the need to manage two separate math namespaces (Unity.Mathematics and MaxMath), providing a single, cohesive API surface.
  4. Optimize MaxMath functions with the Promise enum

    master
    MaxMath leverages Unity.Burst.CompilerServices.Constant.IsConstantExpression<T>() to select optimized code paths at compile time. Users can influence this compile-time optimization behavior by providing the optional Promise enum parameter available in many MaxMath functions. This allows the library to choose more efficient implementations based on whether a value is guaranteed to be constant.
  5. Install MaxMath via Scoped Registries

    master

    The recommended way to install MaxMath is using Unity's Scoped Registries feature. This allows for easy updates, version management, and cleaner project structures.

    1. Open your Unity project.
    2. Navigate to Edit → Project Settings → Package Manager.
    3. Under Scoped Registries, click + to add a new registry with these details:
      • Name: MrUnbelievable
      • URL: https://registry.npmjs.org
      • Scopes: com.mrunbelievable
    4. Click Save.
    5. Open Window → Package Manager.
    6. Select My Registries in the package list and install MaxMath.
    Name: MrUnbelievable
    URL: https://registry.npmjs.org
    Scopes: com.mrunbelievable
  6. Migrate from Unity.Mathematics to MaxMath

    master

    Migrating to MaxMath is generally a find-and-replace operation, but requires attention to namespace changes and property access.

    Namespace Mapping

    Replace Unity.Mathematics with MaxMath, then apply these specific mappings:

    • MaxMath.Geometry.Math → MaxMath.math
    • MaxMath.Geometry → MaxMath

    Key Breaking Changes

    • Vector Fields as Ref Properties: Vector fields in MaxMath are exposed as ref properties. You cannot take their address in an unsafe context. You must initialize the vector before assigning to its components directly or via the out keyword.
    • Serialization: Because fields are now properties, serialized Unity.Mathematics vector values in the Inspector may be invalidated. MaxMath uses custom property serialization to handle this.
    • Boolean Vectors: While bool{X} vectors (e.g., bool3 cmp = a > b) still work and are not obsolete, they involve a performance cost due to conversion. For optimal performance, use MaxMath's native mask types (mask[BITS]x[COLUMNS]x[ROWS]) directly.
  7. Manage MaxMath Debug Assertions

    master

    MaxMath uses C# Dev Tools to provide safety assertions in DEBUG builds. These catch programmer errors but can increase code size in the Burst Inspector and impact performance during development.

    To disable these safety checks (e.g., for running performance benchmarks or inspecting release code generation), use the Unity Editor menu: Window → C# Dev Tools → Manage Safety Checks...

    Warning: It is strongly recommended to keep these enabled during normal development to prevent memory corruption, infinite loops, and editor crashes.

  8. Overview of MaxMath Arithmetic and Miscellaneous Functions

    master

    MaxMath provides a wide range of arithmetic operations applicable to scalar, vector, and matrix types.

    Miscellaneous Arithmetic:

    • addsub(a, b): Alternating add/subtract.
    • subadd(a, b): Alternating subtract/add.
    • avg(a, b): Rounded average for integer types; true average for floating point types.
    • divrem(a, b, out remainder): Division with remainder.
    • square(a): Squares the input.
    • mad(a, b, c): Multiply-add.
    • msub(a, b, c): Multiply-subtract.
    • maddsub(a, b, c): Alternating multiply-add/subtract.
    • msubadd(a, b, c): Alternating multiply-add/subtract.

    Many functions include an optional enum Promise parameter for optimized code paths.

    // Example of usage (signatures are simplified in documentation)
    addsub(a, b);
    divrem(a, b, out var remainder);
    mad(a, b, c);
  9. Integer Functions in MaxMath

    master

    MaxMath provides specialized integer math:

    Multiplication and Division:

    • mulwide(a, b, out lo, out hi): Full precision multiplication.
    • isdivisible(a, b): Checks if $a % b == 0$.
    • intsqrt(a), intcbrt(a), intpow(a, b).
    • inthypot(a, b): $\sqrt{a^2 + b^2}$ without overflow.
    • ceildiv(a, b), floordiv(a, b).

    Bit and Power Operations:

    • floorpow2(a): Round to nearest smaller power of 2.
    • ceilpow2(a): Round to nearest greater power of 2.
    • floorlog2(a), ceillog2(a).

    Combinatorics and Number Theory:

    • gcd(a, b): Greatest common divisor.
    • lcm(a, b): Least common multiple.
    • comb(a, b): Binomial coefficient.
    • perm(a, b): $k$-permutations of $n$.
    • factorial(a).
  10. Bitwise Operations and Bitfields in MaxMath

    master

    MaxMath offers extensive bit manipulation capabilities.

    Bitfields and Masks:

    • bitfield(params a): Pack multiple values into one integer.
    • bitfield[numBits](a, b): Create a bitfield of a consecutive 1-bits starting at index b.
    • bitmask(a): Create a bitfield from a boolean vector.
    • bits_extract(a, b, c): Extract c bits starting at index b.
    • lzmask(a), l1mask(a), tzmask(a), t1mask(a): Create masks from leading/trailing zeros/ones.
    • bits_extractparallel(a, b) / bits_depositparallel(a, b): Pack/scatter bits based on a mask.

    Testing and Counting:

    • testbit(a, b): Test if bit b is set.
    • testbitset(ref a, b): Test and set bit b to 1.
    • testbitreset(ref a, b): Test and set bit b to 0.
    • testbitflip(ref a, b): Test and flip bit b.
    • countbits(a): Count bits set to 1.
    • lzcnt(a), l1cnt(a), tzcnt(a), t1cnt(a): Count leading/trailing zeros/ones.

    Transformations:

    • shl/shrl/shra(a, b): Logical/arithmetic bit shifts.
    • rol/ror(a, b): Bitwise rotations (scalar and vector).
    • reversebits(a), reversebytes(a).
    • signextend(a, b): Sign-extend a treated as having b bits.
  11. Noise Generation in MaxMath

    master

    MaxMath includes a noise namespace for various procedural noise algorithms:

    • noise.cellular(a)
    • noise.cellular2x2(a)
    • noise.cellular2x2x2(a)
    • noise.cnoise(a): Perlin noise.
    • noise.pnoise(a): Periodic Perlin noise.
    • noise.snoise(a): Simplex noise.
    • noise.psrdnoise(a): Periodic simplex noise with fixed gradients and analytical derivative.
    • noise.psrnoise(a): Periodic simplex noise with rotating gradients (no analytical derivative).
    • noise.srdnoise(a): Non-periodic simplex noise with rotating gradients and analytical derivative.
    • noise.srnoise(a): Non-periodic simplex noise with fixed gradients (no analytical derivative).
  12. Floating Point Functions in MaxMath

    master

    MaxMath includes a comprehensive suite of floating-point operations:

    Roots and Powers:

    • sqrt(a), rsqrt(a) (1/sqrt), fastrsqrt(a) (fast approximate).
    • cbrt(a), rcbrt(a) (1/cbrt).
    • pow(a, b): Supports both floating point and optimized integer exponents.

    Exponentials and Logarithms:

    • exp(a), exp2(a), exp10(a).
    • log(a), log2(a), log10(a), and log(a, b) for arbitrary bases.

    Trigonometric and Other:

    • hypot(a, b): $\sqrt{a^2 + b^2}$ without overflow.
    • frac(a): Fractional part.
    • modf(a, out i): Splits into fractional and integer parts.
    • rcp(a), fastrcp(a): Reciprocal and fast approximate reciprocal.
    • fmod(a, b): Modulo operation.
    • isint(a): Checks if value has no fractional part.
    • round(a), trunc(a), floor(a), ceil(a).
    • div(a, b, [bool] fast): Division (with optional fast approximation).
    • dad, dsub, daddsub, dsubadd: Various divide-add/subtract operations (with optional fast flag).