Skip to content

3D engine that AI agents drive

Refuse repeated crowd seeds, bad bone mappings and unusable rig joints (#2487)

Nguyen Xuan An19a5170bbbab
diff --git a/changes/2487.md b/changes/2487.md
new file mode 100644
index 00000000..75b90673
--- /dev/null
+++ b/changes/2487.md
@@ -0,0 +1 @@
+- Retargeting refuses a bone mapping that repeats a joint or names an unknown bone, rig joints with a zero rotation or a non-finite translation, and a crowd seed that is not a whole number from -2147483648 to 4294967295 (#2487, #2488, #2489)
diff --git a/changes/2487.size.md b/changes/2487.size.md
new file mode 100644
index 00000000..7562996f
--- /dev/null
+++ b/changes/2487.size.md
@@ -0,0 +1 @@
+- scene:agent-scene+lazy: refusing a repeated crowd seed, a duplicate or unknown bone mapping and a zero or NaN rig joint stops silently wrong crowds and NaN poses for 252 bytes gzip
diff --git a/docs/retarget.md b/docs/retarget.md
index d8f5501e..364bfe94 100644
--- a/docs/retarget.md
+++ b/docs/retarget.md
@@ -21,7 +21,7 @@ renderer.updateParts(characterAsset.parts);
## Rigs
A rig is `{ joints, rootMatrix?, mapping? }`. Each joint is `{ name, parent, translation, rotation, scale }` with the local rest pose,
-`parent` as an index (`-1` for a root) and quaternions in XYZW order.
+`parent` as an index (`-1` for a root) and quaternions in XYZW order. A rest translation must be finite and a rest rotation finite and not zero, and a `mapping` may name only canonical bones and give each joint to one bone, otherwise the call throws a `RangeError`.
`createRigFromSkin(skin)` builds one from an imported skin: the bind pose becomes the rest pose.
`rootMatrix` is the world matrix of whatever sits above the root joints, such as a scaled Armature node. Pass it when the clip's root
tracks are authored relative to that node. Uniform scale is assumed throughout.
@@ -81,7 +81,7 @@ world matrices and calls `updateSkinPose`. The renderer still needs `updateParts
## Crowds
-`createCrowd({ count, clip, seed, layout, spacing, columns, size, rateJitter, randomYaw })` is deterministic for a seed. `columns` must be a positive integer and `size` a positive finite number, otherwise it throws a `RangeError`. `layout` is
+`createCrowd({ count, clip, seed, layout, spacing, columns, size, rateJitter, randomYaw })` is deterministic for a seed, a whole number from -2147483648 to 4294967295. `columns` must be a positive integer and `size` a positive finite number, otherwise it throws a `RangeError`. `layout` is
`'grid'` (centred, `columns` wide) or `'scatter'` (rejection sampling with at least `0.75 * spacing` between instances where room allows).
Each instance has `position`, `yawRadians`, a `timeOffset` in the clip duration, a `playbackRate` within `1 ± rateJitter` and a
column-major `matrix`. `clipTime(index, seconds)` gives the instance's clip time and `sample(seconds)` returns every instance's tracks
diff --git a/src/retarget.js b/src/retarget.js
index 4bfbfeb6..77010f56 100644
--- a/src/retarget.js
+++ b/src/retarget.js
@@ -1,6 +1,7 @@
import { mat4, quat, vec3 } from 'gl-matrix';
import { createAnimationClip, compileAnimationSampler } from './animation.js';
import { updateSkinPose } from './skinning.js';
+import { requireWholeSeed } from './seeded-random.js';
const SIDES = ['left', 'right'];
const FINGERS = ['thumb', 'index', 'middle', 'ring', 'little'];
@@ -208,6 +209,10 @@ export function validateRigJoints(joints, label) {
const parentIsValid = Number.isInteger(joint.parent) && joint.parent >= -1 && joint.parent < joints.length;
if (typeof joint.name !== 'string' || !parentIsValid) throw new TypeError(`${label} rig joints need a name and a parent index.`);
if (joint.translation?.length !== 3 || joint.rotation?.length !== 4) throw new TypeError(`${label} rig joint ${joint.name} needs translation and rotation rest values.`);
+ const rotationLength = Math.hypot(...joint.rotation);
+ if (!Array.from(joint.translation).every(Number.isFinite) || !(rotationLength > 0) || !Number.isFinite(rotationLength)) {
+ throw new RangeError(`${label} rig joint ${joint.name} needs a finite translation and a finite nonzero rotation.`);
+ }
});
}
@@ -248,7 +253,11 @@ function prepareRig(rig, label, overrides) {
}
const indexByName = new Map(jointNames.map((name, index) => [name, index]));
const indexByBone = {};
+ const boneByJoint = new Map();
for (const [bone, jointName] of Object.entries(mapping)) {
+ if (!HUMANOID_BONES.includes(bone)) throw new RangeError(`${label} mapping names an unknown bone: ${bone}. Use a canonical humanoid bone name.`);
+ if (boneByJoint.has(jointName)) throw new RangeError(`${label} mapping sends ${boneByJoint.get(jointName)} and ${bone} to one joint: ${jointName}`);
+ boneByJoint.set(jointName, bone);
if (!indexByName.has(jointName)) throw new RangeError(`${label} mapping names a joint that is not in the rig: ${jointName}`);
indexByBone[bone] = indexByName.get(jointName);
}
@@ -499,7 +508,7 @@ export function createCrowd({ count, clip, seed = 1, layout = 'grid', spacing =
if (size !== undefined && (!Number.isFinite(size) || size <= 0)) {
throw new RangeError(`Crowd size must be a positive finite number, got ${size}.`);
}
- const nextRandom = createRandomGenerator(seed);
+ const nextRandom = createRandomGenerator(requireWholeSeed(seed, 'Crowd seed'));
const columnCount = columns ?? Math.ceil(Math.sqrt(count));
const positions = layout === 'grid'
? gridPositions(count, spacing, columnCount)
diff --git a/src/seeded-random.js b/src/seeded-random.js
index b0479c4e..7ac82598 100644
--- a/src/seeded-random.js
+++ b/src/seeded-random.js
@@ -17,3 +17,9 @@ export function requireSeed(value, label) {
if (!Number.isFinite(value)) throw new TypeError(`${label} must be a finite number such as 1.`);
return value;
}
+
+/** Returns `value` when it is a whole number from -2147483648 to 4294967295, else throws. A fraction or a number outside 32 bits would repeat another seed's sequence. */
+export function requireWholeSeed(value, label) {
+ if (!Number.isInteger(value) || value < -0x80000000 || value > 0xffffffff) throw new RangeError(`${label} must be a whole number from -2147483648 to 4294967295; pass e.g. 1.`);
+ return value;
+}
diff --git a/tests/retarget-input-guards.test.js b/tests/retarget-input-guards.test.js
new file mode 100644
index 00000000..909847a2
--- /dev/null
+++ b/tests/retarget-input-guards.test.js
@@ -0,0 +1,51 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+
+const CLIP = { duration: 1, loop: true, tracks: [] };
+
+async function humanoidJoints() {
+ const { REQUIRED_HUMANOID_BONES } = await import('../src/retarget.js');
+ return REQUIRED_HUMANOID_BONES.map((name, index) => ({
+ name, parent: index === 0 ? -1 : 0, translation: [0, index === 0 ? 1 : -0.5, 0], rotation: [0, 0, 0, 1],
+ }));
+}
+
+function identityMapping(joints) {
+ return Object.fromEntries(joints.map(joint => [joint.name, joint.name]));
+}
+
+function crowdOffsets(createCrowd, seed) {
+ const crowd = createCrowd({ count: 3, clip: CLIP, seed, layout: 'scatter', randomYaw: true });
+ return JSON.stringify(crowd.instances.map(instance => [instance.position, instance.timeOffset, instance.yawRadians]));
+}
+
+test('createCrowd refuses seeds that would repeat another seed', async () => {
+ const { createCrowd } = await import('../src/retarget.js');
+ for (const seed of [1.5, NaN, Infinity, -(2 ** 31) - 1, 2 ** 32]) {
+ assert.throws(() => createCrowd({ count: 2, clip: CLIP, seed }), { name: 'RangeError', message: /Crowd seed/ }, String(seed));
+ }
+ assert.notEqual(crowdOffsets(createCrowd, 1), crowdOffsets(createCrowd, 2));
+ assert.doesNotThrow(() => createCrowd({ count: 2, clip: CLIP, seed: -5 }));
+ assert.equal(crowdOffsets(createCrowd, 4294967295), crowdOffsets(createCrowd, 4294967295));
+});
+
+test('retargetClip refuses a mapping that sends two bones to one joint or names an unknown bone', async () => {
+ const { retargetClip } = await import('../src/retarget.js');
+ const joints = await humanoidJoints();
+ const validRig = { joints, mapping: identityMapping(joints) };
+ assert.doesNotThrow(() => retargetClip(validRig, validRig, CLIP));
+ const duplicate = { joints, mapping: { ...identityMapping(joints), leftHand: 'rightHand' } };
+ assert.throws(() => retargetClip(duplicate, validRig, CLIP), { name: 'RangeError', message: /Source mapping.*rightHand/ });
+ const typo = { joints, mapping: { ...identityMapping(joints), leftArmm: 'hips' } };
+ assert.throws(() => retargetClip(validRig, typo, CLIP), { name: 'RangeError', message: /Target mapping.*unknown bone: leftArmm/ });
+});
+
+test('rig joints with a zero rotation or a non-finite translation are refused by name', async () => {
+ const { retargetClip, validateRigJoints } = await import('../src/retarget.js');
+ const joints = await humanoidJoints();
+ const zeroRotation = joints.map((joint, index) => (index === 1 ? { ...joint, rotation: [0, 0, 0, 0] } : joint));
+ assert.throws(() => retargetClip({ joints: zeroRotation }, { joints }, CLIP), { name: 'RangeError', message: new RegExp(`Source rig joint ${joints[1].name}`) });
+ const notANumber = joints.map((joint, index) => (index === 2 ? { ...joint, translation: [NaN, 0, 0] } : joint));
+ assert.throws(() => validateRigJoints(notANumber, 'Pose'), { name: 'RangeError', message: new RegExp(`Pose rig joint ${joints[2].name}`) });
+ assert.doesNotThrow(() => validateRigJoints(joints, 'Pose'));
+});