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: Sphere.expandByPoint, as three.js has it (#142)

Kevin Rajanb71bb9fcbc43
diff --git a/packages/scene/src/math.ts b/packages/scene/src/math.ts
index 6c737b7..09d5e09 100644
--- a/packages/scene/src/math.ts
+++ b/packages/scene/src/math.ts
@@ -820,6 +820,25 @@ export class Sphere {
this.radius = Math.sqrt(r2);
return this;
}
+ /** Grow the sphere to include a point, as three.js Sphere.expandByPoint does. */
+ expandByPoint(point: Vector3): this {
+ if (this.radius < 0) {
+ this.center.copy(point);
+ this.radius = 0;
+ return this;
+ }
+
+ const offset = new Vector3().subVectors(point, this.center);
+ const lengthSq = offset.lengthSq();
+ if (lengthSq > this.radius * this.radius) {
+ const length = Math.sqrt(lengthSq);
+ const delta = (length - this.radius) * 0.5;
+ this.center.addScaledVector(offset, delta / length);
+ this.radius += delta;
+ }
+ return this;
+ }
+
clone(): Sphere {
return new Sphere(this.center.clone(), this.radius);
}
diff --git a/packages/scene/test/three-compat-sphere.test.ts b/packages/scene/test/three-compat-sphere.test.ts
new file mode 100644
index 0000000..2ef9115
--- /dev/null
+++ b/packages/scene/test/three-compat-sphere.test.ts
@@ -0,0 +1,27 @@
+// Sphere.expandByPoint parity: empty seed, minimal growth, and unchanged interior points.
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import * as THREE from "../src/index.ts";
+
+test("Sphere.expandByPoint grows minimally from an empty sphere, as three.js does", () => {
+ const sphere = new THREE.Sphere();
+ const first = new THREE.Vector3(2, 0, 0);
+ assert.equal(sphere.radius, -1);
+
+ assert.equal(sphere.expandByPoint(first), sphere);
+ assert.deepEqual(sphere.center.toArray(), [2, 0, 0]);
+ assert.equal(sphere.radius, 0);
+ assert.deepEqual(first.toArray(), [2, 0, 0], "the input point is not mutated");
+
+ assert.equal(sphere.expandByPoint(new THREE.Vector3(6, 0, 0)), sphere);
+ assert.deepEqual(sphere.center.toArray(), [4, 0, 0]);
+ assert.equal(sphere.radius, 2);
+
+ sphere.expandByPoint(new THREE.Vector3(5, 0, 0));
+ assert.deepEqual(sphere.center.toArray(), [4, 0, 0]);
+ assert.equal(sphere.radius, 2);
+
+ sphere.expandByPoint(new THREE.Vector3(-2, 0, 0));
+ assert.deepEqual(sphere.center.toArray(), [2, 0, 0]);
+ assert.equal(sphere.radius, 4);
+});