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: Quaternion.normalize turns a zero quaternion into the identity, as three.js does (#127)

Kevin Rajand04a996db577
diff --git a/packages/scene/src/math.ts b/packages/scene/src/math.ts
index 3bc4171..e50619f 100644
--- a/packages/scene/src/math.ts
+++ b/packages/scene/src/math.ts
@@ -216,7 +216,8 @@ export class Quaternion {
);
}
normalize(): this {
- const l = Math.hypot(this._x, this._y, this._z, this._w) || 1;
+ const l = Math.hypot(this._x, this._y, this._z, this._w);
+ if (l === 0) return this.set(0, 0, 0, 1);
return this.set(this._x / l, this._y / l, this._z / l, this._w / l);
}
slerp(qb: Quaternion, t: number): this {
diff --git a/packages/scene/test/three-compat-quaternion.test.ts b/packages/scene/test/three-compat-quaternion.test.ts
new file mode 100644
index 0000000..79cce7e
--- /dev/null
+++ b/packages/scene/test/three-compat-quaternion.test.ts
@@ -0,0 +1,15 @@
+// three.js r187 Quaternion.normalize treats a zero quaternion as the identity rotation.
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import * as THREE from "../src/index.ts";
+
+test("Quaternion: normalizing zero gives identity, as three.js does", () => {
+ const zero = new THREE.Quaternion(0, 0, 0, 0);
+ assert.equal(zero.normalize(), zero, "normalize returns its receiver");
+ assert.deepEqual(zero.toArray(), [0, 0, 0, 1], "zero becomes the identity quaternion");
+ assert.equal(zero.dot(zero), 1, "the resulting quaternion has unit squared length");
+
+ const scaled = new THREE.Quaternion(0, 0, 0, 2);
+ assert.equal(scaled.normalize(), scaled);
+ assert.deepEqual(scaled.toArray(), [0, 0, 0, 1], "nonzero normalization still works");
+});