3D engine that AI agents drive
Make motion, clip layer, relation, branch, path and crowd errors name the field (issue #653)
Nguyen Xuan An16354b5273d9
diff --git a/changes/653-motion.md b/changes/653-motion.mdnew file mode 100644index 00000000..643e8fe2--- /dev/null+++ b/changes/653-motion.md@@ -0,0 +1 @@+- Errors for motion tracks and IK, clip layers, part relations, branches, path queries and crowds now name the field, the value and an example: `nodes[1].relations[0].side: got "+w"; expected one of +x, -x, +y, -y, +z, -z, the face of "a" it sits against.` The shared motion helpers (`bounded`, `denseArray`, `knownKeys`) keep their wording for now (#653)diff --git a/changes/653-motion.size.md b/changes/653-motion.size.mdnew file mode 100644index 00000000..644197f4--- /dev/null+++ b/changes/653-motion.size.md@@ -0,0 +1 @@+- scene:agent-scene+lazy: 955 bytes gzip of message text in the motion, clip layer, relation, branch, path query and crowd validators; nothing new runs unless a recipe is rejected, and an agent fixes the input in one retry.diff --git a/src/agent-branches.js b/src/agent-branches.jsindex 96b24730..6bb79087 100644--- a/src/agent-branches.js+++ b/src/agent-branches.js@@ -2,13 +2,15 @@// recipe they produce. Recipes are stored once per distinct content, so three branches that end in the same recipe cost// one snapshot. This module holds plain data only: it must stay free of engine imports so the MCP server can share it.+import { invalidField } from './field-error.js';+export const BRANCH_LIMITS = Object.freeze({ maximumBranches: 8, maximumNameLength: 24, maximumLabels: 24 });export const BRANCH_NAME_PATTERN = /^[a-z][a-z0-9_-]{0,23}$/;export function validateBranchName(name) {if (typeof name !== 'string' || !BRANCH_NAME_PATTERN.test(name)) {- throw new TypeError('A branch name starts with a lowercase letter and has at most 24 lowercase letters, digits, underscores or hyphens.');+ throw invalidField('branch', name, 'a name that starts with a lowercase letter and has at most 24 lowercase letters, digits, underscores or hyphens, such as "alt-1"', TypeError);}return name;}@@ -38,7 +40,7 @@ export function createBranchStore() {fork(name, { recipe, baseRecipe, operations, baseRevision }) {validateBranchName(name);if (!branches.has(name) && branches.size >= BRANCH_LIMITS.maximumBranches) {- throw new RangeError(`At most ${BRANCH_LIMITS.maximumBranches} branches can exist. Keep one, or reuse a name to replace it.`);+ throw invalidField('branch', name, `a name that is already a branch, since at most ${BRANCH_LIMITS.maximumBranches} branches can exist; reuse one to replace it, such as "${[...branches.keys()][0]}"`);}const recipeKey = JSON.stringify(recipe);const shared = [...branches.entries()].some(([otherName, other]) => otherName !== name && other.recipeKey === recipeKey);@@ -51,7 +53,7 @@ export function createBranchStore() {validateBranchName(name);const branch = branches.get(name);if (!branch) {- throw new RangeError(`Unknown branch: ${name}. Known branches: ${[...branches.keys()].join(', ') || 'none'}.`);+ throw invalidField('branch', name, `one of the known branches: ${[...branches.keys()].join(', ') || 'none yet, so fork one first'}`);}return { recipe: structuredClone(snapshots.get(branch.recipeKey)), baseKey: branch.baseKey,operations: structuredClone(branch.operations), baseRevision: branch.baseRevision };diff --git a/src/agent-clip-layers.js b/src/agent-clip-layers.jsindex 841d77be..79155a6c 100644--- a/src/agent-clip-layers.js+++ b/src/agent-clip-layers.js@@ -1,5 +1,6 @@import { bounded, denseArray, knownKeys } from './motion-validation.js';import { retargetReport } from './agent-retarget.js';+import { invalidField } from './field-error.js';// Clip layers for an imported asset's motion: play clips the file ships, blend them over each other, and limit each to// some bones. Agent input is untrusted plain data, so everything here is named, bounded and checked against the asset.@@ -39,83 +40,85 @@ export function retargetSourceFromAsset(decoded) {function nodeNameResolver(context) {const nameById = new Map(context.nodes.map(node => [node.id, node.name]));const names = new Set(context.nodes.map(node => node.name));- return function resolveNode(value, label) {+ return function resolveNode(value, path) {if (typeof value !== 'string' || !value || value.length > MAX_NAME_LENGTH) {- throw new TypeError(`${label} needs a node ID or name of 1 to ${MAX_NAME_LENGTH} characters.`);+ throw invalidField(path, value, `a node ID or name of 1 to ${MAX_NAME_LENGTH} characters, such as "Hips"`, TypeError);}if (nameById.has(value)) return nameById.get(value);if (names.has(value)) return value;- throw new RangeError(`${label}: ${value.slice(0, 64)} is not a node of this asset. Find IDs and names with scene_inspect kind hierarchy.`);+ throw invalidField(path, value, 'a node ID or name of this asset, such as "Hips"; find them with scene_inspect kind hierarchy');};}function normalizedMask(input, resolveNode, position) {const label = `Motion layer ${position} mask`;+ const path = `motion.layers[${position}].mask`;knownKeys(input, ['joints', 'descendants', 'exclude'], label);denseArray(input.joints, MAX_MASK_JOINTS, `${label} joints`);- if (!input.joints.length) throw new RangeError(`${label} needs at least one joint.`);- const mask = { joints: input.joints.map(joint => resolveNode(joint, `${label} joint`)) };+ if (!input.joints.length) throw invalidField(`${path}.joints`, input.joints, 'at least one node, such as ["Spine"]');+ const mask = { joints: input.joints.map(joint => resolveNode(joint, `${path}.joints`)) };if (input.descendants !== undefined) {- if (typeof input.descendants !== 'boolean') throw new TypeError(`${label} descendants must be boolean.`);+ if (typeof input.descendants !== 'boolean') throw invalidField(`${path}.descendants`, input.descendants, 'true or false', TypeError);mask.descendants = input.descendants;}if (input.exclude !== undefined) {denseArray(input.exclude, MAX_MASK_JOINTS, `${label} exclude`);- mask.exclude = input.exclude.map(joint => resolveNode(joint, `${label} exclude`));+ mask.exclude = input.exclude.map(joint => resolveNode(joint, `${path}.exclude`));}return mask;}/** Retargeting by name: the clip's track target (a node name in the clip) mapped to the node of this asset it should move. */function normalizedBoneMap(input, clip, resolveNode, position) {- const label = `Motion layer ${position} bones`;- if (!input || Object.getPrototypeOf(input) !== Object.prototype) throw new TypeError(`${label} must be a plain object.`);+ const path = `motion.layers[${position}].bones`;+ if (!input || Object.getPrototypeOf(input) !== Object.prototype) throw invalidField(path, input, 'an object from clip node names to asset node names, such as { "Hips": "mixamorig:Hips" }', TypeError);const entries = Object.entries(input);- if (!entries.length || entries.length > MAX_BONE_MAP_ENTRIES) throw new RangeError(`${label} needs 1 to ${MAX_BONE_MAP_ENTRIES} entries.`);+ if (!entries.length || entries.length > MAX_BONE_MAP_ENTRIES) throw invalidField(path, input, `1 to ${MAX_BONE_MAP_ENTRIES} entries, such as { "Hips": "mixamorig:Hips" }`);const resolved = entries.map(([from, to]) => {- if (!clip.targets.has(from)) throw new RangeError(`${label}: the clip has no track for ${from.slice(0, 64)}.`);- return [from, resolveNode(to, `${label} ${from.slice(0, 64)}`)];+ if (!clip.targets.has(from)) throw invalidField(`${path}.${from.slice(0, 64)}`, from, `a node the clip moves: one of ${[...clip.targets].slice(0, 8).join(', ')}`);+ return [from, resolveNode(to, `${path}.${from.slice(0, 64)}`)];});const destinations = resolved.map(([, destination]) => destination);- if (new Set(destinations).size !== destinations.length) throw new RangeError(`${label} cannot send two clip nodes to the same node.`);+ if (new Set(destinations).size !== destinations.length) throw invalidField(path, input, 'each asset node used once, so no two clip nodes map to the same node');return Object.fromEntries(resolved);}/** `from`: a clip of another catalog asset. It must be loaded for this session, and both skeletons must map to the humanoid bones. */-function normalizedSource(input, context, label) {+function normalizedSource(input, context, label, path) {knownKeys(input, ['asset', 'clip'], `${label} from`);const source = typeof input.asset === 'string' ? context.external.get(input.asset.toLowerCase()) : undefined;- if (!source) throw new RangeError(`${label} from.asset is not a catalog asset available to this session. Use an asset ID from scene_asset_catalog other than this scene's own.`);+ if (!source) throw invalidField(`${path}.from.asset`, input.asset, 'the ID of a catalog asset loaded for this session other than this scene\'s own, such as one from scene_asset_catalog');const clip = source.clips[input.clip];- if (!Number.isInteger(input.clip) || !clip) throw new RangeError(`${label} from.clip must be the index of a clip in that asset (0 to ${source.clips.length - 1}).`);+ if (!Number.isInteger(input.clip) || !clip) throw invalidField(`${path}.from.clip`, input.clip, `the index of a clip in that asset, from 0 to ${source.clips.length - 1}`);retargetReport(source.nodes, context.hierarchy, label);return { from: { asset: input.asset.toLowerCase(), clip: input.clip }, clip };}function normalizedLayer(input, position, context, resolveNode) {const label = `Motion layer ${position}`;+ const path = `motion.layers[${position}]`;knownKeys(input, ['clip', 'from', 'scale', 'rootMotion', 'loop', 'weight', 'speed', 'offset', 'additive', 'reference', 'mask', 'bones', 'morph'], label);const layer = {};let clip;if (input.from !== undefined) {- if (input.clip !== undefined || input.bones !== undefined || input.morph !== undefined) throw new TypeError(`${label} takes from or clip, and from has no bones or morph.`);- const sourced = normalizedSource(input.from, context, label);+ if (input.clip !== undefined || input.bones !== undefined || input.morph !== undefined) throw invalidField(`${path}.from`, input.from, 'from or clip, not both, such as { "clip": 0 } alone; a layer with from has no bones or morph', TypeError);+ const sourced = normalizedSource(input.from, context, label, path);clip = sourced.clip;layer.from = sourced.from;if (input.scale !== undefined) layer.scale = bounded(input.scale, 0.1, 10, `${label} scale`);if (input.rootMotion !== undefined) {- if (typeof input.rootMotion !== 'boolean') throw new TypeError(`${label} rootMotion must be boolean.`);+ if (typeof input.rootMotion !== 'boolean') throw invalidField(`${path}.rootMotion`, input.rootMotion, 'true or false', TypeError);layer.rootMotion = input.rootMotion;}} else {clip = context.clips[input.clip];- if (!Number.isInteger(input.clip) || !clip) throw new RangeError(`${label} clip must be the index of a clip in the asset (0 to ${context.clips.length - 1}).`);+ if (!Number.isInteger(input.clip) || !clip) throw invalidField(`${path}.clip`, input.clip, `the index of a clip in the asset, from 0 to ${context.clips.length - 1}`);layer.clip = input.clip;- if (input.scale !== undefined || input.rootMotion !== undefined) throw new TypeError(`${label} scale and rootMotion only apply to a layer with from.`);+ if (input.scale !== undefined || input.rootMotion !== undefined) throw invalidField(`${path}.${input.scale !== undefined ? 'scale' : 'rootMotion'}`, input.scale ?? input.rootMotion, 'a field left out, since scale and rootMotion only apply to a layer with from', TypeError);}for (const flag of ['loop', 'additive', 'morph']) {if (input[flag] === undefined) continue;- if (typeof input[flag] !== 'boolean') throw new TypeError(`${label} ${flag} must be boolean.`);+ if (typeof input[flag] !== 'boolean') throw invalidField(`${path}.${flag}`, input[flag], 'true or false', TypeError);layer[flag] = input[flag];}if (input.weight !== undefined) layer.weight = bounded(input.weight, 0, 1, `${label} weight`);@@ -129,9 +132,9 @@ function normalizedLayer(input, position, context, resolveNode) {/** Validate `motion.layers` against the asset. Returns plain data the asset turns into layer definitions. */export function normalizeClipLayers(input, context) {- if (!context) throw new RangeError('Motion layers play clips of an imported asset, so they need an asset recipe.');+ if (!context) throw invalidField('motion.layers', input, 'a field left out, since layers play clips of an imported asset and this is a scene recipe; use an asset recipe');denseArray(input, MAX_CLIP_LAYERS, 'Motion layers');- if (!input.length) throw new RangeError('Motion layers needs at least one layer. Leave it out to play none.');+ if (!input.length) throw invalidField('motion.layers', input, 'at least one layer, such as [{ "clip": 0 }]; leave layers out to play none');const resolveNode = nodeNameResolver(context);return input.map((layer, position) => normalizedLayer(layer, position, context, resolveNode));}diff --git a/src/agent-crowd.js b/src/agent-crowd.jsindex 8f0fa133..2597ada2 100644--- a/src/agent-crowd.js+++ b/src/agent-crowd.js@@ -1,3 +1,4 @@+import { invalidField } from './field-error.js';import { createCrowd } from './retarget.js';import { bakeCrowdPalette, createCrowdParts, createCrowdRig } from './crowd-skinning.js';import { jsonMaterial, materialOutput, registerCrowdModule } from './agent-scene-assets.js';@@ -13,24 +14,24 @@ const CROWD_FIELDS = ['clip', 'count', 'seed', 'layout', 'spacing', 'columns', 'function numberWithin(value, minimum, maximum, label) {if (!Number.isFinite(value) || value < minimum || value > maximum) {- throw new RangeError(`crowd ${label} must be a number from ${minimum} to ${maximum}.`);+ throw invalidField(`crowd.${label}`, value, `a number from ${minimum} to ${maximum}, such as ${Math.min(Math.max(1, minimum), maximum)}`);}return value;}/** Validate the `crowd` field of an asset placement. Returns the canonical form kept in the recipe. */export function normalizeCrowd(value) {- if (!value || typeof value !== 'object' || Array.isArray(value)) throw new TypeError('crowd must be an object.');+ if (!value || typeof value !== 'object' || Array.isArray(value)) throw invalidField('crowd', value, 'an object such as { "count": 50, "layout": "grid" }', TypeError);for (const key of Object.keys(value)) {- if (!CROWD_FIELDS.includes(key)) throw new TypeError(`Unknown crowd field: ${key}. Allowed fields: ${CROWD_FIELDS.join(', ')}.`);+ if (!CROWD_FIELDS.includes(key)) throw invalidField(`crowd.${key}`, value[key], `a known field, one of ${CROWD_FIELDS.join(', ')}`, TypeError);}if (!Number.isInteger(value.count) || value.count < 1 || value.count > CROWD_LIMITS.maxInstances) {- throw new RangeError(`crowd count must be an integer from 1 to ${CROWD_LIMITS.maxInstances}.`);+ throw invalidField('crowd.count', value.count, `an integer from 1 to ${CROWD_LIMITS.maxInstances}, such as 50`);}const layout = value.layout ?? 'grid';- if (layout !== 'grid' && layout !== 'scatter') throw new RangeError('crowd layout must be grid or scatter.');+ if (layout !== 'grid' && layout !== 'scatter') throw invalidField('crowd.layout', layout, 'one of grid or scatter');const clip = value.clip ?? 0;- if (!Number.isInteger(clip) || clip < 0) throw new RangeError('crowd clip must be a non-negative clip index.');+ if (!Number.isInteger(clip) || clip < 0) throw invalidField('crowd.clip', clip, 'a clip index of 0 or more, such as 0');const result = {clip,count: value.count,@@ -44,12 +45,12 @@ export function normalizeCrowd(value) {if (value.columns !== undefined) result.columns = Math.round(numberWithin(value.columns, 1, CROWD_LIMITS.maxInstances, 'columns'));if (value.size !== undefined) result.size = numberWithin(value.size, 0.1, 100_000, 'size');for (const flag of ['randomYaw', 'morphs', 'lods']) {- if (value[flag] !== undefined && typeof value[flag] !== 'boolean') throw new TypeError(`crowd ${flag} must be boolean.`);+ if (value[flag] !== undefined && typeof value[flag] !== 'boolean') throw invalidField(`crowd.${flag}`, value[flag], 'true or false', TypeError);}result.randomYaw = value.randomYaw ?? false;result.morphs = value.morphs ?? false;result.lods = value.lods ?? true;- if ((value.farDistance === undefined) !== (value.farRate === undefined)) throw new TypeError('crowd farDistance and farRate go together.');+ if ((value.farDistance === undefined) !== (value.farRate === undefined)) throw invalidField(value.farDistance === undefined ? 'crowd.farDistance' : 'crowd.farRate', undefined, 'both farDistance and farRate, or neither, such as { "farDistance": 40, "farRate": 8 }', TypeError);if (value.farDistance !== undefined) {result.farDistance = numberWithin(value.farDistance, 0.1, 100_000, 'farDistance');result.farRate = numberWithin(value.farRate, 1, 60, 'farRate');@@ -81,7 +82,7 @@ function buildCrowd(asset, assetId, settings) {export function expandCrowd(recipe, node, asset, copy, cache, runtime, limits) {const { id: assetId, crowd: settings } = node.asset;if (!asset.animations[settings.clip]) {- throw new RangeError(`Node ${node.id}: asset ${assetId.slice(0, 12)} has ${asset.animations.length} clips, so crowd clip ${settings.clip} does not exist.`);+ throw invalidField(`nodes.${node.id}.asset.crowd.clip`, settings.clip, `a clip index from 0 to ${asset.animations.length - 1} (asset ${assetId.slice(0, 12)} has ${asset.animations.length} clips)`);}const key = `crowd:${node.id}:${assetId}:${copy}:${JSON.stringify(settings)}`;if (cache.get(key)?.asset !== asset) {@@ -97,7 +98,7 @@ export function expandCrowd(recipe, node, asset, copy, cache, runtime, limits) {const built = cache.get(key);const rigPartCount = built.rig.parts.length;if (recipe.nodes.length + settings.count * rigPartCount > limits.maxNodes) {- throw new RangeError(`Node ${node.id}: a crowd of ${settings.count} makes ${settings.count * rigPartCount} part nodes (${rigPartCount} per instance), which with the ${recipe.nodes.length} authored nodes exceeds maxNodes ${limits.maxNodes}. Lower count or raise maxNodes.`);+ throw invalidField(`nodes.${node.id}.asset.crowd.count`, settings.count, `a count whose part nodes (${rigPartCount} per instance) fit in maxNodes ${limits.maxNodes} beside the ${recipe.nodes.length} authored nodes, so at most ${Math.max(0, Math.floor((limits.maxNodes - recipe.nodes.length) / rigPartCount))}`);}const prefix = `crowd:${assetId.slice(0, 12)}:${copy}`;const materialIds = built.rig.parts.map((rigPart, index) => {diff --git a/src/agent-motion.js b/src/agent-motion.jsindex 42a5d067..885231fc 100644--- a/src/agent-motion.js+++ b/src/agent-motion.js@@ -110,14 +110,14 @@ function normalizedKeyframe(keyframe, track, duration, interpolation) {validateValue(track.kind, track.property, result.value, 'value');const easing = normalizeKeyframeEasing(keyframe);if (easing && interpolation !== 'LINEAR' && interpolation !== 'SMOOTH') {- throw new RangeError(`Keyframe easing needs LINEAR or SMOOTH interpolation, not ${interpolation}.`);+ throw invalidField('easing', keyframe.easing, `a field left out unless the track interpolation is LINEAR or SMOOTH, not ${interpolation}`);}Object.assign(result, easing);if (interpolation === 'CUBICSPLINE') {result.inTangent = valueFrom(keyframe.inTangent, size, 'Incoming tangent');result.outTangent = valueFrom(keyframe.outTangent, size, 'Outgoing tangent');} else if (Object.hasOwn(keyframe, 'inTangent') || Object.hasOwn(keyframe, 'outTangent')) {- throw new TypeError('Tangents require CUBICSPLINE interpolation.');+ throw invalidField(Object.hasOwn(keyframe, 'inTangent') ? 'inTangent' : 'outTangent', keyframe.inTangent ?? keyframe.outTangent, `a field left out unless the track interpolation is CUBICSPLINE, such as "interpolation": "CUBICSPLINE" (this track is ${interpolation})`, TypeError);}return result;}@@ -132,25 +132,25 @@ function checkLookTarget(track, recipe) {const { kind, id, property } = track;if (!LOOK_KINDS.has(kind)) return;if (!recipe.environment || !recipe.effects) {- throw new RangeError(`Motion ${kind} tracks move the lights, sky and effects of a scene recipe; an imported asset has none.`);+ throw invalidField(`motion.tracks.${kind}`, kind, 'a node, material, morph or camera track, since lights, sky and effects belong to a scene recipe and an imported asset has none');}if (kind === 'light') {const ids = lightIds(recipe.environment);if (!ids.includes(id)) {- throw new RangeError(`Motion light was not found: ${JSON.stringify(id)}. Lights of this scene: ${ids.join(', ') || 'none'}. The sun is a sun track.`);+ throw invalidField('motion.tracks.id', id, `one of the lights of this scene: ${ids.join(', ') || 'none yet'}; the sun is a sun track, such as "point:0"`);}if (property === 'direction' && !LIGHT_DIRECTION_TYPES.has(id.split(':')[0])) {- throw new RangeError(`Motion light ${id} has no direction; only spot and area lights do. A point light takes position, color and intensity.`);+ throw invalidField('motion.tracks.property', `${id}.direction`, 'a property the light has; only spot and area lights have a direction, and a point light takes position, color and intensity');}}if (kind === 'effects' && property === 'focusDistance' && !(recipe.effects.depthOfField?.blur > 0)) {- throw new RangeError('Motion focusDistance needs effects.depthOfField.blur above 0. A camera with an fStop focuses on its target, so move the camera target track instead.');+ throw invalidField('motion.tracks.property', 'effects.focusDistance', 'a track only when effects.depthOfField.blur is above 0, such as blur 2; a camera with an fStop focuses on its target, so move the camera target track instead');}}function nodeIdFrom(value, nodes, label) {if (typeof value !== 'string' || !nodes.has(value)) {- throw new RangeError(`${label} must be a node ID in this recipe; got ${JSON.stringify(value)}.`);+ throw invalidField(label, value, 'a node ID in this recipe, such as "arm"');}return value;}@@ -160,15 +160,15 @@ function ikKeyframes(input, size, duration, label) {knownKeys(input, ['keyframes', 'interpolation'], label);const interpolation = input.interpolation ?? 'LINEAR';if (!['LINEAR', 'STEP', 'SMOOTH'].includes(interpolation)) {- throw new RangeError(`${label} interpolation must be LINEAR, STEP or SMOOTH.`);+ throw invalidField(`${label}.interpolation`, interpolation, 'LINEAR, STEP or SMOOTH');}- denseArray(input.keyframes, 64, `${label} keyframes`);+ denseArray(input.keyframes, 64, `${label}.keyframes`);if (!input.keyframes.length) {- throw new RangeError(`${label} needs at least one keyframe.`);+ throw invalidField(`${label}.keyframes`, input.keyframes, 'at least one keyframe, such as [{ "time": 0, "value": [0, 1, 0] }]');}const keyframes = input.keyframes.map(keyframe => {- knownKeys(keyframe, ['time', 'value'], `${label} keyframe`);- return { time: bounded(keyframe.time, 0, duration, 'Keyframe time'), value: valueFrom(keyframe.value, size, `${label} value`) };+ knownKeys(keyframe, ['time', 'value'], `${label}.keyframe`);+ return { time: bounded(keyframe.time, 0, duration, 'Keyframe time'), value: valueFrom(keyframe.value, size, `${label}.value`) };});return { interpolation, keyframes };}@@ -179,12 +179,12 @@ function ikPoint(input, nodes, duration, label) {}if (input && Object.hasOwn(input, 'node')) {knownKeys(input, ['node'], label);- return { node: nodeIdFrom(input.node, nodes, `${label} node`) };+ return { node: nodeIdFrom(input.node, nodes, `${label}.node`) };}if (input && Object.hasOwn(input, 'keyframes')) {return ikKeyframes(input, 3, duration, label);}- throw new TypeError(`${label} must be [x, y, z], { "node": id } or { "keyframes": [{ "time", "value" }] }.`);+ throw invalidField(label, input, '[x, y, z], { "node": id } or { "keyframes": [{ "time", "value" }] }, such as [0, 1, 0]', TypeError);}function ikWeight(input, duration, label) {@@ -204,12 +204,12 @@ 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}`);+ 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}`);+ 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.`);+ throw invalidField(`${label}.${joint}.${axis}`, input[joint][axis], '[min, max] degrees within -180 and 180, min first, such as [-90, 90]');}limits[joint][axis] = range;}@@ -218,63 +218,63 @@ function jointLimits(input, label) {}function normalizeIkSolver(input, position, nodes, visibleNodes, duration) {- const label = `Motion ik ${position}`;+ const label = `motion.ik[${position}]`;if (input?.type === 'two-bone') {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`),- middle: nodeIdFrom(input.middle, nodes, `${label} middle`),- end: nodeIdFrom(input.end, nodes, `${label} end`),- target: ikPoint(input.target, visibleNodes, duration, `${label} target`),- weight: ikWeight(input.weight, duration, `${label} weight`),+ root: nodeIdFrom(input.root, nodes, `${label}.root`),+ middle: nodeIdFrom(input.middle, nodes, `${label}.middle`),+ end: nodeIdFrom(input.end, nodes, `${label}.end`),+ target: ikPoint(input.target, visibleNodes, duration, `${label}.target`),+ weight: ikWeight(input.weight, duration, `${label}.weight`),};if (input.pole !== undefined) {- solver.pole = ikPoint(input.pole, visibleNodes, duration, `${label} pole`);+ solver.pole = ikPoint(input.pole, visibleNodes, duration, `${label}.pole`);}if (input.keepEndRotation !== undefined) {if (typeof input.keepEndRotation !== 'boolean') {- throw new TypeError(`${label} keepEndRotation must be boolean.`);+ throw invalidField(`${label}.keepEndRotation`, input.keepEndRotation, 'true or false', TypeError);}solver.keepEndRotation = input.keepEndRotation;}if (input.limits !== undefined) {- solver.limits = jointLimits(input.limits, `${label} limits`);+ solver.limits = jointLimits(input.limits, `${label}.limits`);}if (input.bendToward !== undefined) {- solver.bendToward = valueFrom(input.bendToward, 3, `${label} bendToward`);+ solver.bendToward = valueFrom(input.bendToward, 3, `${label}.bendToward`);}return solver;}if (input?.type === 'aim') {knownKeys(input, ['type', 'joint', 'joints', 'forward', 'worldForward', 'target', 'maxAngle', 'weight'], label);if (input.forward !== undefined && input.worldForward !== undefined) {- throw new TypeError(`${label} takes forward or worldForward, not both.`);+ throw invalidField(`${label}.worldForward`, input.worldForward, 'forward or worldForward, not both; leave one out', TypeError);}if ((input.joint === undefined) === (input.joints === undefined)) {- throw new TypeError(`${label} needs joint, or joints listed from the base of the chain to the aiming node.`);+ throw invalidField(`${label}.joint`, input.joint, 'joint, or joints listed from the base of the chain to the aiming node, such as { "joint": "head" }', TypeError);}- const names = input.joints === undefined ? [input.joint] : denseArray(input.joints, 16, `${label} joints`);+ const names = input.joints === undefined ? [input.joint] : denseArray(input.joints, 16, `${label}.joints`);if (!names.length) {- throw new RangeError(`${label} joints cannot be empty.`);+ throw invalidField(`${label}.joints`, input.joints, 'at least one node ID, such as ["neck", "head"]');}const solver = {type: 'aim',- joints: names.map(name => nodeIdFrom(name, nodes, `${label} joint`)),- target: ikPoint(input.target, visibleNodes, duration, `${label} target`),- weight: ikWeight(input.weight, duration, `${label} weight`),+ joints: names.map(name => nodeIdFrom(name, nodes, `${label}.joint`)),+ target: ikPoint(input.target, visibleNodes, duration, `${label}.target`),+ weight: ikWeight(input.weight, duration, `${label}.weight`),};if (input.worldForward !== undefined) {- solver.worldForward = valueFrom(input.worldForward, 3, `${label} worldForward`);+ solver.worldForward = valueFrom(input.worldForward, 3, `${label}.worldForward`);} else {- solver.forward = valueFrom(input.forward ?? [0, 0, 1], 3, `${label} forward`);+ solver.forward = valueFrom(input.forward ?? [0, 0, 1], 3, `${label}.forward`);}if (input.maxAngle !== undefined) {- solver.maxAngle = bounded(input.maxAngle, 0.001, 180, `${label} maxAngle`);+ solver.maxAngle = bounded(input.maxAngle, 0.001, 180, `${label}.maxAngle`);}return solver;}- throw new RangeError(`${label} type must be two-bone or aim.`);+ throw invalidField(`${label}.type`, input?.type, 'one of two-bone or aim');}function solverNodes(solver) {@@ -308,11 +308,11 @@ function checkIkScales(ik, tracks, recipe) {}for (const id of uniformRequired) {if (scaledByTrack.has(id)) {- throw new RangeError(`Motion ik: node ${id} has IK nodes below it, so it cannot have a scale track.`);+ throw invalidField('motion.tracks', `node ${id} scale`, `no scale track on node ${id}, since IK nodes sit below it; drop the track or put the size on a child node`);}const scale = nodesById.get(id).scale ?? [1, 1, 1];if (Math.max(...scale) - Math.min(...scale) > 1e-3 * Math.max(...scale)) {- throw new RangeError(`Motion ik: node ${id} has non-uniform scale ${JSON.stringify(scale)}. It has IK nodes below it, so keep it at uniform scale and put the size on a child node with the geometry.`);+ throw invalidField(`nodes.${id}.scale`, scale, 'a uniform scale such as [1, 1, 1], since IK nodes sit below it; put the size on a child node with the geometry');}}}@@ -345,7 +345,7 @@ function ikKeyframeCount(ik) {/** The canonical drive entry and the drive built from it, which proves the wheels, path and speeds are usable. */function normalizedDrive(input, recipe) {if (!recipe.normalizeDrive) {- throw new RangeError('motion.drive moves an imported asset recipe. For an asset placed in a scene, give the placement a drive: { asset: { id, drive } }.');+ throw invalidField('motion.drive', input, 'a field left out in a scene recipe, since it moves an imported asset recipe; for an asset placed in a scene, give the placement a drive: { asset: { id, drive } }');}const canonical = recipe.normalizeDrive(input, 'motion.drive');return { canonical, built: recipe.buildDrive(canonical) };@@ -366,7 +366,7 @@ export function normalizeAgentMotion(input, recipe) {const inputTracks = input.tracks ?? [];denseArray(inputTracks, 128, 'Motion tracks');if (!inputTracks.length && !input.layers?.length && !input.ik?.length && !input.constraints?.length && !input.drivers?.length && !drive) {- throw new RangeError('Motion needs at least one track, IK solver, constraint or driver. Use null to clear it.');+ throw invalidField('motion', input, 'at least one track, IK solver, constraint or driver, such as { "duration": 1, "tracks": [...] }; 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));@@ -382,16 +382,16 @@ export function normalizeAgentMotion(input, recipe) {}if (SINGLETON_KINDS.has(track.kind)) {if (Object.hasOwn(track, 'id')) {- throw new TypeError(`${track.kind[0].toUpperCase()}${track.kind.slice(1)} tracks cannot have an ID.`);+ throw invalidField(`motion.tracks[${index}].id`, track.id, `a field left out, since ${track.kind} tracks have no ID, such as { "kind": "${track.kind}", "property": ..., "keyframes": [...] }`, TypeError);}} else {if (typeof track.id !== 'string' || !track.id.trim() || track.id.length > 128) {- throw new TypeError('Motion target IDs need 1 to 128 characters.');+ throw invalidField(`motion.tracks[${index}].id`, track.id, 'an ID of 1 to 128 characters, such as "body"', TypeError);}const references = track.kind === 'node' ? nodes : track.kind === 'morph' ? morphTargets : materials;if (track.kind !== 'light' && !references.has(track.id)) {- const hint = track.kind === 'morph' ? ` Morph targets of this asset: ${[...morphTargets].slice(0, 24).join(', ') || 'none'}.` : '';- throw new RangeError(`Motion target was not found: ${track.id}.${hint}`);+ const hint = track.kind === 'morph' ? `; morph targets of this asset: ${[...morphTargets].slice(0, 24).join(', ') || 'none'}` : '';+ throw invalidField(`motion.tracks[${index}].id`, track.id, `the ID of a ${track.kind} in this recipe, such as ${JSON.stringify([...references][0] ?? 'body')}${hint}`);}}checkLookTarget(track, recipe);@@ -407,7 +407,7 @@ export function normalizeAgentMotion(input, recipe) {denseArray(track.keyframes, 64, 'Motion keyframes');keyframeCount += track.keyframes.length;if (keyframeCount > 2048) {- throw new RangeError('Motion exceeds 2048 total keyframes.');+ throw invalidField(`motion.tracks[${index}].keyframes`, track.keyframes.length, `fewer keyframes, since a motion holds at most 2048 in total and this track reaches ${keyframeCount}`);}const keyframes = track.keyframes.map((keyframe, keyframeIndex) => withFieldPrefix(`motion.tracks[${index}].keyframes[${keyframeIndex}]`, () => normalizedKeyframe(keyframe, track, duration, interpolation)));const clip = createAnimationClip({@@ -434,13 +434,13 @@ export function normalizeAgentMotion(input, recipe) {result.layers = normalizeClipLayers(input.layers, recipe.clipLayerContext);}if (input.footLock !== undefined) {- if (!result.layers?.length) throw new RangeError('Motion footLock plants the feet of the clips in motion.layers, so it needs layers.');+ if (!result.layers?.length) throw invalidField('motion.footLock', input.footLock, 'a field left out unless motion.layers has layers, since it plants the feet of their clips, such as layers [{ "clip": 0 }]');result.footLock = normalizeFootLock(input.footLock);}if (input.ik !== undefined) {result.ik = normalizeIk(input.ik, recipe, tracks, duration);if (keyframeCount + ikKeyframeCount(result.ik) > 2048) {- throw new RangeError('Motion exceeds 2048 total keyframes.');+ throw invalidField('motion.ik', input.ik, `fewer keyframes, since a motion holds at most 2048 in total and tracks plus IK reach ${keyframeCount + ikKeyframeCount(result.ik)}`);}}const visibleIds = new Set(ikHierarchy(recipe).map(node => node.id));@@ -451,7 +451,7 @@ export function normalizeAgentMotion(input, recipe) {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.`);+ throw invalidField('motion.drivers', `${target.id} ${target.property}`, `a property no track animates, since a track on ${target.kind} ${target.id} already moves ${target.property}; drop the track or the driver`);}}}@@ -563,16 +563,16 @@ function createIkEvaluator(motion, recipe, stagedNodeTracks) {};}-function validateRadiance(material) {+function validateRadiance(material, materialId) {const emission = material.emission ?? 0;const color = material.emissiveColor ?? material.color ?? [0.5, 0.5, 0.5];for (const component of color) {const radiance = Math.fround(component) * Math.fround(emission);if (!Number.isFinite(Math.fround(radiance))) {- throw new RangeError('Motion emissive radiance exceeds Float32 range.');+ throw invalidField(`materials.${materialId}.emission`, emission, 'a value that keeps emissiveColor times emission inside Float32 range, such as 5');}if (material.tag === 'unlit' && radiance > 65500) {- throw new RangeError('Motion unlit radiance exceeds the HDR range.');+ throw invalidField(`materials.${materialId}.emission`, emission, 'a value that keeps an unlit emissiveColor times emission at or below 65500, such as 5');}}}@@ -716,7 +716,7 @@ export function compileAgentMotion(input, recipe) {const stagedCamera = cameraPath ? { eye: new Float32Array(3), target: new Float32Array(3), up: new Float32Array(3) } : null;if (cameraPath) {if (cameraInput.focalLength !== undefined && cameraTracks.some(track => track.property === 'fov')) {- throw new RangeError('A camera with a focalLength cannot have a fov track. Give the camera a fov, or leave fov out of the motion.');+ throw invalidField('motion.tracks.property', 'camera.fov', 'a camera track other than fov, since the camera has a focalLength; give the camera a fov instead, or leave fov out of the motion');}output.camera = {eye: new Float32Array(3), target: new Float32Array(3), up: new Float32Array(3),@@ -807,8 +807,8 @@ export function compileAgentMotion(input, recipe) {materialSamples.get(target.id)[target.property] = value;drivenValues.push({ target, value });}- for (const material of materialSamples.values()) {- validateRadiance(material);+ for (const [materialId, material] of materialSamples) {+ validateRadiance(material, materialId);}if (cameraPath) {cameraPath.sample(time, stagedCamera);@@ -817,7 +817,7 @@ export function compileAgentMotion(input, recipe) {}if (Math.fround(stagedCamera.fov) <= 0 || Math.fround(stagedCamera.fov) >= 180 ||Math.fround(stagedCamera.near) <= 0 || Math.fround(stagedCamera.far) <= Math.fround(stagedCamera.near)) {- throw new RangeError('Sampled camera lens is invalid at Float32 precision.');+ throw invalidField('motion.tracks.camera', { fov: stagedCamera.fov, near: stagedCamera.near, far: stagedCamera.far }, 'a lens with fov above 0 and below 180, near above 0 and far above near, such as fov 50, near 0.1, far 100; check the fov, near and far tracks');}}// Publish only after every track, material product, camera pose, IK solve and constraint passes.diff --git a/src/agent-navigation.js b/src/agent-navigation.jsindex 9472554b..d4617bed 100644--- a/src/agent-navigation.js+++ b/src/agent-navigation.js@@ -1,6 +1,7 @@// The path query of scene_inspect: a route over a ground node that goes around holes and obstacles, returned as// keyframes that can go straight into a node translation track. It loads on demand, so the scene entry does not carry it.import { createNavmesh } from './navmesh.js';+import { invalidField } from './field-error.js';export const NAVIGATION_FIELDS = ['ground', 'from', 'to', 'avoid', 'radius', 'maxSlope', 'cellSize', 'seconds', 'speed', 'lift', 'spacing'];@@ -14,7 +15,7 @@ function rounded(value) {function numberOption(value, label, minimum, maximum) {if (value === undefined) return undefined;if (!Number.isFinite(value) || value < minimum || value > maximum) {- throw new RangeError(`path ${label} must be a number from ${minimum} to ${maximum}.`);+ throw invalidField(`path.${label}`, value, `a number from ${minimum} to ${maximum}, such as ${Math.min(Math.max(1, minimum), maximum)}`);}return value;}@@ -26,7 +27,7 @@ function numberOption(value, label, minimum, maximum) {export function queryAgentPath(query, ground, avoidBounds) {const seconds = numberOption(query.seconds, 'seconds', 0.1, 600);const speed = numberOption(query.speed, 'speed', 0.01, 100);- if (seconds !== undefined && speed !== undefined) throw new RangeError('path takes seconds or speed, not both.');+ if (seconds !== undefined && speed !== undefined) throw invalidField('path.speed', speed, 'speed or seconds, not both; leave speed out when seconds is set, such as { "seconds": 4 }');const lift = numberOption(query.lift, 'lift', -MAXIMUM_LIFT, MAXIMUM_LIFT) ?? 0;const navmesh = createNavmesh({positions: ground.positions,@@ -56,11 +57,11 @@ export function queryAgentPath(query, ground, avoidBounds) {/** The path option of scene_inspect: checks the query, resolves the ground and avoided node IDs through `nodeGeometry` and finds the route. */export function resolvePathQuery(query, nodeGeometry, boundsFor) {- if (query === null || typeof query !== 'object' || Array.isArray(query)) throw new TypeError('path must be an object.');+ if (query === null || typeof query !== 'object' || Array.isArray(query)) throw invalidField('path', query, 'an object such as { "ground": "floor", "from": [0, 0, 0], "to": [5, 0, 5] }', TypeError);for (const key of Object.keys(query)) {- if (!NAVIGATION_FIELDS.includes(key)) throw new TypeError(`Unknown path field: ${key}. Allowed fields: ${NAVIGATION_FIELDS.join(', ')}.`);+ if (!NAVIGATION_FIELDS.includes(key)) throw invalidField(`path.${key}`, query[key], `a known field, one of ${NAVIGATION_FIELDS.join(', ')}`, TypeError);}- if (query.avoid !== undefined && (!Array.isArray(query.avoid) || query.avoid.length > 64)) throw new RangeError('path avoid must list at most 64 node IDs.');+ if (query.avoid !== undefined && (!Array.isArray(query.avoid) || query.avoid.length > 64)) throw invalidField('path.avoid', query.avoid, 'a list of at most 64 node IDs, such as ["wall"]');const { geometry, worldMatrix } = nodeGeometry(query.ground, 'ground');const positions = new Float32Array(geometry.positions.length);for (let offset = 0; offset < positions.length; offset += 3) {diff --git a/src/agent-relations.js b/src/agent-relations.jsindex 1a44c7b1..f32012d5 100644--- a/src/agent-relations.js+++ b/src/agent-relations.js@@ -1,4 +1,5 @@import { mat4, vec3 } from 'gl-matrix';+import { invalidField } from './field-error.js';// Relations place a part against another part's bounds, so a resized body keeps its handle where it belongs.// A node lists relations; each one fixes the node's world bounds on one or more axes from the bounds of another@@ -27,32 +28,33 @@ function sideAxis(side) {return axisIndex(side[1]);}-function describe(nodeId, index, relation) {- return `Relation ${index} of node ${JSON.stringify(nodeId.slice(0, 48))} (${relation.kind} to ${JSON.stringify(String(relation.to).slice(0, 48))})`;+function relationPath(nodeIndex, index) {+ return `nodes[${nodeIndex}].relations[${index}]`;}-function normalizeRelation(node, index, relation) {+function normalizeRelation(nodeIndex, index, relation) {+ const path = relationPath(nodeIndex, index);if (!relation || typeof relation !== 'object' || Array.isArray(relation)) {- throw new TypeError(`Relation ${index} of node ${node.id} must be an object such as { "kind": "attach", "to": "body", "side": "+x" }.`);+ throw invalidField(path, relation, 'an object such as { "kind": "attach", "to": "body", "side": "+x" }', TypeError);}if (!RELATION_KINDS.includes(relation.kind)) {- throw new TypeError(`Relation ${index} of node ${node.id} has kind ${JSON.stringify(String(relation.kind).slice(0, 48))}. Use one of ${RELATION_KINDS.join(', ')}.`);+ throw invalidField(`${path}.kind`, relation.kind, `one of ${RELATION_KINDS.join(', ')}`, TypeError);}const allowed = ['kind', 'to', 'region', ...(KIND_FIELDS[relation.kind] ?? [])];for (const key of Object.keys(relation)) {if (!allowed.includes(key)) {- throw new TypeError(`${describe(node.id, index, relation)} has unknown field ${JSON.stringify(key.slice(0, 48))}. A ${relation.kind} relation takes: ${allowed.join(', ')}.`);+ throw invalidField(`${path}.${key.slice(0, 48)}`, relation[key], `a field a ${relation.kind} relation takes: ${allowed.join(', ')}`, TypeError);}}if (typeof relation.to !== 'string' || !relation.to) {- throw new TypeError(`${describe(node.id, index, relation)} needs "to", the ID of the part it is placed against.`);+ throw invalidField(`${path}.to`, relation.to, 'the ID of the part it is placed against, such as "body"', TypeError);}if (relation.region !== undefined && (typeof relation.region !== 'string' || !relation.region || relation.region.length > 128)) {- throw new TypeError(`${describe(node.id, index, relation)} region must be a mesh tag name of at most 128 characters.`);+ throw invalidField(`${path}.region`, relation.region, 'a mesh tag name of 1 to 128 characters, such as "top"', TypeError);}const offset = relation.offset ?? 0;if (!Number.isFinite(offset) || Math.abs(offset) > RELATION_LIMITS.maxOffset) {- throw new RangeError(`${describe(node.id, index, relation)} offset must be a finite number of metres within +-${RELATION_LIMITS.maxOffset}.`);+ throw invalidField(`${path}.offset`, relation.offset, `a finite number of metres within +-${RELATION_LIMITS.maxOffset}, such as 0.1`);}const result = { kind: relation.kind, to: relation.to };if (relation.region !== undefined) {@@ -63,13 +65,13 @@ function normalizeRelation(node, index, relation) {}if (KIND_FIELDS[relation.kind].includes('side')) {if (!RELATION_SIDES.includes(relation.side)) {- throw new TypeError(`${describe(node.id, index, relation)} needs side, one of ${RELATION_SIDES.join(', ')}: the face of "${relation.to}" it sits against.`);+ throw invalidField(`${path}.side`, relation.side, `one of ${RELATION_SIDES.join(', ')}, the face of "${relation.to}" it sits against`, TypeError);}result.side = relation.side;}if (relation.kind === 'align') {if (!AXES.includes(relation.axis) || !ANCHORS.includes(relation.at)) {- throw new TypeError(`${describe(node.id, index, relation)} needs axis (x, y or z) and at (${ANCHORS.join(', ')}).`);+ throw invalidField(AXES.includes(relation.axis) ? `${path}.at` : `${path}.axis`, AXES.includes(relation.axis) ? relation.at : relation.axis, AXES.includes(relation.axis) ? `one of ${ANCHORS.join(', ')}` : 'x, y or z', TypeError);}result.axis = relation.axis;result.at = relation.at;@@ -77,7 +79,7 @@ function normalizeRelation(node, index, relation) {if (relation.kind === 'centered') {const axes = relation.axes ?? AXES;if (!Array.isArray(axes) || axes.length === 0 || axes.length > 3 || axes.some(axis => !AXES.includes(axis)) || new Set(axes).size !== axes.length) {- throw new TypeError(`${describe(node.id, index, relation)} axes must list each of x, y, z at most once, or be left out for all three.`);+ throw invalidField(`${path}.axes`, relation.axes, 'a list of x, y, z with each at most once, such as ["x", "z"], or left out for all three', TypeError);}result.axes = [...axes].sort();}@@ -110,8 +112,8 @@ function dependencyOrder(nodesById, relatedIds) {}const position = path.indexOf(nodeId);if (position !== -1) {- const cycle = [...path.slice(position), nodeId].map(id => JSON.stringify(id.slice(0, 48))).join(' -> ');- throw new RangeError(`Relations form a cycle: ${cycle} (each part waits for the next, parents included). Remove one relation in the loop with set-node relations, or place one part with translation instead.`);+ const cycle = [...path.slice(position), nodeId].map(id => id.slice(0, 48));+ throw invalidField(`nodes[${[...nodesById.keys()].indexOf(nodeId)}].relations`, cycle, 'relations that form no loop, since each part waits for the next in the list, parents included; remove one relation in the loop with set-node relations, or place one part with translation');}path.push(nodeId);const node = nodesById.get(nodeId);@@ -152,10 +154,11 @@ export function normalizeRelations(nodes) {const resultById = indexNodes(result);let relatedCount = 0;for (const node of related) {+ const nodeIndex = nodes.indexOf(node);if (!Array.isArray(node.relations) || node.relations.length > RELATION_LIMITS.maxPerNode) {- throw new RangeError(`Node ${node.id} relations must be an array of at most ${RELATION_LIMITS.maxPerNode} entries. Merge or drop relations.`);+ throw invalidField(`nodes[${nodeIndex}].relations`, node.relations, `an array of at most ${RELATION_LIMITS.maxPerNode} relations; merge or drop some`);}- const normalized = node.relations.map((relation, index) => normalizeRelation(node, index, relation));+ const normalized = node.relations.map((relation, index) => normalizeRelation(nodeIndex, index, relation));const target = resultById.get(node.id);if (normalized.length === 0) {delete target.relations;@@ -163,26 +166,26 @@ export function normalizeRelations(nodes) {}relatedCount++;if (relatedCount > RELATION_LIMITS.maxNodes) {- throw new RangeError(`At most ${RELATION_LIMITS.maxNodes} nodes can carry relations. Group repeated parts or place the rest with translation.`);+ throw invalidField(`nodes[${nodeIndex}].relations`, node.relations, `relations on at most ${RELATION_LIMITS.maxNodes} nodes; group repeated parts or place the rest with translation`);}if (node.geometry === undefined) {- throw new TypeError(`Node ${node.id} is a group, and relations place mesh nodes. Put the relations on a mesh node inside the group.`);+ throw invalidField(`nodes[${nodeIndex}].relations`, node.relations, 'relations on a mesh node, since this node is a group; put them on a mesh node inside the group', TypeError);}const decided = new Map();normalized.forEach((relation, index) => {const referenced = nodesById.get(relation.to);if (relation.to === node.id) {- throw new RangeError(`${describe(node.id, index, relation)} points at its own node. Point "to" at another part.`);+ throw invalidField(`${relationPath(nodeIndex, index)}.to`, relation.to, 'the ID of another part, such as "body", not its own node');}if (!referenced) {- throw new RangeError(`${describe(node.id, index, relation)}: no node has that ID. Use a node ID from scene_inspect, or drop the relation.`);+ throw invalidField(`${relationPath(nodeIndex, index)}.to`, relation.to, 'the ID of a node in this recipe; list them with scene_inspect, or drop the relation');}if (referenced.geometry === undefined) {- throw new RangeError(`${describe(node.id, index, relation)}: the target is a group with no geometry. Point "to" at a mesh node.`);+ throw invalidField(`${relationPath(nodeIndex, index)}.to`, relation.to, 'the ID of a mesh node, such as a box, since this one is a group with no geometry');}for (const axis of relationAxes(relation)) {if (decided.has(axis)) {- throw new RangeError(`${describe(node.id, index, relation)} decides the ${AXES[axis]} axis, which relation ${decided.get(axis)} already decides. Keep one relation per axis.`);+ throw invalidField(`${relationPath(nodeIndex, index)}.kind`, relation.kind, `a relation that leaves the ${AXES[axis]} axis to relation ${decided.get(axis)}, which already decides it; keep one relation per axis`);}decided.set(axis, index);}@@ -270,6 +273,7 @@ export function solveRelations(nodes, worldBounds) {const cache = new Map();for (const nodeId of dependencyOrder(nodesById, new Set(related.map(node => node.id)))) {const node = nodesById.get(nodeId);+ const nodeIndex = nodes.findIndex(candidate => candidate.id === nodeId);const delta = [0, 0, 0];const selfBounds = worldBounds(node, worldMatrixOf(nodeId, nodesById, cache), undefined);node.relations.forEach((relation, index) => {@@ -278,7 +282,7 @@ export function solveRelations(nodes, worldBounds) {try {targetBounds = worldBounds(target, worldMatrixOf(target.id, nodesById, cache), relation.region);} catch (error) {- throw new RangeError(`${describe(nodeId, index, relation)} cannot be satisfied: ${error.message}`);+ throw invalidField(`${relationPath(nodeIndex, index)}.${relation.region === undefined ? 'to' : 'region'}`, relation.region ?? relation.to, `a target that can be measured (${error.message})`);}for (const constraint of constraintsFor(relation, selfBounds, targetBounds)) {delta[constraint.axis] = constraint.delta;@@ -287,13 +291,13 @@ export function solveRelations(nodes, worldBounds) {const parentWorld = node.parent !== null && nodesById.has(node.parent) ? worldMatrixOf(node.parent, nodesById, cache) : mat4.create();const inverse = mat4.invert(mat4.create(), parentWorld);if (!inverse) {- throw new RangeError(`Node ${nodeId} sits under a parent with a singular transform, so its relations cannot be solved. Fix the parent scale.`);+ throw invalidField(`nodes[${nodes.findIndex(candidate => candidate.id === node.parent)}].scale`, nodesById.get(node.parent).scale, `a scale with no zero axis, since the relations of nodes[${nodeIndex}] cannot be solved under it, such as [1, 1, 1]`);}const local = vec3.transformMat4(vec3.create(), delta, inverse);const origin = vec3.transformMat4(vec3.create(), [0, 0, 0], inverse);node.translation = node.translation.map((value, axis) => value + local[axis] - origin[axis]);if (!node.translation.every(Number.isFinite)) {- throw new RangeError(`Relations on node ${nodeId} produce a translation outside the number range. Reduce offsets or part sizes.`);+ throw invalidField(`nodes[${nodeIndex}].translation`, node.translation, 'finite numbers, but its relations produce a translation outside the number range; reduce offsets or part sizes');}cache.clear();}diff --git a/tests/actionable-errors-motion.test.js b/tests/actionable-errors-motion.test.jsnew file mode 100644index 00000000..048af709--- /dev/null+++ b/tests/actionable-errors-motion.test.js@@ -0,0 +1,169 @@+import assert from 'node:assert/strict';+import { readFileSync } from 'node:fs';+import test from 'node:test';+import { createAgentScene, loadAllAgentSceneModules } from '../src/agent-scene.js';+import { assetCopyKey } from '../src/agent-scene-assets.js';+import { createAgentAssetScene } from '../src/agent-asset.js';+import { createBranchStore } from '../src/agent-branches.js';+import { describeReceived } from '../src/field-error.js';+import { parseGltf } from '../src/gltf.js';+import { MIXAMO_LIKE, UNREAL_LIKE, humanoidGlb, humanoidJoints, walkTracks } from './fixtures/humanoid-glb.js';++await loadAllAgentSceneModules();++// Validation errors of the motion group: a field path, the value received and what is accepted with an example or range.++function sceneRecipe(change) {+ const recipe = {+ format: '67js.scene', schemaVersion: 1,+ geometries: [{ id: 'cube', type: 'box' }],+ materials: [{ id: 'plain', color: [0.5, 0.5, 0.5] }],+ nodes: [+ { id: 'body', geometry: 'cube', material: 'plain' },+ { id: 'arm', geometry: 'cube', material: 'plain', parent: 'body' },+ { id: 'group' },+ ],+ motion: { duration: 1, tracks: [{ kind: 'node', id: 'body', property: 'translation', keyframes: [{ time: 0, value: [0, 0, 0] }] }] },+ };+ change(recipe);+ return () => createAgentScene(recipe);+}++const track = extra => ({ kind: 'node', id: 'body', property: 'translation', keyframes: [{ time: 0, value: [0, 0, 0] }], ...extra });+const withTracks = tracks => recipe => { recipe.motion.tracks = tracks; };+const withRelations = relations => recipe => { recipe.nodes[1].relations = relations; };+const attach = { kind: 'attach', to: 'body', side: '+x' };++const ASSET_ID = 'ef'.repeat(32);+const robotBytes = readFileSync(new URL('./fixtures/RobotExpressive.glb', import.meta.url));++async function crowdScene(crowd) {+ const parse = () => parseGltf(robotBytes.buffer.slice(robotBytes.byteOffset, robotBytes.byteOffset + robotBytes.byteLength), { maxVertices: 500000 });+ const assets = new Map([[assetCopyKey(ASSET_ID, 0), await parse()], [assetCopyKey(ASSET_ID, 1), await parse()]]);+ return createAgentScene({+ format: '67js.scene', schemaVersion: 1,+ geometries: [{ id: 'ground', type: 'box' }],+ materials: [{ id: 'grass', color: [0.2, 0.5, 0.2] }],+ nodes: [{ id: 'floor', geometry: 'ground', material: 'grass' }, { id: 'people', asset: { id: ASSET_ID, crowd } }],+ }, {}, { assets });+}++const SOURCE_ID = 'ab'.repeat(32);+const TARGET_ID = 'cd'.repeat(32);++async function layerScene(layers) {+ const parse = bytes => parseGltf(bytes, { maxVertices: 500000 });+ const sourceJoints = humanoidJoints();+ const clips = [{ name: 'Walk', duration: 1, tracks: walkTracks(sourceJoints) }];+ const source = await parse(humanoidGlb({ names: MIXAMO_LIKE, joints: sourceJoints, clips }));+ const asset = await parse(humanoidGlb({ names: UNREAL_LIKE, joints: humanoidJoints(), face: true }));+ const recipe = { format: '67js.asset', schemaVersion: 1, assetId: TARGET_ID, motion: { duration: 1, layers } };+ return createAgentAssetScene(asset, recipe, { sources: { [SOURCE_ID]: source } });+}++const fromSource = extra => ({ from: { asset: SOURCE_ID, clip: 0 }, ...extra });++function inspectPath(path) {+ return () => {+ const scene = createAgentScene({+ format: '67js.scene', schemaVersion: 1,+ geometries: [{ id: 'ground', type: 'box' }],+ materials: [{ id: 'grass', color: [0.3, 0.6, 0.2] }],+ nodes: [{ id: 'ground', geometry: 'ground', material: 'grass', scale: [40, 0.1, 40] }],+ });+ return scene.inspect({ path: { ground: 'ground', from: [-15, -15], to: [15, 15], ...path } });+ };+}++function forkInput() {+ return { recipe: { nodes: [] }, baseRecipe: { nodes: [] }, operations: [], baseRevision: 0 };+}++// Each case: how an agent reaches the error, the field path it must name and the value it must echo.+const CASES = [+ // src/agent-motion.js+ ['motion track on an unknown node', sceneRecipe(withTracks([track({ id: 'ghost' })])), 'motion.tracks[0].id', '"ghost"'],+ ['motion sun track with an ID', sceneRecipe(withTracks([track({ kind: 'sun', id: 'x', property: 'intensity', keyframes: [{ time: 0, value: 1 }] })])), 'motion.tracks[0].id', '"x"'],+ ['motion light track that does not exist', sceneRecipe(withTracks([track({ kind: 'light', id: 'point:9', property: 'intensity', keyframes: [{ time: 0, value: 1 }] })])), 'motion.tracks.id', '"point:9"'],+ ['motion keyframe tangent without CUBICSPLINE', sceneRecipe(withTracks([track({ keyframes: [{ time: 0, value: [0, 0, 0], inTangent: [0, 0, 0] }] })])), 'motion.tracks[0].keyframes[0].inTangent', '[0,0,0]'],+ ['motion IK solver of an unknown type', sceneRecipe(recipe => { recipe.motion.ik = [{ type: 'fabrik', target: [0, 0, 0] }]; }), 'motion.ik[0].type', '"fabrik"'],+ ['motion IK aim without a joint', sceneRecipe(recipe => { recipe.motion.ik = [{ type: 'aim', target: [0, 0, 0] }]; }), 'motion.ik[0].joint', 'undefined'],+ ['motion with nothing to play', sceneRecipe(recipe => { recipe.motion = { duration: 1 }; }), 'motion', '{"duration":1}'],++ // src/agent-relations.js+ ['relation of an unknown kind', sceneRecipe(withRelations([{ ...attach, kind: 'weld' }])), 'nodes[1].relations[0].kind', '"weld"'],+ ['relation with a bad side', sceneRecipe(withRelations([{ ...attach, side: '+w' }])), 'nodes[1].relations[0].side', '"+w"'],+ ['relation to its own node', sceneRecipe(withRelations([{ ...attach, to: 'arm' }])), 'nodes[1].relations[0].to', '"arm"'],+ ['relation to a group', sceneRecipe(withRelations([{ ...attach, to: 'group' }])), 'nodes[1].relations[0].to', '"group"'],+ ['relation offset out of range', sceneRecipe(withRelations([{ ...attach, offset: 1e12 }])), 'nodes[1].relations[0].offset', '1000000000000'],++ // src/agent-branches.js+ ['branch name with capitals', () => createBranchStore().fork('Bad Name', forkInput()), 'branch', '"Bad Name"'],+ ['branch that is not known', () => createBranchStore().get('missing'), 'branch', '"missing"'],+ ['ninth branch', () => {+ const store = createBranchStore();+ for (let index = 0; index < 9; index++) store.fork(`b${index}`, forkInput());+ }, 'branch', '"b8"'],++ // src/agent-navigation.js+ ['path with both seconds and speed', inspectPath({ seconds: 2, speed: 1 }), 'path.speed', '1'],+ ['path with an unknown field', inspectPath({ bogus: 1 }), 'path.bogus', '1'],+ ['path avoid that is not a list', inspectPath({ avoid: 'rock' }), 'path.avoid', '"rock"'],+ ['path radius out of range', inspectPath({ radius: 0 }), 'path.radius', '0'],++ // src/agent-crowd.js+ ['crowd with an unknown field', () => crowdScene({ count: 4, bogus: 1 }), 'crowd.bogus', '1'],+ ['crowd count of zero', () => crowdScene({ count: 0 }), 'crowd.count', '0'],+ ['crowd layout that does not exist', () => crowdScene({ count: 4, layout: 'ring' }), 'crowd.layout', '"ring"'],+ ['crowd clip beyond the clip list', () => crowdScene({ count: 4, clip: 99 }), 'clip', '99'],++ // src/agent-clip-layers.js+ ['layer from an asset that is not loaded', () => layerScene([{ from: { asset: 'ee'.repeat(32), clip: 0 } }]), 'motion.layers[0].from.asset', describeReceived('ee'.repeat(32))],+ ['layer clip beyond the clip list', () => layerScene([fromSource({ from: { asset: SOURCE_ID, clip: 5 } })]), 'motion.layers[0].from.clip', '5'],+ ['layer with both from and clip', () => layerScene([fromSource({ clip: 0 })]), 'motion.layers[0].from', describeReceived({ asset: SOURCE_ID, clip: 0 })],+ ['layer flag that is not boolean', () => layerScene([fromSource({ loop: 'yes' })]), 'motion.layers[0].loop', '"yes"'],+ ['layer mask without joints', () => layerScene([fromSource({ mask: { joints: [] } })]), 'motion.layers[0].mask.joints', '[]'],+ ['layer mask on an unknown node', () => layerScene([fromSource({ mask: { joints: ['nowhere'] } })]), 'motion.layers[0].mask.joints', '"nowhere"'],+];++const ACCEPTED = /such as|\bfrom -?[\d.e]+ to -?[\d.e]+|one of |true or false|above \d|\bor more\b/;++for (const [label, trigger, path, received] of CASES) {+ test(`error for ${label} names the field, the value and what is accepted`, async () => {+ let message;+ try {+ await trigger();+ } catch (error) {+ message = error.message;+ }+ assert.ok(message, `${label} must throw`);+ assert.ok(message.includes(path), `path ${path} missing in: ${message}`);+ assert.ok(message.includes(`got ${received}`), `received value ${received} missing in: ${message}`);+ assert.match(message, /expected /, `no expectation in: ${message}`);+ assert.match(message, ACCEPTED, `no example or range in: ${message}`);+ });+}++// The guard: these files hold validators an agent reaches through motion, relations, branches, path queries and crowds.+// A throw in them reports through invalidField, which names the path, the value and what is accepted. The throws listed+// here stay raw on purpose (engine invariants no recipe field can fix). A new raw throw fails this test until it uses+// invalidField or is listed.+const RAW_THROWS_LEFT = {+ 'src/agent-motion.js': [+ '`Motion ik produced an invalid rotation ',+ ],+ 'src/agent-clip-layers.js': [],+ 'src/agent-relations.js': [],+ 'src/agent-branches.js': [],+ 'src/agent-navigation.js': [],+ 'src/agent-crowd.js': [],+};+const THROW_PATTERN = /throw new (?:Range|Type)?Error\((.{0,40})/;++for (const [file, listed] of Object.entries(RAW_THROWS_LEFT)) {+ test(`${file} adds no raw throw that lacks a field path and an expectation`, () => {+ const lines = readFileSync(new URL(`../${file}`, import.meta.url), 'utf8').split(/\r?\n/);+ const found = lines.map(line => line.match(THROW_PATTERN)?.[1]).filter(Boolean);+ assert.deepEqual(found, listed, `${file}: report agent input mistakes with invalidField(path, value, expected) from src/field-error.js; list a throw here only when no input field can cause it`);+ });+}diff --git a/tests/agent-asset-ik.test.js b/tests/agent-asset-ik.test.jsindex 669c57e3..95d6e8c0 100644--- a/tests/agent-asset-ik.test.js+++ b/tests/agent-asset-ik.test.js@@ -164,7 +164,7 @@ test('a target can follow a node of the character, and aim takes worldForward',test('asset IK mistakes say what to pass', async () => {const asset = await loadRobot();const motion = ik => ({ duration: 1, tracks: [], ik });- assert.throws(() => assetScene(asset, motion([{ ...armSolver(asset), root: 'node-99999' }])), /root must be a node ID/);+ assert.throws(() => assetScene(asset, motion([{ ...armSolver(asset), root: 'node-99999' }])), /root: got "node-99999"; expected a node ID in this recipe/);const feet = { type: 'two-bone', root: nodeId(asset, 'UpperLegL'), middle: nodeId(asset, 'LowerLegL'), end: nodeId(asset, 'FootL'), target: [0, 0, 0] };assert.throws(() => assetScene(asset, motion([feet])), /end must descend from middle/);assert.throws(() => assetScene(asset, motion([armSolver(asset)]), { root: { scale: [1, 2, 1] } }), /uniform asset root scale/);diff --git a/tests/agent-asset-retarget.test.js b/tests/agent-asset-retarget.test.jsindex 61daf73d..de9b7fce 100644--- a/tests/agent-asset-retarget.test.js+++ b/tests/agent-asset-retarget.test.js@@ -66,9 +66,9 @@ test('a walk from one humanoid file plays on another with different names, propo});test('a layer from an unavailable clip, or between rigs without humanoid bones, says what is wrong', async () => {- await assert.rejects(createTarget({ duration: 1, layers: [{ from: { asset: 'ee'.repeat(32), clip: 0 } }] }), /not a catalog asset available/);- await assert.rejects(createTarget({ duration: 1, layers: [{ from: { asset: SOURCE_ID, clip: 5 } }] }), /from\.clip must be the index/);- await assert.rejects(createTarget({ duration: 1, layers: [{ from: { asset: SOURCE_ID, clip: 0 }, clip: 0 }] }), /takes from or clip/);+ await assert.rejects(createTarget({ duration: 1, layers: [{ from: { asset: 'ee'.repeat(32), clip: 0 } }] }), /from\.asset: got .*expected the ID of a catalog asset/);+ await assert.rejects(createTarget({ duration: 1, layers: [{ from: { asset: SOURCE_ID, clip: 5 } }] }), /from\.clip: got 5; expected the index of a clip in that asset, from 0 to 0/);+ await assert.rejects(createTarget({ duration: 1, layers: [{ from: { asset: SOURCE_ID, clip: 0 }, clip: 0 }] }), /from: got .*expected from or clip, not both/);const broken = await createTarget(undefined, { names: { ...UNREAL_LIKE, leftLowerArm: 'misc', leftHand: 'misc2' } });const revision = hierarchyOf(broken).revision;assert.throws(() => broken.scene.apply([{ type: 'set-motion', motion: motionOf() }], { expectedRevision: revision }), /not humanoid to the bone map. Missing bones: leftLowerArm/);@@ -121,6 +121,6 @@ test('keyed morph weights blink and open the jaw by target name, and seeking reptarget.scene.sampleMotion(0.6);assert.deepEqual(face(), atBlink, 'seeking back repeats the earlier weights');assert.deepEqual(hierarchyOf(target).morphTargetNames, FACE_TARGETS);- await assert.rejects(createTarget({ duration: 1, tracks: [{ kind: 'morph', id: 'cheekPuff', property: 'weight', keyframes: [{ time: 0, value: 1 }] }] }), /Morph targets of this asset: eyeBlinkLeft/);+ await assert.rejects(createTarget({ duration: 1, tracks: [{ kind: 'morph', id: 'cheekPuff', property: 'weight', keyframes: [{ time: 0, value: 1 }] }] }), /motion\.tracks\[0\]\.id: got "cheekPuff"; expected the ID of a morph in this recipe; morph targets of this asset: eyeBlinkLeft/);await assert.rejects(createTarget({ duration: 1, tracks: [{ kind: 'morph', id: 'jawOpen', property: 'weight', keyframes: [{ time: 0, value: 2 }] }] }), /morph weight from 0 to 1/);});diff --git a/tests/agent-branches.test.js b/tests/agent-branches.test.jsindex 997ff2dc..e54f648d 100644--- a/tests/agent-branches.test.js+++ b/tests/agent-branches.test.js@@ -38,9 +38,9 @@ test('branch reads return copies, so a caller cannot edit stored recipes', () =>test('the branch count is capped, a name can be reused at the cap, and unknown names fail clearly', () => {const store = createBranchStore();for (let index = 0; index < BRANCH_LIMITS.maximumBranches; index++) store.fork(`b${index}`, forkInput(`r${index}`));- assert.throws(() => store.fork('extra', forkInput('x')), /At most 8 branches/);+ assert.throws(() => store.fork('extra', forkInput('x')), /branch: got "extra"; expected a name that is already a branch/);store.fork('b0', forkInput('replacement'));- assert.throws(() => store.get('missing'), /Unknown branch: missing/);+ assert.throws(() => store.get('missing'), /branch: got "missing"; expected one of the known branches/);assert.throws(() => store.get('Bad Name'), TypeError);store.clear();assert.deepEqual(store.names(), []);diff --git a/tests/agent-motion-constraints.test.js b/tests/agent-motion-constraints.test.jsindex 044ec8c1..463901f8 100644--- a/tests/agent-motion-constraints.test.js+++ b/tests/agent-motion-constraints.test.js@@ -192,7 +192,7 @@ test('drivers and constraints reject anything that is not bounded data', () => {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/);+ assert.throws(() => createAgentScene(clash), /a track on .* already moves/);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/);diff --git a/tests/agent-motion-ik.test.js b/tests/agent-motion-ik.test.jsindex f3193525..9ab55751 100644--- a/tests/agent-motion-ik.test.js+++ b/tests/agent-motion-ik.test.js@@ -160,21 +160,21 @@ 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, 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/);- assert.throws(() => create([armIk('here')]), /target must be \[x, y, z\]/);+ assert.throws(() => create([{ type: 'fabrik', target: [0, 0, 0] }]), /motion\.ik\[0\]\.type: got "fabrik"; expected "two-bone" or "aim"/);+ assert.throws(() => create([armIk([0, 0, 0], { root: 'nope' })]), /motion\.ik\[0\]\.root: got "nope"; expected a node ID in this recipe/);+ assert.throws(() => create([armIk({ node: 'nope' })]), /motion\.ik\[0\]\.target\.node: got "nope"; expected a node ID/);+ assert.throws(() => create([armIk('here')]), /motion\.ik\[0\]\.target: got "here"; expected \[x, y, z\]/);assert.throws(() => create([armIk([0, 0, 0], { end: 'ball' })]), /end must descend from middle/);assert.throws(() => create([armIk([0, 0, 0], { weight: 3 })]), /weight: got 3; expected a number from/);- assert.throws(() => create([{ type: 'aim', target: [0, 0, 0] }]), /needs joint, or joints/);- assert.throws(() => create([armIk([0, 0, 0])], { elbow: { scale: [1, 2, 1] } }), /non-uniform scale.*child node/);+ assert.throws(() => create([{ type: 'aim', target: [0, 0, 0] }]), /joint: got undefined; expected joint, or joints/);+ assert.throws(() => create([armIk([0, 0, 0])], { elbow: { scale: [1, 2, 1] } }), /nodes\.elbow\.scale: got \[1,2,1\]; expected a uniform scale.*child node/);assert.doesNotThrow(() => create([armIk([0.4, 1.5, 0.3])], { tip: { scale: [0.1, 0.2, 0.3] } }));assert.doesNotThrow(() => create([{ type: 'aim', joint: 'lamp', target: [0, 0, 0] }], { lamp: { scale: [0.2, 0.2, 0.3] } }));assert.throws(() => createAgentScene(armRecipe({duration: 1,tracks: [{ kind: 'node', id: 'elbow', property: 'scale', keyframes: [{ time: 0, value: [1, 1, 1] }] }],ik: [armIk([0, 0, 0])],- })), /cannot have a scale track/);+ })), /no scale track on node/);assert.throws(() => create([{ type: 'aim', joint: 'lamp', target: [0, 0, 0], forward: [0, 0, 1], worldForward: [0, 0, 1] }]), /forward or worldForward, not both/);assert.deepEqual([...AGENT_SCENE_CAPABILITIES.motionIk], ['two-bone', 'aim']);});diff --git a/tests/agent-motion-look.test.js b/tests/agent-motion-look.test.jsindex a8b575cf..40c3c42d 100644--- a/tests/agent-motion-look.test.js+++ b/tests/agent-motion-look.test.js@@ -83,15 +83,15 @@ test('a scene with no look tracks reads the authored environment and effects', (test('unknown lights, properties and ill-fitting targets name the valid ones', () => {const failure = (track, pattern) => assert.throws(() => createAgentScene(sceneRecipe([track])), pattern);failure({ kind: 'light', id: 'point:3', property: 'color', keyframes: keys([1, 1, 1], [0, 0, 0]) }, /point:3.*point:0, spot:0, area:0/);- failure({ kind: 'light', id: 'point:0', property: 'direction', keyframes: keys([0, -1, 0], [0, 1, 0]) }, /point light has no direction|point:0 has no direction/);+ failure({ kind: 'light', id: 'point:0', property: 'direction', keyframes: keys([0, -1, 0], [0, 1, 0]) }, /motion\.tracks\.property: got "point:0\.direction"; expected a property the light has; only spot and area lights/);failure({ kind: 'light', id: 'point:0', property: 'radius', keyframes: keys(1, 2) }, /light properties: position, direction, color, intensity/);failure({ kind: 'sun', property: 'angle', keyframes: keys(1, 2) }, /sun properties: direction, color, intensity/);- failure({ kind: 'sun', id: 'x', property: 'intensity', keyframes: keys(1, 2) }, /Sun tracks cannot have an ID/);+ failure({ kind: 'sun', id: 'x', property: 'intensity', keyframes: keys(1, 2) }, /motion\.tracks\[0\]\.id: got "x"; expected a field left out, since sun tracks have no ID/);failure({ kind: 'environment', property: 'skyTop', keyframes: keys([0, 0, 0], [2, 0, 0]) }, /environment skyTop values from 0 to 1/);failure({ kind: 'sun', property: 'direction', keyframes: keys([0, 0, 0], [0, 1, 0]) }, /keyframes\[0\]\.value: got \[0,0,0\]; expected a direction that is not all zero/);failure({ kind: 'effects', property: 'exposure', keyframes: keys(1, 99) }, /effects exposure values from 0.01 to 16/);assert.throws(() => createAgentScene(sceneRecipe([{ kind: 'effects', property: 'focusDistance', keyframes: keys(1, 2) }],- { effects: {} })), /focusDistance needs effects.depthOfField.blur above 0/);+ { effects: {} })), /effects\.focusDistance"; expected a track only when effects\.depthOfField\.blur is above 0/);});test('a sunset changes the sun and sky between two frames of a render', async (context) => {diff --git a/tests/agent-motion.test.js b/tests/agent-motion.test.jsindex 1d455f4a..dd315b99 100644--- a/tests/agent-motion.test.js+++ b/tests/agent-motion.test.js@@ -113,10 +113,10 @@ test('camera-only motion compiles an empty ordinary clip and retains the statictest('strict schema, final references, duplicate tracks and allocation bounds reject invalid authoring', () => {assert.throws(() => normalizeAgentMotion(motion([]), recipe), /at least one/);assert.throws(() => normalizeAgentMotion({ ...motion([]), unknown: true }, recipe), /field/);- assert.throws(() => normalizeAgentMotion(motion([{ ...track('emission', 0, 1), id: 'missing' }]), recipe), /not found/);+ assert.throws(() => normalizeAgentMotion(motion([{ ...track('emission', 0, 1), id: 'missing' }]), recipe), /motion\.tracks\[0\]\.id: got "missing"; expected the ID of a material in this recipe/);assert.throws(() => normalizeAgentMotion(motion([track('emission', 0, 1), track('emission', 0, 1)]), recipe), /repeats an earlier track/);- assert.throws(() => normalizeAgentMotion(motion([{ kind: 'camera', id: 'camera', property: 'fov', keyframes: [{ time: 0, value: 45 }] }]), recipe), /cannot have/);- assert.throws(() => normalizeAgentMotion(motion([{ ...track('emission', 0, 1), keyframes: [{ time: 0, value: 0, outTangent: 1 }] }]), recipe), /Tangents/);+ assert.throws(() => normalizeAgentMotion(motion([{ kind: 'camera', id: 'camera', property: 'fov', keyframes: [{ time: 0, value: 45 }] }]), recipe), /motion\.tracks\[0\]\.id: got "camera"; expected a field left out, since camera tracks have no ID/);+ assert.throws(() => normalizeAgentMotion(motion([{ ...track('emission', 0, 1), keyframes: [{ time: 0, value: 0, outTangent: 1 }] }]), recipe), /keyframes\[0\]\.outTangent: got 1; expected a field left out unless the track interpolation is CUBICSPLINE/);assert.throws(() => normalizeAgentMotion(motion([{ ...track('emission', 0, 1), interpolation: 'CUBICSPLINE' }]), recipe), /tangent/i);assert.throws(() => normalizeAgentMotion(motion(Array(129)), recipe), /bounded/);const tooManyKeys = Array.from({ length: 65 }, (_, index) => ({ time: index / 64, value: 0 }));@@ -166,7 +166,7 @@ test('radiance overflow, camera midpose collisions and cubic lens overshoot presconst sampler = compileAgentMotion(input, recipe);const output = sampler.sample(0);const before = snapshot(output);- assert.throws(() => sampler.sample(0.5), /radiance|distinct|field of view/);+ assert.throws(() => sampler.sample(0.5), /materials\.[^.]+\.emission: got|distinct|field of view/);assert.deepEqual(snapshot(output), before);}});@@ -176,7 +176,7 @@ test('unlit radiance uses the authored base color when emissiveColor is absent',const sampler = compileAgentMotion(motion([track('emission', 0, 200000)]), unlitRecipe);const output = sampler.sample(0);const before = snapshot(output);- assert.throws(() => sampler.sample(0.5), /unlit radiance/);+ assert.throws(() => sampler.sample(0.5), /unlit emissiveColor times emission/);assert.deepEqual(snapshot(output), before);assert.equal(sampler.sample(0.25).materials.get('bulb').emission, 50000);});diff --git a/tests/agent-scene-crowd.test.js b/tests/agent-scene-crowd.test.jsindex 8f605e04..5def95dc 100644--- a/tests/agent-scene-crowd.test.js+++ b/tests/agent-scene-crowd.test.js@@ -97,9 +97,9 @@ test('far instances change pose only farRate times a second while near ones chantest('crowd settings are validated and the clip must exist', async () => {await assert.rejects(crowdScene({ count: 0 }), /count/);- await assert.rejects(crowdScene({ bogus: 1 }), /Unknown crowd field/);- await assert.rejects(crowdScene({ farDistance: 5 }), /go together/);- await assert.rejects(crowdScene({ clip: 99 }), /does not exist/);+ await assert.rejects(crowdScene({ bogus: 1 }), /crowd\.bogus: got 1; expected a known field/);+ await assert.rejects(crowdScene({ farDistance: 5 }), /crowd\.farRate: got undefined; expected both farDistance and farRate, or neither/);+ await assert.rejects(crowdScene({ clip: 99 }), /nodes\.people\.asset\.crowd\.clip: got 99; expected a clip index from 0 to 13/);});test('a crowd keeps its baked parts across an edit that does not touch it', async () => {diff --git a/tests/agent-scene-motion.test.js b/tests/agent-scene-motion.test.jsindex ff876e39..677a4277 100644--- a/tests/agent-scene-motion.test.js+++ b/tests/agent-scene-motion.test.js@@ -96,7 +96,7 @@ test('final batch reference validation prevents dangling tracks and permits atomscene.sampleMotion(1);const before = pose(scene);const canonical = scene.exportRecipe();- assert.throws(() => scene.apply([{ type: 'remove-node', id: 'hinge', recursive: true }], { expectedRevision: 0 }), /target/);+ assert.throws(() => scene.apply([{ type: 'remove-node', id: 'hinge', recursive: true }], { expectedRevision: 0 }), /motion\.tracks\[0\]\.id: got "hinge"/);assert.deepEqual(pose(scene), before);assert.deepEqual(scene.exportRecipe(), canonical);assert.throws(() => scene.apply([{ type: 'set-motion' }], { expectedRevision: 0 }), /requires motion/);diff --git a/tests/mesh-shape-keys.test.js b/tests/mesh-shape-keys.test.jsindex 2b193f18..269f8863 100644--- a/tests/mesh-shape-keys.test.js+++ b/tests/mesh-shape-keys.test.js@@ -95,7 +95,7 @@ test('shape keys that change the vertex count, repeat a name or sit on a missingassert.throws(() => createAgentScene(both), /exactly one of edits or offsets/);const unknownTrack = structuredClone(mesh);unknownTrack.motion.tracks[0].id = 'smile';- assert.throws(() => createAgentScene(unknownTrack), /Motion target was not found: smile/);+ assert.throws(() => createAgentScene(unknownTrack), /motion\.tracks\[0\]\.id: got "smile"; expected the ID of a morph/);});test('the starting value of a key is the weight without motion, and a GLB export writes the morph targets', () => {diff --git a/tests/navmesh.test.js b/tests/navmesh.test.jsindex 9b3c41be..fa6557e2 100644--- a/tests/navmesh.test.js+++ b/tests/navmesh.test.js@@ -82,5 +82,5 @@ test('scene_inspect path returns translation keyframes around the hole of a reci}assert.throws(() => scene.inspect({ path: { ground: 'ground', from: [0, 0], to: [15, 15] } }), /a hole/);assert.throws(() => scene.inspect({ path: { ground: 'nowhere', from: [0, 0], to: [15, 15] } }), /not a node/);- assert.throws(() => scene.inspect({ path: { ground: 'ground', from: [-15, -15], to: [15, 15], seconds: 2, speed: 1 } }), /seconds or speed/);+ assert.throws(() => scene.inspect({ path: { ground: 'ground', from: [-15, -15], to: [15, 15], seconds: 2, speed: 1 } }), /path\.speed: got 1; expected speed or seconds, not both/);});diff --git a/tests/part-relations.test.js b/tests/part-relations.test.jsindex 8d93b926..13f3475b 100644--- a/tests/part-relations.test.js+++ b/tests/part-relations.test.js@@ -97,7 +97,7 @@ test('a tagged region of the target is the reference, not the whole part', () =>{ id: 'tank', geometry: 'tank' },{ id: 'cap', relations: [{ kind: 'gap', to: 'tank', region: 'lid', side: '+y' }] },], [body]);- assert.throws(() => createAgentScene(bad), /cannot be satisfied.*Unknown tag lid.*Known tags: .*top/s);+ assert.throws(() => createAgentScene(bad), /nodes\[1\]\.relations\[0\]\.region: got "lid"; expected a target that can be measured \(Unknown tag lid.*Known tags: .*top/s);const plain = recipeWith([{ id: 'a' }, { id: 'b', relations: [{ kind: 'gap', to: 'a', region: 'top', side: '+y' }] }]);assert.throws(() => createAgentScene(plain), /plain shape.*tag faces with a mesh_edit tag op/s);});@@ -130,70 +130,70 @@ test('cycles, unknown parts and self references are rejected with the next actiorejects([{ id: 'a', relations: [{ kind: 'attach', to: 'b', side: '+x' }] },{ id: 'b', relations: [{ kind: 'attach', to: 'a', side: '+x' }] },- ], /cycle: "a" -> "b" -> "a".*Remove one relation/s);+ ], /nodes\[0\]\.relations: got \["a","b","a"\]; expected relations that form no loop.*remove one relation/s);rejects([{ id: 'a', relations: [{ kind: 'attach', to: 'ghost', side: '+x' }] },- ], /no node has that ID.*scene_inspect/s);+ ], /relations\[0\]\.to: got "ghost"; expected the ID of a node in this recipe; list them with scene_inspect/);rejects([{ id: 'a', relations: [{ kind: 'centered', to: 'a' }] },- ], /its own node.*another part/s);+ ], /relations\[0\]\.to: got "a"; expected the ID of another part, not its own node/);rejects([{ id: 'a', relations: [{ kind: 'attach', to: 'loop', side: '+x' }] },{ id: 'a2', relations: [{ kind: 'attach', to: 'a', side: '+x' }] },{ id: 'loop', parent: 'a2' },- ], /cycle/);+ ], /expected relations that form no loop/);});test('a part cannot be placed against its own child, which would move with it', () => {rejects([{ id: 'parent', relations: [{ kind: 'attach', to: 'kid', side: '+x' }] },{ id: 'kid', parent: 'parent' },- ], /cycle.*parents included/s);+ ], /relations: got \["parent","kid","parent"\]; expected relations that form no loop.*parents included/s);});test('group nodes, group targets and two relations on one axis are rejected', () => {const noGeometry = recipeWith([{ id: 'g' }, { id: 'a', relations: [{ kind: 'centered', to: 'g' }] }]);noGeometry.nodes[0] = { id: 'g' };- assert.throws(() => createAgentScene(noGeometry), /group with no geometry.*mesh node/s);+ assert.throws(() => createAgentScene(noGeometry), /relations\[0\]\.to: got "g"; expected the ID of a mesh node, since this one is a group with no geometry/);noGeometry.nodes[0] = { id: 'g', geometry: 'cube', material: 'grey' };noGeometry.nodes[1] = { id: 'a', relations: [{ kind: 'centered', to: 'g' }] };- assert.throws(() => createAgentScene(noGeometry), /group, and relations place mesh nodes/s);+ assert.throws(() => createAgentScene(noGeometry), /nodes\[1\]\.relations: got .*; expected relations on a mesh node, since this node is a group/);rejects([{ id: 'a' },{ id: 'b', relations: [{ kind: 'gap', to: 'a', side: '+x' }, { kind: 'align', to: 'a', axis: 'x', at: 'min' }] },- ], /decides the x axis.*already decides.*one relation per axis/is);+ ], /leaves the x axis to relation.*already decides.*one relation per axis/is);rejects([{ id: 'a' },{ id: 'b', relations: [{ kind: 'attach', to: 'a', side: '+x' }, { kind: 'centered', to: 'a', axes: ['y'] }] },- ], /decides the y axis/);+ ], /relations\[1\]\.kind: got "centered"; expected a relation that leaves the y axis to relation 0/);});test('hostile relation input is rejected without leaking or hanging', () => {const attach = { kind: 'attach', to: 'a', side: '+x' };const cases = [- [{ ...attach, kind: 'weld' }, /Use one of attach, flush, align, centered, gap/],- [{ ...attach, side: '+w' }, /needs side/],+ [{ ...attach, kind: 'weld' }, /relations\[0\]\.kind: got "weld"; expected one of attach, flush, align, centered, gap/],+ [{ ...attach, side: '+w' }, /relations\[0\]\.side: got "\+w"; expected one of \+x, -x/],[{ ...attach, offset: Infinity }, /Copy|finite|JSON/],[{ ...attach, offset: 1e12 }, /finite number of metres/],[{ ...attach, offset: '1' }, /finite number of metres/],- [{ ...attach, to: 7 }, /needs "to"/],- [{ ...attach, to: '' }, /needs "to"/],- [{ ...attach, region: 5 }, /region must be a mesh tag name/],- [{ ...attach, axis: 'x' }, /unknown field "axis".*takes: kind, to, region, side, offset/s],- [{ kind: 'align', to: 'a', axis: 'q', at: 'min' }, /needs axis/],- [{ kind: 'centered', to: 'a', axes: ['x', 'x'] }, /each of x, y, z at most once/],- [{ kind: 'centered', to: 'a', axes: [] }, /each of x, y, z at most once/],- [{ kind: 'centered', to: 'a', axes: 'x' }, /each of x, y, z at most once/],- [{ ...attach, to: 'x'.repeat(5000) }, /no node has that ID|maxRecipeBytes|IDs/],- [null, /must be an object/],- ['attach', /must be an object/],- [[attach], /must be an object/],+ [{ ...attach, to: 7 }, /relations\[0\]\.to: got 7; expected the ID of the part it is placed against/],+ [{ ...attach, to: '' }, /relations\[0\]\.to: got ""; expected the ID of the part it is placed against/],+ [{ ...attach, region: 5 }, /relations\[0\]\.region: got 5; expected a mesh tag name/],+ [{ ...attach, axis: 'x' }, /relations\[0\]\.axis: got "x"; expected a field a attach relation takes: kind, to, region, side, offset/],+ [{ kind: 'align', to: 'a', axis: 'q', at: 'min' }, /relations\[0\]\.axis: got "q"; expected x, y or z/],+ [{ kind: 'centered', to: 'a', axes: ['x', 'x'] }, /relations\[0\]\.axes: got .*; expected a list of x, y, z with each at most once/],+ [{ kind: 'centered', to: 'a', axes: [] }, /relations\[0\]\.axes: got .*; expected a list of x, y, z with each at most once/],+ [{ kind: 'centered', to: 'a', axes: 'x' }, /relations\[0\]\.axes: got .*; expected a list of x, y, z with each at most once/],+ [{ ...attach, to: 'x'.repeat(5000) }, /expected the ID of a node in this recipe|maxRecipeBytes|IDs/],+ [null, /relations\[0\]: got null; expected an object such as/],+ ['attach', /relations\[0\]: got "attach"; expected an object such as/],+ [[attach], /relations\[0\]: got \[\{.*; expected an object such as/],];for (const [relation, pattern] of cases) {rejects([{ id: 'a' }, { id: 'b', relations: [relation] }], pattern);}- rejects([{ id: 'a' }, { id: 'b', relations: 'attach' }], /array of at most 8/);- rejects([{ id: 'a' }, { id: 'b', relations: Array.from({ length: 9 }, () => attach) }], /at most 8/);+ rejects([{ id: 'a' }, { id: 'b', relations: 'attach' }], /relations: got "attach"; expected an array of at most 8/);+ rejects([{ id: 'a' }, { id: 'b', relations: Array.from({ length: 9 }, () => attach) }], /expected an array of at most 8 relations/);const polluted = JSON.parse('{"kind":"attach","to":"a","side":"+x","__proto__":{"kind":"gap"}}');rejects([{ id: 'a' }, { id: 'b', relations: [polluted] }], /Invalid JSON key/);});@@ -203,7 +203,7 @@ test('relation nodes are bounded', () => {for (let index = 0; index < 257; index++) {nodes.push({ id: `part${index}`, scale: [0.1, 0.1, 0.1], relations: [{ kind: 'attach', to: 'anchor', side: '+x' }] });}- rejects(nodes, /At most 256 nodes can carry relations/);+ rejects(nodes, /expected relations on at most 256 nodes; group repeated parts/);});test('a long chain of relations solves with work in proportion to its length', () => {@@ -229,6 +229,6 @@ test('a long chain of relations solves with work in proportion to its length', (test('relations on a rejected edit leave the scene unchanged', () => {const scene = createAgentScene(handleRecipe());const revision = scene.revision;- assert.throws(() => scene.apply([{ type: 'set-node', id: 'body', relations: [{ kind: 'attach', to: 'handle', side: '+x' }] }], { expectedRevision: revision }), /cycle/);+ assert.throws(() => scene.apply([{ type: 'set-node', id: 'body', relations: [{ kind: 'attach', to: 'handle', side: '+x' }] }], { expectedRevision: revision }), /expected relations that form no loop/);assert.equal(scene.revision, revision);});