3D engine that AI agents drive
Add joint limits, node constraints and drivers to motion
Nguyen Xuan Anf47e53c95df4
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex c71b390c..92174c76 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -2,6 +2,8 @@## Unreleased+- Add joint limits, node constraints and drivers to motion (issue #58). Two-bone IK takes `limits` per joint and axis in degrees and `bendToward`; `scene_inspect` `motionIk` now carries `limited` (each pose a limit changed) and `warnings` (`hyperextended`, and `wrong-bend` for a knee or elbow bent the unnatural way, which a wrong pole used to hide behind `reached`). `motion.constraints` adds `copy_location`, `copy_rotation`, `copy_scale`, `limit_location`, `limit_rotation`, `track_to`, `child_of` (with an inverse and an influence blend) and `floor`, and `motion.drivers` sets a node component or material property from a bounded JSON expression over time and other nodes (never run as code). The order is tracks, IK, drivers, constraints, with no state between samples, so a seek equals playing. `copy_rotation`, `limit_rotation`, `track_to`, `child_of` and `floor` match Blender 5.2 world matrices in 8 recorded cases (`tests/fixtures/blender/constraints.json`). Joint limits are also in `67js/addons/skeleton-pose`. The `leg-plant` task joins the agent modeling suite. The expression language is a new small one in `src/motion-expression.js`: the field expressions of the mesh addon were not on `main` yet+- Add the `scene_export_glb` MCP tool (22 tools now) and morph weight clips in `exportGlb`. The tool writes the active recipe or imported asset scene as a GLB under `<jobs>/exports/` with a server-chosen name and returns the path, byte count and SHA-256; it takes no path, keeps the newest eight files and refuses more than 32 MiB. It exports the current pose (pattern textures, imported textures, skins, morph weights, IK as posed), `motionTime` seeks authored motion first, and `clip` adds an imported asset's source clip. Clip tracks with `property: 'weights'` write a SCALAR sampler of one weight per target. Checked in Blender 5.2: a patterned recipe opens with 2 meshes and 3 images, the robot with IK opens as 1 armature, 43 bones and 20 meshes, and its Walking clip as one action of 23 frames. Nothing in `src/index.js` changes, so no size budget moves- Add material layers: `clearcoat` and `clearcoatRoughness`, `transmission` with `thickness`, `ior`, `attenuationColor` and `attenuationDistance`, `sheenColor` and `sheenRoughness`, and `specular` and `specularColor`. Recipes, the MCP schema, glTF import and export (`KHR_materials_clearcoat`, `transmission`, `volume`, `ior`, `specular`, `sheen`) all take them, each checked at the boundary. Transmission refracts the opaque scene like the `liquid` material. Anisotropy and iridescence are not rendered yet. Import of those two still warns- Change the glTF import of the six layer extensions above from accepted-and-ignored to rendered, so `asset.warnings` no longer lists themdiff --git a/bench/agent-modeling/README.md b/bench/agent-modeling/README.mdindex a5c95d33..c93d8f9c 100644--- a/bench/agent-modeling/README.md+++ b/bench/agent-modeling/README.md@@ -36,6 +36,7 @@ own mesh report:| crate-uv | The crate with even UVs || crate-wood | The crate with a wood material pattern, to see whether agents find `pattern` || arm-reach | A jointed arm whose tip moves between two points, to see whether agents find `motion.ik` |+| leg-plant | A leg that plants its foot on two points with the knee bending forward: `motion.ik` with `bendToward`, `pole` and `limits` || robot-reach | The CC0 robot from `tests/fixtures`: IK over its Idle clip, found through the asset catalog and hierarchy || dice | Rounded edges plus 21 recessed pips, in one piece (harder) || flange | A hollow pipe with flanges and 12 bolt holes, in one piece (harder) |diff --git a/bench/agent-modeling/check.mjs b/bench/agent-modeling/check.mjsindex 9f2bfa59..6307a46c 100644--- a/bench/agent-modeling/check.mjs+++ b/bench/agent-modeling/check.mjs@@ -69,6 +69,15 @@ function checkOne(check, measures) {const distance = Math.hypot(...from.map((value, axis) => value - to[axis]));return { pass: Math.abs(distance - check.distance) <= 0.01, detail: `${round(distance)} m apart at t=${check.time}` };}+ case 'bendsToward': {+ const root = measures.nodePosition(check.from, check.time);+ const middle = measures.nodePosition(check.node, check.time);+ const end = measures.nodePosition(check.to, check.time);+ if (!root || !middle || !end) return { pass: false, detail: `no drawn node ${check.from}, ${check.node} or ${check.to}` };+ const offset = middle.map((value, axis) => value - (root[axis] + end[axis]) / 2);+ const along = offset.reduce((total, value, axis) => total + value * check.direction[axis], 0);+ return { pass: along >= check.minOffset, detail: `${check.node} sits ${round(along)} m toward ${JSON.stringify(check.direction)} at t=${check.time}` };+ }case 'assetClip': {return { pass: measures.clipName === check.name, detail: `clip ${measures.clipName ?? 'none'}` };}diff --git a/bench/agent-modeling/references.mjs b/bench/agent-modeling/references.mjsindex 7753e9dd..f2492dae 100644--- a/bench/agent-modeling/references.mjs+++ b/bench/agent-modeling/references.mjs@@ -136,6 +136,24 @@ export const REFERENCES = {}],},},+ 'leg-plant': {+ ...scene(+ [{ id: 'ball', type: 'sphere', segments: 16, rings: 8 }],+ [+ { id: 'hip', geometry: 'ball', translation: [0, 1, 0], scale: [0.03, 0.03, 0.03] },+ { id: 'knee', geometry: 'ball', parent: 'hip', translation: [0, -0.5 / 0.03, 0] },+ { id: 'foot', geometry: 'ball', parent: 'knee', translation: [0, -0.5 / 0.03, 0] },+ ],+ ),+ motion: {+ duration: 2, tracks: [],+ ik: [{+ type: 'two-bone', root: 'hip', middle: 'knee', end: 'foot', pole: [0, 0.5, 3], bendToward: [0, 0, 1],+ limits: { middle: { x: [-150, 150] } },+ target: { keyframes: [{ time: 0, value: [0.1, 0.5, 0.35] }, { time: 2, value: [0.1, 0.6, 0.2] }] },+ }],+ },+ },dice: scene([{ id: 'die', type: 'mesh', base: { type: 'box', bevel: 0 }, edits: dieEdits() }],[{ id: 'die', geometry: 'die', translation: [0, 0.05, 0], scale: [0.1, 0.1, 0.1] }],diff --git a/bench/agent-modeling/tasks.mjs b/bench/agent-modeling/tasks.mjsindex 2ae774c9..14b4d15b 100644--- a/bench/agent-modeling/tasks.mjs+++ b/bench/agent-modeling/tasks.mjs@@ -245,6 +245,23 @@ For this task the object does not need to rest on the ground.`,{ kind: 'nodeDistance', from: 'elbow', to: 'tip', time: 1, distance: 0.4 },],},+ {+ id: 'leg-plant',+ prompt: `A walking character's leg that plants its foot on two points, the way a real knee bends. Use three nodes with+these exact IDs, each with a small visible geometry: hip at [0, 1, 0], knee 0.5 m below the hip, and foot 0.5 m below the knee.+Make knee a child of hip and foot a child of knee. The character faces +z, so the knee must bend forward, never backward.+Add a 2 second motion in which the foot is exactly at [0.1, 0.5, 0.35] at time 0 and exactly at [0.1, 0.6, 0.2] at time 2,+with both bones keeping their lengths and the knee in front of the hip-to-foot line at both times.+For this task the object does not need to rest on the ground.`,+ checks: [+ { kind: 'nodeAt', node: 'foot', time: 0, position: [0.1, 0.5, 0.35] },+ { kind: 'nodeAt', node: 'foot', time: 2, position: [0.1, 0.6, 0.2] },+ { kind: 'nodeDistance', from: 'hip', to: 'knee', time: 1, distance: 0.5 },+ { kind: 'nodeDistance', from: 'knee', to: 'foot', time: 1, distance: 0.5 },+ { kind: 'bendsToward', from: 'hip', node: 'knee', to: 'foot', time: 0, direction: [0, 0, 1], minOffset: 0.02 },+ { kind: 'bendsToward', from: 'hip', node: 'knee', to: 'foot', time: 2, direction: [0, 0, 1], minOffset: 0.02 },+ ],+ },{id: 'robot-reach',assets: true,diff --git a/bench/size/budgets.json b/bench/size/budgets.jsonindex 24bbc9e3..a625ced9 100644--- a/bench/size/budgets.json+++ b/bench/size/budgets.json@@ -21,18 +21,18 @@"entry:physics": 16500,"entry:spume": 9000,"entry:retarget": 15700,- "entry:skeleton-pose": 17200,+ "entry:skeleton-pose": 18100,"entry:vehicle": 14700,"entry:vegetation": 17900,"entry:terrain": 3100,"entry:grass": 4400,"entry:clutter": 5300,"entry:texture-set": 900,- "entry:agent-scene": 110900,- "entry:agent-asset": 118400,+ "entry:agent-scene": 115200,+ "entry:agent-asset": 122600,"entry:hdri": 3300,"scene:lit-box": 56000,"scene:gltf-box": 75300,- "scene:agent-scene": 137600+ "scene:agent-scene": 141400}}diff --git a/docs/agent-motion.md b/docs/agent-motion.mdindex 5fcf4240..82cdb4c6 100644--- a/docs/agent-motion.md+++ b/docs/agent-motion.md@@ -115,7 +115,76 @@ On an imported asset, joints are its `node-N` IDs from `scene_inspect` with `kinEach sample stages the clip and overrides, reads the local pose, solves, and stages again, so the rest of the body stays onthe selected clip and skins and rigid parts all follow. Targets are in world space, under the asset's `root`, which needs auniform scale. Some rigs have no chain to the foot: if the foot is not a descendant of the lower leg, two-bone IK refuses it.-There are no joint angle limits. [Skeleton pose layers](skeleton-pose.md) add clip layers and masks in code.+[Skeleton pose layers](skeleton-pose.md) add clip layers and masks in code.++### Joint limits and sanity warnings++A two-bone solver takes `limits: { "root": { "x": [min, max], "y": [...], "z": [...] }, "middle": {...} }` in degrees. Each+range bounds how far that joint turns away from its rest rotation, per axis of the joint's own frame, as Euler XYZ (the+order Blender uses). A limited joint is clamped after the solve and the end rotation is restored, so a clamped knee leaves+the foot short of its target and `reached` turns false. `motionIk[n].limited` lists each joint and axis a limit changed:+`{ joint, axis, requested, applied, atTime }`, degrees, first time it happens.++`motionIk[n].warnings` lists `{ code, message, atTime }` once per code:++| Code | When |+| --- | --- |+| `hyperextended` | The middle joint is within 5 degrees of straight: the target is at or past the limb's reach |+| `wrong-bend` | The middle joint bends opposite to its natural side, which a pole on the wrong side produces while the foot still arrives |++The natural side is `bendToward` (a world direction, such as `[0, 0, 1]` for a knee on a character that faces +z) or, when+that is absent, the way the limb is bent in its rest pose. A limb that rests perfectly straight and has no `bendToward` is+never checked for the wrong bend, so give legs and arms one.++## Constraints++`motion.constraints` is a list of Blender-style node constraints, at most 32. Each names the constrained `node` (a recipe+node, or an editable asset node), a `type`, a `target` node where the type needs one, and an `influence`: 0 to 1 (default 1)+or an expression. Influence blends the node's matrix before and after the constraint, location, rotation and scale+separately, as Blender does. Euler angles are XYZ in degrees. `space` is `world` (default) or `local`, local being the node's+own transform under its parent.++| Type | Fields | Meaning |+| --- | --- | --- |+| `copy_location` | `target`, `axes`, `invert`, `offset`, `space` | The chosen axes take the target's location; `offset` adds it to the node's own |+| `copy_rotation` | `target`, `axes`, `invert`, `mix` (`replace` or `add`), `space` | The chosen Euler axes take the target's |+| `copy_scale` | `target`, `axes`, `offset`, `space` | The chosen axes take the target's scale; `offset` multiplies |+| `limit_location` | `x`, `y`, `z` as `[min, max]`, `space` | Clamp the location per axis |+| `limit_rotation` | `x`, `y`, `z` as `[min, max]` degrees, `space` | Clamp the Euler angles per axis |+| `track_to` | `target`, `trackAxis` (default `-z`), `upAxis` (default `y`), `worldUp` (default `[0, 1, 0]`) | Turn the node so its track axis points at the target and its up axis leans toward `worldUp`. Blender's up is Z, so its numbers match with `worldUp: [0, 0, 1]` |+| `child_of` | `target`, `inverse` (`rest` or `none`) | The node follows the target: its world matrix becomes target * inverse * its own. `rest` uses the inverse of the target's rest matrix, so the node stays put until the target moves; Blender's default is `none` |+| `floor` | `target`, `axis` (default `+y`), `offset` | Keep the node on the positive side of the plane through the target, along `axis`, plus `offset` |++Not covered yet: `use_*` switches on `child_of`, `limit_scale`, `copy_transforms`, `damped_track`, `locked_track`,+`stretch_to`, bone sub-targets and `head_tail`.++## Drivers++`motion.drivers` sets one node component or material property from a bounded expression, at most 32. A target is+`{ "kind": "node", "id", "property": "translation" | "rotation" | "scale", "component": "x" | "y" | "z" }` (rotation is Euler+XYZ in degrees) or `{ "kind": "material", "id", "property" }` for `emission`, `metallic` and `roughness`, or with a+`component` for `color` and `emissiveColor` (`x`, `y`, `z` for red, green, blue). A driven property cannot also have a track.++An expression is JSON data and is never run as code: a number, the string `"time"`, a read of another node+`{ "node", "property", "component", "space" }`, or one operator object such as `{ "mul": ["time", 2] }`. Operators: `add`,+`mul`, `min`, `max` (2 to 8 operands), `sub`, `div`, `pow`, `mod`, `atan2`, `gt`, `lt`, `neg`, `abs`, `sin`, `cos` (radians),+`sqrt`, `floor`, `fract`, `saturate`, `clamp(x, low, high)`, `mix(a, b, t)`, `smoothstep(low, high, x)` and+`if(condition, then, otherwise)`. An expression has at most 64 parts and 8 levels, and a result that is not finite is an+error. The operator names follow the field expressions of the mesh addon where they overlap.++### Evaluation order++For any time, the pose is built in this order and keeps no state between samples, so seeking gives the same pose as playing+to that time:++1. Tracks, and for an asset the selected clip.+2. IK, in list order.+3. Drivers. They read the pose from steps 1 and 2, so one driver never sees another's result.+4. Constraints, in list order. Each reads the pose the ones before it left. Expressions in `influence` read the pose from+ step 2.++IK targets that follow a node see that node before drivers and constraints move it. Material drivers on an imported asset+read node values from the tracks and rest pose, not the clip.## Internal sampling helpersdiff --git a/docs/parity.md b/docs/parity.mdindex e5173faa..f8ab06d2 100644--- a/docs/parity.md+++ b/docs/parity.md@@ -139,34 +139,34 @@ To move to a new Blender release, run `node scripts/parity-manual-snapshot.mjs`.| Animation & Rigging > Lattice | missing | No lattice. | | #42 || Animation & Rigging > Constraints > Interface | out of scope | Interface for a mouse. | | || Animation & Rigging > Constraints > Motion Tracking | out of scope | Motion tracking is out of scope in issue #23. | | |-| Animation & Rigging > Constraints > Transform > Copy Location Constraint | missing | No constraint. | | #58 |-| Animation & Rigging > Constraints > Transform > Copy Rotation Constraint | missing | No constraint. | | #58 |-| Animation & Rigging > Constraints > Transform > Copy Scale Constraint | missing | No constraint. | | #58 |+| Animation & Rigging > Constraints > Transform > Copy Location Constraint | partial | `copy_location` in `motion.constraints`: axes, invert, offset, world or local space, influence. Matches Blender where tested. | [agent-motion-constraints](../tests/agent-motion-constraints.test.js) | #58 |+| Animation & Rigging > Constraints > Transform > Copy Rotation Constraint | partial | `copy_rotation`: Euler axes, invert, replace or add, world or local. World matrices match Blender 5.2 in 2 cases. | [blender-constraints](../tests/blender-constraints.test.js) | #58 |+| Animation & Rigging > Constraints > Transform > Copy Scale Constraint | partial | `copy_scale`: axes and offset, world or local. | [agent-motion-constraints](../tests/agent-motion-constraints.test.js) | #58 || Animation & Rigging > Constraints > Transform > Copy Transforms Constraint | missing | No constraint. | | #58 || Animation & Rigging > Constraints > Transform > Limit Distance Constraint | missing | No constraint. | | #58 |-| Animation & Rigging > Constraints > Transform > Limit Location Constraint | missing | No constraint. | | #58 |-| Animation & Rigging > Constraints > Transform > Limit Rotation Constraint | missing | Joints have no limits, except `maxAngle` on aim IK. | | #58 |+| Animation & Rigging > Constraints > Transform > Limit Location Constraint | partial | `limit_location`: per-axis clamp, world or local. | [agent-motion-constraints](../tests/agent-motion-constraints.test.js) | #58 |+| Animation & Rigging > Constraints > Transform > Limit Rotation Constraint | partial | `limit_rotation` constraint and per-axis `limits` on two-bone IK joints, reported in `motionIk`. Matches Blender 5.2. | [blender-constraints](../tests/blender-constraints.test.js), [skeleton-pose-limits](../tests/skeleton-pose-limits.test.js) | #58 || Animation & Rigging > Constraints > Transform > Limit Scale Constraint | missing | No constraint. | | #58 || Animation & Rigging > Constraints > Transform > Maintain Volume Constraint | missing | No constraint. | | || Animation & Rigging > Constraints > Transform > Transformation Constraint | missing | No constraint. | | || Animation & Rigging > Constraints > Transform > Transform Cache Constraint | missing | No constraint. | | || Animation & Rigging > Constraints > Tracking > Clamp To Constraint | missing | No constraint. | | || Animation & Rigging > Constraints > Tracking > Damped Track Constraint | partial | Aim IK turns one joint toward a target. It is not a general constraint. | [agent-motion-ik](../tests/agent-motion-ik.test.js) | #58 |-| Animation & Rigging > Constraints > Tracking > Inverse Kinematics Constraint | partial | Two-bone and aim IK, in code and in `motion.ik`. There are no longer chains or limits. | [agent-motion-ik](../tests/agent-motion-ik.test.js), [agent-asset-ik](../tests/agent-asset-ik.test.js) | #58 |+| Animation & Rigging > Constraints > Tracking > Inverse Kinematics Constraint | partial | Two-bone and aim IK, in code and in `motion.ik`, with joint limits and sanity warnings on two-bone. There are no longer chains. | [agent-motion-ik](../tests/agent-motion-ik.test.js), [agent-asset-ik](../tests/agent-asset-ik.test.js) | #58 || Animation & Rigging > Constraints > Tracking > Locked Track Constraint | missing | No constraint. | | || Animation & Rigging > Constraints > Tracking > Spline IK Constraint | missing | No constraint. | | || Animation & Rigging > Constraints > Tracking > Stretch To Constraint | missing | No constraint. | | |-| Animation & Rigging > Constraints > Tracking > Track To Constraint | partial | Cameras track a target. Nodes have no track constraint. | [camera-path](../tests/camera-path.test.js) | #58 |+| Animation & Rigging > Constraints > Tracking > Track To Constraint | partial | `track_to` on nodes: track and up axes, `worldUp`. Matches Blender 5.2 in 2 cases. Cameras still use camera paths. | [blender-constraints](../tests/blender-constraints.test.js), [camera-path](../tests/camera-path.test.js) | #58 || Animation & Rigging > Constraints > Relationship > Action Constraint | missing | No constraint. | | || Animation & Rigging > Constraints > Relationship > Armature Constraint | missing | No constraint. | | |-| Animation & Rigging > Constraints > Relationship > Child Of Constraint | partial | Static parents. A parent can not change or blend over time. | [scene-graph](../tests/scene-graph.test.js) | #58 |-| Animation & Rigging > Constraints > Relationship > Floor Constraint | missing | No constraint. | | #58 |+| Animation & Rigging > Constraints > Relationship > Child Of Constraint | partial | `child_of` in `motion.constraints`: follows a moving target from its rest inverse (or none), with an influence that can be animated by an expression. Matches Blender 5.2 in 2 cases. No per-channel switches. | [blender-constraints](../tests/blender-constraints.test.js), [scene-graph](../tests/scene-graph.test.js) | #58 |+| Animation & Rigging > Constraints > Relationship > Floor Constraint | partial | `floor`: keeps a node on one side of a plane through the target, axis and offset. Matches Blender 5.2 for the Z floor with an offset; no `use_rotation`. | [blender-constraints](../tests/blender-constraints.test.js) | #58 || Animation & Rigging > Constraints > Relationship > Follow Path Constraint | partial | Camera paths only. | [camera-path](../tests/camera-path.test.js) | || Animation & Rigging > Constraints > Relationship > Geometry Attribute Constraint | missing | No constraint. | | || Animation & Rigging > Constraints > Relationship > Pivot Constraint | missing | No constraint. | | || Animation & Rigging > Constraints > Relationship > Shrinkwrap Constraint | partial | `addons/surface-attachment` binds points to a surface in code. | [surface-attachment](../tests/surface-attachment.test.js) | || Animation & Rigging > Actions | partial | Clips, weights and crossfades in code. An asset through MCP plays one clip at a time. | [animation-mixer](../tests/animation-mixer.test.js) | #59 |-| Animation & Rigging > Drivers | missing | No drivers. | | #58 |+| Animation & Rigging > Drivers | partial | `motion.drivers`: a node component or material property from a bounded expression over time and other nodes. No custom properties, shape keys or variables. | [agent-motion-constraints](../tests/agent-motion-constraints.test.js) | #58 || Animation & Rigging > Markers | missing | No markers or events. | | #60 || Animation & Rigging > Shape Keys | partial | Morph targets import, render and animate. Recipes can not author them. | [morph](../tests/morph.test.js) | #59 || Animation & Rigging > Motion Paths | out of scope | Viewport display for hand work. `scene_inspect` reports motion as numbers. | | |diff --git a/docs/skeleton-pose.md b/docs/skeleton-pose.mdindex 127a2fdf..7cfdc5be 100644--- a/docs/skeleton-pose.md+++ b/docs/skeleton-pose.md@@ -73,6 +73,8 @@ joint's own frame (`local = local * delta`), and weight scales the delta. An add| `pole` | World point the middle joint bends toward, or `(time, middlePosition) => point`. Without one, it keeps the current bend || `weight` | 0 to 1 (default 1), or a function of time || `keepEndRotation` | Default `true`: the end joint keeps its world rotation, so a foot stays flat while the leg moves |+| `limits` | `{ root: { x: [min, max], y, z }, middle: {...} }` in degrees: the turn away from the joint's rest rotation, per axis of its own, as Euler XYZ. Applied after the solve; `ikResults[n].limited` lists each change as `{ joint, axis, requested, applied }` |+| `bendToward` | World direction the middle joint should bend toward. `ikResults[n].warnings` gets `wrong-bend` when the solve bends the other way, and `hyperextended` when the limb is locked straight. Without it, a limb that rests bent is checked against its rest bend |The solve is analytic, keeps bone lengths, and turns the two upper joints by the shortest rotations, so twist already inthe pose survives. A limb that is straight in the pose with its target straight ahead has no bend direction, so givediff --git a/scripts/blender-constraints-golden.py b/scripts/blender-constraints-golden.pynew file mode 100644index 00000000..c7e0d865--- /dev/null+++ b/scripts/blender-constraints-golden.py@@ -0,0 +1,175 @@+"""Record Blender's result for each constraint case in tests/fixtures/blender/constraints.json.++Run from Bash:+ PATH="/c/Program Files/Blender Foundation/Blender 5.2:$PATH" blender -b --factory-startup --python scripts/blender-constraints-golden.py++Each case lists nodes (empties with a parent, location, Euler XYZ degrees and scale), one constraint written in 67.js's+recipe form, and optionally a `pose` that moves a node after the constraint is set up (child_of binds at the rest pose+and then follows the target). The script builds the same scene in Blender, reads the owner's evaluated world matrix and+writes it column-major, the layout 67.js uses. The numbers come from Blender's own evaluation; nothing is copied from it.+"""+import json+import math+import os++import bpy+from mathutils import Euler++OUTPUT = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "tests", "fixtures", "blender", "constraints.json")++CASES = [+ {+ "name": "copy_rotation_xz",+ "nodes": [+ {"id": "source", "translation": [1, 2, 3], "rotation": [20, 30, 40]},+ {"id": "owner", "translation": [0, 0, 0], "rotation": [10, 5, -15]},+ ],+ "constraint": {"type": "copy_rotation", "node": "owner", "target": "source", "axes": ["x", "z"]},+ },+ {+ "name": "copy_rotation_all_with_parent",+ "nodes": [+ {"id": "holder", "translation": [4, 0, 1], "rotation": [0, 0, 25]},+ {"id": "source", "translation": [1, 2, 3], "rotation": [-35, 20, 50]},+ {"id": "owner", "parent": "holder", "translation": [1, 1, 0], "rotation": [10, 5, -15]},+ ],+ "constraint": {"type": "copy_rotation", "node": "owner", "target": "source"},+ },+ {+ "name": "limit_rotation_xy",+ "nodes": [{"id": "owner", "translation": [0, 0, 0], "rotation": [80, 70, 10]}],+ "constraint": {"type": "limit_rotation", "node": "owner", "x": [-45, 45], "y": [-30, 30]},+ },+ {+ "name": "track_to_negative_z_up_y",+ "nodes": [+ {"id": "owner", "translation": [-1, 1, 0]},+ {"id": "target", "translation": [0.3, 1.5, 0.3]},+ ],+ "constraint": {"type": "track_to", "node": "owner", "target": "target", "trackAxis": "-z", "upAxis": "y", "worldUp": [0, 0, 1]},+ },+ {+ "name": "track_to_positive_x_up_z",+ "nodes": [+ {"id": "owner", "translation": [2, -1, 0.5], "rotation": [0, 0, 15]},+ {"id": "target", "translation": [-1, 3, 2]},+ ],+ "constraint": {"type": "track_to", "node": "owner", "target": "target", "trackAxis": "+x", "upAxis": "z", "worldUp": [0, 0, 1]},+ },+ {+ "name": "child_of_follows_target_from_rest",+ "nodes": [+ {"id": "target", "translation": [1, 2, 0], "rotation": [0, 0, 30]},+ {"id": "owner", "translation": [0, 1, 0]},+ ],+ "constraint": {"type": "child_of", "node": "owner", "target": "target", "inverse": "rest"},+ "pose": {"id": "target", "translation": [3, 1, 2], "rotation": [10, 20, 70]},+ },+ {+ "name": "child_of_half_influence",+ "nodes": [+ {"id": "target", "translation": [1, 2, 0], "rotation": [0, 0, 30]},+ {"id": "owner", "translation": [0, 1, 0]},+ ],+ "constraint": {"type": "child_of", "node": "owner", "target": "target", "inverse": "rest", "influence": 0.5},+ "pose": {"id": "target", "translation": [3, 1, 2], "rotation": [10, 20, 70]},+ },+ {+ "name": "floor_z_with_offset",+ "nodes": [+ {"id": "ground", "translation": [0, 0, 0.5]},+ {"id": "owner", "translation": [0.3, 0.2, -1]},+ ],+ "constraint": {"type": "floor", "node": "owner", "target": "ground", "axis": "+z", "offset": 0.1},+ },+]++BLENDER_TYPES = {+ "copy_rotation": "COPY_ROTATION",+ "limit_rotation": "LIMIT_ROTATION",+ "track_to": "TRACK_TO",+ "child_of": "CHILD_OF",+ "floor": "FLOOR",+}+TRACK_AXES = {"+x": "TRACK_X", "-x": "TRACK_NEGATIVE_X", "+y": "TRACK_Y", "-y": "TRACK_NEGATIVE_Y", "+z": "TRACK_Z", "-z": "TRACK_NEGATIVE_Z"}+++def set_transform(blender_object, node):+ blender_object.location = node.get("translation", [0, 0, 0])+ blender_object.rotation_mode = "XYZ"+ blender_object.rotation_euler = Euler([math.radians(angle) for angle in node.get("rotation", [0, 0, 0])], "XYZ")+ blender_object.scale = node.get("scale", [1, 1, 1])+++def evaluated_world(blender_object):+ bpy.context.view_layer.update()+ evaluated = blender_object.evaluated_get(bpy.context.evaluated_depsgraph_get())+ matrix = evaluated.matrix_world+ return [matrix[row][column] for column in range(4) for row in range(4)]+++def add_constraint(owner, objects, spec):+ kind = spec["type"]+ constraint = owner.constraints.new(BLENDER_TYPES[kind])+ if "target" in spec:+ constraint.target = objects[spec["target"]]+ constraint.influence = spec.get("influence", 1)+ if kind == "copy_rotation":+ axes = spec.get("axes", ["x", "y", "z"])+ constraint.use_x = "x" in axes+ constraint.use_y = "y" in axes+ constraint.use_z = "z" in axes+ constraint.mix_mode = "REPLACE"+ constraint.target_space = "WORLD"+ constraint.owner_space = "WORLD"+ elif kind == "limit_rotation":+ for axis in ("x", "y", "z"):+ if axis in spec:+ setattr(constraint, "use_limit_" + axis, True)+ setattr(constraint, "min_" + axis, math.radians(spec[axis][0]))+ setattr(constraint, "max_" + axis, math.radians(spec[axis][1]))+ constraint.owner_space = "WORLD"+ elif kind == "track_to":+ constraint.track_axis = TRACK_AXES[spec.get("trackAxis", "-z")]+ constraint.up_axis = "UP_" + spec.get("upAxis", "y").upper()+ constraint.use_target_z = False+ elif kind == "floor":+ constraint.floor_location = "FLOOR_" + spec.get("axis", "+y").replace("+", "").replace("-", "NEGATIVE_").upper()+ constraint.offset = spec.get("offset", 0)+ constraint.use_rotation = False+ return constraint+++def run_case(case):+ objects = {}+ for node in case["nodes"]:+ blender_object = bpy.data.objects.new(node["id"], None)+ bpy.context.scene.collection.objects.link(blender_object)+ set_transform(blender_object, node)+ objects[node["id"]] = blender_object+ for node in case["nodes"]:+ if "parent" in node:+ objects[node["id"]].parent = objects[node["parent"]]+ owner = objects[case["constraint"]["node"]]+ constraint = add_constraint(owner, objects, case["constraint"])+ if case["constraint"]["type"] == "child_of":+ bpy.context.view_layer.update()+ constraint.inverse_matrix = objects[case["constraint"]["target"]].matrix_world.inverted()+ if "pose" in case:+ set_transform(objects[case["pose"]["id"]], case["pose"])+ result = dict(case)+ result["expectedOwnerWorld"] = evaluated_world(owner)+ for blender_object in objects.values():+ bpy.data.objects.remove(blender_object)+ return result+++def main():+ cases = [run_case(case) for case in CASES]+ with open(OUTPUT, "w", encoding="utf-8") as handle:+ json.dump({"blender": bpy.app.version_string, "cases": cases}, handle, indent=1)+ handle.write("\n")+ print("wrote", len(cases), "cases for Blender", bpy.app.version_string)+++main()diff --git a/scripts/mcp-server.mjs b/scripts/mcp-server.mjsindex 833cfc27..55e78f79 100644--- a/scripts/mcp-server.mjs+++ b/scripts/mcp-server.mjs@@ -286,6 +286,38 @@ const ikPoint = z.union([ikKeyframes(vector3, 'A moving world position.'),]);const ikWeight = z.union([unit, ikKeyframes(unit, 'Fade the solve in or out over time.')]).optional();+const degreeRange = z.tuple([z.number().min(-180).max(180), z.number().min(-180).max(180)]);+const jointLimit = z.strictObject({ x: degreeRange.optional(), y: degreeRange.optional(), z: degreeRange.optional() });+const axisName = z.enum(['x', 'y', 'z']);+const axisNames = z.array(axisName).min(1).max(3);+const signedAxis = z.enum(['+x', '-x', '+y', '-y', '+z', '-z']);+const constraintSpace = z.enum(['world', 'local']).optional();+const limitRange = z.tuple([z.number().min(-1e6).max(1e6), z.number().min(-1e6).max(1e6)]).optional();+// A bounded expression: data only, never code. See docs/agent-motion.md for the operators.+const expression = z.lazy(() => z.union([+ z.number().min(-1e6).max(1e6),+ z.literal('time'),+ z.strictObject({ node: identifier, property: z.enum(['translation', 'rotation', 'scale']), component: axisName, space: z.enum(['local', 'world']).optional() }),+ z.record(z.string().max(24), z.array(expression).min(1).max(8)),+])).describe('Number, "time", {"node","property","component","space"} read, or one operator such as {"mul":[2,"time"]}. Operators: add mul min max sub div pow mod atan2 gt lt neg abs sin cos sqrt floor fract saturate clamp mix smoothstep if. At most 64 parts, 8 deep.');+const influence = z.union([unit, expression]).optional().describe('0 to 1 blend of the constraint, or an expression.');+const constraint = z.discriminatedUnion('type', [+ z.strictObject({ type: z.literal('copy_location'), node: identifier, target: identifier, axes: axisNames.optional(), invert: axisNames.optional(), offset: z.boolean().optional(), space: constraintSpace, influence }),+ z.strictObject({ type: z.literal('copy_rotation'), node: identifier, target: identifier, axes: axisNames.optional(), invert: axisNames.optional(), mix: z.enum(['replace', 'add']).optional(), space: constraintSpace, influence }),+ z.strictObject({ type: z.literal('copy_scale'), node: identifier, target: identifier, axes: axisNames.optional(), offset: z.boolean().optional(), space: constraintSpace, influence }),+ z.strictObject({ type: z.literal('limit_location'), node: identifier, x: limitRange, y: limitRange, z: limitRange, space: constraintSpace, influence }),+ z.strictObject({ type: z.literal('limit_rotation'), node: identifier, x: degreeRange.optional(), y: degreeRange.optional(), z: degreeRange.optional(), space: constraintSpace, influence }),+ z.strictObject({ type: z.literal('track_to'), node: identifier, target: identifier, trackAxis: signedAxis.optional(), upAxis: axisName.optional(), worldUp: vector3.optional(), influence }),+ z.strictObject({ type: z.literal('child_of'), node: identifier, target: identifier, inverse: z.enum(['rest', 'none']).optional(), influence }),+ z.strictObject({ type: z.literal('floor'), node: identifier, target: identifier, axis: signedAxis.optional(), offset: z.number().min(-1e6).max(1e6).optional(), influence }),+]);+const driver = z.strictObject({+ target: z.union([+ z.strictObject({ kind: z.literal('node'), id: identifier, property: z.enum(['translation', 'rotation', 'scale']), component: axisName }),+ z.strictObject({ kind: z.literal('material'), id: identifier, property: z.enum(['color', 'emissiveColor', 'emission', 'metallic', 'roughness']), component: axisName.optional() }),+ ]),+ expression,+});const ikSolver = z.discriminatedUnion('type', [z.strictObject({type: z.literal('two-bone'),@@ -294,6 +326,8 @@ const ikSolver = z.discriminatedUnion('type', [pole: ikPoint.optional().describe('World point the middle joint bends toward. Give one, or a straight limb has no bend direction.'),weight: ikWeight,keepEndRotation: z.boolean().optional().describe('Default true: end keeps its world rotation, so a foot or gripper stays level.'),+ limits: z.strictObject({ root: jointLimit.optional(), middle: jointLimit.optional() }).optional().describe('Joint limits in degrees: how far root or middle may turn from its rest rotation, per axis of its own, as Euler XYZ. scene_inspect motionIk lists each pose a limit changed.'),+ bendToward: vector3.optional().describe('World direction the middle joint should bend toward, such as [0, 0, 1] for a knee on a character facing +z. motionIk warns with wrong-bend when the solve bends the other way. Rigs that rest bent need none.'),}).describe('Limb of three nodes, each a descendant of the one before: shoulder, elbow, wrist. Computes their rotations, so you need no quaternions. Nodes with IK nodes below them must have uniform scale: put sizes on child mesh nodes.'),z.strictObject({type: z.literal('aim'),@@ -309,6 +343,8 @@ const ikSolver = z.discriminatedUnion('type', [const motion = z.strictObject({duration: z.number().min(0.1).max(30),ik: z.array(ikSolver).max(16).optional().describe('Inverse kinematics run after the tracks and any selected clip, in order, on recipes and imported assets. IDs are recipe node IDs or an asset\'s node-N IDs; find them with scene_inspect kind hierarchy. scene_inspect reports motionIk: whether each solver reaches its target across the clip.'),+ constraints: z.array(constraint).max(32).optional().describe('Blender-style node constraints, run in order after the tracks, drivers and IK, each on the pose the one before left: copy_location, copy_rotation, copy_scale, limit_location, limit_rotation, track_to, child_of, floor. Euler angles are XYZ in degrees; space defaults to world. Same result at any time, so seeking equals playing.'),+ drivers: z.array(driver).max(32).optional().describe('Drive one node component or material property from a bounded expression over time and other nodes\' values. A driven property cannot also have a track.'),loop: z.boolean().optional(),tracks: z.array(z.union([motionTrack('node', 'translation', vector3, vector3),diff --git a/scripts/smoke-character.mjs b/scripts/smoke-character.mjsindex 56c230aa..10180967 100644--- a/scripts/smoke-character.mjs+++ b/scripts/smoke-character.mjs@@ -113,6 +113,32 @@ try {assert.notEqual(atEnd, atMiddle);assert.equal(await look(sessionId, null, 1), atMiddle, 'seeking back gives the same picture');+ // Leg IK with a tight knee limit, a bend direction, and a constraint and driver on the same character.+ const legTarget = { interpolation: 'SMOOTH', keyframes: [{ time: 0, value: [-0.6, 1.2, 0.9] }, { time: 2, value: [-0.6, 0.9, 1.2] }] };+ const legMotion = {+ duration: 2,+ tracks: [],+ ik: [{+ // The robot's shin ends in a helper node below LowerLeg.R; its separate Foot.R bone is not part of the leg chain.+ type: 'two-bone', root: idOf('UpperLeg.R'), middle: idOf('LowerLeg.R'), end: nodes.find(node => /^LowerLeg.?R_end$/.test(node.label)).id, target: legTarget,+ pole: [-0.6, 1.6, 3], bendToward: [0, 0, 1], limits: { middle: { x: [-20, 20] } },+ }],+ constraints: [{ type: 'limit_rotation', node: idOf('Head'), x: [-10, 10], y: [-10, 10], space: 'local' }],+ drivers: [{ target: { kind: 'node', id: idOf('Head'), property: 'rotation', component: 'z' }, expression: { mul: [{ sin: [{ mul: ['time', 3] }] }, 8] } }],+ };+ const legApplied = (await call('scene_apply', { sessionId, expectedRevision: revision, operations: [{ type: 'set-motion', motion: legMotion }] })).structuredContent;+ assert.equal(legApplied.renderSucceeded, true, legApplied.renderError);+ revision = legApplied.revision;+ const legReport = (await call('scene_inspect', { sessionId, kind: 'hierarchy', limit: 1 })).structuredContent.motionIk[0];+ assert.ok(Array.isArray(legReport.limited) && Array.isArray(legReport.warnings), JSON.stringify(legReport));+ report.legIk = legReport;+ const legStart = await look(sessionId, 'leg-start', 0);+ const legEnd = await look(sessionId, 'leg-end', 2);+ assert.notEqual(legEnd, legStart, 'the leg target and the driver move the character');+ assert.equal(await look(sessionId, null, 0), legStart, 'seeking back gives the same picture with constraints and drivers');+ const armMotionApplied = (await call('scene_apply', { sessionId, expectedRevision: revision, operations: [{ type: 'set-motion', motion }] })).structuredContent;+ revision = armMotionApplied.revision;+const restored = (await call('scene_restore', { sessionId, checkpointId: checkpoint.checkpointId, expectedRevision: revision })).structuredContent;revision = restored.revision;assert.equal(await look(sessionId), base, 'restore gives back the exact picture from before the IK');diff --git a/skills/build-67js-scene/SKILL.md b/skills/build-67js-scene/SKILL.mdindex a6632ea3..ffce5e1a 100644--- a/skills/build-67js-scene/SKILL.md+++ b/skills/build-67js-scene/SKILL.md@@ -40,7 +40,7 @@ Use `simplify-code` and `engineering-workflows` for implementation.- A surface look in a recipe (wood, planks, bricks, tiles, marble, stone, concrete, metal, rust, fabric) uses the material `pattern` field, which needs no UVs. See "Material patterns" in the checkout's `docs/agent-scene.md`.- Glass, water, gems, car paint and cloth in a recipe use the material layer fields `transmission` (with `thickness` and `ior`), `clearcoat`, `sheenColor` and `specular`. A transmissive material needs a nonzero `thickness` to bend the view behind it, and does not show blended surfaces. Ranges and limits are in "Material layers" in the checkout's `docs/material-maps.md`.- Layered skeletal animation in code (a clip on some joints only, additive clips, foot planting, reaching, looking at a point) uses `createAssetPose` from `src/skeleton-pose.js` and the checkout's `docs/skeleton-pose.md`. Clip layers are not available through MCP.-- Jointed motion (an arm reaching, a lamp or head tracking a point) on a recipe or an imported character uses `motion.ik`, which needs no quaternions: on a recipe parent the joint nodes and put sizes on child mesh nodes, on an asset find `node-N` IDs with `scene_inspect` kind hierarchy and aim with `worldForward`. Read `motionIk` from `scene_inspect`. See "Inverse kinematics" in the checkout's `docs/agent-motion.md`.+- Jointed motion (an arm reaching, a lamp or head tracking a point) on a recipe or an imported character uses `motion.ik`, which needs no quaternions: on a recipe parent the joint nodes and put sizes on child mesh nodes, on an asset find `node-N` IDs with `scene_inspect` kind hierarchy and aim with `worldForward`. Read `motionIk` from `scene_inspect`: besides `reached`, it lists `warnings` (`wrong-bend` when a knee or elbow bends the unnatural way, `hyperextended`) and `limited` (poses a joint limit changed). Give a leg or arm `bendToward` (a world direction, such as `[0, 0, 1]` for a knee on a character facing +z) and `limits` per joint in degrees, and fix any warning before you finish. `motion.constraints` (copy, limit, `track_to`, `child_of`, `floor`, Blender's meanings, Euler XYZ degrees) and `motion.drivers` (a node or material property from a bounded JSON expression) run after IK and give the same pose at any time. See "Inverse kinematics", "Constraints" and "Drivers" in the checkout's `docs/agent-motion.md`.- 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.- Agent procedural animation uses `docs/agent-motion.md` from release `0.7.0`. Author recipe tracks, then seek through `sampleMotion` or MCP `motionTime`.diff --git a/src/agent-asset.js b/src/agent-asset.jsindex f8f671fa..9bd53a18 100644--- a/src/agent-asset.js+++ b/src/agent-asset.js@@ -480,8 +480,8 @@ export function createAgentAssetScene(asset, inputRecipe) {const nodeOverrides = trackOverrides(candidate.nodeOverrides, sampled);if (targetTime !== null && stagedSampler?.ikUsesStagedPose) {const nodePoses = stagedNodePoses(candidate.animation, [...nodeOverrides.values()]);- for (const { id, rotation } of stagedSampler.solveStagedIk(targetTime, nodePoses)) {- nodeOverrides.set(id, { ...nodeOverrides.get(id), id, rotation });+ for (const override of stagedSampler.solveStagedPose(targetTime, nodePoses)) {+ nodeOverrides.set(override.id, { ...nodeOverrides.get(override.id), ...override });}}let transaction;diff --git a/src/agent-motion.js b/src/agent-motion.jsindex e2486e41..0842299b 100644--- a/src/agent-motion.js+++ b/src/agent-motion.js@@ -1,6 +1,8 @@import { createAnimationClip, compileAnimationSampler } from './animation.js';import { createCameraPath } from './camera-path.js';import { createSkeletonPose } from './skeleton-pose.js';+import { createNodeConstraintEvaluator, normalizeConstraints, normalizeDrivers } from './node-constraints.js';+import { bounded, denseArray, finite, knownKeys, valueFrom } from './motion-validation.js';const PROPERTIES = {node: { translation: 3, rotation: 4, scale: 3 },@@ -12,57 +14,6 @@ const MAX_IK_SOLVERS = 16;const IK_SWEEP_SAMPLES = 33;const CAMERA_DEFAULTS = { eye: [4, 3, 5], target: [0, 0, 0], up: [0, 1, 0], fov: 45, near: 0.1, far: 1000 };-function knownKeys(value, fields, label) {- if (!value || Object.getPrototypeOf(value) !== Object.prototype) {- throw new TypeError(`${label} must be a plain object.`);- }- for (const key of Reflect.ownKeys(value)) {- const descriptor = Object.getOwnPropertyDescriptor(value, key);- if (typeof key !== 'string' || !fields.includes(key) || !descriptor.enumerable || !Object.hasOwn(descriptor, 'value')) {- throw new TypeError(`Unknown or unsupported ${label} field: ${String(key)}.`);- }- }-}--function finite(value, label) {- if (!Number.isFinite(value) || !Number.isFinite(Math.fround(value))) {- throw new RangeError(`${label} must be finite at Float32 precision.`);- }- return value;-}--function bounded(value, minimum, maximum, label) {- finite(value, label);- if (value < minimum || value > maximum) {- throw new RangeError(`${label} must be within ${minimum} and ${maximum}.`);- }- return value;-}--function denseArray(value, maximum, label) {- if (!Array.isArray(value) || value.length > maximum || Object.keys(value).length !== value.length ||- Reflect.ownKeys(value).length !== value.length + 1 || Object.keys(value).some((key, index) => key !== String(index))) {- throw new TypeError(`${label} must be a bounded dense array.`);- }- for (let index = 0; index < value.length; index++) {- if (!Object.hasOwn(Object.getOwnPropertyDescriptor(value, index), 'value')) {- throw new TypeError(`${label} cannot contain accessors.`);- }- }- return value;-}--function valueFrom(value, size, label) {- if (size === 1) {- return finite(value, label);- }- denseArray(value, size, label);- if (value.length !== size) {- throw new TypeError(`${label} needs ${size} components.`);- }- return value.map(component => finite(component, label));-}-function validateValue(kind, property, value) {const components = typeof value === 'number' ? [value] : value;for (const component of components) {@@ -171,10 +122,28 @@ function ikWeight(input, duration, label) {return weight;}+/** { root: { x: [min, max], y, z }, middle: {...} } in degrees, the turn away from the rest rotation in the joint's own axes. */+function jointLimits(input, label) {+ knownKeys(input, ['root', 'middle'], label);+ const limits = {};+ for (const joint of Object.keys(input)) {+ knownKeys(input[joint], ['x', 'y', 'z'], `${label} ${joint}`);+ limits[joint] = {};+ for (const axis of Object.keys(input[joint])) {+ const range = valueFrom(input[joint][axis], 2, `${label} ${joint}.${axis}`);+ if (range[0] > range[1] || range[0] < -180 || range[1] > 180) {+ throw new RangeError(`${label} ${joint}.${axis} must be [min, max] degrees within -180 and 180, min first.`);+ }+ limits[joint][axis] = range;+ }+ }+ return limits;+}+function normalizeIkSolver(input, position, nodes, visibleNodes, duration) {const label = `Motion ik ${position}`;if (input?.type === 'two-bone') {- knownKeys(input, ['type', 'root', 'middle', 'end', 'target', 'pole', 'weight', 'keepEndRotation'], label);+ knownKeys(input, ['type', 'root', 'middle', 'end', 'target', 'pole', 'weight', 'keepEndRotation', 'limits', 'bendToward'], label);const solver = {type: 'two-bone',root: nodeIdFrom(input.root, nodes, `${label} root`),@@ -192,6 +161,12 @@ function normalizeIkSolver(input, position, nodes, visibleNodes, duration) {}solver.keepEndRotation = input.keepEndRotation;}+ if (input.limits !== undefined) {+ solver.limits = jointLimits(input.limits, `${label} limits`);+ }+ if (input.bendToward !== undefined) {+ solver.bendToward = valueFrom(input.bendToward, 3, `${label} bendToward`);+ }return solver;}if (input?.type === 'aim') {@@ -294,15 +269,15 @@ export function normalizeAgentMotion(input, recipe) {if (input === null || input === undefined) {return null;}- knownKeys(input, ['duration', 'loop', 'tracks', 'ik'], 'motion');+ knownKeys(input, ['duration', 'loop', 'tracks', 'ik', 'constraints', 'drivers'], 'motion');const duration = bounded(input.duration, 0.1, 30, 'Motion duration');const loop = input.loop === undefined ? false : input.loop;if (typeof loop !== 'boolean') {throw new TypeError('Motion loop must be boolean.');}denseArray(input.tracks, 128, 'Motion tracks');- if (!input.tracks.length && !input.ik?.length) {- throw new RangeError('Motion needs at least one track or IK solver. Use null to clear it.');+ if (!input.tracks.length && !input.ik?.length && !input.constraints?.length && !input.drivers?.length) {+ throw new RangeError('Motion needs at least one track, IK solver, constraint or driver. Use null to clear it.');}const nodes = new Set((recipe.nodes ?? []).map(node => node.id));const materials = new Set((recipe.materials ?? []).map(material => material.id));@@ -363,6 +338,18 @@ export function normalizeAgentMotion(input, recipe) {throw new RangeError('Motion exceeds 2048 total keyframes.');}}+ const visibleIds = new Set(ikHierarchy(recipe).map(node => node.id));+ if (input.constraints !== undefined) {+ result.constraints = normalizeConstraints(input.constraints, nodes, visibleIds);+ }+ if (input.drivers !== undefined) {+ result.drivers = normalizeDrivers(input.drivers, nodes, materials, visibleIds);+ for (const { target } of result.drivers) {+ if (identities.has(JSON.stringify([target.kind, target.id, target.property]))) {+ throw new RangeError(`Motion driver for ${target.id} ${target.property} clashes with a track on the same property.`);+ }+ }+ }return result;}@@ -428,7 +415,7 @@ function createIkEvaluator(motion, recipe, stagedNodeTracks) {return {...common, type: 'two-bone', root: solver.root, middle: solver.middle, end: solver.end,...(solver.pole ? { pole: pointReader(solver.pole, `pole ${position}`) } : {}),- keepEndRotation: solver.keepEndRotation,+ keepEndRotation: solver.keepEndRotation, limits: solver.limits, bendToward: solver.bendToward,};});pose = createSkeletonPose({ rig, ik: definitions });@@ -485,6 +472,12 @@ function validateRadiance(material) {}}+/** IDs of the nodes a driver or constraint writes. */+function constrainedNodeIds(motion) {+ const driven = (motion.drivers ?? []).filter(driver => driver.target.kind === 'node').map(driver => driver.target.id);+ return new Set([...driven, ...(motion.constraints ?? []).map(constraint => constraint.node)]);+}+/** Retains published maps and vectors. A failed sample leaves them unchanged. */export function compileAgentMotion(input, recipe) {const motion = normalizeAgentMotion(input, recipe);@@ -521,8 +514,12 @@ export function compileAgentMotion(input, recipe) {stagedNodeTracks.get(track.id)[track.property] = staged;}const ikEvaluator = motion.ik?.length ? createIkEvaluator(motion, recipe, stagedNodeTracks) : null;- // An imported asset's base pose comes from its decoder, so it asks for IK itself with solveStagedIk.- const ikUsesStagedPose = Boolean(ikEvaluator && recipe.ikHierarchy);+ const constraintEvaluator = createNodeConstraintEvaluator({+ hierarchy: ikHierarchy(recipe), rootMatrix: recipe.ikRootMatrix,+ constraints: motion.constraints, drivers: motion.drivers, materials: recipe.materials ?? [],+ });+ // An imported asset's base pose comes from its decoder, so it asks for IK and constraints itself with solveStagedPose.+ const ikUsesStagedPose = Boolean((ikEvaluator || constraintEvaluator) && recipe.ikHierarchy);if (ikEvaluator && !ikUsesStagedPose) {for (const id of ikEvaluator.staged.keys()) {if (!output.nodes.has(id)) output.nodes.set(id, {});@@ -530,6 +527,20 @@ export function compileAgentMotion(input, recipe) {if (!nodePatch.rotation) nodePatch.rotation = new Float64Array(4);}}+ if (constraintEvaluator && !ikUsesStagedPose) {+ for (const id of constrainedNodeIds(motion)) {+ if (!output.nodes.has(id)) output.nodes.set(id, {});+ const nodePatch = output.nodes.get(id);+ nodePatch.translation ??= new Float64Array(3);+ nodePatch.rotation ??= new Float64Array(4);+ nodePatch.scale ??= new Float64Array(3);+ }+ }+ const drivenMaterials = (motion.drivers ?? []).filter(driver => driver.target.kind === 'material');+ for (const { target } of drivenMaterials) {+ if (!output.materials.has(target.id)) output.materials.set(target.id, {});+ output.materials.get(target.id)[target.property] = target.component === undefined ? 0 : new Float64Array(3);+ }const baselines = new Map((recipe.materials ?? []).map(material => [material.id, structuredClone(material)]));const cameraTracks = motion.tracks.filter(track => track.kind === 'camera');const cameraInput = {@@ -550,12 +561,36 @@ export function compileAgentMotion(input, recipe) {};}const materialSamples = new Map([...output.materials.keys()].map(id => [id, { ...baselines.get(id) }]));+ /** Node values straight from the tracks. A node without a track keeps its rest value. */+ const trackBases = () => new Map([...stagedNodeTracks].map(([id, tracks]) => [id, { ...tracks }]));+ /** The tracks with IK's rotations on top: the pose drivers and constraints start from. */+ function poseBases() {+ const bases = trackBases();+ for (const [id, rotation] of ikEvaluator?.staged ?? []) bases.set(id, { ...bases.get(id), rotation });+ return bases;+ }return Object.freeze({ikUsesStagedPose,- /** Solve IK over a pose an asset staged for this time. Returns the node rotations to add. */- solveStagedIk(time, nodePoses) {- ikEvaluator.solve(time, nodePoses);- return [...ikEvaluator.staged].map(([id, rotation]) => ({ id, rotation: Array.from(rotation) }));+ /**+ * Solve IK, then drivers and constraints, over a pose an asset staged for this time ({ id, translation, rotation,+ * scale } per node). Returns the node overrides to add: rotations for IK nodes, whole transforms for constrained ones.+ */+ solveStagedPose(time, nodePoses) {+ const overrides = new Map();+ const bases = new Map(nodePoses.map(({ id, translation, rotation, scale }) => [id, { translation, rotation, scale }]));+ if (ikEvaluator) {+ ikEvaluator.solve(time, nodePoses);+ for (const [id, rotation] of ikEvaluator.staged) {+ overrides.set(id, { rotation: Array.from(rotation) });+ bases.set(id, { ...bases.get(id), rotation });+ }+ }+ if (constraintEvaluator) {+ for (const [id, frame] of constraintEvaluator.evaluate(time, bases).nodes) {+ overrides.set(id, { translation: Array.from(frame.translation), rotation: Array.from(frame.rotation), scale: Array.from(frame.scale) });+ }+ }+ return [...overrides].map(([id, fields]) => ({ id, ...fields }));},/*** How IK fares across the whole clip: one { type, reached, worstError, atTime } per solver. Moves the sampler.@@ -563,16 +598,24 @@ export function compileAgentMotion(input, recipe) {*/sweepIk(stagedPoseAt) {if (!ikEvaluator) return [];- const worst = motion.ik.map(solver => ({ type: solver.type, reached: true, worstError: 0, atTime: 0 }));+ const worst = motion.ik.map(solver => ({ type: solver.type, reached: true, worstError: 0, atTime: 0, warnings: [], limited: [] }));for (let sample = 0; sample < IK_SWEEP_SAMPLES; sample++) {const time = motion.duration * sample / (IK_SWEEP_SAMPLES - 1);sampler.sample(time);ikEvaluator.solve(time, stagedPoseAt?.(time)).forEach((result, position) => {const record = worst[position];+ const atTime = Number(time.toFixed(3));record.reached = record.reached && result.reached;if (result.error > record.worstError) {record.worstError = Number(result.error.toFixed(6));- record.atTime = Number(time.toFixed(3));+ record.atTime = atTime;+ }+ // Each distinct warning and each limited axis is reported once, at the first time it shows.+ for (const warning of result.warnings ?? []) {+ if (!record.warnings.some(known => known.code === warning.code)) record.warnings.push({ ...warning, atTime });+ }+ for (const change of result.limited ?? []) {+ if (!record.limited.some(known => known.joint === change.joint && known.axis === change.axis)) record.limited.push({ ...change, atTime });}});}@@ -588,6 +631,15 @@ export function compileAgentMotion(input, recipe) {materialSamples.get(track.id)[track.property] = value;}}+ if (!ikUsesStagedPose) ikEvaluator?.solve(time);+ const evaluated = constraintEvaluator?.evaluate(time, ikUsesStagedPose ? trackBases() : poseBases());+ const drivenValues = [];+ for (const { target } of drivenMaterials) {+ const value = evaluated.materials.get(target.id)[target.property];+ validateValue('material', target.property, value);+ materialSamples.get(target.id)[target.property] = value;+ drivenValues.push({ target, value });+ }for (const material of materialSamples.values()) {validateRadiance(material);}@@ -601,8 +653,7 @@ export function compileAgentMotion(input, recipe) {throw new RangeError('Sampled camera lens is invalid at Float32 precision.');}}- if (!ikUsesStagedPose) ikEvaluator?.solve(time);- // Publish only after every track, material product, camera pose and IK solve passes.+ // Publish only after every track, material product, camera pose, IK solve and constraint passes.for (const { track, patch, staged } of bindings) {if (staged.length === 1) {patch[track.property] = staged[0];@@ -613,6 +664,19 @@ export function compileAgentMotion(input, recipe) {if (ikEvaluator && !ikUsesStagedPose) {for (const [id, rotation] of ikEvaluator.staged) output.nodes.get(id).rotation.set(rotation);}+ if (evaluated && !ikUsesStagedPose) {+ for (const [id, frame] of evaluated.nodes) {+ const nodePatch = output.nodes.get(id);+ nodePatch.translation.set(frame.translation);+ nodePatch.rotation.set(frame.rotation);+ nodePatch.scale.set(frame.scale);+ }+ }+ for (const { target, value } of drivenValues) {+ const materialPatch = output.materials.get(target.id);+ if (typeof value === 'number') materialPatch[target.property] = value;+ else materialPatch[target.property].set(value);+ }if (cameraPath) {for (const field of ['eye', 'target', 'up']) {output.camera[field].set(stagedCamera[field]);diff --git a/src/agent-scene-capabilities.js b/src/agent-scene-capabilities.jsindex 09462f2c..d2f489d6 100644--- a/src/agent-scene-capabilities.js+++ b/src/agent-scene-capabilities.js@@ -37,5 +37,7 @@ export const AGENT_SCENE_CAPABILITIES = Object.freeze({lightLinking: false,proceduralMotion: true,motionIk: Object.freeze(['two-bone', 'aim']),+ motionConstraints: Object.freeze(['copy_location', 'copy_rotation', 'copy_scale', 'limit_location', 'limit_rotation', 'track_to', 'child_of', 'floor']),+ motionDrivers: Object.freeze({ maxDrivers: 32, maxConstraints: 32, maxExpressionParts: 64, maxExpressionDepth: 8 }),motionLimits: Object.freeze({ maxTracks: 128, maxKeyframesPerTrack: 64, maxKeyframes: 2048, maxDuration: 30 }),});diff --git a/src/gltf.js b/src/gltf.jsindex 4c728631..1badd974 100644--- a/src/gltf.js+++ b/src/gltf.js@@ -1083,7 +1083,7 @@ export async function parseGltf(data, options = {}) {/** Local transform of every source node in this candidate pose, after the clip and overrides. */nodePoses() {requirePending();- return [...sourceNodes].map(([id, node]) => ({ id, translation: node.position.toArray(), rotation: node.quaternion.toArray() }));+ return [...sourceNodes].map(([id, node]) => ({ id, translation: node.position.toArray(), rotation: node.quaternion.toArray(), scale: node.scale.toArray() }));},commit() {requirePending();diff --git a/src/motion-expression.js b/src/motion-expression.jsnew file mode 100644index 00000000..7af2215a--- /dev/null+++ b/src/motion-expression.js@@ -0,0 +1,118 @@+import { denseArray, knownKeys } from './motion-validation.js';++// Bounded motion expressions: a small JSON language for drivers and constraint influence. An expression is data, never+// code. It is read by walking plain objects against a fixed table of operators, compiled once into closures and checked+// against its limits before anything runs. No string is executed, and operator names come from a Map.+//+// { "mul": [{ "node": "wheel", "property": "rotation", "component": "x" }, 0.01] }+// { "clamp": [{ "mul": ["time", 0.5] }, 0, 1] }+//+// A number is a constant and the string "time" is the motion time in seconds. A node read takes a component (x, y or z)+// of a node's translation, scale, or rotation (Euler XYZ in degrees), in "local" (default) or "world" space.+// Operators: add mul min max (2 to 8 operands), sub div pow mod atan2 gt lt (2), neg abs sin cos sqrt floor fract+// saturate (1), clamp(x, low, high) mix(a, b, t) smoothstep(low, high, x) if(condition, then, otherwise) (3).+// sin and cos take radians; gt, lt and if use 1 and 0 for true and false.++export const MAX_EXPRESSION_NODES = 64;+export const MAX_EXPRESSION_DEPTH = 8;+const MAX_LITERAL = 1e6;+const MAX_OPERANDS = 8;+const COMPONENTS = Object.freeze({ x: 0, y: 1, z: 2 });+const READ_PROPERTIES = ['translation', 'rotation', 'scale'];++const smoothstep = (low, high, value) => {+ const fraction = Math.min(1, Math.max(0, (value - low) / (high - low)));+ return fraction * fraction * (3 - 2 * fraction);+};++const UNARY = new Map([+ ['neg', value => -value], ['abs', Math.abs], ['sin', Math.sin], ['cos', Math.cos], ['sqrt', Math.sqrt],+ ['floor', Math.floor], ['fract', value => value - Math.floor(value)], ['saturate', value => Math.min(1, Math.max(0, value))],+]);+const VARIADIC = new Map([+ ['add', (left, right) => left + right], ['mul', (left, right) => left * right], ['min', Math.min], ['max', Math.max],+]);+const BINARY = new Map([+ ['sub', (left, right) => left - right], ['div', (left, right) => left / right], ['pow', Math.pow],+ ['mod', (left, right) => left - right * Math.floor(left / right)], ['atan2', Math.atan2],+ ['gt', (left, right) => (left > right ? 1 : 0)], ['lt', (left, right) => (left < right ? 1 : 0)],+]);+const TERNARY = new Map([+ ['clamp', (value, low, high) => Math.min(high, Math.max(low, value))],+ ['mix', (start, end, fraction) => start + (end - start) * fraction],+ ['smoothstep', smoothstep],+ ['if', (condition, thenValue, otherwiseValue) => (condition > 0 ? thenValue : otherwiseValue)],+]);++function compileRead(input, state, label) {+ knownKeys(input, ['node', 'property', 'component', 'space'], `${label} node read`);+ if (!state.nodeIds.has(input.node)) throw new RangeError(`${label}: node ${JSON.stringify(input.node)} is not in this scene.`);+ if (!READ_PROPERTIES.includes(input.property)) throw new RangeError(`${label}: property must be translation, rotation or scale.`);+ if (!Object.hasOwn(COMPONENTS, input.component)) throw new RangeError(`${label}: component must be x, y or z.`);+ const space = input.space ?? 'local';+ if (space !== 'local' && space !== 'world') throw new RangeError(`${label}: space must be local or world.`);+ state.reads.add(input.node);+ const component = COMPONENTS[input.component];+ return context => context.read(input.node, input.property, component, space);+}++function compileOperator(input, state, depth, label) {+ const keys = Object.keys(input);+ if (keys.length !== 1) throw new TypeError(`${label}: an operator object has exactly one key, such as {"add": [1, 2]}.`);+ const [name] = keys;+ const operands = denseArray(input[name], MAX_OPERANDS, `${label} ${name} operands`).map(operand => compile(operand, state, depth + 1, label));+ const arity = (count, text) => {+ if (operands.length !== count) throw new RangeError(`${label}: ${name} takes ${text}.`);+ };+ if (UNARY.has(name)) {+ arity(1, 'one operand');+ const compute = UNARY.get(name);+ return context => compute(operands[0](context));+ }+ if (VARIADIC.has(name)) {+ if (operands.length < 2) throw new RangeError(`${label}: ${name} takes 2 to ${MAX_OPERANDS} operands.`);+ const compute = VARIADIC.get(name);+ return context => operands.slice(1).reduce((total, operand) => compute(total, operand(context)), operands[0](context));+ }+ if (BINARY.has(name)) {+ arity(2, 'two operands');+ const compute = BINARY.get(name);+ return context => compute(operands[0](context), operands[1](context));+ }+ if (TERNARY.has(name)) {+ arity(3, 'three operands');+ const compute = TERNARY.get(name);+ return context => compute(operands[0](context), operands[1](context), operands[2](context));+ }+ throw new RangeError(`${label}: unknown operator ${JSON.stringify(name.slice(0, 24))}.`);+}++function compile(input, state, depth, label) {+ state.count += 1;+ if (state.count > MAX_EXPRESSION_NODES) throw new RangeError(`${label} has more than ${MAX_EXPRESSION_NODES} parts.`);+ if (depth > MAX_EXPRESSION_DEPTH) throw new RangeError(`${label} nests deeper than ${MAX_EXPRESSION_DEPTH} levels.`);+ if (typeof input === 'number') {+ if (!Number.isFinite(input) || Math.abs(input) > MAX_LITERAL) throw new RangeError(`${label}: a number must be finite and within ${MAX_LITERAL}.`);+ return () => input;+ }+ if (input === 'time') return context => context.time;+ if (!input || Object.getPrototypeOf(input) !== Object.prototype) throw new TypeError(`${label}: use a number, "time", a node read or an operator object.`);+ return Object.hasOwn(input, 'node') ? compileRead(input, state, label) : compileOperator(input, state, depth, label);+}++/**+ * Compile an expression. `evaluate({ time, read })` returns a finite number; `read(id, property, component, space)`+ * supplies node values. `reads` lists the node IDs the expression looks at.+ */+export function compileMotionExpression(input, nodeIds, label) {+ const state = { count: 0, reads: new Set(), nodeIds };+ const evaluateTree = compile(input, state, 0, label);+ return Object.freeze({+ reads: [...state.reads],+ evaluate(context) {+ const value = evaluateTree(context);+ if (!Number.isFinite(value)) throw new RangeError(`${label} produced ${value} at time ${context.time}; it must stay finite.`);+ return value;+ },+ });+}diff --git a/src/motion-validation.js b/src/motion-validation.jsnew file mode 100644index 00000000..7acf1eae--- /dev/null+++ b/src/motion-validation.js@@ -0,0 +1,52 @@+// Checks shared by the motion normalizers: agent input is untrusted plain data, so every field is named and bounded.++export function knownKeys(value, fields, label) {+ if (!value || Object.getPrototypeOf(value) !== Object.prototype) {+ throw new TypeError(`${label} must be a plain object.`);+ }+ for (const key of Reflect.ownKeys(value)) {+ const descriptor = Object.getOwnPropertyDescriptor(value, key);+ if (typeof key !== 'string' || !fields.includes(key) || !descriptor.enumerable || !Object.hasOwn(descriptor, 'value')) {+ throw new TypeError(`Unknown or unsupported ${label} field: ${String(key)}.`);+ }+ }+}++export function finite(value, label) {+ if (!Number.isFinite(value) || !Number.isFinite(Math.fround(value))) {+ throw new RangeError(`${label} must be finite at Float32 precision.`);+ }+ return value;+}++export function bounded(value, minimum, maximum, label) {+ finite(value, label);+ if (value < minimum || value > maximum) {+ throw new RangeError(`${label} must be within ${minimum} and ${maximum}.`);+ }+ return value;+}++export function denseArray(value, maximum, label) {+ if (!Array.isArray(value) || value.length > maximum || Object.keys(value).length !== value.length ||+ Reflect.ownKeys(value).length !== value.length + 1 || Object.keys(value).some((key, index) => key !== String(index))) {+ throw new TypeError(`${label} must be a bounded dense array.`);+ }+ for (let index = 0; index < value.length; index++) {+ if (!Object.hasOwn(Object.getOwnPropertyDescriptor(value, index), 'value')) {+ throw new TypeError(`${label} cannot contain accessors.`);+ }+ }+ return value;+}++export function valueFrom(value, size, label) {+ if (size === 1) {+ return finite(value, label);+ }+ denseArray(value, size, label);+ if (value.length !== size) {+ throw new TypeError(`${label} needs ${size} components.`);+ }+ return value.map(component => finite(component, label));+}diff --git a/src/node-constraints.js b/src/node-constraints.jsnew file mode 100644index 00000000..1c8d55a1--- /dev/null+++ b/src/node-constraints.js@@ -0,0 +1,450 @@+import { mat4, quat, vec3 } from 'gl-matrix';+import { compileMotionExpression } from './motion-expression.js';+import { bounded, denseArray, knownKeys, valueFrom } from './motion-validation.js';+import { eulerFromQuaternion, quaternionFromEuler } from './rotation-euler.js';++// Node constraints and drivers, evaluated in this order for any time, with no state kept between calls:+// 1. Base pose: the node values after tracks and IK.+// 2. Drivers, in list order. They read the base pose, so one driver never sees another's result.+// 3. Constraints, in list order. Each reads the pose the ones before it left, including its target's constrained pose.+// Seeking to a time therefore gives the same pose as playing up to it. Constraints act on a node's world matrix and+// keep Blender's meaning: Euler angles are XYZ in degrees, copy and limit work per axis, influence blends the matrix+// before and after, and child_of multiplies the owner by the target's matrix and an inverse.++export const MAX_CONSTRAINTS = 32;+export const MAX_DRIVERS = 32;+const AXES = ['x', 'y', 'z'];+const SIGNED_AXES = ['+x', '-x', '+y', '-y', '+z', '-z'];+const TO_RADIANS = Math.PI / 180;+const NEAR_ZERO = 1e-9;+const MAX_COORDINATE = 1e6;+const SPACES = ['world', 'local'];+const MATERIAL_SCALARS = ['emission', 'metallic', 'roughness'];+const MATERIAL_VECTORS = ['color', 'emissiveColor'];++const COMMON_FIELDS = ['type', 'node', 'influence'];+const CONSTRAINT_FIELDS = {+ copy_location: ['target', 'axes', 'invert', 'offset', 'space'],+ copy_rotation: ['target', 'axes', 'invert', 'mix', 'space'],+ copy_scale: ['target', 'axes', 'offset', 'space'],+ limit_location: ['x', 'y', 'z', 'space'],+ limit_rotation: ['x', 'y', 'z', 'space'],+ track_to: ['target', 'trackAxis', 'upAxis', 'worldUp'],+ child_of: ['target', 'inverse'],+ floor: ['target', 'axis', 'offset'],+};+export const CONSTRAINT_TYPES = Object.freeze(Object.keys(CONSTRAINT_FIELDS));++// ---------------------------------------------------------------------------------------------------------------+// Input++function axisList(value, label) {+ if (value === undefined) return [...AXES];+ denseArray(value, 3, label);+ if (!value.length || value.some(axis => !AXES.includes(axis)) || new Set(value).size !== value.length) {+ throw new RangeError(`${label} must list distinct axes from x, y and z.`);+ }+ return [...value];+}++function oneOf(value, allowed, fallback, label) {+ if (value === undefined) return fallback;+ if (!allowed.includes(value)) throw new RangeError(`${label} must be one of ${allowed.join(', ')}.`);+ return value;+}++function axisRanges(input, limit, label) {+ const ranges = {};+ for (const axis of AXES) {+ if (input[axis] === undefined) continue;+ const range = valueFrom(input[axis], 2, `${label} ${axis}`);+ if (range[0] > range[1] || Math.abs(range[0]) > limit || Math.abs(range[1]) > limit) {+ throw new RangeError(`${label} ${axis} must be [min, max] within ${-limit} and ${limit}, min first.`);+ }+ ranges[axis] = range;+ }+ if (!Object.keys(ranges).length) throw new RangeError(`${label} needs an x, y or z range.`);+ return ranges;+}++function influenceFrom(value, nodeIds, label) {+ if (value === undefined) return 1;+ if (typeof value === 'number') return bounded(value, 0, 1, `${label} influence`);+ compileMotionExpression(value, nodeIds, `${label} influence`);+ return structuredClone(value);+}++function normalizeConstraint(input, position, movableIds, visibleIds) {+ const label = `Motion constraint ${position}`;+ if (!input || !Object.hasOwn(CONSTRAINT_FIELDS, input.type)) {+ throw new RangeError(`${label} type must be one of ${CONSTRAINT_TYPES.join(', ')}.`);+ }+ knownKeys(input, [...COMMON_FIELDS, ...CONSTRAINT_FIELDS[input.type]], label);+ if (!movableIds.has(input.node)) throw new RangeError(`${label} node must be a node ID in this recipe; got ${JSON.stringify(input.node)}.`);+ const result = { type: input.type, node: input.node, influence: influenceFrom(input.influence, visibleIds, label) };+ if (CONSTRAINT_FIELDS[input.type].includes('target')) {+ if (!visibleIds.has(input.target)) throw new RangeError(`${label} target must be a node ID in this recipe; got ${JSON.stringify(input.target)}.`);+ if (input.target === input.node) throw new RangeError(`${label} target cannot be the constrained node itself.`);+ result.target = input.target;+ }+ if (CONSTRAINT_FIELDS[input.type].includes('space')) result.space = oneOf(input.space, SPACES, 'world', `${label} space`);+ switch (input.type) {+ case 'copy_location':+ case 'copy_rotation':+ case 'copy_scale':+ result.axes = axisList(input.axes, `${label} axes`);+ if (input.invert !== undefined) {+ if (input.type === 'copy_scale') throw new TypeError(`${label} does not take invert.`);+ result.invert = axisList(input.invert, `${label} invert`);+ }+ if (input.offset !== undefined) {+ if (typeof input.offset !== 'boolean' || input.type === 'copy_rotation') throw new TypeError(`${label} offset must be a boolean on copy_location and copy_scale.`);+ result.offset = input.offset;+ }+ if (input.type === 'copy_rotation') result.mix = oneOf(input.mix, ['replace', 'add'], 'replace', `${label} mix`);+ break;+ case 'limit_location':+ Object.assign(result, axisRanges(input, MAX_COORDINATE, label));+ break;+ case 'limit_rotation':+ Object.assign(result, axisRanges(input, 180, label));+ break;+ case 'track_to': {+ result.trackAxis = oneOf(input.trackAxis, SIGNED_AXES, '-z', `${label} trackAxis`);+ result.upAxis = oneOf(input.upAxis, AXES, 'y', `${label} upAxis`);+ if (result.trackAxis.slice(1) === result.upAxis) throw new RangeError(`${label} trackAxis and upAxis must be different axes.`);+ result.worldUp = input.worldUp === undefined ? [0, 1, 0] : valueFrom(input.worldUp, 3, `${label} worldUp`);+ if (vec3.length(result.worldUp) < NEAR_ZERO) throw new RangeError(`${label} worldUp cannot be zero.`);+ break;+ }+ case 'child_of':+ result.inverse = oneOf(input.inverse, ['rest', 'none'], 'rest', `${label} inverse`);+ break;+ default:+ result.axis = oneOf(input.axis, SIGNED_AXES, '+y', `${label} axis`);+ result.offset = input.offset === undefined ? 0 : bounded(input.offset, -MAX_COORDINATE, MAX_COORDINATE, `${label} offset`);+ }+ return result;+}++/** Validate a constraint list against the node IDs a motion may move and the ones it may read. Returns plain data. */+export function normalizeConstraints(input, movableIds, visibleIds) {+ denseArray(input, MAX_CONSTRAINTS, 'Motion constraints');+ return input.map((constraint, position) => normalizeConstraint(constraint, position, movableIds, visibleIds));+}++function normalizeDriver(input, position, movableIds, materialIds, visibleIds) {+ const label = `Motion driver ${position}`;+ knownKeys(input, ['target', 'expression'], label);+ knownKeys(input.target, ['kind', 'id', 'property', 'component'], `${label} target`);+ const { kind, id, property, component } = input.target;+ if (component !== undefined && !AXES.includes(component)) throw new RangeError(`${label} component must be x, y or z.`);+ if (kind === 'node') {+ if (!movableIds.has(id)) throw new RangeError(`${label} node must be a node ID in this recipe; got ${JSON.stringify(id)}.`);+ if (!['translation', 'rotation', 'scale'].includes(property)) throw new RangeError(`${label} property must be translation, rotation or scale.`);+ if (component === undefined) throw new RangeError(`${label} needs a component: x, y or z. Rotation is Euler XYZ in degrees.`);+ } else if (kind === 'material') {+ if (!materialIds.has(id)) throw new RangeError(`${label} material was not found: ${JSON.stringify(id)}.`);+ const isVector = MATERIAL_VECTORS.includes(property);+ if (!isVector && !MATERIAL_SCALARS.includes(property)) throw new RangeError(`${label} property must be one of ${[...MATERIAL_VECTORS, ...MATERIAL_SCALARS].join(', ')}.`);+ if (isVector !== (component !== undefined)) throw new RangeError(`${label}: color properties need a component (x, y, z for red, green, blue); the others take none.`);+ } else {+ throw new RangeError(`${label} target kind must be node or material.`);+ }+ compileMotionExpression(input.expression, visibleIds, `${label} expression`);+ return { target: { kind, id, property, ...(component === undefined ? {} : { component }) }, expression: structuredClone(input.expression) };+}++export function normalizeDrivers(input, movableIds, materialIds, visibleIds) {+ denseArray(input, MAX_DRIVERS, 'Motion drivers');+ const seen = new Set();+ return input.map((driver, position) => {+ const normalized = normalizeDriver(driver, position, movableIds, materialIds, visibleIds);+ const identity = JSON.stringify(Object.values(normalized.target));+ if (seen.has(identity)) throw new RangeError(`Motion driver ${position} drives the same property as an earlier driver.`);+ seen.add(identity);+ return normalized;+ });+}++// ---------------------------------------------------------------------------------------------------------------+// Matrices and frames. A frame is { translation, rotation, scale }.++// gl-matrix's getRotation divides the wrong entries by the scale, so non-uniform scale gives a wrong rotation.+function rotationOfMatrix(matrix, scale) {+ const axes = [0, 4, 8].map((start, column) => Array.from(matrix.slice(start, start + 3), component => component / (scale[column] || 1)));+ return quat.normalize(new Float64Array(4), quat.fromMat3(new Float64Array(4), axes.flat()));+}++function decompose(matrix) {+ const scale = mat4.getScaling(new Float64Array(3), matrix);+ return { translation: mat4.getTranslation(new Float64Array(3), matrix), rotation: rotationOfMatrix(matrix, scale), scale };+}++function compose(frame) {+ return mat4.fromRotationTranslationScale(new Float64Array(16), frame.rotation, frame.translation, frame.scale);+}++function copyFrame(frame) {+ return { translation: Float64Array.from(frame.translation), rotation: Float64Array.from(frame.rotation), scale: Float64Array.from(frame.scale) };+}++/** Blend two world matrices the way Blender blends a constraint's influence: location, rotation and scale separately. */+function blendMatrices(before, after, influence) {+ if (influence >= 1) return after;+ const from = decompose(before);+ const to = decompose(after);+ return compose({+ translation: vec3.lerp(new Float64Array(3), from.translation, to.translation, influence),+ rotation: quat.slerp(new Float64Array(4), from.rotation, to.rotation, influence),+ scale: vec3.lerp(new Float64Array(3), from.scale, to.scale, influence),+ });+}++function signOf(axis) {+ return axis.startsWith('-') ? -1 : 1;+}++function axisIndex(axis) {+ return AXES.indexOf(axis.replace(/^[+-]/, ''));+}++// ---------------------------------------------------------------------------------------------------------------+// Constraint operators on frames (copy and limit) and on matrices (track_to, child_of, floor).++function copyLocation(owner, target, constraint) {+ for (const axis of constraint.axes) {+ const index = axisIndex(axis);+ const sign = constraint.invert?.includes(axis) ? -1 : 1;+ owner.translation[index] = (constraint.offset ? owner.translation[index] : 0) + sign * target.translation[index];+ }+}++function copyRotation(owner, target, constraint) {+ const angles = eulerFromQuaternion(owner.rotation);+ const wanted = eulerFromQuaternion(target.rotation);+ for (const axis of constraint.axes) {+ const index = axisIndex(axis);+ const sign = constraint.invert?.includes(axis) ? -1 : 1;+ angles[index] = (constraint.mix === 'add' ? angles[index] : 0) + sign * wanted[index];+ }+ quaternionFromEuler(owner.rotation, angles[0], angles[1], angles[2]);+}++function copyScale(owner, target, constraint) {+ for (const axis of constraint.axes) {+ const index = axisIndex(axis);+ owner.scale[index] = (constraint.offset ? owner.scale[index] : 1) * target.scale[index];+ }+}++function limitLocation(owner, target, constraint) {+ for (const axis of AXES) {+ if (!constraint[axis]) continue;+ const index = axisIndex(axis);+ owner.translation[index] = Math.min(constraint[axis][1], Math.max(constraint[axis][0], owner.translation[index]));+ }+}++function limitRotation(owner, target, constraint) {+ const angles = eulerFromQuaternion(owner.rotation);+ for (const axis of AXES) {+ if (!constraint[axis]) continue;+ const index = axisIndex(axis);+ angles[index] = Math.min(constraint[axis][1] * TO_RADIANS, Math.max(constraint[axis][0] * TO_RADIANS, angles[index]));+ }+ quaternionFromEuler(owner.rotation, angles[0], angles[1], angles[2]);+}++const FRAME_CONSTRAINTS = {+ copy_location: copyLocation, copy_rotation: copyRotation, copy_scale: copyScale,+ limit_location: limitLocation, limit_rotation: limitRotation,+};++function perpendicularTo(direction) {+ const reference = Math.abs(direction[1]) < 0.9 ? [0, 1, 0] : [1, 0, 0];+ return vec3.normalize(new Float64Array(3), vec3.cross(new Float64Array(3), direction, reference));+}++/** Turn the owner so its track axis points at the target and its up axis leans toward worldUp. Position and scale stay. */+function trackTo(ownerWorld, targetWorld, constraint) {+ const frame = decompose(ownerWorld);+ const forward = vec3.subtract(new Float64Array(3), mat4.getTranslation(new Float64Array(3), targetWorld), frame.translation);+ if (vec3.length(forward) < NEAR_ZERO) return ownerWorld;+ vec3.normalize(forward, forward);+ const worldUp = vec3.normalize(new Float64Array(3), constraint.worldUp);+ const up = vec3.scaleAndAdd(new Float64Array(3), worldUp, forward, -vec3.dot(worldUp, forward));+ if (vec3.length(up) < 1e-6) vec3.copy(up, perpendicularTo(forward));+ vec3.normalize(up, up);+ const trackIndex = axisIndex(constraint.trackAxis);+ const upIndex = AXES.indexOf(constraint.upAxis);+ const columns = [null, null, null];+ columns[trackIndex] = vec3.scale(new Float64Array(3), forward, signOf(constraint.trackAxis));+ columns[upIndex] = up;+ const thirdIndex = 3 - trackIndex - upIndex;+ columns[thirdIndex] = vec3.cross(new Float64Array(3), columns[(thirdIndex + 1) % 3], columns[(thirdIndex + 2) % 3]);+ frame.rotation = quat.normalize(new Float64Array(4), quat.fromMat3(new Float64Array(4), columns.flatMap(column => Array.from(column))));+ return compose(frame);+}++function floorConstraint(ownerWorld, targetWorld, constraint) {+ const normal = new Float64Array(3);+ normal[axisIndex(constraint.axis)] = signOf(constraint.axis);+ const position = mat4.getTranslation(new Float64Array(3), ownerWorld);+ const planePoint = mat4.getTranslation(new Float64Array(3), targetWorld);+ const height = vec3.dot(vec3.subtract(new Float64Array(3), position, planePoint), normal);+ if (height >= constraint.offset) return ownerWorld;+ const lifted = mat4.clone(ownerWorld);+ const raise = constraint.offset - height;+ for (let index = 0; index < 3; index++) lifted[12 + index] += normal[index] * raise;+ return lifted;+}++// ---------------------------------------------------------------------------------------------------------------+// Evaluation++function topologicalOrder(hierarchy, indexById) {+ const order = [];+ const visited = new Uint8Array(hierarchy.length);+ const visit = index => {+ if (visited[index]) return;+ visited[index] = 1;+ const parent = hierarchy[index].parent;+ if (parent !== undefined && parent !== null) visit(indexById.get(parent));+ order.push(index);+ };+ hierarchy.forEach((node, index) => visit(index));+ return order;+}++function restFrame(node) {+ return {+ translation: Float64Array.from(node.translation ?? [0, 0, 0]),+ rotation: Float64Array.from(node.rotation ?? [0, 0, 0, 1]),+ scale: Float64Array.from(node.scale ?? [1, 1, 1]),+ };+}++function wantsEvaluation(constraints, drivers) {+ return Boolean(constraints?.length || drivers?.length);+}++/**+ * Build an evaluator over { hierarchy, rootMatrix, constraints, drivers, materials }. `hierarchy` lists every node as+ * { id, parent, translation, rotation, scale }. `evaluate(time, bases)` takes the base pose as a Map of node ID to+ * { translation, rotation, scale } (missing parts use the rest pose) and returns the final local frames of every node+ * a driver or constraint writes, plus driven material values. The base arrays are not changed.+ */+export function createNodeConstraintEvaluator({ hierarchy, rootMatrix, constraints = [], drivers = [], materials = [] }) {+ if (!wantsEvaluation(constraints, drivers)) return null;+ const indexById = new Map(hierarchy.map((node, index) => [node.id, index]));+ const order = topologicalOrder(hierarchy, indexById);+ const parentIndices = hierarchy.map(node => (node.parent === undefined || node.parent === null ? -1 : indexById.get(node.parent)));+ const rootWorld = rootMatrix ? mat4.clone(rootMatrix) : mat4.create();+ const nodeIds = new Set(indexById.keys());+ const materialBaselines = new Map(materials.map(material => [material.id, material]));+ const compiledDrivers = drivers.map(driver => ({ ...driver, compiled: compileMotionExpression(driver.expression, nodeIds, 'Motion driver expression') }));+ const compiledConstraints = constraints.map(constraint => ({+ ...constraint,+ compiledInfluence: typeof constraint.influence === 'number' ? null : compileMotionExpression(constraint.influence, nodeIds, 'Motion constraint influence'),+ }));++ function computeWorlds(locals) {+ const worlds = new Array(hierarchy.length);+ for (const index of order) {+ const parentWorld = parentIndices[index] >= 0 ? worlds[parentIndices[index]] : rootWorld;+ worlds[index] = mat4.multiply(new Float64Array(16), parentWorld, compose(locals[index]));+ }+ return worlds;+ }++ const restLocals = hierarchy.map(restFrame);+ const restWorlds = computeWorlds(restLocals);++ function readFrom(locals, worlds) {+ return (id, property, component, space) => {+ const index = indexById.get(id);+ const frame = space === 'world' ? decompose(worlds[index]) : locals[index];+ if (property === 'rotation') return eulerFromQuaternion(frame.rotation)[component] / TO_RADIANS;+ return frame[property][component];+ };+ }++ function applyDriver(driver, locals, context, touchedMaterials) {+ const value = driver.compiled.evaluate(context);+ const { kind, id, property, component } = driver.target;+ const index = AXES.indexOf(component);+ if (kind === 'material') {+ if (index < 0) {+ touchedMaterials.set(id, { ...touchedMaterials.get(id), [property]: value });+ return;+ }+ const current = touchedMaterials.get(id)?.[property] ?? Array.from(materialBaselines.get(id)?.[property] ?? [0.5, 0.5, 0.5]);+ current[index] = value;+ touchedMaterials.set(id, { ...touchedMaterials.get(id), [property]: current });+ return;+ }+ const frame = locals[indexById.get(id)];+ if (property === 'rotation') {+ const angles = eulerFromQuaternion(frame.rotation);+ angles[index] = value * TO_RADIANS;+ quaternionFromEuler(frame.rotation, angles[0], angles[1], angles[2]);+ return;+ }+ if (property === 'scale' && !(Math.fround(value) > 0)) throw new RangeError(`Motion driver made the scale of ${id} not positive (${value}).`);+ frame[property][index] = value;+ }++ function applyConstraint(constraint, locals, context) {+ const worlds = computeWorlds(locals);+ const ownerIndex = indexById.get(constraint.node);+ const parentWorld = parentIndices[ownerIndex] >= 0 ? worlds[parentIndices[ownerIndex]] : rootWorld;+ const ownerWorld = worlds[ownerIndex];+ const targetIndex = constraint.target === undefined ? -1 : indexById.get(constraint.target);+ const influence = constraint.compiledInfluence ? Math.min(1, Math.max(0, constraint.compiledInfluence.evaluate(context))) : constraint.influence;+ let result;+ if (FRAME_CONSTRAINTS[constraint.type]) {+ const inLocalSpace = constraint.space === 'local';+ const owner = inLocalSpace ? copyFrame(locals[ownerIndex]) : decompose(ownerWorld);+ const target = targetIndex < 0 ? null : (inLocalSpace ? locals[targetIndex] : decompose(worlds[targetIndex]));+ FRAME_CONSTRAINTS[constraint.type](owner, target, constraint);+ result = inLocalSpace ? mat4.multiply(new Float64Array(16), parentWorld, compose(owner)) : compose(owner);+ } else if (constraint.type === 'track_to') {+ result = trackTo(ownerWorld, worlds[targetIndex], constraint);+ } else if (constraint.type === 'floor') {+ result = floorConstraint(ownerWorld, worlds[targetIndex], constraint);+ } else {+ const inverse = constraint.inverse === 'rest' ? mat4.invert(new Float64Array(16), restWorlds[targetIndex]) : mat4.create();+ const parent = mat4.multiply(new Float64Array(16), worlds[targetIndex], inverse);+ result = mat4.multiply(new Float64Array(16), parent, ownerWorld);+ }+ const blended = blendMatrices(ownerWorld, result, influence);+ const local = mat4.multiply(new Float64Array(16), mat4.invert(new Float64Array(16), parentWorld), blended);+ locals[ownerIndex] = decompose(local);+ }++ return Object.freeze({+ evaluate(time, bases = new Map()) {+ const baseLocals = hierarchy.map((node, index) => {+ const base = bases.get(node.id);+ const frame = copyFrame(restLocals[index]);+ if (base?.translation) frame.translation.set(base.translation);+ if (base?.rotation) frame.rotation.set(base.rotation);+ if (base?.scale) frame.scale.set(base.scale);+ return frame;+ });+ const context = { time, read: readFrom(baseLocals, computeWorlds(baseLocals)) };+ const locals = baseLocals.map(copyFrame);+ const touchedMaterials = new Map();+ for (const driver of compiledDrivers) applyDriver(driver, locals, context, touchedMaterials);+ for (const constraint of compiledConstraints) applyConstraint(constraint, locals, context);+ const written = new Set([...compiledDrivers.filter(driver => driver.target.kind === 'node').map(driver => driver.target.id), ...compiledConstraints.map(constraint => constraint.node)]);+ const nodes = new Map([...written].map(id => [id, locals[indexById.get(id)]]));+ for (const [id, frame] of nodes) {+ if (![...frame.translation, ...frame.rotation, ...frame.scale].every(Number.isFinite)) throw new RangeError(`Motion constraints produced an invalid pose for node ${id}.`);+ if (frame.scale.some(component => !(Math.fround(component) > 0))) throw new RangeError(`Motion constraints made the scale of node ${id} not positive.`);+ }+ return { nodes, materials: touchedMaterials };+ },+ });+}diff --git a/src/rotation-euler.js b/src/rotation-euler.jsnew file mode 100644index 00000000..528b8d94--- /dev/null+++ b/src/rotation-euler.js@@ -0,0 +1,33 @@+import { quat } from 'gl-matrix';++// Euler angles in Blender's XYZ order: the rotation is X first, then Y, then Z, so R = Rz * Ry * Rx. Angles are radians+// here. Quaternions are XYZW. Constraints and joint limits use this order so their numbers match Blender's.++const GIMBAL_THRESHOLD = 1 - 1e-9;++/** Quaternion from Euler X, Y, Z angles in radians. */+export function quaternionFromEuler(out, angleX, angleY, angleZ) {+ const quaternionX = quat.setAxisAngle(new Float64Array(4), [1, 0, 0], angleX);+ const quaternionY = quat.setAxisAngle(new Float64Array(4), [0, 1, 0], angleY);+ const quaternionZ = quat.setAxisAngle(new Float64Array(4), [0, 0, 1], angleZ);+ quat.multiply(out, quaternionZ, quaternionY);+ return quat.multiply(out, out, quaternionX);+}++/** Euler X, Y, Z angles in radians from a quaternion. At gimbal lock the Z angle is zero and X takes the whole turn. */+export function eulerFromQuaternion(rotation) {+ const [x, y, z, w] = rotation;+ const lengthSquared = x * x + y * y + z * z + w * w;+ const scale = lengthSquared > 0 ? 2 / lengthSquared : 0;+ const row2Column0 = scale * (x * z - w * y);+ const row2Column1 = scale * (y * z + w * x);+ const row2Column2 = 1 - scale * (x * x + y * y);+ const row1Column0 = scale * (x * y + w * z);+ const row0Column0 = 1 - scale * (y * y + z * z);+ if (Math.abs(row2Column0) >= GIMBAL_THRESHOLD) {+ const row1Column1 = 1 - scale * (x * x + z * z);+ const row1Column2 = scale * (y * z - w * x);+ return [Math.atan2(-row1Column2, row1Column1), Math.asin(Math.max(-1, Math.min(1, -row2Column0))), 0];+ }+ return [Math.atan2(row2Column1, row2Column2), Math.asin(-row2Column0), Math.atan2(row1Column0, row0Column0)];+}diff --git a/src/skeleton-pose.js b/src/skeleton-pose.jsindex aaf91e87..cc968d5e 100644--- a/src/skeleton-pose.js+++ b/src/skeleton-pose.js@@ -1,6 +1,7 @@import { mat4, quat, vec3 } from 'gl-matrix';import { compileAnimationSampler, createAnimationClip } from './animation.js';import { updateSkinPose } from './skinning.js';+import { eulerFromQuaternion, quaternionFromEuler } from './rotation-euler.js';import {bindSourceTracks, computeWorldPose, createPoseState, createRigFromSkin, mapHumanoidBones, prepareRigGeometry, validateRigJoints,} from './retarget.js';@@ -146,6 +147,108 @@ function checkedVector(value, label) {return value;}+const LIMIT_AXES = ['x', 'y', 'z'];+// The solver stops just short of full stretch (a 2 to 3 degree bend), so a locked limb reads as about 177 degrees.+const HYPEREXTENSION_ANGLE = 175 * TO_RADIANS;+const MIN_BEND_FRACTION = 0.01;+const MIN_REST_BEND_FRACTION = 0.02;++/**+ * Joint limits from { root: { x: [min, max], y, z }, middle: {...} } in degrees. Angles are the joint's turn away from its+ * rest rotation, in its own axes, as Euler XYZ (the order Blender uses). An axis left out is free.+ */+function createJointLimits(definition, label, jointIndices, prepared) {+ if (definition === undefined) return [];+ if (!definition || typeof definition !== 'object' || Array.isArray(definition)) throw new TypeError(`${label} limits must be { root, middle } with an x, y or z range each.`);+ return Object.entries(definition).map(([role, axes]) => {+ if (!Object.hasOwn(jointIndices, role)) throw new RangeError(`${label} limits: ${role} must be root or middle.`);+ const unknownAxis = Object.keys(axes ?? {}).find(axis => !LIMIT_AXES.includes(axis));+ if (unknownAxis !== undefined) throw new RangeError(`${label} limits ${role}: ${unknownAxis} must be x, y or z.`);+ const ranges = LIMIT_AXES.map(axis => {+ const range = axes[axis];+ if (range === undefined) return null;+ if (!Array.isArray(range) || range.length !== 2 || !range.every(Number.isFinite) || range[0] > range[1] || range[0] < -180 || range[1] > 180) {+ throw new RangeError(`${label} limits ${role}.${axis} must be [min, max] degrees within -180 and 180, min first.`);+ }+ return range.map(degrees => degrees * TO_RADIANS);+ });+ const index = jointIndices[role];+ return { index, name: prepared.joints[index].name, ranges };+ });+}++function roundedDegrees(radians) {+ return Number((radians / TO_RADIANS).toFixed(4));+}++/** Clamp each limited joint's local rotation. Returns one { joint, axis, requested, applied } (degrees) per change. */+function applyJointLimits(limits, prepared, localRotations) {+ const changes = [];+ for (const limit of limits) {+ const rest = prepared.restRotations[limit.index];+ const delta = quat.multiply(new Float64Array(4), quat.invert(new Float64Array(4), rest), localRotations[limit.index]);+ const angles = eulerFromQuaternion(delta);+ let changed = false;+ angles.forEach((angle, axis) => {+ const range = limit.ranges[axis];+ if (!range) return;+ const clamped = Math.min(range[1], Math.max(range[0], angle));+ if (Math.abs(clamped - angle) < 1e-9) return;+ changes.push({ joint: limit.name, axis: LIMIT_AXES[axis], requested: roundedDegrees(angle), applied: roundedDegrees(clamped) });+ angles[axis] = clamped;+ changed = true;+ });+ if (!changed) continue;+ quaternionFromEuler(delta, angles[0], angles[1], angles[2]);+ quat.normalize(localRotations[limit.index], quat.multiply(localRotations[limit.index], rest, delta));+ }+ return changes;+}++/** How far the middle joint sits off the straight line from root to end, as a vector. */+function bendVector(rootPosition, middlePosition, endPosition) {+ const line = vec3.subtract(new Float64Array(3), endPosition, rootPosition);+ const toMiddle = vec3.subtract(new Float64Array(3), middlePosition, rootPosition);+ const lineLengthSquared = vec3.squaredLength(line);+ if (lineLengthSquared < NEAR_ZERO) return toMiddle;+ return vec3.scaleAndAdd(toMiddle, toMiddle, line, -vec3.dot(toMiddle, line) / lineLengthSquared);+}++/** The side the limb bent toward at rest, in the frame of the joint above the root. Null when the rest limb is straight. */+function restBendInParentFrame(prepared, root, middle, end) {+ const { positions, rotations } = prepared.restWorld;+ const bend = bendVector(positions[root], positions[middle], positions[end]);+ const chainLength = vec3.distance(positions[root], positions[middle]) + vec3.distance(positions[middle], positions[end]);+ if (vec3.length(bend) < chainLength * MIN_REST_BEND_FRACTION) return null;+ const parent = prepared.joints[root].parent;+ const parentRotation = parent >= 0 ? rotations[parent] : prepared.rootRotation;+ return vec3.transformQuat(new Float64Array(3), bend, quat.invert(new Float64Array(4), parentRotation));+}++/** Sanity checks on a solved limb: locked straight, or bent the opposite way to its natural direction. */+function bendWarnings(solver, state, prepared) {+ const warnings = [];+ const rootPosition = state.positions[solver.root];+ const middlePosition = state.positions[solver.middle];+ const endPosition = state.positions[solver.end];+ const interiorAngle = vec3.angle(vec3.subtract(new Float64Array(3), rootPosition, middlePosition), vec3.subtract(new Float64Array(3), endPosition, middlePosition));+ if (interiorAngle > HYPEREXTENSION_ANGLE) {+ warnings.push({ code: 'hyperextended', message: `${prepared.joints[solver.middle].name} is locked straight (${roundedDegrees(interiorAngle)} degrees). The target is at or beyond the limb's reach, so a real joint would hyperextend.` });+ }+ let expected = solver.bendToward;+ if (!expected && solver.restBend) {+ const parent = prepared.joints[solver.root].parent;+ expected = vec3.transformQuat(new Float64Array(3), solver.restBend, parent >= 0 ? state.rotations[parent] : prepared.rootRotation);+ }+ if (!expected) return warnings;+ const bend = bendVector(rootPosition, middlePosition, endPosition);+ const chainLength = vec3.distance(rootPosition, middlePosition) + vec3.distance(middlePosition, endPosition);+ if (vec3.length(bend) >= chainLength * MIN_BEND_FRACTION && vec3.dot(bend, expected) < 0) {+ warnings.push({ code: 'wrong-bend', message: `${prepared.joints[solver.middle].name} bends away from its natural direction. Move the pole to the other side, or set bendToward.` });+ }+ return warnings;+}+function createSolver(definition, position, prepared, resolveJoint) {const label = `IK ${position}`;const weight = weightFunction(definition?.weight ?? 1, `${label} weight`);@@ -158,7 +261,13 @@ function createSolver(definition, position, prepared, resolveJoint) {throw new RangeError(`${label}: end must descend from middle, and middle from root.`);}if (definition.pole !== undefined && typeof definition.pole !== 'function') checkedVector(definition.pole, `${label} pole`);- return { type: 'two-bone', label, weight, root, middle, end, target: definition.target, pole: definition.pole, keepEndRotation: definition.keepEndRotation !== false };+ const limits = createJointLimits(definition.limits, label, { root, middle }, prepared);+ const bendToward = definition.bendToward === undefined ? null : vec3.normalize(new Float64Array(3), checkedVector(definition.bendToward, `${label} bendToward`));+ return {+ type: 'two-bone', label, weight, root, middle, end, target: definition.target, pole: definition.pole, limits, bendToward,+ restBend: restBendInParentFrame(prepared, root, middle, end),+ keepEndRotation: definition.keepEndRotation !== false,+ };}if (definition.type === 'aim') {const names = definition.joints ?? (definition.joint === undefined ? [] : [definition.joint]);@@ -201,7 +310,7 @@ function createSolverContext(prepared, state, localRotations, localTranslations)quat.normalize(localRotations[index], quat.slerp(localRotations[index], localRotations[index], scratch, weight));update();}- return { state, update, setWorldRotation };+ return { state, prepared, localRotations, update, setWorldRotation };}/**@@ -209,11 +318,11 @@ function createSolverContext(prepared, state, localRotations, localTranslations)* turns the two upper joints with the shortest rotations, so twist already in the pose survives.*/function solveTwoBone(solver, time, context) {- const { state, setWorldRotation } = context;+ const { state, prepared, localRotations, update, setWorldRotation } = context;const weight = checkedWeight(solver.weight, time, `${solver.label} weight`);const endPosition = state.positions[solver.end];const target = resolvedPoint(solver.target, time, endPosition, `${solver.label} target`);- if (weight === 0) return { reached: true, error: 0 };+ if (weight === 0) return { reached: true, error: 0, warnings: [], limited: [] };const rootPosition = Float64Array.from(state.positions[solver.root]);const middlePosition = Float64Array.from(state.positions[solver.middle]);const startEnd = Float64Array.from(endPosition);@@ -223,7 +332,7 @@ function solveTwoBone(solver, time, context) {const toTarget = vec3.subtract(new Float64Array(3), target, rootPosition);const targetDistance = vec3.length(toTarget);if (targetDistance < NEAR_ZERO || upperLength < NEAR_ZERO || lowerLength < NEAR_ZERO) {- return { reached: false, error: vec3.distance(startEnd, target) };+ return { reached: false, error: vec3.distance(startEnd, target), warnings: [], limited: [] };}const direction = vec3.scale(new Float64Array(3), toTarget, 1 / targetDistance);// Stop just short of the limits: a fully straight limb has no defined bend plane for the next frame.@@ -259,9 +368,11 @@ function solveTwoBone(solver, time, context) {const newMiddleRotation = quat.multiply(new Float64Array(4), middleTurn, quat.multiply(new Float64Array(4), rootTurn, state.rotations[solver.middle]));setWorldRotation(solver.root, newRootRotation, weight);setWorldRotation(solver.middle, newMiddleRotation, weight);+ const limited = applyJointLimits(solver.limits, prepared, localRotations);+ if (limited.length) update();if (solver.keepEndRotation) setWorldRotation(solver.end, endRotation, weight);const error = vec3.distance(state.positions[solver.end], target);- return { reached: error <= margin * 2 + NEAR_ZERO, error };+ return { reached: error <= margin * 2 + NEAR_ZERO, error, warnings: bendWarnings(solver, state, prepared), limited };}/** Turn a joint, or a chain sharing the turn evenly, so its forward axis points at the target. */diff --git a/tests/agent-motion-constraints.test.js b/tests/agent-motion-constraints.test.jsnew file mode 100644index 00000000..659f01c0--- /dev/null+++ b/tests/agent-motion-constraints.test.js@@ -0,0 +1,207 @@+import assert from 'node:assert/strict';+import test from 'node:test';+import { mat4, quat, vec3 } from 'gl-matrix';+import { createAgentScene } from '../src/agent-scene.js';+import { AGENT_SCENE_CAPABILITIES } from '../src/agent-scene-capabilities.js';+import { CONSTRAINT_TYPES } from '../src/node-constraints.js';+import { eulerFromQuaternion, quaternionFromEuler } from '../src/rotation-euler.js';++const DEGREES = Math.PI / 180;++function nodeRecipe(nodes, motion, materials = []) {+ return {+ format: '67js.scene', schemaVersion: 1,+ geometries: [{ id: 'box', type: 'box', bevel: 0 }],+ materials: [{ id: 'paint', color: [0.6, 0.6, 0.6] }, ...materials],+ nodes: nodes.map(node => ({ geometry: 'box', material: 'paint', ...node })),+ ...(motion ? { motion } : {}),+ };+}++function part(scene, name) {+ return scene.parts.find(candidate => candidate.name === name);+}++function worldPosition(scene, name) {+ return Array.from(mat4.getTranslation(new Float64Array(3), part(scene, name).matrix));+}++function worldEulerDegrees(scene, name) {+ return eulerFromQuaternion(mat4.getRotation(new Float64Array(4), part(scene, name).matrix)).map(radians => radians / DEGREES);+}++function rotationOf(x, y, z) {+ return Array.from(quaternionFromEuler(new Float64Array(4), x * DEGREES, y * DEGREES, z * DEGREES));+}++function assertClose(actual, expected, tolerance = 1e-4, label = '') {+ expected.forEach((value, index) => assert.ok(Math.abs(actual[index] - value) <= tolerance, `${label} ${JSON.stringify(Array.from(actual))} vs ${JSON.stringify(expected)}`));+}++function sampledAt(recipe, time) {+ const scene = createAgentScene(recipe);+ scene.sampleMotion(time);+ return scene;+}++const SOURCE = { id: 'source', translation: [1, 2, 3], rotation: rotationOf(20, 30, 40), scale: [2, 3, 4] };+const OWNER = { id: 'owner', translation: [0, 0, 0], scale: [1, 1, 1] };+const motionWith = (constraints, extra = {}) => ({ duration: 1, tracks: [], constraints, ...extra });++test('copy_location copies chosen axes, inverts, and can offset', () => {+ const run = options => worldPosition(sampledAt(nodeRecipe([SOURCE, { ...OWNER, translation: [5, 5, 5] }], motionWith([{ type: 'copy_location', node: 'owner', target: 'source', ...options }])), 0), 'owner');+ assertClose(run({}), [1, 2, 3]);+ assertClose(run({ axes: ['x', 'z'] }), [1, 5, 3]);+ assertClose(run({ invert: ['y'] }), [1, -2, 3]);+ assertClose(run({ offset: true }), [6, 7, 8]);+});++test('copy_rotation replaces chosen Euler axes in world space and adds on request', () => {+ const owner = { ...OWNER, rotation: rotationOf(10, 0, 0) };+ const run = options => worldEulerDegrees(sampledAt(nodeRecipe([SOURCE, owner], motionWith([{ type: 'copy_rotation', node: 'owner', target: 'source', ...options }])), 0), 'owner');+ assertClose(run({}), [20, 30, 40], 1e-3);+ assertClose(run({ axes: ['z'] }), [10, 0, 40], 1e-3);+ assertClose(run({ axes: ['x'], mix: 'add' }), [30, 0, 0], 1e-3);+});++test('copy_scale copies and multiplies', () => {+ const owner = { ...OWNER, scale: [2, 2, 2] };+ const scaleOf = options => {+ const scene = sampledAt(nodeRecipe([{ ...SOURCE, rotation: [0, 0, 0, 1] }, owner], motionWith([{ type: 'copy_scale', node: 'owner', target: 'source', ...options }])), 0);+ return Array.from(mat4.getScaling(new Float64Array(3), part(scene, 'owner').matrix));+ };+ assertClose(scaleOf({}), [2, 3, 4]);+ assertClose(scaleOf({ axes: ['y'] }), [2, 3, 2]);+ assertClose(scaleOf({ offset: true }), [4, 6, 8]);+});++test('limit_location and limit_rotation clamp, in world or local space', () => {+ const owner = { ...OWNER, translation: [5, -5, 0.5], rotation: rotationOf(80, -70, 10) };+ const scene = sampledAt(nodeRecipe([owner], motionWith([+ { type: 'limit_location', node: 'owner', x: [-1, 1], y: [-1, 1] },+ { type: 'limit_rotation', node: 'owner', x: [-45, 45], y: [-30, 30] },+ ])), 0);+ assertClose(worldPosition(scene, 'owner'), [1, -1, 0.5]);+ assertClose(worldEulerDegrees(scene, 'owner'), [45, -30, 10], 1e-3);+ const underParent = sampledAt(nodeRecipe([{ id: 'holder', translation: [10, 0, 0] }, { ...OWNER, parent: 'holder', translation: [5, 0, 0] }],+ motionWith([{ type: 'limit_location', node: 'owner', x: [0, 2], space: 'local' }])), 0);+ assertClose(worldPosition(underParent, 'owner'), [12, 0, 0]);+});++test('track_to points the track axis at the target with the up axis toward worldUp', () => {+ const recipe = nodeRecipe([{ id: 'lamp', translation: [-1, 1, 0], scale: [0.1, 0.1, 0.1] }, { id: 'ball', translation: [0.3, 1.5, 0.3], scale: [0.05, 0.05, 0.05] }],+ motionWith([{ type: 'track_to', node: 'lamp', target: 'ball' }]));+ const matrix = part(sampledAt(recipe, 0), 'lamp').matrix;+ const trackAxis = vec3.normalize(new Float64Array(3), [-matrix[8], -matrix[9], -matrix[10]]);+ const toBall = vec3.normalize(new Float64Array(3), [1.3, 0.5, 0.3]);+ assertClose(trackAxis, Array.from(toBall), 1e-5);+ assert.ok(matrix[5] > 0, 'the up axis leans toward world up');+ const plusZ = nodeRecipe(recipe.nodes, motionWith([{ type: 'track_to', node: 'lamp', target: 'ball', trackAxis: '+z', upAxis: 'x', worldUp: [0, 0, 1] }]));+ const turned = part(sampledAt(plusZ, 0), 'lamp').matrix;+ assertClose(vec3.normalize(new Float64Array(3), [turned[8], turned[9], turned[10]]), Array.from(toBall), 1e-5);+ assert.ok(turned[2] > 0, 'the x axis leans toward the given up');+});++test('child_of keeps the owner in place at rest and carries it with the target; influence blends', () => {+ const nodes = [{ id: 'platform', translation: [1, 0, 0] }, { id: 'cargo', translation: [0, 1, 0], scale: [0.2, 0.2, 0.2] }];+ const move = { kind: 'node', id: 'platform', property: 'translation', keyframes: [{ time: 0, value: [1, 0, 0] }, { time: 1, value: [3, 0, 0] }] };+ const run = (options, time) => worldPosition(sampledAt(nodeRecipe(nodes, { duration: 1, tracks: [move], constraints: [{ type: 'child_of', node: 'cargo', target: 'platform', ...options }] }), time), 'cargo');+ assertClose(run({}, 0), [0, 1, 0]);+ assertClose(run({}, 1), [2, 1, 0]);+ assertClose(run({ influence: 0.5 }, 1), [1, 1, 0]);+ assertClose(run({ inverse: 'none' }, 0), [1, 1, 0]);+});++test('floor keeps a node above the target plane along the chosen axis', () => {+ const run = (y, options = {}) => worldPosition(sampledAt(nodeRecipe([{ id: 'ground', translation: [0, 0.5, 0] }, { id: 'ball', translation: [0, y, 0] }],+ motionWith([{ type: 'floor', node: 'ball', target: 'ground', ...options }])), 0), 'ball');+ assertClose(run(-1), [0, 0.5, 0]);+ assertClose(run(2), [0, 2, 0]);+ assertClose(run(0, { offset: 0.25 }), [0, 0.75, 0]);+});++test('constraints run in order on the result of the one before', () => {+ const recipe = nodeRecipe([SOURCE, { ...OWNER, translation: [9, 9, 9] }], motionWith([+ { type: 'copy_location', node: 'owner', target: 'source' },+ { type: 'limit_location', node: 'owner', y: [0, 1] },+ ]));+ assertClose(worldPosition(sampledAt(recipe, 0), 'owner'), [1, 1, 3]);+});++test('constraints follow a target moved by a track and a seek equals playing', () => {+ const recipe = nodeRecipe([{ id: 'lead', translation: [0, 0, 0] }, { id: 'follower', translation: [0, 0, 0] }, { id: 'ground', translation: [0, 0.2, 0] }], {+ duration: 2,+ tracks: [{ kind: 'node', id: 'lead', property: 'translation', keyframes: [{ time: 0, value: [0, 1, 0] }, { time: 2, value: [4, -1, 2] }] }],+ constraints: [+ { type: 'copy_location', node: 'follower', target: 'lead', influence: { clamp: [{ mul: ['time', 0.5] }, 0, 1] } },+ { type: 'floor', node: 'follower', target: 'ground' },+ ],+ });+ const played = createAgentScene(recipe);+ [0, 0.4, 0.8, 1.2, 1.6, 2, 1.2, 0.5].forEach(time => played.sampleMotion(time));+ const sought = createAgentScene(recipe);+ sought.sampleMotion(1.4);+ played.sampleMotion(1.4);+ assert.deepEqual(worldPosition(sought, 'follower'), worldPosition(played, 'follower'));+ assertClose(worldPosition(sought, 'follower'), [0.7 * 2.8, 0.2, 0.7 * 1.4], 1e-5, 'a 70 percent blend toward the lead, floored at the ground');+ sought.sampleMotion(0);+ assertClose(worldPosition(sought, 'follower'), [0, 0.2, 0], 1e-6);+});++test('drivers set a node component and a material property from time and other nodes', () => {+ const recipe = nodeRecipe([{ id: 'wheel', translation: [0, 1, 0] }, { id: 'lamp', translation: [0, 0, 0] }, { id: 'bulb', material: 'glow' }], {+ duration: 2,+ tracks: [{ kind: 'node', id: 'wheel', property: 'translation', keyframes: [{ time: 0, value: [0, 1, 0] }, { time: 2, value: [4, 1, 0] }] }],+ drivers: [+ { target: { kind: 'node', id: 'lamp', property: 'rotation', component: 'z' }, expression: { mul: [{ node: 'wheel', property: 'translation', component: 'x' }, 10] } },+ { target: { kind: 'node', id: 'lamp', property: 'translation', component: 'y' }, expression: { add: [1, { mul: [0.5, { sin: [{ mul: ['time', 3.14159265] }] }] }] } },+ { target: { kind: 'material', id: 'glow', property: 'roughness' }, expression: { clamp: [{ div: ['time', 2] }, 0, 1] } },+ { target: { kind: 'material', id: 'glow', property: 'color', component: 'x' }, expression: { saturate: [{ node: 'wheel', property: 'translation', component: 'x' }] } },+ ],+ }, [{ id: 'glow', color: [0.1, 0.2, 0.3], roughness: 0.9 }]);+ const scene = sampledAt(recipe, 0.5);+ assertClose(worldEulerDegrees(scene, 'lamp'), [0, 0, 10], 1e-3);+ assertClose(worldPosition(scene, 'lamp'), [0, 1.5, 0], 1e-4);+ const glow = part(scene, 'bulb').material;+ assert.ok(Math.abs(glow.roughness - 0.25) < 1e-6, `roughness ${glow.roughness}`);+ assertClose(glow.color, [1, 0.2, 0.3], 1e-6);+ const resampled = sampledAt(recipe, 0.5);+ assert.deepEqual(worldPosition(resampled, 'lamp'), worldPosition(scene, 'lamp'));+});++test('a seek equals play for drivers too', () => {+ const recipe = nodeRecipe([{ id: 'lamp' }], { duration: 3, tracks: [], drivers: [{ target: { kind: 'node', id: 'lamp', property: 'translation', component: 'x' }, expression: { mul: ['time', 2] } }] });+ const played = createAgentScene(recipe);+ [0, 1, 2.5, 0.5].forEach(time => played.sampleMotion(time));+ const sought = sampledAt(recipe, 0.5);+ assert.deepEqual(worldPosition(played, 'lamp'), worldPosition(sought, 'lamp'));+});++test('drivers and constraints reject anything that is not bounded data', () => {+ const driver = expression => nodeRecipe([{ id: 'lamp' }], { duration: 1, tracks: [], drivers: [{ target: { kind: 'node', id: 'lamp', property: 'translation', component: 'x' }, expression }] });+ assert.throws(() => createAgentScene(driver('process.exit(1)')), /use a number, "time"/);+ assert.throws(() => createAgentScene(driver({ constructor: [1, 2] })), /unknown operator/);+ assert.throws(() => createAgentScene(driver({ add: [1] })), /2 to 8 operands/);+ assert.throws(() => createAgentScene(driver({ node: 'missing', property: 'translation', component: 'x' })), /not in this scene/);+ assert.throws(() => createAgentScene(driver({ div: [1, 0] })).sampleMotion(0), /finite/);+ let deep = 1;+ for (let level = 0; level < 10; level++) deep = { neg: [deep] };+ assert.throws(() => createAgentScene(driver(deep)), /nests deeper/);+ const clash = nodeRecipe([{ id: 'lamp' }], {+ duration: 1, tracks: [{ kind: 'node', id: 'lamp', property: 'translation', keyframes: [{ time: 0, value: [0, 0, 0] }] }],+ drivers: [{ target: { kind: 'node', id: 'lamp', property: 'translation', component: 'x' }, expression: 1 }],+ });+ assert.throws(() => createAgentScene(clash), /clashes with a track/);+ const constraint = fields => nodeRecipe([{ id: 'lamp' }, { id: 'ball' }], motionWith([{ type: 'copy_location', node: 'lamp', target: 'ball', ...fields }]));+ assert.throws(() => createAgentScene(constraint({ target: 'lamp' })), /itself/);+ assert.throws(() => createAgentScene(constraint({ axes: ['w'] })), /distinct axes/);+ assert.throws(() => createAgentScene(constraint({ influence: 2 })), /influence/);+ assert.throws(() => createAgentScene(constraint({ extra: 1 })), /Unknown or unsupported/);+ assert.throws(() => createAgentScene(nodeRecipe([{ id: 'lamp' }], motionWith([{ type: 'wiggle', node: 'lamp' }]))), /type must be one of/);+ assert.throws(() => createAgentScene(nodeRecipe([{ id: 'lamp' }], motionWith([{ type: 'limit_rotation', node: 'lamp', x: [-200, 10] }]))), /within -180 and 180/);+});++test('the capabilities list every constraint type', () => {+ assert.deepEqual([...AGENT_SCENE_CAPABILITIES.motionConstraints], [...CONSTRAINT_TYPES]);+ assert.ok(quat.length(rotationOf(1, 2, 3)) > 0);+});diff --git a/tests/agent-motion-ik-limits.test.js b/tests/agent-motion-ik-limits.test.jsnew file mode 100644index 00000000..08767d3e--- /dev/null+++ b/tests/agent-motion-ik-limits.test.js@@ -0,0 +1,84 @@+import assert from 'node:assert/strict';+import { readFileSync } from 'node:fs';+import test from 'node:test';+import { mat4 } from 'gl-matrix';+import { createAgentScene } from '../src/agent-scene.js';+import { createAgentAssetScene } from '../src/agent-asset.js';+import { parseGltf } from '../src/gltf.js';++const SEGMENT_MATERIALS = [{ id: 'paint', color: [0.6, 0.6, 0.6] }];++/** A planar arm along +x: shoulder at (0, 1, 0), 0.5 m to the elbow, 0.4 m to the tip. */+function armRecipe(motion) {+ const nodes = [+ { id: 'base', translation: [0, 1, 0] },+ { id: 'shoulder', parent: 'base' },+ { id: 'elbow', parent: 'shoulder', translation: [0.5, 0, 0] },+ { id: 'tip', parent: 'elbow', translation: [0.4, 0, 0], geometry: 'box', material: 'paint', scale: [0.03, 0.03, 0.03] },+ ];+ return { format: '67js.scene', schemaVersion: 1, geometries: [{ id: 'box', type: 'box', bevel: 0 }], materials: SEGMENT_MATERIALS, nodes, motion };+}++const arm = extra => ({ type: 'two-bone', root: 'shoulder', middle: 'elbow', end: 'tip', target: [0.3, 1.5, 0.2], pole: [0, 3, 0], ...extra });+const reportFor = ik => createAgentScene(armRecipe({ duration: 1, tracks: [], ik: [ik] })).inspect().motionIk[0];++test('motionIk reports the poses a joint limit changed', () => {+ const free = reportFor(arm({}));+ assert.deepEqual(free.limited, []);+ const limited = reportFor(arm({ limits: { middle: { z: [-5, 5] } } }));+ assert.equal(limited.reached, false);+ assert.ok(limited.limited.length >= 1);+ assert.equal(limited.limited[0].joint, 'elbow');+ assert.equal(limited.limited[0].axis, 'z');+ assert.equal(typeof limited.limited[0].atTime, 'number');+});++test('a deliberately wrong pole produces a warning while IK still reports reached', () => {+ const natural = reportFor(arm({ bendToward: [0, 1, 0] }));+ assert.deepEqual(natural.warnings, []);+ const wrong = reportFor(arm({ pole: [0, -3, 0], bendToward: [0, 1, 0] }));+ assert.equal(wrong.reached, true);+ assert.deepEqual(wrong.warnings.map(warning => warning.code), ['wrong-bend']);+ assert.match(wrong.warnings[0].message, /elbow/);+});++test('a target at full reach warns about hyperextension', () => {+ const report = reportFor(arm({ target: [0.9, 1, 0] }));+ assert.ok(report.warnings.some(warning => warning.code === 'hyperextended'));+});++test('limits and bendToward are validated', () => {+ const build = ik => createAgentScene(armRecipe({ duration: 1, tracks: [], ik: [ik] }));+ assert.throws(() => build(arm({ limits: { tip: { z: [0, 1] } } })), /Unknown or unsupported/);+ assert.throws(() => build(arm({ limits: { middle: { z: [10, -10] } } })), /min first/);+ assert.throws(() => build(arm({ limits: { middle: { w: [0, 1] } } })), /Unknown or unsupported/);+ assert.throws(() => build(arm({ bendToward: [0, 1] })), /3 components/);+});++const bytes = readFileSync(new URL('./fixtures/RobotExpressive.glb', import.meta.url));+const ASSET_ID = 'ab'.repeat(32);++function robotScene(motion) {+ const asset = parseGltf(bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength), { maxVertices: 500000 });+ return asset.then(loaded => ({ loaded, scene: createAgentAssetScene(loaded, { format: '67js.asset', schemaVersion: 1, assetId: ASSET_ID, motion }) }));+}++function translationOf({ loaded, scene }, name) {+ const index = loaded.parts.findIndex(part => part.name === name);+ return Array.from(mat4.getTranslation(new Float64Array(3), scene.parts[index].matrix));+}++test('constraints move parts of an imported character, and a seek equals play', async () => {+ const constrained = await robotScene({ duration: 1, tracks: [], constraints: [{ type: 'copy_location', node: 'node-38', target: 'node-18' }] });+ const plain = await robotScene({ duration: 1, tracks: [], constraints: [{ type: 'limit_location', node: 'node-12', y: [-100, 100] }] });+ plain.scene.sampleMotion(0);+ constrained.scene.sampleMotion(0);+ const armRight = translationOf(constrained, 'ArmR');+ const armLeft = translationOf(constrained, 'ArmL');+ armRight.forEach((value, index) => assert.ok(Math.abs(value - armLeft[index]) < 1e-4, `${armRight} vs ${armLeft}`));+ const unconstrainedGap = translationOf(plain, 'ArmR').map((value, index) => Math.abs(value - translationOf(plain, 'ArmL')[index]));+ assert.ok(Math.max(...unconstrainedGap) > 1e-2, 'the arms are apart without the constraint');+ constrained.scene.sampleMotion(0.7);+ constrained.scene.sampleMotion(0);+ assert.deepEqual(translationOf(constrained, 'ArmR'), armRight);+});diff --git a/tests/agent-motion-ik.test.js b/tests/agent-motion-ik.test.jsindex e048c2ff..021a7474 100644--- a/tests/agent-motion-ik.test.js+++ b/tests/agent-motion-ik.test.js@@ -158,7 +158,7 @@ test('recipes export and reload with their ik', () => {test('mistakes say what to pass', () => {const create = (ik, overrides) => createAgentScene(armRecipe({ duration: 1, tracks: [], ik }, overrides));- assert.throws(() => createAgentScene(armRecipe({ duration: 1, tracks: [] })), /at least one track or IK solver/);+ assert.throws(() => createAgentScene(armRecipe({ duration: 1, tracks: [] })), /at least one track, IK solver, constraint or driver/);assert.throws(() => create([{ type: 'fabrik', target: [0, 0, 0] }]), /type must be two-bone or aim/);assert.throws(() => create([armIk([0, 0, 0], { root: 'nope' })]), /root must be a node ID/);assert.throws(() => create([armIk({ node: 'nope' })]), /target node must be a node ID/);diff --git a/tests/blender-constraints.test.js b/tests/blender-constraints.test.jsnew file mode 100644index 00000000..5c7011e1--- /dev/null+++ b/tests/blender-constraints.test.js@@ -0,0 +1,55 @@+import assert from 'node:assert/strict';+import { readFileSync } from 'node:fs';+import test from 'node:test';+import { createAgentScene } from '../src/agent-scene.js';+import { quaternionFromEuler } from '../src/rotation-euler.js';++// tests/fixtures/blender/constraints.json holds Blender 5.2's evaluated world matrix of the constrained node in each case+// (scripts/blender-constraints-golden.py). 67.js builds the same nodes, applies the same constraint and must land on the same+// matrix. Coordinates are shared as they are; track_to is given worldUp [0, 0, 1] because Blender's up is Z.++const golden = JSON.parse(readFileSync(new URL('./fixtures/blender/constraints.json', import.meta.url), 'utf8'));+const TOLERANCE = 2e-4;++function eulerQuaternion(degrees) {+ return Array.from(quaternionFromEuler(new Float64Array(4), ...degrees.map(angle => angle * Math.PI / 180)));+}++function recipeFor(testCase) {+ const nodes = testCase.nodes.map(node => ({+ id: node.id, geometry: 'box', material: 'paint',+ ...(node.parent ? { parent: node.parent } : {}),+ translation: node.translation ?? [0, 0, 0],+ rotation: eulerQuaternion(node.rotation ?? [0, 0, 0]),+ }));+ const tracks = [];+ if (testCase.pose) {+ tracks.push({ kind: 'node', id: testCase.pose.id, property: 'translation', keyframes: [{ time: 0, value: testCase.pose.translation }] });+ tracks.push({ kind: 'node', id: testCase.pose.id, property: 'rotation', keyframes: [{ time: 0, value: eulerQuaternion(testCase.pose.rotation) }] });+ }+ return {+ format: '67js.scene', schemaVersion: 1,+ geometries: [{ id: 'box', type: 'box', bevel: 0 }], materials: [{ id: 'paint', color: [0.6, 0.6, 0.6] }],+ nodes, motion: { duration: 1, tracks, constraints: [testCase.constraint] },+ };+}++test('the fixture was recorded by Blender 5.2 and covers the required constraints', () => {+ assert.match(golden.blender, /^5\.2/);+ const types = new Set(golden.cases.map(testCase => testCase.constraint.type));+ for (const required of ['copy_rotation', 'limit_rotation', 'track_to', 'child_of']) {+ assert.ok(types.has(required), `${required} is in the fixture`);+ }+});++for (const testCase of golden.cases) {+ test(`${testCase.name} matches Blender's world matrix`, () => {+ const scene = createAgentScene(recipeFor(testCase));+ scene.sampleMotion(0);+ const owner = scene.parts.find(part => part.name === testCase.constraint.node);+ testCase.expectedOwnerWorld.forEach((expected, index) => {+ assert.ok(Math.abs(owner.matrix[index] - expected) <= TOLERANCE,+ `${testCase.name} matrix[${index}] ${owner.matrix[index]} vs Blender ${expected}\n${Array.from(owner.matrix).map(value => value.toFixed(4))}\n${testCase.expectedOwnerWorld.map(value => value.toFixed(4))}`);+ });+ });+}diff --git a/tests/fixtures/blender/constraints.json b/tests/fixtures/blender/constraints.jsonnew file mode 100644index 00000000..dafe5343--- /dev/null+++ b/tests/fixtures/blender/constraints.json@@ -0,0 +1,459 @@+{+ "blender": "5.2.2 LTS",+ "cases": [+ {+ "name": "copy_rotation_xz",+ "nodes": [+ {+ "id": "source",+ "translation": [+ 1,+ 2,+ 3+ ],+ "rotation": [+ 20,+ 30,+ 40+ ]+ },+ {+ "id": "owner",+ "translation": [+ 0,+ 0,+ 0+ ],+ "rotation": [+ 10,+ 5,+ -15+ ]+ }+ ],+ "constraint": {+ "type": "copy_rotation",+ "node": "owner",+ "target": "source",+ "axes": [+ "x",+ "z"+ ]+ },+ "expectedOwnerWorld": [+ 0.7631294131278992,+ 0.640341579914093,+ -0.08715573698282242,+ 0.0,+ -0.5811877250671387,+ 0.7390071749687195,+ 0.34071868658065796,+ 0.0,+ 0.2825850546360016,+ -0.2093586027622223,+ 0.9361168146133423,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 1.0+ ]+ },+ {+ "name": "copy_rotation_all_with_parent",+ "nodes": [+ {+ "id": "holder",+ "translation": [+ 4,+ 0,+ 1+ ],+ "rotation": [+ 0,+ 0,+ 25+ ]+ },+ {+ "id": "source",+ "translation": [+ 1,+ 2,+ 3+ ],+ "rotation": [+ -35,+ 20,+ 50+ ]+ },+ {+ "id": "owner",+ "parent": "holder",+ "translation": [+ 1,+ 1,+ 0+ ],+ "rotation": [+ 10,+ 5,+ -15+ ]+ }+ ],+ "constraint": {+ "type": "copy_rotation",+ "node": "owner",+ "target": "source"+ },+ "expectedOwnerWorld": [+ 0.604022741317749,+ 0.7198463082313538,+ -0.3420201539993286,+ 0.0,+ -0.7536054849624634,+ 0.37626221776008606,+ -0.5389854907989502,+ 0.0,+ -0.2592974901199341,+ 0.5833078026771545,+ 0.7697511315345764,+ 0.0,+ 4.483689308166504,+ 1.3289260864257812,+ 1.0,+ 1.0+ ]+ },+ {+ "name": "limit_rotation_xy",+ "nodes": [+ {+ "id": "owner",+ "translation": [+ 0,+ 0,+ 0+ ],+ "rotation": [+ 80,+ 70,+ 10+ ]+ }+ ],+ "constraint": {+ "type": "limit_rotation",+ "node": "owner",+ "x": [+ -45,+ 45+ ],+ "y": [+ -30,+ 30+ ]+ },+ "expectedOwnerWorld": [+ 0.8528684973716736,+ 0.15038374066352844,+ -0.5,+ 0.0,+ 0.22539430856704712,+ 0.7577580809593201,+ 0.6123723983764648,+ 0.0,+ 0.47096991539001465,+ -0.6349703073501587,+ 0.6123723387718201,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 1.0+ ]+ },+ {+ "name": "track_to_negative_z_up_y",+ "nodes": [+ {+ "id": "owner",+ "translation": [+ -1,+ 1,+ 0+ ]+ },+ {+ "id": "target",+ "translation": [+ 0.3,+ 1.5,+ 0.3+ ]+ }+ ],+ "constraint": {+ "type": "track_to",+ "node": "owner",+ "target": "target",+ "trackAxis": "-z",+ "upAxis": "y",+ "worldUp": [+ 0,+ 0,+ 1+ ]+ },+ "expectedOwnerWorld": [+ 0.35897910594940186,+ -0.9333456158638,+ 0.0,+ 0.0,+ -0.19652406871318817,+ -0.07558618485927582,+ 0.977581262588501,+ 0.0,+ -0.9124211668968201,+ -0.35093122720718384,+ -0.21055874228477478,+ 0.0,+ -1.0,+ 1.0,+ 0.0,+ 1.0+ ]+ },+ {+ "name": "track_to_positive_x_up_z",+ "nodes": [+ {+ "id": "owner",+ "translation": [+ 2,+ -1,+ 0.5+ ],+ "rotation": [+ 0,+ 0,+ 15+ ]+ },+ {+ "id": "target",+ "translation": [+ -1,+ 3,+ 2+ ]+ }+ ],+ "constraint": {+ "type": "track_to",+ "node": "owner",+ "target": "target",+ "trackAxis": "+x",+ "upAxis": "z",+ "worldUp": [+ 0,+ 0,+ 1+ ]+ },+ "expectedOwnerWorld": [+ -0.5746957063674927,+ 0.7662609815597534,+ 0.28734785318374634,+ 0.0,+ -0.7999999523162842,+ -0.5999999046325684,+ 0.0,+ 0.0,+ 0.17240874469280243,+ -0.22987832129001617,+ 0.9578262567520142,+ 0.0,+ 2.0,+ -1.0,+ 0.5,+ 1.0+ ]+ },+ {+ "name": "child_of_follows_target_from_rest",+ "nodes": [+ {+ "id": "target",+ "translation": [+ 1,+ 2,+ 0+ ],+ "rotation": [+ 0,+ 0,+ 30+ ]+ },+ {+ "id": "owner",+ "translation": [+ 0,+ 1,+ 0+ ]+ }+ ],+ "constraint": {+ "type": "child_of",+ "node": "owner",+ "target": "target",+ "inverse": "rest"+ },+ "pose": {+ "id": "target",+ "translation": [+ 3,+ 1,+ 2+ ],+ "rotation": [+ 10,+ 20,+ 70+ ]+ },+ "expectedOwnerWorld": [+ 0.7308870553970337,+ 0.568402886390686,+ -0.3777860403060913,+ 0.0,+ -0.6231458187103271,+ 0.7815417051315308,+ -0.029695585370063782,+ 0.0,+ 0.2783765196800232,+ 0.25711992383003235,+ 0.9254165887832642,+ 0.0,+ 2.892258882522583,+ -0.34994471073150635,+ 2.4074816703796387,+ 1.0+ ]+ },+ {+ "name": "child_of_half_influence",+ "nodes": [+ {+ "id": "target",+ "translation": [+ 1,+ 2,+ 0+ ],+ "rotation": [+ 0,+ 0,+ 30+ ]+ },+ {+ "id": "owner",+ "translation": [+ 0,+ 1,+ 0+ ]+ }+ ],+ "constraint": {+ "type": "child_of",+ "node": "owner",+ "target": "target",+ "inverse": "rest",+ "influence": 0.5+ },+ "pose": {+ "id": "target",+ "translation": [+ 3,+ 1,+ 2+ ],+ "rotation": [+ 10,+ 20,+ 70+ ]+ },+ "expectedOwnerWorld": [+ 0.9301754236221313,+ 0.3142187297344208,+ -0.1898413747549057,+ 0.0,+ -0.3284223973751068,+ 0.9433184266090393,+ -0.04784069210290909,+ 0.0,+ 0.1640484780073166,+ 0.10684843361377716,+ 0.980648398399353,+ 0.0,+ 1.4461294412612915,+ 0.3250276446342468,+ 1.2037408351898193,+ 1.0+ ]+ },+ {+ "name": "floor_z_with_offset",+ "nodes": [+ {+ "id": "ground",+ "translation": [+ 0,+ 0,+ 0.5+ ]+ },+ {+ "id": "owner",+ "translation": [+ 0.3,+ 0.2,+ -1+ ]+ }+ ],+ "constraint": {+ "type": "floor",+ "node": "owner",+ "target": "ground",+ "axis": "+z",+ "offset": 0.1+ },+ "expectedOwnerWorld": [+ 1.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 1.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 1.0,+ 0.0,+ 0.30000001192092896,+ 0.20000000298023224,+ 0.6000000238418579,+ 1.0+ ]+ }+ ]+}diff --git a/tests/skeleton-pose-limits.test.js b/tests/skeleton-pose-limits.test.jsnew file mode 100644index 00000000..124ba433--- /dev/null+++ b/tests/skeleton-pose-limits.test.js@@ -0,0 +1,118 @@+import assert from 'node:assert/strict';+import test from 'node:test';+import { quat } from 'gl-matrix';+import { createSkeletonPose } from '../src/skeleton-pose.js';+import { eulerFromQuaternion, quaternionFromEuler } from '../src/rotation-euler.js';++const LEG = { type: 'two-bone', root: 'hip', middle: 'knee', end: 'ankle' };++function createLegRig() {+ return {+ mapping: {},+ joints: [+ { name: 'hip', parent: -1, translation: [0, 1, 0], rotation: [0, 0, 0, 1], scale: [1, 1, 1] },+ { name: 'knee', parent: 0, translation: [0, -0.5, 0], rotation: [0, 0, 0, 1], scale: [1, 1, 1] },+ { name: 'ankle', parent: 1, translation: [0, -0.5, 0], rotation: [0, 0, 0, 1], scale: [1, 1, 1] },+ ],+ };+}++function solved(definition, time = 0) {+ const pose = createSkeletonPose({ rig: createLegRig(), ik: [{ ...LEG, ...definition }] });+ pose.apply(time);+ return pose;+}++function localKneeDegrees(pose) {+ return eulerFromQuaternion(pose.localRotation(1)).map(radians => radians * 180 / Math.PI);+}++test('euler conversion round trips in Blender XYZ order', () => {+ const angles = [0.4, -0.7, 1.1];+ const rotation = quaternionFromEuler(new Float64Array(4), ...angles);+ eulerFromQuaternion(rotation).forEach((angle, axis) => assert.ok(Math.abs(angle - angles[axis]) < 1e-9));+ const expected = quat.multiply(new Float64Array(4), quat.setAxisAngle(new Float64Array(4), [0, 0, 1], 1.1),+ quat.multiply(new Float64Array(4), quat.setAxisAngle(new Float64Array(4), [0, 1, 0], -0.7), quat.setAxisAngle(new Float64Array(4), [1, 0, 0], 0.4)));+ assert.ok(Math.abs(Math.abs(quat.dot(rotation, expected)) - 1) < 1e-12);+});++test('a joint limit clamps the solved pose and the change is reported', () => {+ const free = solved({ target: [0, 0.4, 0.45], pole: [0, 0.7, 2] });+ const freeKnee = localKneeDegrees(free)[0];+ assert.ok(Math.abs(freeKnee) > 60, `the unlimited knee bends ${freeKnee} degrees`);+ const limit = Math.sign(freeKnee) > 0 ? [0, 30] : [-30, 0];+ const pose = solved({ target: [0, 0.4, 0.45], pole: [0, 0.7, 2], limits: { middle: { x: limit } } });+ const [result] = pose.ikResults;+ assert.ok(Math.abs(localKneeDegrees(pose)[0]) <= 30 + 1e-6);+ assert.equal(result.limited.length, 1);+ assert.equal(result.limited[0].joint, 'knee');+ assert.equal(result.limited[0].axis, 'x');+ assert.ok(Math.abs(result.limited[0].requested) > Math.abs(result.limited[0].applied));+ assert.equal(result.reached, false, 'a clamped knee can not reach the far target');+ assert.deepEqual(free.ikResults[0].limited, []);+});++test('limits that the pose already respects change nothing', () => {+ const free = solved({ target: [0, 0.4, 0.45], pole: [0, 0.7, 2] });+ const limited = solved({ target: [0, 0.4, 0.45], pole: [0, 0.7, 2], limits: { middle: { x: [-170, 170] }, root: { z: [-45, 45] } } });+ assert.deepEqual(limited.ikResults[0].limited, []);+ assert.ok(Math.abs(quat.dot(free.localRotation(1), limited.localRotation(1))) > 1 - 1e-12);+});++test('limits are checked when the pose is built', () => {+ const build = limits => createSkeletonPose({ rig: createLegRig(), ik: [{ ...LEG, target: [0, 0.5, 0], limits }] });+ assert.throws(() => build({ ankle: { x: [0, 1] } }), /root or middle/);+ assert.throws(() => build({ middle: { w: [0, 1] } }), /x, y or z/);+ assert.throws(() => build({ middle: { x: [10, -10] } }), /min first/);+ assert.throws(() => build({ middle: { x: [0, 400] } }), /within -180 and 180/);+});++test('a wrong pole bends the knee backward and warns; the right pole stays quiet', () => {+ const backward = solved({ target: [0, 0.4, 0.2], pole: [0, 0.7, -2], bendToward: [0, 0, 1] });+ const [wrong] = backward.ikResults;+ assert.equal(wrong.reached, true, 'the foot still arrives, which is why the warning is needed');+ assert.deepEqual(wrong.warnings.map(warning => warning.code), ['wrong-bend']);+ assert.match(wrong.warnings[0].message, /knee/);+ const forward = solved({ target: [0, 0.4, 0.2], pole: [0, 0.7, 2], bendToward: [0, 0, 1] });+ assert.deepEqual(forward.ikResults[0].warnings, []);+});++test('a limb that rests bent warns when it is solved the other way, without bendToward', () => {+ const rig = createLegRig();+ rig.joints[1].rotation = Array.from(quaternionFromEuler(new Float64Array(4), 0.6, 0, 0));+ const run = pole => {+ const pose = createSkeletonPose({ rig, ik: [{ ...LEG, target: [0, 0.4, 0.2], pole }] });+ pose.apply(0);+ return pose.ikResults[0].warnings.map(warning => warning.code);+ };+ const restBend = createSkeletonPose({ rig });+ restBend.apply(0);+ const restKneeZ = restBend.jointWorld('knee').position[2];+ const naturalSide = Math.sign(restKneeZ) || 1;+ assert.deepEqual(run([0, 0.7, 2 * naturalSide]), []);+ assert.deepEqual(run([0, 0.7, -2 * naturalSide]), ['wrong-bend']);+});++test('a limb stretched to its reach warns about hyperextension', () => {+ const pose = solved({ target: [0, -2, 0.1], pole: [0, 0, 2] });+ const [result] = pose.ikResults;+ assert.equal(result.reached, false);+ assert.ok(result.warnings.some(warning => warning.code === 'hyperextended'));+});++test('seeking gives the same limited pose as playing to that time', () => {+ const definition = {+ target: { },+ pole: [0, 0.7, 2], limits: { middle: { x: [-30, 30] } },+ };+ const targetAt = time => [0, 0.45 - 0.1 * time, 0.4 * time];+ const make = () => createSkeletonPose({ rig: createLegRig(), ik: [{ ...LEG, ...definition, target: (time) => targetAt(time) }] });+ const played = make();+ [0, 0.25, 0.5, 0.75, 1].forEach(time => played.apply(time));+ const sought = make();+ sought.apply(1);+ for (let index = 0; index < 3; index++) {+ assert.deepEqual(Array.from(sought.localRotation(index)), Array.from(played.localRotation(index)));+ }+ assert.deepEqual(sought.ikResults[0].limited, played.ikResults[0].limited);+});