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: Matrix4.decompose leaves a singular matrix as identity rotation and unit scale, as three.js does (#126)

Kevin Rajan5c936678a3c2
diff --git a/packages/scene/src/math.ts b/packages/scene/src/math.ts
index 90ccd6c..3bc4171 100644
--- a/packages/scene/src/math.ts
+++ b/packages/scene/src/math.ts
@@ -394,11 +394,20 @@ export class Matrix4 {
}
decompose(p: Vector3, q: Quaternion, s: Vector3): this {
const te = this.elements;
+ p.set(te[12], te[13], te[14]);
+ // three.js r187 uses the affine determinant and leaves a singular matrix undecomposed.
+ const det = te[0] * (te[5] * te[10] - te[6] * te[9])
+ - te[4] * (te[1] * te[10] - te[2] * te[9])
+ + te[8] * (te[1] * te[6] - te[2] * te[5]);
+ if (det === 0) {
+ s.set(1, 1, 1);
+ q.set(0, 0, 0, 1);
+ return this;
+ }
let sx = Math.hypot(te[0], te[1], te[2]);
const sy = Math.hypot(te[4], te[5], te[6]);
const sz = Math.hypot(te[8], te[9], te[10]);
- if (this.determinant() < 0) sx = -sx;
- p.set(te[12], te[13], te[14]);
+ if (det < 0) sx = -sx;
const m = this.clone();
const me = m.elements;
me[0] /= sx; me[1] /= sx; me[2] /= sx;
diff --git a/packages/scene/test/three-compat-matrix4.test.ts b/packages/scene/test/three-compat-matrix4.test.ts
new file mode 100644
index 0000000..2d343d7
--- /dev/null
+++ b/packages/scene/test/three-compat-matrix4.test.ts
@@ -0,0 +1,18 @@
+// Matrix4.decompose singular-transform parity with three.js r187.
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import * as THREE from "../src/index.ts";
+
+test("Matrix4.decompose: zero scale retains translation and resets rotation and scale", () => {
+ const matrix = new THREE.Matrix4().makeScale(0, 2, 3).setPosition(4, 5, 6);
+ const position = new THREE.Vector3();
+ const rotation = new THREE.Quaternion(1, 2, 3, 4);
+ const scale = new THREE.Vector3(8, 9, 10);
+
+ assert.equal(matrix.determinant(), 0);
+ assert.equal(matrix.decompose(position, rotation, scale), matrix);
+ assert.deepEqual([position.x, position.y, position.z], [4, 5, 6]);
+ assert.deepEqual([rotation.x, rotation.y, rotation.z, rotation.w], [0, 0, 0, 1]);
+ assert.deepEqual([scale.x, scale.y, scale.z], [1, 1, 1]);
+ assert.deepEqual(matrix.elements, [0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 3, 0, 4, 5, 6, 1]);
+});