async createBroadphase(device, worldBuffers, options = {})

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: GPUBroadphase.js — GPU Compute Spatial Hash Broadphase Spatial hash broad phase collision detection on GPU. Computes AABBs from collider shapes + world transforms, inserts into spatial hash grid, finds candidate collision pairs. Based on: GPU Gems 3 Ch.32: Broad Phase Collision Detection with CUDA GPU Gems 3 Ch.29: Uniform grid with 27 neighbor cell queries Existing GPUSpatialHash.js patterns (morton codes, hash primes) Uses atomicAdd for pair output (modern WebGPU, no multi pass needed). Collision layer/mask filtering happens during pair generation. Classes Method Signature Summary Dispatch broadphase into a command encoder. Async readback of pair count from GPU. Functions Create and initialize a GPU broadphase. Parameters: (GPUDevice) — No description in source JSDoc. (Object) — GPURigidBodyWorld. buffers (Object) — No description in source JSDoc. Constants <! HUMAN NOTES Notes & Examples Physics Engine Integration The physics system provides rigid body dynamics, collision detection, and raycasting. Bodies have shapes (box, sphere, mesh), mass properties, and constraints. The GPU physics engine accelerates broad phase collision detection and particle systems. Example: Creating physics bodies Advanced: Collision detection and raycasting Advanced: Constraints and joints Advanced: Continuous collision detection (CCD) Gotchas: Units : Physics uses meters, kilograms, seconds. A 1 unit cube is 1 meter. Time step : Fixed time step (1/60) gives stable simulation; variable dt causes explosions. Collision layers : Use collision masks to filter what collides (player vs enemy, bullet vs world). Sleeping : At rest bodies sleep to save CPU — wake them before applying forces. See also:


masks to filter what collides (player vs enemy, bullet vs world). Sleeping : At rest bodies sleep to save CPU — wake them before applying forces. See also: Physics · GPU Physics Engine


<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: GPUCharacterController.js — Kinematic Character Controller PhysX style character controller (CCT) for player/NPC movement. Kinematic body that sweeps through the scene, resolves collisions, handles ground detection, slope limits, step climbing, and skin width. Based on: PhysX PxController: kinematic move with depenetration, auto step, slope limit Quake/Source: slide move along wall normals, stair stepping Jolt CharacterVirtual: predictive contacts, inner body shape Architecture: CPU driven (character movement is inherently sequential per character) Uses GPURaycast (CPU fallback) for ground probes and sweep tests Applies final position to a kinematic body in GPURigidBodyWorld Supports capsule and box shapes The controller does NOT use GPU compute shaders directly because character movement is latency sensitive (needs immediate response to input) and typically only a handful of characters exist. CPU is the right choice here. Classes Method Signature Summary Sync position from world body state. Call once after creating the body to initialize. Main update: move the character by displacement. Handles gravity, ground detection, slope sliding, step climbing. Jump: set vertical velocity. Teleport character to position. Method Signature Summary Create a character controller. Remove a character controller. Get controller by body handle. Update all controllers. Functions Constants <! HUMAN NOTES Notes & Examples Physics Engine Integration The physics system provides rigid body dynamics, collision detection, and raycasting. Bodies have shapes (box, sphere, mesh), mass properties, and constraints. The GPU physics engine accelerates broad phase collision detection and particle systems.


have shapes (box, sphere, mesh), mass properties, and constraints. The GPU physics engine accelerates broad phase collision detection and particle systems. Example: Creating physics bodies Advanced: Collision detection and raycasting Advanced: Constraints and joints Advanced: Continuous collision detection (CCD) Gotchas: Units : Physics uses meters, kilograms, seconds. A 1 unit cube is 1 meter. Time step : Fixed time step (1/60) gives stable simulation; variable dt causes explosions. Collision layers : Use collision masks to filter what collides (player vs enemy, bullet vs world). Sleeping : At rest bodies sleep to save CPU — wake them before applying forces. See also: Physics · GPU Physics Engine


async createConstraintSolver(device, worldBuffers, narrowphaseBuffers, options = {})

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: GPUConstraintSolver.js — GPU Compute XPBD/TGS Constraint Solver Solves contact constraints and joint constraints on GPU. Uses TGS Soft approach (Erin Catto, Box2D v3): Sub step contact separation update via local frame anchors Accumulated impulse clamping (Sequential Impulses) Warm starting from previous frame's Lagrange multipliers Relaxation pass to drain bias energy Coulomb friction with tangent clamping Restitution via velocity level bounce Joint constraints use D6 as sole native type (PhysX 5 GPU best practice). Ball, hinge, fixed, distance, prismatic are D6 presets. Parallel solving via graph colored Gauss Seidel (Fratarcangeli et al.): CPU side graph coloring groups non conflicting constraints One GPU dispatch per color group Based on: XPBD (Macklin 2016): Δλ = (C + α̃·λ) / (w a + w b + α̃) Small Steps (Macklin 2019): sub stepping iteration Box2D v3 Solver2D: TGS Soft, relaxation, accumulated impulse clamping PhysX 5 GPU: D6 joints native, soft constraint compliance Classes Method Signature Summary Update a hinge joint's angular motor at runtime (live tuning). Dispatch constraint solving into a command encoder. Called per substep from GPURigidBodyWorld.step(). Functions Constants <! HUMAN NOTES Notes & Examples Physics Engine Integration The physics system provides rigid body dynamics, collision detection, and raycasting. Bodies have shapes (box, sphere, mesh), mass properties, and constraints. The GPU physics engine accelerates broad phase collision detection and particle systems. Example: Creating physics bodies Advanced: Collision detection and raycasting Advanced: Constraints and joints Advanced: Continuous collision detection (CCD) Gotchas: Units : Physics uses


Advanced: Collision detection and raycasting Advanced: Constraints and joints Advanced: Continuous collision detection (CCD) Gotchas: Units : Physics uses meters, kilograms, seconds. A 1 unit cube is 1 meter. Time step : Fixed time step (1/60) gives stable simulation; variable dt causes explosions. Collision layers : Use collision masks to filter what collides (player vs enemy, bullet vs world). Sleeping : At rest bodies sleep to save CPU — wake them before applying forces. See also: Physics · GPU Physics Engine


async createContinuousCollision(device, worldBuffers, narrowphaseBuffers, options = {})

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: GPUContinuousCollision.js — GPU Speculative CCD (Continuous Collision Detection) Prevents fast moving objects from tunneling through thin geometry. Uses speculative contacts: expand AABBs by velocity, generate conservative contacts at predicted future positions. Based on: PhysX CCD: PxPairFlag::eDETECT CCD CONTACT, PxRigidBodyFlag::eENABLE CCD Bullet Physics: speculative contacts (Erwin Coumans GDC 2013) Existing engine SpeculativeContacts.js (CPU) — this is the GPU version Architecture: GPU shader expands AABBs by linear velocity dt Broadphase runs on expanded AABBs (catches potential tunneling pairs) For CCD flagged bodies, compute time of impact (TOI) via conservative advancement Clamp body position to TOI displacement if tunneling detected Generates speculative contacts at predicted impact point When to enable CCD: Bullets, projectiles, fast vehicles Small objects near thin walls Any body with speed size/dt (tunneling risk) Classes Method Signature Summary Set CCD pairs found during broadphase (call from CPU after broadphase readback). Dispatch CCD passes. 1. Expand AABBs (use expanded AABBs for broadphase) 2. TOI computation for CCD pairs (generates speculative contacts) Get expanded AABB buffers (feed to broadphase instead of regular AABBs). Functions Constants <! HUMAN NOTES Notes & Examples Physics Engine Integration The physics system provides rigid body dynamics, collision detection, and raycasting. Bodies have shapes (box, sphere, mesh), mass properties, and constraints. The GPU physics engine accelerates broad phase collision detection and particle systems. Example: Creating physics bodies Advanced: Collision detection and raycasting Advanced: Constraints and joints


phase collision detection and particle systems. Example: Creating physics bodies Advanced: Collision detection and raycasting Advanced: Constraints and joints Advanced: Continuous collision detection (CCD) Gotchas: Units : Physics uses meters, kilograms, seconds. A 1 unit cube is 1 meter. Time step : Fixed time step (1/60) gives stable simulation; variable dt causes explosions. Collision layers : Use collision masks to filter what collides (player vs enemy, bullet vs world). Sleeping : At rest bodies sleep to save CPU — wake them before applying forces. See also: Physics · GPU Physics Engine


computeConvexHull(vertices, options = {})

buildSupportMap(hull, numDirections = SUPPORTMAPDIRECTIONS)

hullToGPUBuffer(device, hull, supportMap = null)

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: GPUConvexHull.js — CPU side Quickhull 3D + GPU Buffer Helpers Computes convex hulls from vertex data (runs once at cook time, not per frame). Produces GPU compatible hull data for narrowphase collision detection. PhysX 5 GPU limits enforced: Max 64 vertices per hull Max 32 vertices per face Hulls exceeding these limits are simplified Algorithm: Incremental Quickhull 3D Find initial tetrahedron from extreme points Iteratively add furthest point from each face Expand horizon edges, rebuild faces Also builds precomputed support maps for GJK: For 128 sampled directions, store the support vertex index Enables O(1) support queries on GPU Functions Compute a 3D convex hull from a set of vertices. Parameters: (Float32Array number[]) — Flat array of xyz positions (length = N 3) (Object) — No description in source JSDoc. (number) — =64] Max vertices in output hull Returns: } Build precomputed support map for fast GPU GJK. For each of N uniformly sampled directions, stores the index of the furthest vertex in that direction. Parameters: (number) — =128] Returns: Support vertex indices (one per direction) Upload hull data to a GPU buffer for narrowphase use. Layout: [vertexCount(u32), faceCount(u32), pad, pad] + [vertices (vec4)] + [normals (vec4)] + [supportMap (u32)] Parameters: (GPUDevice) — No description in source JSDoc. (Uint32Array) — From buildSupportMap() Compute AABB half extents from hull vertices (for broadphase). Returns: [halfX, halfY, halfZ] Constants <! HUMAN NOTES Notes & Examples Physics Engine Integration The physics system provides rigid body dynamics, collision detection, and raycasting. Bodies have shapes (box, sphere, mesh), mass properties, and constraints. The GPU


system provides rigid body dynamics, collision detection, and raycasting. Bodies have shapes (box, sphere, mesh), mass properties, and constraints. The GPU physics engine accelerates broad phase collision detection and particle systems. Example: Creating physics bodies Advanced: Collision detection and raycasting Advanced: Constraints and joints Advanced: Continuous collision detection (CCD) Gotchas: Units : Physics uses meters, kilograms, seconds. A 1 unit cube is 1 meter. Time step : Fixed time step (1/60) gives stable simulation; variable dt causes explosions. Collision layers : Use collision masks to filter what collides (player vs enemy, bullet vs world). Sleeping : At rest bodies sleep to save CPU — wake them before applying forces. See also: Physics · GPU Physics Engine


async createHeightfield(device, worldBuffers, narrowphaseBuffers, options = {})

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: GPUHeightfield.js — GPU Terrain Heightfield Collider Heightmap based terrain collision for GPU physics. Stores a 2D grid of heights, generates contacts against rigid bodies via GPU compute shader. Based on: PhysX PxHeightField: regular grid, per sample materials, hole support Bullet btHeightfieldTerrainShape: bilinear interpolation Jolt HeightFieldShape: hierarchical BVH for large terrains Features: Bilinear height interpolation for smooth normals Per cell material index (for surface types: grass, rock, mud, etc.) Hole support (cells with height = NaN are passthrough) GPU shader: one thread per body, probes heightfield under body AABB CPU upload of heightmap data (set once or update regions) Supports terrains up to 1024×1024 (configurable) Classes Method Signature Summary Set the entire heightmap from a Float32Array. Set a single height sample. Set a rectangular region of heights. Mark a cell as a hole (bodies pass through). Get height at a world position (CPU side bilinear interpolation). Get surface normal at a world position (CPU side finite difference). Set per cell material index (for surface type queries). Get material index at world position. Generate heightfield from a noise function. Dispatch heightfield contact generation. Call after broadphase but adds contacts to the same narrowphase contact buffer. Functions Constants <! HUMAN NOTES Notes & Examples Physics Engine Integration The physics system provides rigid body dynamics, collision detection, and raycasting. Bodies have shapes (box, sphere, mesh), mass properties, and constraints. The GPU physics engine accelerates broad phase collision detection and particle systems. Example: Creating physics bodies Advanced:


and constraints. The GPU physics engine accelerates broad phase collision detection and particle systems. Example: Creating physics bodies Advanced: Collision detection and raycasting Advanced: Constraints and joints Advanced: Continuous collision detection (CCD) Gotchas: Units : Physics uses meters, kilograms, seconds. A 1 unit cube is 1 meter. Time step : Fixed time step (1/60) gives stable simulation; variable dt causes explosions. Collision layers : Use collision masks to filter what collides (player vs enemy, bullet vs world). Sleeping : At rest bodies sleep to save CPU — wake them before applying forces. See also: Physics · GPU Physics Engine


sim/physics/gpu/GPUMeshDeform.js
Classes
class GPUMeshDeform
Notes & Examples
Physics Engine Integration

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: GPUMeshDeform.js — GPU accelerated vertex displacement for impact dents Fast path for small impacts: pushes vertices inward within a radius around the impact point, weighted by distance. Runs in <1ms on GPU vs 50 200ms for the full voxelize→SDF→marching cubes CPU pipeline. Also includes a normal recalculation pass (GAP 4). Usage: const deformer = new GPUMeshDeform(device); const result = await deformer.applyDent(positions, indices, { impactPoint: [x, y, z], impactNormal: [nx, ny, nz], radius: 0.3, depth: 0.1, }); // result.positions — Float32Array of deformed positions // result.normals — Float32Array of recalculated normals Classes Method Signature Summary Apply a dent to mesh vertices and recalculate normals on GPU. <! HUMAN NOTES Notes & Examples Physics Engine Integration The physics system provides rigid body dynamics, collision detection, and raycasting. Bodies have shapes (box, sphere, mesh), mass properties, and constraints. The GPU physics engine accelerates broad phase collision detection and particle systems. Example: Creating physics bodies Advanced: Collision detection and raycasting Advanced: Constraints and joints Advanced: Continuous collision detection (CCD) Gotchas: Units : Physics uses meters, kilograms, seconds. A 1 unit cube is 1 meter. Time step : Fixed time step (1/60) gives stable simulation; variable dt causes explosions. Collision layers : Use collision masks to filter what collides (player vs enemy, bullet vs world). Sleeping : At rest bodies sleep to save CPU — wake them before applying forces. See also: Physics · GPU Physics Engine


async createNarrowphase(device, worldBuffers, broadphaseBuffers, options = {})

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: GPUNarrowphase.js — GPU Compute Contact Generation Analytic shape shape collision tests on GPU compute shaders. Processes candidate pairs from GPUBroadphase, generates contact manifold. Supported shape pairs: sphere–sphere, sphere–box, sphere–capsule box–box (SAT, 15 separating axes) capsule–capsule (closest points on two line segments) capsule–box (segment vs box faces) ground plane (infinite y=0, special cased) Contact manifold uses Persistent Contact Manifold (PCM) approach: Contacts stored with local frame anchors for sub step updating Feature IDs for warm start matching across frames OGC barrier energy for penetration prevention Based on: PhysX 5 GPU: PCM required for GPU contact gen PhysX 5: convex hulls capped at 64 verts for GPU compat Box2D v3 TGS: sub step contact separation update via local anchors OGCContact.js: barrier energy WGSL module Classes Method Signature Summary Dispatch narrowphase contact generation. Functions Constants <! HUMAN NOTES Notes & Examples Physics Engine Integration The physics system provides rigid body dynamics, collision detection, and raycasting. Bodies have shapes (box, sphere, mesh), mass properties, and constraints. The GPU physics engine accelerates broad phase collision detection and particle systems. Example: Creating physics bodies Advanced: Collision detection and raycasting Advanced: Constraints and joints Advanced: Continuous collision detection (CCD) Gotchas: Units : Physics uses meters, kilograms, seconds. A 1 unit cube is 1 meter. Time step : Fixed time step (1/60) gives stable simulation; variable dt causes explosions. Collision layers : Use collision masks to filter what collides (player vs enemy, bullet vs world). Sleeping :


stable simulation; variable dt causes explosions. Collision layers : Use collision masks to filter what collides (player vs enemy, bullet vs world). Sleeping : At rest bodies sleep to save CPU — wake them before applying forces. See also: Physics · GPU Physics Engine


gpuRaycastCPU(world, origin, direction, maxDistance = 1000)

async createGPURaycast(device, worldBuffers, options = {})

async gpuRaycast(rc, world, origin, direction, maxDistance = 1000)

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: GPURaycast.js — GPU Compute Parallel Raycast Casts rays against all rigid bodies on the GPU. Each thread tests one body, writes closest hit to output. Reduction pass finds global closest hit across all threads. Result returned via async readback (Promise). Also provides CPU fallback for synchronous raycasting against CPU shadow data (1 frame lag, but instant). Shape ray tests: ray sphere (geometric closest approach) ray box (slab method) ray capsule (ray segment closest point + sphere test) Classes Method Signature Summary Cast a ray on GPU. Returns a Promise with the closest hit. Functions Synchronous CPU raycast against CPU shadow data (1 frame lag). Use when async GPU raycast is too slow or when GPU is busy. Parameters: (GPURigidBodyWorld) — No description in source JSDoc. (number[]) — No description in source JSDoc. (number[]) — No description in source JSDoc. (number) — No description in source JSDoc. Returns: } GPU raycast (async). <! HUMAN NOTES Notes & Examples Physics Engine Integration The physics system provides rigid body dynamics, collision detection, and raycasting. Bodies have shapes (box, sphere, mesh), mass properties, and constraints. The GPU physics engine accelerates broad phase collision detection and particle systems. Example: Creating physics bodies Advanced: Collision detection and raycasting Advanced: Constraints and joints Advanced: Continuous collision detection (CCD) Gotchas: Units : Physics uses meters, kilograms, seconds. A 1 unit cube is 1 meter. Time step : Fixed time step (1/60) gives stable simulation; variable dt causes explosions. Collision layers : Use collision masks to filter what collides (player vs enemy, bullet vs world). Sleeping : At


simulation; variable dt causes explosions. Collision layers : Use collision masks to filter what collides (player vs enemy, bullet vs world). Sleeping : At rest bodies sleep to save CPU — wake them before applying forces. See also: Physics · GPU Physics Engine


async createGPUPhysicsWorld(device, options = {})

gpuApplyForce(world, handle, fx, fy, fz)

gpuApplyTorque(world, handle, tx, ty, tz)

gpuStepWorld(world, dt, broadphase, narrowphase, solver)

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: GPURigidBodyWorld.js — GPU Compute Rigid Body Physics World Custom WebGPU compute based rigid body simulation engine. Runs broadphase, narrowphase, constraint solving, and integration entirely on the GPU via WGSL compute shaders. Architecture based on: TGS Soft solver (Erin Catto, Box2D v3 Solver2D, Feb 2024) Sub stepping + warm starting + soft constraints + relaxation XPBD compliance (Macklin 2016) for stiffness independent constraints Small Steps (Macklin 2019) for sub step contact updating PhysX 5 GPU rigid bodies: fixed pre allocated buffers, D6 native joints Jolt + Box2D v3: simulation islands via union find, per island sleep Delta position formulation (Catto) to avoid FP cancellation far from origin Graph colored parallel Gauss Seidel (Fratarcangeli et al.) GPU Gems 3 Ch.29: spatial hash broadphase, 27 neighbor cell queries SoA buffer layout for cache coherent GPU access. All WGSL shaders embedded as template literals (matches codebase pattern). Classes Method Signature Summary Create a rigid body. Remove a body by handle. Get body state from CPU shadow (1 frame lag from GPU readback). Set body to kinematic or dynamic. Apply external force to a body (accumulated until next step). Apply external torque to a body (accumulated until next step). Set body position directly (for kinematic or teleportation). Set body rotation directly (quaternion xyzw). Set body linear velocity directly. Step the physics world. Dispatches GPU compute shaders for integration, broadphase, narrowphase, constraint solving, velocity derivation, and sleep detection. Async readback GPU → CPU shadow arrays. Call once per frame AFTER step(). Updates getBody() data. Functions Create a GPU physics world.


and sleep detection. Async readback GPU → CPU shadow arrays. Call once per frame AFTER step(). Updates getBody() data. Functions Create a GPU physics world. Parameters: (GPUDevice) — No description in source JSDoc. (Object) — No description in source JSDoc. Step the GPU physics world. Parameters: (GPURigidBodyWorld) — No description in source JSDoc. (number) — Time step in seconds (Object) — GPUBroadphase instance (Object) — GPUNarrowphase instance (Object) — GPUConstraintSolver instance Constants <! HUMAN NOTES Notes & Examples Physics Engine Integration The physics system provides rigid body dynamics, collision detection, and raycasting. Bodies have shapes (box, sphere, mesh), mass properties, and constraints. The GPU physics engine accelerates broad phase collision detection and particle systems. Example: Creating physics bodies Advanced: Collision detection and raycasting Advanced: Constraints and joints Advanced: Continuous collision detection (CCD) Gotchas: Units : Physics uses meters, kilograms, seconds. A 1 unit cube is 1 meter. Time step : Fixed time step (1/60) gives stable simulation; variable dt causes explosions. Collision layers : Use collision masks to filter what collides (player vs enemy, bullet vs world). Sleeping : At rest bodies sleep to save CPU — wake them before applying forces. See also: Physics · GPU Physics Engine


sim/physics/gpu/GPUSceneQuery.js
Classes
class GPUSceneQuery
Functions
createSceneQuery(world)
Constants
Notes & Examples
Physics Engine Integration

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: GPUSceneQuery.js — GPU Scene Queries (Overlap, Sweep, Shape Cast) PhysX style scene query system for spatial queries against the physics world. Supports overlap tests, sweep/shape casts, and multi hit collection. Features: Sphere/Box/Capsule overlap tests (find all bodies overlapping a shape) Sphere/Box sweep (shape cast along a direction, find first/all hits) Closest hit and multi hit modes Layer/mask filtering CPU side for low latency (synchronous results), uses CPU shadow data Based on: PhysX PxScene::overlap(), sweep(), raycast() PhysX PxOverlapBuffer, PxSweepBuffer Jolt NarrowPhaseQuery: CastShape, CollideShape CPU only implementation (not GPU compute) because: Scene queries are typically 1 10 per frame (not thousands) Need synchronous results (gameplay logic depends on them immediately) GPU readback latency would negate the benefit Classes Method Signature Summary Find all bodies overlapping a sphere. Find all bodies overlapping a box (AABB). Boolean overlap test: does anything overlap the sphere? Boolean overlap test: does anything overlap the box? Sphere sweep (shape cast): move a sphere along a direction, find first hit. Box sweep: move an AABB along a direction, find first hit. Multi hit sphere sweep: find ALL hits along the path. Functions Constants <! HUMAN NOTES Notes & Examples Physics Engine Integration The physics system provides rigid body dynamics, collision detection, and raycasting. Bodies have shapes (box, sphere, mesh), mass properties, and constraints. The GPU physics engine accelerates broad phase collision detection and particle systems. Example: Creating physics bodies Advanced: Collision detection and raycasting Advanced: Constraints and joints


async createSoftBodySolver(device, options = {})

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: GPUSoftBody.js — GPU FEM Soft Body Simulation Finite Element Method (FEM) soft body using tetrahedral meshes. PhysX 5's signature GPU feature — deformable materials like rubber, jelly, flesh, foam, etc. Based on: PhysX 5 FEM Soft Bodies: tetrahedral simulation mesh + collision mesh Müller et al. "Real Time Physics" (XPBD for FEM) Smith et al. "Stable Neo Hookean Flesh Simulation" (SIGGRAPH 2018) Irving et al. "Invertible Finite Elements" (SIGGRAPH 2004) Architecture: Tetrahedral mesh defines volume elements Each tet has a rest state inverse matrix (Dm inv) Per frame: compute deformation gradient F, strain, stress → nodal forces GPU shader: one thread per tetrahedron Supports Neo Hookean and co rotational constitutive models Nodes can be pinned (fixed) or coupled to rigid bodies Material properties: Young's modulus E: stiffness (rubber 1MPa, steel 200GPa) Poisson's ratio ν: incompressibility (rubber 0.49, steel 0.3) Damping: velocity proportional damping Classes Method Signature Summary Add a material. Create a soft body from tetrahedral mesh data. Generate a simple cube soft body for testing. Step soft body simulation. Async readback of node positions. Functions Lamé parameters from Young's modulus and Poisson's ratio. Constants — Material presets (Young's modulus in Pa, Poisson's ratio). <! HUMAN NOTES Notes & Examples Physics Engine Integration The physics system provides rigid body dynamics, collision detection, and raycasting. Bodies have shapes (box, sphere, mesh), mass properties, and constraints. The GPU physics engine accelerates broad phase collision detection and particle systems. Example: Creating physics bodies Advanced: Collision detection and raycasting Advanced:


accelerates broad phase collision detection and particle systems. Example: Creating physics bodies Advanced: Collision detection and raycasting Advanced: Constraints and joints Advanced: Continuous collision detection (CCD) Gotchas: Units : Physics uses meters, kilograms, seconds. A 1 unit cube is 1 meter. Time step : Fixed time step (1/60) gives stable simulation; variable dt causes explosions. Collision layers : Use collision masks to filter what collides (player vs enemy, bullet vs world). Sleeping : At rest bodies sleep to save CPU — wake them before applying forces. See also: Physics · GPU Physics Engine


async createTriangleMesh(device, worldBuffers, narrowphaseBuffers, options = {})

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: GPUTriangleMesh.js — GPU Triangle Mesh Static Collider Collision detection against static triangle meshes on GPU. Used for environment geometry (terrain, buildings, props) that doesn't move but needs accurate concave collision. Based on: PhysX PxTriangleMeshGeometry: cooked triangle mesh with BVH PhysX GPU: buildGPUData flag for GPU accelerated triangle mesh contacts Embree style BVH: AABB tree for triangle culling Architecture: CPU: Cook mesh → build BVH → upload to GPU buffers GPU: Per body shader traverses BVH, tests triangles in leaf nodes Generates contacts into the shared narrowphase contact buffer Limitations (matching PhysX): Triangle meshes are STATIC only (no deformation at runtime) For deformable meshes, use GPUSoftBody.js instead Max 65536 triangles per mesh (GPU buffer limit, configurable) Max 16 meshes registered simultaneously Classes Method Signature Summary Register a triangle mesh for collision. Unregister a triangle mesh. Dispatch collision detection for all registered meshes. Adds contacts to the narrowphase contact buffer. Functions Build a BVH from triangle data for GPU traversal. Uses surface area heuristic (SAH) median split. Parameters: (Float32Array) — Flat xyz positions (Uint32Array) — Triangle indices (length = triCount 3) Returns: } Constants <! HUMAN NOTES Notes & Examples Physics Engine Integration The physics system provides rigid body dynamics, collision detection, and raycasting. Bodies have shapes (box, sphere, mesh), mass properties, and constraints. The GPU physics engine accelerates broad phase collision detection and particle systems. Example: Creating physics bodies Advanced: Collision detection and raycasting Advanced: Constraints and


broad phase collision detection and particle systems. Example: Creating physics bodies Advanced: Collision detection and raycasting Advanced: Constraints and joints Advanced: Continuous collision detection (CCD) Gotchas: Units : Physics uses meters, kilograms, seconds. A 1 unit cube is 1 meter. Time step : Fixed time step (1/60) gives stable simulation; variable dt causes explosions. Collision layers : Use collision masks to filter what collides (player vs enemy, bullet vs world). Sleeping : At rest bodies sleep to save CPU — wake them before applying forces. See also: Physics · GPU Physics Engine


async createTriggerSystem(device, worldBuffers, broadphaseBuffers, narrowphaseBuffers, options = {})

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: GPUTriggerSystem.js — Trigger Volumes & Contact Event System GPU accelerated trigger overlap detection and contact event generation. Mirrors PhysX's onContact/onTrigger callback system. Features: Trigger volumes: AABB overlap tests on GPU, event dispatch on CPU Contact events: begin/persist/end contact tracking with entity IDs Event buffering: GPU writes events, CPU reads back and dispatches Pair tracking: persistent pair state across frames for begin/end detection Based on: PhysX PxSimulationEventCallback: onContact, onTrigger, onConstraintBreak PhysX PxPairFlag: eNOTIFY TOUCH FOUND, eNOTIFY TOUCH PERSISTS, eNOTIFY TOUCH LOST PhysX PxShapeFlagEnum: eTRIGGER SHAPE (no contact response, only overlap events) Classes Method Signature Summary Dispatch trigger and contact event generation. Call after broadphase (needs AABBs) and after narrowphase (needs contacts). Async readback + event processing. Resolves enter/stay/exit for triggers and begin/persist/end for contacts. Functions Constants <! HUMAN NOTES Notes & Examples Physics Engine Integration The physics system provides rigid body dynamics, collision detection, and raycasting. Bodies have shapes (box, sphere, mesh), mass properties, and constraints. The GPU physics engine accelerates broad phase collision detection and particle systems. Example: Creating physics bodies Advanced: Collision detection and raycasting Advanced: Constraints and joints Advanced: Continuous collision detection (CCD) Gotchas: Units : Physics uses meters, kilograms, seconds. A 1 unit cube is 1 meter. Time step : Fixed time step (1/60) gives stable simulation; variable dt causes explosions. Collision layers : Use collision masks to filter what collides


Time step : Fixed time step (1/60) gives stable simulation; variable dt causes explosions. Collision layers : Use collision masks to filter what collides (player vs enemy, bullet vs world). Sleeping : At rest bodies sleep to save CPU — wake them before applying forces. See also: Physics · GPU Physics Engine


async createVehicleManager(device, worldBuffers, options = {})

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: GPUVehicle.js — GPU Accelerated Vehicle Physics Arcade to simulation vehicle system running on GPU compute. Models wheels, suspension, engine, transmission, steering, and drivetrain. Based on: PhysX 5 Vehicle SDK: suspension raycasts, tire model, drivetrain Bullet Vehicle: raycast vehicle with Pacejka tire friction Marco Monster's "Car Physics for Games" (classic reference) Brian Beckman's "Physics of Racing" series Architecture: Vehicle is a rigid body in GPURigidBodyWorld with attached wheel descriptors Each frame: suspension raycasts → tire forces → engine torque → apply to chassis body GPU shader handles all wheels in parallel (one thread per wheel across all vehicles) CPU manages gear shifts, input mapping, and vehicle creation Tire model: simplified Pacejka "Magic Formula" F = D sin(C atan(B slip E (B slip atan(B slip)))) Simplified to: F = peakForce sin(2 atan(slip / peakSlip)) Classes Method Signature Summary Create a vehicle. Set vehicle input state. Update vehicle states before GPU dispatch. Computes engine torque, gear ratio, etc. from inputs. Dispatch vehicle physics compute. Call BEFORE the main rigid body step so forces are ready. After dispatch, accumulated wheel forces need to be applied to chassis bodies. After GPU dispatch + readback, apply accumulated wheel forces to chassis rigid bodies. Called on CPU after readback. Get vehicle state for UI/audio. Functions Constants — Default wheel presets for common vehicle types. — Default engine/transmission presets. <! HUMAN NOTES Notes & Examples Physics Engine Integration The physics system provides rigid body dynamics, collision detection, and raycasting. Bodies have shapes (box, sphere, mesh), mass properties, and


Integration The physics system provides rigid body dynamics, collision detection, and raycasting. Bodies have shapes (box, sphere, mesh), mass properties, and constraints. The GPU physics engine accelerates broad phase collision detection and particle systems. Example: Creating physics bodies Advanced: Collision detection and raycasting Advanced: Constraints and joints Advanced: Continuous collision detection (CCD) Gotchas: Units : Physics uses meters, kilograms, seconds. A 1 unit cube is 1 meter. Time step : Fixed time step (1/60) gives stable simulation; variable dt causes explosions. Collision layers : Use collision masks to filter what collides (player vs enemy, bullet vs world). Sleeping : At rest bodies sleep to save CPU — wake them before applying forces. See also: Physics · GPU Physics Engine


sim/physics/gpu/index.js
Exports
Notes & Examples
Physics Engine Integration

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: GPU Physics Engine — Barrel Export Standalone WebGPU compute based rigid body physics engine. Full PhysX 5 feature parity via WebGPU compute shaders. Import from this file to access all GPU physics components. Usage: import { createGPUPhysicsWorld, createBroadphase, ... } from './gpu/index.js'; ═══════════════════════════════════════════════════════════════ Core Rigid Body Pipeline (7 files): GPURigidBodyWorld — World, bodies, integration, islands, readback GPUBroadphase — Spatial hash broadphase, AABB, pair finding GPUNarrowphase — Shape shape contact generation (PCM) GPUConstraintSolver — TGS Soft contacts + D6 joints + relaxation GPUConvexHull — Quickhull 3D, support maps, GPU upload GPURaycast — GPU parallel raycast + CPU fallback GPUContinuousCollision — Speculative CCD (AABB expansion + TOI) Extended Simulation (4 files): GPUVehicle — Wheels, suspension, Pacejka tires, drivetrain GPUCharacterController — Kinematic CCT (slide move, step climb, slope limit) GPUSoftBody — FEM soft body (tetrahedral, co rotational elasticity) GPUTriggerSystem — Trigger volumes + contact events (enter/stay/exit) Geometry & Queries (4 files): GPUSceneQuery — Overlap tests, sweep/shape casts GPUHeightfield — Terrain heightfield collider (bilinear, materials, holes) GPUTriangleMesh — Static triangle mesh collider (BVH traversal) ═══════════════════════════════════════════════════════════════ Existing Engine Systems (already built, import from parent): ../GPUClothSolver.js — PBD cloth (small substeps + OGC contact) ../GPUArticulationSolver.js — Articulated chains (Cosserat rods) ../GPUSpatialHash.js — Morton code spatial hash (GPU Gems 3) ../SDFCollision.js — SDF mesh geometry (PhysX 5 style)


— Articulated chains (Cosserat rods) ../GPUSpatialHash.js — Morton code spatial hash (GPU Gems 3) ../SDFCollision.js — SDF mesh geometry (PhysX 5 style) ../PBDSolver.js — Position Based Dynamics (XPBD, graph coloring) ../MLSMPMSolver.js — MLS MPM soft body (snow, sand, jelly) ../OGCContact.js — Offset Geometric Contact (SIGGRAPH 2025) ../SpeculativeContacts.js — CPU speculative CCD ../ShockPropagation.js — Shock propagation (Guendelman 2003) ../VoronoiFracture.js — Voronoi destruction (Blast SDK equivalent) ../ConvexDecomposition.js — V HACD convex decomposition ../VoxelMeshCollision.js — Voxelized mesh collider (LOD) ../DynamicMeshCollider.js — Runtime mesh collider updates ═══════════════════════════════════════════════════════════════ Exports No ES module exports detected in this file. <! HUMAN NOTES Notes & Examples Physics Engine Integration The physics system provides rigid body dynamics, collision detection, and raycasting. Bodies have shapes (box, sphere, mesh), mass properties, and constraints. The GPU physics engine accelerates broad phase collision detection and particle systems. Example: Creating physics bodies Advanced: Collision detection and raycasting Advanced: Constraints and joints Advanced: Continuous collision detection (CCD) Gotchas: Units : Physics uses meters, kilograms, seconds. A 1 unit cube is 1 meter. Time step : Fixed time step (1/60) gives stable simulation; variable dt causes explosions. Collision layers : Use collision masks to filter what collides (player vs enemy, bullet vs world). Sleeping : At rest bodies sleep to save CPU — wake them before applying forces. See also: Physics · GPU Physics Engine


sim/physics/index.js
Re-exports
Notes & Examples
Physics Engine Integration

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: engine/sim/physics/index.js Physics Systems Barrel Export Re exports , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , <! HUMAN NOTES Notes & Examples Physics Engine Integration The physics system provides rigid body dynamics, collision detection, and raycasting. Bodies have shapes (box, sphere, mesh), mass properties, and constraints. The GPU physics engine accelerates broad phase collision detection and particle systems. Example: Creating physics bodies Advanced: Collision detection and raycasting Advanced: Constraints and joints Advanced: Continuous collision detection (CCD) Gotchas: Units : Physics uses meters, kilograms, seconds. A 1 unit cube is 1 meter. Time step : Fixed time step (1/60) gives stable simulation; variable dt causes explosions. Collision layers : Use collision masks to filter what collides (player vs enemy, bullet vs world). Sleeping : At rest bodies sleep to save CPU — wake them before applying forces. See also: Physics · GPU Physics Engine


<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: No file level description found in source. Add one as a leading JSDoc comment, or document it below. Classes Method Signature Summary Build a passive Verlet/PBD ragdoll (engine/assets/rig/RagdollSim.js) from the rig's parts. Works with EITHER adapter's part shape (both set as a numeric index): full fidelity (real axis/swingDeg/ twistDeg, hinge vs ball) when the rig came from CharacterPhysicsAssetAdapter; generic ball joints when it came from the legacy StickmanActiveRigAdapter (whose are PhysX D6 axis keyed, not swingDeg/twistDeg/axis). RagdollSim is intentionally passive (no muscle/drive concept) — this tier is a physical fallback, not an active motor replacement. Last resort tier: no physics at all, purely pose driven. Always succeeds. Functions <! HUMAN NOTES Notes & Examples Fallback chain (Phase 2 of the Ragdoll Stack Consolidation Roadmap) no longer picks a single backend and gives up on failure — it cascades through four tiers, updating to reflect whichever tier actually activated: 1. PhysX reduced articulation ( ) — tried first if and a PhysX was passed. 2. PhysX D6 ragdoll ( ) — tried if articulation wasn't requested/available, still requires a . 3. Verlet/PBD ( , new) — no PhysX required at all. Builds bones directly from (works with either or output, since both set as a numeric index). Full axis/swing/twist fidelity when the rig came from ; degrades to generic ball joints for the legacy shape. This tier is intentionally passive — no drives/muscles, just gravity + constraints. 4. Kinematic only ( , new) — always succeeds; no physics at all, is forced to and the controller becomes purely pose driven (render pose === blended/balanced pose every frame). , , and all branch


succeeds; no physics at all, is forced to and the controller becomes purely pose driven (render pose === blended/balanced pose every frame). , , and all branch on (now including and ) so the rest of the API is identical regardless of which tier is active — callers don't need to know or care which backend actually initialized. Physics Engine Integration The physics system provides rigid body dynamics, collision detection, and raycasting. Bodies have shapes (box, sphere, mesh), mass properties, and constraints. The GPU physics engine accelerates broad phase collision detection and particle systems. Example: Creating physics bodies Advanced: Collision detection and raycasting Advanced: Constraints and joints Advanced: Continuous collision detection (CCD) Gotchas: Units : Physics uses meters, kilograms, seconds. A 1 unit cube is 1 meter. Time step : Fixed time step (1/60) gives stable simulation; variable dt causes explosions. Collision layers : Use collision masks to filter what collides (player vs enemy, bullet vs world). Sleeping : At rest bodies sleep to save CPU — wake them before applying forces. See also: Physics · GPU Physics Engine Physics Engine Integration The physics system provides rigid body dynamics, collision detection, and raycasting. Bodies have shapes (box, sphere, mesh), mass properties, and constraints. The GPU physics engine accelerates broad phase collision detection and particle systems. Example: Creating physics bodies Advanced: Collision detection and raycasting Advanced: Constraints and joints Advanced: Continuous collision detection (CCD) Gotchas: Units : Physics uses meters, kilograms, seconds. A 1 unit cube is 1 meter. Time step : Fixed time step (1/60) gives stable simulation; variable dt causes explosions. Collision layers : Use collision


seconds. A 1 unit cube is 1 meter. Time step : Fixed time step (1/60) gives stable simulation; variable dt causes explosions. Collision layers : Use collision masks to filter what collides (player vs enemy, bullet vs world). Sleeping : At rest bodies sleep to save CPU — wake them before applying forces. See also: Physics · GPU Physics Engine


frequencyToDrive({ frequencyHz = 4.5, dampingRatio = 1.0, effectiveMass = 1, mode = DRIVEMODES.acceleration } = {})

getJointTorqueBudget(jointType, massKg = 80, presetName = 'HumanAverage', tier = 'avg')

createDriveProfile({ joints = [], massKg = 80, preset = 'HumanAverage', frequencyHz = 4.5, dampingRatio = 1.0, driveMode = DRIVEMODES.acceleration } = {})

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: No file level description found in source. Add one as a leading JSDoc comment, or document it below. Functions Constants <! HUMAN NOTES Notes & Examples Physics Engine Integration The physics system provides rigid body dynamics, collision detection, and raycasting. Bodies have shapes (box, sphere, mesh), mass properties, and constraints. The GPU physics engine accelerates broad phase collision detection and particle systems. Example: Creating physics bodies Advanced: Collision detection and raycasting Advanced: Constraints and joints Advanced: Continuous collision detection (CCD) Gotchas: Units : Physics uses meters, kilograms, seconds. A 1 unit cube is 1 meter. Time step : Fixed time step (1/60) gives stable simulation; variable dt causes explosions. Collision layers : Use collision masks to filter what collides (player vs enemy, bullet vs world). Sleeping : At rest bodies sleep to save CPU — wake them before applying forces. See also: Physics · GPU Physics Engine


estimateCenterOfMass(joints = {}, fallback = [0, 0, 0])

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: No file level description found in source. Add one as a leading JSDoc comment, or document it below. Classes Method Signature Summary Functions <! HUMAN NOTES Notes & Examples Physics Engine Integration The physics system provides rigid body dynamics, collision detection, and raycasting. Bodies have shapes (box, sphere, mesh), mass properties, and constraints. The GPU physics engine accelerates broad phase collision detection and particle systems. Example: Creating physics bodies Advanced: Collision detection and raycasting Advanced: Constraints and joints Advanced: Continuous collision detection (CCD) Gotchas: Units : Physics uses meters, kilograms, seconds. A 1 unit cube is 1 meter. Time step : Fixed time step (1/60) gives stable simulation; variable dt causes explosions. Collision layers : Use collision masks to filter what collides (player vs enemy, bullet vs world). Sleeping : At rest bodies sleep to save CPU — wake them before applying forces. See also: Physics · GPU Physics Engine


createActiveRigFromCharacterPhysicsAsset(asset, options = {})

createActiveRigControllerOptionsFromCharacterPhysicsAsset(asset, options = {})

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: engine/sim/physics/rig/CharacterPhysicsAssetAdapter.js — converts a CharacterPhysicsAsset (engine/assets/rig/CharacterPhysicsAsset.js) into the { parts, joints, bodies } rig shape ActiveRigController expects. This is the Phase 1 fix for the ragdoll stack's root cause bug: StickmanActiveRigAdapter.js only ever read the hand authored StickmanRagdoll ECS shape, completely disconnected from RagdollBuilder/JointLimits' output — meaning PhysX built joints from different axis/limit data than RagdollSim did, so systems disagreed about which way an elbow/knee should bend. This adapter reads the SAME asset.jointDefs (axis/swingDeg/twistDeg/motion/ frameA/frameB) that RagdollSim consumes, so PhysX and the Verlet fallback now agree by construction. Functions Build an ActiveRigController compatible rig descriptor from a CharacterPhysicsAsset. Parameters: (object) — A CharacterPhysicsAsset (see engine/assets/rig/CharacterPhysicsAsset.js) (object) — No description in source JSDoc. Returns: rig — { id, name, backend, root, parts, joints, bodies, bonePairs, pose, retarget, driveProfile } Build the full option bag expects, from a CharacterPhysicsAsset — the CharacterPhysicsAsset equivalent of . Parameters: (object) — A CharacterPhysicsAsset (object) — No description in source JSDoc. Returns: { rig, retargetGraph, initialPoseState, config } Trivial identity retarget graph (physics joint id === render bone id/slot). <! HUMAN NOTES Notes & Examples Physics Engine Integration The physics system provides rigid body dynamics, collision detection, and raycasting. Bodies have shapes (box, sphere, mesh), mass properties, and constraints. The GPU physics engine accelerates broad phase collision detection


and raycasting. Bodies have shapes (box, sphere, mesh), mass properties, and constraints. The GPU physics engine accelerates broad phase collision detection and particle systems. Example: Creating physics bodies Advanced: Collision detection and raycasting Advanced: Constraints and joints Advanced: Continuous collision detection (CCD) Gotchas: Units : Physics uses meters, kilograms, seconds. A 1 unit cube is 1 meter. Time step : Fixed time step (1/60) gives stable simulation; variable dt causes explosions. Collision layers : Use collision masks to filter what collides (player vs enemy, bullet vs world). Sleeping : At rest bodies sleep to save CPU — wake them before applying forces. See also: Physics · GPU Physics Engine


sim/physics/rig/MuscleLayer.js
Classes
class MuscleLayer
Constants
Notes & Examples
Physics Engine Integration

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: No file level description found in source. Add one as a leading JSDoc comment, or document it below. Classes Method Signature Summary Constants <! HUMAN NOTES Notes & Examples Physics Engine Integration The physics system provides rigid body dynamics, collision detection, and raycasting. Bodies have shapes (box, sphere, mesh), mass properties, and constraints. The GPU physics engine accelerates broad phase collision detection and particle systems. Example: Creating physics bodies Advanced: Collision detection and raycasting Advanced: Constraints and joints Advanced: Continuous collision detection (CCD) Gotchas: Units : Physics uses meters, kilograms, seconds. A 1 unit cube is 1 meter. Time step : Fixed time step (1/60) gives stable simulation; variable dt causes explosions. Collision layers : Use collision masks to filter what collides (player vs enemy, bullet vs world). Sleeping : At rest bodies sleep to save CPU — wake them before applying forces. See also: Physics · GPU Physics Engine


resolveRequestedPoseState(intent = {}, fallback = 'idlestand')

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: No file level description found in source. Add one as a leading JSDoc comment, or document it below. Classes Method Signature Summary Functions Constants <! HUMAN NOTES Notes & Examples Physics Engine Integration The physics system provides rigid body dynamics, collision detection, and raycasting. Bodies have shapes (box, sphere, mesh), mass properties, and constraints. The GPU physics engine accelerates broad phase collision detection and particle systems. Example: Creating physics bodies Advanced: Collision detection and raycasting Advanced: Constraints and joints Advanced: Continuous collision detection (CCD) Gotchas: Units : Physics uses meters, kilograms, seconds. A 1 unit cube is 1 meter. Time step : Fixed time step (1/60) gives stable simulation; variable dt causes explosions. Collision layers : Use collision masks to filter what collides (player vs enemy, bullet vs world). Sleeping : At rest bodies sleep to save CPU — wake them before applying forces. See also: Physics · GPU Physics Engine


sim/physics/rig/RetargetGraph.js
Classes
class RetargetGraph
class PoseBlendState
Functions
createEmptyPoseBuffer()
createPoseJoint(id, options = {})
clonePoseBuffer(pose)
blendPoseBuffers(a, b, t)
poseFromJointArray(joints = [])
Notes & Examples
Physics Engine Integration

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: No file level description found in source. Add one as a leading JSDoc comment, or document it below. Classes Method Signature Summary Method Signature Summary Functions <! HUMAN NOTES Notes & Examples Physics Engine Integration The physics system provides rigid body dynamics, collision detection, and raycasting. Bodies have shapes (box, sphere, mesh), mass properties, and constraints. The GPU physics engine accelerates broad phase collision detection and particle systems. Example: Creating physics bodies Advanced: Collision detection and raycasting Advanced: Constraints and joints Advanced: Continuous collision detection (CCD) Gotchas: Units : Physics uses meters, kilograms, seconds. A 1 unit cube is 1 meter. Time step : Fixed time step (1/60) gives stable simulation; variable dt causes explosions. Collision layers : Use collision masks to filter what collides (player vs enemy, bullet vs world). Sleeping : At rest bodies sleep to save CPU — wake them before applying forces. See also: Physics · GPU Physics Engine


createActiveRigFromStickman(stickman = {}, options = {})

createActiveRigControllerOptionsFromStickman(stickman = {}, options = {})

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: No file level description found in source. Add one as a leading JSDoc comment, or document it below. Functions <! HUMAN NOTES Notes & Examples Physics Engine Integration The physics system provides rigid body dynamics, collision detection, and raycasting. Bodies have shapes (box, sphere, mesh), mass properties, and constraints. The GPU physics engine accelerates broad phase collision detection and particle systems. Example: Creating physics bodies Advanced: Collision detection and raycasting Advanced: Constraints and joints Advanced: Continuous collision detection (CCD) Gotchas: Units : Physics uses meters, kilograms, seconds. A 1 unit cube is 1 meter. Time step : Fixed time step (1/60) gives stable simulation; variable dt causes explosions. Collision layers : Use collision masks to filter what collides (player vs enemy, bullet vs world). Sleeping : At rest bodies sleep to save CPU — wake them before applying forces. See also: Physics · GPU Physics Engine


sim/physics/rig/index.js
Exports
Notes & Examples
Physics Engine Integration

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: No file level description found in source. Add one as a leading JSDoc comment, or document it below. Exports No ES module exports detected in this file. <! HUMAN NOTES Notes & Examples Physics Engine Integration The physics system provides rigid body dynamics, collision detection, and raycasting. Bodies have shapes (box, sphere, mesh), mass properties, and constraints. The GPU physics engine accelerates broad phase collision detection and particle systems. Example: Creating physics bodies Advanced: Collision detection and raycasting Advanced: Constraints and joints Advanced: Continuous collision detection (CCD) Gotchas: Units : Physics uses meters, kilograms, seconds. A 1 unit cube is 1 meter. Time step : Fixed time step (1/60) gives stable simulation; variable dt causes explosions. Collision layers : Use collision masks to filter what collides (player vs enemy, bullet vs world). Sleeping : At rest bodies sleep to save CPU — wake them before applying forces. See also: Physics · GPU Physics Engine


<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: Vehicle2 WebIDL capability adapters. The generated declaration exposes several helpers as statics while the emitted JavaScript places them on the constructor prototype, so all vehicle code crosses that mismatch here. Functions <! HUMAN NOTES Notes & Examples Physics Engine Integration The physics system provides rigid body dynamics, collision detection, and raycasting. Bodies have shapes (box, sphere, mesh), mass properties, and constraints. The GPU physics engine accelerates broad phase collision detection and particle systems. Example: Creating physics bodies Advanced: Collision detection and raycasting Advanced: Constraints and joints Advanced: Continuous collision detection (CCD) Gotchas: Units : Physics uses meters, kilograms, seconds. A 1 unit cube is 1 meter. Time step : Fixed time step (1/60) gives stable simulation; variable dt causes explosions. Collision layers : Use collision masks to filter what collides (player vs enemy, bullet vs world). Sleeping : At rest bodies sleep to save CPU — wake them before applying forces. See also: Physics · GPU Physics Engine


configureVehicleChassis(PhysX, vehicle, config, alloc)

initializeVehicleActor(PhysX, topLevel, world, vehicle, config, alloc)


sim/physics/vehicle/VehicleConfig.js
Functions
resolveVehicleConfig(options = {})
arrayAt(owner, field, index)
Notes & Examples
Physics Engine Integration


createVehicleController({ PhysX, world, topLevel, vehicle, actor, context, sweepMesh, tracked, config, gears, })


sim/physics/vehicle/VehicleEngine.js
Functions
configureVehicleEngine(vehicle, config)
Notes & Examples
Physics Engine Integration


configureVehicleWheels(PhysX, topLevel, vehicle, config, alloc)


sim/physics/vehicle/index.js
Functions
createPhysXVehicle(world, options = {})
Re-exports
Notes & Examples
Physics Engine Integration

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: No file level description found in source. Add one as a leading JSDoc comment, or document it below. Functions Build a complete PhysX Vehicle2 car from independently owned subsystems. Re exports <! HUMAN NOTES Notes & Examples Physics Engine Integration The physics system provides rigid body dynamics, collision detection, and raycasting. Bodies have shapes (box, sphere, mesh), mass properties, and constraints. The GPU physics engine accelerates broad phase collision detection and particle systems. Example: Creating physics bodies Advanced: Collision detection and raycasting Advanced: Constraints and joints Advanced: Continuous collision detection (CCD) Gotchas: Units : Physics uses meters, kilograms, seconds. A 1 unit cube is 1 meter. Time step : Fixed time step (1/60) gives stable simulation; variable dt causes explosions. Collision layers : Use collision masks to filter what collides (player vs enemy, bullet vs world). Sleeping : At rest bodies sleep to save CPU — wake them before applying forces. See also: Physics · GPU Physics Engine


sim/world/WindSimulation.js
Classes
class WindSimulation
class ProceduralWeather
class VolumetricClouds
Notes & Examples
Physics Engine Integration

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: No file level description found in source. Add one as a leading JSDoc comment, or document it below. Classes Method Signature Summary Set terrain boundary from heightmap Set wind direction and speed Run one LBM simulation step Get velocity buffer for wind erosion Get density buffer Load config from object Procedural Weather System Grid based weather simulation Simulates coupled ODE system for: Temperature (fed by sunshine, decreased by rain/altitude) Humidity (fed by water evaporation, lost to rain) Clouds (appear above temp/humidity thresholds) Precipitation (impulsive rain from cooling humid air) Wind (convects temperature and humidity) Method Signature Summary Initialize weather grids Step weather simulation Update wind field based on terrain Convect field using wind Diffuse (smooth) field Sample weather at world position Get average weather stats (for vegetation/biome generation) Load config Volumetric Cloud Generator Raymarched 3D density clouds INTEGRATION: Uses GPU particles for cloud puffs/wisps Uses WindSimulation for cloud advection Uses SpatialHashCompute for LOD particle culling Uses multi octave noise for cloud density with: Wind advection from LBM simulation Rayleigh/Mie scattering for realistic lighting LOD based on ray distance Method Signature Summary Connect to wind simulation and particle system CPU noise for cloud density (can be moved to GPU) Generate cloud density field Sample cloud density at world position Get cloud texture for rendering Load config <! HUMAN NOTES Notes & Examples Physics Engine Integration The physics system provides rigid body dynamics, collision detection, and raycasting. Bodies have shapes (box, sphere, mesh), mass properties, and


Integration The physics system provides rigid body dynamics, collision detection, and raycasting. Bodies have shapes (box, sphere, mesh), mass properties, and constraints. The GPU physics engine accelerates broad phase collision detection and particle systems. Example: Creating physics bodies Advanced: Collision detection and raycasting Advanced: Constraints and joints Advanced: Continuous collision detection (CCD) Gotchas: Units : Physics uses meters, kilograms, seconds. A 1 unit cube is 1 meter. Time step : Fixed time step (1/60) gives stable simulation; variable dt causes explosions. Collision layers : Use collision masks to filter what collides (player vs enemy, bullet vs world). Sleeping : At rest bodies sleep to save CPU — wake them before applying forces. See also: Physics · GPU Physics Engine


sim/world/WindSystem.js
Classes
class WindSystem
Notes & Examples
Physics Engine Integration

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: No file level description found in source. Add one as a leading JSDoc comment, or document it below. Classes WindSystem.js Global Wind Simulation Provides wind data for vegetation, particles, cloth, etc. Features gusts, turbulence, and directional wind Method Signature Summary <! HUMAN NOTES Notes & Examples Physics Engine Integration The physics system provides rigid body dynamics, collision detection, and raycasting. Bodies have shapes (box, sphere, mesh), mass properties, and constraints. The GPU physics engine accelerates broad phase collision detection and particle systems. Example: Creating physics bodies Advanced: Collision detection and raycasting Advanced: Constraints and joints Advanced: Continuous collision detection (CCD) Gotchas: Units : Physics uses meters, kilograms, seconds. A 1 unit cube is 1 meter. Time step : Fixed time step (1/60) gives stable simulation; variable dt causes explosions. Collision layers : Use collision masks to filter what collides (player vs enemy, bullet vs world). Sleeping : At rest bodies sleep to save CPU — wake them before applying forces. See also: Physics · GPU Physics Engine


stepWorldSim(worldSim, deltaSeconds, options = {})

exportWorldSimState(worldSim, options = {})


authorizes(cap, { principal, object, action, epoch, context = {} } = {})

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: state/authority/Capability.js — scoped, attenuable, revocable authority (spec §12). Observation does NOT imply permission (spec rule 29). A capability names a principal, an object, an allowed action, scope/constraints, expiry, and whether it is single use. Following Macaroons, a capability can be ATTENUATED by adding caveats (narrowing who/where/when/what) — never widened. Critical single use capabilities are themselves USOs (consumed on use). Authority is re checked at commit, closing the time of check/time of use gap. Functions Mint a capability. Parameters: (object) — No description in source JSDoc. (string) — who may use it (string) — target object/entity (or ' ' pattern) (string) — allowed action (e.g. 'edit file') (object) — arbitrary caveat predicates' data (number) — operational time expiry Returns: frozen capability with a stable Attenuate a capability by adding a caveat. The result is a NEW capability that is strictly narrower; it can never grant more than its parent (spec rule 30, CSE rule "a capability cannot grant rights beyond its issuer's rights"). Parameters: (object) — No description in source JSDoc. Test whether a capability authorizes an action in a context. Checks object/action match, expiry, and every caveat predicate. Does NOT check revocation — that lives in the registry (online status, spec rule 31). Returns: } <! HUMAN NOTES Notes & Examples No hand authored notes yet. Add page notes in or a reusable block in — see API Reference Standard.


state/authority/CapabilityRegistry.js
Classes
class CapabilityRegistry
Notes & Examples

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: state/authority/CapabilityRegistry.js — registry + revocation (spec §6,§12). Holds issued capabilities and a revocation set. A revoked critical capability can never commit (safety invariant, spec §19). Revocation sensitive capabilities require an online status check at commit, so the coordinator asks the registry — not a cached plan — whether a capability is still valid. Classes Method Signature Summary Issue (store) a capability. Returns its id. Look up a capability by id, or null. Revoke a capability (online status — checked at commit). Authorize a request against a stored capability id, applying revocation and single use checks. Does NOT consume — the coordinator consumes only after a successful atomic commit (single use caps are USOs). Mark a single use capability consumed (called by coordinator post commit). <! HUMAN NOTES Notes & Examples No hand authored notes yet. Add page notes in or a reusable block in — see API Reference Standard.


async createSigner(principal, opts = {})

async verifyWithKey(publicKeyHex, data, signatureHex)

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: state/authority/Identity.js — pluggable signer for the Authority plane (spec §12). Authority is explicit and bound to a signing key, not an ambient bearer token (spec rule 30, CSE rule 1). This wraps the engine's existing ECDSA P 256 identity (engine/collab/CollabIdentity.js) behind a minimal signer interface so the commit coordinator can verify signatures at commit time. When SubtleCrypto is unavailable it degrades to a deterministic FNV stamp — usable for local dev, but flags that it carries no cryptographic guarantee. Functions Create an authority signer bound to a principal id. Each distinct principal gets its OWN persisted ECDSA P 256 keypair (via CollabIdentity's named key support) rather than sharing the single default device key. This lets the same device host multiple unlinkable signers — e.g. a stable identity and per group pseudonymous identities (engine/network/identity) — without one leaking the other's fingerprint. Parameters: (string) — logical actor id (e.g. 'agent.builder', 'profile:alice') (object) — No description in source JSDoc. (string) — explicit IndexedDB key id (defaults to ) Returns: signer { principal, fingerprint, publicKeyHex, secure, sign, verify } Verify a signature against an explicit public key (cross actor verification). Re exports <! HUMAN NOTES Notes & Examples No hand authored notes yet. Add page notes in or a reusable block in — see API Reference Standard.


state/authority/PolicyEngine.js
Classes
class PolicyEngine
Functions
policyRule(r)
Constants
Notes & Examples

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: state/authority/PolicyEngine.js — Authority plane policy engine + approval/risk gates (spec §3 plane 6, rules 30, 34). Capabilities say WHAT a principal may do; policy says under WHICH conditions it is currently allowed, and which actions need human/authority approval before they may commit. The engine evaluates ordered rules (deny overrides allow) and classifies an action's risk; irreversible / high risk actions are gated behind an explicit approval that must be present at commit time — closing the time of check/time of use gap together with the capability re check (rule 31). Policy is versioned (rule 5) so receipts can record which policy decided. Classes Method Signature Summary Evaluate a request. DENY overrides ALLOW; risk is the max asserted by any matching rule; approval is required if any matching allow rule demands it. Functions Parameters: (object) — No description in source JSDoc. (string) — No description in source JSDoc. ((ctx:object)= boolean) — matches the request context (string) — ALLOW DENY (string) — RISK LEVEL this rule asserts for the action (boolean) — No description in source JSDoc. Constants <! HUMAN NOTES Notes & Examples No hand authored notes yet. Add page notes in or a reusable block in — see API Reference Standard.


state/causal/CausalParents.js
Classes
class CausalGraph
Notes & Examples

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: state/causal/CausalParents.js — partial order over committed events (spec §2,§9). Lamport's happened before: causal relationships establish a partial order; concurrent events need not have a global order. This Causal Plane tracks the DAG of committed ids (commits, observations) so a new transaction can declare and the coordinator can verify those parents are known before committing. It reuses the partial order toposort from facts/Causality.js for deterministic projection of the known causal graph. Classes Method Signature Summary Register a known event id (commit, observation, fact). True if an event id is known to the graph. Record a new event with explicit causal parents. Parents must already be known (else the relationship is dangling). Returns the unknown parents. Verify causal parents for a proposed transaction WITHOUT mutating the graph. Deterministic partial order projection of all known events. Does (transitively) causally depend on ? <! HUMAN NOTES Notes & Examples No hand authored notes yet. Add page notes in or a reusable block in — see API Reference Standard.


state/causal/DottedVersionVector.js
Classes
class VersionVector
class DVVSet
Constants
Notes & Examples

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: state/causal/DottedVersionVector.js — precise concurrent version causality (spec §9 "Causal time", rule 8/9). A VersionVector summarizes "what I have seen" per node and gives a partial order: equal / before / after / concurrent. Dotted version vectors (Preguiça et al.) add the ability to track each write as an isolated event (a "dot") so concurrent writes are kept as explicit SIBLINGS instead of being silently lost or forcing per client metadata to grow without bound. This is the causality backbone the Causal Plane uses to decide when order is genuinely required. Classes Method Signature Summary Record a local event for , returning a new vector. Join: max per node (everything either side has seen). True if this vector dominates (has seen everything in) . Partial order comparison against another vector. A dotted version vector set for ONE logical key: stores the current value(s) plus the causal history at which each was written. Concurrent writes survive as siblings; a write that causally dominates a value replaces it. Method Signature Summary Read all current sibling values + the causal context to write back with. Number of concurrent siblings currently held (1 = no conflict). Constants <! HUMAN NOTES Notes & Examples No hand authored notes yet. Add page notes in or a reusable block in — see API Reference Standard.


state/causal/HLC.js
Classes
class HLC
Functions
compareHLC(a, b)
Notes & Examples

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: state/causal/HLC.js — Hybrid Logical Clock (spec §9 "Operational time", rule 11). An HLC (Kulkarni et al.) combines a logical clock's causal guarantees with a timestamp that stays close to physical time. Each timestamp is (l, c): tracks the max physical time observed, is a bounded counter that breaks ties when events share the same . HLC gives a total order consistent with causality (if A → B then ts(A) < ts(B)) while remaining readable as wall time. IMPORTANT (rule 11): a timestamp NEVER establishes authority, ownership, or uniqueness on its own — HLC orders events; the commit protocol decides truth. Classes Method Signature Summary Current timestamp without advancing. Generate a timestamp for a LOCAL event (send / new commit). Ensures monotonicity even if the physical clock has not advanced. Update on RECEIVING a remote timestamp, merging causal information so the local clock never goes backwards relative to a cause. Functions Compare two HLC timestamps {l,c}. Returns 1, 0, or 1. <! HUMAN NOTES Notes & Examples No hand authored notes yet. Add page notes in or a reusable block in — see API Reference Standard.


state/codebook/CodeEntry.js
Functions
makeCodeEntry(rawId, opts = {})
Notes & Examples

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: state/codebook/CodeEntry.js — the layered code packet. NOT one magic number: each field has exactly one job and never pretends to be another. denseID fast runtime handle exactID literal pattern identity (9 bit packed / canonical) spatialID where it belongs in space (filled by the spatial layer, M2) resonanceVector what it resembles (filled by the resonance layer, M3) correctionCode how to repair corruption (filled by the correction layer, M5) hashID have we seen this exact thing symbolicSig what it MEANS (optional) Functions Build a CodeEntry for a raw 3x3 pattern. Later layers enrich the null fields: spatialID (M2 SpatialCode), resonanceVector (M3 Transforms), correctionCode (M5 CorrectionGate). Keeping them explicitly null preserves the layer law — a missing layer is visibly missing, never faked. Parameters: (number) — packed 9 bit pattern (object) — No description in source JSDoc. (import('./PatternCodebook.js').PatternCodebook) — No description in source JSDoc. (object) — result of SymbolicSig.symbolicSig(...) Returns: CodeEntry <! HUMAN NOTES Notes & Examples No hand authored notes yet. Add page notes in or a reusable block in — see API Reference Standard.


state/codebook/PatternCodebook.js
Classes
class PatternCodebook
Functions
packPattern(cells)
unpackPattern(id)
hammingDistance(a, b)
symmetries(id)
canonicalId(id)
patternHashId(rawId)
Constants
Notes & Examples

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: state/codebook/PatternCodebook.js — Phase 1 of the URC pipeline: raw 3x3 block 9 bit exact id canonical (rotations/flips) dense id + hash id + nearest legal attractor (Hamming distance). This is the smallest stable codebook. Bigger blocks (8x8 DCT, 32x32 wavelets) plug into the resonance layer later; the contract here is: a raw pattern maps deterministically to a stable codebook entry. Classes Method Signature Summary Allocate (or fetch) a dense runtime id for a raw pattern's canonical form. Mark a canonical pattern as legal (an attractor that corrupted input may snap to). Snap a (possibly corrupted) raw pattern to the nearest LEGAL canonical attractor by Hamming distance. Resonance suggests ; this never asserts truth — callers decide whether to accept (visual) or verify (semantic). Functions Pack a length 9 array of truthy/0 cells (row major) into a 9 bit id (0..511). Unpack a 9 bit id back into a length 9 Uint8Array (row major). Number of differing cells between two packed 3x3 patterns. All 8 dihedral symmetries of a packed pattern. Canonical id = smallest packed id over all dihedral symmetries (rotation/flip invariant). Stable content fingerprint for a pattern (hash = identity). Constants <! HUMAN NOTES Notes & Examples No hand authored notes yet. Add page notes in or a reusable block in — see API Reference Standard.


state/codebook/SymbolicSig.js
Functions
primeAt(index)
symbolicSig(primeIndices)
sigEquals(a, b)
sigContains(sig, sub)
Constants
Notes & Examples

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: state/codebook/SymbolicSig.js — symbolic meaning via prime INDICES. Layer law: "Primes = symbolic meaning". We never multiply giant prime products at runtime (that would be slow and pretend to be storage). A symbolic signature is just a sorted set of prime indices; identity stays in hashes, speed stays in dense ids. Two things that look alike (resonance) can still mean opposite things — meaning is checked HERE, not by similarity. Functions Prime value for a given index (bounds checked). Build a symbolic signature: a sorted, de duplicated vector of prime indices. Parameters: (Iterable<number ) — No description in source JSDoc. Returns: } Meaning equality — compares index sets, NEVER products. True if 's meanings are all present in (symbolic containment). Constants <! HUMAN NOTES Notes & Examples No hand authored notes yet. Add page notes in or a reusable block in — see API Reference Standard.


createCommitGate({ constraints = [], authority = null } = {})

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: state/commit/CommitGate.js — only commit gates decide FINAL truth. Core law: "Similarity may suggest. Facts may branch. Constraints may reject. But only commit gates decide final truth." Used for the orderless unsafe things: inventory, permissions, ownership, money, save overwrite, security, multiplayer hit confirm, choosing a canonical branch. A commit applies a delta (adds + tombstones) to a CLONE of the base store, runs COMMIT strength constraints, then an optional authority check. It never mutates the base — truth is the returned store, with a witness either way. Functions Parameters: (object) — No description in source JSDoc. (Array) — commit strength constraints ((context:object)= boolean) — e.g. signature / ownership check <! HUMAN NOTES Notes & Examples No hand authored notes yet. Add page notes in or a reusable block in — see API Reference Standard.


correct({ tier, repaired, verify, unsure = false })

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: state/commit/CorrectionGate.js — correction is NOT authority. Tiered policy (the layer law for repair): VISUAL state may auto correct (particles, cache, chunk, network with confidence) SEMANTIC state must verify before applying (inventory, save, ...) SECURITY state must NEVER silently repair (permission, ownership, security) When unsure: branch / quarantine / request authority — never silently fix. Resonance (nearestAttractor) may SUGGEST the repaired value, but acceptance is decided here, and a security tier can only escalate, never apply. Functions Decide what to do with a (resonance )repaired candidate. Parameters: (object) — No description in source JSDoc. (string) — CORRECTION TIERS. ( ) — suggested repaired value (from attractor snap, etc.) (()= boolean) — semantic verifier (hash / constraint / authority check) (boolean) — if true, never auto apply even at VISUAL Returns: } Constants <! HUMAN NOTES Notes & Examples No hand authored notes yet. Add page notes in or a reusable block in — see API Reference Standard.


state/consistency/CRDT.js
Classes
class GCounter
class PNCounter
class GSet
class ORSet
class LWWRegister
Notes & Examples

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: state/consistency/CRDT.js — approved mergeable types (spec §4 "Mergeable state", rule 14/36). State based CRDTs (CvRDTs): every type exposes a that is a least upper bound join — associative, commutative, and idempotent — so replicas that exchange state in any order/any number of times converge to the same value WITHOUT coordination (CALM / coordination avoidance). Each merge is non mutating and returns a NEW instance so the join algebra is easy to test. IMPORTANT (rule 36): CRDT convergence is NOT proof of application validity. A CRDT may only be used for a value after confirms its operations preserve the relevant invariants. These types are the approved building blocks, not a license to make any value mergeable. Classes Method Signature Summary Increment this node's count (monotonic, n ≥ 0). Join: take the max observed count per node. Method Signature Summary Method Signature Summary Method Signature Summary Add an element with a unique tag (auto generated if omitted). Remove an element by tombstoning every tag currently observed for it. Join: union add tags per element and union the remove tombstones. Method Signature Summary <! HUMAN NOTES Notes & Examples No hand authored notes yet. Add page notes in or a reusable block in — see API Reference Standard.


classifyConfluence({ initial, merge, invariant, operations, depth = 2 })

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: state/consistency/InvariantConfluence.js — coordination avoidance classifier (spec §4, §8 "Consistency Plane", rule 35/36). Invariant confluence (Bailis et al.) is the precise test for whether a set of operations can run WITHOUT coordination: a set of operations is I confluent with respect to an invariant I if, for any I valid states reachable from a common ancestor, their merge is also I valid. If so, replicas may diverge and merge freely (CALM); if not, those operations need a coordinating commit (Exclusive/serializable profile). This is a BOUNDED, honest classifier (a finite model property check, in the spirit of §19) — it explores states reachable within operations and reports a concrete counterexample when it finds one. A "confluent" result is evidence within the explored bound, not a closed form proof. Functions Classify a set of operations for invariant confluence. Parameters: (object) — No description in source JSDoc. ( ) — a valid starting state (CRDT instance or value) ((a: , b: )= ) — least upper bound join of two states ((s: )= boolean) — the application invariant I (number) — branch exploration depth (default 2) Returns: } <! HUMAN NOTES Notes & Examples No hand authored notes yet. Add page notes in or a reusable block in — see API Reference Standard.


<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: state/consistency/OptimisticValidator.js — optimistic read set / predicate validation and write skew detection (spec §6, §8, rule 22/24). The "Optimistic" consistency profile reads versions, proposes a replacement, and commits only if every read remained current (MVCC validation). Checking only WRITTEN objects is insufficient: snapshot execution can admit write skew anomalies involving predicates or separately read objects. So validation must cover the full declared read set AND predicates, and a serializability check must detect dangerous rw antidependency structures between concurrent transactions. Classes Validate a transaction's declared read set and predicates against the current state. Used standalone or alongside the CommitCoordinator's version check. Method Signature Summary Functions Detect a write skew (non serializable) hazard between two CONCURRENT transactions. Write skew occurs when each transaction reads data the other writes — two rw antidependency edges — so both can pass snapshot validation yet jointly violate an invariant coupling the items. Returns: } <! HUMAN NOTES Notes & Examples No hand authored notes yet. Add page notes in or a reusable block in — see API Reference Standard.


state/consistency/Reservation.js
Classes
class ReservationManager
class BoundedCounterEscrow
Notes & Examples

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: state/consistency/Reservation.js — reservations + bounded counter escrow (spec §5 fragmentation fix, §10, rule 16). Two coordination avoidance tools that sit in front of the commit path: • ReservationManager — a reservation is itself a USO (single use, exclusive). Reserving a scarce resource creates a reservation output; it is later CONSUMED on commit or RELEASED/expired. A reservation can never be consumed twice (inherits the USO double commit guarantee), and an expired reservation cannot mutate protected state (liveness: aborted reservation is eventually released). • BoundedCounterEscrow — divides decrement rights for a scarce quantity among holders so each can withdraw from its local grant WITHOUT coordination, while preserving the lower bound invariant (quantity never drops below the floor). Coordination is only needed when a holder exhausts its grant and must be rebalanced. This is the escrow / bounded counter CRDT pattern. Classes Method Signature Summary Reserve a resource for a holder until (operational time). Creates a reservation USO; returns its id. True if the reservation is unspent and not past its expiry at . Consume a reservation (the holder commits). Fails if expired or already consumed/released — guaranteeing it is honored at most once. Release a reservation (holder abandons it or it expired). Marks the reservation USO spent so it can never be consumed afterward. Method Signature Summary Withdrawable headroom not yet granted to any holder. Total withdrawn across all holders. Remaining quantity above the floor (pool + all outstanding grants). A holder's local (coordination free) withdrawal rights. Grant part of the ungranted pool to a holder as local withdrawal


floor (pool + all outstanding grants). A holder's local (coordination free) withdrawal rights. Grant part of the ungranted pool to a holder as local withdrawal rights. Returns the amount actually granted (may be less than requested). Withdraw from a holder's LOCAL grant — no coordination required while the holder has rights. Preserves the lower bound invariant because the sum of all grants never exceeds . Return unused local rights to the shared pool (e.g. holder going offline). The lower bound invariant the escrow guarantees holds at all times. <! HUMAN NOTES Notes & Examples No hand authored notes yet. Add page notes in or a reusable block in — see API Reference Standard.


state/consistency/SerializableQueue.js
Classes
class SerializableQueue
Notes & Examples

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: state/consistency/SerializableQueue.js — Consistency plane serializable commit queue (spec §3 plane 3, §6, §8 "Serializable", rule 24). The "Exclusive"/serializable consistency profile needs commits to be applied in an order equivalent to some serial schedule. This queue admits transactions (each declaring a read set and write set), assigns a monotonic commit sequence, and detects when admitting a transaction would create a non serializable schedule against already queued/committed transactions (a read write or write write conflict on overlapping items). Conflicting transactions are not silently interleaved — the queue rejects them for retry, preserving serializability for the invariants that require it. Classes Method Signature Summary Try to admit a transaction into the serial order. Finalize an admitted transaction at its assigned sequence (serial order). Drop an admitted but aborted transaction, freeing its conflict claims. The serial schedule actually committed, in sequence order. <! HUMAN NOTES Notes & Examples No hand authored notes yet. Add page notes in or a reusable block in — see API Reference Standard.


state/entity/EntityRegistry.js
Classes
class EntityRegistry
Notes & Examples

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: state/entity/EntityRegistry.js — versioned entity state (spec §4, rule 2). A mutable logical object is represented as a chain of immutable versions. The logical entity id stays stable; each version's id is the content hash of its canonical bytes. "Editing" creates a new version pointing at its parent — the old version is never mutated. This is what optimistic concurrency reads against: a transaction's readSet declares the version it expected, and the commit fails if the entity has since advanced (write skew protection). Classes Method Signature Summary Current version id for an entity, or null if unknown. Full version record by version id, or null. True if the entity's head matches (optimistic read). Create the first version of a new entity. Returns the version record. Append a new immutable version. (if given) must equal the current head or the update is rejected (optimistic concurrency). All current head version ids, sorted (for state roots). <! HUMAN NOTES Notes & Examples No hand authored notes yet. Add page notes in or a reusable block in — see API Reference Standard.


state/entity/ProvenanceStore.js
Classes
class ProvenanceStore
Functions
makeProvenance(p = {})
isUntrusted(prov)
Constants
Notes & Examples

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: state/entity/ProvenanceStore.js — every observation, inference, prediction, and commit carries provenance (spec §14, rule 4). Vocabulary follows W3C PROV (entities, activities, agents, generation, derivation). Provenance lets the engine distinguish directly observed vs inferred vs model predicted vs stale vs untrusted data — crucial for the prompt injection boundary (spec §15): retrieved/tool/model content is recorded as untrusted observation, never as authority. Classes Method Signature Summary Attach provenance to a subject id (appends — provenance is append only). All provenance records for a subject (frozen copy). Functions Build a provenance record for a subject (a fact, version, or transaction). Parameters: (object) — No description in source JSDoc. (string) — e.g. 'tool:file reader' (string) — No description in source JSDoc. (string) — activity id (string) — agent id (number) — 0..1 confidence (string) — one of CERTAINTY (number) — No description in source JSDoc. (string[]) — No description in source JSDoc. True if a provenance record came from an untrusted external source. Constants <! HUMAN NOTES Notes & Examples No hand authored notes yet. Add page notes in or a reusable block in — see API Reference Standard.


state/entity/SchemaRegistry.js
Classes
class SchemaRegistry
Notes & Examples

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: state/entity/SchemaRegistry.js — meaning from schemas, not numeric tricks (spec rule 3). Every schema/validator/policy is versioned (spec rule 5) so migrations can reference exact stamps. A schema declares a name, a version, and a validate(value) predicate; validation is structural (legality), never a claim of semantic truth — that comes from commit logic. Classes Method Signature Summary Register a versioned schema. Look up a schema by name + version, or null. Validate a value against a registered schema. <! HUMAN NOTES Notes & Examples No hand authored notes yet. Add page notes in or a reusable block in — see API Reference Standard.


state/facts/Branch.js
Functions
applySequence(store, ops)
commutes(base, opA, opB)
branchOrders(base, opA, opB)
mergeEquivalent(stores)
prune(stores, constraints)
Notes & Examples

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: state/facts/Branch.js — split non commuting possibilities; merge equivalent; prune invalid. Core law: "If A + B = B + A, merge them. If A + B != B + A, branch them." An operation is a pure function (store) = void that adds facts / tombstones. Functions Apply a sequence of operations to a (cloned) store. Returns the store. Does applying opA then opB yield the same projection as opB then opA? Returns: } Produce both order branches [A→B, B→A] from a base store. Collapse branches with identical projections (merge equivalent). Drop branches that fail commit strength constraints (prune invalid). <! HUMAN NOTES Notes & Examples No hand authored notes yet. Add page notes in or a reusable block in — see API Reference Standard.


state/facts/Causality.js
Functions
link(cause, effect)
toposort(nodes, links = [])
dependsOn(effect, cause, links = [])
Notes & Examples

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: state/facts/Causality.js — partial order ONLY when a dependency forces it. Layer law: "Only causality creates before/after". Facts with no dependency link stay unordered; we never invent sequence. Independent nodes get a deterministic tie break (canonical sort) purely for reproducibility, not as claimed truth. Functions A causal link: effect depends on cause (cause must precede effect). Partial order sort. Nodes only ordered where links force it; otherwise deterministic by string. Throws on a causal cycle (an impossible order). Parameters: (Iterable<string ) — No description in source JSDoc. Transitive dependency test: does (transitively) depend on ? <! HUMAN NOTES Notes & Examples No hand authored notes yet. Add page notes in or a reusable block in — see API Reference Standard.


validateFacts(liveFacts, constraints, { phase = SCOPERUNTIME } = {})

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: state/facts/Constraints.js — the laws of the system. Layer law: runtime uses simple validators; commit uses stronger validators (a superset). A constraint never repairs — it accepts or rejects. When a commit constraint fails, the caller branches / quarantines / requests authority (see CommitGate, M5) rather than silently fixing. Functions Define a constraint. Parameters: (string) — No description in source JSDoc. ((liveFacts:Set<string )= boolean) — true = legal (object) — { scope:'runtime' 'commit', message } Validate live facts. phase 'runtime' runs only runtime constraints; phase 'commit' runs ALL (runtime + commit) — commit is strictly stronger. Returns: }} No more than one live fact matching a regex (single source of truth). Two facts must never be live at once (mutual exclusion). Constants <! HUMAN NOTES Notes & Examples No hand authored notes yet. Add page notes in or a reusable block in — see API Reference Standard.


state/facts/Fact.js
Functions
fact(predicate, ...args)
revoke(f)
isTombstone(f)
tombstoneTarget(f)
Notes & Examples

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: state/facts/Fact.js — canonical facts + tombstones. Layer law: facts are MONOTONIC. We prefer adding facts, never deleting them. "Deletion" is a tombstone fact ; projection later decides what is currently valid. A fact is just a canonical string predicate so that {A,B} and {B,A} hash identically (see util/hashing.canonicalSetHash). Functions Build a canonical fact string: fact('hasKey','player','red') → "hasKey(player,red)". Wrap a fact as a tombstone (the monotonic stand in for deletion). Is this fact a tombstone? The fact a tombstone revokes, or null. <! HUMAN NOTES Notes & Examples No hand authored notes yet. Add page notes in or a reusable block in — see API Reference Standard.


state/facts/FactStore.js
Classes
class FactStore
Notes & Examples

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: state/facts/FactStore.js — the unordered, monotonic fact set. No sequence is stored. is the order independent hash of ALL facts (history identity); is the hash of the currently valid projection (tombstones applied). Merge is a set union — naturally commutative and idempotent (a CRDT style anti entropy merge), so two peers that saw events in different orders converge to the same id. Classes Method Signature Summary Add a fact (monotonic — never removes). Returns this. Revoke a fact by adding its tombstone (never deletes). Returns this. Raw membership (includes tombstones). All raw facts including tombstones (canonical history). Currently valid facts: non tombstone facts whose tombstone is absent. State id = order independent hash of the full canonical fact set. Projection id = hash of the live (valid) facts only. Deep copy. Commutative, idempotent union merge (anti entropy). Returns this. <! HUMAN NOTES Notes & Examples No hand authored notes yet. Add page notes in or a reusable block in — see API Reference Standard.


state/index.js

state/index.js
Re-exports
Notes & Examples

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: state/index.js — public barrel for the Causal State Engine (CSE), formerly the Universal Resonance State Engine (URC). Order on demand: unordered facts encoded through a resonance codebook, organized spatially, compared by wave like similarity, repaired through correction codes, branched when order matters, committed only when reality must choose one truth, and projected by observers into experienced sequence. The CSE upgrade (see plans/causal state engine upgrade 59657d.md) layers a partially ordered, capability secured, transactionally committed world state system on top of the URC core. The codebook/resonance/spatial layers are kept as the optional indexing/perception extension (spec §16) — never in the trusted authority/correctness path. Build status: URC core: [x] M0 [x] M1 codebook [x] M2 spatial [x] M3 resonance [x] M4 facts [x] M5 commit [x] M6 observer CSE: [x] P1 formal core (USO, tx envelope, idempotency, causal, 14 step commit, receipts) [x] P2 single authority (entity/version, schema, provenance, capabilities, identity, event log, state roots, checkpoints) [x] P3 reliability (outbox, idempotent inbox, sagas+compensation, reconciler, reservations + bounded counter escrow) [x] P4 concurrency (CRDTs, invariant confluence classifier, optimistic/write skew validator, dotted version vectors, HLC) [x] P5 world model (belief vs canonical, object graph, affordances, tool effect/discrepancy, prediction sandbox, untrusted boundary) [x] P6 distributed (shard router, replicated log, Raft adapter, cross shard 2PC + recovery, quorum checkpoints) [x] P7 sim/resonance (independent sim clocks, deterministic world dynamics, approximate retrieve→exact verify perception index) [x] P8


state/index.js

quorum checkpoints) [x] P7 sim/resonance (independent sim clocks, deterministic world dynamics, approximate retrieve→exact verify perception index) [x] P8 completeness (proposal pool, serializable queue, policy engine+risk gates, encryption/retention crypto erase, GC, causal dynamics, TLA+ core stub) [x] P9 hardening (WebCrypto AES GCM retention, Byzantine adapter, executable bounded model checker + TLC config) CSE COMPLETE: all 12 planes implemented + verified in verify.html. Re exports , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , <! HUMAN NOTES Notes & Examples No hand authored notes yet. Add page notes in or a reusable block in — see API Reference Standard.