Skip to content

armgit / 67.js

Public Imported from GitHub
0

3D engine that AI agents drive

Bind physics bodies to the bones of a rig for ragdolls

Nguyen Xuan Anf3130d765410
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 127b693d..c1dfbf68 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -2,6 +2,8 @@
## Unreleased
+- Add ragdolls (part of issue #96): `physics.ragdoll` in a recipe with armatures and `physics` in an asset recipe (`set-physics`) bind a capsule body to every bone or joint and play the fall back as the pose of those bones, the same bytes for the same seek. New `src/ragdoll.js`, loaded with the physics code only. New suite task `robot-ragdoll`. The lazy budgets of `agent-scene+lazy` and `agent-asset+lazy` rise by 100 and 800 bytes gzip for it; the core entries did not grow from this. Joints have no swing limits yet.
+
- Make the path tracer about 2.8 times faster per thread and draw normal and metallic-roughness maps (part of issue #129; a 1080p still of the 181,708 triangle demo room at 64 samples still does not fit the 240 s job limit). Profiling the demo room showed the ray query dominating: 54 percent of the time sat in the generic BVH visitor, which called a closure per box and per triangle and kept distances in a boxed array. `createTracer` in `src/ray-query.js` now walks the BVH with typed stacks, a slab test on inverse directions and triangles packed in leaf order; pixels are bit-identical to before (checksum of a band unchanged) and it runs 1.2 times faster alone. The larger gain is shadow rays: the demo room has 11 light sources, and every bounce traced all of them. The first hit of a path still samples every light; later hits draw one at random and divide by its chance (and the environment multiple importance weights use that chance), which gives 23,300 paths a second per thread against 9,800, with the average moved by less than 1 percent in the demo room and 3 percent allowed by a test. Image jobs now use 8 workers, up from 4 (the machine limit). `normalMap` (with `normalScale`, tangent frame from the UVs as in the rasterizer) and `metallicRoughnessMap` (green scales roughness, blue scales metallic) are drawn on UV-mapped materials; on box-projected materials (`boxMapScale`) they are still ignored and `report.ignored` says so. The `entry:path-tracer` size budget goes from 12,900 to 13,800 bytes gzip for the maps, light selection and the packed ray query; `entry:core` did not change. Tests: maps tilt and mask the light, one light drawn at random keeps the average, and bands drawn in any order give the pixels of the whole image.
- Move the anisotropy and iridescence shader code out of the core bundle (part of issue #51). It lives in the new `addons/material-layer-shaders` entry, which registers it on import; the renderer asks for it only when a part uses a layer, so a lit box no longer pays for it. A scene that uses a layer in code must import the entry first, or the renderer throws a message that names the import. Recipes load it through `loadAgentSceneModules`, the MCP server does so itself, and the glTF loader loads it for a file that uses either extension. The unused short overloads of `environmentLighting` are gone. Pictures are unchanged.
diff --git a/bench/agent-modeling/check.mjs b/bench/agent-modeling/check.mjs
index b0bb8d3d..bf5377ee 100644
--- a/bench/agent-modeling/check.mjs
+++ b/bench/agent-modeling/check.mjs
@@ -142,6 +142,14 @@ function checkOne(check, measures) {
const pass = target.genus === check.genus && target.closedParts === 1 && target.partCount === 1 && target.lintOk && volumeKept && others.length === 0;
return { pass, detail: `${check.part}: genus ${target.genus}, ${target.partCount} part(s), lint ${target.lintOk}, ${round(target.volumeRatio)} of the volume kept, other edited parts ${others.join(', ') || 'none'}` };
}
+ case 'assetRagdoll': {
+ const ragdoll = measures.ragdoll;
+ if (!ragdoll) return { pass: false, detail: 'the recipe has no physics ragdoll' };
+ const liftedAboveFloor = ragdoll.startHeight - ragdoll.floor >= check.minimumDrop;
+ const lyingOnFloor = ragdoll.lowestY <= check.floorTolerance && ragdoll.highestY <= check.maximumHeight;
+ return { pass: liftedAboveFloor && lyingOnFloor && ragdoll.duration >= check.minimumDuration,
+ detail: `root ${ragdoll.startHeight} over floor ${ragdoll.floor}, ${ragdoll.duration} s, ends between y ${ragdoll.lowestY} and ${ragdoll.highestY}` };
+ }
case 'assetClip': {
return { pass: measures.clipName === check.name, detail: `clip ${measures.clipName ?? 'none'}` };
}
diff --git a/bench/agent-modeling/measure.mjs b/bench/agent-modeling/measure.mjs
index aec44cb4..c87c7fd5 100644
--- a/bench/agent-modeling/measure.mjs
+++ b/bench/agent-modeling/measure.mjs
@@ -256,10 +256,15 @@ function measureEditedParts(scene, asset, recipe) {
}
export async function measureAssetRecipe(recipe) {
- if (recipe.meshEdits) {
+ if (recipe.meshEdits || recipe.physics) {
await loadAllAgentSceneModules();
+ }
+ if (recipe.meshEdits) {
await loadMeshBooleans();
}
+ if (needsPhysics(recipe)) {
+ await loadPhysicsEngine();
+ }
const asset = await loadFixtureRobot();
const scene = createAgentAssetScene(asset, recipe);
const layerPose = await measureLayerPose(recipe, await loadFixtureRobot());
@@ -274,6 +279,7 @@ export async function measureAssetRecipe(recipe) {
return {
clipName: recipe.animation ? asset.animations[recipe.animation.clip]?.name : null,
layerPose,
+ ragdoll: recipe.physics?.ragdoll ? { startHeight: recipe.root?.translation?.[1] ?? 0, floor: recipe.physics.floor ?? 0, duration: recipe.physics.duration, ...scene.inspect({}).physics.ragdoll } : null,
editedParts: measureEditedParts(scene, asset, recipe),
camera: recipe.camera ?? null,
reachSolvers: solvers.filter(solver => solver.type === 'two-bone').map(solver => {
diff --git a/bench/agent-modeling/references.mjs b/bench/agent-modeling/references.mjs
index c25c2a35..16d26a75 100644
--- a/bench/agent-modeling/references.mjs
+++ b/bench/agent-modeling/references.mjs
@@ -235,6 +235,11 @@ export const REFERENCES = {
}],
},
},
+ 'robot-ragdoll': {
+ format: '67js.asset', schemaVersion: 1, assetId: 'ab'.repeat(32),
+ root: { translation: [0, 2, 0] },
+ physics: { duration: 4, ragdoll: {} },
+ },
'robot-walk-wave': {
format: '67js.asset', schemaVersion: 1, assetId: 'ab'.repeat(32),
motion: {
diff --git a/bench/agent-modeling/results/2026-10-31-22-07-haiku-run.json b/bench/agent-modeling/results/2026-10-31-22-07-haiku-run.json
new file mode 100644
index 00000000..97395992
--- /dev/null
+++ b/bench/agent-modeling/results/2026-10-31-22-07-haiku-run.json
@@ -0,0 +1,77 @@
+{
+ "run": "2026-10-31-22-07-haiku-run",
+ "model": "claude-haiku-5-5",
+ "date": "2026-10-31T22:10:35.124Z",
+ "skill": false,
+ "runsPerTask": 1,
+ "passed": 0,
+ "tasks": 1,
+ "toolCalls": 20,
+ "costUsd": 0.25,
+ "byModel": {
+ "claude-haiku-5-5": {
+ "runs": 1,
+ "passed": 0,
+ "successRate": 0,
+ "toolCalls": 20,
+ "toolErrors": 3,
+ "inputTokens": 2314153,
+ "outputTokens": 24481,
+ "costUsd": 0.25,
+ "tasks": {
+ "robot-ragdoll": {
+ "runs": 1,
+ "passed": 0,
+ "successRate": 0,
+ "toolCalls": 20,
+ "toolErrors": 3,
+ "inputTokens": 2314153,
+ "outputTokens": 24481,
+ "costUsd": 0.25
+ }
+ }
+ }
+ },
+ "records": [
+ {
+ "task": "robot-ragdoll",
+ "attempt": 1,
+ "pass": false,
+ "passed": 0,
+ "total": 1,
+ "failed": [
+ "assetRagdoll: the recipe has no physics ragdoll"
+ ],
+ "model": "claude-haiku-5-5",
+ "toolCalls": 20,
+ "toolErrors": 3,
+ "toolsByName": {
+ "ToolSearch": 2,
+ "scene_capabilities": 1,
+ "scene_asset_catalog": 1,
+ "scene_create_asset": 1,
+ "scene_inspect": 3,
+ "scene_apply": 6,
+ "scene_look": 2,
+ "scene_review": 5,
+ "scene_export_recipe": 1
+ },
+ "features": {
+ "geometryTypes": [],
+ "meshOperations": [],
+ "motionIk": [],
+ "motionTracks": 1
+ },
+ "look": {
+ "error": "Cannot read properties of undefined (reading 'format')"
+ },
+ "turns": 23,
+ "costUsd": 0.25004268,
+ "inputTokens": 2314153,
+ "outputTokens": 24481,
+ "wallSeconds": 188,
+ "exitCode": 0,
+ "stopped": "success"
+ }
+ ]
+}
diff --git a/bench/agent-modeling/results/2026-10-31-22-13-haiku-run.json b/bench/agent-modeling/results/2026-10-31-22-13-haiku-run.json
new file mode 100644
index 00000000..bc6dd98b
--- /dev/null
+++ b/bench/agent-modeling/results/2026-10-31-22-13-haiku-run.json
@@ -0,0 +1,115 @@
+{
+ "run": "2026-10-31-22-13-haiku-run",
+ "model": "claude-haiku-5-5",
+ "date": "2026-10-31T22:17:24.852Z",
+ "skill": false,
+ "runsPerTask": 2,
+ "passed": 1,
+ "tasks": 2,
+ "toolCalls": 37,
+ "costUsd": 0.32,
+ "byModel": {
+ "claude-haiku-5-5": {
+ "runs": 2,
+ "passed": 1,
+ "successRate": 0.5,
+ "toolCalls": 37,
+ "toolErrors": 7,
+ "inputTokens": 3514377,
+ "outputTokens": 23725,
+ "costUsd": 0.32,
+ "tasks": {
+ "robot-ragdoll": {
+ "runs": 2,
+ "passed": 1,
+ "successRate": 0.5,
+ "toolCalls": 37,
+ "toolErrors": 7,
+ "inputTokens": 3514377,
+ "outputTokens": 23725,
+ "costUsd": 0.32
+ }
+ }
+ }
+ },
+ "records": [
+ {
+ "task": "robot-ragdoll",
+ "attempt": 1,
+ "pass": false,
+ "passed": 0,
+ "total": 1,
+ "failed": [
+ "assetRagdoll: the recipe has no physics ragdoll"
+ ],
+ "model": "claude-haiku-5-5",
+ "toolCalls": 21,
+ "toolErrors": 2,
+ "toolsByName": {
+ "ToolSearch": 1,
+ "scene_capabilities": 1,
+ "scene_asset_catalog": 1,
+ "scene_create_asset": 1,
+ "scene_inspect": 3,
+ "scene_apply": 5,
+ "scene_look": 8,
+ "scene_export_recipe": 1,
+ "scene_dispose": 1
+ },
+ "features": {
+ "geometryTypes": [],
+ "meshOperations": [],
+ "motionIk": [],
+ "motionTracks": 2
+ },
+ "look": {
+ "error": "Cannot read properties of undefined (reading 'format')"
+ },
+ "turns": 23,
+ "costUsd": 0.18923791,
+ "inputTokens": 1978568,
+ "outputTokens": 17595,
+ "wallSeconds": 170,
+ "exitCode": 0,
+ "stopped": "success"
+ },
+ {
+ "task": "robot-ragdoll",
+ "attempt": 2,
+ "pass": true,
+ "passed": 1,
+ "total": 1,
+ "failed": [],
+ "model": "claude-haiku-5-5",
+ "toolCalls": 16,
+ "toolErrors": 5,
+ "toolsByName": {
+ "ToolSearch": 2,
+ "scene_capabilities": 1,
+ "scene_asset_catalog": 1,
+ "scene_create_asset": 1,
+ "scene_inspect": 2,
+ "scene_look": 2,
+ "scene_apply": 7,
+ "scene_export_recipe": 1,
+ "scene_dispose": 1
+ },
+ "features": {
+ "geometryTypes": [],
+ "meshOperations": [],
+ "motionIk": [],
+ "motionTracks": 0
+ },
+ "look": {
+ "error": "Cannot read properties of undefined (reading 'format')"
+ },
+ "turns": 19,
+ "costUsd": 0.12881438999999997,
+ "inputTokens": 1535809,
+ "outputTokens": 6130,
+ "wallSeconds": 73,
+ "exitCode": 0,
+ "stopped": "success"
+ }
+ ]
+}
diff --git a/bench/agent-modeling/tasks.mjs b/bench/agent-modeling/tasks.mjs
index ae966b53..6cf2f6e6 100644
--- a/bench/agent-modeling/tasks.mjs
+++ b/bench/agent-modeling/tasks.mjs
@@ -519,6 +519,18 @@ recipe is what gets graded.`,
{ kind: 'assetReach', endLabel: 'Palm2.R', from: [-1.3, 2.6, 0.8], to: [-1, 1.7, 1.1] },
],
},
+ {
+ id: 'robot-ragdoll',
+ assets: true,
+ prompt: `The asset catalog holds an imported robot character, about 3 m tall. Create a scene from it with its root lifted so its
+feet start 2 m above the ground plane (world height 0), and make it fall limp: it drops, hits the ground and collapses in a
+heap within 4 seconds, its body lying low on the ground at the end. When it is finished, call scene_export_recipe once: the
+exported recipe is what gets graded.`,
+ ownPreamble: true,
+ checks: [
+ { kind: 'assetRagdoll', minimumDrop: 1.5, minimumDuration: 3, floorTolerance: 0.3, maximumHeight: 1.6 },
+ ],
+ },
...KETTLE_TASKS,
...DESK_TASKS,
{
diff --git a/bench/size/budgets.json b/bench/size/budgets.json
index e04b838f..4ca133f0 100644
--- a/bench/size/budgets.json
+++ b/bench/size/budgets.json
@@ -33,9 +33,9 @@
"entry:path-tracer": 13800,
"entry:texture-set": 900,
"entry:agent-scene": 65300,
- "entry:agent-scene+lazy": 217300,
+ "entry:agent-scene+lazy": 217400,
"entry:agent-asset": 96700,
- "entry:agent-asset+lazy": 228400,
+ "entry:agent-asset+lazy": 229200,
"entry:hdri": 3300,
"entry:camera-effects": 8600,
"entry:render-passes": 1700,
diff --git a/docs/parity.md b/docs/parity.md
index 06ffb5df..5d369717 100644
--- a/docs/parity.md
+++ b/docs/parity.md
@@ -133,7 +133,7 @@ To move to a new Blender release, run `node scripts/parity-manual-snapshot.mjs`.
| Grease Pencil | out of scope | Decided in issue #23. | | |
| Animation & Rigging > Animation Editors | out of scope | Interface for a mouse. | | |
| Animation & Rigging > Keyframes | partial | Linear, step, smooth and Hermite curves with deterministic seeks. There are no other easing types or keying sets. | [animation](../tests/animation.test.js) | |
-| Animation & Rigging > Armatures > Bones | partial | Recipe `armatures` list bones with a name, parent, head and tail, and each bone is a recipe node that tracks and `motion.ik` address. No roll, bone shapes or custom properties. | [rigging](../tests/rigging.test.js) | #46 |
+| Animation & Rigging > Armatures > Bones | partial | Recipe `armatures` list bones with a name, parent, head and tail, and each bone is a recipe node that tracks, `motion.ik` and a physics ragdoll (#96, `tests/ragdoll.test.js`: a capsule body per bone, spherical joints without swing limits, a seekable baked fall, at most 48 bones) address. No roll, bone shapes or custom properties. | [rigging](../tests/rigging.test.js) | #46 |
| Animation & Rigging > Armatures > Properties | partial | An armature has an id, a parent node, a transform, an optional bone-ID prefix and a `humanoid` or `quadruped` preset fitted to a mesh node or to bounds. No display settings or bone collections. | [rigging](../tests/rigging.test.js) | #46 |
| Animation & Rigging > Armatures > Structure | partial | Imported rigs keep their hierarchy, and recipes author one. A rig exports to GLB with its bones and a baked walk clip; Blender 5.2 opens it as 1 armature, 21 bones, 14 vertex-grouped meshes and 1 action. | [gltf](../tests/gltf.test.js), [rigging](../tests/rigging.test.js) | #46 |
| Animation & Rigging > Armatures > Skinning | partial | Four-influence GPU skinning, with automatic binding by distance to the bone segments. Not heat diffusion, so two limbs that pass close can share weights; `scene_inspect` reports unweighted vertices, bones with no vertices and joint axis problems. | [skinning](../tests/skinning.test.js), [rigging](../tests/rigging.test.js) | #46 |
diff --git a/docs/physics.md b/docs/physics.md
index f84fc761..e1b2f6a2 100644
--- a/docs/physics.md
+++ b/docs/physics.md
@@ -385,6 +385,24 @@ Rapier is loaded on demand, an optional peer dependency. The MCP runtime serves
`scene_inspect` returns a `physics` report: per body the `finalPosition`, `finalSpeed` and `restsAtTime` (null while moving), the `contacts` between bodies with `firstTime`, `count` and `touchingAtEnd`, and the sensor `enter` and `leave` events with times.
An agent can check that a ball came to rest on a mesh from these numbers, without a picture.
+## Recipe ragdoll
+
+Part of issue #96. A ragdoll binds one physics body to every bone of a rig and writes the simulated result back as the local pose of each bone node, so skinning, export and seeking work as for any other pose.
+
+```json
+{ "physics": { "duration": 4, "bodies": [{ "node": "floor", "type": "fixed" }], "ragdoll": { "armature": "rig" } } }
+```
+
+For a recipe armature, `ragdoll.armature` names it. The optional `density`, `friction`, `restitution` and `layer` (default 1) apply to every bone. An imported asset takes `physics: { duration, floor, gravity, ragdoll }` in its own recipe (`set-physics` edits it); every joint of the asset becomes a bone, `floor` is a world height (default 0) and the character falls from the pose its clip and overrides give at the start.
+
+- Each bone is one capsule from its head to its tail, joined to its parent bone by a spherical joint. Bones never touch each other, so the capsules at a joint do not push apart. The lightest bone weighs a quarter of the longest, because a joint between a very light and a very heavy body blows up the solver.
+- The bake is a table of poses by time, recorded at 60 frames a second for at most 10 seconds and 48 bones. A seek to the same time gives the same bytes, and an unchanged section on an unchanged rig reuses the last bake.
+- Joints have no swing limits, and Rapier has none for a spherical joint. Linear blend skinning inverts where neighbouring joints turn about 180 degrees apart, and the engine refuses such a pose, so a posed bone stays within 120 degrees of its rest pose. In a deep fold the drawn bone can therefore differ from its collider, and a joint can sit below the floor by a fraction of a bone length. The report is read from the colliders.
+- Rigs need uniform scale above the bones (a scale of 100 on an armature node is fine). A bone with no length, more than 48 bones, a bone with a translation or rotation track in the same recipe, or a missing floor body in a scene recipe is refused or falls forever.
+- On an asset, physics wins over motion tracks and `ik` on joints.
+- `scene_inspect` returns `physics.ragdoll`: `bones`, `lowestY`, `highestY`, `fastestFinalSpeed` and `restsAtTime` (null while still moving). Read those instead of a picture.
+- Rapier stays an optional peer. A recipe without `physics` loads none of this code.
+
## Recipe cloth
A recipe `cloth` section records deformable sheets with a position-based solver (`src/cloth.js`, `src/agent-cloth.js`). It needs no peer dependency and loads on demand with the `cloth` module, so a scene without cloth pays nothing.
diff --git a/skills/build-67js-scene/SKILL.md b/skills/build-67js-scene/SKILL.md
index 22a5f517..de63a72a 100644
--- a/skills/build-67js-scene/SKILL.md
+++ b/skills/build-67js-scene/SKILL.md
@@ -47,7 +47,7 @@ Use `simplify-code` and `engineering-workflows` for implementation.
- Agent tool calls use the installed `67js-mcp` stdio server from release `0.5.0` onward. Read `docs/mcp.md` for launch and PNG feedback.
- Agent render jobs use `docs/agent-render-jobs.md`. Check source versus published support, configure a private store and poll until terminal.
- A character or creature that must move (a walker, a quadruped) gets a recipe `armatures` entry and a `skin` on each mesh node: `{ "id": "rig", "preset": "humanoid", "fit": { "bounds": { "min": [...], "max": [...] } } }` (or `fit.node`), then `skin: { "armature": "rig" }` on every body part. Bones are nodes named `hips`, `leftUpperLeg`, `leftLowerLeg` and so on, so rotation tracks and `motion.ik` address them directly (rotation is local, about the bone head; positive X swings a hanging limb backward). Build the mesh at rest in the preset's pose (facing +Z, arms down), and read `rig` in `scene_inspect`: unweighted vertices, bones with no vertices, joint axis problems. Weights are by distance to the bone segments, so give limbs the same loops you want to bend. See "Authored rigs" in `docs/agent-motion.md`.
-- Things that fall, pile up or rest on an authored mesh (dropped objects, a ball in a bowl, a trigger zone) use the recipe `physics` section: bodies on root node IDs, `shape: 'trimesh'` on a fixed body so objects follow the mesh, `sensor: true` for triggers, `layer` and `collidesWith` for masks. Seek with `motionTime` like motion, and read `physics` from `scene_inspect` (resting times, contacts, sensor events) instead of guessing from a picture. Needs the optional peer `@dimforge/rapier3d-compat`; bodies bound to bones for ragdolls are not supported. See "Recipe physics" in the checkout's `docs/physics.md`.
+- Things that fall, pile up or rest on an authored mesh (dropped objects, a ball in a bowl, a trigger zone) use the recipe `physics` section: bodies on root node IDs, `shape: 'trimesh'` on a fixed body so objects follow the mesh, `sensor: true` for triggers, `layer` and `collidesWith` for masks. Seek with `motionTime` like motion, and read `physics` from `scene_inspect` (resting times, contacts, sensor events) instead of guessing from a picture. Needs the optional peer `@dimforge/rapier3d-compat`; a limp character uses `physics.ragdoll` (`{ armature }` for a recipe armature; an imported asset takes `physics: { duration, floor, ragdoll: {} }` and falls from its current pose onto a floor at world height `floor`), needs a floor body in a scene recipe, and reports `physics.ragdoll` (`lowestY`, `highestY`, `restsAtTime`); joints have no swing limits. See "Recipe physics" in the checkout's `docs/physics.md`.
- Flags, curtains, capes and cloths draped over props use the recipe `cloth` section: a `grid` geometry node (flat sheet in XY, `segments` up to 64) listed in `sheets` with `pin` edges (`top`, `left`, a corner...), `wind` in m/s, and fixed `colliders` (`ball` or `box` fitted to their node). Seek with `motionTime`; a flag needs wind along its length (+x for a left pin), not across it. No peer needed, no self collision, no soft bodies. Units, defaults and limits are in `scene_capabilities` under `cloth`; see "Recipe cloth" in `docs/physics.md`.
- Sparks, dust, embers, confetti and fur use the recipe `particles` section: a root node whose small low-poly geometry (a box) is the particle, in an emitter system with `seed`, `count` (at most 2000), `rate` (omit for one burst), `lifetime`, `speed`, `spread`, `drag`, `floor` and an `emitter` shape; a system with `type: "hair"` grows strands from a `surface` node. Seek with `motionTime`; the same seed and time give the same particles. The node transform does not move particles, and there is no collision beyond the floor, bounce or per-particle colour. Fields and limits are in `scene_capabilities` under `particles`; see "Recipe particles and hair" in `docs/physics.md`. Smoke, fire and browser liquid are not supported.
- A closed room, or any scene lit by point lights, is dark where the light does not reach. Add the recipe `bake` section (`{ "preset": "standard" }`, or `draft` to try fast, `fine` to finish) or the `set-bake` operation: it writes bounced light into lightmaps when the scene builds and reruns only when parts, lights, materials or the bake change. `scene_inspect` shows `bake.seconds` and `bake.skipped` (parts with maps, patterns, emission, alpha, skins or morphs are left as they were). It bakes the rest pose and no spot or area lights. Read `docs/light-bake.md`.
diff --git a/src/agent-asset.js b/src/agent-asset.js
index c2c73544..d8a6257a 100644
--- a/src/agent-asset.js
+++ b/src/agent-asset.js
@@ -32,8 +32,9 @@ export const AGENT_ASSET_CAPABILITIES = Object.freeze({
format: '67js.asset', schemaVersion: 1, fixedTopology: false,
operations: Object.freeze([
'set-camera', 'set-environment', 'set-effects', 'set-shadow',
- 'set-root', 'set-animation', 'set-material', 'set-asset-node', 'set-motion', 'edit-mesh',
+ 'set-root', 'set-animation', 'set-material', 'set-asset-node', 'set-motion', 'set-physics', 'edit-mesh',
]),
+ ragdoll: 'physics {duration, floor?, ragdoll {}}: joints fall limp onto a floor at world height floor (default 0)',
boundsKind: 'authored-base-world',
});
@@ -314,6 +315,8 @@ export function createAgentAssetScene(asset, inputRecipe) {
let matrices = [];
let revision = 0;
let sampler = null;
+ let physicsSampler = null;
+ let physicsBake = null;
let layerEvaluator = null;
let motionTime = null;
let sampledCamera;
@@ -409,7 +412,7 @@ export function createAgentAssetScene(asset, inputRecipe) {
function normalize(input) {
const candidate = copiedJson(input);
- knownKeys(candidate, ['format', 'schemaVersion', 'assetId', 'camera', ...LOOK_FIELDS, 'root', 'animation', 'materialOverrides', 'nodeOverrides', 'motion', 'meshEdits'], 'asset recipe');
+ knownKeys(candidate, ['format', 'schemaVersion', 'assetId', 'camera', ...LOOK_FIELDS, 'root', 'animation', 'materialOverrides', 'nodeOverrides', 'motion', 'physics', 'meshEdits'], 'asset recipe');
if (candidate.format !== '67js.asset' || candidate.schemaVersion !== 1 ||
typeof candidate.assetId !== 'string' || candidate.assetId.toLowerCase() !== canonicalAssetId) {
throw new RangeError('Expected the bound 67js.asset schemaVersion 1 assetId.');
@@ -479,6 +482,9 @@ export function createAgentAssetScene(asset, inputRecipe) {
throw new RangeError('Motion ik needs a uniform asset root scale.');
}
result.motion = agentMotion.normalizeAgentMotion(candidate.motion, motionRecipe(result));
+ if (candidate.physics !== undefined && candidate.physics !== null) {
+ result.physics = agentSceneModule('physics').normalizeAssetPhysics(candidate.physics);
+ }
return copiedJson(result);
}
@@ -543,6 +549,25 @@ export function createAgentAssetScene(asset, inputRecipe) {
return nodeOverrides;
}
+ /** A ragdoll bake costs a solver run, so an unchanged section on an unchanged starting pose reuses the last one. */
+ function stageAssetPhysics(candidate) {
+ if (!candidate.physics) return null;
+ const key = JSON.stringify([candidate.physics, candidate.animation, candidate.nodeOverrides, candidate.root]);
+ if (physicsBake?.key !== key) {
+ const root = candidate.root;
+ const rootMatrix = mat4.fromRotationTranslationScale(mat4.create(), root.rotation, root.translation, root.scale);
+ const startingPoses = stagedNodePoses(candidate.animation, candidate.nodeOverrides);
+ physicsBake = { key, sampler: agentSceneModule('physics').bakeAssetRagdoll(candidate.physics, [...sourceNodes.values()], startingPoses, rootMatrix) };
+ }
+ return physicsBake.sampler;
+ }
+
+ /** Joint poses from the ragdoll at a time. Physics holds its last pose after its duration. */
+ function ragdollOverrides(stagedPhysics, time) {
+ const patches = stagedPhysics.sample(Math.min(time, stagedPhysics.duration));
+ return [...patches].map(([id, patch]) => ({ id, translation: Array.from(patch.translation), rotation: Array.from(patch.rotation) }));
+ }
+
function publish(input, autoFrame = false, increment = true, transientTime = undefined, transientAnimation = undefined) {
let candidate = transientTime === undefined ? normalize(input) : recipe;
if (transientAnimation !== undefined) {
@@ -550,11 +575,12 @@ export function createAgentAssetScene(asset, inputRecipe) {
}
let stagedSampler = transientTime === undefined ? agentMotion.compileAgentMotion(candidate.motion, motionRecipe(candidate)) : sampler;
const stagedLayers = transientTime === undefined ? compileLayers(candidate.motion) : layerEvaluator;
- const targetTime = transientTime === undefined ? (candidate.motion ? 0 : null) : transientTime;
- if (targetTime !== null && !stagedSampler) {
- throw new RangeError('The asset has no authored motion to sample.');
+ const stagedPhysics = transientTime === undefined ? stageAssetPhysics(candidate) : physicsSampler;
+ const targetTime = transientTime === undefined ? (candidate.motion || candidate.physics ? 0 : null) : transientTime;
+ if (targetTime !== null && !stagedSampler && !stagedPhysics) {
+ throw new RangeError('The asset has no authored motion or physics to sample.');
}
- let sampled = targetTime === null ? null : stagedSampler.sample(targetTime);
+ let sampled = targetTime === null ? null : stagedSampler?.sample(targetTime);
if (asset.parts.length !== records.length) {
throw new RangeError('Decoded part membership must remain fixed.');
}
@@ -577,6 +603,11 @@ export function createAgentAssetScene(asset, inputRecipe) {
nodeOverrides.set(override.id, { ...nodeOverrides.get(override.id), ...override });
}
}
+ if (targetTime !== null && stagedPhysics) {
+ for (const override of ragdollOverrides(stagedPhysics, targetTime)) {
+ nodeOverrides.set(override.id, { ...nodeOverrides.get(override.id), ...override });
+ }
+ }
let transaction;
try {
transaction = asset.stagePose({ animation: candidate.animation, nodeOverrides: [...nodeOverrides.values()], morphWeights });
@@ -604,7 +635,7 @@ export function createAgentAssetScene(asset, inputRecipe) {
candidate.camera = framedCamera(framingBounds(records.map(record => geometryInfoOf(record, stagedEdits)), stagedMatrices));
candidate = normalize(candidate);
stagedSampler = agentMotion.compileAgentMotion(candidate.motion, motionRecipe(candidate));
- sampled = targetTime === null ? null : stagedSampler.sample(targetTime);
+ sampled = targetTime === null ? null : stagedSampler?.sample(targetTime);
}
const stagedMaterials = new Map([...materialRecords].map(([id, record]) => [id, { ...record.baseline }]));
for (const override of candidate.materialOverrides) {
@@ -644,6 +675,7 @@ export function createAgentAssetScene(asset, inputRecipe) {
if (transientTime === undefined) {
recipe = candidate;
sampler = stagedSampler;
+ physicsSampler = stagedPhysics;
layerEvaluator = stagedLayers;
}
materialSnapshots = stagedMaterials;
@@ -776,6 +808,12 @@ export function createAgentAssetScene(asset, inputRecipe) {
throw new TypeError('set-motion requires a motion record or explicit null.');
}
candidate.motion = operation.motion;
+ } else if (operation.type === 'set-physics') {
+ knownKeys(operation, ['type', 'physics'], 'operation');
+ if (!Object.hasOwn(operation, 'physics')) {
+ throw new TypeError('set-physics requires physics; use null to clear it.');
+ }
+ candidate.physics = operation.physics;
} else if (operation.type === 'set-asset-node') {
knownKeys(operation, ['type', 'id', ...ROOT_FIELDS], 'operation');
if (!sourceNodes.has(operation.id)) {
@@ -904,6 +942,7 @@ export function createAgentAssetScene(asset, inputRecipe) {
counts: { nodes: parts.length, parts: parts.length, geometries: activeGeometries.size, materials: materials.size, vertices },
geometryBytes, animation: structuredClone(recipe.animation),
motion: recipe.motion ? { duration: recipe.motion.duration, loop: recipe.motion.loop, tracks: recipe.motion.tracks.length, layers: recipe.motion.layers?.length ?? 0, time: motionTime } : null,
+ physics: physicsSampler ? physicsSampler.report() : null,
animations: asset.animations.map((clip, index) => ({ id: index, label: String(clip.name ?? `Clip ${index}`).slice(0, 256), duration: clip.duration })),
nodes, offset, truncated: selected.length > offset + nodes.length,
};
diff --git a/src/agent-physics.js b/src/agent-physics.js
index 9072e221..72df7c79 100644
--- a/src/agent-physics.js
+++ b/src/agent-physics.js
@@ -1,3 +1,6 @@
+import { mat4, vec3 } from 'gl-matrix';
+import { restWorldMatrix, boneTails, boneNodeId } from './rig.js';
+import { createRagdoll, ragdollPatches, ragdollReport } from './ragdoll.js';
import { bakePhysicsScene, loadPhysicsEngine, physicsEngineLoaded, setPhysicsModuleLoader } from './physics.js';
export { loadPhysicsEngine, physicsEngineLoaded, setPhysicsModuleLoader };
@@ -18,7 +21,8 @@ const SHAPES = ['box', 'ball', 'capsule', 'convex', 'trimesh'];
const JOINT_TYPES = ['spherical', 'revolute', 'prismatic', 'fixed'];
const BODY_FIELDS = ['node', 'type', 'shape', 'mass', 'density', 'friction', 'restitution', 'sensor', 'velocity', 'angularVelocity', 'layer', 'collidesWith'];
const JOINT_FIELDS = ['type', 'bodyA', 'bodyB', 'anchorA', 'anchorB', 'axis', 'limits'];
-const PHYSICS_FIELDS = ['duration', 'gravity', 'bodies', 'joints'];
+const PHYSICS_FIELDS = ['duration', 'gravity', 'bodies', 'joints', 'ragdoll'];
+const RAGDOLL_FIELDS = ['armature', 'density', 'friction', 'restitution', 'layer'];
function knownKeys(value, fields, label) {
if (!value || Object.getPrototypeOf(value) !== Object.prototype) {
@@ -134,6 +138,44 @@ function normalizeJoint(input, bodyNodeIds) {
return joint;
}
+function normalizeRagdoll(input, recipe, motionNodeIds) {
+ knownKeys(input, RAGDOLL_FIELDS, 'physics ragdoll');
+ const armature = (recipe.armatures ?? []).find(candidate => candidate.id === input.armature);
+ if (!armature) {
+ throw new RangeError(`Physics ragdoll armature was not found: ${JSON.stringify(String(input.armature).slice(0, 48))}. Add it to the recipe armatures.`);
+ }
+ const ragdoll = { armature: armature.id };
+ if (input.density !== undefined) ragdoll.density = finiteNumber(input.density, 'Ragdoll density', 1e-6, 1e9);
+ if (input.friction !== undefined) ragdoll.friction = finiteNumber(input.friction, 'Ragdoll friction', 0, 100);
+ if (input.restitution !== undefined) ragdoll.restitution = finiteNumber(input.restitution, 'Ragdoll restitution', 0, 1);
+ if (input.layer !== undefined) ragdoll.layer = Math.trunc(finiteNumber(input.layer, 'Ragdoll layer', 0, MAX_LAYER));
+ for (const bone of armature.bones) {
+ if (motionNodeIds.has(boneNodeId(armature, bone.name))) {
+ throw new RangeError(`Bone ${bone.name} has a motion translation or rotation track and a ragdoll. Pick one.`);
+ }
+ }
+ ragdollForRecipe(ragdoll, recipe);
+ return ragdoll;
+}
+
+/** The ragdoll of an armature, placed from the recipe's rest pose. Throws on a bone without length or too many bones. */
+function ragdollForRecipe(ragdoll, recipe) {
+ const armature = recipe.armatures.find(candidate => candidate.id === ragdoll.armature);
+ const nodesById = new Map(recipe.nodes.map(node => [node.id, node]));
+ const armatureWorld = restWorldMatrix(armature.id, nodesById);
+ const tails = boneTails(armature);
+ const bones = armature.bones.map((bone, index) => {
+ const id = boneNodeId(armature, bone.name);
+ return {
+ id, parentId: bone.parent === null ? null : boneNodeId(armature, bone.parent),
+ worldMatrix: restWorldMatrix(id, nodesById), parentWorldMatrix: restWorldMatrix(nodesById.get(id).parent, nodesById),
+ tail: Array.from(vec3.transformMat4(vec3.create(), tails[index], armatureWorld)),
+ };
+ });
+ const { armature: armatureId, ...options } = ragdoll;
+ return createRagdoll(bones, options);
+}
+
/** Validate a recipe physics section against its nodes. Returns the plain, bounded form stored in the recipe. */
export function normalizeAgentPhysics(input, recipe) {
if (input === null || input === undefined) {
@@ -146,11 +188,12 @@ export function normalizeAgentPhysics(input, recipe) {
.filter(track => track.kind === 'node' && (track.property === 'translation' || track.property === 'rotation'))
.map(track => track.id));
const claimedNodes = new Set();
- const bodies = boundedArray(input.bodies, MAX_BODIES, 'Physics bodies').map(body => normalizeBody(body, recipeNodes, motionNodeIds, claimedNodes));
- if (!bodies.length) {
+ const bodies = boundedArray(input.bodies ?? [], MAX_BODIES, 'Physics bodies').map(body => normalizeBody(body, recipeNodes, motionNodeIds, claimedNodes));
+ if (!bodies.length && input.ragdoll === undefined) {
throw new RangeError('Physics needs at least one body. Use null to clear it.');
}
const result = { duration, bodies };
+ if (input.ragdoll !== undefined) result.ragdoll = normalizeRagdoll(input.ragdoll, recipe, motionNodeIds);
if (input.gravity !== undefined) result.gravity = numberList(input.gravity, 3, 'Physics gravity');
if (input.joints !== undefined) {
result.joints = boundedArray(input.joints, MAX_JOINTS, 'Physics joints').map(joint => normalizeJoint(joint, claimedNodes));
@@ -222,7 +265,7 @@ function layerBits(layers) {
return layers.reduce((bits, layer) => bits | (1 << layer), 0);
}
-function physicsDefinition(physics, recipe, geometries) {
+function physicsDefinition(physics, recipe, geometries, ragdoll) {
const nodes = new Map(recipe.nodes.map(node => [node.id, node]));
const definition = { bodies: [], colliders: [], joints: [] };
if (physics.gravity) definition.gravity = physics.gravity;
@@ -248,6 +291,11 @@ function physicsDefinition(physics, recipe, geometries) {
}
definition.colliders.push(collider);
}
+ if (ragdoll) {
+ definition.bodies.push(...ragdoll.definition.bodies);
+ definition.colliders.push(...ragdoll.definition.colliders);
+ definition.joints.push(...ragdoll.definition.joints);
+ }
(physics.joints ?? []).forEach((joint, index) => definition.joints.push({ name: `joint-${index}`, ...joint }));
return definition;
}
@@ -296,22 +344,38 @@ function bodyReport(scene, physics) {
});
}
+/** Identity of a bake: the section, the nodes it moves and the geometry under them. A ragdoll also reads the rig. */
+export function physicsBakeKey(recipe, geometryRecords) {
+ const bodyNodes = recipe.nodes.filter(node => recipe.physics.bodies.some(body => body.node === node.id));
+ const rig = recipe.physics.ragdoll ? [recipe.nodes, recipe.armatures] : null;
+ return JSON.stringify([recipe.physics, bodyNodes, bodyNodes.map(node => geometryRecords.get(node.geometry).signature), rig]);
+}
+
/**
* Bake the physics section with Rapier. The solver must already be loaded (see loadPhysicsEngine).
* The result is a pure function of time: `sample(t)` returns node patches and a seek never replays the solver.
*/
export function bakeAgentPhysics(physics, recipe, geometries) {
- const definition = physicsDefinition(physics, recipe, geometries);
+ const ragdoll = physics.ragdoll ? ragdollForRecipe(physics.ragdoll, recipe) : null;
+ const definition = physicsDefinition(physics, recipe, geometries, ragdoll);
const frameCount = Math.round(physics.duration * FRAMES_PER_SECOND) + 1;
const scene = bakePhysicsScene(definition, { frameCount, timestep: 1 / FRAMES_PER_SECOND, maxColliderTriangles: MAX_TRIMESH_TRIANGLES, maxHullPoints: MAX_HULL_POINTS });
const patches = new Map(physics.bodies.map(body => [body.node, { translation: new Float64Array(3), rotation: new Float64Array(4) }]));
+ const ragdollTable = ragdoll ? ragdollPatches(ragdoll) : new Map();
+ for (const [nodeId, patch] of ragdollTable) patches.set(nodeId, patch);
const pose = new Float32Array(scene.bodyNames.length * 7);
+ const readBodyPose = nodeId => {
+ const offset = scene.bodyIndex(nodeId) * 7;
+ return { translation: pose.subarray(offset, offset + 3), rotation: pose.subarray(offset + 3, offset + 7) };
+ };
let reportCache = null;
return Object.freeze({
duration: physics.duration,
sample(time) {
scene.sample(time, pose);
+ ragdoll?.writePatches(readBodyPose, ragdollTable);
for (const [nodeId, patch] of patches) {
+ if (ragdollTable.has(nodeId)) continue;
const offset = scene.bodyIndex(nodeId) * 7;
patch.translation.set(pose.subarray(offset, offset + 3));
patch.rotation.set(pose.subarray(offset + 3, offset + 7));
@@ -324,8 +388,105 @@ export function bakeAgentPhysics(physics, recipe, geometries) {
duration: physics.duration, frames: scene.frameCount, gravity: physics.gravity ?? [0, -9.81, 0],
bodies: bodyReport(scene, physics), ...contactReport(scene, physics),
eventsTruncated: scene.contactEventsTruncated,
+ ...(ragdoll ? { ragdoll: ragdollReport(ragdoll, scene) } : {}),
};
return structuredClone(reportCache);
},
});
}
+
+const ASSET_PHYSICS_FIELDS = ['duration', 'gravity', 'floor', 'ragdoll'];
+const FLOOR_HALF_EXTENT = 200;
+const FLOOR_HALF_THICKNESS = 0.5;
+
+/** Validate the physics of an imported asset: a ragdoll of its joints falling onto a floor at a world height. */
+export function normalizeAssetPhysics(input) {
+ knownKeys(input, ASSET_PHYSICS_FIELDS, 'asset physics');
+ const physics = { duration: finiteNumber(input.duration, 'Physics duration', 0.1, MAX_DURATION_SECONDS) };
+ if (input.gravity !== undefined) physics.gravity = numberList(input.gravity, 3, 'Physics gravity');
+ if (input.floor !== undefined) physics.floor = finiteNumber(input.floor, 'Physics floor', -1e6, 1e6);
+ if (input.ragdoll === undefined) {
+ throw new TypeError('Asset physics needs a ragdoll section: it is what moves the asset joints.');
+ }
+ knownKeys(input.ragdoll, RAGDOLL_FIELDS.filter(field => field !== 'armature'), 'physics ragdoll');
+ const ragdoll = {};
+ for (const [field, minimum, maximum] of [['density', 1e-6, 1e9], ['friction', 0, 100], ['restitution', 0, 1]]) {
+ if (input.ragdoll[field] !== undefined) ragdoll[field] = finiteNumber(input.ragdoll[field], `Ragdoll ${field}`, minimum, maximum);
+ }
+ if (input.ragdoll.layer !== undefined) ragdoll.layer = Math.trunc(finiteNumber(input.ragdoll.layer, 'Ragdoll layer', 0, MAX_LAYER));
+ return { ...physics, ragdoll };
+}
+
+function worldMatrixOfNode(node, nodesById, localMatrices, worldMatrices, rootMatrix) {
+ if (worldMatrices.has(node.id)) return worldMatrices.get(node.id);
+ const parentMatrix = node.parent === null ? rootMatrix : worldMatrixOfNode(nodesById.get(node.parent), nodesById, localMatrices, worldMatrices, rootMatrix);
+ const world = mat4.multiply(mat4.create(), parentMatrix, localMatrices.get(node.id));
+ worldMatrices.set(node.id, world);
+ return world;
+}
+
+function nearestJointAncestor(node, nodesById) {
+ let current = node.parent === null ? undefined : nodesById.get(node.parent);
+ while (current && !current.joint) current = current.parent === null ? undefined : nodesById.get(current.parent);
+ return current?.id ?? null;
+}
+
+function assetRagdollBones(nodes, nodePoses, rootMatrix) {
+ const nodesById = new Map(nodes.map(node => [node.id, node]));
+ const localMatrices = new Map(nodePoses.map(pose => [pose.id, mat4.fromRotationTranslationScale(mat4.create(), pose.rotation, pose.translation, pose.scale)]));
+ const worldMatrices = new Map();
+ const joints = nodes.filter(node => node.joint);
+ const lockedJoint = joints.find(node => !node.editable);
+ if (lockedJoint) {
+ throw new RangeError(`Joint ${lockedJoint.id} cannot be edited (mirrored or sheared), so a ragdoll cannot drive it.`);
+ }
+ const depthOf = node => (node.parent === null ? 0 : 1 + depthOf(nodesById.get(node.parent)));
+ const ordered = joints.map(node => ({ node, depth: depthOf(node) })).sort((first, second) => first.depth - second.depth).map(entry => entry.node);
+ const worlds = new Map(ordered.map(node => [node.id, worldMatrixOfNode(node, nodesById, localMatrices, worldMatrices, rootMatrix)]));
+ const skeleton = { bones: ordered.map(node => ({
+ name: node.id, parent: nearestJointAncestor(node, nodesById), head: Array.from(mat4.getTranslation(vec3.create(), worlds.get(node.id))),
+ })) };
+ const tails = boneTails(skeleton);
+ return ordered.map((node, index) => ({
+ id: node.id, parentId: skeleton.bones[index].parent, worldMatrix: worlds.get(node.id), tail: tails[index],
+ parentWorldMatrix: node.parent === null ? rootMatrix : worldMatrixOfNode(nodesById.get(node.parent), nodesById, localMatrices, worldMatrices, rootMatrix),
+ }));
+}
+
+/**
+ * Bake a ragdoll of an imported asset's joints, starting from the pose the asset has now (clip and overrides) and falling
+ * onto a floor at world height `physics.floor`. `nodes` are the asset's source nodes, `nodePoses` their local poses and
+ * `rootMatrix` the asset root. The sampler returns local translation and rotation per joint, a pure function of time.
+ */
+export function bakeAssetRagdoll(physics, nodes, nodePoses, rootMatrix) {
+ const ragdoll = createRagdoll(assetRagdollBones(nodes, nodePoses, rootMatrix), physics.ragdoll);
+ const floorHeight = physics.floor ?? 0;
+ const definition = {
+ bodies: [{ name: 'ragdoll-floor', type: 'fixed', translation: [0, floorHeight - FLOOR_HALF_THICKNESS, 0] }, ...ragdoll.definition.bodies],
+ colliders: [
+ { name: 'ragdoll-floor', body: 'ragdoll-floor', shape: 'cuboid', halfExtents: [FLOOR_HALF_EXTENT, FLOOR_HALF_THICKNESS, FLOOR_HALF_EXTENT] },
+ ...ragdoll.definition.colliders,
+ ],
+ joints: ragdoll.definition.joints,
+ ...(physics.gravity ? { gravity: physics.gravity } : {}),
+ };
+ const frameCount = Math.round(physics.duration * FRAMES_PER_SECOND) + 1;
+ const scene = bakePhysicsScene(definition, { frameCount, timestep: 1 / FRAMES_PER_SECOND, maxColliderTriangles: MAX_TRIMESH_TRIANGLES, maxHullPoints: MAX_HULL_POINTS });
+ const patches = ragdollPatches(ragdoll);
+ const pose = new Float32Array(scene.bodyNames.length * 7);
+ const readBodyPose = nodeId => {
+ const offset = scene.bodyIndex(nodeId) * 7;
+ return { translation: pose.subarray(offset, offset + 3), rotation: pose.subarray(offset + 3, offset + 7) };
+ };
+ return Object.freeze({
+ duration: physics.duration,
+ sample(time) {
+ scene.sample(time, pose);
+ ragdoll.writePatches(readBodyPose, patches);
+ return patches;
+ },
+ report() {
+ return { duration: physics.duration, frames: scene.frameCount, gravity: physics.gravity ?? [0, -9.81, 0], ragdoll: ragdollReport(ragdoll, scene) };
+ },
+ });
+}
diff --git a/src/agent-scene-capabilities.js b/src/agent-scene-capabilities.js
index 189e4586..1a34ff16 100644
--- a/src/agent-scene-capabilities.js
+++ b/src/agent-scene-capabilities.js
@@ -195,7 +195,8 @@ export const AGENT_SCENE_CAPABILITIES = Object.freeze({
bodyTypes: Object.freeze(['dynamic', 'fixed', 'kinematic']),
shapes: Object.freeze(['box', 'ball', 'capsule', 'convex', 'trimesh']),
jointTypes: Object.freeze(['spherical', 'revolute', 'prismatic', 'fixed']),
- sensors: true, collisionLayers: 16, boneBodies: false,
+ sensors: true, collisionLayers: 16,
+ ragdoll: 'physics.ragdoll {armature}: limp capsule per bone; needs a floor',
limits: Object.freeze({ maxBodies: 64, maxJoints: 64, maxDuration: 10, framesPerSecond: 60, maxTrimeshTriangles: 20000, maxHullPoints: 2048 }),
}),
// Recipe cloth: a position-based solver (no peer dependency) records any root mesh node as a deformable sheet.
diff --git a/src/agent-scene.js b/src/agent-scene.js
index 9fe274d6..261fd748 100644
--- a/src/agent-scene.js
+++ b/src/agent-scene.js
@@ -1036,8 +1036,7 @@ export function createAgentScene(input, inputLimits = {}) {
if (!recipe.physics) {
return null;
}
- const bodyNodes = recipe.nodes.filter(node => recipe.physics.bodies.some(body => body.node === node.id));
- const key = JSON.stringify([recipe.physics, bodyNodes, bodyNodes.map(node => geometryRecords.get(node.geometry).signature)]);
+ const key = agentSceneModule('physics').physicsBakeKey(recipe, geometryRecords);
if (physicsBake?.key !== key) {
const geometries = new Map([...geometryRecords].map(([id, record]) => [id, record.geometry]));
physicsBake = { key, sampler: agentSceneModule('physics').bakeAgentPhysics(recipe.physics, recipe, geometries) };
diff --git a/src/ragdoll.js b/src/ragdoll.js
new file mode 100644
index 00000000..d5044a28
--- /dev/null
+++ b/src/ragdoll.js
@@ -0,0 +1,177 @@
+import { mat4, quat, vec3 } from 'gl-matrix';
+
+// A ragdoll gives every bone of a rig one capsule body, joined to its parent bone by a spherical joint, and hands the
+// simulated world poses back as the local pose of each bone node. The bones are plain nodes (armature bones or the
+// joints of an imported asset), so skinning, export and seeking need nothing new: the baked result is a table of local
+// transforms read by time, never a solver replay.
+//
+// Bones never collide with each other (a shared collision layer that excludes itself), which keeps the capsules that
+// meet at a joint from pushing apart. Joints have no swing limits, so a limb folds as far as the bodies allow.
+
+export const MAX_RAGDOLL_BONES = 48;
+const MIN_BONE_LENGTH = 1e-4;
+// A joint between a light and a heavy body makes the solver blow up, so the lightest bone weighs a quarter of the longest.
+const MIN_MASS_OF_LONGEST = 0.25;
+const RADIUS_OF_LENGTH = 0.2;
+const ANGULAR_DAMPING = 3;
+// Linear blend skinning inverts a vertex where neighbouring joints turn past about 180 degrees from each other, and an
+// engine that refuses such a pose cannot play the fall. The posed joint therefore stays within this angle of its rest pose.
+const MAX_POSED_JOINT_ANGLE = (120 * Math.PI) / 180;
+const DEFAULT_LAYER = 1;
+const ALL_LAYERS_MASK = 0xffff;
+const UNIFORM_SCALE_TOLERANCE = 1e-3;
+const UP = [0, 1, 0];
+
+function describeBone(bone) {
+ const worldMatrix = mat4.clone(bone.worldMatrix);
+ const rotation = quat.normalize(quat.create(), mat4.getRotation(quat.create(), worldMatrix));
+ const head = mat4.getTranslation(vec3.create(), worldMatrix);
+ const toLocal = vec3.transformQuat(vec3.create(), vec3.subtract(vec3.create(), bone.tail, head), quat.invert(quat.create(), rotation));
+ const length = vec3.length(toLocal);
+ if (!(length > MIN_BONE_LENGTH)) {
+ throw new RangeError(`Ragdoll bone ${bone.id} has no length: its head and tail coincide.`);
+ }
+ const uniformScale = uniformScaleOf(worldMatrix, bone.id);
+ const staticParent = bone.parentId === null ? frameOf(bone.parentWorldMatrix, bone.id) : null;
+ return { ...bone, head, rotation, uniformScale, staticParent, tailInBone: toLocal, length };
+}
+
+// A uniform scale keeps a bone's local pose a rotation and a translation; a stretched rig would shear.
+function uniformScaleOf(matrix, boneId) {
+ const scale = mat4.getScaling(vec3.create(), matrix);
+ if (Math.max(...scale) - Math.min(...scale) > UNIFORM_SCALE_TOLERANCE * Math.max(...scale)) {
+ throw new RangeError(`Ragdoll bone ${boneId} sits under a stretched (non-uniform) scale ${JSON.stringify(Array.from(scale))}; a ragdoll needs uniform scale above its bones.`);
+ }
+ return scale[0];
+}
+
+function frameOf(matrix, boneId) {
+ return {
+ translation: mat4.getTranslation(vec3.create(), matrix),
+ rotation: quat.normalize(quat.create(), mat4.getRotation(quat.create(), matrix)),
+ scale: uniformScaleOf(matrix, boneId),
+ };
+}
+
+function limitTurnFromRest(rotation, restLocalRotation) {
+ quat.normalize(rotation, rotation);
+ const turn = quat.multiply(quat.create(), quat.invert(quat.create(), restLocalRotation), rotation);
+ if (turn[3] < 0) quat.scale(turn, turn, -1);
+ const angle = 2 * Math.acos(Math.min(1, turn[3]));
+ if (angle <= MAX_POSED_JOINT_ANGLE) return;
+ const limitedTurn = quat.slerp(quat.create(), quat.create(), turn, MAX_POSED_JOINT_ANGLE / angle);
+ quat.multiply(rotation, restLocalRotation, limitedTurn);
+}
+
+function boneCollider(bone, options, longestLength) {
+ const radius = bone.length * RADIUS_OF_LENGTH;
+ const layer = options.layer ?? DEFAULT_LAYER;
+ const collider = {
+ name: bone.id, body: bone.id, shape: 'capsule', radius,
+ halfHeight: Math.max(bone.length / 2 - radius, radius * 0.01),
+ translation: Array.from(vec3.scale(vec3.create(), bone.tailInBone, 0.5)),
+ rotation: Array.from(quat.rotationTo(quat.create(), UP, vec3.normalize(vec3.create(), bone.tailInBone))),
+ groups: 1 << layer,
+ mask: options.collidesWith ?? (ALL_LAYERS_MASK & ~(1 << layer)),
+ mass: (options.density ?? 1) * Math.max(bone.length, longestLength * MIN_MASS_OF_LONGEST),
+ };
+ if (options.friction !== undefined) collider.friction = options.friction;
+ if (options.restitution !== undefined) collider.restitution = options.restitution;
+ return collider;
+}
+
+function boneJoint(bone, parent, index) {
+ const offset = vec3.subtract(vec3.create(), bone.head, parent.head);
+ const anchorInParent = vec3.transformQuat(vec3.create(), offset, quat.invert(quat.create(), parent.rotation));
+ return { name: `ragdoll-joint-${index}`, type: 'spherical', bodyA: parent.id, bodyB: bone.id, anchorA: Array.from(anchorInParent), anchorB: [0, 0, 0] };
+}
+
+/**
+ * Describe a ragdoll for the solver and read its result back as local node poses.
+ * Each bone is `{ id, parentId, worldMatrix, parentWorldMatrix, tail }`: `parentId` names the bone above it (or null),
+ * `worldMatrix` is its rest world matrix, `parentWorldMatrix` the rest world matrix of the node above it (used when
+ * `parentId` is null) and `tail` where the bone ends in world space. A parent must come before its children.
+ */
+export function createRagdoll(bones, options = {}) {
+ if (!Array.isArray(bones) || bones.length < 1 || bones.length > MAX_RAGDOLL_BONES) {
+ throw new RangeError(`A ragdoll needs 1 to ${MAX_RAGDOLL_BONES} bones; this rig has ${Array.isArray(bones) ? bones.length : 0}.`);
+ }
+ const described = bones.map(describeBone);
+ const byId = new Map(described.map(bone => [bone.id, bone]));
+ const longestLength = Math.max(...described.map(bone => bone.length));
+ const bodies = [];
+ const colliders = [];
+ const joints = [];
+ for (const bone of described) {
+ const parent = bone.parentId === null ? null : byId.get(bone.parentId);
+ if (bone.parentId !== null && !parent) {
+ throw new RangeError(`Ragdoll bone ${bone.id} names a parent that is not in the ragdoll: ${bone.parentId}.`);
+ }
+ bodies.push({ name: bone.id, type: 'dynamic', translation: Array.from(bone.head), rotation: Array.from(bone.rotation), angularDamping: ANGULAR_DAMPING });
+ colliders.push(boneCollider(bone, options, longestLength));
+ if (parent) joints.push(boneJoint(bone, parent, joints.length));
+ }
+ for (const bone of described) {
+ const parentRotation = bone.parentId === null ? bone.staticParent.rotation : byId.get(bone.parentId).rotation;
+ bone.restLocalRotation = quat.multiply(quat.create(), quat.invert(quat.create(), parentRotation), bone.rotation);
+ }
+ const offset = vec3.create();
+ return Object.freeze({
+ boneIds: described.map(bone => bone.id),
+ definition: { bodies, colliders, joints },
+ /** Write each bone's local translation and rotation, given the simulated world pose of its body. */
+ writePatches(readPose, patches) {
+ const sampledFrames = new Map();
+ for (const bone of described) {
+ const pose = readPose(bone.id);
+ const parent = bone.parentId === null ? bone.staticParent : sampledFrames.get(bone.parentId);
+ sampledFrames.set(bone.id, { translation: pose.translation, rotation: pose.rotation, scale: bone.uniformScale });
+ const inverseParentRotation = quat.invert(quat.create(), parent.rotation);
+ const patch = patches.get(bone.id);
+ vec3.subtract(offset, pose.translation, parent.translation);
+ vec3.transformQuat(patch.translation, offset, inverseParentRotation);
+ vec3.scale(patch.translation, patch.translation, 1 / parent.scale);
+ quat.multiply(patch.rotation, inverseParentRotation, pose.rotation);
+ limitTurnFromRest(patch.rotation, bone.restLocalRotation);
+ }
+ },
+ /** Where each end of a bone is in world space for a body pose. */
+ ends(boneId, pose) {
+ const tailInBone = byId.get(boneId).tailInBone;
+ const tail = vec3.transformQuat(vec3.create(), tailInBone, pose.rotation);
+ return { head: Array.from(pose.translation), tail: Array.from(vec3.add(tail, tail, pose.translation)) };
+ },
+ });
+}
+
+/** An empty patch table for a ragdoll's bones, to be filled by `writePatches`. */
+export function ragdollPatches(ragdoll) {
+ return new Map(ragdoll.boneIds.map(id => [id, { translation: new Float64Array(3), rotation: new Float64Array(4) }]));
+}
+
+const rounded = value => Number(value.toFixed(4));
+
+/** Numbers an agent can read instead of a picture: how low the rig lies, how high it stays, and when it stops. */
+export function ragdollReport(ragdoll, scene) {
+ const finalPose = scene.sample(scene.duration);
+ const previousPose = scene.sample(Math.max(0, scene.duration - scene.timestep));
+ let lowest = Infinity;
+ let highest = -Infinity;
+ let fastest = 0;
+ let restFrame = 0;
+ for (const id of ragdoll.boneIds) {
+ const offset = scene.bodyIndex(id) * 7;
+ const pose = { translation: finalPose.subarray(offset, offset + 3), rotation: finalPose.subarray(offset + 3, offset + 7) };
+ const { head, tail } = ragdoll.ends(id, pose);
+ lowest = Math.min(lowest, head[1], tail[1]);
+ highest = Math.max(highest, head[1], tail[1]);
+ const step = Math.hypot(...[0, 1, 2].map(axis => finalPose[offset + axis] - previousPose[offset + axis]));
+ fastest = Math.max(fastest, step / scene.timestep);
+ const bodyRest = scene.restFrames[scene.bodyIndex(id)];
+ restFrame = restFrame < 0 || bodyRest < 0 ? -1 : Math.max(restFrame, bodyRest);
+ }
+ return {
+ bones: ragdoll.boneIds.length, lowestY: rounded(lowest), highestY: rounded(highest), fastestFinalSpeed: rounded(fastest),
+ restsAtTime: restFrame < 0 ? null : Number((restFrame * scene.timestep).toFixed(3)),
+ };
+}
diff --git a/tests/ragdoll.test.js b/tests/ragdoll.test.js
new file mode 100644
index 00000000..5b401d8b
--- /dev/null
+++ b/tests/ragdoll.test.js
@@ -0,0 +1,142 @@
+import assert from 'node:assert/strict';
+import { readFileSync } from 'node:fs';
+import test from 'node:test';
+import { createAgentScene, loadPhysicsEngine, needsPhysics } from '../src/agent-scene.js';
+import { loadAllAgentSceneModules } from '../src/agent-scene-modules.js';
+import { createAgentAssetScene } from '../src/agent-asset.js';
+import { parseGltf } from '../src/gltf.js';
+import { walkerRecipe } from '../bench/agent-modeling/walker.mjs';
+
+await loadPhysicsEngine();
+await loadAllAgentSceneModules();
+
+const ASSET_ID = 'ab'.repeat(32);
+const FLOOR_NODE = { id: 'floor', geometry: 'slab', material: 'cloth', translation: [0, -0.25, 0], scale: [8, 0.5, 8] };
+
+function ragdollWalker(physics = {}) {
+ const recipe = walkerRecipe();
+ delete recipe.motion;
+ recipe.geometries.push({ id: 'slab', type: 'box' });
+ recipe.nodes.push(FLOOR_NODE);
+ recipe.armatures[0].translation = [0, 1, 0];
+ recipe.physics = { duration: 4, bodies: [{ node: 'floor', type: 'fixed' }], ragdoll: { armature: 'rig' }, ...physics };
+ return recipe;
+}
+
+function snapshot(scene) {
+ return scene.parts.map(part => [Array.from(part.matrix), part.skin ? Array.from(part.skin.jointMatrices) : null]);
+}
+
+function lowestJointHeight(scene) {
+ const heights = scene.parts.filter(part => part.skin).flatMap(part => Array.from({ length: part.skin.jointWorldMatrices.length / 16 }, (unused, joint) => part.skin.jointWorldMatrices[joint * 16 + 13]));
+ return Math.min(...heights);
+}
+
+test('a ragdoll on a preset armature falls, lies on the floor and reports numbers', () => {
+ const scene = createAgentScene(ragdollWalker());
+ const standing = snapshot(scene);
+ scene.sampleMotion(4);
+ const collapsed = snapshot(scene);
+ assert.notDeepEqual(collapsed, standing);
+ const report = scene.inspect({}).physics.ragdoll;
+ assert.ok(report.bones >= 15, `bones ${report.bones}`);
+ assert.ok(report.lowestY > -0.05 && report.lowestY < 0.2, `lowest ${report.lowestY}`);
+ assert.ok(report.highestY < 1.2, `a 1.8 m figure lying down stays below 1.2 m, got ${report.highestY}`);
+ assert.ok(report.restsAtTime !== null && report.restsAtTime < 4, `rests at ${report.restsAtTime}`);
+ assert.ok(lowestJointHeight(scene) > -0.8, `no joint falls through the floor, lowest ${lowestJointHeight(scene)}`);
+});
+
+test('a seek to the same time gives the same bytes in any order', () => {
+ const scene = createAgentScene(ragdollWalker());
+ scene.sampleMotion(1.5);
+ const first = snapshot(scene);
+ scene.sampleMotion(4);
+ scene.sampleMotion(0.2);
+ scene.sampleMotion(1.5);
+ assert.deepEqual(snapshot(scene), first);
+ const again = createAgentScene(ragdollWalker());
+ again.sampleMotion(1.5);
+ assert.deepEqual(snapshot(again), first, 'a second bake of the same recipe matches');
+ scene.sampleMotion(0);
+ assert.deepEqual(snapshot(scene), snapshot(createAgentScene(ragdollWalker())), 'time zero is the authored pose');
+});
+
+test('the ragdoll bake is reused until the rig changes', () => {
+ const scene = createAgentScene(ragdollWalker());
+ const before = scene.inspect({}).physics;
+ scene.apply([{ type: 'set-node', id: 'floor', translation: [0, -0.25, 0] }], { expectedRevision: 0 });
+ assert.deepEqual(scene.inspect({}).physics, before);
+});
+
+test('a scene without physics never loads the ragdoll code path', () => {
+ assert.equal(needsPhysics(walkerRecipe()), false);
+ assert.equal(needsPhysics(ragdollWalker()), true);
+});
+
+test('bad ragdoll sections fail with a message that names the fix', () => {
+ const cases = [
+ [{ ragdoll: { armature: 'missing' } }, /armature was not found/],
+ [{ ragdoll: {} }, /armature was not found/],
+ [{ ragdoll: { armature: 'rig', color: 1 } }, /Unknown/],
+ [{ ragdoll: { armature: 'rig', density: 0 } }, /density/],
+ [{ ragdoll: { armature: 'rig', layer: 16 } }, /layer/],
+ [{ ragdoll: { armature: 'rig', friction: -1 } }, /friction/],
+ [{ ragdoll: 'rig' }, /plain object/],
+ [{ ragdoll: null }, /plain object/],
+ [{ ragdoll: { armature: 'rig' }, bodies: 3 }, /array/],
+ ];
+ for (const [physics, message] of cases) {
+ assert.throws(() => createAgentScene(ragdollWalker(physics)), message);
+ }
+});
+
+test('a bone cannot have both a ragdoll and a pose track', () => {
+ const recipe = ragdollWalker();
+ recipe.motion = { duration: 1, tracks: [{ kind: 'node', id: 'leftUpperLeg', property: 'rotation', keyframes: [{ time: 0, value: [0, 0, 0, 1] }, { time: 1, value: [0, 0, 0, 1] }] }] };
+ assert.throws(() => createAgentScene(recipe), /Pick one/);
+});
+
+test('an armature larger than the bone limit is refused before the solver runs', () => {
+ const recipe = ragdollWalker();
+ const bones = Array.from({ length: 60 }, (unused, index) => ({ name: `b${index}`, parent: index === 0 ? null : `b${index - 1}`, head: [0, index * 0.05, 0] }));
+ recipe.armatures = [{ id: 'rig', bones }];
+ recipe.nodes = recipe.nodes.filter(node => !node.skin);
+ assert.throws(() => createAgentScene(recipe), /1 to 48 bones/);
+});
+
+test('a bone with no length is refused', () => {
+ const recipe = ragdollWalker();
+ recipe.armatures = [{ id: 'rig', bones: [{ name: 'root', parent: null, head: [0, 0, 0], tail: [0, 0, 0] }] }];
+ recipe.nodes = recipe.nodes.filter(node => !node.skin);
+ assert.throws(() => createAgentScene(recipe), /no length/);
+});
+
+const robotBytes = readFileSync(new URL('./fixtures/RobotExpressive.glb', import.meta.url));
+
+async function robotScene(physics, root = { translation: [0, 2, 0] }) {
+ const asset = await parseGltf(robotBytes.buffer.slice(robotBytes.byteOffset, robotBytes.byteOffset + robotBytes.byteLength), { maxVertices: 500000 });
+ return createAgentAssetScene(asset, { format: '67js.asset', schemaVersion: 1, assetId: ASSET_ID, root, physics });
+}
+
+test('an imported robot ragdolls onto the floor and seeks to the same pose', async () => {
+ const scene = await robotScene({ duration: 4, ragdoll: {} });
+ scene.sampleMotion(0);
+ const standing = snapshot(scene);
+ scene.sampleMotion(1.2);
+ const falling = snapshot(scene);
+ scene.sampleMotion(4);
+ const collapsed = snapshot(scene);
+ assert.notDeepEqual(collapsed, standing);
+ scene.sampleMotion(1.2);
+ assert.deepEqual(snapshot(scene), falling);
+ const report = scene.inspect({}).physics;
+ assert.ok(report.ragdoll.lowestY > -0.05, `lowest ${report.ragdoll.lowestY}`);
+ assert.ok(report.ragdoll.highestY < 2, `highest ${report.ragdoll.highestY}`);
+ assert.equal(scene.exportRecipe().physics.ragdoll.constructor, Object);
+});
+
+test('asset physics refuses unknown fields and a missing ragdoll', async () => {
+ for (const physics of [{ duration: 2 }, { duration: 2, ragdoll: { color: 1 } }, { duration: 0, ragdoll: {} }, { duration: 2, bodies: [], ragdoll: {} }]) {
+ await assert.rejects(robotScene(physics));
+ }
+});