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: Vector2.roundToZero, as three.js has it (#143)

Kevin Rajanab9f1ae4a9bf
diff --git a/packages/scene/src/math.ts b/packages/scene/src/math.ts
index 09d5e09..ff61f6e 100644
--- a/packages/scene/src/math.ts
+++ b/packages/scene/src/math.ts
@@ -691,6 +691,9 @@ export class Vector2 {
multiplyScalar(s: number): this {
return this.set(this.x * s, this.y * s);
}
+ roundToZero(): this {
+ return this.set(Math.trunc(this.x), Math.trunc(this.y));
+ }
dot(v: Vector2): number {
return this.x * v.x + this.y * v.y;
}
diff --git a/packages/scene/test/three-compat-vector-componentwise.test.ts b/packages/scene/test/three-compat-vector-componentwise.test.ts
new file mode 100644
index 0000000..3cb00e0
--- /dev/null
+++ b/packages/scene/test/three-compat-vector-componentwise.test.ts
@@ -0,0 +1,19 @@
+// Vector2.roundToZero preserves signed truncation, as three.js r187 does.
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import * as THREE from "../src/index.ts";
+
+test("Vector2.roundToZero truncates each signed component toward zero", () => {
+ const value = new THREE.Vector2(-2.9, 3.9);
+ assert.equal(value.roundToZero(), value, "roundToZero is chainable");
+ assert.deepEqual(value.toArray(), [-2, 3], "both signs truncate toward zero");
+
+ const fractions = new THREE.Vector2(-0.75, 0.75);
+ fractions.roundToZero();
+ assert.ok(Object.is(fractions.x, -0), "negative fractions retain a negative zero");
+ assert.ok(Object.is(fractions.y, 0), "positive fractions become positive zero");
+
+ const integers = new THREE.Vector2(-4, 5);
+ assert.equal(integers.roundToZero(), integers);
+ assert.deepEqual(integers.toArray(), [-4, 5], "integers are unchanged");
+});