3D engine that AI agents drive
Add retained scene hierarchy and pivot-aware reparenting
Nguyen Xuan Anae0823881edb
diff --git a/docs/scene-graph.md b/docs/scene-graph.mdnew file mode 100644index 00000000..92ade6f4--- /dev/null+++ b/docs/scene-graph.md@@ -0,0 +1,115 @@+# Scene graph++This API is available in the current source. It is not in the published 0.3.3 package.++`createSceneGraph(definitions, options)` builds named nodes with retained local and world matrices.+Each definition can refer to its parent by name, even when the parent appears later in the array.+Nodes without a parent form independent roots.++```js+const graph = createSceneGraph([+ { name: 'rig' },+ {+ name: 'arm',+ parent: 'rig',+ matrix: [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1],+ pivot: [0.5, 0, 0],+ geometry: armGeometry,+ material: armMaterial,+ },+]);++const mixer = createAnimationMixer(graph.animationTargets);+mixer.clipAction(armClip).play();+mixer.apply(1);+graph.update();+// graph.parts contains mesh nodes with published world matrices for Renderer67.+```++## Definitions and retained objects++| Field | Contract |+| --- | --- |+| `name` | A unique, nonempty string. |+| `parent` | An existing node name or `null`. Omitted parents produce roots. |+| `matrix` | Sixteen finite Float32 values in column-major order. Defaults to identity. |+| `pivot` | Three finite Float32 values in parent coordinates. Defaults to `[0, 0, 0]`. |+| `geometry`, `material` | Both objects for a mesh node, or both omitted for a group. |++Matrices and pivots accept plain arrays or typed arrays, and the graph copies them during creation.+Plain arrays make topology and transform definitions compatible with JSON round trips.+Geometry and material objects retain their original identities. Live textures and typed geometry buffers need their own asset serialization.++| Graph member | Purpose |+| --- | --- |+| `nodes` | Stable nodes in definition order, including groups. |+| `parts` | Stable flat mesh parts with `{ name, geometry, material, matrix }`. Their matrices contain world transforms. |+| `animationTargets` | Stable aliases for every node. Their matrices contain local transforms. |+| `getNode(name)` | Returns the named node or throws when it is missing. |+| `update()` | Propagates current local transforms, publishes world matrices and returns `parts`. |+| `reparent(name, parent, { keepWorld = false })` | Changes topology and publishes the resulting world matrices. `null` creates a root. |++Nodes expose `localMatrix`, `worldMatrix`, `pivot`, `geometry`, `material` and a read-only `parent` name.+The node lists, alias objects and matrix identities remain stable.+Local matrices and pivots remain mutable for animation and application edits.+World matrices contain graph output and must not serve as local inputs.++## Pivot and propagation rules++Each node uses `parentWorld * T(pivot) * localMatrix * T(-pivot)`.+This rotates and scales around the pivot in the parent's coordinates.+The local matrix translation adds to the transformed pivot position.+Children inherit the complete world matrix, including shear produced by rotated nonuniform scales.++The graph compiles a parent-before-child order independently of definition order.+`update()` evaluates the entire graph into retained staging buffers before publishing any world matrix.+It does not depend on previously published matrices, so repeated evaluations of the same locals produce the same output.+The update path allocates no arrays, maps, matrix objects or material copies.++## Animation and materials++Animation players and mixers bind `animationTargets` so they change local transforms.+Propagation follows animation sampling, and the renderer receives `parts`.+Material getters and setters share one slot between each node, its animation alias and its render part.+Animation material isolation therefore reaches the render part while preserving shared texture references.++Animation binding still requires local rotation with positive scale and no shear.+The graph itself accepts nonsingular affine shear and reflections.+World matrices can contain shear without violating the local animation contract.++## Reparenting++Without `keepWorld`, reparenting preserves the local matrix and allows the world pose to change.+With `keepWorld`, reparenting computes the current world pose from locals, including edits that were not yet published.+It compensates the new local matrix for the new parent's world transform and the node's pivot.+The node and its descendants preserve their world poses within Float32 precision.++Reparenting retains full matrices instead of decomposing them into translation, rotation and scale.+This permits compensation under rotated nonuniform scales, but the resulting local matrix can contain shear.+Existing animation bindings retain their captured base poses and authored local values.+Subsequent animation sampling can therefore overwrite the compensated pose. Reparenting does not retarget clips or recapture mixer base poses.++Topology changes allocate candidate parent links and traversal data.+They validate candidate matrices and depth before committing the parent name, local compensation or any world output.+Cycles, missing parents and invalid candidate transforms leave published graph state unchanged.++## Validation and limits++`maxNodes` defaults to `4096`, and `maxDepth` defaults to `256` with each root at depth one.+Both options must be positive safe integers. Traversal uses no recursion.+Duplicate names, missing parents, cycles and exceeded limits throw during creation or reparenting.++Local and composed world matrices must remain affine, nonsingular and finite in Float32 representation.+Invalid local edits, pivots, matrix overflow and singular results throw before any world matrix changes.+Caller edits to local buffers remain present after a failed update, so the caller must repair them before retrying.+This graph validation covers transforms and mesh object pairing. The renderer owns geometry, material and texture validation.++## API design choice++| Shape | Benefit | Cost |+| --- | --- | --- |+| Recursive mutable node objects | Expresses parent and child relationships directly. | Object references complicate JSON serialization and expose topology mutations. |+| Flat definitions with parent names | Supports JSON topology, forward references and centralized cycle checks. | Requires a compiled traversal order and explicit reparenting. |++Flat definitions fit the existing flat renderer parts and local animation bindings.+The graph does not add constraints, inverse kinematics, skinning, morph targets or clip retargeting.diff --git a/src/index.js b/src/index.jsindex 0c622bdf..cad5d473 100644--- a/src/index.js+++ b/src/index.js@@ -5,6 +5,7 @@ export { Renderer67 } from './renderer.js';export { box, cylinder, sphere, torus } from './geometry.js';export { exportGlb } from './export.js';export { createAnimationMixer } from './animation-mixer.js';+export { createSceneGraph } from './scene-graph.js';export { RENDER_PRESETS, planRenderSize, estimateFrameBytes } from './budget.js';export { assemblyOffset } from './assembly.js';diff --git a/src/scene-graph.js b/src/scene-graph.jsnew file mode 100644index 00000000..24c57f7a--- /dev/null+++ b/src/scene-graph.js@@ -0,0 +1,216 @@+import { mat4 } from 'gl-matrix';++const IDENTITY = Object.freeze([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]);+const ZERO_PIVOT = Object.freeze([0, 0, 0]);++function copiedFloats(value, size, label) {+ if ((!Array.isArray(value) && !ArrayBuffer.isView(value)) || value.length !== size) {+ throw new TypeError(`${label} needs ${size} finite Float32 values.`);+ }+ const result = new Float32Array(size);+ for (let index = 0; index < size; index++) {+ if (!Number.isFinite(value[index]) || !Number.isFinite(Math.fround(value[index]))) {+ throw new TypeError(`${label} needs ${size} finite Float32 values.`);+ }+ result[index] = value[index];+ }+ return result;+}++function validMatrix(matrix, name) {+ for (let index = 0; index < 16; index++) {+ if (!Number.isFinite(matrix[index]) || !Number.isFinite(Math.fround(matrix[index]))) {+ throw new RangeError(`Node ${name} matrix must contain finite Float32 values.`);+ }+ }+ if (matrix[3] !== 0 || matrix[7] !== 0 || matrix[11] !== 0 || matrix[15] !== 1) {+ throw new RangeError(`Node ${name} matrix must be affine.`);+ }+ const determinant = mat4.determinant(matrix);+ if (!Number.isFinite(determinant) || determinant === 0) throw new RangeError(`Node ${name} matrix must be nonsingular.`);+}++function limit(value, label) {+ if (!Number.isSafeInteger(value) || value <= 0) throw new RangeError(`${label} must be a positive safe integer.`);+ return value;+}++function compileOrder(parents, maxDepth) {+ const children = Array.from({ length: parents.length }, () => []);+ const order = [];+ const depths = new Uint32Array(parents.length);+ for (let index = 0; index < parents.length; index++) {+ if (parents[index] < 0) {+ order.push(index);+ depths[index] = 1;+ } else children[parents[index]].push(index);+ }+ for (let cursor = 0; cursor < order.length; cursor++) {+ const parentIndex = order[cursor];+ if (depths[parentIndex] > maxDepth) throw new RangeError('Scene graph exceeds maxDepth.');+ const descendants = children[parentIndex];+ for (let index = 0; index < descendants.length; index++) {+ const childIndex = descendants[index];+ depths[childIndex] = depths[parentIndex] + 1;+ order.push(childIndex);+ }+ }+ if (order.length !== parents.length) throw new RangeError('Scene graph parent references contain a cycle.');+ return order;+}++function materialAlias(node, matrix) {+ return Object.freeze({+ name: node.name,+ geometry: node.geometry,+ matrix,+ get material() {+ return node.material;+ },+ set material(value) {+ node.material = value;+ },+ });+}++/** Defines topology once and retains local, staged and published world matrices. */+export function createSceneGraph(definitions = [], { maxNodes = 4096, maxDepth = 256 } = {}) {+ limit(maxNodes, 'maxNodes');+ limit(maxDepth, 'maxDepth');+ if (!Array.isArray(definitions)) throw new TypeError('Scene graph definitions must be an array.');+ if (definitions.length > maxNodes) throw new RangeError('Scene graph exceeds maxNodes.');+ const namedIndices = new Map();+ const records = definitions.map((definition, index) => {+ if (!definition || typeof definition.name !== 'string' || !definition.name.trim()) throw new TypeError('Scene graph nodes need names.');+ if (namedIndices.has(definition.name)) throw new RangeError(`Duplicate scene graph node name: ${definition.name}`);+ namedIndices.set(definition.name, index);+ const parent = definition.parent ?? null;+ if (parent !== null && (typeof parent !== 'string' || !parent.trim())) throw new TypeError('Node parent must be a name or null.');+ const geometry = definition.geometry;+ const material = definition.material;+ if ((geometry != null) !== (material != null)) throw new TypeError('Mesh nodes need both geometry and material.');+ if (geometry != null && (typeof geometry !== 'object' || typeof material !== 'object')) throw new TypeError('Node geometry and material must be objects.');+ const localMatrix = copiedFloats(definition.matrix ?? IDENTITY, 16, `${definition.name} matrix`);+ validMatrix(localMatrix, definition.name);+ return {+ name: definition.name,+ parent,+ localMatrix,+ worldMatrix: mat4.create(),+ stagedWorld: mat4.create(),+ effectiveLocal: new Float64Array(16),+ pivot: copiedFloats(definition.pivot ?? ZERO_PIVOT, 3, `${definition.name} pivot`),+ geometry,+ material,+ };+ });+ let parents = new Int32Array(records.length);+ for (let index = 0; index < records.length; index++) {+ const parent = records[index].parent;+ if (parent !== null && !namedIndices.has(parent)) throw new RangeError(`Node ${records[index].name} parent was not found: ${parent}`);+ parents[index] = parent === null ? -1 : namedIndices.get(parent);+ }+ let order = compileOrder(parents, maxDepth);+ const parts = [];+ const animationTargets = [];+ const nodes = records.map(record => {+ if (record.geometry != null) parts.push(materialAlias(record, record.worldMatrix));+ animationTargets.push(materialAlias(record, record.localMatrix));+ return Object.freeze({+ name: record.name,+ localMatrix: record.localMatrix,+ worldMatrix: record.worldMatrix,+ pivot: record.pivot,+ geometry: record.geometry,+ get parent() {+ return record.parent;+ },+ get material() {+ return record.material;+ },+ set material(value) {+ record.material = value;+ },+ });+ });++ function evaluate(candidateOrder, candidateParents, overrideIndex = -1, overrideMatrix = null) {+ for (let cursor = 0; cursor < candidateOrder.length; cursor++) {+ const index = candidateOrder[cursor];+ const record = records[index];+ const local = index === overrideIndex ? overrideMatrix : record.localMatrix;+ validMatrix(local, record.name);+ const pivot = record.pivot;+ for (let axis = 0; axis < 3; axis++) {+ if (!Number.isFinite(pivot[axis])) throw new RangeError(`Node ${record.name} pivot must stay finite.`);+ }+ const effective = record.effectiveLocal;+ effective.set(local);+ // Conjugating the local transform rotates and scales about the parent-space pivot.+ for (let axis = 0; axis < 3; axis++) {+ effective[12 + axis] += pivot[axis] - local[axis] * pivot[0] - local[4 + axis] * pivot[1] - local[8 + axis] * pivot[2];+ }+ const parentIndex = candidateParents[index];+ if (parentIndex < 0) record.stagedWorld.set(effective);+ else mat4.multiply(record.stagedWorld, records[parentIndex].stagedWorld, effective);+ validMatrix(record.stagedWorld, record.name);+ }+ }++ function commitWorlds() {+ for (let index = 0; index < records.length; index++) records[index].worldMatrix.set(records[index].stagedWorld);+ }++ function nodeIndex(name) {+ if (!namedIndices.has(name)) throw new RangeError(`Scene graph node was not found: ${name}`);+ return namedIndices.get(name);+ }++ const graph = Object.freeze({+ nodes: Object.freeze(nodes),+ parts: Object.freeze(parts),+ animationTargets: Object.freeze(animationTargets),+ getNode(name) {+ return nodes[nodeIndex(name)];+ },+ update() {+ evaluate(order, parents);+ commitWorlds();+ return parts;+ },+ reparent(name, parent = null, { keepWorld = false } = {}) {+ if (typeof keepWorld !== 'boolean') throw new TypeError('keepWorld must be boolean.');+ const index = nodeIndex(name);+ const parentIndex = parent === null ? -1 : nodeIndex(parent);+ const candidateParents = new Int32Array(parents);+ candidateParents[index] = parentIndex;+ const candidateOrder = compileOrder(candidateParents, maxDepth);+ let candidateLocal = null;+ if (keepWorld) {+ // Fresh staged worlds include caller edits that have not yet been published.+ evaluate(order, parents);+ const desiredLocal = new Float64Array(records[index].stagedWorld);+ if (parentIndex >= 0) {+ const inverseParent = new Float64Array(16);+ if (!mat4.invert(inverseParent, records[parentIndex].stagedWorld)) throw new RangeError('New parent world matrix must be invertible.');+ mat4.multiply(desiredLocal, inverseParent, desiredLocal);+ }+ const pivot = records[index].pivot;+ for (let axis = 0; axis < 3; axis++) {+ desiredLocal[12 + axis] = desiredLocal[12 + axis] - pivot[axis] + desiredLocal[axis] * pivot[0] + desiredLocal[4 + axis] * pivot[1] + desiredLocal[8 + axis] * pivot[2];+ }+ candidateLocal = new Float32Array(desiredLocal);+ validMatrix(candidateLocal, name);+ }+ evaluate(candidateOrder, candidateParents, candidateLocal ? index : -1, candidateLocal);+ if (candidateLocal) records[index].localMatrix.set(candidateLocal);+ records[index].parent = parent;+ parents = candidateParents;+ order = candidateOrder;+ commitWorlds();+ return graph;+ },+ });+ graph.update();+ return graph;+}diff --git a/tests/scene-graph.test.js b/tests/scene-graph.test.jsnew file mode 100644index 00000000..0aea00f5--- /dev/null+++ b/tests/scene-graph.test.js@@ -0,0 +1,347 @@+import assert from 'node:assert/strict';+import test from 'node:test';+import { mat4, quat, vec3 } from 'gl-matrix';+import { Object3D } from 'three';+import { createSceneGraph } from '../src/scene-graph.js';+import { createAnimationClip, createAnimationPlayer } from '../src/animation.js';+import { createAnimationMixer } from '../src/animation-mixer.js';+import { box } from '../src/geometry.js';++function transform(translation = [0, 0, 0], angles = [0, 0, 0], scale = [1, 1, 1]) {+ return mat4.fromRotationTranslationScale(mat4.create(), quat.fromEuler(quat.create(), ...angles), translation, scale);+}++function closeMatrix(actual, expected, tolerance = 2e-5) {+ for (let index = 0; index < 16; index++) {+ assert.ok(Math.abs(actual[index] - expected[index]) < tolerance, `component ${index}: ${actual[index]} differs from ${expected[index]}`);+ }+}++function snapshot(graph) {+ return graph.nodes.map(node => ({ name: node.name, parent: node.parent, world: Array.from(node.worldMatrix) }));+}++function material() {+ return { color: [0.5, 0.6, 0.7], metallic: 0.2, roughness: 0.5, emission: 0, map: {} };+}++test('child-first definitions propagate nested rotations and nonuniform scales like Three Object3D', () => {+ const definitions = [+ { name: 'tip', parent: 'arm', matrix: transform([0, 2, 0], [15, 25, 30], [0.5, 1.5, 0.75]) },+ { name: 'arm', parent: 'body', matrix: transform([1, 0, 0], [0, 0, 60], [1, 2, 1]) },+ { name: 'body', matrix: transform([3, 4, 5], [0, 45, 0], [2, 3, 4]) },+ ];+ const graph = createSceneGraph(definitions);+ const reference = new Map();+ for (const definition of definitions) {+ const object = new Object3D();+ object.matrixAutoUpdate = false;+ object.matrix.fromArray(definition.matrix);+ reference.set(definition.name, object);+ }+ reference.get('body').add(reference.get('arm'));+ reference.get('arm').add(reference.get('tip'));+ reference.get('body').updateMatrixWorld(true);+ for (const node of graph.nodes) closeMatrix(node.worldMatrix, reference.get(node.name).matrixWorld.elements);+ const reordered = createSceneGraph([...definitions].reverse());+ for (const node of graph.nodes) closeMatrix(reordered.getNode(node.name).worldMatrix, node.worldMatrix);+});++test('pivot conjugation places the pivot correctly under parent translation, rotation and scale', () => {+ const graph = createSceneGraph([+ { name: 'parent', matrix: transform([2, 0, 0]) },+ { name: 'rotor', parent: 'parent', matrix: transform([5, 0, 0], [0, 0, 90]), pivot: [1, 0, 0] },+ ]);+ const rotor = graph.getNode('rotor');+ closeMatrix(rotor.worldMatrix, transform([8, -1, 0], [0, 0, 90]));+ const pivotPosition = vec3.transformMat4(new Float64Array(3), [1, 0, 0], rotor.worldMatrix);+ assert.ok(Math.abs(pivotPosition[0] - 8) < 1e-5);+ assert.ok(Math.abs(pivotPosition[1]) < 1e-5);+ graph.getNode('parent').localMatrix.set(transform([0, 0, 0], [0, 0, 90], [2, 3, 1]));+ graph.update();+ const transformedPivot = vec3.transformMat4(new Float64Array(3), [1, 0, 0], rotor.worldMatrix);+ assert.ok(Math.abs(transformedPivot[0]) < 1e-5);+ assert.ok(Math.abs(transformedPivot[1] - 12) < 1e-5);+});++test('roots, empty graphs and multiple render meshes keep a stable Renderer67 part shape', () => {+ const geometry = box(0, 1);+ const sharedMaterial = material();+ const graph = createSceneGraph([+ { name: 'first', matrix: transform([2, 0, 0]), geometry, material: sharedMaterial },+ { name: 'group' },+ { name: 'second', matrix: transform([0, 3, 0]), geometry, material: sharedMaterial },+ ]);+ const parts = graph.parts;+ const targets = graph.animationTargets;+ assert.equal(parts.length, 2);+ assert.equal(targets.length, 3);+ assert.deepEqual(parts.map(part => part.name), ['first', 'second']);+ for (const part of parts) {+ assert.equal(part.geometry, geometry);+ assert.equal(part.material, sharedMaterial);+ assert.equal(part.matrix, graph.getNode(part.name).worldMatrix);+ assert.ok(part.matrix instanceof Float32Array);+ assert.ok(part.matrix.every(Number.isFinite));+ assert.ok(part.geometry.positions instanceof Float32Array);+ }+ for (const target of targets) assert.equal(target.matrix, graph.getNode(target.name).localMatrix);+ assert.equal(graph.update(), parts);+ assert.equal(graph.parts, parts);+ assert.equal(graph.animationTargets, targets);+ const empty = createSceneGraph();+ assert.deepEqual(empty.nodes, []);+ assert.deepEqual(empty.update(), []);+});++test('definition matrices and pivots copy serializable inputs while geometry and material remain shared', () => {+ const definitions = [{ name: 'root', matrix: Array.from(transform([3, 0, 0])), pivot: [1, 0, 0] }];+ const restored = createSceneGraph(JSON.parse(JSON.stringify(definitions)));+ const graph = createSceneGraph(definitions);+ definitions[0].matrix[12] = 100;+ definitions[0].pivot[0] = 100;+ definitions[0].name = 'changed';+ graph.update();+ closeMatrix(graph.getNode('root').worldMatrix, restored.getNode('root').worldMatrix);+ assert.deepEqual(Array.from(graph.getNode('root').pivot), [1, 0, 0]);+ assert.throws(() => graph.getNode('changed'), /not found/);+});++test('nonsingular affine shear and reflected transforms remain valid graph transforms', () => {+ const shear = mat4.create();+ shear[4] = 0.5;+ const graph = createSceneGraph([+ { name: 'reflected', matrix: transform([0, 0, 0], [0, 0, 0], [-1, 2, 3]) },+ { name: 'sheared', parent: 'reflected', matrix: shear },+ ]);+ assert.ok(mat4.determinant(graph.getNode('sheared').worldMatrix) < 0);+ const clip = createAnimationClip({ duration: 1, tracks: [{ target: 'sheared', property: 'translation', keyframes: [{ time: 0, value: [0, 0, 0] }] }] });+ assert.throws(() => createAnimationPlayer(clip, graph.animationTargets), /shear/);+});++test('local mixer and parent animation propagate independently for arbitrary seek order', () => {+ const graph = createSceneGraph([+ { name: 'parent', matrix: transform([0, 0, 0], [0, 0, 0], [2, 3, 1]) },+ { name: 'child', parent: 'parent', matrix: transform([1, 0, 0]), pivot: [1, 0, 0], geometry: box(0, 1), material: material() },+ ]);+ const parentClip = createAnimationClip({ duration: 2, tracks: [{ target: 'parent', property: 'translation', keyframes: [+ { time: 0, value: [0, 0, 0] }, { time: 2, value: [4, 0, 0] },+ ] }] });+ const childClip = createAnimationClip({ duration: 2, tracks: [{ target: 'child', property: 'rotation', keyframes: [+ { time: 0, value: [0, 0, 0, 1] }, { time: 2, value: Array.from(quat.fromEuler(quat.create(), 0, 0, 90)) },+ ] }] });+ const parentPlayer = createAnimationPlayer(parentClip, graph.animationTargets);+ const mixer = createAnimationMixer(graph.animationTargets);+ mixer.clipAction(childClip).play();+ parentPlayer.apply(1);+ mixer.apply(1);+ graph.update();+ const expected = snapshot(graph);+ const node = graph.getNode('child');+ const world = node.worldMatrix;+ const local = node.localMatrix;+ const pivotPosition = vec3.transformMat4(new Float64Array(3), [1, 0, 0], world);+ assert.ok(Math.abs(pivotPosition[0] - 6) < 1e-5);+ assert.ok(Math.abs(pivotPosition[1]) < 1e-5);+ for (const time of [2, 0, 1.75, 0.25, 1]) {+ mixer.apply(time);+ parentPlayer.apply(time);+ graph.update();+ }+ assert.deepEqual(snapshot(graph), expected);+ assert.equal(node.worldMatrix, world);+ assert.equal(node.localMatrix, local);+});++test('animation target material assignment forwards retained isolation to render parts and preserves map identity', () => {+ const shared = Object.freeze(material());+ const graph = createSceneGraph([+ { name: 'first', geometry: box(0, 1), material: shared },+ { name: 'second', geometry: box(0, 1), material: shared },+ ]);+ const clip = createAnimationClip({ duration: 2, tracks: [{ target: 'first', property: 'emission', keyframes: [+ { time: 0, value: 0 }, { time: 2, value: 2 },+ ] }] });+ const player = createAnimationPlayer(clip, graph.animationTargets);+ const renderPart = graph.parts[0];+ const isolated = renderPart.material;+ assert.notEqual(isolated, shared);+ assert.equal(isolated.map, shared.map);+ assert.equal(graph.animationTargets[0].material, isolated);+ assert.equal(graph.getNode('first').material, isolated);+ const mixer = createAnimationMixer(graph.animationTargets);+ mixer.clipAction(clip).play();+ assert.equal(renderPart.material, isolated);+ player.apply(1);+ assert.equal(renderPart.material.emission, 1);+ mixer.apply(2);+ assert.equal(renderPart.material.emission, 2);+ assert.equal(renderPart.material, isolated);+ assert.equal(graph.parts[1].material, shared);+ assert.equal(shared.emission, 0);+ const replacement = { ...isolated, emission: 3 };+ graph.animationTargets[0].material = replacement;+ assert.equal(renderPart.material, replacement);+});++test('all published world matrices remain unchanged when any local, pivot or composed world is invalid', () => {+ const graph = createSceneGraph([{ name: 'root' }, { name: 'child', parent: 'root', matrix: transform([1, 0, 0]) }]);+ const expected = snapshot(graph);+ const root = graph.getNode('root');+ const child = graph.getNode('child');+ root.localMatrix[12] = 5;+ for (const corrupt of [+ () => { child.localMatrix[0] = NaN; },+ () => { child.localMatrix[3] = 1; },+ () => { child.localMatrix[0] = 0; },+ () => { child.pivot[0] = Infinity; },+ ]) {+ child.localMatrix.set(transform([1, 0, 0]));+ child.pivot[0] = 0;+ corrupt();+ assert.throws(() => graph.update(), RangeError);+ assert.deepEqual(snapshot(graph), expected);+ }+ child.pivot[0] = 0;+ root.localMatrix.set(transform([0, 0, 0], [0, 0, 0], [1e30, 1, 1]));+ child.localMatrix.set(transform([0, 0, 0], [0, 0, 0], [1e30, 1, 1]));+ assert.throws(() => graph.update(), /finite Float32/);+ assert.deepEqual(snapshot(graph), expected);+ root.localMatrix.set(transform([0, 0, 0], [0, 0, 0], [1e-30, 1, 1]));+ child.localMatrix.set(transform([0, 0, 0], [0, 0, 0], [1e-30, 1, 1]));+ assert.throws(() => graph.update(), /nonsingular/);+ assert.deepEqual(snapshot(graph), expected);+ root.localMatrix.set(transform([5, 0, 0]));+ child.localMatrix.set(transform([1, 0, 0]));+ graph.update();+ assert.equal(child.worldMatrix[12], 6);+});++test('keepWorld reparent preserves pivoted subtrees under rotated nonuniform scales without changing identities', () => {+ const graph = createSceneGraph([+ { name: 'first', matrix: transform([2, 3, 4], [0, 35, 15], [2, 3, 4]) },+ { name: 'second', matrix: transform([-3, 1, 2], [20, -25, 10], [1, 2, 3]) },+ { name: 'child', parent: 'first', matrix: transform([1, 2, 0], [30, 45, 0]), pivot: [0.5, 1, 0], geometry: box(0, 1), material: material() },+ { name: 'tip', parent: 'child', matrix: transform([0, 2, 1]) },+ ]);+ const child = graph.getNode('child');+ const localIdentity = child.localMatrix;+ const worldIdentity = child.worldMatrix;+ const partsIdentity = graph.parts;+ const childWorld = Array.from(child.worldMatrix);+ const tipWorld = Array.from(graph.getNode('tip').worldMatrix);+ assert.equal(graph.reparent('child', 'second', { keepWorld: true }), graph);+ assert.equal(child.parent, 'second');+ assert.equal(child.localMatrix, localIdentity);+ assert.equal(child.worldMatrix, worldIdentity);+ assert.equal(graph.parts, partsIdentity);+ closeMatrix(child.worldMatrix, childWorld);+ closeMatrix(graph.getNode('tip').worldMatrix, tipWorld);+ graph.reparent('child', null, { keepWorld: true });+ assert.equal(child.parent, null);+ closeMatrix(child.worldMatrix, childWorld);+ closeMatrix(graph.getNode('tip').worldMatrix, tipWorld);+});++test('reparent without keepWorld preserves local pose and keepWorld includes unpublished local edits', () => {+ const graph = createSceneGraph([+ { name: 'first', matrix: transform([2, 0, 0]) },+ { name: 'second', matrix: transform([10, 0, 0]) },+ { name: 'child', parent: 'first', matrix: transform([1, 0, 0]) },+ ]);+ const child = graph.getNode('child');+ const initialLocal = Array.from(child.localMatrix);+ graph.reparent('child', 'second');+ assert.deepEqual(Array.from(child.localMatrix), initialLocal);+ assert.equal(child.worldMatrix[12], 11);+ graph.getNode('second').localMatrix[12] = 20;+ graph.reparent('child', 'first', { keepWorld: true });+ assert.equal(child.worldMatrix[12], 21);+ assert.equal(child.localMatrix[12], 19);+ assert.equal(graph.getNode('second').worldMatrix[12], 20);+});++test('reparent rejects cycles, excessive depth and invalid candidate worlds atomically', () => {+ const graph = createSceneGraph([{ name: 'root' }, { name: 'child', parent: 'root' }, { name: 'other' }], { maxDepth: 2 });+ const expected = snapshot(graph);+ const local = Array.from(graph.getNode('root').localMatrix);+ assert.throws(() => graph.reparent('root', 'child'), /cycle/);+ assert.throws(() => graph.reparent('root', 'root'), /cycle/);+ assert.throws(() => graph.reparent('other', 'child'), /maxDepth/);+ assert.throws(() => graph.reparent('child', 'missing'), /not found/);+ assert.throws(() => graph.reparent('missing', 'root'), /not found/);+ assert.throws(() => graph.reparent('child', 'other', { keepWorld: 1 }), TypeError);+ assert.deepEqual(snapshot(graph), expected);+ assert.deepEqual(Array.from(graph.getNode('root').localMatrix), local);++ const extreme = createSceneGraph([+ { name: 'large', matrix: transform([0, 0, 0], [0, 0, 0], [1e30, 1, 1]) },+ { name: 'small', matrix: transform([0, 0, 0], [0, 0, 0], [1e-30, 1, 1]) },+ { name: 'child', matrix: transform([0, 0, 0], [0, 0, 0], [1e30, 1, 1]) },+ ]);+ const previous = snapshot(extreme);+ const previousLocal = Array.from(extreme.getNode('child').localMatrix);+ assert.throws(() => extreme.reparent('child', 'large'), /finite Float32/);+ assert.throws(() => extreme.reparent('child', 'small', { keepWorld: true }), /finite Float32/);+ assert.deepEqual(snapshot(extreme), previous);+ assert.deepEqual(Array.from(extreme.getNode('child').localMatrix), previousLocal);+});++test('hierarchy guards bound node count and depth without recursive traversal', () => {+ assert.throws(() => createSceneGraph([{ name: 'first' }, { name: 'first' }]), /Duplicate/);+ assert.throws(() => createSceneGraph([{ name: 'child', parent: 'missing' }]), /not found/);+ assert.throws(() => createSceneGraph([{ name: 'first', parent: 'second' }, { name: 'second', parent: 'first' }]), /cycle/);+ assert.throws(() => createSceneGraph([{ name: 'self', parent: 'self' }]), /cycle/);+ assert.throws(() => createSceneGraph([{ name: 'root' }, { name: 'child', parent: 'root' }], { maxDepth: 1 }), /maxDepth/);+ assert.throws(() => createSceneGraph([{ name: 'first' }, { name: 'second' }], { maxNodes: 1 }), /maxNodes/);+ for (const limit of [0, -1, 1.5, Infinity, NaN]) {+ assert.throws(() => createSceneGraph([], { maxNodes: limit }), RangeError);+ assert.throws(() => createSceneGraph([], { maxDepth: limit }), RangeError);+ }+ const chain = Array.from({ length: 300 }, (_, index) => ({ name: `node-${index}`, parent: index ? `node-${index - 1}` : null }));+ assert.throws(() => createSceneGraph(chain), /maxDepth/);+ assert.equal(createSceneGraph(chain, { maxDepth: 300 }).nodes.length, 300);+});++test('malformed matrices, pivots and mesh definitions fail before graph publication', () => {+ assert.throws(() => createSceneGraph({}), TypeError);+ assert.throws(() => createSceneGraph([{ name: '' }]), TypeError);+ assert.throws(() => createSceneGraph([{ name: 'node', parent: 1 }]), TypeError);+ assert.throws(() => createSceneGraph([{ name: 'node', matrix: [1] }]), TypeError);+ const nonfinite = Array.from(mat4.create());+ nonfinite[0] = 1e100;+ assert.throws(() => createSceneGraph([{ name: 'node', matrix: nonfinite }]), TypeError);+ assert.throws(() => createSceneGraph([{ name: 'node', matrix: transform([0, 0, 0], [0, 0, 0], [0, 1, 1]) }]), /nonsingular/);+ const projective = mat4.create();+ projective[3] = 0.5;+ assert.throws(() => createSceneGraph([{ name: 'node', matrix: projective }]), /affine/);+ assert.throws(() => createSceneGraph([{ name: 'node', pivot: [Infinity, 0, 0] }]), TypeError);+ assert.throws(() => createSceneGraph([{ name: 'node', geometry: {} }]), TypeError);+ assert.throws(() => createSceneGraph([{ name: 'node', material: {} }]), TypeError);+});++test('update reuses parent matrices and effective-local buffers across repeated evaluation', () => {+ const graph = createSceneGraph([{ name: 'parent' }, { name: 'child', parent: 'parent', matrix: transform([1, 0, 0]) }]);+ const originalMultiply = mat4.multiply;+ let retained;+ let calls = 0;+ mat4.multiply = (output, parent, local) => {+ if (!retained) retained = [output, parent, local];+ else {+ assert.equal(output, retained[0]);+ assert.equal(parent, retained[1]);+ assert.equal(local, retained[2]);+ }+ calls++;+ return originalMultiply(output, parent, local);+ };+ try {+ for (let frame = 0; frame < 200; frame++) {+ graph.getNode('parent').localMatrix[12] = frame * 17 % 20;+ graph.update();+ }+ } finally {+ mat4.multiply = originalMultiply;+ }+ assert.equal(calls, 200);+});