createMaterialVariant(base, overrides = {})

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: engine/assets/material/MaterialVariant.js — variants + shader model fallback (spec §7). Imported materials won't always match the engine shader model, so we normalize into EngineMaterial, can generate a metallic roughness fallback approximation when needed, and always keep the original recoverable. Variants (e.g. a re tinted body panel) share the source material and only narrow/adjust. Functions Create a material variant that overrides a few fields of a base material while preserving the original (recoverable) and recording the variant lineage. Approximate a non metallic roughness material as metallic roughness for the engine's PBR shader. The original is preserved so the imported look can always be restored. This is a deliberate, labelled approximation — not an exact port. Returns: a new EngineMaterial (workflow = metallicRoughness) Restore the original imported material descriptor (the raw source block). Re exports <! HUMAN NOTES Notes & Examples No hand authored notes yet. Add page notes in or a reusable block in — see API Reference Standard.


createSegmentView(model, mode = SEGMENTMODE.MATERIAL)

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: engine/assets/material/SegmentView.js — non destructive segmentation (spec §8). We need modular breaking (swap tires, detach doors, tint glass, split a magazine) WITHOUT destroying the source. A SegmentView references original primitive ids / index ranges / materials — it never copies or rewrites geometry. A physical split is only baked later, on export or when a detachable part is actually created. This keeps skeletons, UVs, and morph targets intact. Functions Create a non destructive segment view of a model. Parameters: (object) — EngineModel (string) — one of SEGMENT MODE Returns: }} Bake a single segment into a standalone EngineModel like payload (only when a detachable part is actually needed — e.g. export). Geometry is copied here, the source model is left untouched. Constants <! HUMAN NOTES Notes & Examples No hand authored notes yet. Add page notes in or a reusable block in — see API Reference Standard.


assets/material/SurfaceBinding.js
Functions
buildSurfaceBindings(model)
Notes & Examples

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: engine/assets/material/SurfaceBinding.js — bind materials to surfaces (spec §7). Material assignment happens at the primitive/submesh level, not per image. A SurfaceBinding records exactly which node/mesh/primitive a material covers, which UV set it uses, and (when known) the semantic part — so segmentation and editing can target real surfaces and bindings survive non destructive splits. Functions Build surface bindings for a model (material ↔ primitive). Populates model.surfaceBindings and returns them. <! HUMAN NOTES Notes & Examples No hand authored notes yet. Add page notes in or a reusable block in — see API Reference Standard.


assets/material/TextureImport.js
Functions
normalizeTextures(model)
async decodeTexture(tex)
async decodeAllTextures(model)
Notes & Examples

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: engine/assets/material/TextureImport.js — normalize textures + decode pixels (spec §7). A texture's colour space and usage are inferred from the material slots that bind it (sRGB for colour/emissive, linear for data/normal/ORM), so the same image used as colour vs data is handled correctly. Pixel decode is a separate, browser only step (createImageBitmap) kept out of parsing. KTX2/ Basis stay compressed here and are routed by TextureManager to the existing native upload or registered decoder/transcoder hook path. Functions Infer per texture colour space + usage from the decoded material bindings, and normalize model.textures into self describing EngineTexture records. Requires importMaterials() to have run first (so bindings exist). Returns: normalized textures Decode a normalized texture's pixels to an ImageBitmap (browser only). Returns the bitmap (also cached on the texture) or null when undecodable (no bytes, external uri, or a compressed format with no transcoder). Decode every decodable texture in a model. Returns the count decoded. <! HUMAN NOTES Notes & Examples No hand authored notes yet. Add page notes in or a reusable block in — see API Reference Standard.


validateCompositeMaterialFacets(value, path = '$.facets')

validateCompositeMaterialProvenance({ facets, sources, fieldSources }, path = '$')

validateEngineCompositeMaterialResource(value, path = '$')

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: Strict, app neutral contracts for immutable composite material data. Functions Validate a complete built in catalog resource. Returns the input unchanged. Constants <! HUMAN NOTES Notes & Examples No hand authored notes yet. Add page notes in or a reusable block in — see API Reference Standard.


async loadEngineCompositeMaterialCatalog({ fetchImpl = globalThis.fetch, urls = ENGINECOMPOSITEMATERIALRESOURCEURLS, } = {})

<! 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 Browser native JSON loader. Callers may inject an equivalent fetch boundary. Constants <! HUMAN NOTES Notes & Examples No hand authored notes yet. Add page notes in or a reusable block in — see API Reference Standard.


assets/material/composite/index.js
Exports
Notes & Examples

<! 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 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: engine/assets/render/ModelGpu.js — reusable GPU side helpers to turn an uploaded EngineModel into drawable items. Small, composable, and shared by the importer/viewer, the editor, and the runtime so nobody re implements texture upload, per primitive bind groups, world matrix flattening, or bounds framing. Pairs with ModelShader (uniform block) and GpuUploader (vertex layout). Pure data in → GPU objects out; callers own the render pass and camera. Functions A linear, repeating sampler — a sane default for model albedo. A 1×1 white texture so untextured primitives sample white (albedo = color). Upload one decoded bitmap to a GPU texture (sRGB for colour, linear for data). Decode + upload every embedded texture in a model. Returns: } Deterministic fallback colour for a primitive lacking a baseColorFactor. Build drawable items for an uploaded model: one per primitive, each with its world draw matrix, uniform buffer, bind group, fallback colour, and (optional) wheel spin descriptor keyed by node id. Returns: } CPU skin every skinned mesh to its DEFAULT pose so the static viewer draws the mesh wrapped around the node hierarchy skeleton (per the glTF rule that a skinned mesh's own node transform is ignored). For each skinned vertex: v' = Σ wⱼ · (jointNodeWorld(j) · inverseBindMatrix(j)) · v (scene space) Positions/normals are replaced in place (original kept on ) and the primitive is flagged . No op without skins/IBMs. GPU free. Returns: primitives baked Free per item uniform buffers built by buildModelDrawables. World space bounds of a set of drawables, for camera framing. Returns: null} Compose the standard import correction matrix from a model's importTransform. Re exports <! HUMAN


of a set of drawables, for camera framing. Returns: null} Compose the standard import correction matrix from a model's importTransform. Re exports <! HUMAN NOTES Notes & Examples No hand authored notes yet. Add page notes in or a reusable block in — see API Reference Standard.


assets/render/ModelRenderer.js
Functions
createModelRenderer(device, opts = {})
Notes & Examples

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: engine/assets/render/ModelRenderer.js — the batteries included way to draw an EngineModel. It composes the small render modules (ModelShader + ModelGpu) and the vehicle wheel spin helper, applying sensible DEFAULTS so any engine system can go from "I have an EngineModel" to "it's on screen" in two calls: const r = createModelRenderer(device, { format }); await r.setModel(model, { wheelSpin: true, rig }); // upload + drawables per frame: r.render(pass, { mvp, eye, distance }); The caller still owns the render pass + camera (so it slots into any pipeline); the renderer owns the model's GPU lifetime and offers a depth texture + camera framing convenience. Override the shader/format/cull via opts when needed. Functions <! HUMAN NOTES Notes & Examples No hand authored notes yet. Add page notes in or a reusable block in — see API Reference Standard.


assets/render/ModelShader.js
Functions
createModelPipeline(device, opts = {})
Constants
Notes & Examples

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: engine/assets/render/ModelShader.js — the default lit WGSL shader + pipeline for drawing an EngineModel's standard layout primitives. Small and overridable: any engine system can grab LIT MODEL SHADER for a sensible default, or pass its own WGSL to createModelPipeline. The shader pairs with standardVertexLayout() (pos3 + nrm3 + uv2) and the 160 byte uniform block written by ModelGpu. Functions Build the render pipeline for EngineModel primitives. Parameters: (GPUDevice) — No description in source JSDoc. (object) — { format, depthFormat?, wgsl?, label?, cullMode? } Returns: } Constants — A neutral physically plausible lit shader with albedo floor + additive rim. — Gallery raster lighting derived from the Astral Sculpture Court studies: warm broad key, restrained green cyan fill, cool portal rim, park/studio environment response, Khronos PBR Neutral, and stable one LSB dithering. It deliberately preserves the default renderer bind/uniform contract. — Full screen gallery/park environment paired with the sculpture shader. <! HUMAN NOTES Notes & Examples No hand authored notes yet. Add page notes in or a reusable block in — see API Reference Standard.


characterPhysicsAssetToBodyTemplate(asset, opts = {})

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: engine/assets/rig/BodyTemplateExport.js — turn a generated into a starting point shaped body template JSON (the schema + consume). This mirrors how every mainstream engine handles the generated vs hand authored split (Unreal's Physics Asset auto generate, Unity's Ragdoll Wizard, Godot's "Create Physical Skeleton"): the generator produces a complete, valid STARTING POINT for skeleton/joint/collision structure — never silently re applied over hand tuned data afterward. A dev generates this once for a new creature/character variant, saves it as a plain JSON file, and hand tunes gameplay only concerns on top (anatomy/organs, ligaments, muscle model, strength/mass presets) that have no generator and are intentionally hand authored. This is the "easy for devs to achieve anything" on ramp: zero authoring skeleton for a new body, full hand tuning power afterward. Functions Convert a (from ) into a body template — a ready to save JSON starting point for a new creature/character variant. Only the skeleton/joint/collision structure is generated; / / / are left as explicit, clearly commented empty stubs since no generator authors those — every mainstream engine's ragdoll generator stops at the same boundary. Parameters: (object) — CharacterPhysicsAsset (createCharacterPhysicsAsset output) (object) — No description in source JSDoc. (string) — template id (default: derived from asset.source) (string) — display name (string) — No description in source JSDoc. Returns: life.body.v1 shaped body template <! HUMAN NOTES Notes & Examples No hand authored notes yet. Add page notes in or a reusable block in — see API Reference Standard.


createCharacterPhysicsAsset(model, opts = {})

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: engine/assets/rig/CharacterPhysicsAsset.js — the single generated packaging layer for a character's physics structure. This is NOT a new generator: it wraps (RagdollBuilder.js) + (JointLimits.js) and repackages their output into one serializable schema that every consumer (ActiveRigController/PhysX, RagdollSim, RagdollSkinning, Life's BodyAssembler, RealmForge's compilers, legacy PBDRagdoll wrapper) can read instead of inventing its own bone/joint shape. GPU free + deterministic. Schema fields: skeletonFingerprint, boneMap, bodyDefs, jointDefs, jointLimits, massProfile, collisionFilters, driveProfiles, skinningOffsets, particleCageDef (reserved for the future flesh cage system), validationReport. Functions Stable fingerprint for a bone topology — same skeleton shape (names + parent links, order independent per bone but position stable) hashes the same way twice. Used to detect when a cached CharacterPhysicsAsset can be reused vs. must be rebuilt. Parameters: (object[]) — No description in source JSDoc. Build a for a model. Humanoid path when a humanoid rig is present, otherwise generic topology — identical branch selection to , which this function delegates to. Parameters: (object) — EngineModel (object) — Passed through to / (density, massKg, heal, forceGeneric, …) Returns: CharacterPhysicsAsset Validate a CharacterPhysicsAsset's internal consistency (indices resolve, joint types known, mass/limit values finite). Follows the same pattern as Life's , adapted to this schema's shape. Parameters: (object) — No description in source JSDoc. Returns: } Constants Re exports <! HUMAN NOTES Notes & Examples No hand authored notes yet. Add page notes in or a reusable block in — see API


in source JSDoc. Returns: } Constants Re exports <! 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: engine/assets/rig/JointLimits.js — automatically derive per joint movement limits (range of motion) from a model, the way Life's BodyAssembler does it: every joint gets a TYPE (ball / hinge / saddle / twist / root) plus a swing cone + twist limit (degrees → radians), and hinge joints get a bend AXIS taken from the bind pose geometry (perpendicular to the parent→joint→child bend plane). Two paths: • humanoid — role based anatomical profile keyed by canonical bone slots. • generic — topology inference (children count + segment straightness) so spiders, dogs, cats, birds, etc. get sensible limits with no template: hub/limb root joints → ball, straight mid limb segments → hinge, leaves → fixed. GPU free + deterministic → gate testable. Functions Hinge bend axis = normal of the parent→joint→child plane (the axis a knee/elbow actually bends about). Falls back to a perpendicular of the bone direction. Joint type carried by an anatomical profile (ball/hinge/saddle/twist/root). Swing cone half angle (degrees) carried by a profile. Hinge bend range (degrees). By Life's hinge convention this value is carried in the profile's field (a hinge drives one axis), so this is semantically distinct from even though both read the same underlying number for a hinge profile. Twist limit (degrees) for a non hinge (ball/saddle/twist) profile. Verify (and defensively enforce) left/right symmetry between two derived limits — swing/twist degrees must match (anatomy is bilaterally symmetric); axes are expected to differ (mirrored bind pose geometry) and are left untouched. Explicit, testable version of the symmetry already guarantees implicitly by stripping the left/right prefix before profile lookup.


and are left untouched. Explicit, testable version of the symmetry already guarantees implicitly by stripping the left/right prefix before profile lookup. Parameters: (object) — No description in source JSDoc. (object) — No description in source JSDoc. Returns: } Infer a coarse drive role (neck/shoulder/elbow/wrist/spineUpper/pelvis/hip/ knee/ankle/toe/default) from a bone/slot name via string matching. Shared so RagdollBuilder, CharacterPhysicsAsset, and future adapters don't each reimplement this heuristic independently. Parameters: (string) — No description in source JSDoc. Derive joint limits for a humanoid rig. Parameters: (object) — EngineModel (with model.rigs.humanoid) (Map) — bind pose map (built if omitted) Returns: canonical slot → limit Derive joint limits for ANY skeleton by topology + geometry (spiders, dogs, cats, birds…). No names required. Returns: nodeId → limit The set of valid joint type strings ( / / / / / ) as a , for membership checks — single source of truth so a validator never hand declares its own copy that can silently drift from (this is exactly how and Life's used to each keep their own disconnected copy). Shared bone topology structural validation — the literally duplicated core every ragdoll/body validator needs (bone id uniqueness, parent reference resolution), extracted once so and Life's can never silently drift apart on these checks again. Each caller still owns its own shape specific checks (mass/position for CharacterPhysicsAsset; anatomy/ligaments/skeleton extensions for Life). Returns: } Count joint types in a limit map (for inspectors/gates). Auto derive and attach joint limits to a model. Humanoid path when a humanoid rig is present, otherwise generic topology inference. Returns: } Constants — Alias for — the joint bend


joint limits to a model. Humanoid path when a humanoid rig is present, otherwise generic topology inference. Returns: } Constants — Alias for — the joint bend direction deriver, named for the generic "derive " family used by RagdollBuilder/CharacterPhysicsAsset. <! HUMAN NOTES Notes & Examples No hand authored notes yet. Add page notes in or a reusable block in — see API Reference Standard.


buildHumanoidRagdoll(model, rig, pose, opts = {})

buildGenericRagdoll(model, pose, opts = {})

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: engine/assets/rig/RagdollBuilder.js — turn a detected skeleton + auto derived joint limits into a RAGDOLL descriptor: one capsule body per bone (sized from the bone length, mass from its volume) plus a constrained joint to its parent using the JointLimits type + swing/twist + bend axis. Pure data (no physics engine here) so it can drive / articulations or the editor's ragdoll. Works for humanoids (canonical bones, incl. healed ones) and for any creature via generic topology. GPU free + deterministic. Functions Build a ragdoll from a humanoid rig (canonical bones, including healed ones). Build a ragdoll from any skeleton by generic topology (spiders, dogs, …). Build a ragdoll for a model and attach it at model.rigs.ragdoll. Humanoid path when a humanoid rig is present, otherwise generic topology. Returns: } <! HUMAN NOTES Notes & Examples No hand authored notes yet. Add page notes in or a reusable block in — see API Reference Standard.


assets/rig/RagdollSim.js
Functions
createRagdollSim(ragdoll, opts = {})
Notes & Examples

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: engine/assets/rig/RagdollSim.js — a tiny, GENERIC Verlet/PBD ragdoll runtime that simulates ANY ragdoll descriptor from RagdollBuilder (humanoid, creature, healed/mirrored limbs). Each bone joint is a particle; each bone is a distance constraint to its parent (Jakobsen "Advanced Character Physics"). Gravity + ground + a few constraint iterations give a stable, believable flop with no dependency on a fixed humanoid template. Pure JS / deterministic / GPU free. Functions Parameters: (object) — RagdollBuilder output ({ bones:[{position,parentIndex}] }) (object) — { gravity:[x,y,z], ground:number null, damping, iterations, pinned:number[] } <! HUMAN NOTES Notes & Examples No hand authored notes yet. Add page notes in or a reusable block in — see API Reference Standard.


skinPrimitiveInterleaved(prim, frames, jointCount, outInterleaved)

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: engine/assets/rig/RagdollSkinning.js — make the live MESH follow a ragdoll. The ragdoll sim (RagdollSim) only moves joint POSITIONS. To deform the skinned mesh with it we need a per joint world transform. We build a ragdoll over the model's actual SKIN JOINTS (1:1 with the skin's joint slots, so vertex skin weights index straight into it) and, each frame, derive a per bone rotation from the rest→current bone direction. Skinning is then the standard linear blend in SCENE space (the renderer applies importMatrix afterwards): v' = Σ wⱼ · ( Rⱼ · (v − bindPosⱼ) + curPosⱼ ) At the bind pose Rⱼ=I and curPos=bindPos, so v'=v (the baked mesh). This needs no inverse bind matrices because jointBindWorld·IBM = I per joint. Pure JS. Functions Build a ragdoll over a model's skin joints (1:1 with skin slot indices) and a sim for it. Joint limits come from the humanoid rig where mapped, else generic topology. Returns null when the model has no skin to drive. Parameters: (object) — EngineModel (must be baked: bakeSkinnedMeshes already ran) (object) — { gravityMag, importMatrix, damping, iterations, pinned } Returns: null} Per bone frames for the current sim state: rotation (3×3 row major), current position, and bind position. Bones with no child inherit their parent's rotation (so leaf verts swing with the limb). Returns: } Linear blend skin a primitive into a standard interleaved [pos3,nrm3,uv2] buffer (UVs at o+6/o+7 are left untouched). Writes scene space positions so the renderer's importMatrix lands them correctly. Mutates + returns . Parameters: (object) — primitive with bindPosition + attributes.{normal,joints,weights} (object) — ragdollBoneFrames() output (number) — number of ragdoll


. Parameters: (object) — primitive with bindPosition + attributes.{normal,joints,weights} (object) — ragdollBoneFrames() output (number) — number of ragdoll bones (skip weights beyond it) (Float32Array) — stride 8 buffer (pre seeded with baked UVs) One time STATIC report of a built ragdoll: every joint's type + auto detected limits, and the full constraint breakdown (bone sticks, hub bracing, ROM, signed hinges, swing cones). Prints rich console.tables when available; always returns a one line summary string (also handed to for the in app console). LIVE per frame measurement: each hinge's current bend, each cone's current swing, and each ROM constraint's grandparent distance — all vs their limits, with an flag. Use it to PROVE the limits hold during simulation (and to spot violations). 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: No file level description found in source. Add one as a leading JSDoc comment, or document it below. Functions <! HUMAN NOTES Notes & Examples No hand authored notes yet. Add page notes in or a reusable block in — see API Reference Standard.


getActiveBodyPerformanceBudgetReport(bodyCount = 0, measurements = {})

<! 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 No hand authored notes yet. Add page notes in or a reusable block in — see API Reference Standard.


buildActiveBodyPayload(config, worldPosition = [0, 0, 0])

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: HumanoidRigBuilder — Builds a physics ready humanoid rig (skeleton, bodies, joints, mass profile, drive profile) from entity phenotype data. Produces a StickmanRagdoll compatible component that ActiveBodySystem can spawn as a PhysX articulation via the engine's ActiveRigController. Moved from editor/people preview/PeoplePhenotypeRig.js into the game simulation layer so any game entity can have an active body. Functions Build a complete humanoid rig from entity data. Parameters: (object) — No description in source JSDoc. (string) — Entity ID (string) — Entity display name (object) — Body scales (heightScale, widthScale, etc.) (string) — 'poweredBody' 'kinematicFollow' 'animatedOnly' Returns: } Build a spawn ready payload for ActiveBodySystem. <! HUMAN NOTES Notes & Examples No hand authored notes yet. Add page notes in or a reusable block in — see API Reference Standard.


buildActiveBodySimulationTierReport(bodies = [], observer = {})


<! 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 Inject PACER sensors. See constructor for shape. Pass to clear. Called once at startup from GameSetup. Build the per frame sensors packet for one body: terrain heightAt(x,z) closure + the nearest agent lookup resolved NOW. Returns null when no sensors are registered — NN obs will then default to "flat + empty". Initialize with a part catalog. Loads body template and assembles spec. Call this once at startup, before adding bodies. Returns the assembled ragdoll spec (or null if init wasn't called with a catalog). Build collision filter options for PBDRagdoll. solveCollisions(). Live body yaw (smoothly slewed in the walking controller). Use this for rendering equipment / fallback meshes / camera follow so visuals stay in sync with the ragdoll's actual orientation instead of snapping to the raw input direction. Request a facing target. The walking controller slews navState.facing toward it at 5 rad/s. Useful when the body should turn in place before moving (e.g. player pushed a direction but hasn't committed to walking). Apply a preset neuro profile to a body's brain. Ramp a neuro profile gradually (0..1). Useful for poison progression. Apply neuro effect to every body (for debug testing). Get training stats for a body's brain. Heal accumulated brain damage. Represents neuroplasticity / medical treatment. Clears brainDamage but does NOT undo weight corruption — the NN has to retrain through normal play to recover those specifically. Directly set intelligence (0 100). Triggers an immediate upgrade check. Useful for character creation, narrative events


play to recover those specifically. Directly set intelligence (0 100). Triggers an immediate upgrade check. Useful for character creation, narrative events (enlightenment, head injury, potions), or debug. Grow intelligence by a delta. Called by gameplay systems when the character learns (skill use, storylet resolution, reading, teacher interaction). Small deltas (+0.1 to +1) are typical; +10 is a major life event. Flip the magical flag — unlocks supernatural tiers (genius through divine, IQ 100–200). Use this for narrative events: divine ascension, archmage initiation, demonic pact, transcendence. Setting to false REMOVES magic — if their brain is already a magical tier it stays (downgrade not supported) but future growth caps at huge / IQ 100. Auto upgrade check: if the character's intelligence has grown past the next tier threshold AND their current brain has saturated (low loss, enough training), grow the brain via Net2Net (preserves learning). Called every 5s by the update loop. Saturation criteria: framesTrained 3000 (enough data for the current capacity) lossEMA < 0.06 (mastered the task within current capacity) Set the brain tier for an entity BEFORE its brain is first created. Save current brain to IndexedDB now. Returns size in bytes or null. Save to a named slot (e.g. player snapshots). Load a saved brain into an entity (from id or slot name). Delete a saved brain (or slot). List all saved brains across IndexedDB. Export a body's brain as a JSON string (for download/share). Download a body's brain as a .brain.json file. Import a JSON string into a body's brain. Set the body's current intent. The NN sees this in its observation vector and the reward function uses it to shape what counts as success. TRACE integration: pass + optional and the body will auto


sees this in its observation vector and the reward function uses it to shape what counts as success. TRACE integration: pass + optional and the body will auto derive from (waypoint pelvis). The NN reward function rewards both proximity to the waypoint AND matching the desired speed, so the character walks toward it at the right pace. When the body reaches the waypoint (within WAYPOINT REACH RADIUS) the caller should advance to the next waypoint — this API does NOT own the waypoint queue; the planner does. Get a body's current pelvis world position as {wx, wy, wz, vx, vz}. Returns null if the body isn't registered or the ragdoll hasn't initialized yet. Used by GameLoop to sync playerState from the physics body (s


createAnimalBrainProfile(skeleton, options = {}, entityId = 'animal')

animalVerticalScaleFor(skeleton, scale = 1)

animalLocalToWorldPosition(origin, yaw, scale, local, verticalScale = scale)

createAnimalPbdRagdoll(skeleton, worldPosition, options = {})

stepAnimalActiveBody(entry, dt, groundY = 0, sensors = null)

logAnimalActiveBodyTrace(entry, frame, groundY = 0)

formatAnimalLegDebug(entry, groundY = 0)

formatAnimalTailDebug(entry, groundY = 0)

applyAnimalPoseDrive(entry, dt, groundY, motion)

computeAnimalLegTargets(entry, root, rootLocal, groundY, motion, basis)

applyAnimalNeuralMotor(entry, legTargets, tailTargets, motion, groundY, dt)

animalBodyVerticality(entry, groundY = 0)

animalNeuralReward(entry, motion, currentV, targetV, coreV)

applyAnimalNeuralLegOffsets(entry, legTargets, offsets, weight)

addAnimalNeuralOffset(target, offsets, alias, weight, footPlanted)

computeAnimalTailTargets(entry, root, rootLocal, groundY, motion, basis, dt)

animalSupportRoot(entry, root, groundY, motion, basis)

animalSwingLateralSweep(entry, descriptor, lift, swingAhead)

animalRestWorld(root, rootLocal, local, scale, basis, verticalScale = scale)

animalLegPhase(entry, descriptor, legCount, speedScale = null)

applyAnimalLegChainTargets(entry, targets, info, descriptor, root, bodyRootLocal, footTarget, lift, swing, basis)

animalLegJointPulse(entry, descriptor, jointIndex, chainLength, lift, swing, basis)

enforceAnimalGroundContact(entry, groundY, dt = 1/60, sensors = null)

enforceAnimalPlantedFootContacts(entry, groundY, dt = 1/60, sensors = null, motion = null)

applyAnimalNoIntentSettleBrake(entry, dt = 1/60, motion = null)

applyAnimalWrongWayBrake(entry, dt = 1/60, motion = null)

computeAnimalBalance(entry, groundY = 0)

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: engine/assets/rig/active body/AnimalLocomotion.js — extracted from ActiveBodySystem.js (Ragdoll Stack Consolidation Roadmap, Phase 7). Owns the animal (quadruped/ arachnid) active body path: anatomy spec generation, PBD ragdoll assembly, per frame locomotion (gait, leg targets, tail, neural residual blending), and animal only debug tracing. Every function here takes its dependencies as explicit parameters (ragdoll/entry/skeleton/dt/...) — none of them close over ActiveBodySystem module state, so this extraction is a pure move, not a redesign. Shared helpers (contact telemetry, balance, small math/format utils) stay in ActiveBodySystem.js and are imported back here; the reverse (the handful of names ActiveBodySystem.js still calls into, e.g. stepAnimalActiveBody) are exported from here. Functions Constants <! HUMAN NOTES Notes & Examples No hand authored notes yet. Add page notes in or a reusable block in — see API Reference Standard.


assets/rig/active-body/BalanceMotor.js
Functions
computeBalance(ragdoll)
makeBalanceState(entry, balance)
toBalanceControllerState(state)
copyBalanceState(balance)
updateState(entry, balance, dt)
snapshotGetupOrientation(entry)
Constants
Notes & Examples

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: engine/assets/rig/active body/BalanceMotor.js — extracted from ActiveBodySystem.js (Ragdoll Stack Consolidation Roadmap, Phase 7). Owns humanoid COM based balance (Winter mass fractions) and the idle/locomotion/stumble/fallen/ getup/ko state machine that reads it. Kept as one module per the Phase 7 pre work findings — the state machine and balance computation are tightly entangled (updateState reads balance.error/groundedFeet every frame) and splitting them would just add a needless import hop. Functions Constants <! HUMAN NOTES Notes & Examples No hand authored notes yet. Add page notes in or a reusable block in — see API Reference Standard.


async loadBodyTemplate(url = '/data/bodies/humanoiddefault.json')

assembleBody(template, partCatalog, options = {})

shouldBonesCollide(spec, boneA, boneB, isActive)

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: BodyAssembler — Data driven ragdoll spec from body template + part catalog. Reads: data/bodies/humanoid default.json (bone hierarchy + collision rules) data/parts/construction volumes/ .json (per part collision metadata) Produces a consumable by ActiveBodySystem: { bones: [{ id, parent, partId, side, joint, collision, mass }, ...] ignorePairs: Set<"a b" // bone pair keys for self collision exclusion ignoreGroupsActive: Set<"groupA groupB" joints: { ball: {...}, hinge: {...}, ... } drives: { ball: {...}, hinge: {...}, ... } anatomy: { thorax, organs, collisionShells } skeletonExtensions: { mode, spineSegments, structuralBones } } This is the single source of truth for ragdoll structure. Edit the JSON files to change the body without touching code. Functions Load the humanoid body template (cached after first call). Build a ragdoll spec from a body template + part catalog. Parameters: (object) — From loadBodyTemplate() (object) — From loadPartCatalog() — has .parts Map (object) — { preset: 'HumanAverage' 'HumanWeak' ... } Returns: RagdollSpec Test if two bones should collide given a ragdoll spec. Parameters: (object) — From assembleBody() (string) — bone id (string) — bone id (boolean) — true if body is in active mode (vs ragdolled) Get bone IDs that are foot contacts (for ground sensing / balance). Get a bone by id. <! HUMAN NOTES Notes & Examples No hand authored notes yet. Add page notes in or a reusable block in — see API Reference Standard.


getWalkCycleWorldTargets(gaitPhase, measurements, anchor, yaw)

getWalkCycleWorldPoseTargets(gaitPhase, measurements, anchor, yaw)

getPoseBoneWorldPosition(pose, boneId, measurements, anchor, yaw)

getPoseWorldTargets(pose, measurements, anchor, yaw)

getPoseWorldPoseTargets(pose, measurements, anchor, yaw)

interpolatePoses(poseA, poseB, t, measurements, anchor, yaw)

interpolatePoseTargets(poseA, poseB, t, measurements, anchor, yaw)

applyKinematicBlend(ragdoll, targets, blendRate = 0.04, options = {})

applyMotorToTargets(ragdoll, targets, options = {})

getPoseAtVerticality(v, measurements, anchor, yaw)

getPoseTargetsAtVerticality(v, measurements, anchor, yaw)

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: BodyPoses — Data driven pose library + biomechanical motor controller. ══════════════════════════════════════════════════════════════════════ POSE DATA ══════════════════════════════════════════════════════════════════════ Poses live in /data/poses/ .json. Each has: id, referenceHeight, rootBone, facing, bones{name:[x,y,z]}, rotations{name:[x,y,z,w]} verticality (0..100) — used by the blend space Sequences live in /data/sequences/ .json and chain poses, though the NEW verticality system (see getPoseAtVerticality) supersedes discrete sequence time for getup — bodies blend continuously between adjacent rungs of the verticality ladder: 0 ── 15 ── 25 ── 35 ── 45 ── 50 ── ( 50 reserved) prone pushup quad kneel half stand tiptoe/jump/reach kneel The ladder is based on the clinical Postural Verticality Scale (PVS) used in stroke rehab, cross referenced with the Gross Motor Function Measure (GMFM) and standard 1D animation blend trees. ══════════════════════════════════════════════════════════════════════ MOTOR: applyKinematicBlend — FOUR STACKED LAYERS ══════════════════════════════════════════════════════════════════════ For each bone we apply, in order: 1. SOFT POSITION NUDGE (kinematic lerp, small % per frame) Guarantees pose convergence even when forces can't. 2. VELOCITY CLAMPED PURSUIT (capped at muscleSpeed m/s) Close to target = slower approach (ease in). Far = full speed. 3. MASS SCALED PD FORCE (the one that actually does work) Kp = m · ω² Kd = 2 · m · ω · ζ (ζ = dampingRatio) F = Kp·(target pos) Kd·velocity Mass scaled means a 20 kg pelvis and a 0.5 kg hand have the SAME natural frequency. Like real biological muscle — body parts reach their targets on the same time scale


means a 20 kg pelvis and a 0.5 kg hand have the SAME natural frequency. Like real biological muscle — body parts reach their targets on the same time scale regardless of weight. 4. MUSCLE TONE GRAVITY COMPENSATION (postural) Bones above knee height get 75% of their weight canceled so posture holds without the motor doing all the lifting. Real humans use passive muscle tone; we model the same. + FORCE RISE TIME FILTER (on the final force) Real muscles can't change force instantly. Rate of force development (RFD) is 800 1500 N/s for untrained adults. Per bone multipliers: thighs 0.7× (slow recruitment, biggest muscles), hands 1.4× (fast, small motor units). From EMG studies. + ERROR GATED DAMPING (near target) Within 5 cm of target, velocity is damped 30% per frame. Kills steady state jitter where the PD motor fights imperceptible position deltas. Doesn't affect in flight motion. ══════════════════════════════════════════════════════════════════════ BIOMECHANICAL CALIBRATION (do not "fix" these without reading!) ══════════════════════════════════════════════════════════════════════ forcePerKg = 15 × g — untrained adult (not Olympic athlete) peak quad ≈ 15g × 8kg = 1176 N (realistic) maxForce = 1500 N — absolute cap (big muscle groups) forceRiseRate = 1200 N/s — typical RFD. Bumping this to 3000 makes bodies feel robotic (athlete level). omega = 6 9 rad/s — muscle response frequency (postural 5 7, voluntary 8 12). Above 12 = twitchy. dampingRatio = 0.7 — slight overshoot (natural muscle feel). 1.0 = critical, 1.2+ = sluggish/locked. gravityTone = 0.75 — 75% of bone weight canceled via feedforward for bones above toneYThreshold. Human postural muscles do this automatically. ══════════════════════════════════════════════════════════════════════ Functions Load a single pose


Human postural muscles do this automatically. ══════════════════════════════════════════════════════════════════════ Functions Load a single pose by id. Cached after first fetch. URL matches the BodyAssembler pattern ( ) since the server roots as . Load a sequence and pre load all poses referenced by its phases. Map gait phase (rad) to two adjacent walk cycle poses and blend factor. Linear blend of bone world positions (stand + walk cycle additive layer). Compute the world space target position of a single bone for a given pose. Applies scale (measurements.height / pose.referenceHeight), yaw rotation around +Y (body facing direction), and translation to anchor. Parameters: (object) — pose JSON (st


shatterRhythm(state, severity = 0.5, rng = Math.random)

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: BodyRhythms — Coupled phase oscillators that generate body rhythms. ══════════════════════════════════════════════════════════════════════ WHAT THIS IS ══════════════════════════════════════════════════════════════════════ Every living body has SYNCHRONIZED internal oscillators: HEART 1.0 1.5 Hz resting (60 90 bpm) BREATH 0.2 0.3 Hz resting (12 18 breaths/min) GAIT L 1.0 Hz walking cadence (left leg) GAIT R 1.0 Hz antiphase to left (π offset) ARM L counter swings with RIGHT leg (inphase with GAIT R) ARM R counter swings with LEFT leg (inphase with GAIT L) These are the output of CENTRAL PATTERN GENERATORS (CPGs) — spinal neural circuits that don't need brain input to produce rhythm. They sync via Kuramoto like coupling so all the oscillators lock into phase locked relationships automatically. Engine provides the math (engine/core/math/MathOscillator.js): stepKuramotoPhases — Euler step for coupled oscillator network phaseCoherence — measure of synchrony (0=chaos, 1=lockstep) stepKuramotoDriven — with external forcing (metronome, music, etc) ══════════════════════════════════════════════════════════════════════ USES IN THE ACTIVE BODY SYSTEM ══════════════════════════════════════════════════════════════════════ 1. NN OBSERVATION INPUT The NN sees sin/cos of key phases, so it knows WHERE in the gait cycle the body is. This lets it learn rhythmic actions — step forward on left foot during gait L peak, etc. 2. POSE MODULATION (future) When intent = walk, leg targets can be modulated by gait phase to produce a stepping motion automatically. 3. VISIBLE RHYTHM (future) Chest rises with breath, head bobs with heart, body sways with gait — alive looking NPCs even when standing still. 4.


automatically. 3. VISIBLE RHYTHM (future) Chest rises with breath, head bobs with heart, body sways with gait — alive looking NPCs even when standing still. 4. DRUG/DISEASE EFFECTS Arrhythmia = desynchronized heart. Panic = tachycardia (faster heart + breath). Paralysis = no gait coupling. Loss of coherence (order parameter drops) indicates systemic failure. ══════════════════════════════════════════════════════════════════════ COUPLING MATRIX (who synchronizes with whom, how strongly) ══════════════════════════════════════════════════════════════════════ HEART BREATH GAIT L GAIT R ARM L ARM R HEART 0.3 0 0 0 0 BREATH 0.3 0.1 0.1 0 0 GAIT L 0 0.1 1.0 0 1.0 (antiphase L↔R, counter with arms) GAIT R 0 0.1 1.0 1.0 0 ARM L 0 0 0 1.0 1.0 ARM R 0 0 1.0 0 1.0 Positive weight = inphase pull (synchronize), negative = antiphase. Kuramoto coupling term: sin(phase j phase i) × weight. Functions Create a new rhythm state for a body. Initial phases are seeded from a per entity RNG so different bodies aren't in lockstep (a crowd of NPCs should look like independent individuals, not a marching band). Advance the rhythm state by dt seconds using the Kuramoto model. Modulates natural frequencies based on body state: walking intent → gait and arms non zero high adrenaline → faster heart and breath high fatigue → slightly elevated heart, faster breath Return sin/cos of a rhythm phase — what the NN sees. sin/cos pair is the standard representation of a circular variable for neural networks (avoids wraparound discontinuity at 2π). Desynchronize rhythms (simulate arrhythmia / panic breakdown). Adds random noise to phases and reduces coupling strength. Re establish healthy coupling after disruption (recovery). Constants Re exports , <! HUMAN NOTES Notes & Examples No hand authored notes yet.


strength. Re establish healthy coupling after disruption (recovery). Constants Re exports , <! HUMAN NOTES Notes & Examples No hand authored notes yet. Add page notes in or a reusable block in — see API Reference Standard.


createHumanoidBrainProfile(entityId, options = {})

estimateNeuralMotorTrust(motor, options = {})

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: engine/assets/rig/active body/BrainProfile.js — extracted from ActiveBodySystem.js (Ragdoll Stack Consolidation Roadmap, Phase 7). Owns humanoid brain profile creation/loading (NN tier, motor profile key resolution, lazy brain file load) and the trust/anatomy/brain readback helpers consumed by getReadback(). Functions <! HUMAN NOTES Notes & Examples No hand authored notes yet. Add page notes in or a reusable block in — see API Reference Standard.


enforceGroundContact(ragdoll, groundY, dt = 1/60, sensors = null)

buildContactTelemetry(entry, groundY = 0, sensors = null)

buildAnimalContactTelemetry(entry, groundY = 0, sensors = null)

buildBoneContactRecord(entry, spec, p, groundY, sensors)

buildSensorAnchorTelemetry(entry, groundY = 0, sensors = null)

buildSensorAnchorRecord(entry, anchor, groundY, sensors)

approximateSensorAnchorPoint(entry, anchor, driver, reference = null)

makeSensorAnchorBasis(entry, anchor, driver, reference = null)

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: engine/assets/rig/active body/ContactTelemetry.js — extracted from ActiveBodySystem.js (Ragdoll Stack Consolidation Roadmap, Phase 7). Owns ground contact resolution (Coulomb friction), per bone/per foot/per sensor anchor contact telemetry (humanoid AND animal — buildContactTelemetry dispatches to buildAnimalContactTelemetry internally so both paths share one entry point), and the contact related debug overlay builders. Every function here takes its dependencies as explicit parameters, matching the same extraction pattern as AnimalLocomotion.js. Functions Constants <! HUMAN NOTES Notes & Examples No hand authored notes yet. Add page notes in or a reusable block in — see API Reference Standard.


makeOverlayToggleMap(source = null, fallback = DEFAULTACTIVEBODYOVERLAYTOGGLES)

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: engine/assets/rig/active body/DebugOverlay.js — extracted from ActiveBodySystem.js (Ragdoll Stack Consolidation Roadmap, Phase 7). Owns pure display/readback helpers: overlay toggle resolution and the make Overlay builders consumed by ActiveBodySystem.getDebugOverlay()/getReadback(). Deliberately excludes buildMotorAuthorityMap — despite being overlay adjacent, it's also consumed by live simulation (applyFootReflexTarget/applyBraceProtection Targets), so it stays with the reflex/motor authority code, not here. Functions Constants <! 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: engine/assets/rig/active body/DirectionDiagnostics.js — extracted from ActiveBodySystem.js (Ragdoll Stack Consolidation Roadmap, Phase 7). Owns per frame pelvis displacement direction tracking (updateDirectionMotion) and the direction/facing diagnostics readback consumed by getDirectionDiagnostics()/getReadback() and the orientation audit debug logging (still in ActiveBodySystem.js). Functions <! HUMAN NOTES Notes & Examples No hand authored notes yet. Add page notes in or a reusable block in — see API Reference Standard.


async loadAniMotionPrior(state, options = {})

mixAniMotionTeacher(teacher, state, entry, ragdoll, bonesByName, intent = null, 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 Constants <! HUMAN NOTES Notes & Examples No hand authored notes yet. Add page notes in or a reusable block in — see API Reference Standard.


tierFromIntelligence(score, magical = false)

createNeuralMotor(tier = DEFAULTTIER, seedSource = null)

buildObservation(ragdoll, bonesByName, currentV, targetV, intent = null, rhythms = null, sensors = null)

neuralMotorForward(motor, obs, time = 0, options = null)

getNeuralInferenceBackendReport(bodyCount = 0, gpu = null)

computeReward(ragdoll, bonesByName, poseTargets, intent)

trainNeuralMotor(motor, obs, teacherOffsets, reward = null, opts = {})

computeTeacherSignal(kinematicTargets, ragdoll, bonesByName, rate = 0.15)

deserializeMotor(motor, data, options = {})

analyzeMotorStorage(motor, packedBytes = null)

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: NeuralMotor — per entity self training MLP for active ragdoll control. ══════════════════════════════════════════════════════════════════════ WHAT THIS IS (read first) ══════════════════════════════════════════════════════════════════════ The NN adds position RESIDUAL offsets (±8cm per bone) on top of the kinematic verticality pose targets. It is NOT a force generator. The force that actually lifts the body comes from the PD motor in BodyPoses.js, which uses the (NN refined) targets. This is called "residual policy learning" — same approach used by DReCon (Ubisoft, 2020) and DeepMimic. The NN learns the RESIDUAL between hand authored poses and what the body actually needs. targets kinematic (from verticality blend) + NN residual (from this file, trained online) = targets final → PD motor tracks targets final with realistic muscle force ══════════════════════════════════════════════════════════════════════ TRAINING ALGORITHM: AWR (Advantage Weighted Regression) ══════════════════════════════════════════════════════════════════════ Every frame: 1. Compute REWARD from body state (pose match, upright, stable, goal progress — see computeReward). 2. Maintain an EMA baseline of reward. 3. Advantage = reward baseline. 4. Gradient weight = clamp(exp(β·advantage), 0.25, 3). 5. Teacher = what the kinematic controller would nudge this frame. 6. Loss = awrWeight × MSE(NN output, teacher). 7. One SGD step per frame. Effect: NN imitates the teacher MORE in above average states and LESS in below average. This turns behavior cloning into a proper RL method. We don't need full PPO with rollout buffers — training is online and stable because the teacher is always available. STABILITY GATE: training


proper RL method. We don't need full PPO with rollout buffers — training is online and stable because the teacher is always available. STABILITY GATE: training is skipped when the body is thrashing (core velocity 24 m/s or head below pelvis). Chaotic frames produce noise teacher signals that would corrupt the NN. ══════════════════════════════════════════════════════════════════════ BRAIN TIERS ══════════════════════════════════════════════════════════════════════ tiny (default NPCs): 43→64→64→60 ≈ 41 KB small (named NPCs): 43→128→128→60 ≈ 130 KB medium (player default):43→256→256→256→60 ≈ 1.2 MB large (player upgrade):43→512→1024→1024→60 ≈ 6.6 MB huge (endgame cap): 43→768→1024³→60 ≈ 10 MB (Input dim 43 = 36 body state + 4 intent one hot + 3 goal vector.) 10 MB hard cap per brain (enforced at serialize time). Upgrades via Net2Net weight transplant (upgradeBrain) — preserves learned behavior, new neurons start near zero and learn later. ══════════════════════════════════════════════════════════════════════ DETERMINISM ══════════════════════════════════════════════════════════════════════ Per entity seeded PRNG (engine's mulberry32 + FNV 1a string hash of entity id). Same id always produces the same initial brain. Different ids (player, npc parent, thief jin) diverge immediately into unique "personalities". Drug/seizure/tremor effects also use the per entity RNG, so effects are reproducible per body. ══════════════════════════════════════════════════════════════════════ NEUROMODIFIERS (drugs, disease, damage) ══════════════════════════════════════════════════════════════════════ The forward pass accepts five perturbations applied to hidden layer activations, grounded in real pharmacology: noise — Gaussian σ (alcohol → loss of coordination) dropout — random activation


applied to hidden layer activations, grounded in real pharmacology: noise — Gaussian σ (alcohol → loss of coordination) dropout — random activation kill (seizure / KO) scale — output multiplier (paralytic=0, stimulant=1.4) tremor — coherent sinusoidal (Parkinsonian 4 6 Hz) delay — observation buffer lag (concussion) seizureAmp — random spikes in activations See NeuroModifiers.js for preset profiles. ══════════════════════════════════════════════════════════════════════ No external ML library — pure JS, uses engine/core/math/MathRandom.js for shared PRNG utilities. Runs on CPU at 60 Hz for 20 bodies on a laptop. Training cost 0.3ms per body per frame (tiny tier). Functions Map an intelligence score to


computeNeuralRotationResidualHints(rotationTargets, poseState, neuralOffsets = null, weight = 1)

neuralOffsetToAxisAngle(neuralOffsets, boneId, weight = 1)

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: engine/assets/rig/active body/NeuralResidualController.js — extracted from ActiveBodySystem.js (Ragdoll Stack Consolidation Roadmap, Phase 7). Owns the humanoid rotation residual cluster: converting NN bone offsets into axis angle residuals blended on top of kinematic rotation targets, and zeroing out idle state NN drift on the horizontal (and, for a fixed set of upper body bones, vertical) axes so a "resting" NN doesn't slowly walk the pose off target. Pure functions — callers (the pose target pipeline, still in ActiveBodySystem.js) own all the surrounding per frame state. Functions Constants <! HUMAN NOTES Notes & Examples No hand authored notes yet. Add page notes in or a reusable block in — see API Reference Standard.


applyNeuroJerks(ragdoll, motor, time, dt)

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: NeuroModifiers — preset effect profiles that corrupt the NeuralMotor's forward pass to produce realistic neurological symptoms. Each profile mutates the bag on a NeuralMotor instance. Multiple effects stack by summing noise/dropout and multiplying scale. Grounded in real pharmacology/neurology: alcohol: inhibits GABA → activation noise + slow reaction (delay) paralytic: blocks ACh at NMJ → output scale → 0 (limp) stimulant: excess catecholamines → amplified output, jitter tranq: dopamine block → output scale 0.4, delay 3 poison: neural death → growing dropout + decreasing scale seizure: hypersynchronous discharge → huge activation spikes tremor: basal ganglia dysfn (Parkinson) → coherent 4 6 Hz oscillation Functions Apply a preset profile to a NeuralMotor (replaces current modifiers). Blend toward a profile over time — e.g. poison progression. ∈ [0,1] is how far along the progression is. Reset all neuromodifiers to healthy. Apply neuromodifier effects DIRECTLY to the ragdoll bones, bypassing the NN. Needed because the NN only runs during state; seizures etc. should be visible in ANY state (idle, fallen, walking). This is the physical manifestation of motor cortex corruption: tremor → coherent sinusoidal force (Parkinsonian shake) seizureAmp → random large impulses (tonic clonic thrashing) noise → Gaussian jitter on force (alcohol wobble) scale → global force multiplier (paralytic = 0 → body goes limp) Scales with bone mass so effects feel right (heavy pelvis thrashes harder than hand). Called each frame in the main update loop. Constants — NeuroModifiers — preset effect profiles that corrupt the NeuralMotor's forward pass to produce realistic neurological symptoms. Each profile


loop. Constants — NeuroModifiers — preset effect profiles that corrupt the NeuralMotor's forward pass to produce realistic neurological symptoms. Each profile mutates the bag on a NeuralMotor instance. Multiple effects stack by summing noise/dropout and multiplying scale. Grounded in real pharmacology/neurology: alcohol: inhibits GABA → activation noise + slow reaction (delay) paralytic: blocks ACh at NMJ → output scale → 0 (limp) stimulant: excess catecholamines → amplified output, jitter tranq: dopamine block → output scale 0.4, delay 3 poison: neural death → growing dropout + decreasing scale seizure: hypersynchronous discharge → huge activation spikes tremor: basal ganglia dysfn (Parkinson) → coherent 4 6 Hz oscillation <! HUMAN NOTES Notes & Examples No hand authored notes yet. Add page notes in or a reusable block in — see API Reference Standard.


logLocomotionTargetTrace(entry, ragdoll, targets, meta)

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: engine/assets/rig/active body/OrientationAudit.js — extracted from ActiveBodySystem.js (Ragdoll Stack Consolidation Roadmap, Phase 7). Owns pure console.log debug tracing: per frame locomotion target deltas, the body vs particle vs facing orientation audit, and the authored pose directional consistency self check (knees/elbows/toes/belly orientation). Distinct from DebugOverlay.js's structured readback data — this is developer console tracing only, no return values consumed by callers. Functions <! HUMAN NOTES Notes & Examples No hand authored notes yet. Add page notes in or a reusable block in — see API Reference Standard.


setRagdollPose(ragdoll, anchor, m, options = {})

applyJointTorques(ragdoll, skeleton, dt, state, driveByBone = null)

computeHingeLimits(ragdoll, m, jointLimitsByBone = null)

complianceStrengthFor(jointLimitsByBone, names, fallback = 1)

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: engine/assets/rig/active body/PhysicsMotor.js — extracted from ActiveBodySystem.js (Ragdoll Stack Consolidation Roadmap, Phase 7). Owns the pure physics application layer for the humanoid Verlet/PBD ragdoll: initial walking skeleton kinematic pose construction, pelvis anchoring, per bone joint torque drive, and hinge limit computation/enforcement + compliance scaling. Separate concern from pose TARGET computation (still in ActiveBodySystem.js) — this module only turns targets/limits into forces applied to the ragdoll's particles. Functions Constants <! HUMAN NOTES Notes & Examples No hand authored notes yet. Add page notes in or a reusable block in — see API Reference Standard.


coupleShoulderGirdleTargets(entry, ragdoll, targets, yaw)

getBodySideAxis(entry, ragdoll, yaw = null, preferYaw = false)

clampTargetToSide(targets, name, base, side, minSide, isLeft, strength = 1)

alignFootToeTargets(entry, targets, yaw, leftLegIsSwing = false, rightLegIsSwing = false, isWalking = false)

clampLimbSideTargets(entry, ragdoll, targets, yaw = null)

dampRelativeVelocity(child, parent, keep, dt)

applyBalanceCorrectionToTargets(targets, balanceState, weight = 1)

applyRhythmPoseModulation(targets, rhythms, weight = 1, fatigue = 0)

applyContactReflexTargets(entry, ragdoll, targets, options = {})

reflexConfidence(contactTelemetry, mode, leftTrust, rightTrust)

applyFootReflexTarget(entry, targets, record, options)

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: engine/assets/rig/active body/PoseAuthority.js — extracted from ActiveBodySystem.js (Ragdoll Stack Consolidation Roadmap, Phase 7). This is the hardest and last Phase 7 cluster: the humanoid standing/getup pose target pipeline — applyStandingController (kinematic pose blending, walk cycle overlay, balance correction, rhythm/breathing modulation, contact reflexes, brace protection, NN residual blending, training) and applyGetupController (orientation aware rise sequencing), plus every helper they call (limb/shoulder/head stabilization, reflex classification, motor authority mapping, pose state resolution). Deliberately NOT split further — these helpers are tightly entangled with the two controller functions and with each other; see the Phase 7 pre work notes in the roadmap doc. Functions Constants <! HUMAN NOTES Notes & Examples No hand authored notes yet. Add page notes in or a reusable block in — see API Reference Standard.


normalizeUniversalLegDescriptors(descriptors, entry, allowMetadataOnly = true)

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: engine/assets/rig/active body/UniversalLegScheduler.js — extracted from ActiveBodySystem.js (Ragdoll Stack Consolidation Roadmap, Phase 7). Owns N legged support polygon analysis and gait preset recommendation for the generic/readback only "universal leg scheduler" — the leg discovery, phase, and support polygon math shared conceptually with the animal gait system, but exposed here purely as debug/readback (ActiveBodySystem's getReadback() is the only call site; it does not drive live pose targets). Functions Constants <! HUMAN NOTES Notes & Examples No hand authored notes yet. Add page notes in or a reusable block in — see API Reference Standard.


stepBioelectricSignals(state, inputs = {}, dt = 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. Functions <! HUMAN NOTES Notes & Examples No hand authored notes yet. Add page notes in or a reusable block in — see API Reference Standard.


getBreathingBodyCouplingReadback(diaphragm = null, rhythms = null)


stepCirculation(state, inputs = {}, dt = 0)


stepDiaphragm(state, rhythms = null, dt = 0)


stepNervousSystem(state, inputs = {}, dt = 0)


applyOrganDamage(state, organs, target, amount, options = {})

stepOrganDamage(state, organs, inputs = {}, dt = 0)


createOrganState(anatomy = null, attachments = null)


addPBPKDose(state, substanceId, amount, options = {})


stepSoftTissue(state, inputs = {}, dt = 0)


stepVitalSigns(state, inputs = {}, dt = 0)


assets/rig/active-body/anatomy/index.js
Exports
Notes & Examples

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: engine/assets/rig/active body/anatomy/index.js — anatomy subsystem barrel. Every other subsystem in the engine exposes a barrel ( , , ); the anatomy modules did not, which is part of why they were unreachable from any compiled bundle. This is purely additive — no module below is modified, and nothing that already imports these files by path is affected. The subsystem models a body as interacting physiological systems rather than a hit point total: per organ integrity, perfusion, oxygenation, function wounds by mechanism, bleeding, hypoxia, shock cardiac output, per limb and per organ blood flow spinal cord, 16 peripheral regions, motor authority, and per region motor/sensory/touch/pain channels heart rate, respiration, blood pressure, SpO2 breathing drive and rib/sternum coupling breathing translated into bone pose offsets mass spring tissue displacement and strain multi compartment pharmacokinetics for any substance low level signal propagation Exports No ES module exports detected in this file. <! HUMAN NOTES Notes & Examples No hand authored notes yet. Add page notes in or a reusable block in — see API Reference Standard.


assets/rig/index.js
Constants
Re-exports
Notes & Examples

<! 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. Constants — Stable public rig surface for raw modules, Engine.Rig, and bundled PE.Rig. The named groups preserve each source module's boundary while the flat functions keep the existing engine/assets API available without adapters. Re exports , , , , , , , , , , , , , , , , , , , , , , , , , , , , , <! HUMAN NOTES Notes & Examples No hand authored notes yet. Add page notes in or a reusable block in — see API Reference Standard.


assets/vehicle/ChassisDetector.js
Functions
detectChassis(model, wheelNodeIds = [])
Notes & Examples

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: engine/assets/vehicle/ChassisDetector.js — identify the chassis + body parts (spec §11). The chassis is the largest non wheel mesh; remaining meshes are categorized by name (glass/lights/doors) so segmentation and material edits (tint glass, emissive headlights, detach doors) can target them. Functions Identify chassis + body part nodes, excluding the given wheel node ids. 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: engine/assets/vehicle/VehicleMath.js — minimal column major 4x4 + quaternion helpers for vehicle rig assembly and the visual wheel transform chain. Kept local and dependency free so the vehicle layer is self contained and the math stays deterministic (and gate testable without the renderer). Functions Column major multiply: out = a b. Compose a TRS matrix (scale may be a number or [x,y,z]). Quaternion (xyzw) from an axis + angle (radians). Hamilton product a b (xyzw). Transform a point (vec3) by a column major 4x4. Local transform of a node (matrix override or TRS). World matrices for every node, accumulating the parent chain. Returns a Map(nodeId → Float32Array(16)). <! HUMAN NOTES Notes & Examples No hand authored notes yet. Add page notes in or a reusable block in — see API Reference Standard.


assets/vehicle/VehicleRigBuilder.js
Functions
buildVehicleRig(model, opts = {})
Notes & Examples

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: engine/assets/vehicle/VehicleRigBuilder.js — assemble a VehicleAsset (spec §11). Vehicles are rigged, not merely loaded. This turns detected wheels + chassis into explicit runtime data: WheelSlots (with suspension/tire/drivetrain), front axle steering, a compound collider descriptor for the chassis (built via the engine's ConvexDecomposition on demand), and a confidence. Detection failures (e.g. wheels merged into the body) flag needsCorrection rather than guessing — the editor exposes every decision (rule 62). Functions Build a vehicle rig for a model and attach it at model.rigs.vehicle. Parameters: (object) — EngineModel (object) — { drivetrain, massKg, physicsMode } Returns: the VehicleAsset <! HUMAN NOTES Notes & Examples No hand authored notes yet. Add page notes in or a reusable block in — see API Reference Standard.


assets/vehicle/WheelDetector.js
Functions
detectWheels(model, opts = {})
Notes & Examples

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: engine/assets/vehicle/WheelDetector.js — find wheels (spec §11). Detection chain (cheap → expensive), each a HINT with a confidence, never an assertion: name match → cylinder geometry → symmetry / low corner position → (editor correction). Wheels that are merged into the body mesh won't be found here and fall through to the editor (see VehicleRigBuilder.needsCorrection). Functions Detect wheel candidates in a model. Returns: } <! HUMAN NOTES Notes & Examples No hand authored notes yet. Add page notes in or a reusable block in — see API Reference Standard.


suspensionForce({ restLength, currentLength, stiffness, damping, compressionVelocity = 0 })

tireForce(slip, normalLoad, grip, slipStiffness = 12)

visualWheelMatrix(chassisWorld, slot, state = {})

advanceSpin(spinAngle, groundSpeed, radius, dt)

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: engine/assets/vehicle/WheelPhysics.js — suspension, tire slip, and the visual wheel transform chain (spec §11). Deterministic CPU model used for the inspector/demo and gates; production deployments route the same WheelSlot data into the engine's GPUVehicle. Wheel visuals FOLLOW physics state: chassisWorld · socket · suspension · steer · spin · meshCorrection. Functions Suspension spring + damper force. compression = restLength currentLength springForce = stiffness compression damperForce = damping compressionVelocity normalLoad = max(0, springForce + damperForce) Returns: } A slip based tire force (Pacejka lite): linear near zero slip, saturating at the friction limit . shapes the knee. Longitudinal slip ratio from wheel surface speed vs ground speed. Free rolling angular velocity (rad/s) for a given ground speed. Compose the visual world matrix for a wheel from chassis world + slot + state. Parameters: (Float32Array) — column major 4x4 (object) — WheelSlot (object) — { suspensionOffset, steerAngle, spinAngle } Returns: column major 4x4 Advance a wheel's spin angle from a ground speed (visual integration). <! HUMAN NOTES Notes & Examples No hand authored notes yet. Add page notes in or a reusable block in — see API Reference Standard.


assets/vehicle/WheelSlot.js
Functions
createWheelSlot(init = {})
createSuspension(init = {})
createTireProfile(init = {})
createVehicleAsset(init = {})
Constants
Notes & Examples

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: engine/assets/vehicle/WheelSlot.js — vehicle rig schemas (spec §11). A vehicle is NOT a mesh: it's a visual model + chassis collider + wheel slots + suspension + tire model + drivetrain. Wheel runtime data is explicit and separate from the visible wheel mesh (matching Jolt/Unity wheel colliders), so visuals follow physics rather than the other way around. Functions A wheel slot: the runtime data for one wheel, decoupled from its visual mesh. The assembled vehicle rig produced by VehicleRigBuilder. It references the model's nodes/meshes and carries explicit runtime data; it can drive the engine's GPUVehicle physics or the CPU WheelPhysics fallback. Constants <! 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: engine/assets/vehicle/WheelSpinVisual.js — visual wheel spin transforms for a rigged vehicle. Separated from physics (WheelPhysics) and detection so the importer/viewer, the editor preview, and the runtime can all reuse one correct implementation. Approach (matches Unity / Godot ): the spin is built in the wheel's MESH LOCAL space from the detector's per wheel hub ( ) and axle ( ), then the node hierarchy + import correction carry it to the right world position and orientation automatically (the renderer does ). This avoids transforming the axle into world space, PCA axis ambiguity on low poly wheels, and pivot guessing — the failure modes of a world space spin. The only world space step is a per wheel SIGN so mirrored wheels roll the same way; the axle vector itself stays the exact per wheel local axis. Functions Column major rotation about an arbitrary (unit normalized) axis. Spin about an axis through a pivot: T(pivot) · R(axis,angle) · T( pivot). Build a per wheel spin descriptor map for a rigged model. Each entry carries the wheel's MESH LOCAL pivot + axle (so the renderer applies the spin in local space: ). The local axle is pre signed so every wheel rolls the same visual direction. Steerable wheels also carry their local steer axis so the renderer can yaw them with input. Parameters: (object) — EngineModel (must be detected/rigged) (Float32Array) — model importTransform matrix (local→world correction) (object) — VehicleAsset (model.rigs.vehicle) with wheelSlots Returns: } keyed by visualNode id Spin angle (radians) for a wheel that has rolled metres. <! HUMAN NOTES Notes & Examples No hand authored notes yet. Add page notes in or a reusable block in — see API Reference


for a wheel that has rolled metres. <! HUMAN NOTES Notes & Examples No hand authored notes yet. Add page notes in or a reusable block in — see API Reference Standard.


assets/vpath.js

assets/vpath.js
Functions
parseVPath(vpath)
isVPath(vpath)
makeVPath(scheme, ...parts)
normalizeSegments(path)
withScheme(vpath, scheme)
vpathBasename(vpath)
vpathExtension(vpath)
cachePathFor(kind, sourceHash, ext)
Constants
Notes & Examples

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: engine/assets/vpath.js — virtual path system. Users never manage raw filesystem paths. Everything addresses through a scheme://path virtual path. The resolver (AssetResolver) maps a virtual path to a concrete backend handle; this module only parses/normalizes/builds them. asset:// project asset library user:// user selected local folder (File System Access) cache:// OPFS / local engine cache cloud:// optional remote mirror temp:// transient drag drop import surface:// live render surface (no backing file) Functions Parse a virtual path into { scheme, path, segments }. Parameters: (string) — No description in source JSDoc. Returns: null} null if malformed Build a virtual path from a scheme + path parts. Collapse duplicate/empty separators and strip leading/trailing slashes. Swap the scheme of a virtual path, keeping the same path (e.g. for backups). The basename (last segment) and extension of a virtual path. Standard cache path for a converted artifact, keyed by content hash. Constants <! HUMAN NOTES Notes & Examples No hand authored notes yet. Add page notes in or a reusable block in — see API Reference Standard.


assets/weapon/WeaponRig.js
Functions
createWeaponRig(init = {})
Constants
Notes & Examples

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: engine/assets/weapon/WeaponRig.js — canonical weapon socket/part schema (spec §13). A weapon is a model + sockets (muzzle/chamber/grips/sight/…) + moving parts (slide/bolt/hammer/…) + a fire/reload timeline + a state machine. This is a GAME ABSTRACTION: sockets/timings are gameplay anchors, not real firearm data. Every detection is a hint with confidence; ambiguous nodes go to the editor. Functions Create a weapon rig descriptor. Parameters: (object) — 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.


assets/weapon/WeaponRigBuilder.js
Functions
buildWeaponRig(model, opts = {})
Notes & Examples

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: engine/assets/weapon/WeaponRigBuilder.js — assemble a WeaponRig from a model: detect sockets + moving parts + forward/muzzle, attach default fire/reload timelines and a state machine seed, and flag needsCorrection when required sockets are missing. Attaches at model.rigs.weapon. GAME ABSTRACTION ONLY. Functions Build a weapon rig and attach it at model.rigs.weapon. Parameters: (object) — EngineModel (object) — No description in source JSDoc. Returns: the WeaponRig <! HUMAN NOTES Notes & Examples No hand authored notes yet. Add page notes in or a reusable block in — see API Reference Standard.


assets/weapon/WeaponSocketDetector.js
Functions
detectWeapon(model)
Notes & Examples

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: engine/assets/weapon/WeaponSocketDetector.js — find weapon sockets + moving parts by NAME (priority ordered patterns) and resolve the forward/aim axis + muzzle by geometry (a firearm is long along the barrel; the muzzle is the front most node along that axis). Hints + confidence; ambiguous → editor. GAME ABSTRACTION ONLY — no real firearm dimensions or ballistics here. Functions Detect weapon sockets, moving parts, forward axis, and muzzle. Parameters: (object) — EngineModel Returns: detection result <! HUMAN NOTES Notes & Examples No hand authored notes yet. Add page notes in or a reusable block in — see API Reference Standard.


assets/weapon/WeaponStateMachine.js
Functions
createWeaponStateMachine(init = {})
Constants
Notes & Examples

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: engine/assets/weapon/WeaponStateMachine.js — a small, deterministic weapon state machine: idle ⇄ firing ⇄ empty, with reloading. It models a magazine + a chambered round (total = ammo + chambered) and auto cycles a fresh round after each shot, so dry fire, last round, and reload from empty all behave correctly. GAME ABSTRACTION ONLY — no real firearm mechanism is modelled. Functions Parameters: (object) — { capacity, ammo, chambered, fireMode } Constants <! HUMAN NOTES Notes & Examples No hand authored notes yet. Add page notes in or a reusable block in — see API Reference Standard.


assets/weapon/WeaponTimeline.js
Functions
createWeaponAction(init = {})
defaultFireAction(duration = 0.12)
defaultReloadAction(duration = 2.0)
eventsBetween(action, t0, t1)
createTimelinePlayer(action)
Constants
Notes & Examples

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: engine/assets/weapon/WeaponTimeline.js — keyframed event tracks for weapon actions (fire, reload). An action is an ordered list of { t, type, payload } events over a duration; returns events crossed in a time step so the host fires them exactly once (deterministic, frame rate independent). GAME ABSTRACTION — timings are gameplay anchors, not real mechanisms. Functions Create a single action timeline (e.g. one shot, or a reload). Parameters: (object) — { name, duration, events:[{t,type,payload?}] } A default semi auto fire action (normalized 0..duration seconds). A default reload action. Events whose time t lies in (t0, t1]. Use with an advancing playhead so each event fires exactly once regardless of frame rate. A small play once cursor over an action. Constants <! HUMAN NOTES Notes & Examples No hand authored notes yet. Add page notes in or a reusable block in — see API Reference Standard.


audio/SpatialAudioEnvironment.js

createSpatialEnvironment(ctx, config = {})

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: SpatialAudioEnvironment.js Advanced Spatial Audio Processing Industry grade environment audio: material absorption, ground reflection, environment zones (underwater/cave/outdoor), diffraction, and dynamic reverb. Research basis: FMOD/Wwise material absorption coefficients (ISO 354 standard) Image source method for early reflections (Allen & Berkley 1979) Underwater acoustics: 300Hz LPF + extended reverb (Wikipedia/Navy research) Diffraction: UTD edge diffraction approximation (Kouyoumjian & Pathak 1974) Ground reflection: single bounce mirror source below floor plane All processing uses Web Audio API nodes (BiquadFilter, Gain, Delay, Convolver). Zero external dependencies. Functions Create the spatial audio environment system. Attaches to an existing AudioContext and provides environment processing. Parameters: (AudioContext) — The Web Audio API context (Object) — Configuration options Returns: The environment system handle Set the raycast function for environment probing. Function signature: (origin: [x,y,z], direction: [x,y,z], maxDist: number) = { hit, distance, position, normal, entityId } null Set the entity material lookup function. Function signature: (entityId) = 'stone' 'wood' 'metal' etc. Set the water surface Y level. Listener below this = underwater. Pass null to disable underwater detection. Update the environment system each frame. Detects environment zone, updates ground reflection, handles underwater. Parameters: (Object) — The environment system (Array) — [x, y, z] listener position (Array) — [x, y, z] listener forward direction Compute material aware occlusion between a source and the listener. Returns { factor: 0 1, lpfMult: 0 1 } where factor affects volume,


audio/SpatialAudioEnvironment.js

forward direction Compute material aware occlusion between a source and the listener. Returns { factor: 0 1, lpfMult: 0 1 } where factor affects volume, lpfMult affects high frequency content (material filtering). Parameters: (Object) — The environment system (Array) — [x, y, z] sound source position Returns: } Compute diffraction factor for partially occluded sources. Casts multiple rays slightly offset from the direct path. If some rays get through, the sound is partially diffracted (not fully blocked). Parameters: (Object) — The environment system (Array) — [x, y, z] sound source position Returns: } 0=fully blocked, 1=clear Compute full spatial occlusion for a sound source. Combines material based occlusion with edge diffraction. Returns 0 1 where 0 = fully blocked, 1 = clear. Parameters: (Object) — The environment system (Array) — [x, y, z] sound source position Returns: Combined occlusion factor (0 1) Generate a procedural impulse response for a given environment. Cached per environment to avoid regeneration. Parameters: (Object) — The environment system (string) — Environment zone name Returns: The generated IR Connect the environment system's master filters into the audio bridge's output chain. Call once after both bridge and environment are created. Inserts: bridge.masterGain → env.masterHPF → env.masterLPF → ctx.destination Also connects ground reflection send from bridge.compressor. Parameters: (Object) — The environment system (Object) — The audio bridge Get absorption data for a material key. Parameters: (string) — Material name (stone, wood, metal, etc.) Returns: } Get all available environment presets. Returns: Map of preset name → preset data Force a specific environment zone (overrides auto detection). Pass null to re enable auto detection. Get current


audio/SpatialAudioEnvironment.js

Returns: Map of preset name → preset data Force a specific environment zone (overrides auto detection). Pass null to re enable auto detection. Get current environment stats. Destroy the environment system and release all audio nodes. <! HUMAN NOTES Notes & Examples Audio Graph Architecture The audio system uses a node based graph architecture. AudioNodes connect to form processing chains: sources (oscillator, buffer) → effects (filter, delay, reverb) → destination (speakers). All processing happens on the audio thread via the Web Audio API with automatic sample rate conversion. Example: Creating a sound effect chain See also: Audio · Engine Overview Audio Graph Architecture The audio system uses a nod


tickCharacterAudio(bridge, audioEngine, entityId, state, dt)

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: CharacterAudioBridge.js Character Movement → Audio Events Triggers footsteps, jumps, lands, and body foley based on character movement state (velocity, grounded, etc). Functions Create a character movement audio bridge. Parameters: (Object) — No description in source JSDoc. (number) — Seconds between footsteps when walking (default 0.45) (number) — Run cadence = walk cadence × this (default 0.65) (number) — Min m/s horizontal speed to trigger footsteps (default 0.8) (number) — Min m/s vertical speed to trigger land sound (default 2.0) (number) — m/s speed to consider "running" (default 3.5) (number) — Max distance from listener to play sounds (default 50) Tick the character audio bridge for a single character. Call once per frame per character entity. Parameters: (Object) — CharacterAudioBridge instance (Object) — AudioEngine instance (string number) — Unique character entity ID (Object) — Character state (number[]) — [x, y, z] world position (number[]) — [x, y, z] velocity in m/s (boolean) — Is character on ground (number string null) — Ground material ID or string (number) — Entity weight multiplier (default 1.0) (number) — Delta time in seconds Clean up character state when entity is destroyed. Parameters: (Object) — No description in source JSDoc. (string number) — No description in source JSDoc. Destroy the character audio bridge and clean up all state. Parameters: (Object) — No description in source JSDoc. <! HUMAN NOTES Notes & Examples Audio Graph Architecture The audio system uses a node based graph architecture. AudioNodes connect to form processing chains: sources (oscillator, buffer) → effects (filter, delay, reverb) → destination (speakers). All processing happens on


connect to form processing chains: sources (oscillator, buffer) → effects (filter, delay, reverb) → destination (speakers). All processing happens on the audio thread via the Web Audio API with automatic sample rate conversion. Example: Creating a sound effect chain See also: Audio · Engine Overview Audio Graph Architecture The audio system uses a node based graph architecture. AudioNodes connect to form processing chains: sources (oscillator, buffer) → effects (filter, delay, reverb) → destination (speakers). All processing happens on the audio thread via the Web Audio API with automatic sample rate conversion. Example: Creating a sound effect chain Advanced: Loading and playing audio assets Advanced: 3D spatial audio Advanced: Mixing and buses Gotchas: AudioContext state : Browsers block audio until user interaction. Call after a click. Memory : holds raw PCM — unload large files when not needed. Scheduling : Use for precise rhythm; drifts vs . See also: Audio · Engine Overview


<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: DestructionAudioBridge.js Destruction Events → Audio Hooks into VoronoiFracture, UnifiedDamageSystem, SeismicSystem, and ShockPropagation to trigger shattering, crumbling, rumble, and explosion sounds. Functions Create a destruction audio bridge. Parameters: (Object) — No description in source JSDoc. (number) — (default 4) (number) — Min seconds between same position triggers (default 0.2) (number) — (default 150) Process a damage event. Parameters: (Object) — No description in source JSDoc. (Object) — No description in source JSDoc. (string) — 'impact' 'explosion' 'erosion' 'pierce' 'crush' 'heat' 'acid' (number[]) — [x,y,z] (number) — Damage magnitude (0 100+) (string) — Material name hint (number) — No description in source JSDoc. Process a fracture event (Voronoi fracture). Parameters: (Object) — No description in source JSDoc. (Object) — No description in source JSDoc. (number[]) — No description in source JSDoc. (string) — 'glass' 'stone' 'wood' 'metal' (number) — Number of pieces (number) — No description in source JSDoc. Process a seismic event (earthquake rumble). Parameters: (Object) — No description in source JSDoc. (Object) — No description in source JSDoc. (number[]) — Epicenter (number) — Richter like scale (number) — No description in source JSDoc. Flush pending destruction audio events. Parameters: (Object) — No description in source JSDoc. Update listener position. Parameters: (Object) — No description in source JSDoc. (number[]) — No description in source JSDoc. <! HUMAN NOTES Notes & Examples Audio Graph Architecture The audio system uses a node based graph architecture. AudioNodes connect to form processing chains: sources (oscillator, buffer) → effects


Graph Architecture The audio system uses a node based graph architecture. AudioNodes connect to form processing chains: sources (oscillator, buffer) → effects (filter, delay, reverb) → destination (speakers). All processing happens on the audio thread via the Web Audio API with automatic sample rate conversion. Example: Creating a sound effect chain See also: Audio · Engine Overview Audio Graph Architecture The audio system uses a node based graph architecture. AudioNodes connect to form processing chains: sources (oscillator, buffer) → effects (filter, delay, reverb) → destination (speakers). All processing happens on the audio thread via the Web Audio API with automatic sample rate conversion. Example: Creating a sound effect chain Advanced: Loading and playing audio assets Advanced: 3D spatial audio Advanced: Mixing and buses Gotchas: AudioContext state : Browsers block audio until user interaction. Call after a click. Memory : holds raw PCM — unload large files when not needed. Scheduling : Use for precise rhythm; drifts vs . See also: Audio · Engine Overview


registerEmitterLoop(bridge, emitterId, sourceId, substanceId, position)

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: EmitterAmbientBridge.js Active Emitters → Continuous Ambient Loops When a substance emitter is active and has an ambientLoop defined, this bridge manages a looping spatial audio source at the emitter position. Sources are created when emitters start and removed when they stop. Functions Create an emitter ambient bridge. Parameters: (Object) — No description in source JSDoc. (number) — Max simultaneous ambient loops (default 8) (number) — Fade in time in seconds (default 0.5) (number) — Fade out time in seconds (default 1.0) Sync active emitters with ambient audio loops. Call each frame with the current list of active emitters. Parameters: (Object) — No description in source JSDoc. (Object[]) — Array of active emitter objects Returns: Array of actions: { action: 'start' 'stop' 'update', ... } Register that a loop was started (store sourceId). Parameters: (Object) — No description in source JSDoc. (number string) — No description in source JSDoc. (number) — AudioEngine source ID (string) — No description in source JSDoc. (number[]) — No description in source JSDoc. Stop all active ambient loops. Parameters: (Object) — No description in source JSDoc. Returns: Stop actions <! HUMAN NOTES Notes & Examples Audio Graph Architecture The audio system uses a node based graph architecture. AudioNodes connect to form processing chains: sources (oscillator, buffer) → effects (filter, delay, reverb) → destination (speakers). All processing happens on the audio thread via the Web Audio API with automatic sample rate conversion. Example: Creating a sound effect chain See also: Audio · Engine Overview Audio Graph Architecture The audio system uses a node based graph architecture. AudioNodes


Creating a sound effect chain See also: Audio · Engine Overview Audio Graph Architecture The audio system uses a node based graph architecture. AudioNodes connect to form processing chains: sources (oscillator, buffer) → effects (filter, delay, reverb) → destination (speakers). All processing happens on the audio thread via the Web Audio API with automatic sample rate conversion. Example: Creating a sound effect chain Advanced: Loading and playing audio assets Advanced: 3D spatial audio Advanced: Mixing and buses Gotchas: AudioContext state : Browsers block audio until user interaction. Call after a click. Memory : holds raw PCM — unload large files when not needed. Scheduling : Use for precise rhythm; drifts vs . See also: Audio · Engine Overview


processFluidSplash(bridge, position, magnitude, currentTime)

processPhaseChangeAudio(bridge, phaseType, position, magnitude, currentTime)

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: FluidAudioBridge.js Fluid Events → Audio Hooks into fluid simulation (splashes, phase changes) and triggers appropriate audio events. Functions Create a fluid audio bridge. Parameters: (Object) — No description in source JSDoc. (number) — (default 4) (number) — (default 0.1) (number) — (default 100) Process a fluid splash event. Parameters: (Object) — No description in source JSDoc. (number[]) — [x,y,z] (number) — Splash intensity (0 1+) (number) — No description in source JSDoc. Process a phase change event. Parameters: (Object) — No description in source JSDoc. (string) — 'freeze' 'melt' 'boil' 'crystallize' (number[]) — [x,y,z] (number) — Intensity (number) — No description in source JSDoc. Flush pending fluid audio events. Parameters: (Object) — No description in source JSDoc. Update listener position. Parameters: (Object) — No description in source JSDoc. (number[]) — No description in source JSDoc. <! HUMAN NOTES Notes & Examples Audio Graph Architecture The audio system uses a node based graph architecture. AudioNodes connect to form processing chains: sources (oscillator, buffer) → effects (filter, delay, reverb) → destination (speakers). All processing happens on the audio thread via the Web Audio API with automatic sample rate conversion. Example: Creating a sound effect chain See also: Audio · Engine Overview Audio Graph Architecture The audio system uses a node based graph architecture. AudioNodes connect to form processing chains: sources (oscillator, buffer) → effects (filter, delay, reverb) → destination (speakers). All processing happens on the audio thread via the Web Audio API with automatic sample rate conversion. Example: Creating a sound effect chain


(speakers). All processing happens on the audio thread via the Web Audio API with automatic sample rate conversion. Example: Creating a sound effect chain Advanced: Loading and playing audio assets Advanced: 3D spatial audio Advanced: Mixing and buses Gotchas: AudioContext state : Browsers block audio until user interaction. Call after a click. Memory : holds raw PCM — unload large files when not needed. Scheduling : Use for precise rhythm; drifts vs . See also: Audio · Engine Overview


<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: PhysicsAudioBridge.js Physics Collision → Audio Events Hooks into physics contact callbacks (PhysX/PBD) and triggers material aware impact sounds via the AudioEngine. Functions Create a physics audio bridge. Parameters: (Object) — No description in source JSDoc. (number) — Max audio triggers per frame (default 4) (number) — Min seconds between triggers for same body pair (default 0.1) (number) — Minimum collision speed to trigger audio (default 2.0) (number) — Max distance from listener (default 100) Process a physics contact event. Parameters: (Object) — No description in source JSDoc. (Object) — No description in source JSDoc. (number[]) — [x,y,z] contact point (number[]) — [x,y,z] relative velocity (number) — Impact impulse magnitude (number) — Material ID of body A (number) — Material ID of body B (number) — Body handle A (number) — Body handle B (number) — Engine time Flush pending physics audio events. Parameters: (Object) — No description in source JSDoc. Returns: Array of trigger configs Update listener position. Parameters: (Object) — No description in source JSDoc. (number[]) — No description in source JSDoc. <! HUMAN NOTES Notes & Examples Audio Graph Architecture The audio system uses a node based graph architecture. AudioNodes connect to form processing chains: sources (oscillator, buffer) → effects (filter, delay, reverb) → destination (speakers). All processing happens on the audio thread via the Web Audio API with automatic sample rate conversion. Example: Creating a sound effect chain See also: Audio · Engine Overview Audio Graph Architecture The audio system uses a node based graph architecture. AudioNodes connect to form processing chains: sources (oscillator,


Overview Audio Graph Architecture The audio system uses a node based graph architecture. AudioNodes connect to form processing chains: sources (oscillator, buffer) → effects (filter, delay, reverb) → destination (speakers). All processing happens on the audio thread via the Web Audio API with automatic sample rate conversion. Example: Creating a sound effect chain Advanced: Loading and playing audio assets Advanced: 3D spatial audio Advanced: Mixing and buses Gotchas: AudioContext state : Browsers block audio until user interaction. Call after a click. Memory : holds raw PCM — unload large files when not needed. Scheduling : Use for precise rhythm; drifts vs . See also: Audio · Engine Overview


buildSpellAudioTrigger(bridge, spell, position, currentTime)

buildSoundHintTrigger(bridge, soundHint, position, currentTime)

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: SpellAudioBridge.js Spell Cast → Audio Events Resolves soundHint strings from SpellGenerator and SpellElementMixer into AudioEngine trigger calls. Functions Create a spell audio bridge. Parameters: (Object) — No description in source JSDoc. (number) — Min seconds between spell sounds (default 0.05) Build audio trigger config from a spell cast. Parameters: (Object) — No description in source JSDoc. (Object) — Generated spell object (from SpellGenerator) (number[]) — [x,y,z] cast position (number) — Engine time Returns: Trigger config for AudioEngine Build audio trigger from a raw soundHint string. Parameters: (Object) — No description in source JSDoc. (string) — No description in source JSDoc. (number[]) — No description in source JSDoc. (number) — No description in source JSDoc. <! HUMAN NOTES Notes & Examples Audio Graph Architecture The audio system uses a node based graph architecture. AudioNodes connect to form processing chains: sources (oscillator, buffer) → effects (filter, delay, reverb) → destination (speakers). All processing happens on the audio thread via the Web Audio API with automatic sample rate conversion. Example: Creating a sound effect chain See also: Audio · Engine Overview Audio Graph Architecture The audio system uses a node based graph architecture. AudioNodes connect to form processing chains: sources (oscillator, buffer) → effects (filter, delay, reverb) → destination (speakers). All processing happens on the audio thread via the Web Audio API with automatic sample rate conversion. Example: Creating a sound effect chain Advanced: Loading and playing audio assets Advanced: 3D spatial audio Advanced: Mixing and buses Gotchas: AudioContext state : Browsers


a sound effect chain Advanced: Loading and playing audio assets Advanced: 3D spatial audio Advanced: Mixing and buses Gotchas: AudioContext state : Browsers block audio until user interaction. Call after a click. Memory : holds raw PCM — unload large files when not needed. Scheduling : Use for precise rhythm; drifts vs . See also: Audio · Engine Overview


applySubstanceParamMap(substanceId, params = {}, mapOverrides = null)

buildSubstancePreviewParams(substanceId, overrides = {}, sourceParams = {})

buildSubstanceTriggerConfig(substanceId, eventType, params = {})

<! AUTOGENERATED by tools/extract api.py — content above HUMAN NOTES is overwritten Source: SubstanceAudioResolver.js Resolve substance key → audio config Maps substance IDs to audio event configurations, supporting both sample based fallback and procedural patch references. Functions Resolve a substance key to its audio configuration. Parameters: (string) — e.g. 'fire', 'water', 'metal' Returns: { impactSound, ambientLoop, collisionSound, volume, pitchRange, proceduralPatch?, paramMap? } Get the impact sound event ID for a substance. Parameters: (string) — No description in source JSDoc. Get the ambient loop event ID for a substance. Parameters: (string) — No description in source JSDoc. Get the collision sound event ID for a substance. Parameters: (string) — No description in source JSDoc. Get procedural patch ID for a substance (if defined). Parameters: (string) — No description in source JSDoc. Get parameter mapping for procedural synthesis. Maps emitter params → synth params. Parameters: (string) — No description in source JSDoc. Returns: e.g. { 'emitRate': { target: 'crackle.density', scale: 0.1, offset: 0 } } Get normalized default procedural params for a substance. Parameters: (string) — No description in source JSDoc. Returns: } Apply a substance paramMap to source params. Supports runtime map override keys: map <src scale / map <src offset. Parameters: (string) — No description in source JSDoc. (Object) — No description in source JSDoc. (Object null) — No description in source JSDoc. Build preview/runtime friendly patch params with shared defaults + paramMap transform. Parameters: (string) — No description in source JSDoc. (Object) — No description in source JSDoc. (Object) — No description in source JSDoc. Build a complete audio trigger config from substance