Skip to content

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.

Scene: Object3D.add fires added and childadded, as three.js does (#207, supersedes #93)

Evan (Yifeng) Wang87c8c96461d6
diff --git a/packages/scene/src/core.ts b/packages/scene/src/core.ts
index f20a4a4..c010c1a 100644
--- a/packages/scene/src/core.ts
+++ b/packages/scene/src/core.ts
@@ -601,6 +601,9 @@ export class Object3D {
o.parent?.remove(o);
o.parent = this;
(this._children ??= []).push(o);
+ // Match three.js: observers see the new parent before either notification fires.
+ o.dispatchEvent({ type: "added" });
+ this.dispatchEvent({ type: "childadded", child: o });
}
restructured("added", objects);
return this;
diff --git a/packages/scene/test/three-compat.test.ts b/packages/scene/test/three-compat.test.ts
index 738cb67..4660398 100644
--- a/packages/scene/test/three-compat.test.ts
+++ b/packages/scene/test/three-compat.test.ts
@@ -154,6 +154,25 @@ test("Object3D: clone (geometry shared, own id), attach (world transform kept),
assert.ok(o.getWorldDirection(new THREE.Vector3()).distanceTo(new THREE.Vector3(1, 0, 0)) < 1e-9);
});
+test("Object3D.add: notifies the child and then the parent after parenting, as three.js does", () => {
+ const parent = new THREE.Group();
+ const child = new THREE.Object3D();
+ const order: string[] = [];
+ child.addEventListener("added", (event) => {
+ assert.equal(event.target, child);
+ assert.equal(child.parent, parent, "the parent is assigned before the added event");
+ order.push("added");
+ });
+ parent.addEventListener("childadded", (event) => {
+ assert.equal(event.target, parent);
+ assert.equal(event.child, child, "the parent event names the child");
+ assert.equal(child.parent, parent);
+ order.push("childadded");
+ });
+ assert.equal(parent.add(child), parent);
+ assert.deepEqual(order, ["added", "childadded"]);
+});
+
test("Mesh.copy and clone: material arrays are independent, but geometry and materials are shared, as three.js does", () => {
const geometry = new THREE.BoxGeometry();
const red = new THREE.MeshStandardMaterial({ color: 0xff0000 });