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: DirectionalLight and SpotLight copy and clone get their own target, as three.js does (#119)

Kevin Rajan762d5bf3dc48
diff --git a/packages/scene/src/core.ts b/packages/scene/src/core.ts
index 274776b..fa9995a 100644
--- a/packages/scene/src/core.ts
+++ b/packages/scene/src/core.ts
@@ -2016,6 +2016,13 @@ export abstract class Light extends Object3D {
abstract class TargetedLight extends Light {
/** World-space point the light aims at. `null` keeps the node's own orientation (-Z). */
target: Object3D | null = new Object3D();
+
+ /** three.js gives copied directional and spot lights their own target object. */
+ override copy(source: Object3D, recursive = true): this {
+ super.copy(source, recursive);
+ if (source instanceof TargetedLight) this.target = source.target?.clone() ?? null;
+ return this;
+ }
}
export class DirectionalLight extends TargetedLight {
diff --git a/packages/scene/test/three-compat-lights.test.ts b/packages/scene/test/three-compat-lights.test.ts
new file mode 100644
index 0000000..8ef0206
--- /dev/null
+++ b/packages/scene/test/three-compat-lights.test.ts
@@ -0,0 +1,28 @@
+// three.js compatibility: DirectionalLight and SpotLight copy their target, as three.js r187 has it (the snippet-level suite is three-compat.test.ts).
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import * as THREE from "../src/index.ts";
+
+test("DirectionalLight and SpotLight: copy and clone give each light its own target, as three.js does", () => {
+ for (const LightType of [THREE.DirectionalLight, THREE.SpotLight]) {
+ for (const targetInScene of [false, true]) {
+ const source = new LightType(0x336699, 2);
+ const target = source.target!;
+ assert.deepEqual(target.position.toArray(), [0, 0, 0], "a new target starts at the origin");
+ target.position.set(2, 3, 4);
+ if (targetInScene) new THREE.Scene().add(target);
+
+ const cloned = source.clone();
+ const copied = new LightType().copy(source);
+ for (const other of [cloned, copied]) {
+ assert.notStrictEqual(other.target, target, `${source.type}: copied target is independent`);
+ assert.equal(other.target!.parent, null, "a copied target is not added to the scene");
+ assert.deepEqual(other.target!.position.toArray(), [2, 3, 4]);
+ }
+
+ target.position.set(7, 8, 9);
+ assert.deepEqual(cloned.target!.position.toArray(), [2, 3, 4], "clone keeps its target position");
+ assert.deepEqual(copied.target!.position.toArray(), [2, 3, 4], "copy keeps its target position");
+ }
+ }
+});