ALICE-Physics
Deterministic 128-bit Fixed-Point Physics Engine - v1.0.0 stable
English | 日本語
Part of ALICE-Eco-System — 260+ crate Edge-to-Cloud data pipeline (SDF / Physics / LLM / Motion / Font / TTS)
A high-precision physics engine designed for deterministic simulation across different platforms and hardware. The rigid-body core uses 128-bit fixed-point arithmetic (Fix128); the surrounding engineering / field modules use IEEE f32 / f64 with every transcendental routed through the crate's own det_math. Either way the result is bit-exact regardless of CPU, compiler, or operating system — see Determinism scope.
Published on crates.io as v1.0.0 semver-locked stable (released 2026-09-14). Install with cargo add alice-physics. All 9 v1.0 roadmap items complete — see CHANGELOG.md for the full release scope, docs/MIGRATION_0.x_TO_1.0.md for 0.x → 1.0 migration, and docs/ECOSYSTEM_CONTRACTS.md for frozen partner API contracts.
Determinism scope
Every module in the crate is bit-exact across platforms, for two different reasons:
| Tier | Modules | Why the bits agree everywhere |
|---|---|---|
| Fix128 core | rigid-body solver, joints, distance / contact constraints, BVH broad-phase, GJK / EPA, CCD, sleeping, scene I/O, netcode snapshot / rollback, neural controller, and every module whose public API is expressed in Fix128 / Vec3Fix / QuatFix |
Pure i64 / u64 integer arithmetic. Pinned by tests/determinism_golden.rs |
f32 / f64 field modules (30: sdf_*, gpu_sdf, thermal, transient_thermal, phase_change, fracture, erosion, sim_field, sim_modifier, rolling_contact, aeroelasticity, piezoelectric, acoustic_wave, pressure, thin_wall, convex_decompose, db_bridge, character_state, fluid_netcode, anomaly, privacy, sketch) |
IEEE 754 + - * / sqrt and fused multiply-add are specified to the bit on every target Rust supports (SSE2+, aarch64, wasm32). Every transcendental (sin, exp, ln, powf, cbrt, hypot, …) goes through det_math — integer range reduction + fixed-order polynomials — never the platform libm. clippy.toml disallowed-methods makes a stray libm call a CI error. Pinned by tests/determinism_golden_f32.rs (13 scenarios, 29 modules; db_bridge is pass-through I/O with no arithmetic) |
Both golden suites run on macOS ARM / x86, Linux ARM / x86, Windows and wasm32-wasip1 in CI.
Boundary — code you pass in. ClosureSdf takes a user closure Fn(f32, f32, f32) -> f32. The solver stays deterministic, but the closure is your code: call alice_physics::det_math::{sin, exp, …} instead of f32::sin etc. inside it, or hand in an SDF whose evaluator has the same discipline. (ALICE-SDF's CPU evaluator is being aligned with det_math; until then treat it as same-binary deterministic.)
Out of scope. Targets that do not honour IEEE 754 for the basic operations: 32-bit x86 built for x87 (i586, no SSE2) and any build with fast-math style flags.
v0.10-0.14 highlights — a five-wave completeness push adds
54 modules + 3 integrated solver loops + a Session 4 19-module tier-classified push
covering the full spectrum from 3D-printing safety (warp / thin-wall /
stress / bridging) through composite / plastic / fatigue mechanics, up
to turbulence, VOF / level-set multi-phase flow, a runnable CFD
time-step loop, humanoid ragdoll, SDF-boundary SPH, transient thermal,
composite failure, VIV / piezoelectric / acoustic / electromagnetic,
IK / anisotropic friction / netcode prediction / character FSM /
kinematic loop / buoyancy zone / wind zone / SDF FEM / SDF wind.
All bit-exact across platforms — Fix128 modules by integer arithmetic, f32 modules via det_math (Determinism scope); see
Session 1-3 Additions and
v0.13.0 Session 4 Additions.
v1.0.0 release highlights (2026-09-14)
- API surface freeze — 32 module × 512 pub items audit (Iterations 1-6 + Final), 133+ items
pub → pub(crate)downgraded, snapshot 20,201 → 19,406 (−795 items).solver_tgs*extension mechanism moved topub(crate)(Option C). 7 prelude-exported structs marked#[non_exhaustive]for forward-compat. - 6-platform bit-exact determinism — golden hash (9 tests) + semantic invariant (22 tests) suite verified on macOS ARM/x86 + Linux ARM/x86 + Windows + WASM (
wasm32-wasip1viawasmtime). - Hard-gated semver enforcement —
cargo semver-checksblocks breaking-API PRs. - Ecosystem contracts frozen — [
docs/ECOSYSTEM_CONTRACTS.md] catalogues API for ALICE-TRT (GpuSolverBridge), ALICE-SDF (SdfField), ALICE-Bamboo, ALICE-Anima, ALICE-Kinematics. - 8/8 fuzz targets —
fuzz_step/fuzz_collision/fuzz_deterministic_roundtrip/fuzz_joint/fuzz_cfd/fuzz_ccd/fuzz_trimesh/fuzz_structural. - 1382 lib tests + 44 determinism tests — all passing on all 6 platforms.
v0.12.0 addition — GpuSolverBridge gains a joint-solve pipeline
(send_joints / send_body_rotations / dispatch_joint_solve_iteration)
and PhysicsWorld auto-routes both contact AND joint solve through the
installed bridge, coordinated with ALICE-TRT v3.1.0's
FIX128_BALL_SOCKET_JOINT_SOLVE_WGSL kernel (byte-exact vs CPU
solve_ball_joint). See CHANGELOG.md.
v0.13.0 Session 4 Additions (19 modules across 3 tiers)
Extends the v0.10-0.12 engineering-solver foundation with a 19-module push covering game-physics polish (ragdoll / character state / netcode prediction / IK), soft-body simulation (SDF SPH / SDF character / SDF FEM / SDF wind), engineering research (composite failure / transient thermal / rolling contact fatigue / VIV / piezoelectric / acoustic / electromagnetic), and multi-material coupling (buoyancy zone / anisotropic friction / kinematic loop). All bit-exact across platforms (Determinism scope); formula sources cited in module docs.
Tier ★★★ — 5 modules (real-world critical, downstream-load-bearing)
| Module | Purpose |
|---|---|
ragdoll |
Humanoid ragdoll builder with pose targets, joint limits, breakable constraints (G1) |
buoyancy_zone |
Bounded 3-D fluid volume with buoyancy + drag, fluid-surface CSF coupling (G2) |
laminate_failure |
Tsai-Wu / Tsai-Hill / Hashin / Puck composite failure indices (R1) |
transient_thermal |
Temperature-dependent material properties + 1-D unsteady heat solver + phase-boundary tracking (R2) |
ALICE-SDF morphology |
Signed offset + tolerance fit check for print clearance (S1, ships in ALICE-SDF v1.7.7) |
Tier ★★ — 7 modules (broad utility, cross-domain glue)
| Module | Purpose |
|---|---|
wind_zone |
Bounded 3-D wind volume with drag + lift on rigid / soft bodies (G3) |
sdf_character |
SDF-terrain-aware character controller with slope / step / air-time state (S4) |
rolling_contact |
Rolling contact fatigue (Hertz + subsurface shear + Basquin S-N cycle counting) (R3) |
netcode_prediction |
Client-side prediction + reconciliation + input replay (G5) |
character_state |
Character FSM (idle / walk / run / jump / fall / crouch) with transition validation (G6) |
sdf_sph |
SDF-boundary SPH fluid with density / viscosity / surface tension (S3) |
kinematic_loop |
Kinematic body loop constraint solver for closed-chain mechanisms (R4) |
Tier ★ — 8 modules (specialized engineering / research)
| Module | Purpose |
|---|---|
ik_physics_bridge |
Physics-aware IK solver with joint-limit respecting FABRIK / CCD backend (G4) |
anisotropic_friction |
Direction-dependent friction coefficient (rolling vs sliding, wood grain, fabric) (G7) |
aeroelasticity |
Vortex-induced vibration (VIV) + flutter + galloping for slender structures (R5) |
piezoelectric |
Piezoelectric coupling for sensors / actuators (voltage ↔ strain) (R6) |
acoustic_wave |
1-D / 2-D / 3-D acoustic wave propagation with material impedance boundary (R7) |
electromagnetic |
Electromagnetic force field (Lorentz / induction / eddy current) for conductor bodies (R8) |
sdf_fem_mesh |
SDF-to-tetrahedral FEM mesh generator for large-deformation simulation (S2) |
sdf_wind_field |
SDF-boundary-aware wind field with turbulence intensity + gust modeling (S5) |
Features
| Feature | Description |
|---|---|
| 128-bit Fixed-Point | I64F64 format (64-bit integer + 64-bit fraction) for extreme precision |
| CORDIC Trigonometry | Deterministic sin/cos/atan without FPU instructions |
| XPBD Solver | Extended Position Based Dynamics for stable constraint solving |
| GJK/EPA Collision | Robust collision detection for convex shapes |
| Stackless BVH | Morton code-based spatial acceleration with escape pointers |
| Constraint Batching | Graph-colored parallel constraint solving |
| Rollback Support | Complete state serialization for netcode |
| Neural Controller | Deterministic AI via ALICE-ML ternary weights + Fix128 inference |
| 12 Joint Types | Ball, Hinge, Fixed, Slider, Spring, D6, Cone-Twist, Pulley, Gear, Weld (breakable), Rack-and-Pinion, Mouse |
| Raycasting | Ray and shape casting against spheres, AABBs, capsules, planes |
| Shape Cast / Overlap | Sphere cast, capsule cast, overlap sphere, overlap AABB queries |
| CCD | Continuous collision detection (TOI, conservative advancement) |
| Sleep/Islands | Automatic sleep with Union-Find island management |
| Triangle Mesh | BVH-accelerated triangle mesh collision (Moller-Trumbore) |
| Height Field | Grid terrain with bilinear interpolation |
| Articulated Bodies | Multi-joint chains, ragdolls, robotic arms with FK propagation |
| Force Fields | Wind, gravity wells, drag, buoyancy, vortex, explosion, magnetic dipole |
| PD Controllers | 1D/3D proportional-derivative joint motors |
| Collision Filtering | Layer/mask bitmask system with collision groups |
| Trigger/Sensor | Sensor bodies that detect overlap without physics response |
| Character Controller | Kinematic capsule-based move-and-slide with stair stepping and SDF terrain |
| Rope | XPBD distance chain rope and cable simulation |
| Cloth | XPBD triangle mesh cloth with self-collision (spatial hash grid) |
| Fluid | Position-Based Fluids (PBF) with spatial hash grid |
| Deformable | FEM-XPBD deformable body (tetrahedral mesh) |
| Vehicle | Wheel, suspension, engine, steering, gear shifting |
| Animation Blend | Ragdoll-to-animation blending with SLERP |
| Audio Physics | Physics-based audio parameter generation (impact, friction, rolling) |
| SDF Manifold | Multi-point contact manifold from SDF surfaces |
| SDF CCD | Sphere tracing continuous collision detection for SDF |
| SDF Force Fields | SDF-driven force fields (attract, repel, contain, flow) |
| SDF Destruction | Real-time CSG boolean destruction |
| SDF Adaptive | Adaptive SDF evaluation with distance-based LOD |
| Convex Decompose | Convex decomposition from SDF voxel grid |
| GPU SDF | GPU compute shader interface for batch SDF evaluation |
| Fluid Netcode | Deterministic fluid netcode with delta compression |
| Simulation Fields | 3D scalar/vector fields with trilinear interpolation and diffusion |
| Thermal | Heat diffusion, melt, thermal expansion, freeze |
| Pressure | Contact force accumulation, crush, bulge, dent deformation |
| Erosion | Wind, water, chemical corrosion, ablation |
| Fracture | Stress-driven crack propagation with CSG subtraction |
| Phase Change | Solid/liquid/gas transitions driven by temperature |
| Deterministic RNG | PCG-XSH-RR pseudo-random number generator |
| Contact Events | Begin/Persist/End contact and trigger event tracking |
| Box/OBB Collider | Oriented Bounding Box with GJK support and fast AABB |
| Compound Shape | Multi-shape compound collider with local transforms |
| Contact Cache | Persistent manifold cache with HashMap O(1) lookup and warm starting |
| Dynamic AABB Tree | Incremental BVH with O(log n) insert/remove/update, AVL balancing |
| D6 Joint | 6-DOF configurable joint with per-axis lock/free/limit |
| Cone-Twist Joint | Ball joint with cone swing limit and twist limit |
| Material Table | Per-pair friction/restitution with combine rules (Avg, Min, Max, Mul) |
| Scaled Shape | Uniform scale wrapper for any Support-implementing shape |
| Speculative CCD | Speculative contacts for fast-moving bodies without time rewinding |
| Featherstone | O(n) forward dynamics for articulated bodies |
| Debug Render | Wireframe visualization API (bodies, contacts, joints, BVH, forces) |
| Profiling | Per-stage timer and per-frame statistics API |
| Substep Interpolation | WorldSnapshot with NLERP quaternion blending for smooth rendering |
| Probabilistic Sketches | HyperLogLog, DDSketch, Count-Min Sketch, Heavy Hitters |
| Streaming Anomaly Detection | MAD, EWMA, Z-score composite detector |
| Local Differential Privacy | Laplace noise, RAPPOR, randomized response |
| Metric Pipeline | Lock-free ring buffer metric aggregation with registry |
| Cone Collider | Cone shape with GJK support (apex +Y, base -Y) |
| Ellipsoid Collider | Three independent semi-axes with anisotropic support |
| Torus Collider | Major/minor radii with Minkowski sum decomposition |
| Plane Collider | Infinite plane (Hessian normal form) with sphere/AABB intersection |
| Wedge Collider | Triangular prism with 6-vertex GJK support |
| Convex Hull Builder | Incremental convex hull from arbitrary point sets |
| 2D Physics | Complete 2D subsystem: SAT collision, XPBD solver, Circle/Polygon/Capsule/Edge shapes |
| Mass Properties | Inertia tensor computation for sphere, box, cylinder, capsule, convex hull |
| Collision Mesh Gen | Marching cubes SDF-to-mesh with edge-collapse simplification |
| Scene I/O | Binary (.aphys) and JSON scene serialization with bit-exact Fix128 roundtrip |
| Cloth-Fluid Coupling | Bidirectional cloth-fluid interaction (drag, buoyancy, boundary repulsion) |
| Rope Attachment | Rigid body rope attachment with compliance and break force |
| Soft Body Cutting | Plane-based cutting of deformable bodies and cloth |
| Stress Heatmap | Stress/temperature/pressure 2D slice visualization with viridis colormap |
| Flow Visualization | Fluid velocity field arrows and streamline generation |
| Contact Visualization | Contact force arrows and friction cone rendering |
| Multi-World | Multiple independent physics worlds with body transfer |
| Particle System | General-purpose emitters, lifetime, force field integration |
| no_std Compatible | Works on embedded systems and WebAssembly |
Session 1-3 Additions (v0.10-0.12)
Three completeness sessions added 35 modules + 3 integrated solver loops + 3 runnable examples to close the gap between "physics primitives" and "usable engineering solvers." Every addition is bit-exact across platforms (see Determinism scope) and cites the source formula (Roark / Timoshenko / Simo & Hughes / Jones / Tsai-Wu / Hill / Norton / Findley / WLF / Brackbill / Smagorinsky / Launder-Spalding / Wilcox / Hasselmann / Turns / Anderson / etc.).
Session 1 — 3D Print Safety + Structural Tier 1 (v0.10)
| Module | Purpose | Formula source |
|---|---|---|
filament_db |
10-material property DB (Young's / yield / tensile / density / Tg / anisotropy) | MatWeb / ASM Metals Handbook |
thin_wall |
SDF sphere-marching wall thickness detection | Bambu/Prusa min-wall guidance |
beam_stress |
Cross-section + load case + Euler buckling + FoS | Roark's Formulas for Stress and Strain |
support_volume |
Overhang → filament mm³ + print time estimate | Bambu Studio support manual |
anisotropic |
9-constant orthotropic + Hill + Tsai-Wu failure | Jones, Mechanics of Composite Materials |
plastic |
von Mises + isotropic/kinematic/combined hardening + Norton creep | Simo & Hughes; Norton (1929) |
buckling |
Johnson / Euler / plate / snap-through | Timoshenko & Gere; Bažant & Cedolin |
hyperelastic |
Neo-Hookean / Mooney-Rivlin / Yeoh | Ogden (1984); Yeoh (1990) |
bimaterial |
Timoshenko bimetal residual + Voigt/Reuss bounds | Timoshenko (1925) |
layer_adhesion |
XY vs Z 6-component effective strength envelope | Empirical FDM data |
print_orientation |
Load-direction optimization + Euler grid search | Anisotropy transformation |
bridging |
Material-specific max bridge distance check | Bambu/Prusa knowledge base |
warp_risk |
Cooling shrinkage × footprint → Low/Medium/High/Critical | ALICE-Bamboo docs incident-tuned |
Session 2 — Structural Tier 2 + Fluid Tier 1-2 (v0.11-0.12)
| Module | Purpose | Formula source |
|---|---|---|
fatigue |
Basquin S-N + Miner cumulative damage | Basquin (1910); Miner (1945) |
modal |
1-DOF / beam / Warburton plate / torsional natural frequency | Blevins; Warburton (1954) |
damping_rayleigh |
C = αM + βK + fit_two_modes | Clough & Penzien |
laminate |
Classical Laminate Theory ABD matrix | Jones eq. 2.84 |
prestressed |
Motosh bolt preload + parabolic cable pretension | Shigley; VDI 2230 |
fillet_stress |
Kirsch / Inglis / Peterson K_t | Peterson; Pilkey; Norton |
vibration_wall |
Thin-wall resonance vs 6 printer excitation presets | Blevins; Bambu X1C spec |
thermal_stress |
Constrained σ = c·E·α·ΔT + Tg proximity warning | Timoshenko & Goodier |
creep_longterm |
Findley 3-parameter + WLF time-temperature superposition | Findley (1989); Williams et al. (1955) |
non_newtonian |
Power-law / Carreau / Bingham / Herschel-Bulkley | Bird, Stewart, Lightfoot |
multiphase |
VOF advection + level set reinit + curvature | Hirt & Nichols (1981); Osher & Sethian (1988) |
compressible |
Ideal gas + Rankine-Hugoniot shock + Riemann invariants | Anderson, Modern Compressible Flow |
eulerian_grid |
Staggered MAC + Jacobi/red-black GS pressure projection | Harlow & Welch (1965) |
turbulence |
Smagorinsky LES + k-ε + k-ω + wall function | Pope; Wilcox; Launder & Spalding |
surface_tension_csf |
Continuum Surface Force | Brackbill, Kothe & Zemach (1992) |
fsi_advanced |
Solid ↔ fluid drag / buoyancy / reaction | Peskin immersed boundary |
smoke_fire |
Arrhenius reaction + soot + Boussinesq buoyancy | Turns; Kuo |
wave_ship |
JONSWAP spectrum + Froude-Krylov + 2-DOF | Hasselmann (1973); Faltinsen |
interface_capture |
Fast Sweeping FSM + PLIC (Rider-Kothe analytical) | Zhao (2005); Youngs (1982) |
Session 3 — Solver Loops + 12 Improvements + 3 Demos (v0.12)
Integrated solver loops — single step(dt) entry points that compose
the Session 1-2 modules into a driven simulation:
| Solver | Composes |
|---|---|
cfd_solver::CfdSolver |
MAC + turbulence + non-Newtonian + level_set + CSF + Boussinesq + gravity |
structural_solver::StructuralSolver |
beam + plastic + creep + fatigue + buckling with history tracking |
print_pipeline_solver |
10 print-safety checks (warp + layer + orientation + thermal + beam + bridging + support + fillet + bimaterial) in one shot |
12 improvements — accuracy / performance / robustness:
- I1
math_utilsharedexp_fix/cbrt_fix/pow_int/clamp_fix - I2
eulerian_gridtrilinear P2G / G2P (was nearest-cell) - I3
multiphasesemi-Lagrangian advection (was first-order upwind) - I4 PLIC Rider-Kothe analytical + cbrt (bisection collapse)
- I5 FSM Godunov 3-neighbour quadratic Eikonal (was min + dx)
- I6
safety::sdf_aabbNaN/degenerate/min-dim guards - I7
safety_validateintegratesthin_wall+layer_adhesion+thermal_stress - I8 turbulence log-law wall function +
ln_fix - I9 pressure projection red-black Gauss-Seidel (~2× convergence)
- I10 dynamic Smagorinsky Germano estimator
- I11
laminate::compute_abdrayon parallel (feature-gated) - I12
fatigue::stress_at_cyclesNewton early exit
3 runnable examples demonstrating the solvers end-to-end:
cfd_smoke_plume demonstrates bit-exact v_y = -g·t recovery, with the
pressure projection maintaining zero divergence at the grid centre throughout
the run. print_full_safety exercises all 10 safety checks and returns a
realistic UNSAFE verdict for a 300 × 300 × 5 mm PLA plate (Warp Critical /
Beam FoS 1.16 / Fillet K_t 3.30) — exactly matching the failure mode
documented in the ALICE-Bamboo warp incident.
Test count
Session 1 baseline (v0.9): 719 → Session 1 end (v0.10): 904 → Session 2 end (v0.11): 1170 → Session 3 end (v0.12): 1175 alice-physics tests + 53 alice-bamboo integration tests, all passing.
Sub-stepping TGS Solver — v1.0 status: pub(crate) internal
The trait-abstracted temporal Gauss-Seidel solver primitives (TgsHooks, ImpulseCache, build_islands, 6-DOF hooks, per-island scoped solve, rayon parallelisation, quaternion orientation integration) exist in-crate as solver_tgs* modules but are pub(crate) since 1.0.0 — the extension mechanism had zero downstream adoption during the v1.0 API audit (Option C, see docs/PUB_AUDIT_FINAL.md). The primary PhysicsWorld::step API uses its own internal TGS solver in crate::solver and remains fully public. If your project needs a generic hooks-based TGS integrator, open an issue — re-exposing pub(crate) items via a semver-minor bump is non-breaking.
Advanced solver primitives (Turn D / Phase E / Phase F)
Additional building blocks stacked on top of the sub-stepping TGS core:
-
Adaptive sub-stepping —
AdaptiveSubStepConfig+HasVelocity+adaptive_substeps_forcompute a deterministic sub-step count from the fastest body's L∞ velocity (Fix128 pure, closed-form, division-free — safe under lockstep and rollback) -
CCD-optimised adaptive sub-stepping —
adaptive_substeps_for_ccdtightens the per-step translation cap tosmallest_collider_radius × safety_factor, guaranteeing fast bodies never tunnel through thin walls -
Adaptive sub-TOI —
adaptive_toi_substepsbridges Adaptive sub-stepping with the existingspeculative_contactTOI so a pair on a collision course overdtimmediately requestsmax_substeps(Phase F 11.1, body complete) -
ImpulseCacheobservability —hits/misses/stats/hit_rate/reset_statsexpose warm-starting effectiveness so callers can gauge whether contact IDs stay stable across frames (high hit rate) or the scene is churning (low hit rate) -
Per-island scoped oriented solve —
solver_tgs_hooks_6dof_oriented_scopedextracts an isolated body / contact subset per island for the full 6-DOF oriented hook, prevents gravity double-counting, and preserves bit-perfect parallel-vs-serial equality -
LinearBvh::refit_leaves(bottom-up) — retains the flat tree structure while requantising leaf AABBs and propagating unions to internal nodes in the i32 domain (no CORDIC / rounding dependency), enablingO(N)refit as an alternative to full rebuild -
BroadphaseHybrid— layers aSpatialGridhash grid over a staticLinearBvh(Turn D 5' plan), reducing per-frame broad-phase work fromO(N_total log N_total)toO(N_dynamic + log N_static). Recommended per-frame flow:clear_dynamic→insert_dynamic× N →build_dynamic→query_pairs -
FeatherstoneSolver::solve_with_mass_splitting— extends the O(n) forward-dynamics solver with a mass-ratio split threshold (heavy / light > threshold →dt / 2× 2 recursion), relieving stiffness-induced ill-conditioning for extreme mass-ratio stacks. Determinism preserved via lookup-free multiplicative comparison andFix128::half(Phase F 11.2, body + 3 tests complete) -
FFI byte-for-byte determinism —
AliceVec3Fix128Raw+alice_physics_body_get_position_fix128_rawexpose Fix128 hi/lo pairs across the C ABI.ffi_contract_gravity_fall_deterministicasserts a bracket bound plus a full second-world replay that must produce the exact same hi/lo pair, so Unity / UE5 hosts can assert bit-pattern equality (Phase F 11.3, runtime determinism gate complete) -
GpuSolverBridgetrait (--features gpu-solver-bridge) — opt-in extension surface for external GPU offload backends (e.g. ALICE-TRTTrtSolverAdapter). Ships withDiffFixture/GpuDivergencetypes so implementations must certify byte-for-byte equivalence with the CPU-side solver before the runtime accepts them. Default builds keep the CPU-native TGS pipeline as the only code path
Companion crate — ALICE-TRT (GPU solver offload)
Pair with ALICE-TRT v1.0.0+ --features physics-solver for the reference GpuSolverBridge implementation (TrtSolverAdapter). Enabling physics-solver on ALICE-TRT automatically activates gpu-solver-bridge on this crate, so a single feature line covers both sides. ALICE-TRT v1.x is semver-stable — public adapter surface (send_island / dispatch_iterations / set_gravity / set_floor / push_distance_constraint / recv_island / assert_bit_exact_vs_cpu) is byte-stable across the v1.x line.
[]
= { = "1", = ["gpu-solver-bridge"] }
= { = "3.1", = ["physics-solver"] }
use ;
use Fix128;
use ;
// Live PGS dispatch (integrate + gravity + floor + multi-distance constraints)
let device = new?;
let mut adapter = new;
adapter.send_island;
adapter.set_gravity;
adapter.set_floor;
adapter.push_distance_constraint; // Gauss-Seidel ordered
adapter.push_distance_constraint;
adapter.dispatch_iterations; // real GPU dispatch, not a stub
adapter.recv_island;
// Production gate: certify byte-for-byte equivalence with the CPU solver.
adapter.assert_bit_exact_vs_cpu?;
Companion releases: ALICE-TRT v3.1.0 (coordinated with alice-physics v0.12.0 for joint-solve GPU offload). Every ALICE-TRT release is validated on macOS (Metal) / Ubuntu (Vulkan lavapipe) / Windows (DX12 WARP) with 37 Fix128 unit tests + 170 physics-solver tests, all byte-exact against the CPU golden.
Determinism guardrails for every primitive above are documented in the deterministic-physics-lockstep-discipline skill (private reference).
Optimizations ("黒焦げ" Edition) — 100/100
ALICE-Physics achieves a perfect 100/100 optimization score across 6 layers:
Optimization Scorecard
| Layer | Score | Key Techniques |
|---|---|---|
| L1: Memory Layout | 15/15 | #[repr(C, align(64))] on RigidBody/Cloth/Fluid, hot/cold field reorder |
| L2: Execution | 20/20 | #[inline(always)] on GJK/BVH/constraints, branchless select, precomputed grid_half |
| L3: Compute | 20/20 | Warm-start cached_lambda, reciprocal precomputation (inv_rest_length, inv_rest_density) |
| L4: GPU & Throughput | 15/15 | SIMD_WIDTH const + simd_width(), GpuSdfInstancedBatch/GpuSdfMultiDispatch, batch_size() |
| L5: Build Profile | 10/10 | opt-level=3, lto="fat", codegen-units=1, panic="abort", strip=true |
| L6: Code Quality | 20/20 | 1372 lib tests + 53 alice-bamboo integration tests + 8 fuzz targets + 44 determinism tests (6-platform bit-exact, Fix128 + f32 golden), clippy -D warnings (default + full native feature set, all targets), MSRV 1.70.0 CI job, #![deny(missing_docs)], cargo-semver-checks hard-gated |
| Total | 100/100 |
L1: Memory Layout (15/15)
All hot data structures use 64-byte cache-line alignment with hot/cold field separation:
- RigidBody (
solver.rs):#[repr(C, align(64))]+ hot/cold field reorder - Cloth (
cloth.rs):#[repr(C, align(64))]+ precomputedinv_rest_lengthper edge constraint - Fluid (
fluid.rs):#[repr(C, align(64))]+ precomputedinv_rest_densityandgrid_half
L2: Execution Model (20/20)
Aggressive inlining and branchless execution across all hot paths:
- GJK/BVH: All support functions and traversal marked
#[inline(always)](35 annotations total) - Constraint solving:
#[inline(always)]on distance/contact constraint kernels - Fluid spatial grid:
grid_halfprecomputed at construction, eliminates repeated division inhash()hot path - Branchless primitives (
math.rs):select_fix128(),select_vec3()— CMOV-equivalent using bitwise masks, zero pipeline flushes
L3: Compute Strategy (20/20)
Division elimination and warm-starting for faster convergence:
- Distance constraint warm-start:
cached_lambdafield stores the Lagrange multiplier from the previous substep, biasing the initial guess for dramatically faster convergence - Cloth reciprocal precomputation:
inv_rest_lengthcomputed once at construction, constraint solving uses multiplication instead of division - Fluid reciprocal precomputation:
inv_rest_densityeliminates 2+ divisions per particle per iteration in incompressibility constraint - Contact manifold warm-start: Per-contact
lambda_n,lambda_t1,lambda_t2accumulated across frames viaapply_warm_start() - Contact modifier parallel pre-pass:
pre_process_contacts()runs sequentially before Rayon parallel dispatch, applying pre-solve hooks and contact modifiers safely without data races
L4: GPU & Throughput (15/15)
SIMD-width-aware batching for optimal GPU and CPU utilization:
// Compile-time CPU feature detection
pub const SIMD_WIDTH: usize = simd_width;
// AVX2=8, SSE=4, NEON=4, scalar=1
SIMD_WIDTHconstant (math.rs): Compile-time CPU feature detection (AVX2=8, SSE=4, NEON=4, scalar=1)GpuSdfInstancedBatch(gpu_sdf.rs): Groups SDF queries by ID to minimize GPU kernel launchesGpuSdfMultiDispatch(gpu_sdf.rs): Manages multiple GPU batches withtotal_queries()andtotal_dispatches()statisticsbatch_size()(gpu_sdf.rs): ReturnsSIMD_WIDTHfor register-width-aligned data streams
L5: Build Profile (10/10)
[]
= 3 # Maximum optimization
= "fat" # Link-time optimization (all crates unified)
= 1 # Single code generation unit (maximum optimization)
= "abort" # No unwinding tables
= true # Strip symbols
L6: Code Quality (20/20)
- 1382 lib tests + 44 determinism tests across the alice-physics crate (Iter 2-6 audit + v1.0 stable release additions + v1.0.1 coloring / island / Fix128 tests)
- 53 alice-bamboo integration tests (end-to-end 3D-print safety scenarios)
- 7 fuzz targets (
fuzz_step,fuzz_collision,fuzz_deterministic_roundtrip,fuzz_joint,fuzz_cfd,fuzz_ccd,fuzz_trimesh) - Total: 1522 passing tests in
cargo test(default features: 1382 lib + 44 determinism (9 Fix128 golden + 13 f32 golden + 22 semantic) + 75 integration + 21 doctests; 1426 lib tests with the full native feature set), clippy: 0 warnings under-D warnings(default +std,simd,parallel,ffi,gpu-solver-bridge,neural,replay,analytics,--all-targets),#
Additional Optimizations
Stackless BVH Traversal
Traditional BVH traversal uses a stack to track nodes to visit. Our implementation uses escape pointers embedded in each node:
┌──────────────────────────────────────────────────────┐
│ BvhNode Layout (32 bytes, cache-aligned) │
├──────────────────────────────────────────────────────┤
│ aabb_min[3] (12 bytes) - Bounding box min │
│ first_child/prim (4 bytes) - Child or prim idx │
│ aabb_max[3] (12 bytes) - Bounding box max │
│ prim_count_escape (4 bytes) - [count:8|escape:24]│
└──────────────────────────────────────────────────────┘
Traversal: single index variable, no stack allocation
if (hit) → descend to first_child
if (miss) → jump to escape_idx (skip entire subtree)
Benefits:
- Zero heap allocation during queries
- Single register for traversal state
- Better branch prediction
- i32 AABB comparison (no Fix128 reconstruction)
SIMD Acceleration (optional)
Enable with --features simd:
// x86_64 with SSE2
Constraint Batching (optional)
Enable with --features parallel:
Constraints are grouped by graph coloring - constraints with no shared bodies are placed in the same "color" and can be solved independently:
// Rebuild constraint batches (greedy graph coloring)
world.rebuild_batches;
// Step with batched constraint solving
world.step_parallel;
// Check number of color batches
println!;
Benefits:
- Zero heap allocation in constraint loop (index-based iteration)
- Rayon-ready parallel solving
- Reduced lock contention
- Better cache utilization
HashMap Contact Cache
Contact manifold lookup via BodyPairKey → usize HashMap for O(1) access:
// O(1) manifold lookup (was O(n) linear scan)
Falls back to linear scan for no_std environments.
Rayon Parallel Integration
Enable with --features parallel:
Position integration and velocity updates run in parallel via par_iter_mut():
// Parallel position integration (gravity + damping + Euler)
bodies.par_iter_mut.for_each;
Python Batch APIs
Zero-copy NumPy batch operations with GIL release:
# Batch body creation from (N,4) array [x, y, z, mass]
# Batch velocity update with GIL release
# (N,3)
# Combined state output as (N,10) array [px,py,pz,vx,vy,vz,qx,qy,qz,qw]
=
Why Deterministic Physics?
Traditional physics engines using IEEE 754 floating-point can produce different results across:
- Different CPU architectures (x86 vs ARM)
- Different compilers (GCC vs Clang vs MSVC)
- Different optimization levels (-O0 vs -O3)
- Different instruction sets (SSE vs AVX)
ALICE-Physics guarantees bit-exact results across platforms for every module (see Determinism scope), enabling:
- Lockstep Multiplayer: All clients compute identical simulation
- Rollback Netcode: Replay inputs deterministically
- Replay Systems: Perfect reproduction of game sessions
- Distributed Simulation: Parallel computation with consistent results
Architecture
┌─────────────────────────────────────────────────────────────────────────────┐
│ ALICE-Physics v1.0.0 stable │
│ 1382 lib tests + 44 determinism tests (9 golden + 22 semantic), 6 CI │
├─────────────────────────────────────────────────────────────────────────────┤
│ Core Layer │
│ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐ │
│ │ math │ │ collider │ │ solver │ │ bvh │ │sdf_colldr│ │
│ │ Fix128 │ │ AABB │ │ RigidBody│ │ Morton │ │ SdfField │ │
│ │ Vec3Fix │ │ Sphere │ │ XPBD │ │ Stackless│ │ Gradient │ │
│ │ QuatFix │ │ Capsule │ │ Sensor │ │ Zero- │ │ Early-out│ │
│ │ CORDIC │ │ GJK/EPA │ │ Rollback │ │ alloc │ │ │ │
│ └──────────┘ └──────────┘ └──────────┘ └──────────┘ └──────────┘ │
│ │
│ AAA Engine Layer │
│ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐ │
│ │box_colldr│ │ compound │ │cont_cache│ │dynamic_bv│ │ material │ │
│ │ OBB │ │ Multi- │ │ HashMap │ │ Incr BVH │ │ Pair Tbl │ │
│ │ GJK Supp │ │ Shape │ │ O(1) Get │ │ AVL Bal │ │ Combine │ │
│ │ Inertia │ │ Local Tx │ │ Warm Str │ │ O(log n) │ │ Friction │ │
│ │ Corners │ │ AABB Mrg │ │ 4-point │ │ Fat AABB │ │ Restit │ │
│ └──────────┘ └──────────┘ └──────────┘ └──────────┘ └──────────┘ │
│ ┌──────────┐ ┌──────────┐ ┌──────────┐ │
│ │dbg_rendr │ │profiling │ │ interp │ │
│ │ Wireframe│ │ Timers │ │ Snapshot │ │
│ │ Contacts │ │ Per-Stage│ │ NLERP │ │
│ │ Joints │ │ Stats │ │ Blend │ │
│ │ BVH/AABB │ │ History │ │ Alpha │ │
│ └──────────┘ └──────────┘ └──────────┘ │
│ │
│ Collision Shapes (v0.5.0) │
│ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐ │
│ │ cone │ │ellipsoid │ │ torus │ │plane_col │ │ wedge │ │
│ │ Apex/Base│ │ 3-Axis │ │ Maj/Min │ │ Hessian │ │ TriPrism │ │
│ │ GJK Supp│ │ Aniso │ │ Minkowsk │ │ Sph/AABB │ │ 6-Vertex │ │
│ │ Inertia │ │ Support │ │ Support │ │ Intersct │ │ GJK Supp│ │
│ └──────────┘ └──────────┘ └──────────┘ └──────────┘ └──────────┘ │
│ ┌──────────┐ │
│ │cvx_mesh │ │
│ │ Incr Hull│ │
│ │ Tetra │ │
│ │ Horizon │ │
│ └──────────┘ │
│ │
│ Constraint & Dynamics Layer │
│ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐ │
│ │ joint │ │joint_extr│ │ motor │ │articulatn│ │ force │ │
│ │ Ball │ │ Pulley │ │ PD 1D/3D │ │ Ragdoll │ │ Wind │ │
│ │ Hinge │ │ Gear │ │ Position │ │ FK Chain │ │ Gravity │ │
│ │ Fixed │ │ Weld │ │ Velocity │ │ Robotic │ │ Buoyancy │ │
│ │ Slider │ │ Rack&Pin │ │ Max Torq │ │ Feather- │ │ Drag │ │
│ │ Spring │ │ Mouse │ │ │ │ stone │ │ Vortex │ │
│ │ D6 │ │ Breakabl │ │ │ │ 12-body │ │ Explosion│ │
│ │ ConeTwst │ │ │ │ │ │ │ │ Magnetic │ │
│ │ Breakable│ │ │ │ │ │ │ │ │ │
│ └──────────┘ └──────────┘ └──────────┘ └──────────┘ └──────────┘ │
│ ┌──────────┐ │
│ │ sleeping │ │
│ │ Islands │ │
│ │ Union- │ │
│ │ Find │ │
│ └──────────┘ │
│ │
│ Query & Collision Layer │
│ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐ │
│ │ raycast │ │ ccd │ │ trimesh │ │heightfld │ │ filter │ │
│ │ Sphere │ │ TOI │ │ Triangle │ │ Bilinear │ │ Layer │ │
│ │ AABB │ │ Conserv. │ │ BVH-accel│ │ Normal │ │ Mask │ │
│ │ Capsule │ │ Advance │ │ Moller- │ │ Sphere │ │ Group │ │
│ │ Plane │ │ Swept │ │ Trumbore │ │ Collide │ │ Bidirect │ │
│ │ Sweep │ │ Specultv │ │ Closest │ │ Signed │ │ │ │
│ └──────────┘ └──────────┘ └──────────┘ └──────────┘ └──────────┘ │
│ ┌──────────┐ ┌──────────┐ │
│ │ query │ │character │ │
│ │ SphCast │ │ Move&Sld │ │
│ │ CapCast │ │ Stair │ │
│ │ Overlap │ │ Ground │ │
│ │ AABB Ovr │ │ SDF Terr │ │
│ └──────────┘ └──────────┘ │
│ │
│ Soft Body & Simulation Layer │
│ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐ │
│ │ rope │ │ cloth │ │ fluid │ │deformable│ │ vehicle │ │
│ │ XPBD │ │ XPBD │ │ PBF │ │ FEM-XPBD │ │ Wheel │ │
│ │ Distance │ │ Triangle │ │ SPH Hash │ │ Tetrahedr│ │ Suspensn │ │
│ │ Chain │ │ Self-Col │ │ Density │ │ Volume │ │ Engine │ │
│ │ Cable │ │ SpatHash │ │ Viscosty │ │ Neo-Hook │ │ Steering │ │
│ └──────────┘ └──────────┘ └──────────┘ └──────────┘ └──────────┘ │
│ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐ │
│ │clth_flud │ │rope_atth │ │soft_cut │ │ particle │ │
│ │ Drag │ │ RigidBdy │ │ Plane │ │ Emitters │ │
│ │ Buoyancy │ │ Complnce │ │ Deform │ │ Lifetime │ │
│ │ Boundary │ │ Break │ │ Cloth │ │ ForceInt │ │
│ └──────────┘ └──────────┘ └──────────┘ └──────────┘ │
│ │
│ SDF Advanced Layer │
│ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐ │
│ │sdf_mnfld │ │ sdf_ccd │ │sdf_force │ │sdf_destr │ │sdf_adapt │ │
│ │ Manifold │ │ SphTrace │ │ Attract │ │ CSG Bool │ │ LOD │ │
│ │ N-point │ │ March │ │ Repel │ │ Subtract │ │ Distance │ │
│ │ Contact │ │ TOI │ │ Contain │ │ Real-time│ │ Adaptive │ │
│ └──────────┘ └──────────┘ └──────────┘ └──────────┘ └──────────┘ │
│ ┌──────────┐ ┌──────────┐ │
│ │cvx_decomp│ │ gpu_sdf │ │
│ │ Voxel │ │ Compute │ │
│ │ Flood │ │ Batch │ │
│ │ Convex │ │ Shader │ │
│ └──────────┘ └──────────┘ │
│ │
│ SDF Simulation Modifiers Layer │
│ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐ │
│ │sim_field │ │sim_modif │ │ thermal │ │ pressure │ │ erosion │ │
│ │ Scalar3D │ │ Modifier │ │ Heat Eq │ │ Crush │ │ Wind │ │
│ │ Vector3D │ │ Chain │ │ Melt │ │ Bulge │ │ Water │ │
│ │ Trilin │ │ Modified │ │ Freeze │ │ Dent │ │ Chemical │ │
│ │ Diffuse │ │ SDF │ │ Expand │ │ Yield │ │ Ablation │ │
│ └──────────┘ └──────────┘ └──────────┘ └──────────┘ └──────────┘ │
│ ┌──────────┐ ┌──────────┐ │
│ │ fracture │ │phase_chg │ │
│ │ Stress │ │ Solid │ │
│ │ Crack │ │ Liquid │ │
│ │ CSG Sub │ │ Gas │ │
│ │ Voronoi │ │ Latent H │ │
│ └──────────┘ └──────────┘ │
│ │
│ 2D Physics Subsystem (v0.5.0) │
│ ┌─────────────────────────────────────────────────────────────────────┐ │
│ │ physics2d │ │
│ │ Vec2Fix, Shape2D (Circle/Polygon/Capsule/Edge), RigidBody2D │ │
│ │ SAT + Voronoi collision, XPBD 2D solver, Joint2D (Rev/Dist/Weld/M) │ │
│ └─────────────────────────────────────────────────────────────────────┘ │
│ │
│ Mesh & I/O Utilities (v0.5.0) │
│ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐ │
│ │mass_prop │ │col_mesh │ │ scene_io │ │multi_wrld│ │
│ │ Sphere │ │ Marching │ │ Binary │ │ N worlds │ │
│ │ Box │ │ Cubes │ │ APHYS │ │ Transfer │ │
│ │ Cylinder │ │ EdgeClps │ │ JSON │ │ Isolate │ │
│ │ PAxis │ │ Simplify │ │ Fix128 │ │ Step All │ │
│ └──────────┘ └──────────┘ └──────────┘ └──────────┘ │
│ │
│ Visualization (v0.5.0) │
│ ┌──────────┐ ┌──────────┐ ┌──────────┐ │
│ │ heatmap │ │ flow_viz │ │contct_viz│ │
│ │ Stress │ │ Arrows │ │ Force │ │
│ │ Temp │ │ Streamln │ │ Friction │ │
│ │ Viridis │ │ Velocity │ │ Cone │ │
│ └──────────┘ └──────────┘ └──────────┘ │
│ │
│ Game Systems Layer │
│ ┌──────────┐ ┌──────────┐ ┌──────────┐ │
│ │anim_blnd │ │audio_phys│ │ netcode │ │
│ │ SLERP │ │ Impact │ │ FrameInp │ │
│ │ Ragdoll │ │ Friction │ │ Checksum │ │
│ │ Blend │ │ Rolling │ │ Snapshot │ │
│ │ IK Mix │ │ Material │ │ Rollback │ │
│ └──────────┘ └──────────┘ └──────────┘ │
│ │
│ Analytics & Privacy Layer │
│ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐ │
│ │ sketch │ │ anomaly │ │ privacy │ │ pipeline │ │
│ │ HyperLog │ │ MAD │ │ Laplace │ │ MetricPi │ │
│ │ DDSketch │ │ EWMA │ │ RAPPOR │ │ RingBuf │ │
│ │ CountMin │ │ Z-score │ │ RandResp │ │ Registry │ │
│ │ HeavyHit │ │ Composit │ │ XorShift │ │ Snapshot │ │
│ └──────────┘ └──────────┘ └──────────┘ └──────────┘ │
│ │
│ Utility Layer │
│ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌─────────────────────────────────┐│
│ │ rng │ │ event │ │fluid_net │ │ neural (ALICE-ML × Phys) ││
│ │ PCG-XSH │ │ Begin │ │ Delta │ │ Ternary {-1,0,+1} → Fix128 ││
│ │ Fix128 │ │ Persist │ │ Compress │ │ Deterministic AI ││
│ │ Direction│ │ End │ │ Snapshot │ │ Ragdoll Controller ││
│ └──────────┘ └──────────┘ └──────────┘ └─────────────────────────────────┘│
└─────────────────────────────────────────────────────────────────────────────┘
Usage
Choose Your Path
Pick the entry point that matches your role. All paths share the same deterministic PhysicsWorld, so you can start simple and layer in advanced features (rollback / GPU offload / joints) later without rewriting.
| You are… | Path | Best for | Section |
|---|---|---|---|
| First time here | Hello, first physics ↓ | Sanity-check the install with a falling sphere | ↓ |
| Simulation dev, want the basics | Basic Simulation | Rigid bodies, gravity, ground, per-frame stepping | ↓ |
| Netcode / lockstep game dev | Rollback Netcode | Snapshot save/load, deterministic replay, Fix128 bit-exact | ↓ |
| Rope / cloth / constraint dev | Distance Constraint + joint module |
Chains, ropes, ragdolls, breakable constraints | ↓ |
| Perf-sensitive (many bodies) | BVH Broad-Phase | Spatial acceleration, zero-alloc queries, Morton codes | ↓ |
| GPU offload (advanced) | GPU Solver Bridge | PGS iteration on GPU via ALICE-TRT, byte-exact vs CPU | ↑ |
| Unity / UE5 / Godot integrator | C-ABI FFI | Fix128 hi/lo pairs across the C ABI, bit-pattern equality | see alice_physics_ffi::* |
| CCD / raycast / trimesh user | Module-specific | ccd / raycast / trimesh modules with dedicated APIs |
see Modules |
Hello, First Physics (30 seconds)
The smallest working sample — one falling sphere onto static ground, step it, print the y-coord:
use *;
let mut world = new;
let sphere = new_dynamic;
let _sphere_id = world.add_body;
world.add_body; // ground plane at y=0
let dt = from_ratio;
for frame in 0..60
Once this runs, jump to the path that matches your role.
Basic Simulation
use *;
Distance Constraint (Rope/Chain)
use *;
Rollback Netcode
use *;
BVH Broad-Phase Collision
use ;
// Build BVH from primitives
let primitives: = bodies.iter.enumerate
.map
.collect;
let bvh = build;
// Query with zero heap allocation (callback version)
bvh.query_callback;
// Or collect results
let hits = bvh.query;
// Get BVH statistics
let stats = bvh.stats;
println!;
Common Recipes
Additional patterns that come up frequently — copy-paste starting points.
1. Raycast against the world
use *;
let ray = Ray ;
if let Some = world.raycast
2. Put idle bodies to sleep (perf win)
// PhysicsConfig has sleeping enabled by default; tune the thresholds when needed.
let mut config = default;
config.sleeping.linear_threshold = from_ratio; // 0.01 m/s
config.sleeping.angular_threshold = from_ratio;
config.sleeping.time_to_sleep = from_ratio; // 0.5 s
let mut world = new;
3. Breakable constraint (rope snap under load)
let constraint = DistanceConstraint ;
let id = world.add_distance_constraint;
world.set_constraint_break_force; // snaps > 500 N
4. Static-ground quick setup
let ground = new_static;
let ground_id = world.add_body;
world.set_collider;
5. Save + reload a snapshot (rollback primitive)
let snapshot: = world.serialize_state; // byte-exact across arch
// ... later, or on another machine:
world.deserialize_state; // resumes at frame boundary
6. Continuous collision (fast-moving projectile)
use ccd;
let bullet = new_dynamic;
let bullet_id = world.add_body;
world.enable_ccd; // subswept collision, avoids tunneling
Session 3 Solver Loops (v0.12)
CFD gravity settling — solve incompressible Navier-Stokes for one time step with pressure projection:
use CfdSolver;
use Fix128;
let mut solver = new;
solver.jacobi_iterations = 100;
// Water in gravity, closed box → settles, divergence ≈ 0
for _ in 0..30
// solver.grid.v[…] centre column will read −0.294 m/s at t = 0.03 s
// matching −g·t exactly (bit-exact recovery of the free-fall analytical solution)
Structural creep + fatigue history — advance a PLA shelf through 20 h of sustained load at 55 °C and print the diagnostic table:
use ;
use MaterialProperties;
use Fix128;
use StructuralSolver;
let section = Rectangular ;
let load = SimplySupportedCenter ;
let mut solver = new;
solver.operating_temp_c = from_int;
solver.dt_s = from_int; // 1-hour steps
let history = solver.run;
println!;
Print pipeline safety — run 10 print-safety checks in one call:
use ;
use Fix128;
use LoadDirection;
use ;
use OverhangRegion;
use Footprint;
let footprint = Footprint ;
let inputs = PrintPipelineInputs ;
let report = analyze_print_pipeline;
report.print;
// Prints warp / strength envelope / thermal / beam FoS / bridging /
// support volume / K_t / bimaterial and an overall SAFE / UNSAFE verdict.
Where to go next
| I want to… | See |
|---|---|
| Understand the full type surface | Modules section below |
| Deep dive into determinism guarantees | Why Deterministic Physics? |
| Offload PGS iterations to the GPU | Companion crate — ALICE-TRT |
| Wire into Unity / UE5 native plugin | alice_physics_ffi::* (module in this crate) |
| See the joint catalog (12 base + 5 advanced) | joint / joint_extra sections |
| Prove byte-exact CI on 3 platforms | See ALICE-TRT's Fix128 + physics-solver test matrix (companion release) |
| Compare to Rapier / PhysX / Box2D | Why Deterministic Physics? benchmark table |
Companion crates that plug directly into PhysicsWorld:
- ALICE-TRT (
gpu-solver-bridgefeature) — GPU PGS solver offload with byte-exact CPU parity - ALICE-Cloth — XPBD cloth on top of the same Fix128 primitives
- ALICE-Vehicle — Deterministic vehicle rig
- ALICE-Netcode — Rollback netcode plumbing built for
serialize_state/deserialize_state
Modules
math - Fixed-Point Primitives
| Type | Description |
|---|---|
Fix128 |
128-bit fixed-point number (I64F64) |
Vec3Fix |
3D vector with Fix128 components |
QuatFix |
Quaternion for rotations |
Mat3Fix |
3x3 matrix for inertia tensors |
Constants:
Fix128::ZERO,Fix128::ONE,Fix128::NEG_ONEFix128::PI,Fix128::HALF_PI,Fix128::TWO_PI
CORDIC functions (deterministic, no FPU):
Fix128::sin(),Fix128::cos(),Fix128::sin_cos()Fix128::atan(),Fix128::atan2()Fix128::sqrt()(Newton-Raphson, 64 iterations)
Utility:
Fix128::from_ratio(num, denom)- Create from fractionFix128::half(),Fix128::double()- Exact bit shiftsFix128::abs(),Fix128::floor(),Fix128::ceil()
collider - Collision Detection
| Shape | Description |
|---|---|
AABB |
Axis-Aligned Bounding Box |
Sphere |
Sphere collider |
Capsule |
Capsule (cylinder + hemispheres) |
ConvexHull |
Arbitrary convex polyhedron |
CollisionResult |
Contact information |
Algorithms:
- GJK: Gilbert-Johnson-Keerthi for intersection test (64 iterations max)
- EPA: Expanding Polytope Algorithm for penetration depth (64 iterations max)
solver - XPBD Physics
RigidBody fields:
| Field | Type | Description |
|---|---|---|
position |
Vec3Fix |
Center of mass position |
rotation |
QuatFix |
Orientation quaternion |
velocity |
Vec3Fix |
Linear velocity |
angular_velocity |
Vec3Fix |
Angular velocity |
inv_mass |
Fix128 |
Inverse mass (0 = static) |
inv_inertia |
Vec3Fix |
Inverse inertia tensor (diagonal) |
restitution |
Fix128 |
Bounciness (0-1) |
friction |
Fix128 |
Friction coefficient |
is_sensor |
bool |
Sensor mode: detects overlap but no physics response |
Constraints:
DistanceConstraint: Fixed distance between anchor pointsContactConstraint: Collision response with friction/restitution
Methods:
RigidBody::new(position, mass)- Create dynamic bodyRigidBody::new_dynamic(position, mass)- Alias for newRigidBody::new_static(position)- Create immovable bodyRigidBody::new_sensor(position)- Create sensor/trigger body (no physics response)
bvh - Spatial Acceleration
| Type | Description |
|---|---|
LinearBvh |
Flat array BVH with stackless traversal |
BvhNode |
32-byte cache-aligned node with escape pointer |
BvhPrimitive |
Primitive entry for construction |
BvhStats |
Tree statistics |
Features:
- Morton Codes: Z-order curve for spatial locality
- Escape Pointers: Stackless traversal (zero allocation)
- i32 AABB: Fast integer comparison without Fix128 reconstruction
joint - 12 Joint Types + Breakable Constraints
| Type | Description |
|---|---|
BallJoint |
Spherical joint (3 rotational DOF) |
HingeJoint |
Revolute joint (1 rotational DOF) with angle limits |
FixedJoint |
Weld joint (0 DOF) |
SliderJoint |
Prismatic joint (1 translational DOF) with limits |
SpringJoint |
Damped spring constraint |
D6Joint |
6-DOF configurable joint with per-axis lock/free/limit |
ConeTwistJoint |
Ball joint with cone swing limit and twist limit |
joint_extra - 5 Advanced Joints (v0.5.0)
| Type | Description |
|---|---|
PulleyJoint |
Pulley with 2 anchors and rope ratio (total distance constraint) |
GearJoint |
Gear coupling (angular velocity ratio between two bodies) |
WeldJoint |
Rigid weld with break_force / break_torque threshold |
RackAndPinionJoint |
Rotation-to-translation conversion with pitch radius |
MouseJoint |
Target-following joint for mouse/touch drag interaction |
All joint types support breakable constraints via with_break_force(max_force). When the constraint force exceeds the threshold, the joint breaks and is removed from simulation.
use *;
// Hinge with angle limits
let hinge = new
.with_limits;
// D6 joint (lock X translation, free Y rotation, limit Z rotation)
let d6 = new
.with_axis
.with_axis
.with_axis;
// Cone-twist joint (shoulder-like with cone + twist limits)
let cone = new
.with_cone_limit // 45° cone
.with_twist_limit; // 30° twist
// Breakable ball joint (breaks at force > 100)
let ball = new
.with_break_force;
// Solve with breakable support — returns indices of broken joints
let broken = solve_joints_breakable;
raycast - Ray & Shape Casting
| Function | Description |
|---|---|
ray_sphere |
Ray vs sphere intersection |
ray_aabb |
Ray vs AABB (slab method) |
ray_capsule |
Ray vs capsule |
ray_plane |
Ray vs infinite plane |
sweep_sphere |
Moving sphere vs sphere (Minkowski expansion) |
ccd - Continuous Collision Detection
| Function | Description |
|---|---|
sphere_sphere_toi |
Sphere-sphere TOI via quadratic |
sphere_plane_toi |
Sphere-plane TOI |
conservative_advancement |
TOI via iterative safe stepping |
swept_aabb |
Swept AABB bounding volume |
speculative_contact |
Speculative contact for CCD integration with solver |
needs_ccd |
Velocity threshold check for CCD activation |
sleeping - Sleep & Island System
| Type | Description |
|---|---|
IslandManager |
Union-Find island management |
SleepData |
Per-body sleep tracking |
SleepConfig |
Velocity thresholds, idle frame count |
trimesh - Triangle Mesh Collision
| Type | Description |
|---|---|
Triangle |
Single triangle with Moller-Trumbore intersection |
TriMesh |
BVH-accelerated triangle mesh |
Features:
- Ray-triangle intersection (Moller-Trumbore)
- Closest point on triangle
- Sphere-mesh collision detection
heightfield - Height Field Terrain
| Type | Description |
|---|---|
HeightField |
Grid-based terrain with bilinear interpolation |
Features:
sample_height(world_x, world_z)with bilinear interpolationsample_normal(world_x, world_z)from central differencescollide_sphere()for sphere-terrain collisionsigned_distance(point)for point-terrain distance
filter - Collision Filtering
| Type | Description |
|---|---|
CollisionFilter |
Layer/mask bitmask with collision groups |
layers module |
Predefined layers (DEFAULT, STATIC, PLAYER, ENEMY, etc.) |
force - 7 Force Fields
| Variant | Description |
|---|---|
Directional |
Uniform wind/gravity (direction + strength) |
Point |
Radial gravity well with inverse-square falloff |
Drag |
Velocity-proportional drag |
Buoyancy |
Plane-based buoyancy with density |
Vortex |
Spinning vortex field (center + axis + strength) |
Explosion |
Radial impulse with configurable falloff_power attenuation |
Magnetic |
Simplified dipole model with 1/r^3 inverse cube law |
motor - PD Controllers
| Type | Description |
|---|---|
PdController |
1D proportional-derivative controller |
PdController3D |
3D PD controller |
JointMotor |
Joint motor with position/velocity/torque modes |
articulation - Articulated Bodies
| Type | Description |
|---|---|
ArticulatedBody |
Multi-joint chain with FK propagation |
Link |
Joint + body pair in a chain |
Presets:
build_ragdoll()— 12-body humanoid (head, torso, arms, legs)
rng - Deterministic Random
| Type | Description |
|---|---|
DeterministicRng |
PCG-XSH-RR 32-bit generator |
Methods:
next_fix128()— Random Fix128 in [0, 1)range_fix128(min, max)— Random in [min, max)next_direction()— Random unit Vec3Fix
event - Contact Events
| Type | Description |
|---|---|
EventCollector |
Tracks contact begin/persist/end per pair |
ContactEvent |
Body pair + event type + contact point |
ContactEventType |
Begin, Persist, End |
query - Shape Cast & Overlap Queries
| Function | Description |
|---|---|
sphere_cast |
Sweep a sphere along a direction (Minkowski sum approach) |
capsule_cast |
Sweep a capsule along a direction (3-point sphere cast) |
overlap_sphere |
Find all bodies overlapping a sphere |
overlap_aabb |
Find all bodies within an AABB (point test) |
overlap_aabb_expanded |
Find all bodies within an AABB expanded by body radius |
character - Character Controller
| Type | Description |
|---|---|
CharacterController |
Kinematic capsule-based character with move-and-slide |
CharacterConfig |
Radius, height, max slope, step height, skin width |
MoveResult |
Movement result with ground state |
Features:
- Collide-and-slide algorithm with configurable max slides
- Ground detection via downward raycast + SDF
- Stair stepping (automatic step-up for small obstacles)
- SDF terrain integration (push out of SDF surfaces)
rope - XPBD Rope & Cable
| Type | Description |
|---|---|
Rope |
XPBD distance-chain rope simulation |
RopeConfig |
Segment count, length, stiffness, damping |
cloth - XPBD Cloth Simulation
| Type | Description |
|---|---|
Cloth |
XPBD triangle mesh cloth with stretch/shear/bend constraints |
ClothConfig |
Stiffness, damping, self-collision, gravity |
Features:
- Distance constraints (stretch resistance)
- Bending constraints
- Self-collision via spatial hash grid
fluid - Position-Based Fluids
| Type | Description |
|---|---|
Fluid |
Position-Based Fluids (PBF) simulation |
FluidConfig |
Particle count, rest density, viscosity, kernel radius |
Features:
- SPH density estimation with spatial hash grid
- Incompressibility constraint solving
- Viscosity (XSPH)
- Surface tension
deformable - FEM-XPBD Deformable Bodies
| Type | Description |
|---|---|
DeformableBody |
FEM tetrahedral mesh deformable body |
DeformableConfig |
Young's modulus, Poisson's ratio, damping |
vehicle - Vehicle Physics
| Type | Description |
|---|---|
Vehicle |
Complete vehicle simulation |
VehicleConfig |
Wheel count, suspension, engine, steering parameters |
Features:
- Wheel contact with ground/terrain
- Spring-damper suspension
- Engine torque with gear shifting
- Ackermann steering geometry
cone - Cone Collider (v0.5.0)
| Type | Description |
|---|---|
Cone |
Cone collider with apex at +Y and base at -Y |
Features:
- GJK
Supporttrait implementation (apex/base center switching) - AABB computation, volume, surface area, inertia diagonal
- Configurable radius and half-height with rotation
ellipsoid - Ellipsoid Collider (v0.5.0)
| Type | Description |
|---|---|
Ellipsoid |
Ellipsoid with three independent semi-axes (rx, ry, rz) |
Features:
- Anisotropic GJK support (scale direction by radii, normalize, scale back)
- Volume, AABB, and inertia diagonal computation
torus - Torus Collider (v0.5.0)
| Type | Description |
|---|---|
Torus |
Torus with major radius (ring) and minor radius (tube) |
Features:
- GJK support via Minkowski sum decomposition
- Volume and AABB computation
plane_collider - Infinite Plane Collider (v0.5.0)
| Type | Description |
|---|---|
PlaneCollider |
Infinite plane in Hessian normal form (normal + offset) |
Features:
intersect_sphere()— sphere-plane intersection with contact pointintersect_aabb()— AABB-plane overlap testsigned_distance()— point-plane signed distance
wedge - Wedge Collider (v0.5.0)
| Type | Description |
|---|---|
Wedge |
Triangular prism (wedge) with 6 vertices |
Features:
- GJK support (iterates 6 vertices for max dot product)
- Volume, AABB, and centroid computation
convex_mesh_builder - Convex Hull Builder (v0.5.0)
| Function | Description |
|---|---|
build_convex_hull(points) |
Build convex hull from arbitrary point set |
compute_centroid(faces, vertices) |
Compute centroid of convex hull |
Algorithm: Incremental convex hull — find initial tetrahedron, incrementally insert points, remove visible faces, patch with horizon edges.
physics2d - 2D Physics Engine (v0.5.0)
| Type | Description |
|---|---|
Vec2Fix |
2D vector with Fix128 components |
Shape2D |
Circle, Polygon (max 16 vertices), Capsule, Edge |
RigidBody2D |
2D rigid body with position, angle, velocity, angular velocity |
PhysicsWorld2D |
Complete 2D physics world with XPBD solver |
PhysicsConfig2D |
Gravity, substeps, iterations, sleep threshold |
Contact2D |
Contact point with normal, depth, body indices |
Joint2D |
Revolute, Distance, Weld, Mouse joint variants |
BodyType2D |
Dynamic, Static, Kinematic |
Algorithms:
- SAT (Separating Axis Theorem) with Voronoi region classification
- XPBD position-based solver with configurable substeps
- Broad-phase AABB overlap, narrow-phase polygon projection
mass_properties - Mass & Inertia (v0.5.0)
| Function | Description |
|---|---|
sphere_mass_properties(radius, density) |
Sphere mass + inertia tensor |
box_mass_properties(half_extents, density) |
Box mass + inertia tensor |
cylinder_mass_properties(radius, half_h, density) |
Cylinder mass + inertia |
capsule_mass_properties(radius, half_h, density) |
Capsule mass + inertia |
convex_hull_mass_properties(vertices, faces, density) |
Convex hull mass + inertia |
translate_inertia(inertia, mass, offset) |
Parallel axis theorem |
collision_mesh_gen - SDF to Mesh (v0.5.0)
| Type / Function | Description |
|---|---|
CollisionMeshConfig |
Grid resolution, bounding box, simplification target |
CollisionMesh |
Vertices + triangle indices output |
generate_collision_mesh(sdf, config) |
Marching cubes mesh generation |
simplify_mesh(mesh, target) |
Edge-collapse mesh simplification |
scene_io - Scene Serialization (v0.5.0, std)
| Function | Description |
|---|---|
save_binary(path, scene) |
Save to .aphys binary format (bit-exact Fix128) |
load_binary(path) |
Load from .aphys binary format |
save_json(path, scene) |
Save to .aphys.json human-readable format |
load_json(path) |
Load from .aphys.json format |
Binary format: Magic APHYS\0, little-endian, raw Fix128 {hi: i64, lo: u64} for bit-exact deterministic roundtrip.
cloth_fluid - Cloth-Fluid Coupling (v0.5.0)
| Type | Description |
|---|---|
ClothFluidCoupling |
Bidirectional cloth-fluid interaction |
Effects: Fluid drag force on cloth vertices, buoyancy based on submersion, boundary repulsion to prevent penetration.
rope_attach - Rope Attachment (v0.5.0)
| Type | Description |
|---|---|
RopeAttachment |
Attach rope endpoints to rigid bodies |
Features: Configurable compliance, break force threshold, automatic detachment.
soft_body_cut - Soft Body Cutting (v0.5.0)
| Function | Description |
|---|---|
cut_deformable(body, plane) |
Cut deformable body along a plane |
cut_cloth(cloth, plane) |
Cut cloth mesh along a plane |
Algorithm: Plane-based topology splitting — classifies vertices, creates new vertices at intersection points, rebuilds connectivity.
heatmap - Stress/Temperature Heatmap (v0.5.0)
| Type | Description |
|---|---|
Heatmap |
2D scalar field visualization with colormap |
HeatmapConfig |
Resolution, value range, colormap selection |
Features: Viridis colormap, RGBA pixel output, configurable min/max range.
flow_viz - Flow Visualization (v0.5.0)
| Type | Description |
|---|---|
FlowArrow |
Velocity arrow with position, direction, magnitude |
Streamline |
Ordered list of points tracing a flow path |
Functions: generate_flow_arrows(), generate_streamlines() from velocity fields.
contact_viz - Contact Visualization (v0.5.0)
| Type | Description |
|---|---|
ContactArrow |
Force arrow at contact point |
FrictionCone |
Cone geometry representing friction limit |
Functions: visualize_contacts(), visualize_friction_cones() from contact manifolds.
multi_world - Multiple Physics Worlds (v0.5.0)
| Type | Description |
|---|---|
MultiWorld |
Container for N independent physics worlds |
Features:
add_world()/remove_world()— manage independent worldsstep_all(dt)— advance all worlds simultaneouslytransfer_body(from, to, body_id)— move body between worlds
particle - Particle System (v0.5.0)
| Type | Description |
|---|---|
ParticleSystem |
General-purpose particle simulation |
ParticleEmitter |
Directional emitter with cone spread |
Particle |
Position, velocity, age, lifetime, mass |
Features:
- Configurable emission rate, spread angle, speed range
- Lifetime management with automatic recycling
- Full
ForceFieldintegration (including Explosion and Magnetic) - Deterministic via
DeterministicRng
animation_blend - Animation Blending
| Type | Description |
|---|---|
AnimationBlender |
Ragdoll-to-animation pose blending |
BlendMode |
Lerp, Slerp, Additive |
SkeletonPose |
Joint transforms for a skeleton |
AnimationClip |
Keyframed animation data |
audio_physics - Physics-Based Audio
| Type | Description |
|---|---|
AudioGenerator |
Generates audio parameters from physics contacts |
AudioConfig |
Material properties for audio synthesis |
AudioEvent |
Impact, friction, rolling audio events |
AudioMaterial |
Surface material with audio properties |
sdf_manifold - SDF Contact Manifold
Multi-point contact generation from SDF surfaces for more stable collision response.
sdf_ccd - SDF Continuous Collision Detection
Sphere tracing-based CCD for bodies moving against SDF surfaces.
sdf_force - SDF Force Fields
| Variant | Description |
|---|---|
Attract |
Pull bodies toward SDF surface |
Repel |
Push bodies away from SDF surface |
Contain |
Keep bodies inside SDF boundary |
Flow |
Flow field following SDF gradient |
sdf_destruction - SDF Boolean Destruction
Real-time CSG boolean operations for destructible environments.
| Type | Description |
|---|---|
DestructibleSdf |
SDF that accumulates destruction shapes |
DestructionShape |
Sphere, box, or custom SDF subtraction |
sdf_adaptive - Adaptive SDF Evaluation
Distance-based LOD for SDF evaluation — faraway queries use coarser sampling.
convex_decompose - Convex Decomposition
Generate convex hull decomposition from an SDF voxel grid for use with GJK/EPA.
gpu_sdf - GPU Compute Shader
Batch SDF evaluation on GPU via compute shaders. Requires --features std.
fluid_netcode - Fluid Netcode
Deterministic fluid simulation with delta-compressed snapshots for network sync. Requires --features std.
sim_field - 3D Simulation Fields
| Type | Description |
|---|---|
ScalarField3D |
Uniform grid scalar field with trilinear interpolation |
VectorField3D |
Uniform grid vector field with trilinear interpolation |
Features:
- Trilinear interpolation for smooth sampling
- Diffusion (heat equation solver)
- Decay over time
- Point splatting for localized effects
sim_modifier - SDF Simulation Modifiers
| Type | Description |
|---|---|
PhysicsModifier |
Trait for physics-driven SDF modification |
ModifiedSdf |
Chain of modifiers that alter SDF distance |
SingleModifiedSdf |
Single-modifier convenience wrapper |
thermal - Thermal Simulation
| Type | Description |
|---|---|
ThermalModifier |
Heat diffusion SDF modifier |
ThermalConfig |
Conductivity, melt/freeze thresholds |
HeatSource |
Point/area heat source |
Effects: Melt (surface recedes), thermal expansion, freeze (crystalline growth)
pressure - Pressure Simulation
| Type | Description |
|---|---|
PressureModifier |
Contact-force-driven deformation |
PressureConfig |
Yield threshold, elastic spring-back |
Effects: Crush (high pressure), bulge (internal pressure), permanent dents
erosion - Erosion Simulation
| Type | Description |
|---|---|
ErosionModifier |
Surface material removal from forces |
ErosionConfig |
Hardness, erosion rate |
ErosionType |
Wind, Water, Chemical, Ablation |
fracture - Fracture Simulation
| Type | Description |
|---|---|
FractureModifier |
Stress-driven crack propagation |
FractureConfig |
Fracture toughness, crack speed |
Crack |
Individual crack with position and direction |
Effects: Stress accumulation, crack seeds, Voronoi-like fragmentation via CSG subtraction
phase_change - Phase Change Simulation
| Type | Description |
|---|---|
PhaseChangeModifier |
Temperature-driven state transitions |
PhaseChangeConfig |
Melt/boil temperatures, latent heat |
Phase |
Solid, Liquid, Gas |
Effects: Melting (solid→liquid, flows downward), vaporization (liquid→gas, expands), solidification, condensation
box_collider - Oriented Bounding Box
| Type | Description |
|---|---|
OrientedBox |
OBB with center, half-extents, and rotation quaternion |
Features:
- GJK
Supporttrait implementation for collision detection - Fast world-space AABB computation from OBB
- Corner vertices, volume, surface area, inertia tensor
compound - Compound Shape
| Type | Description |
|---|---|
CompoundShape |
Multi-shape collider with local transforms |
ChildShape |
Individual shape + local offset/rotation |
Features:
- Merges child AABBs for broadphase
- Per-child GJK support (transforms direction to child local space)
- Mass properties from children
contact_cache - Persistent Contact Cache
| Type | Description |
|---|---|
ContactCache |
Frame-persistent contact manifold storage |
ContactManifold |
Up to 4 contact points with warm-started lambdas |
Features:
- HashMap O(1) manifold lookup by body pair
- Warm starting (carry lambda across frames for stable stacking)
- Automatic manifold pruning at end of frame
dynamic_bvh - Dynamic AABB Tree
| Type | Description |
|---|---|
DynamicBvh |
Incremental BVH with insert/remove/update |
Features:
- O(log n) insert, remove, and update operations
- AVL-style tree balancing (rotation on height imbalance)
- Fat AABBs with margin to reduce update frequency
- AABB query and ray query
material - Material Pair Table
| Type | Description |
|---|---|
MaterialTable |
Per-pair friction/restitution override table |
MaterialProperties |
Friction, restitution, combine rule |
CombineRule |
Average, Min, Max, Multiply |
debug_render - Debug Visualization
| Type | Description |
|---|---|
DebugRenderer |
Wireframe rendering of physics state |
DebugLine |
Line segment with color |
DebugDrawFlags |
Bitmask for bodies, contacts, joints, BVH, forces |
profiling - Performance Profiling
| Type | Description |
|---|---|
PhysicsProfiler |
Per-stage timing and statistics |
StageTimer |
Individual stage measurement |
FrameStats |
Broadphase/narrowphase/solver/total times |
interpolation - Substep Interpolation
| Type | Description |
|---|---|
WorldSnapshot |
Captured physics state for interpolation |
interpolate_snapshots |
NLERP blending between two snapshots |
Features:
- Capture position + rotation snapshots
- NLERP quaternion interpolation (faster than SLERP, visually smooth)
- Alpha-based blending for fixed-timestep rendering
pipeline - Metric Aggregation Pipeline
| Type | Description |
|---|---|
MetricPipeline |
Lock-free ring buffer metric aggregation engine |
MetricRegistry |
Named metric registration and lookup |
MetricSnapshot |
Point-in-time metric state capture |
MetricEvent |
Timestamped metric event with type and value |
MetricType |
Counter, Gauge, Histogram metric kinds |
RingBuffer |
Fixed-capacity circular buffer for time-series data |
Features:
- Lock-free ring buffer for high-throughput metric collection
- Named metric registry with typed metric support
- Snapshot capture for periodic reporting
- Integrates with
sketchmodule for probabilistic aggregation
sketch - Probabilistic Sketches
| Type | Description |
|---|---|
HyperLogLog |
Cardinality estimation with configurable precision |
DDSketch |
Distribution-aware quantile sketch (P50/P99/P99.9) |
CountMinSketch |
Frequency estimation with configurable width/depth |
HeavyHitters |
Top-k frequent item tracking via Count-Min Sketch |
FnvHasher |
FNV-1a hash for deterministic, allocation-free hashing |
Mergeable |
Trait for sketch merging across distributed workers |
Size variants:
HyperLogLog10(1 KB),HyperLogLog12(4 KB),HyperLogLog14(16 KB),HyperLogLog16(64 KB)DDSketch128,DDSketch256,DDSketch512CountMinSketch256x4,CountMinSketch512x4,CountMinSketch1024x8
anomaly - Streaming Anomaly Detection
| Type | Description |
|---|---|
MadDetector |
Median Absolute Deviation detector |
EwmaDetector |
Exponentially Weighted Moving Average detector |
ZScoreDetector |
Standard Z-score detector with running statistics |
CompositeDetector |
Combines multiple detectors with voting |
StreamingMedian |
O(log n) streaming median via sorted-insert buffer |
AnomalyEvent |
Timestamped anomaly report with severity |
AnomalyCallback |
Callback trait for anomaly notifications |
Features:
- Streaming operation with constant memory per detector
- Composite detector with configurable voting threshold
- Callback-driven anomaly notification
privacy - Local Differential Privacy
| Type | Description |
|---|---|
LaplaceNoise |
Calibrated Laplace mechanism for numeric queries |
Rappor |
RAPPOR protocol for categorical data collection |
RandomizedResponse |
Binary randomized response with tunable epsilon |
PrivacyBudget |
Epsilon budget tracker with composition accounting |
PrivateAggregator |
Privacy-preserving aggregation over multiple queries |
XorShift64 |
Deterministic PRNG for reproducible noise generation |
Features:
- Laplace noise calibrated to sensitivity/epsilon
- RAPPOR with Bloom filter encoding for categorical data
- Composable privacy budget tracking
SDF Collider (ALICE-SDF Integration)
ALICE-Physics can use ALICE-SDF distance fields as collision shapes. Instead of approximating complex shapes with convex hulls (GJK/EPA), the solver samples the SDF directly — giving mathematically exact surfaces at O(1) cost per query.
How It Works
Body (sphere) SdfCollider
┌───┐ ┌──────────────────────┐
│ ● │──world_to_local(pos)──▶│ SdfField::distance() │─── >0 → no hit (early-out)
└───┘ │ SdfField::normal() │─── ≤0 → contact + resolve
│ cached inv_rotation │
│ cached scale_f32 │
└──────────────────────┘
Key Optimizations
| Optimization | Description | Benefit |
|---|---|---|
| Early-out | Call distance() (1 eval) first, only compute normal() (4 evals) on collision |
80% fewer evals for non-colliding bodies |
| Cached invariants | Pre-computed inv_rotation, scale_f32, inv_scale_f32 |
No per-query recomputation |
| Rayon parallel | par_iter_mut over bodies with --features parallel |
Linear speedup with cores |
| 4-eval combined | Tetrahedral gradient gives distance + normal from 4 evals | 1 eval saved vs naive 1+4 |
Usage
use *;
use SdfCollider;
use CompiledSdfField;
use *;
// 1. Create SDF shape in ALICE-SDF
let terrain = plane // ground plane
.union; // hill
let field = new;
// 2. Create physics world
let mut world = new;
// 3. Register SDF as static collider
let collider = new_static;
world.add_sdf_collider;
// 4. Add dynamic bodies — they will collide with the SDF surface
let ball = new_dynamic;
world.add_body;
// 5. Simulate — SDF collisions resolved automatically in step()
let dt = from_ratio;
for _ in 0..300
SdfCollider API
| Method | Description |
|---|---|
SdfCollider::new_static(field, position, rotation) |
Static SDF collider |
SdfCollider::new_dynamic(field, position, rotation, body_index) |
Attached to a body |
.with_scale(scale) |
Set uniform scale (updates cached invariants) |
.update_cache() |
Recompute cached inv_rotation, scale_f32 after manual changes |
collide_point_sdf(point, sdf) |
Point vs SDF contact test |
collide_sphere_sdf(center, radius, sdf) |
Sphere vs SDF contact test |
Requirements
Enable the physics feature in ALICE-SDF:
[]
= { = "../ALICE-SDF", = ["physics"] }
See the ALICE-SDF README for CompiledSdfField details.
Rendering Pipeline Integration (ALICE-SDF v1.4.0+)
ALICE-Physics provides physics state data that drives ALICE-SDF's rendering pipeline destruction uniforms. The physics engine simulates thermal, fracture, erosion, and pressure fields — the application layer samples these fields and uploads them as shader uniforms for real-time visual feedback.
Architecture
ALICE-Physics (CPU) ALICE-SDF Shader (GPU)
┌─────────────────────┐ ┌──────────────────────┐
│ ThermalModifier │──→ sample ──→│ uniform float uShatter│
│ FractureModifier │──→ sample ──→│ uniform float uEntropy│
│ PressureModifier │──→ sample ──→│ uniform float uImpact │
│ ErosionModifier │──→ sample ──→│ uniform vec2 uShake │
│ ForceField::Explosion│──→ sample ──→│ uniform float uMeteorY│
└─────────────────────┘ └──────────────────────┘
↓ Application layer bridges the gap (each frame)
Uniform Mapping
| Physics Source | Field / Method | Rendering Uniform | Description |
|---|---|---|---|
ThermalModifier |
temperature.sample(pos) |
uShatter |
Temperature above melt threshold → destruction intensity |
ThermalModifier |
melt_accumulator.sample(pos) |
uEntropy |
Cumulative material loss (0-1) |
FractureModifier |
stress_field.sample(pos) |
uShatter |
Stress-driven crack propagation |
PressureModifier |
pressure_field.sample(pos) |
uImpact |
Contact force deformation depth |
ForceField::Explosion |
center, radius |
uMeteorImpact, uImpactRing |
Explosion center and blast radius |
| Impact event | collision velocity | uShake |
Camera shake from impact force |
| Projectile body | body.position.y |
uMeteorY |
Falling object altitude |
Example: Physics-Driven Destruction
use ;
use RenderConfig;
// Physics side: thermal simulation
let mut thermal = new;
thermal.add_heat_source;
// Each frame:
thermal.step;
// Application bridge: sample physics → upload to shader
let shatter = thermal.melt_accumulator.sample.min;
let entropy = thermal.temperature.sample / 1000.0;
gl.uniform1f;
gl.uniform1f;
Relevant Modules
| Module | Description | Drives Uniform |
|---|---|---|
thermal.rs |
Heat diffusion, melt, thermal expansion, freeze | uShatter, uEntropy |
fracture.rs |
Stress-driven crack propagation (CSG subtraction) | uShatter |
pressure.rs |
Contact force → crush/bulge/dent deformation | uImpact |
erosion.rs |
Wind, water, chemical, ablation erosion | uEntropy |
sdf_destruction.rs |
Real-time CSG boolean destruction | uImpactRing |
force.rs |
Explosion force field (center, radius, falloff) | uMeteorImpact, uImpactRing |
sim_field.rs |
3D scalar/vector field with trilinear interpolation | All (infrastructure) |
RenderConfig Compatibility
Enable destruction: true in ALICE-SDF's RenderConfig to activate the shader-side destruction features:
let config = RenderConfig ;
Deterministic Neural Controller (ALICE-ML Integration)
ALICE-Physics integrates with ALICE-ML to provide bit-exact deterministic AI for game characters. By combining 1.58-bit ternary weights {-1, 0, +1} with 128-bit fixed-point arithmetic, neural inference reduces to pure addition/subtraction — no floating-point, no rounding, no platform-dependent behavior.
This is the "holy grail" for networked fighting games and action games: all clients compute identical AI behavior without synchronization.
How It Works
Ternary Weight {-1, 0, +1}:
+1 → Fix128 addition
-1 → Fix128 subtraction
0 → skip (free sparsity)
Result: Zero floating-point multiplication in the entire inference pipeline.
Ragdoll Controller Example
use *;
use ;
// 1. Quantize pre-trained weights to ternary
let = quantize_to_ternary;
let = quantize_to_ternary;
// 2. Convert to fixed-point (one-time)
let ftw1 = from_ternary_weight;
let ftw2 = from_ternary_weight;
// 3. Build deterministic network
let network = new;
// 4. Create ragdoll controller
let config = ControllerConfig ;
let mut controller = new;
// 5. In physics loop — deterministic across ALL clients
for frame in 0..3600
Neural Controller API
| Type | Description |
|---|---|
FixedTernaryWeight |
TernaryWeight wrapper with Fix128 scale |
DeterministicNetwork |
Multi-layer network (zero-allocation forward pass) |
RagdollController |
Body states → joint torques |
ControllerConfig |
max_torque, num_joints, num_bodies |
ControllerOutput |
Vec3Fix torque per joint |
Activation |
ReLU, HardTanh, TanhApprox, None |
| Function | Description |
|---|---|
fix128_ternary_matvec() |
Core kernel — pure add/sub, zero multiplication |
fix128_relu() |
max(0, x) via sign-bit comparison |
fix128_hard_tanh() |
clamp(x, -1, 1) for bounded output |
fix128_tanh_approx() |
Padé rational x(27+x²)/(27+9x²) |
fix128_leaky_relu() |
Leaky ReLU with Fix128 alpha |
Requirements
[]
= { = "../ALICE-Physics", = ["neural"] }
Configuration
// SolverConfig / PhysicsConfig
let config = PhysicsConfig ;
// Or use defaults
let config = default;
Performance Characteristics
| Operation | Complexity | Notes |
|---|---|---|
| Fix128 add/sub | O(1) | ~2-3 cycles |
| Fix128 mul | O(1) | ~10 cycles (128-bit multiply) |
| Fix128 div | O(1) | ~40 cycles (128-bit division) |
| CORDIC sin/cos | O(48) | 48 iterations, deterministic |
| GJK intersection | O(64) | Max 64 iterations |
| EPA penetration | O(64) | Max 64 iterations |
| BVH build | O(n log n) | Morton code sort |
| BVH query | O(log n) | Stackless traversal |
MSRV Policy
Minimum Supported Rust Version: 1.70.0
ALICE-Physics follows a Serde-style MSRV policy:
- MSRV bumps within the 0.x line are treated as minor version bumps (
0.13.x → 0.14.0), never patch bumps - MSRV bumps within a stable 1.x line will also be treated as minor version bumps (
1.x → 1.(x+1)), never patch - The MSRV commitment covers the latest 3 stable Rust channels (N-2 policy) — at the time of a release, we support the current stable + previous 2
alice-physicsdoes not require a nightly toolchain- CI enforces the declared MSRV via a dedicated
msrvjob (since v1.0.1): stable resolves an MSRV-aware lockfile (CARGO_RESOLVER_INCOMPATIBLE_RUST_VERSIONS=fallback), thencargo +1.70.0 check --locked --features "std,simd,parallel,ffi,gpu-solver-bridge"type-checks the library on 1.70.0
Scope of the MSRV guarantee — the library with the default feature set and the core native features (std, simd, parallel, ffi, gpu-solver-bridge) builds on 1.70.0. Outside that scope:
| Component | Effective MSRV | Why |
|---|---|---|
neural / replay / analytics bridge features |
follows the sibling crate (alice-ml / alice-db / alice-analytics); 1.87 as of alice-db 0.2.0-beta.1 → alice-zip 0.3.0 |
sibling crates set their own MSRV |
| Tests / benches (dev-dependencies) | 1.71+ | criterion, serde_derive |
wasm feature |
stable channel recommended | wasm-bindgen moves fast |
Downstream crates can rely on alice-physics not raising its MSRV within a patch release, preserving their own MSRV window.
Building
Note on --all-features: alice-physics uses wasm and ffi as mutually exclusive features (they link wasm-bindgen and C ABI FFI respectively, which cannot coexist in a single binary). cargo build --all-features will fail with a compile_error! by design. Build with one or the other.
Recommended feature combinations:
| Target | Command |
|---|---|
| Native app / game engine host (Unity, UE5, Godot) | cargo build --features "std,simd,parallel,ffi,gpu-solver-bridge" |
| Browser (WebGL / WebGPU via wasm-bindgen) | cargo build --features "std,simd,parallel,wasm,gpu-solver-bridge" |
| Embedded / no_std | cargo build --no-default-features |
| Python bindings | cargo build --features "std,simd,parallel,python" |
docs.rs builds with the native feature set (see [package.metadata.docs.rs] in Cargo.toml).
# Standard build
# no_std build (for embedded/WASM)
# Run tests
# Run all feature combinations
# Run benchmarks (requires nightly or criterion)
Cargo Features
| Feature | Default | Description |
|---|---|---|
std |
Yes | Standard library support |
simd |
No | SIMD-accelerated Fix128/Vec3Fix operations (x86_64) |
parallel |
No | Constraint batching with Rayon (graph-colored parallel solving) |
neural |
No | Deterministic neural controller via ALICE-ML ternary inference |
python |
No | Python bindings (PyO3 + NumPy zero-copy) |
replay |
No | Replay recording/playback via ALICE-DB |
ffi |
No | C FFI for Unity, Unreal Engine, and other game engines |
wasm |
No | WebAssembly bindings via wasm-bindgen |
analytics |
No | Simulation profiling via ALICE-Analytics |
Note:
wasmandffiare mutually exclusive — enabling both causes a compile error.
# Enable SIMD optimizations
# Enable parallel constraint solving
# Enable both
# Enable neural controller (requires ALICE-ML)
# Build C shared library for game engines
Tested Feature Combinations
All feature combinations are tested in CI across macOS, Ubuntu, and Windows:
| Combination | Status | Tests |
|---|---|---|
--no-default-features (no_std) |
✅ | 9 |
--features std (default) |
✅ | 645 unit + 72 integration + 20 doc |
--features simd |
✅ | 20 |
--features parallel |
✅ | 20 |
--features "simd,parallel" |
✅ | 20 |
--features ffi |
✅ | build only |
--features python |
✅ | 1 |
--features replay |
✅ | build only |
--features analytics |
✅ | build only |
--features neural |
✅ | build only |
--features wasm |
✅ | build only |
Feature compatibility matrix:
| std | simd | parallel | neural | python | ffi | wasm | replay | analytics | |
|---|---|---|---|---|---|---|---|---|---|
| std | - | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
| simd | ✅ | - | ✅ | ✅ | ✅ | ✅ | ❌ | ✅ | ✅ |
| parallel | ✅ | ✅ | - | ✅ | ✅ | ✅ | ❌ | ✅ | ✅ |
| wasm | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | - | ❌ | ❌ |
Game Engine Integration (C FFI / Unity / UE5)
ALICE-Physics provides a C FFI layer for integration with Unity, Unreal Engine, and any language that can call C functions.
Building the Shared Library
# macOS (.dylib)
# Linux (.so)
# Windows (.dll)
The output library is in target/release/ (libalice_physics.dylib, libalice_physics.so, or alice_physics.dll).
C API
The C header is at include/alice_physics.h. All types use f64 at the FFI boundary and convert to Fix128 internally.
// Create world
AlicePhysicsWorld* world = ;
// Add bodies
AliceVec3 pos = ;
uint32_t body = ;
// Step simulation
;
// Read back position
AliceVec3 out_pos;
;
// State serialization (rollback netcode)
uint32_t len;
uint8_t* state = ;
;
;
// Cleanup
;
Unity C# Bindings
Copy bindings/AlicePhysics.cs and the native library to your Unity project:
Assets/
Plugins/
macOS/ libalice_physics.dylib
Win64/ alice_physics.dll
Linux/ libalice_physics.so
Scripts/
AlicePhysics.cs
using AlicePhysics;
var world = new AlicePhysicsWorld();
uint body = world.AddDynamicBody(new Vector3(0, 10, 0), 1.0);
world.Step(1.0 / 60.0);
Vector3 pos = world.GetBodyPosition(body);
// Rollback netcode
byte[] state = world.SerializeState();
world.DeserializeState(state);
world.Dispose();
Unreal Engine 5 Plugin
Copy the unreal-plugin/ contents to Plugins/AlicePhysics/ in your UE5 project and place the native library in ThirdParty/AlicePhysics/lib/<Platform>/.
The plugin provides UAlicePhysicsWorldComponent with full Blueprint support:
AddDynamicBody,AddStaticBody— body creationGetBodyPosition,GetBodyRotation,GetBodyVelocity— state queriesApplyImpulse,ApplyImpulseAt— force applicationSerializeState,DeserializeState— rollback netcode- Automatic coordinate system conversion (UE5 Z-up cm → ALICE Y-up m)
Release Workflow
Tag a version to trigger automatic cross-platform builds:
GitHub Actions builds for macOS (ARM + Intel), Windows, and Linux, then packages:
- UE5 Plugin ZIP — includes native library + plugin source + header
- Unity Package ZIP — includes native library + C# bindings + header
Comparison with Floating-Point Engines
| Aspect | ALICE-Physics | Float Engines |
|---|---|---|
| Determinism | Guaranteed | Platform-dependent |
| Precision | 64-bit fraction | 23-bit (f32) / 52-bit (f64) |
| Speed | Slower (2-5x) | Faster |
| Rollback | Trivial | Requires care |
| Embedded | no_std | Requires FPU |
| Range | ±9.2×10^18 | ±3.4×10^38 (f32) |
Deterministic Netcode
ALICE-Physics includes a frame-based deterministic netcode foundation. Because the engine guarantees bit-exact results, only player inputs need to be synchronized — state sync is unnecessary.
Bandwidth Savings
| Approach | Per-Frame (10 bodies, 2 players) |
|---|---|
| State sync (traditional) | ~1,600 bytes |
| Input sync (ALICE) | ~40 bytes |
| Savings | 97.5% |
Core Types
| Type | Description |
|---|---|
FrameInput |
20-byte serializable player input (movement, actions, aim) |
SimulationChecksum |
XOR rolling hash of physics state (WyHash-style avalanche) |
SimulationSnapshot |
Full state capture for rollback |
DeterministicSimulation |
PhysicsWorld wrapper with frame counter, checksum history, snapshot ring buffer |
InputApplicator |
Trait for game-specific input → physics force mapping |
Usage
use *;
// Both clients create identical simulation
let mut sim = new;
// Add bodies and assign to players
let body0 = sim.add_body;
sim.assign_player_body;
// Each frame: collect inputs, advance, compare checksums
let inputs = vec!;
let checksum = sim.advance_frame;
// Save snapshot for rollback
sim.save_snapshot;
// Verify remote client's checksum
assert_eq!;
ALICE-Sync Integration (Game Engine Pipeline)
ALICE-Physics integrates with ALICE-Sync for complete multiplayer game networking. Enable physics feature in ALICE-Sync:
[]
= { = "../ALICE-Sync", = ["physics"] }
How It Works
Player Input ──► InputFrame (i16, 24B) ──► FrameInput (Fix128) ──► PhysicsWorld
ALICE-Sync bridge step()
│
PhysicsWorld ──► SimulationChecksum ──► WorldHash ──► Desync Verify
from_world() bridge ALICE-Sync
ALICE-Sync's PhysicsRollbackSession wraps both RollbackSession (input sync) and DeterministicSimulation (physics) into a single game loop driver:
- Submit local input → predict remote inputs
- Convert InputFrame (i16) → FrameInput (Fix128)
- Save snapshot → step physics → record checksum
- On mismatch: auto rollback + re-simulate
Bandwidth
| Approach | Per-Frame (4 players, 60fps) |
|---|---|
| State sync | ~960 KB/s |
| Input sync (ALICE) | 5.6 KB/s |
| Savings | 99.4% |
See ALICE-Sync README for full API.
Python Bindings (PyO3 + NumPy Zero-Copy)
Install with:
Optimization Layers
| Layer | Technique | Effect |
|---|---|---|
| L1 | GIL Release (py.allow_threads) |
Parallel physics stepping |
| L2 | Zero-Copy NumPy (into_pyarray_bound) |
No memcpy for bulk positions/velocities |
| L3 | Batch API (step_n, positions, states) |
FFI amortization |
| L4 | Batch Mutation (add_bodies_batch, set_velocities_batch, apply_impulses_batch) |
Bulk operations with GIL release |
| L5 | Rust backend (Fix128, XPBD, BVH) | Hardware-speed simulation |
Python API
# Basic physics world
=
=
=
# Step with GIL release (other Python threads can run)
# Batch step for training loops
# Get all positions as NumPy (N, 3) float64 array (zero-copy)
= # shape: (N, 3)
= # shape: (N, 3)
# Deterministic netcode simulation
=
=
# Advance with player inputs: (player_id, move_x, move_y, move_z, actions)
=
# Snapshot for rollback
=
# Serialization
= # NumPy uint8 array
# Frame input encoding (20 bytes, network-ready)
=
, , , , , , , =
# === Batch APIs (v0.4.0) ===
# Batch body creation from (N,4) array [x, y, z, mass]
=
# Batch velocity update (N,3) with GIL release
# Batch impulse (M,4) [body_id, ix, iy, iz] with GIL release
# Combined state output (N,10) [px,py,pz, vx,vy,vz, qx,qy,qz,qw]
= # shape: (N, 10), zero-copy NumPy
Replay Recording (ALICE-DB Integration)
ALICE-Physics can record and replay simulation trajectories via ALICE-DB. Enable with --features replay.
[]
= { = "../ALICE-Physics", = ["replay"] }
Recording
use ReplayRecorder;
// Create recorder (path, body_count)
let mut recorder = new?;
// In game loop: record every frame
for _ in 0..300
recorder.flush?;
recorder.close?;
Playback
use ReplayPlayer;
let player = open?;
// Random access: get position at any frame
let pos = player.get_position?;
// Returns Option<(f32, f32, f32)>
// Range query: scan positions over frame range
let trajectory = player.scan_positions?;
// Returns Vec<(u64, f32, f32, f32)>
player.close?;
Storage Format
Each body stores 6 channels (pos_x/y/z, vel_x/y/z) in ALICE-DB. ALICE-DB's model-based compression automatically fits trajectories:
- Constant velocity → linear model (2 coefficients)
- Projectile motion → quadratic model (3 coefficients)
- Complex motion → Fourier model
Test Results
v0.4.0 Test Summary:
- 358 unit tests across 63 modules
- 62 integration tests (end-to-end physics scenarios)
- 12 doc tests (runnable examples)
- Total: 432 passing tests (435 with --features parallel)
- Clippy: 0 warnings
- CI: Format + Clippy + Test (macOS/Ubuntu/Windows)
- All feature combinations pass (default, parallel, simd, no_std)
Cross-Crate Bridges
ALICE-Physics connects to other ALICE ecosystem crates via feature-gated bridge modules:
| Bridge | Feature | Target Crate | Description |
|---|---|---|---|
| Physics Visualization | view |
ALICE-View | Real-time physics debug overlay rendering |
| GPU Physics Controller | trt |
ALICE-TRT | GPU ternary inference for physics control policies |
| Physics State Streaming | asp |
ALICE-Streaming-Protocol | Physics body state delta encoding as ASP D-packets |
db_bridge |
replay |
ALICE-DB | Physics state snapshot persistence (energy, bodies, contacts) |
analytics_bridge |
analytics |
ALICE-Analytics | Simulation profiling (step time, collision pairs, energy drift) |
Recent Performance Improvements
| Module | Change | Impact |
|---|---|---|
fluid.rs |
Buffer reuse in neighbor queries | ~99% allocation reduction in SPH simulation |
animation_blend.rs |
clone_from() replaces clone() |
Eliminates 60 allocs/sec during blend |
Cargo Profile
Standardized [profile.bench] added for consistent benchmarking across ALICE crates.
Complete API Reference
Core Types
| Module | Type / Function | Description |
|---|---|---|
math |
Fix128 |
128-bit fixed-point number (I64F64) |
math |
Vec3Fix |
3D vector with Fix128 components |
math |
QuatFix |
Quaternion for rotations |
math |
Mat3Fix |
3x3 matrix for inertia tensors |
math |
SIMD_WIDTH |
Compile-time SIMD lane count (AVX2=8, NEON=4, scalar=1) |
math |
simd_width() |
Returns SIMD width at compile time |
math |
select_fix128() |
Branchless conditional select |
math |
select_vec3() |
Branchless Vec3 conditional select |
Collision Detection
| Module | Type / Function | Description |
|---|---|---|
collider |
AABB |
Axis-Aligned Bounding Box |
collider |
Sphere |
Sphere collider |
collider |
Capsule |
Capsule (cylinder + hemispheres) |
collider |
ConvexHull |
Arbitrary convex polyhedron |
collider |
ScaledShape |
Uniform scale wrapper for any Support shape |
collider |
CollisionResult |
Contact point, normal, depth |
collider |
Support trait |
GJK support function interface |
box_collider |
OrientedBox |
OBB with center, half-extents, rotation |
compound |
CompoundShape |
Multi-shape compound collider |
compound |
ShapeRef |
Shape reference within compound |
cylinder |
Cylinder |
Cylinder collider with GJK support |
filter |
CollisionFilter |
Layer/mask bitmask collision groups |
Solver & Dynamics
| Module | Type / Function | Description |
|---|---|---|
solver |
PhysicsWorld |
Main simulation world |
solver |
PhysicsConfig |
Substeps, iterations, gravity, damping |
solver |
RigidBody |
Dynamic/static/sensor rigid body |
solver |
BodyType |
Dynamic, Static, Kinematic |
solver |
DistanceConstraint |
Fixed distance between anchor points |
solver |
ContactConstraint |
Collision response with friction/restitution |
solver |
ContactModifier |
Trait for custom contact modification (std) |
joint |
BallJoint |
Spherical joint (3 rotational DOF) |
joint |
HingeJoint |
Revolute joint with angle limits |
joint |
FixedJoint |
Weld joint (0 DOF) |
joint |
SliderJoint |
Prismatic joint with limits |
joint |
SpringJoint |
Damped spring constraint |
joint |
D6Joint |
6-DOF configurable joint |
joint |
ConeTwistJoint |
Cone swing + twist limit joint |
joint |
solve_joints_breakable() |
Solve with break-force support |
motor |
PdController |
1D proportional-derivative controller |
motor |
JointMotor |
Joint motor (position/velocity/torque modes) |
force |
ForceField |
Wind, gravity well, drag, buoyancy, vortex |
force |
ForceFieldInstance |
Active force field in simulation |
material |
MaterialTable |
Per-pair friction/restitution override |
material |
PhysicsMaterial |
Material properties |
material |
CombineRule |
Average, Min, Max, Multiply |
Spatial Acceleration
| Module | Type / Function | Description |
|---|---|---|
bvh |
LinearBvh |
Flat array BVH with stackless traversal |
bvh |
BvhNode |
32-byte cache-aligned node |
bvh |
BvhPrimitive |
Primitive entry for BVH construction |
dynamic_bvh |
DynamicAabbTree |
Incremental BVH with O(log n) insert/remove |
spatial |
SpatialGrid |
Hash grid for neighbor queries |
Queries
| Module | Type / Function | Description |
|---|---|---|
raycast |
Ray |
Ray origin + direction |
raycast |
RayHit |
Hit result (t, normal, index) |
raycast |
ray_sphere(), ray_aabb(), ray_capsule(), ray_plane() |
Shape-specific ray tests |
raycast |
raycast_all_spheres(), raycast_all_aabbs() |
Batch raycasts |
query |
sphere_cast() |
Sweep sphere along direction |
query |
capsule_cast() |
Sweep capsule along direction |
query |
overlap_sphere() |
Find bodies in sphere |
query |
overlap_aabb() |
Find bodies in AABB |
query |
batch_raycast(), batch_sphere_cast() |
Batch queries |
ccd |
sphere_sphere_toi() |
Time of impact (sphere-sphere) |
ccd |
conservative_advancement() |
Iterative safe stepping TOI |
ccd |
speculative_contact() |
Speculative CCD contacts |
Soft Body & Simulation
| Module | Type / Function | Description |
|---|---|---|
rope |
Rope |
XPBD distance-chain rope |
rope |
RopeConfig |
Segment count, stiffness, damping |
cloth |
Cloth |
XPBD triangle mesh cloth |
cloth |
ClothConfig |
Stiffness, self-collision, gravity |
fluid |
Fluid |
Position-Based Fluids (PBF) |
fluid |
FluidConfig |
Rest density, viscosity, kernel radius |
deformable |
DeformableBody |
FEM tetrahedral mesh |
deformable |
DeformableConfig |
Young's modulus, Poisson's ratio |
vehicle |
Vehicle |
Vehicle simulation |
vehicle |
VehicleConfig |
Wheels, suspension, engine, steering |
character |
CharacterController |
Kinematic capsule move-and-slide |
character |
CharacterConfig |
Radius, height, max slope, step height |
SDF Integration
| Module | Type / Function | Description |
|---|---|---|
sdf_collider |
SdfCollider |
SDF as collision shape |
sdf_collider |
SdfField trait |
Distance + normal evaluation interface |
sdf_collider |
ClosureSdf |
Closure-based SDF implementation |
sdf_manifold |
SdfManifold |
Multi-point contact from SDF surface |
sdf_manifold |
ManifoldConfig |
Contact point count, spread |
sdf_ccd |
SdfCcdConfig |
Sphere tracing CCD for SDF |
sdf_force |
SdfForceField |
SDF-driven force field |
sdf_force |
SdfForceType |
Attract, Repel, Contain, Flow |
sdf_destruction |
DestructibleSdf |
CSG boolean destruction (std) |
sdf_destruction |
DestructionShape |
Sphere/box subtraction shape |
sdf_adaptive |
AdaptiveSdfEvaluator |
Distance-based LOD evaluation (std) |
convex_decompose |
DecomposeConfig |
Voxel grid decomposition settings (std) |
gpu_sdf |
GpuSdfBatch |
GPU compute SDF batch (std) |
gpu_sdf |
GpuSdfInstancedBatch |
Instanced GPU SDF batch |
gpu_sdf |
GpuSdfMultiDispatch |
Multi-batch GPU dispatch |
SDF Simulation Modifiers
| Module | Type / Function | Description |
|---|---|---|
sim_field |
ScalarField3D |
3D scalar field with trilinear interpolation (std) |
sim_field |
VectorField3D |
3D vector field with trilinear interpolation (std) |
sim_modifier |
PhysicsModifier trait |
SDF modifier interface (std) |
sim_modifier |
ModifiedSdf |
Modifier chain (std) |
thermal |
ThermalModifier |
Heat diffusion, melt, freeze (std) |
thermal |
ThermalConfig |
Conductivity, melt/freeze thresholds |
pressure |
PressureModifier |
Contact-force deformation (std) |
pressure |
PressureConfig |
Yield threshold, spring-back |
erosion |
ErosionModifier |
Wind/water/chemical erosion (std) |
erosion |
ErosionType |
Wind, Water, Chemical, Ablation |
fracture |
FractureModifier |
Stress-driven crack propagation (std) |
fracture |
FractureConfig |
Toughness, crack speed |
phase_change |
PhaseChangeModifier |
Solid/liquid/gas transitions (std) |
phase_change |
Phase |
Solid, Liquid, Gas |
Game Systems
| Module | Type / Function | Description |
|---|---|---|
animation_blend |
AnimationBlender |
Ragdoll-to-animation blending |
animation_blend |
BlendMode |
Lerp, Slerp, Additive |
animation_blend |
SkeletonPose |
Joint transforms for skeleton |
audio_physics |
AudioGenerator |
Physics-based audio parameters |
audio_physics |
AudioEvent |
Impact, friction, rolling events |
audio_physics |
AudioMaterial |
Surface material with audio properties |
netcode |
DeterministicSimulation |
PhysicsWorld + frame counter + checksum |
netcode |
FrameInput |
20-byte serializable player input |
netcode |
SimulationChecksum |
XOR rolling hash of physics state |
netcode |
SimulationSnapshot |
Full state capture for rollback |
netcode |
InputApplicator trait |
Game-specific input → force mapping |
fluid_netcode |
FluidSnapshot |
Deterministic fluid state (std) |
fluid_netcode |
FluidDelta |
Delta-compressed fluid update (std) |
Analytics & Privacy
| Module | Type / Function | Description |
|---|---|---|
sketch |
HyperLogLog |
Cardinality estimation (std) |
sketch |
DDSketch |
Quantile sketch (P50/P99/P99.9) (std) |
sketch |
CountMinSketch |
Frequency estimation (std) |
sketch |
HeavyHitters |
Top-k frequent items (std) |
sketch |
FnvHasher |
FNV-1a deterministic hasher (std) |
sketch |
Mergeable trait |
Distributed sketch merging (std) |
anomaly |
MadDetector |
Median Absolute Deviation (std) |
anomaly |
EwmaDetector |
Exponentially Weighted Moving Average (std) |
anomaly |
ZScoreDetector |
Standard Z-score detector (std) |
anomaly |
CompositeDetector |
Multi-detector voting (std) |
anomaly |
StreamingMedian |
O(log n) streaming median (std) |
privacy |
LaplaceNoise |
Calibrated Laplace mechanism (std) |
privacy |
Rappor |
RAPPOR protocol for categorical data (std) |
privacy |
RandomizedResponse |
Binary randomized response (std) |
privacy |
PrivacyBudget |
Epsilon budget tracker (std) |
privacy |
PrivateAggregator |
Privacy-preserving aggregation (std) |
privacy |
XorShift64 |
Deterministic PRNG (std) |
pipeline |
MetricPipeline |
Lock-free ring buffer aggregation (std) |
pipeline |
MetricRegistry |
Named metric registration (std) |
pipeline |
MetricEvent |
Timestamped metric event (std) |
pipeline |
MetricType |
Counter, Gauge, Histogram (std) |
pipeline |
RingBuffer |
Fixed-capacity circular buffer (std) |
Utility
| Module | Type / Function | Description |
|---|---|---|
rng |
DeterministicRng |
PCG-XSH-RR 32-bit generator |
event |
EventCollector |
Contact begin/persist/end tracking |
event |
ContactEvent |
Body pair + event type + contact point |
sleeping |
IslandManager |
Union-Find island management |
sleeping |
SleepConfig |
Velocity thresholds, idle frame count |
trimesh |
TriMesh |
BVH-accelerated triangle mesh |
trimesh |
Triangle |
Single triangle (Moller-Trumbore) |
heightfield |
HeightField |
Grid terrain with bilinear interpolation |
articulation |
ArticulatedBody |
Multi-joint chain with FK propagation |
articulation |
FeatherstoneSolver |
O(n) forward dynamics |
contact_cache |
ContactCache |
HashMap O(1) manifold lookup |
contact_cache |
ContactManifold |
Up to 4 contact points |
interpolation |
WorldSnapshot |
Physics state for interpolation |
debug_render |
DebugDrawData |
Wireframe visualization |
debug_render |
DebugDrawFlags |
Bitmask for what to draw |
profiling |
PhysicsProfiler |
Per-stage timing |
profiling |
StepStats |
Broadphase/narrowphase/solver times |
error |
PhysicsError |
Typed physics error enum |
Feature-Gated Modules
| Module | Feature | Description |
|---|---|---|
neural |
neural |
Deterministic ternary neural controller (ALICE-ML) |
python |
python |
PyO3 + NumPy zero-copy Python bindings |
ffi |
ffi |
C FFI for Unity/UE5 game engines |
wasm |
wasm |
WebAssembly bindings (wasm-bindgen) |
replay |
replay |
Replay recording/playback via ALICE-DB |
db_bridge |
replay |
Physics state persistence bridge |
analytics_bridge |
analytics |
Simulation profiling bridge (ALICE-Analytics) |
Python API (PyO3)
| Class / Function | Description |
|---|---|
PhysicsWorld |
Python wrapper for physics simulation |
PhysicsWorld.add_dynamic_body(x, y, z, mass) |
Add dynamic body |
PhysicsWorld.add_static_body(x, y, z) |
Add static body |
PhysicsWorld.step(dt) |
Step with GIL release |
PhysicsWorld.step_n(dt, steps) |
Batch step for training |
PhysicsWorld.positions() |
NumPy (N,3) zero-copy |
PhysicsWorld.velocities() |
NumPy (N,3) zero-copy |
PhysicsWorld.states() |
NumPy (N,10) combined state |
PhysicsWorld.add_bodies_batch(array) |
Batch body creation from (N,4) |
PhysicsWorld.set_velocities_batch(array) |
Batch velocity update (N,3) |
PhysicsWorld.apply_impulses_batch(array) |
Batch impulse (M,4) |
PhysicsWorld.serialize_state() |
State to NumPy uint8 |
PhysicsWorld.deserialize_state(data) |
Restore from bytes |
DeterministicSimulation |
Netcode simulation wrapper |
DeterministicSimulation.advance_frame(inputs) |
Advance with player inputs |
DeterministicSimulation.save_snapshot() |
Save for rollback |
DeterministicSimulation.load_snapshot(frame) |
Restore snapshot |
encode_frame_input(...) |
Encode 20-byte input |
decode_frame_input(data) |
Decode 20-byte input |
C FFI API
| Function | Description |
|---|---|
alice_physics_world_create() |
Create physics world |
alice_physics_world_destroy(world) |
Destroy physics world |
alice_physics_world_step(world, dt) |
Step simulation |
alice_physics_body_add_dynamic(world, pos, mass) |
Add dynamic body |
alice_physics_body_add_static(world, pos) |
Add static body |
alice_physics_body_get_position(world, id, out) |
Get body position |
alice_physics_body_apply_impulse(world, id, impulse) |
Apply impulse |
alice_physics_state_serialize(world, len) |
Serialize state |
alice_physics_state_deserialize(world, data, len) |
Deserialize state |
alice_physics_state_free(data, len) |
Free serialized buffer |
License
AGPL-3.0 - See LICENSE for details.
Copyright (C) 2024-2026 Moroya Sakamoto
Acknowledgments
- XPBD: Müller et al., "XPBD: Position-Based Simulation of Compliant Constrained Dynamics"
- GJK/EPA: Ericson, "Real-Time Collision Detection"
- Morton Codes: Morton, "A Computer Oriented Geodetic Data Base"
- CORDIC: Volder, "The CORDIC Trigonometric Computing Technique"