The native runtime for three.js: three.js, down to the metal. 45× smaller than Electron, on a Sony PS3, and path-traced at 60 fps on ray-tracing GPUs.
Rust electron-alternativegame-engineglobal-illuminationgraphicsjavascript-runtimemetalpath-tracingray-tracingreal-time-renderingrenderingrustthreejstypescriptvoxelvulkanwebgpuwgpu
Scene: Object3D.matrixWorldAutoUpdate, with authored world matrices rendered as three.js does (supersedes #103)
Evan (Yifeng) Wang22ed39dfc0d0
diff --git a/packages/scene/src/core.ts b/packages/scene/src/core.tsindex 1b8c4a2..9604515 100644--- a/packages/scene/src/core.ts+++ b/packages/scene/src/core.ts@@ -405,8 +405,9 @@ export class Object3D {}/*** The local transform as a matrix (three.js): `updateMatrix()` composes it from position / quaternion / scale, which- * `updateWorldMatrix` does first while `matrixAutoUpdate` is on. The engine is always sent position / rotation /- * scale, so a matrix set by hand moves only what reads it (`matrixWorld`, `setMatrixAt(i, o.matrix)`).+ * `updateWorldMatrix` does first while `matrixAutoUpdate` is on. Normally the engine is sent local position /+ * rotation / scale. With `matrixWorldAutoUpdate = false`, the binding instead derives a local transform from the+ * authored world matrix for the renderer. Editing `matrix` alone still affects only readers of that matrix.*/get matrix(): Matrix4 {return (this._matrix ??= new Matrix4());@@ -418,6 +419,18 @@ export class Object3D {return (this._matrixWorld ??= new Matrix4());}declare private _matrixWorld: Matrix4 | undefined;+ /** Set (only) while `matrixWorldAutoUpdate` is false: an object that leaves it on carries no field for it. */+ declare private _matrixWorldManual: true | undefined;+ /** Set false to retain and render a manually supplied matrixWorld, as in three.js. */+ get matrixWorldAutoUpdate(): boolean {+ return !this._matrixWorldManual;+ }+ set matrixWorldAutoUpdate(value: boolean) {+ if (value === this.matrixWorldAutoUpdate) return;+ if (value) delete this._matrixWorldManual;+ else this._matrixWorldManual = true;+ touched(this);+ }/*** The stable id set by scene code (picking, gameplay events, the editor; the binding names the object by it); until@@ -652,8 +665,10 @@ export class Object3D {updateWorldMatrix(updateParents: boolean, updateChildren: boolean): void {if (updateParents && this.parent) this.parent.updateWorldMatrix(true, false);if (this.matrixAutoUpdate) this.updateMatrix();- if (this.parent) this.matrixWorld.multiplyMatrices(this.parent.matrixWorld, this.matrix);- else this.matrixWorld.copy(this.matrix);+ if (this.matrixWorldAutoUpdate) {+ if (this.parent) this.matrixWorld.multiplyMatrices(this.parent.matrixWorld, this.matrix);+ else this.matrixWorld.copy(this.matrix);+ }if (updateChildren) for (const c of this.children) c.updateWorldMatrix(false, true);}diff --git a/packages/scene/src/engine.ts b/packages/scene/src/engine.tsindex bd4fa58..e434b0f 100644--- a/packages/scene/src/engine.ts+++ b/packages/scene/src/engine.ts@@ -361,6 +361,8 @@ export class SceneBinding {private readonly trs = new Float32Array(10);private readonly scratch = new Float64Array(Math.max(HOT, LIGHT_VALUES));private readonly changes: SceneChanges = { objects: new Set(), structure: true, added: new Set(), removed: new Set() };+ /** In-place Matrix4 edits have no setter to report a change. Revisit only opted-in objects each sync. */+ private readonly manualWorld = new Set<Object3D>();private readonly untrack: () => void;private epoch = 0;// Physics: ids of bodies (a body's collider has its id) and joints, the slots of the engine's pose table, the joints@@ -394,6 +396,7 @@ export class SceneBinding {/** Stops tracking the scene's changes (the binding is not used any more). */dispose(): void {this.untrack();+ this.manualWorld.clear();}/** The object the engine knows under `name` (picking reports names). */@@ -418,6 +421,7 @@ export class SceneBinding {sync(): SyncStats {const stats: SyncStats = { created: 0, updated: 0, removed: 0 };const ch = this.changes;+ for (const o of this.manualWorld) ch.objects.add(o);if (ch.structure || !this.objects.has(this.camera)) {// The whole graph: walk it (creates new objects, re-parents, removes what is gone).ch.structure = false;@@ -574,6 +578,7 @@ export class SceneBinding {if (o instanceof Joint) this.dropJoint(o);this.engine.remove(b.id);this.objects.delete(o);+ this.manualWorld.delete(o);this.byName.delete(b.name);const cut = b.name.lastIndexOf("_"), n = Number(b.name.slice(cut + 1));if (cut > 0 && Number.isInteger(n) && n >= 1 && n < (this.nameFloor.get(b.name.slice(0, cut)) ?? 1)) this.nameFloor.set(b.name.slice(0, cut), n);@@ -615,6 +620,8 @@ export class SceneBinding {// A new scale changes the size of the bodies below it too (their colliders and joint anchors are made at the// object's scale in the world): those under it are made anew at the new size, once the sync has sent every// transform.+ if (o.matrixWorldAutoUpdate) this.manualWorld.delete(o);+ else this.manualWorld.add(o);if (this.sendTransform(o, b, stats)) this.rescaleBodiesBelow(o);if (o.visible !== b.visible) {b.visible = o.visible;@@ -717,11 +724,34 @@ export class SceneBinding {/** Sends the object's transform if it changed. True if its scale did (and it had been sent before). */private sendTransform(o: Object3D, b: Bound, stats: SyncStats): boolean {- const q = resolveOrientation(o);const t = this.trs;- t[0] = o.position.x; t[1] = o.position.y; t[2] = o.position.z;- t[3] = q.x; t[4] = q.y; t[5] = q.z; t[6] = q.w;- t[7] = o.scale.x; t[8] = o.scale.y; t[9] = o.scale.z;+ if (o.matrixWorldAutoUpdate) {+ const q = resolveOrientation(o);+ t[0] = o.position.x; t[1] = o.position.y; t[2] = o.position.z;+ t[3] = q.x; t[4] = q.y; t[5] = q.z; t[6] = q.w;+ t[7] = o.scale.x; t[8] = o.scale.y; t[9] = o.scale.z;+ } else {+ // The renderer's object tree stores local TRS, while matrixWorld is authored in world space.+ // Its parent is the engine parent, not necessarily Object3D.parent (the scene root is not bound).+ const local = o.matrixWorld.clone();+ if (b.parent !== null && o.parent) {+ o.parent.updateWorldMatrix(true, false);+ local.premultiply(o.parent.matrixWorld.clone().invert());+ }+ const p = new Vector3(), q = new Quaternion(), s = new Vector3();+ local.decompose(p, q, s);+ // A sheared or singular matrix cannot be represented by the renderer's TRS API.+ // Fail explicitly rather than silently draw it somewhere different from matrixWorld.+ const recomposed = new Matrix4().compose(p, q, s).elements;+ for (let i = 0; i < 16; i++) {+ const expected = local.elements[i], actual = recomposed[i];+ if (!Number.isFinite(expected) || !Number.isFinite(actual) || Math.abs(expected - actual) > 1e-6 * Math.max(1, Math.abs(expected)))+ throw new TypeError(`${b.name}: matrixWorld must be a finite, decomposable TRS matrix to render`);+ }+ t[0] = p.x; t[1] = p.y; t[2] = p.z;+ t[3] = q.x; t[4] = q.y; t[5] = q.z; t[6] = q.w;+ t[7] = s.x; t[8] = s.y; t[9] = s.z;+ }let moved = false, posed = false, scaled = false;for (let k = 0; k < 10; k++) {if (b.trs[k] !== t[k]) {diff --git a/packages/scene/test/engine.test.ts b/packages/scene/test/engine.test.tsindex 8f01e31..4c3c8be 100644--- a/packages/scene/test/engine.test.ts+++ b/packages/scene/test/engine.test.ts@@ -79,6 +79,85 @@ test("later syncs send only what changed", () => {assert.equal(((engine.take()[0][2]) as MaterialDesc).alphaTest, 0.4);});+test("manual matrixWorld is sent to the renderer, including in-place edits and parent changes", () => {+ const scene = new Scene();+ const carrier = new Group();+ carrier.id = "carrier";+ carrier.position.x = 5;+ const manual = new Mesh(new BoxGeometry(1, 1, 1));+ manual.id = "manual";+ manual.position.set(1, 2, 3);+ manual.matrixWorldAutoUpdate = false;+ manual.matrixWorld.makeTranslation(10, 20, 30);+ const child = new Mesh(new BoxGeometry(1, 1, 1));+ child.id = "child";+ child.position.x = 2;+ manual.add(child);+ carrier.add(manual);+ scene.add(carrier);+ const camera = new PerspectiveCamera();+ scene.add(camera);+ const { engine, b, calls } = bind(scene, camera);+ const ids = new Map(ofType(calls, "object").map((c) => [(c[2] as ObjectDesc).name, c[1] as number]));+ const placements = (batch: [string, ...unknown[]][]) =>+ new Map(ofType(batch, "transform").map((c) => [c[1] as number, c[2] as number[]]));+ assert.deepEqual(placements(calls).get(ids.get("carrier")!)?.slice(0, 3), [5, 0, 0]);+ assert.deepEqual(placements(calls).get(ids.get("manual")!)?.slice(0, 3), [5, 20, 30], "10 world x - 5 parent x");+ assert.deepEqual(placements(calls).get(ids.get("child")!)?.slice(0, 3), [2, 0, 0]);+ assert.deepEqual(child.getWorldPosition(new Vector3()).toArray(), [12, 20, 30]);+ b.sync();+ assert.deepEqual(engine.take(), [], "unchanged manual matrices cause no redundant renderer calls");++ manual.matrixWorld.setPosition(20, 20, 30); // Matrix4 writes do not notify change tracking.+ b.sync();+ const edited = engine.take();+ assert.equal(ofType(edited, "transform").length, 1);+ assert.deepEqual(placements(edited).get(ids.get("manual")!)?.slice(0, 3), [15, 20, 30]);++ carrier.position.x = 7;+ b.sync();+ const moved = engine.take();+ assert.equal(ofType(moved, "transform").length, 2, "manual object re-bases when its parent moves");+ assert.deepEqual(placements(moved).get(ids.get("carrier")!)?.slice(0, 3), [7, 0, 0]);+ assert.deepEqual(placements(moved).get(ids.get("manual")!)?.slice(0, 3), [13, 20, 30]);++ manual.matrixWorldAutoUpdate = true;+ b.sync();+ const automatic = engine.take();+ assert.equal(ofType(automatic, "transform").length, 1);+ assert.deepEqual(placements(automatic).get(ids.get("manual")!)?.slice(0, 3), [1, 2, 3],+ "turning automatic updates back on sends local components again");+ b.sync();+ assert.deepEqual(engine.take(), []);+});++test("manual matrixWorld TRS uses parent scale and rejects unrenderable shear", () => {+ const scene = new Scene();+ const carrier = new Group();+ carrier.position.x = 4;+ carrier.scale.set(2, 2, 2);+ const manual = new Mesh(new BoxGeometry(1, 1, 1));+ manual.matrixWorldAutoUpdate = false;+ manual.matrixWorld.compose(new Vector3(10, 0, 0), new Quaternion(), new Vector3(4, 4, 4));+ const child = new Mesh(new BoxGeometry(1, 1, 1));+ child.position.x = 1;+ manual.add(child);+ carrier.add(manual);+ scene.add(carrier);+ const camera = new PerspectiveCamera();+ scene.add(camera);+ const { b, calls } = bind(scene, camera);+ const name = b.nameOf(manual);+ const id = ofType(calls, "object").find((c) => (c[2] as ObjectDesc).name === name)![1];+ const local = ofType(calls, "transform").find((c) => c[1] === id)![2] as number[];+ assert.deepEqual(local.slice(0, 3), [3, 0, 0], "(10 world - 4 parent) / 2 parent scale");+ assert.deepEqual(local.slice(7, 10), [2, 2, 2], "4 world scale / 2 parent scale");+ assert.deepEqual(child.getWorldPosition(new Vector3()).toArray(), [14, 0, 0], "10 + (4 x 1)");++ manual.matrixWorld.set(1, 1, 0, 10, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1);+ assert.throws(() => b.sync(), /matrixWorld must be a finite, decomposable TRS matrix/);+});+test("dynamicGeometry meshes: the flag reaches the engine; a new geometry re-creates the object with it", () => {const scene = new Scene();const mat = new MeshStandardMaterial();diff --git a/packages/scene/test/three-compat.test.ts b/packages/scene/test/three-compat.test.tsindex 1232760..714fd44 100644--- a/packages/scene/test/three-compat.test.ts+++ b/packages/scene/test/three-compat.test.ts@@ -220,6 +220,31 @@ test("Object3D.attach preserves world position with matrixAutoUpdate disabled, aassert.equal(child.matrix.elements[12], 10, "explicit matrix must use the new local translation");});+test("Object3D.matrixWorldAutoUpdate: manual world matrices survive updates and world helpers", () => {+ const parent = new THREE.Group();+ const child = new THREE.Object3D();+ parent.position.set(1, 2, 3);+ child.position.set(2, 0, 0);+ parent.add(child);+ parent.matrixWorldAutoUpdate = false;+ parent.matrixWorld.makeTranslation(10, 20, 30);++ parent.updateWorldMatrix(true, true);+ assert.deepEqual(parent.getWorldPosition(new THREE.Vector3()).toArray(), [10, 20, 30], "preserves the authored parent matrix");+ assert.deepEqual(child.getWorldPosition(new THREE.Vector3()).toArray(), [12, 20, 30], "children inherit the authored parent matrix");+ assert.deepEqual(child.localToWorld(new THREE.Vector3(0, 0, 1)).toArray(), [12, 20, 31]);+ assert.deepEqual(child.worldToLocal(new THREE.Vector3(12, 20, 31)).toArray(), [0, 0, 1]);++ const copy = parent.clone(false);+ assert.equal(copy.matrixWorldAutoUpdate, false, "clones retain the manual-world setting");+ assert.deepEqual(copy.getWorldPosition(new THREE.Vector3()).toArray(), [10, 20, 30]);++ parent.matrixWorldAutoUpdate = true;+ parent.updateWorldMatrix(true, true);+ assert.deepEqual(parent.getWorldPosition(new THREE.Vector3()).toArray(), [1, 2, 3], "automatic world updates resume");+ assert.deepEqual(child.getWorldPosition(new THREE.Vector3()).toArray(), [3, 2, 3]);+});+test("Raycaster: the nearest hit first, front faces of single-sided materials, instanceId, near / far", () => {const scene = new THREE.Scene();const near = new THREE.Mesh(new THREE.PlaneGeometry(2, 2), new THREE.MeshStandardMaterial());