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: three.js parity, batch 2 — Matrix3, Plane, Layers, interleaved buffers, Euler in all six orders, and more (#256)

Evan (Yifeng) Wang8c90822bdc61
diff --git a/packages/scene/src/core.ts b/packages/scene/src/core.ts
index 9604515..91f0563 100644
--- a/packages/scene/src/core.ts
+++ b/packages/scene/src/core.ts
@@ -248,7 +248,7 @@ export function bindBody(o: Object3D, b: BoundBody): void {
if (b.epoch !== physicsEpoch) pullPose(b, p, q);
if (b.euler) {
b.euler = false;
- r.setFromQuaternion(q, false);
+ r.setFromQuaternion(q, undefined, false);
}
return r;
},
@@ -333,10 +333,49 @@ export interface SwayDesc {
phase?: number;
}
+/**
+ * three.js's layers: which of 32 layers an object is on (a bit mask; layer 0 alone to begin with). `Raycaster.layers`
+ * picks by them; the renderer draws every object whatever its layers (a camera's layers select nothing yet).
+ */
+export class Layers {
+ mask = 1 | 0;
+ /** On `layer` alone. */
+ set(layer: number): void {
+ this.mask = ((1 << layer) | 0) >>> 0;
+ }
+ enable(layer: number): void {
+ this.mask |= (1 << layer) | 0;
+ }
+ enableAll(): void {
+ this.mask = 0xffffffff | 0;
+ }
+ toggle(layer: number): void {
+ this.mask ^= (1 << layer) | 0;
+ }
+ disable(layer: number): void {
+ this.mask &= ~((1 << layer) | 0);
+ }
+ disableAll(): void {
+ this.mask = 0;
+ }
+ /** Whether the two share a layer. */
+ test(layers: Layers): boolean {
+ return (this.mask & layers.mask) !== 0;
+ }
+ isEnabled(layer: number): boolean {
+ return (this.mask & ((1 << layer) | 0)) !== 0;
+ }
+}
+
+/** @internal Whether `o` is on one of `layers`, without making its `Layers` (most objects never have one). */
+export function onLayers(o: Object3D, layers: Layers): boolean {
+ return (((o as unknown as { _layers?: Layers })._layers?.mask ?? 1) & layers.mask) !== 0;
+}
+
let objectIds = 0;
/** What `Object3D.copy` does not take over as it is (transforms are copied by value, children cloned). */
-const COPY_SKIP = new Set(["parent", "children", "position", "quaternion", "rotation", "scale", "up", "matrix", "matrixWorld", "userData", "tags", "_id", "_autoId", "uuid", "_body", "_listeners", "_ref", "_up", "_matrix", "_matrixWorld", "_userData", "_tags", "_custom", "_children"]);
+const COPY_SKIP = new Set(["parent", "children", "position", "quaternion", "rotation", "scale", "up", "matrix", "matrixWorld", "userData", "tags", "_id", "_autoId", "uuid", "_body", "_listeners", "_ref", "_up", "_matrix", "_matrixWorld", "_userData", "_tags", "_custom", "_children", "_layers"]);
const NO_CHILDREN = Object.freeze([]) as unknown as Object3D[];
const NO_CUSTOM: readonly [number, number, number, number] = Object.freeze([0, 0, 0, 0] as [number, number, number, number]);
/** An object's rotation changed: its quaternion follows (the object through the rotation's weak owner). */
@@ -350,7 +389,7 @@ function rotationChanged(this: Euler): void {
function quaternionChanged(this: Quaternion): void {
const o = this._owner?.deref() as Object3D | undefined;
if (!o) return;
- o.rotation.setFromQuaternion(this, false);
+ o.rotation.setFromQuaternion(this, undefined, false);
touched(o);
}
@@ -390,6 +429,14 @@ export class Object3D {
private _movable = false;
receiveShadow = true;
declare private _tags: string[] | undefined;
+ declare private _layers: Layers | undefined;
+ /** The layers the object is on (`Layers`), made when first asked for. */
+ get layers(): Layers {
+ return (this._layers ??= new Layers());
+ }
+ set layers(v: Layers) {
+ this._layers = v;
+ }
declare private _userData: Record<string, unknown> | undefined;
get tags(): string[] {
return (this._tags ??= []);
@@ -721,13 +768,19 @@ export class Object3D {
(this as unknown as Record<string, unknown>)[k] = v instanceof Color || v instanceof Vector3 || v instanceof Vector2 ? v.clone() : v;
}
this.position.copy(source.position);
- this.quaternion.copy(source.quaternion);
+ // The rotation in the source's order and angles (three.js copies the order), then its quaternion exactly; the
+ // quaternion quietly, as the two already agree.
+ const r = source.rotation, q = source.quaternion;
+ this.rotation.set(r.x, r.y, r.z, r.order);
+ this.quaternion.set(q.x, q.y, q.z, q.w, false);
this.scale.copy(source.scale);
this.up.copy(source.up);
this.matrix.copy(source.matrix);
this.matrixWorld.copy(source.matrixWorld);
this.userData = JSON.parse(JSON.stringify(source.userData));
this.tags = [...source.tags];
+ // The mask by value, as three.js (an object never asked for its layers is on layer 0).
+ if (source._layers || this._layers) this.layers.mask = source._layers?.mask ?? 1;
if (recursive) for (const c of source.children) this.add(c.clone());
touched(this);
return this;
@@ -1201,6 +1254,8 @@ export interface MeshPhysicalMaterialParameters extends MeshStandardMaterialPara
/** Scales `transmission` by its red channel (three.js / glTF transmissionTexture). */
transmissionMap?: Texture | null;
ior?: number;
+ /** Sets `ior` (three.js): 0..1, 0.5 = ior 1.5. */
+ reflectivity?: number;
specularIntensity?: number;
}
@@ -1249,6 +1304,13 @@ export class MeshPhysicalMaterial extends MeshStandardMaterial {
transmissionMap: Texture | null = null;
ior = 1.5;
specularIntensity = 1;
+ /** The dielectric's reflectance as three.js has it: `ior` mapped to 0..1 (0.5 = ior 1.5); setting it sets `ior`. */
+ get reflectivity(): number {
+ return Math.min(Math.max((2.5 * (this.ior - 1)) / (this.ior + 1), 0), 1);
+ }
+ set reflectivity(reflectivity: number) {
+ this.ior = (1 + 0.4 * reflectivity) / (1 - 0.4 * reflectivity);
+ }
constructor(params: MeshPhysicalMaterialParameters = {}) {
super();
this.setValues(params);
@@ -2020,10 +2082,12 @@ export interface LightShadow {
normalBias: number;
radius: number;
blurSamples: number;
+ /** three.js frees the shadow map; there is none to free. */
+ dispose(): void;
}
function lightShadow(): LightShadow {
- return { mapSize: new Vector2(512, 512), camera: { near: 0.5, far: 500, left: -5, right: 5, top: 5, bottom: -5, fov: 90, updateProjectionMatrix() {} }, bias: 0, normalBias: 0, radius: 1, blurSamples: 8 };
+ return { mapSize: new Vector2(512, 512), camera: { near: 0.5, far: 500, left: -5, right: 5, top: 5, bottom: -5, fov: 90, updateProjectionMatrix() {} }, bias: 0, normalBias: 0, radius: 1, blurSamples: 8, dispose() {} };
}
export abstract class Light extends Object3D {
@@ -2044,6 +2108,10 @@ export abstract class Light extends Object3D {
protected override get looksDownNegativeZ(): boolean {
return true;
}
+ /** three.js frees the light's shadow map; ThreeRT's lights hold no GPU resources of their own. */
+ dispose(): void {
+ this.shadow.dispose();
+ }
}
/** Light pointing at `target` (three.js semantics); resolved to an orientation at compile time. */
@@ -2148,6 +2216,8 @@ export class AmbientLight extends Object3D {
this.color = new Color(color);
this.intensity = intensity;
}
+ /** three.js API; nothing to free. */
+ dispose(): void {}
}
/** three.js HemisphereLight: sky colour from above, ground colour from below; as AmbientLight, a gradient sky. */
@@ -2164,6 +2234,8 @@ export class HemisphereLight extends Object3D {
this.groundColor = new Color(groundColor);
this.intensity = intensity;
}
+ /** three.js API; nothing to free. */
+ dispose(): void {}
}
const DEFAULT_EXPOSURE = { mode: "auto", compensation: 0, minEv100: -10, maxEv100: 20 } as const;
@@ -2212,10 +2284,21 @@ export class PerspectiveCamera extends Object3D {
}
/** Set the vertical FOV from focal length, using the film height for this aspect ratio (three.js). */
setFocalLength(focalLength: number): void {
- const filmHeight = this.filmGauge / Math.max(this.aspect, 1);
- this.fov = (2 * Math.atan(0.5 * filmHeight / focalLength) * 180) / Math.PI;
+ this.fov = (2 * Math.atan((0.5 * this.getFilmHeight()) / focalLength) * 180) / Math.PI;
this.updateProjectionMatrix();
}
+ /** The focal length, in film-gauge millimeters, that gives the current vertical FOV (three.js). */
+ getFocalLength(): number {
+ return (0.5 * this.getFilmHeight()) / Math.tan((this.fov * Math.PI) / 360);
+ }
+ /** The film's width for this aspect ratio: the gauge, narrowed when the view is portrait (three.js). */
+ getFilmWidth(): number {
+ return this.filmGauge * Math.min(this.aspect, 1);
+ }
+ /** The film's height for this aspect ratio: the gauge, shortened when the view is landscape (three.js). */
+ getFilmHeight(): number {
+ return this.filmGauge / Math.max(this.aspect, 1);
+ }
/** three.js API; the engine reads fov / aspect / near / far as they are. */
updateProjectionMatrix(): void {}
/** As Object3D's, exposure and depth of field copied rather than shared (a default exposure stays the default). */
diff --git a/packages/scene/src/geometry.ts b/packages/scene/src/geometry.ts
index 5ac07b1..eedba07 100644
--- a/packages/scene/src/geometry.ts
+++ b/packages/scene/src/geometry.ts
@@ -1,6 +1,7 @@
// three.js-compatible geometry generators. Vertex layout and winding match three (CCW front faces).
import { Box3, Matrix4, type Quaternion, Sphere, Vector3 } from "./math.ts";
+import type { InterleavedBufferAttribute } from "./interleaved.ts";
let geometryIds = 0;
@@ -9,7 +10,7 @@ let geometryIds = 0;
export const StaticDrawUsage = 35044;
export const DynamicDrawUsage = 35048;
-type NumberArray = Float32Array | Uint32Array | Uint16Array | Uint8Array | Int32Array | Int16Array | Int8Array;
+type NumberArray = Float32Array | Uint32Array | Uint16Array | Uint8Array | Uint8ClampedArray | Int32Array | Int16Array | Int8Array;
/**
* A geometry's per-vertex numbers (three.js BufferAttribute): `itemSize` per vertex in `array`. After writing them
@@ -44,57 +45,66 @@ export class BufferAttribute {
this.usage = usage;
return this;
}
+ /** A stored component as a number: a normalized integer attribute's in 0..1 (or -1..1), as three.js reads it. */
+ private _get(o: number): number {
+ const v = this.array[o];
+ return this.normalized ? denormalize(v, this.array) : v;
+ }
+ /** Stores a component: a normalized integer attribute's from 0..1 (or -1..1), as three.js writes it. */
+ private _set(o: number, v: number): void {
+ this.array[o] = this.normalized ? normalize(v, this.array) : v;
+ }
getComponent(i: number, k: number): number {
- return this.array[i * this.itemSize + k];
+ return this._get(i * this.itemSize + k);
}
setComponent(i: number, k: number, v: number): this {
- this.array[i * this.itemSize + k] = v;
+ this._set(i * this.itemSize + k, v);
return this;
}
getX(i: number): number {
- return this.array[i * this.itemSize];
+ return this._get(i * this.itemSize);
}
getY(i: number): number {
- return this.array[i * this.itemSize + 1];
+ return this._get(i * this.itemSize + 1);
}
getZ(i: number): number {
- return this.array[i * this.itemSize + 2];
+ return this._get(i * this.itemSize + 2);
}
getW(i: number): number {
- return this.array[i * this.itemSize + 3];
+ return this._get(i * this.itemSize + 3);
}
setX(i: number, v: number): this {
- this.array[i * this.itemSize] = v;
+ this._set(i * this.itemSize, v);
return this;
}
setY(i: number, v: number): this {
- this.array[i * this.itemSize + 1] = v;
+ this._set(i * this.itemSize + 1, v);
return this;
}
setZ(i: number, v: number): this {
- this.array[i * this.itemSize + 2] = v;
+ this._set(i * this.itemSize + 2, v);
return this;
}
setW(i: number, v: number): this {
- this.array[i * this.itemSize + 3] = v;
+ this._set(i * this.itemSize + 3, v);
return this;
}
setXY(i: number, x: number, y: number): this {
const o = i * this.itemSize;
- this.array[o] = x;
- this.array[o + 1] = y;
+ this._set(o, x);
+ this._set(o + 1, y);
return this;
}
setXYZ(i: number, x: number, y: number, z: number): this {
const o = i * this.itemSize;
- this.array[o] = x;
- this.array[o + 1] = y;
- this.array[o + 2] = z;
+ this._set(o, x);
+ this._set(o + 1, y);
+ this._set(o + 2, z);
return this;
}
setXYZW(i: number, x: number, y: number, z: number, w: number): this {
this.setXYZ(i, x, y, z);
- this.array[i * this.itemSize + 3] = w;
+ this._set(i * this.itemSize + 3, w);
return this;
}
set(values: ArrayLike<number>, offset = 0): this {
@@ -117,7 +127,7 @@ export class BufferAttribute {
applyMatrix4(m: Matrix4): this {
const v = new Vector3();
for (let i = 0; i < this.count; i++) {
- v.fromArray(this.array, i * this.itemSize).applyMatrix4(m);
+ v.set(this.getX(i), this.getY(i), this.getZ(i)).applyMatrix4(m);
this.setXYZ(i, v.x, v.y, v.z);
}
return this;
@@ -126,7 +136,7 @@ export class BufferAttribute {
transformDirection(m: Matrix4): this {
const v = new Vector3();
for (let i = 0; i < this.count; i++) {
- v.fromArray(this.array, i * this.itemSize).transformDirection(m);
+ v.set(this.getX(i), this.getY(i), this.getZ(i)).transformDirection(m);
this.setXYZ(i, v.x, v.y, v.z);
}
return this;
@@ -151,6 +161,31 @@ export class Uint16BufferAttribute extends BufferAttribute {
super(typeof array === "number" ? new Uint16Array(array) : Uint16Array.from(array), itemSize, normalized);
}
}
+export class Int32BufferAttribute extends BufferAttribute {
+ constructor(array: ArrayLike<number> | number, itemSize: number, normalized = false) {
+ super(typeof array === "number" ? new Int32Array(array) : Int32Array.from(array), itemSize, normalized);
+ }
+}
+export class Int16BufferAttribute extends BufferAttribute {
+ constructor(array: ArrayLike<number> | number, itemSize: number, normalized = false) {
+ super(typeof array === "number" ? new Int16Array(array) : Int16Array.from(array), itemSize, normalized);
+ }
+}
+export class Uint8ClampedBufferAttribute extends BufferAttribute {
+ constructor(array: ArrayLike<number> | number, itemSize: number, normalized = false) {
+ super(typeof array === "number" ? new Uint8ClampedArray(array) : Uint8ClampedArray.from(array), itemSize, normalized);
+ }
+}
+export class Uint8BufferAttribute extends BufferAttribute {
+ constructor(array: ArrayLike<number> | number, itemSize: number, normalized = false) {
+ super(typeof array === "number" ? new Uint8Array(array) : Uint8Array.from(array), itemSize, normalized);
+ }
+}
+export class Int8BufferAttribute extends BufferAttribute {
+ constructor(array: ArrayLike<number> | number, itemSize: number, normalized = false) {
+ super(typeof array === "number" ? new Int8Array(array) : Int8Array.from(array), itemSize, normalized);
+ }
+}
/** A range of a geometry's index (or vertices) drawn with `materials[materialIndex]` of a mesh with several. */
export interface GeometryGroup {
@@ -212,7 +247,9 @@ export class BufferGeometry {
this.needsUpdate = true;
this.version++;
}
- setAttribute(name: string, attribute: BufferAttribute): this {
+ /** An `InterleavedBufferAttribute` is taken de-interleaved (its `clone()`): set it again after editing its buffer. */
+ setAttribute(name: string, attribute: BufferAttribute | InterleavedBufferAttribute): this {
+ if (!(attribute instanceof BufferAttribute)) attribute = attribute.clone();
const a = name === "position" || name === "normal" || name === "uv" ? asFloat32(attribute) : attribute;
a._geometry = this;
this.attributes[name] = a;
@@ -385,6 +422,23 @@ export class BufferGeometry {
}
}
+/** three.js's normalization scale of an integer array type (MathUtils.getNormalizationScale). */
+function normalizationScale(array: NumberArray): number {
+ if (array instanceof Uint32Array) return 4294967295;
+ if (array instanceof Uint16Array) return 65535;
+ if (array instanceof Uint8Array || (array as unknown) instanceof Uint8ClampedArray) return 255;
+ if (array instanceof Int32Array) return 2147483647;
+ if (array instanceof Int16Array) return 32767;
+ if (array instanceof Int8Array) return 127;
+ throw new Error("BufferAttribute: invalid component type for a normalized attribute");
+}
+function denormalize(v: number, array: NumberArray): number {
+ return array instanceof Float32Array ? v : Math.max(v / normalizationScale(array), -1);
+}
+function normalize(v: number, array: NumberArray): number {
+ return array instanceof Float32Array ? v : Math.round(v * normalizationScale(array));
+}
+
function matrix(): Matrix4 {
return new Matrix4();
}
diff --git a/packages/scene/src/index.ts b/packages/scene/src/index.ts
index 2c2c9c5..abce710 100644
--- a/packages/scene/src/index.ts
+++ b/packages/scene/src/index.ts
@@ -1,5 +1,6 @@
export * from "./math.ts";
export * from "./geometry.ts";
+export * from "./interleaved.ts";
export * from "./core.ts";
export * from "./engine.ts";
export { rendering, type RenderingRequest, type RenderingStatus, type ReconstructionMethod, type ReconstructionRequest, type QualityRequest, type FrameGenerationRequest, type LatencyRequest, type SkipReason } from "./rendering.ts";
diff --git a/packages/scene/src/interleaved.ts b/packages/scene/src/interleaved.ts
new file mode 100644
index 0000000..a10eb72
--- /dev/null
+++ b/packages/scene/src/interleaved.ts
@@ -0,0 +1,192 @@
+// three.js-compatible interleaved vertex data: several attributes in one array, `stride` numbers a vertex.
+
+import { BufferAttribute, StaticDrawUsage } from "./geometry.ts";
+import { Vector3, type Matrix4 } from "./math.ts";
+
+type NumberArray = BufferAttribute["array"];
+
+let bufferIds = 0;
+
+/** One array holding several attributes per vertex (three.js `InterleavedBuffer`): `stride` numbers per vertex. */
+export class InterleavedBuffer {
+ readonly isInterleavedBuffer = true;
+ readonly uuid = `ib${++bufferIds}`;
+ array: NumberArray;
+ stride: number;
+ count: number;
+ usage = StaticDrawUsage;
+ /** Bumped by `needsUpdate = true`. */
+ version = 0;
+ updateRanges: { start: number; count: number }[] = [];
+ constructor(array: NumberArray, stride: number) {
+ this.array = array;
+ this.stride = stride;
+ this.count = array.length / stride;
+ }
+ set needsUpdate(v: boolean) {
+ if (v) this.version++;
+ }
+ setUsage(usage: number): this {
+ this.usage = usage;
+ return this;
+ }
+ addUpdateRange(start: number, count: number): void {
+ this.updateRanges.push({ start, count });
+ }
+ clearUpdateRanges(): void {
+ this.updateRanges.length = 0;
+ }
+ copy(source: InterleavedBuffer): this {
+ this.array = source.array.slice() as NumberArray;
+ this.count = source.count;
+ this.stride = source.stride;
+ this.usage = source.usage;
+ return this;
+ }
+ /** Copies one vertex's `stride` numbers from another buffer. */
+ copyAt(index1: number, buffer: InterleavedBuffer, index2: number): this {
+ const dst = index1 * this.stride, src = index2 * buffer.stride;
+ for (let i = 0; i < this.stride; i++) this.array[dst + i] = buffer.array[src + i];
+ return this;
+ }
+ set(values: ArrayLike<number>, offset = 0): this {
+ this.array.set(values, offset);
+ return this;
+ }
+ /** A buffer with its own copy of the array. */
+ clone(): InterleavedBuffer {
+ return new (this.constructor as typeof InterleavedBuffer)(this.array.slice() as NumberArray, this.stride).setUsage(this.usage);
+ }
+}
+
+/**
+ * One attribute of an `InterleavedBuffer` (three.js `InterleavedBufferAttribute`): `itemSize` numbers at `offset` in
+ * each vertex's `stride`. A geometry's `setAttribute` takes it de-interleaved (as `clone()` gives it): edits to the
+ * buffer afterwards reach the geometry by setting the attribute again.
+ */
+export class InterleavedBufferAttribute {
+ readonly isInterleavedBufferAttribute = true;
+ name = "";
+ data: InterleavedBuffer;
+ itemSize: number;
+ offset: number;
+ normalized: boolean;
+ constructor(interleavedBuffer: InterleavedBuffer, itemSize: number, offset: number, normalized = false) {
+ this.data = interleavedBuffer;
+ this.itemSize = itemSize;
+ this.offset = offset;
+ this.normalized = normalized;
+ }
+ get count(): number {
+ return this.data.count;
+ }
+ get array(): NumberArray {
+ return this.data.array;
+ }
+ set needsUpdate(v: boolean) {
+ this.data.needsUpdate = v;
+ }
+ private _get(i: number, k: number): number {
+ const v = this.data.array[i * this.data.stride + this.offset + k];
+ return this.normalized ? denormalize(v, this.data.array) : v;
+ }
+ private _set(i: number, k: number, v: number): void {
+ this.data.array[i * this.data.stride + this.offset + k] = this.normalized ? normalize(v, this.data.array) : v;
+ }
+ getComponent(i: number, k: number): number {
+ return this._get(i, k);
+ }
+ setComponent(i: number, k: number, v: number): this {
+ this._set(i, k, v);
+ return this;
+ }
+ getX(i: number): number {
+ return this._get(i, 0);
+ }
+ getY(i: number): number {
+ return this._get(i, 1);
+ }
+ getZ(i: number): number {
+ return this._get(i, 2);
+ }
+ getW(i: number): number {
+ return this._get(i, 3);
+ }
+ setX(i: number, v: number): this {
+ this._set(i, 0, v);
+ return this;
+ }
+ setY(i: number, v: number): this {
+ this._set(i, 1, v);
+ return this;
+ }
+ setZ(i: number, v: number): this {
+ this._set(i, 2, v);
+ return this;
+ }
+ setW(i: number, v: number): this {
+ this._set(i, 3, v);
+ return this;
+ }
+ setXY(i: number, x: number, y: number): this {
+ this._set(i, 0, x);
+ this._set(i, 1, y);
+ return this;
+ }
+ setXYZ(i: number, x: number, y: number, z: number): this {
+ this.setXY(i, x, y);
+ this._set(i, 2, z);
+ return this;
+ }
+ setXYZW(i: number, x: number, y: number, z: number, w: number): this {
+ this.setXYZ(i, x, y, z);
+ this._set(i, 3, w);
+ return this;
+ }
+ /** Positions by `m` (itemSize 3). */
+ applyMatrix4(m: Matrix4): this {
+ const v = new Vector3();
+ for (let i = 0; i < this.count; i++) {
+ v.set(this.getX(i), this.getY(i), this.getZ(i)).applyMatrix4(m);
+ this.setXYZ(i, v.x, v.y, v.z);
+ }
+ return this;
+ }
+ /** Directions by `m`'s rotation and scale, renormalised (normals; itemSize 3). */
+ transformDirection(m: Matrix4): this {
+ const v = new Vector3();
+ for (let i = 0; i < this.count; i++) {
+ v.set(this.getX(i), this.getY(i), this.getZ(i)).transformDirection(m);
+ this.setXYZ(i, v.x, v.y, v.z);
+ }
+ return this;
+ }
+ /** The attribute de-interleaved into a `BufferAttribute` of its own (three.js's `clone()` without `data`). */
+ clone(): BufferAttribute {
+ const out = new (this.array.constructor as new (n: number) => NumberArray)(this.count * this.itemSize);
+ for (let i = 0; i < this.count; i++) {
+ const o = i * this.data.stride + this.offset;
+ for (let j = 0; j < this.itemSize; j++) out[i * this.itemSize + j] = this.data.array[o + j];
+ }
+ const a = new BufferAttribute(out, this.itemSize, this.normalized);
+ a.name = this.name;
+ return a;
+ }
+}
+
+/** three.js's normalization scale of an integer array type (MathUtils.getNormalizationScale). */
+function normalizationScale(array: NumberArray): number {
+ if (array instanceof Uint32Array) return 4294967295;
+ if (array instanceof Uint16Array) return 65535;
+ if (array instanceof Uint8Array || (array as unknown) instanceof Uint8ClampedArray) return 255;
+ if (array instanceof Int32Array) return 2147483647;
+ if (array instanceof Int16Array) return 32767;
+ if (array instanceof Int8Array) return 127;
+ throw new Error("InterleavedBufferAttribute: invalid component type for a normalized attribute");
+}
+function denormalize(v: number, array: NumberArray): number {
+ return array instanceof Float32Array ? v : Math.max(v / normalizationScale(array), -1);
+}
+function normalize(v: number, array: NumberArray): number {
+ return array instanceof Float32Array ? v : Math.round(v * normalizationScale(array));
+}
diff --git a/packages/scene/src/math.ts b/packages/scene/src/math.ts
index affe7a7..314d704 100644
--- a/packages/scene/src/math.ts
+++ b/packages/scene/src/math.ts
@@ -47,6 +47,102 @@ export class Vector3 {
multiplyScalar(s: number): this {
return this.set(this.x * s, this.y * s, this.z * s);
}
+ // Component-wise arithmetic, as three.js r187 has it. Each goes through set(), so a tracked position reports one change.
+ setX(x: number): this {
+ return this.set(x, this.y, this.z);
+ }
+ setY(y: number): this {
+ return this.set(this.x, y, this.z);
+ }
+ setZ(z: number): this {
+ return this.set(this.x, this.y, z);
+ }
+ getComponent(index: number): number {
+ if (index === 0) return this.x;
+ if (index === 1) return this.y;
+ if (index === 2) return this.z;
+ throw new RangeError(`index is out of range: ${index}`);
+ }
+ addScalar(s: number): this {
+ return this.set(this.x + s, this.y + s, this.z + s);
+ }
+ addVectors(a: Vector3, b: Vector3): this {
+ return this.set(a.x + b.x, a.y + b.y, a.z + b.z);
+ }
+ subScalar(s: number): this {
+ return this.set(this.x - s, this.y - s, this.z - s);
+ }
+ multiply(v: Vector3): this {
+ return this.set(this.x * v.x, this.y * v.y, this.z * v.z);
+ }
+ multiplyVectors(a: Vector3, b: Vector3): this {
+ return this.set(a.x * b.x, a.y * b.y, a.z * b.z);
+ }
+ divide(v: Vector3): this {
+ return this.set(this.x / v.x, this.y / v.y, this.z / v.z);
+ }
+ divideScalar(s: number): this {
+ return this.multiplyScalar(1 / s);
+ }
+ min(v: Vector3): this {
+ return this.set(Math.min(this.x, v.x), Math.min(this.y, v.y), Math.min(this.z, v.z));
+ }
+ max(v: Vector3): this {
+ return this.set(Math.max(this.x, v.x), Math.max(this.y, v.y), Math.max(this.z, v.z));
+ }
+ /** Assumes min <= max component-wise, as three.js does. */
+ clamp(min: Vector3, max: Vector3): this {
+ return this.set(
+ Math.max(min.x, Math.min(max.x, this.x)),
+ Math.max(min.y, Math.min(max.y, this.y)),
+ Math.max(min.z, Math.min(max.z, this.z)),
+ );
+ }
+ clampScalar(minVal: number, maxVal: number): this {
+ return this.set(
+ Math.max(minVal, Math.min(maxVal, this.x)),
+ Math.max(minVal, Math.min(maxVal, this.y)),
+ Math.max(minVal, Math.min(maxVal, this.z)),
+ );
+ }
+ clampLength(min: number, max: number): this {
+ const l = this.length();
+ return this.divideScalar(l || 1).multiplyScalar(Math.max(min, Math.min(max, l)));
+ }
+ floor(): this {
+ return this.set(Math.floor(this.x), Math.floor(this.y), Math.floor(this.z));
+ }
+ ceil(): this {
+ return this.set(Math.ceil(this.x), Math.ceil(this.y), Math.ceil(this.z));
+ }
+ round(): this {
+ return this.set(Math.round(this.x), Math.round(this.y), Math.round(this.z));
+ }
+ roundToZero(): this {
+ return this.set(Math.trunc(this.x), Math.trunc(this.y), Math.trunc(this.z));
+ }
+ negate(): this {
+ return this.set(-this.x, -this.y, -this.z);
+ }
+ manhattanLength(): number {
+ return Math.abs(this.x) + Math.abs(this.y) + Math.abs(this.z);
+ }
+ setLength(length: number): this {
+ return this.normalize().multiplyScalar(length);
+ }
+ lerpVectors(v1: Vector3, v2: Vector3, alpha: number): this {
+ return this.set(v1.x + (v2.x - v1.x) * alpha, v1.y + (v2.y - v1.y) * alpha, v1.z + (v2.z - v1.z) * alpha);
+ }
+ distanceToSquared(v: Vector3): number {
+ const dx = this.x - v.x, dy = this.y - v.y, dz = this.z - v.z;
+ return dx * dx + dy * dy + dz * dz;
+ }
+ manhattanDistanceTo(v: Vector3): number {
+ return Math.abs(this.x - v.x) + Math.abs(this.y - v.y) + Math.abs(this.z - v.z);
+ }
+ equals(v: Vector3): boolean {
+ return v.x === this.x && v.y === this.y && v.z === this.z;
+ }
dot(v: Vector3): number {
return this.x * v.x + this.y * v.y + this.z * v.z;
}
@@ -88,6 +184,15 @@ export class Vector3 {
(e[2] * x + e[6] * y + e[10] * z + e[14]) * w,
);
}
+ applyMatrix3(m: Matrix3): this {
+ const e = m.elements;
+ const { x, y, z } = this;
+ return this.set(e[0] * x + e[3] * y + e[6] * z, e[1] * x + e[4] * y + e[7] * z, e[2] * x + e[5] * y + e[8] * z);
+ }
+ /** Transforms a normal by `Matrix3.getNormalMatrix` output and renormalizes, as three.js does. */
+ applyNormalMatrix(m: Matrix3): this {
+ return this.applyMatrix3(m).normalize();
+ }
transformDirection(m: Matrix4): this {
const e = m.elements;
const { x, y, z } = this;
@@ -278,8 +383,24 @@ export class Quaternion {
}
/** The inverse rotation (of a unit quaternion). */
invert(): this {
+ return this.conjugate();
+ }
+ conjugate(): this {
return this.set(-this._x, -this._y, -this._z, this._w);
}
+ identity(): this {
+ return this.set(0, 0, 0, 1);
+ }
+ lengthSq(): number {
+ return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
+ }
+ length(): number {
+ return Math.sqrt(this.lengthSq());
+ }
+ /** Set to the spherical interpolation of `qa` to `qb` at `t` (three.js). */
+ slerpQuaternions(qa: Quaternion, qb: Quaternion, t: number): this {
+ return this.copy(qa).slerp(qb, t);
+ }
equals(q: Quaternion): boolean {
return q._x === this._x && q._y === this._y && q._z === this._z && q._w === this._w;
}
@@ -289,8 +410,14 @@ export class Quaternion {
const x0 = Math.random(), r1 = Math.sqrt(1 - x0), r2 = Math.sqrt(x0);
return this.set(r1 * Math.sin(theta1), r1 * Math.cos(theta1), r2 * Math.sin(theta2), r2 * Math.cos(theta2));
}
- toArray(): [number, number, number, number] {
- return [this._x, this._y, this._z, this._w];
+ toArray(): [number, number, number, number];
+ toArray<T extends { [i: number]: number }>(array: T, offset?: number): T;
+ toArray(array: { [i: number]: number } = [], offset = 0): { [i: number]: number } {
+ array[offset] = this._x;
+ array[offset + 1] = this._y;
+ array[offset + 2] = this._z;
+ array[offset + 3] = this._w;
+ return array;
}
fromArray(a: ArrayLike<number>, o = 0): this {
return this.set(a[o], a[o + 1], a[o + 2], a[o + 3]);
@@ -331,26 +458,111 @@ export class Euler {
this._onChange();
return this;
}
- setFromQuaternion(q: Quaternion, notify = true): this {
- const m = new Matrix4().makeRotationFromQuaternion(q);
+ copy(euler: Euler): this {
+ return this.set(euler._x, euler._y, euler._z, euler._order);
+ }
+ clone(): Euler {
+ return new Euler(this._x, this._y, this._z, this._order);
+ }
+ equals(euler: Euler): boolean {
+ return euler._x === this._x && euler._y === this._y && euler._z === this._z && euler._order === this._order;
+ }
+ /** `[x, y, z, order?]`; a missing order keeps the current one, as three.js does. */
+ fromArray(array: ArrayLike<number | EulerOrder>): this {
+ const order = array[3] === undefined ? this._order : (array[3] as EulerOrder);
+ return this.set(array[0] as number, array[1] as number, array[2] as number, order);
+ }
+ toArray(array: Array<number | EulerOrder> = [], offset = 0): Array<number | EulerOrder> {
+ array[offset] = this._x;
+ array[offset + 1] = this._y;
+ array[offset + 2] = this._z;
+ array[offset + 3] = this._order;
+ return array;
+ }
+ setFromVector3(v: Vector3, order: EulerOrder = this._order): this {
+ return this.set(v.x, v.y, v.z, order);
+ }
+ /** The angles of the (unscaled) rotation in `m`, in any of the six orders (three.js r187). */
+ setFromRotationMatrix(m: Matrix4, order: EulerOrder = this._order, update = true): this {
const te = m.elements;
const clamp = (v: number) => Math.min(1, Math.max(-1, v));
const m11 = te[0], m12 = te[4], m13 = te[8];
- const m22 = te[5], m23 = te[9];
- const m32 = te[6], m33 = te[10];
- // Only XYZ is needed for the rotation<->quaternion sync; other orders go through Quaternion.setFromEuler.
- this._y = Math.asin(clamp(m13));
- if (Math.abs(m13) < 0.9999999) {
- this._x = Math.atan2(-m23, m33);
- this._z = Math.atan2(-m12, m11);
- } else {
- this._x = Math.atan2(m32, m22);
- this._z = 0;
+ const m21 = te[1], m22 = te[5], m23 = te[9];
+ const m31 = te[2], m32 = te[6], m33 = te[10];
+ switch (order) {
+ case "XYZ":
+ this._y = Math.asin(clamp(m13));
+ if (Math.abs(m13) < 0.9999999) {
+ this._x = Math.atan2(-m23, m33);
+ this._z = Math.atan2(-m12, m11);
+ } else {
+ this._x = Math.atan2(m32, m22);
+ this._z = 0;
+ }
+ break;
+ case "YXZ":
+ this._x = Math.asin(-clamp(m23));
+ if (Math.abs(m23) < 0.9999999) {
+ this._y = Math.atan2(m13, m33);
+ this._z = Math.atan2(m21, m22);
+ } else {
+ this._y = Math.atan2(-m31, m11);
+ this._z = 0;
+ }
+ break;
+ case "ZXY":
+ this._x = Math.asin(clamp(m32));
+ if (Math.abs(m32) < 0.9999999) {
+ this._y = Math.atan2(-m31, m33);
+ this._z = Math.atan2(-m12, m22);
+ } else {
+ this._y = 0;
+ this._z = Math.atan2(m21, m11);
+ }
+ break;
+ case "ZYX":
+ this._y = Math.asin(-clamp(m31));
+ if (Math.abs(m31) < 0.9999999) {
+ this._x = Math.atan2(m32, m33);
+ this._z = Math.atan2(m21, m11);
+ } else {
+ this._x = 0;
+ this._z = Math.atan2(-m12, m22);
+ }
+ break;
+ case "YZX":
+ this._z = Math.asin(clamp(m21));
+ if (Math.abs(m21) < 0.9999999) {
+ this._x = Math.atan2(-m23, m22);
+ this._y = Math.atan2(-m31, m11);
+ } else {
+ this._x = 0;
+ this._y = Math.atan2(m13, m33);
+ }
+ break;
+ case "XZY":
+ this._z = Math.asin(-clamp(m12));
+ if (Math.abs(m12) < 0.9999999) {
+ this._x = Math.atan2(m32, m22);
+ this._y = Math.atan2(m13, m11);
+ } else {
+ this._x = Math.atan2(-m23, m33);
+ this._y = 0;
+ }
+ break;
}
- this._order = "XYZ";
- if (notify) this._onChange();
+ this._order = order;
+ if (update) this._onChange();
return this;
}
+ /** The angles of `q` in `order` (default: this Euler's own order, which an object's rotation keeps). */
+ setFromQuaternion(q: Quaternion, order: EulerOrder = this._order, update = true): this {
+ return this.setFromRotationMatrix(new Matrix4().makeRotationFromQuaternion(q), order, update);
+ }
+ /** The same rotation, expressed in `newOrder` (three.js; may flip to an equivalent solution). */
+ reorder(newOrder: EulerOrder): this {
+ return this.setFromQuaternion(new Quaternion().setFromEuler(this), newOrder);
+ }
}
export class Matrix4 {
@@ -369,6 +581,11 @@ export class Matrix4 {
clone(): Matrix4 {
return new Matrix4().copy(this);
}
+ /** `m` as the upper 3x3, with no translation, as three.js does. */
+ setFromMatrix3(m: Matrix3): this {
+ const me = m.elements;
+ return this.set(me[0], me[3], me[6], 0, me[1], me[4], me[7], 0, me[2], me[5], me[8], 0, 0, 0, 0, 1);
+ }
compose(p: Vector3, q: Quaternion, s: Vector3): this {
return this.composeComponents(p.x, p.y, p.z, q.x, q.y, q.z, q.w, s.x, s.y, s.z);
}
@@ -424,6 +641,63 @@ export class Matrix4 {
te[2] = x.z; te[6] = y.z; te[10] = z.z;
return this;
}
+ /** Determinant of the upper 3x3 (rotation and scale) part. */
+ determinantAffine(): number {
+ const te = this.elements;
+ return te[0] * (te[5] * te[10] - te[9] * te[6])
+ - te[4] * (te[1] * te[10] - te[9] * te[2])
+ + te[8] * (te[1] * te[6] - te[5] * te[2]);
+ }
+ /** Sets the rotation part from three basis vectors and clears the translation, as three.js does. */
+ makeBasis(xAxis: Vector3, yAxis: Vector3, zAxis: Vector3): this {
+ return this.set(
+ xAxis.x, yAxis.x, zAxis.x, 0,
+ xAxis.y, yAxis.y, zAxis.y, 0,
+ xAxis.z, yAxis.z, zAxis.z, 0,
+ 0, 0, 0, 1,
+ );
+ }
+ /** The first three columns; the unit axes for a singular matrix, as three.js r187. */
+ extractBasis(xAxis: Vector3, yAxis: Vector3, zAxis: Vector3): this {
+ if (this.determinantAffine() === 0) {
+ xAxis.set(1, 0, 0);
+ yAxis.set(0, 1, 0);
+ zAxis.set(0, 0, 1);
+ return this;
+ }
+ const te = this.elements;
+ xAxis.set(te[0], te[1], te[2]);
+ yAxis.set(te[4], te[5], te[6]);
+ zAxis.set(te[8], te[9], te[10]);
+ return this;
+ }
+ /** `m`'s rotation with scale and translation removed; identity for a singular `m`, as three.js r187. */
+ extractRotation(m: Matrix4): this {
+ if (m.determinantAffine() === 0) return this.identity();
+ const me = m.elements;
+ const scaleX = 1 / Math.hypot(me[0], me[1], me[2]);
+ const scaleY = 1 / Math.hypot(me[4], me[5], me[6]);
+ const scaleZ = 1 / Math.hypot(me[8], me[9], me[10]);
+ this.elements = [
+ me[0] * scaleX, me[1] * scaleX, me[2] * scaleX, 0,
+ me[4] * scaleY, me[5] * scaleY, me[6] * scaleY, 0,
+ me[8] * scaleZ, me[9] * scaleZ, me[10] * scaleZ, 0,
+ 0, 0, 0, 1,
+ ];
+ return this;
+ }
+ /** Rotation of `angle` radians about the unit vector `axis`. */
+ makeRotationAxis(axis: Vector3, angle: number): this {
+ const c = Math.cos(angle), s = Math.sin(angle), t = 1 - c;
+ const x = axis.x, y = axis.y, z = axis.z;
+ const tx = t * x, ty = t * y;
+ return this.set(
+ tx * x + c, tx * y - s * z, tx * z + s * y, 0,
+ tx * y + s * z, ty * y + c, ty * z - s * x, 0,
+ tx * z - s * y, ty * z + s * x, t * z * z + c, 0,
+ 0, 0, 0, 1,
+ );
+ }
decompose(p: Vector3, q: Quaternion, s: Vector3): this {
const te = this.elements;
p.set(te[12], te[13], te[14]);
@@ -462,6 +736,30 @@ export class Matrix4 {
n44 * (-n13 * n22 * n31 - n11 * n23 * n32 + n11 * n22 * n33 + n13 * n21 * n32 - n12 * n21 * n33 + n12 * n23 * n31)
);
}
+ /** Multiplies every element by `s`, as three.js does. */
+ multiplyScalar(s: number): this {
+ const te = this.elements;
+ for (let k = 0; k < 16; k++) te[k] *= s;
+ return this;
+ }
+ /** Scales the first three columns by `v`, as three.js does. */
+ scale(v: Vector3): this {
+ const te = this.elements;
+ const x = v.x, y = v.y, z = v.z;
+ te[0] *= x; te[4] *= y; te[8] *= z;
+ te[1] *= x; te[5] *= y; te[9] *= z;
+ te[2] *= x; te[6] *= y; te[10] *= z;
+ te[3] *= x; te[7] *= y; te[11] *= z;
+ return this;
+ }
+ /** The largest of the three basis-column lengths. */
+ getMaxScaleOnAxis(): number {
+ const te = this.elements;
+ const scaleXSq = te[0] * te[0] + te[1] * te[1] + te[2] * te[2];
+ const scaleYSq = te[4] * te[4] + te[5] * te[5] + te[6] * te[6];
+ const scaleZSq = te[8] * te[8] + te[9] * te[9] + te[10] * te[10];
+ return Math.sqrt(Math.max(scaleXSq, scaleYSq, scaleZSq));
+ }
/** Transpose in place, as three.js does. */
transpose(): this {
const te = this.elements;
@@ -550,8 +848,115 @@ export class Matrix4 {
}
}
+/** A 3x3 matrix, column-major `elements`, as three.js. */
+export class Matrix3 {
+ readonly isMatrix3 = true;
+ elements: number[];
+ /** Row-major arguments, as three.js. */
+ constructor(n11?: number, n12?: number, n13?: number, n21?: number, n22?: number, n23?: number, n31?: number, n32?: number, n33?: number) {
+ this.elements = [1, 0, 0, 0, 1, 0, 0, 0, 1];
+ if (n11 !== undefined) this.set(n11, n12!, n13!, n21!, n22!, n23!, n31!, n32!, n33!);
+ }
+ /** Row-major arguments, as three.js. */
+ set(n11: number, n12: number, n13: number, n21: number, n22: number, n23: number, n31: number, n32: number, n33: number): this {
+ const te = this.elements;
+ te[0] = n11; te[1] = n21; te[2] = n31;
+ te[3] = n12; te[4] = n22; te[5] = n32;
+ te[6] = n13; te[7] = n23; te[8] = n33;
+ return this;
+ }
+ identity(): this {
+ return this.set(1, 0, 0, 0, 1, 0, 0, 0, 1);
+ }
+ copy(m: Matrix3): this {
+ for (let k = 0; k < 9; k++) this.elements[k] = m.elements[k];
+ return this;
+ }
+ clone(): Matrix3 {
+ return new Matrix3().copy(this);
+ }
+ /** The upper 3x3 of `m`. */
+ setFromMatrix4(m: Matrix4): this {
+ const me = m.elements;
+ return this.set(me[0], me[4], me[8], me[1], me[5], me[9], me[2], me[6], me[10]);
+ }
+ multiply(m: Matrix3): this {
+ return this.multiplyMatrices(this, m);
+ }
+ premultiply(m: Matrix3): this {
+ return this.multiplyMatrices(m, this);
+ }
+ multiplyMatrices(a: Matrix3, b: Matrix3): this {
+ const ae = a.elements, be = b.elements;
+ const a11 = ae[0], a12 = ae[3], a13 = ae[6];
+ const a21 = ae[1], a22 = ae[4], a23 = ae[7];
+ const a31 = ae[2], a32 = ae[5], a33 = ae[8];
+ const b11 = be[0], b12 = be[3], b13 = be[6];
+ const b21 = be[1], b22 = be[4], b23 = be[7];
+ const b31 = be[2], b32 = be[5], b33 = be[8];
+ return this.set(
+ a11 * b11 + a12 * b21 + a13 * b31, a11 * b12 + a12 * b22 + a13 * b32, a11 * b13 + a12 * b23 + a13 * b33,
+ a21 * b11 + a22 * b21 + a23 * b31, a21 * b12 + a22 * b22 + a23 * b32, a21 * b13 + a22 * b23 + a23 * b33,
+ a31 * b11 + a32 * b21 + a33 * b31, a31 * b12 + a32 * b22 + a33 * b32, a31 * b13 + a32 * b23 + a33 * b33,
+ );
+ }
+ multiplyScalar(s: number): this {
+ for (let k = 0; k < 9; k++) this.elements[k] *= s;
+ return this;
+ }
+ determinant(): number {
+ const [a, b, c, d, e, f, g, h, i] = this.elements;
+ return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g;
+ }
+ /** The inverse (all zeros for a singular matrix, as three.js). */
+ invert(): this {
+ const [n11, n21, n31, n12, n22, n32, n13, n23, n33] = this.elements;
+ const t11 = n33 * n22 - n32 * n23, t12 = n32 * n13 - n33 * n12, t13 = n23 * n12 - n22 * n13;
+ const det = n11 * t11 + n21 * t12 + n31 * t13;
+ if (det === 0) return this.set(0, 0, 0, 0, 0, 0, 0, 0, 0);
+ const d = 1 / det;
+ const te = this.elements;
+ te[0] = t11 * d;
+ te[1] = (n31 * n23 - n33 * n21) * d;
+ te[2] = (n32 * n21 - n31 * n22) * d;
+ te[3] = t12 * d;
+ te[4] = (n33 * n11 - n31 * n13) * d;
+ te[5] = (n31 * n12 - n32 * n11) * d;
+ te[6] = t13 * d;
+ te[7] = (n21 * n13 - n23 * n11) * d;
+ te[8] = (n22 * n11 - n21 * n12) * d;
+ return this;
+ }
+ /** Transpose in place, as three.js does. */
+ transpose(): this {
+ const m = this.elements;
+ let tmp: number;
+ tmp = m[1]; m[1] = m[3]; m[3] = tmp;
+ tmp = m[2]; m[2] = m[6]; m[6] = tmp;
+ tmp = m[5]; m[5] = m[7]; m[7] = tmp;
+ return this;
+ }
+ /** Inverse transpose of `m`'s upper 3x3: transforms normals under non-uniform scale. */
+ getNormalMatrix(m: Matrix4): this {
+ return this.setFromMatrix4(m).invert().transpose();
+ }
+ equals(m: Matrix3): boolean {
+ return this.elements.every((v, k) => v === m.elements[k]);
+ }
+ /** Column-major, as `elements`. */
+ fromArray(a: ArrayLike<number>, offset = 0): this {
+ for (let k = 0; k < 9; k++) this.elements[k] = a[k + offset];
+ return this;
+ }
+ toArray<T extends { [k: number]: number } = number[]>(a: T = [] as unknown as T, offset = 0): T {
+ for (let k = 0; k < 9; k++) a[k + offset] = this.elements[k];
+ return a;
+ }
+}
+
/** Colors are stored in linear sRGB (Rec.709 primaries), like three.js with ColorManagement enabled. */
export class Color {
+ readonly isColor = true;
r = 1;
g = 1;
b = 1;
@@ -586,6 +991,13 @@ export class Color {
if (named !== undefined) return this.setHex(named);
throw new Error(`unsupported color: ${style}`);
}
+ /** A CSS color keyword (sRGB) such as `"skyblue"`; unknown names warn and leave the color unchanged, as three.js. */
+ setColorName(style: string): this {
+ const hex = NAMED_COLORS[style.toLowerCase()];
+ if (hex !== undefined) return this.setHex(hex);
+ console.warn(`THREE.Color: Unknown color ${style}`);
+ return this;
+ }
/** Linear components. */
setRGB(r: number, g: number, b: number): this {
this.r = r; this.g = g; this.b = b;
@@ -595,12 +1007,39 @@ export class Color {
this.r *= s; this.g *= s; this.b *= s;
return this;
}
+ /** All three linear components to `scalar`. */
+ setScalar(scalar: number): this {
+ return this.setRGB(scalar, scalar, scalar);
+ }
+ /** Linear components from a vector's x, y, z. */
+ setFromVector3(v: { x: number; y: number; z: number }): this {
+ return this.setRGB(v.x, v.y, v.z);
+ }
+ /** Multiplies the linear components by a column-major 3x3 matrix, as three.js. */
+ applyMatrix3(m: { elements: ArrayLike<number> }): this {
+ const { r, g, b } = this, e = m.elements;
+ return this.setRGB(e[0] * r + e[3] * g + e[6] * b, e[1] * r + e[4] * g + e[7] * b, e[2] * r + e[5] * g + e[8] * b);
+ }
clone(): Color {
return new Color().setRGB(this.r, this.g, this.b);
}
copy(c: Color): this {
return this.setRGB(c.r, c.g, c.b);
}
+ /** Copies `c`, decoding its components from sRGB to linear. */
+ copySRGBToLinear(c: Color): this {
+ return this.setRGB(srgbToLinear(c.r), srgbToLinear(c.g), srgbToLinear(c.b));
+ }
+ /** Copies `c`, encoding its components from linear to sRGB. */
+ copyLinearToSRGB(c: Color): this {
+ return this.setRGB(linearToSrgb(c.r), linearToSrgb(c.g), linearToSrgb(c.b));
+ }
+ convertSRGBToLinear(): this {
+ return this.copySRGBToLinear(this);
+ }
+ convertLinearToSRGB(): this {
+ return this.copyLinearToSRGB(this);
+ }
/** Hue, saturation, lightness in 0..1, sRGB-encoded as CSS / three.js (converted to linear). */
setHSL(h: number, s: number, l: number): this {
h = ((h % 1) + 1) % 1;
@@ -642,6 +1081,17 @@ export class Color {
multiply(c: Color): this {
return this.setRGB(this.r * c.r, this.g * c.g, this.b * c.b);
}
+ /** Sets this color to `color1 + color2`. */
+ addColors(color1: Color, color2: Color): this {
+ return this.setRGB(color1.r + color2.r, color1.g + color2.g, color1.b + color2.b);
+ }
+ addScalar(s: number): this {
+ return this.setRGB(this.r + s, this.g + s, this.b + s);
+ }
+ /** Subtracts `c`, clamping each component at 0, as three.js. */
+ sub(c: Color): this {
+ return this.setRGB(Math.max(0, this.r - c.r), Math.max(0, this.g - c.g), Math.max(0, this.b - c.b));
+ }
/** A CSS colour string, as three.js. */
getStyle(): string {
return `#${this.getHex().toString(16).padStart(6, "0")}`;
@@ -654,6 +1104,28 @@ export class Color {
const k = (v: number) => Math.round(Math.min(Math.max(linearToSrgb(v), 0), 1) * 255);
return (k(this.r) << 16) | (k(this.g) << 8) | k(this.b);
}
+ /** `getHex` as six lowercase hex digits, without `#`. */
+ getHexString(): string {
+ return this.getHex().toString(16).padStart(6, "0");
+ }
+ /** The linear components, into `target`. */
+ getRGB<T extends { r: number; g: number; b: number }>(target: T): T {
+ target.r = this.r; target.g = this.g; target.b = this.b;
+ return target;
+ }
+ /** Linear components from item `index` of a 3-component attribute. */
+ fromBufferAttribute(attribute: { getX(i: number): number; getY(i: number): number; getZ(i: number): number }, index: number): this {
+ return this.setRGB(attribute.getX(index), attribute.getY(index), attribute.getZ(index));
+ }
+ /** The sRGB hex, as three.js serializes a color. */
+ toJSON(): number {
+ return this.getHex();
+ }
+ *[Symbol.iterator](): Generator<number, void, undefined> {
+ yield this.r;
+ yield this.g;
+ yield this.b;
+ }
fromArray(a: ArrayLike<number>, offset = 0): this {
return this.setRGB(a[offset], a[offset + 1], a[offset + 2]);
}
@@ -666,6 +1138,10 @@ export class Color {
return a;
}
/** Color temperature in Kelvin -> linear sRGB (normalized to max component 1). */
+ /** CSS color keywords to sRGB hex, as three.js `Color.NAMES`. */
+ static get NAMES(): Readonly<Record<string, number>> {
+ return NAMED_COLORS;
+ }
static fromTemperature(kelvin: number): Color {
return new Color().setRGB(...kelvinToLinearRGB(kelvin));
}
@@ -716,6 +1192,110 @@ export class Vector2 {
multiplyScalar(s: number): this {
return this.set(this.x * s, this.y * s);
}
+ // Component-wise arithmetic and plane geometry, as three.js r187 has them.
+ setX(x: number): this {
+ return this.set(x, this.y);
+ }
+ setY(y: number): this {
+ return this.set(this.x, y);
+ }
+ setComponent(index: number, value: number): this {
+ if (index === 0) this.x = value;
+ else if (index === 1) this.y = value;
+ else throw new RangeError(`index is out of range: ${index}`);
+ return this;
+ }
+ getComponent(index: number): number {
+ if (index === 0) return this.x;
+ if (index === 1) return this.y;
+ throw new RangeError(`index is out of range: ${index}`);
+ }
+ addScalar(s: number): this {
+ return this.set(this.x + s, this.y + s);
+ }
+ addVectors(a: Vector2, b: Vector2): this {
+ return this.set(a.x + b.x, a.y + b.y);
+ }
+ addScaledVector(v: Vector2, s: number): this {
+ return this.set(this.x + v.x * s, this.y + v.y * s);
+ }
+ subScalar(s: number): this {
+ return this.set(this.x - s, this.y - s);
+ }
+ subVectors(a: Vector2, b: Vector2): this {
+ return this.set(a.x - b.x, a.y - b.y);
+ }
+ multiply(v: Vector2): this {
+ return this.set(this.x * v.x, this.y * v.y);
+ }
+ divide(v: Vector2): this {
+ return this.set(this.x / v.x, this.y / v.y);
+ }
+ divideScalar(s: number): this {
+ return this.multiplyScalar(1 / s);
+ }
+ min(v: Vector2): this {
+ return this.set(Math.min(this.x, v.x), Math.min(this.y, v.y));
+ }
+ max(v: Vector2): this {
+ return this.set(Math.max(this.x, v.x), Math.max(this.y, v.y));
+ }
+ /** Assumes min <= max component-wise, as three.js does. */
+ clamp(min: Vector2, max: Vector2): this {
+ return this.set(Math.max(min.x, Math.min(max.x, this.x)), Math.max(min.y, Math.min(max.y, this.y)));
+ }
+ clampScalar(minVal: number, maxVal: number): this {
+ return this.set(Math.max(minVal, Math.min(maxVal, this.x)), Math.max(minVal, Math.min(maxVal, this.y)));
+ }
+ clampLength(min: number, max: number): this {
+ const l = this.length();
+ return this.divideScalar(l || 1).multiplyScalar(Math.max(min, Math.min(max, l)));
+ }
+ floor(): this {
+ return this.set(Math.floor(this.x), Math.floor(this.y));
+ }
+ ceil(): this {
+ return this.set(Math.ceil(this.x), Math.ceil(this.y));
+ }
+ round(): this {
+ return this.set(Math.round(this.x), Math.round(this.y));
+ }
+ negate(): this {
+ return this.set(-this.x, -this.y);
+ }
+ lengthSq(): number {
+ return this.x * this.x + this.y * this.y;
+ }
+ manhattanLength(): number {
+ return Math.abs(this.x) + Math.abs(this.y);
+ }
+ setLength(length: number): this {
+ return this.normalize().multiplyScalar(length);
+ }
+ /** The angle from the +x axis, in [0, 2π). */
+ angle(): number {
+ return Math.atan2(-this.y, -this.x) + Math.PI;
+ }
+ angleTo(v: Vector2): number {
+ const denominator = Math.sqrt(this.lengthSq() * v.lengthSq());
+ if (denominator === 0) return Math.PI / 2;
+ return Math.acos(Math.max(-1, Math.min(1, this.dot(v) / denominator)));
+ }
+ distanceToSquared(v: Vector2): number {
+ const dx = this.x - v.x, dy = this.y - v.y;
+ return dx * dx + dy * dy;
+ }
+ manhattanDistanceTo(v: Vector2): number {
+ return Math.abs(this.x - v.x) + Math.abs(this.y - v.y);
+ }
+ lerpVectors(v1: Vector2, v2: Vector2, alpha: number): this {
+ return this.set(v1.x + (v2.x - v1.x) * alpha, v1.y + (v2.y - v1.y) * alpha);
+ }
+ rotateAround(center: Vector2, angle: number): this {
+ const c = Math.cos(angle), s = Math.sin(angle);
+ const x = this.x - center.x, y = this.y - center.y;
+ return this.set(x * c - y * s + center.x, x * s + y * c + center.y);
+ }
roundToZero(): this {
return this.set(Math.trunc(this.x), Math.trunc(this.y));
}
@@ -729,8 +1309,8 @@ export class Vector2 {
return Math.hypot(this.x, this.y);
}
normalize(): this {
- const l = this.length() || 1;
- return this.set(this.x / l, this.y / l);
+ // Through divideScalar (a multiply by 1 / length), as three.js does, so normalize and setLength round alike.
+ return this.divideScalar(this.length() || 1);
}
distanceTo(v: Vector2): number {
return Math.hypot(this.x - v.x, this.y - v.y);
@@ -818,6 +1398,32 @@ export class Box3 {
this.min.y <= b.min.y && b.max.y <= this.max.y &&
this.min.z <= b.min.z && b.max.z <= this.max.z;
}
+ /** `point` clamped into this box, written to `target` (three.js). */
+ clampPoint(point: Vector3, target = new Vector3()): Vector3 {
+ const { min, max } = this;
+ return target.set(Math.max(min.x, Math.min(max.x, point.x)), Math.max(min.y, Math.min(max.y, point.y)), Math.max(min.z, Math.min(max.z, point.z)));
+ }
+ /** The distance from `point` to this box: 0 inside (three.js). */
+ distanceToPoint(point: Vector3): number {
+ return this.clampPoint(point).distanceTo(point);
+ }
+ /** Whether `sphere` touches this box (three.js). */
+ intersectsSphere(sphere: Sphere): boolean {
+ const c = this.clampPoint(sphere.center);
+ const dx = c.x - sphere.center.x, dy = c.y - sphere.center.y, dz = c.z - sphere.center.z;
+ return dx * dx + dy * dy + dz * dz <= sphere.radius * sphere.radius;
+ }
+ /** The sphere around this box; an empty box gives an empty sphere (three.js). */
+ getBoundingSphere(target = new Sphere()): Sphere {
+ if (this.isEmpty()) {
+ target.center.set(0, 0, 0);
+ target.radius = -1;
+ } else {
+ this.getCenter(target.center);
+ target.radius = this.getSize().length() * 0.5;
+ }
+ return target;
+ }
intersectsBox(b: Box3): boolean {
return b.max.x >= this.min.x && b.min.x <= this.max.x && b.max.y >= this.min.y && b.min.y <= this.max.y && b.max.z >= this.min.z && b.min.z <= this.max.z;
}
@@ -831,12 +1437,61 @@ export class Box3 {
/** A sphere (three.js Sphere): bounds. */
export class Sphere {
+ readonly isSphere = true;
center: Vector3;
radius: number;
constructor(center = new Vector3(), radius = -1) {
this.center = center;
this.radius = radius;
}
+ set(center: Vector3, radius: number): this {
+ this.center.copy(center);
+ this.radius = radius;
+ return this;
+ }
+ copy(sphere: Sphere): this {
+ return this.set(sphere.center, sphere.radius);
+ }
+ /** A negative radius is empty; a zero radius is a point (three.js). */
+ isEmpty(): boolean {
+ return this.radius < 0;
+ }
+ makeEmpty(): this {
+ this.center.set(0, 0, 0);
+ this.radius = -1;
+ return this;
+ }
+ containsPoint(point: Vector3): boolean {
+ const dx = point.x - this.center.x, dy = point.y - this.center.y, dz = point.z - this.center.z;
+ return dx * dx + dy * dy + dz * dz <= this.radius * this.radius;
+ }
+ /** Signed: negative inside the sphere (three.js). */
+ distanceToPoint(point: Vector3): number {
+ return point.distanceTo(this.center) - this.radius;
+ }
+ intersectsSphere(sphere: Sphere): boolean {
+ const r = this.radius + sphere.radius;
+ const dx = sphere.center.x - this.center.x, dy = sphere.center.y - this.center.y, dz = sphere.center.z - this.center.z;
+ return dx * dx + dy * dy + dz * dz <= r * r;
+ }
+ /** The centre transformed by `m`, the radius scaled by its largest axis scale (three.js). */
+ applyMatrix4(m: Matrix4): this {
+ const e = m.elements;
+ const sx = e[0] * e[0] + e[1] * e[1] + e[2] * e[2];
+ const sy = e[4] * e[4] + e[5] * e[5] + e[6] * e[6];
+ const sz = e[8] * e[8] + e[9] * e[9] + e[10] * e[10];
+ this.center.applyMatrix4(m);
+ this.radius *= Math.sqrt(Math.max(sx, sy, sz));
+ return this;
+ }
+ translate(offset: Vector3): this {
+ this.center.add(offset);
+ return this;
+ }
+ equals(sphere: Sphere): boolean {
+ const a = this.center, b = sphere.center;
+ return a.x === b.x && a.y === b.y && a.z === b.z && sphere.radius === this.radius;
+ }
setFromArray(a: ArrayLike<number>): this {
const b = new Box3().setFromArray(a);
b.getCenter(this.center);
@@ -925,6 +1580,115 @@ export class Ray {
const t = (e2x * qx + e2y * qy + e2z * qz) * inv;
return t >= 0 ? { t, u, v } : null;
}
+ /** The distance along the ray to `plane` (0 if the origin lies on it), or null if the ray does not reach it. */
+ distanceToPlane(plane: Plane): number | null {
+ const denom = plane.normal.dot(this.direction);
+ if (denom === 0) return plane.distanceToPoint(this.origin) === 0 ? 0 : null;
+ const t = -(this.origin.dot(plane.normal) + plane.constant) / denom;
+ return t >= 0 ? t : null;
+ }
+ /** Where the ray meets `plane`, or null. */
+ intersectPlane(plane: Plane, target = new Vector3()): Vector3 | null {
+ const t = this.distanceToPlane(plane);
+ return t === null ? null : this.at(t, target);
+ }
+ intersectsPlane(plane: Plane): boolean {
+ const d = plane.distanceToPoint(this.origin);
+ if (d === 0) return true;
+ return plane.normal.dot(this.direction) * d < 0;
+ }
+}
+
+/** An infinite plane: the points p with `normal · p + constant = 0` (three.js's Plane). */
+export class Plane {
+ normal: Vector3;
+ constant: number;
+ constructor(normal = new Vector3(1, 0, 0), constant = 0) {
+ this.normal = normal;
+ this.constant = constant;
+ }
+ set(normal: Vector3, constant: number): this {
+ this.normal.copy(normal);
+ this.constant = constant;
+ return this;
+ }
+ setComponents(x: number, y: number, z: number, w: number): this {
+ this.normal.set(x, y, z);
+ this.constant = w;
+ return this;
+ }
+ setFromNormalAndCoplanarPoint(normal: Vector3, point: Vector3): this {
+ this.normal.copy(normal);
+ this.constant = -point.dot(this.normal);
+ return this;
+ }
+ /** The plane through a, b and c, facing the side from which they run counter-clockwise. */
+ setFromCoplanarPoints(a: Vector3, b: Vector3, c: Vector3): this {
+ const n = new Vector3().subVectors(c, b).cross(new Vector3().subVectors(a, b)).normalize();
+ return this.setFromNormalAndCoplanarPoint(n, a);
+ }
+ copy(plane: Plane): this {
+ this.normal.copy(plane.normal);
+ this.constant = plane.constant;
+ return this;
+ }
+ clone(): Plane {
+ return new Plane().copy(this);
+ }
+ /** Scales normal and constant so that the normal has unit length. */
+ normalize(): this {
+ const inv = 1 / this.normal.length();
+ this.normal.multiplyScalar(inv);
+ this.constant *= inv;
+ return this;
+ }
+ negate(): this {
+ this.constant *= -1;
+ this.normal.multiplyScalar(-1);
+ return this;
+ }
+ /** Signed distance (positive on the side the normal points to). */
+ distanceToPoint(point: Vector3): number {
+ return this.normal.dot(point) + this.constant;
+ }
+ distanceToSphere(sphere: Sphere): number {
+ return this.distanceToPoint(sphere.center) - sphere.radius;
+ }
+ projectPoint(point: Vector3, target = new Vector3()): Vector3 {
+ return target.copy(point).addScaledVector(this.normal, -this.distanceToPoint(point));
+ }
+ coplanarPoint(target = new Vector3()): Vector3 {
+ return target.copy(this.normal).multiplyScalar(-this.constant);
+ }
+ intersectsSphere(sphere: Sphere): boolean {
+ return Math.abs(this.distanceToPoint(sphere.center)) <= sphere.radius;
+ }
+ intersectsBox(box: Box3): boolean {
+ const n = this.normal;
+ let min = 0, max = 0;
+ for (const k of ["x", "y", "z"] as const) {
+ const lo = n[k] * box.min[k], hi = n[k] * box.max[k];
+ min += Math.min(lo, hi);
+ max += Math.max(lo, hi);
+ }
+ return min <= -this.constant && max >= -this.constant;
+ }
+ /** The plane moved by `m`; its normal goes through m's normal matrix (the inverse transpose of its upper 3 x 3). */
+ applyMatrix4(m: Matrix4): this {
+ const p = this.coplanarPoint().applyMatrix4(m);
+ const e = m.clone().invert().elements;
+ const { x, y, z } = this.normal;
+ this.normal.set(e[0] * x + e[1] * y + e[2] * z, e[4] * x + e[5] * y + e[6] * z, e[8] * x + e[9] * y + e[10] * z).normalize();
+ this.constant = -p.dot(this.normal);
+ return this;
+ }
+ translate(offset: Vector3): this {
+ this.constant -= offset.dot(this.normal);
+ return this;
+ }
+ equals(plane: Plane): boolean {
+ return plane.normal.x === this.normal.x && plane.normal.y === this.normal.y && plane.normal.z === this.normal.z && plane.constant === this.constant;
+ }
}
export function srgbToLinear(c: number): number {
@@ -956,10 +1720,37 @@ export function kelvinToLinearRGB(T: number): [number, number, number] {
return [Math.max(r, 0) / m, Math.max(g, 0) / m, Math.max(b, 0) / m];
}
+/** CSS color keywords, as three.js `Color.NAMES` (sRGB hex). */
const NAMED_COLORS: Record<string, number> = {
- white: 0xffffff, black: 0x000000, red: 0xff0000, green: 0x008000, lime: 0x00ff00, blue: 0x0000ff,
- yellow: 0xffff00, cyan: 0x00ffff, magenta: 0xff00ff, orange: 0xffa500, gray: 0x808080, grey: 0x808080,
- gold: 0xffd700, silver: 0xc0c0c0, purple: 0x800080, pink: 0xffc0cb, brown: 0xa52a2a, skyblue: 0x87ceeb,
+ aliceblue: 0xf0f8ff, antiquewhite: 0xfaebd7, aqua: 0x00ffff, aquamarine: 0x7fffd4, azure: 0xf0ffff, beige: 0xf5f5dc,
+ bisque: 0xffe4c4, black: 0x000000, blanchedalmond: 0xffebcd, blue: 0x0000ff, blueviolet: 0x8a2be2, brown: 0xa52a2a,
+ burlywood: 0xdeb887, cadetblue: 0x5f9ea0, chartreuse: 0x7fff00, chocolate: 0xd2691e, coral: 0xff7f50,
+ cornflowerblue: 0x6495ed, cornsilk: 0xfff8dc, crimson: 0xdc143c, cyan: 0x00ffff, darkblue: 0x00008b,
+ darkcyan: 0x008b8b, darkgoldenrod: 0xb8860b, darkgray: 0xa9a9a9, darkgreen: 0x006400, darkgrey: 0xa9a9a9,
+ darkkhaki: 0xbdb76b, darkmagenta: 0x8b008b, darkolivegreen: 0x556b2f, darkorange: 0xff8c00, darkorchid: 0x9932cc,
+ darkred: 0x8b0000, darksalmon: 0xe9967a, darkseagreen: 0x8fbc8f, darkslateblue: 0x483d8b, darkslategray: 0x2f4f4f,
+ darkslategrey: 0x2f4f4f, darkturquoise: 0x00ced1, darkviolet: 0x9400d3, deeppink: 0xff1493, deepskyblue: 0x00bfff,
+ dimgray: 0x696969, dimgrey: 0x696969, dodgerblue: 0x1e90ff, firebrick: 0xb22222, floralwhite: 0xfffaf0,
+ forestgreen: 0x228b22, fuchsia: 0xff00ff, gainsboro: 0xdcdcdc, ghostwhite: 0xf8f8ff, gold: 0xffd700,
+ goldenrod: 0xdaa520, gray: 0x808080, green: 0x008000, greenyellow: 0xadff2f, grey: 0x808080, honeydew: 0xf0fff0,
+ hotpink: 0xff69b4, indianred: 0xcd5c5c, indigo: 0x4b0082, ivory: 0xfffff0, khaki: 0xf0e68c, lavender: 0xe6e6fa,
+ lavenderblush: 0xfff0f5, lawngreen: 0x7cfc00, lemonchiffon: 0xfffacd, lightblue: 0xadd8e6, lightcoral: 0xf08080,
+ lightcyan: 0xe0ffff, lightgoldenrodyellow: 0xfafad2, lightgray: 0xd3d3d3, lightgreen: 0x90ee90, lightgrey: 0xd3d3d3,
+ lightpink: 0xffb6c1, lightsalmon: 0xffa07a, lightseagreen: 0x20b2aa, lightskyblue: 0x87cefa,
+ lightslategray: 0x778899, lightslategrey: 0x778899, lightsteelblue: 0xb0c4de, lightyellow: 0xffffe0, lime: 0x00ff00,
+ limegreen: 0x32cd32, linen: 0xfaf0e6, magenta: 0xff00ff, maroon: 0x800000, mediumaquamarine: 0x66cdaa,
+ mediumblue: 0x0000cd, mediumorchid: 0xba55d3, mediumpurple: 0x9370db, mediumseagreen: 0x3cb371,
+ mediumslateblue: 0x7b68ee, mediumspringgreen: 0x00fa9a, mediumturquoise: 0x48d1cc, mediumvioletred: 0xc71585,
+ midnightblue: 0x191970, mintcream: 0xf5fffa, mistyrose: 0xffe4e1, moccasin: 0xffe4b5, navajowhite: 0xffdead,
+ navy: 0x000080, oldlace: 0xfdf5e6, olive: 0x808000, olivedrab: 0x6b8e23, orange: 0xffa500, orangered: 0xff4500,
+ orchid: 0xda70d6, palegoldenrod: 0xeee8aa, palegreen: 0x98fb98, paleturquoise: 0xafeeee, palevioletred: 0xdb7093,
+ papayawhip: 0xffefd5, peachpuff: 0xffdab9, peru: 0xcd853f, pink: 0xffc0cb, plum: 0xdda0dd, powderblue: 0xb0e0e6,
+ purple: 0x800080, rebeccapurple: 0x663399, red: 0xff0000, rosybrown: 0xbc8f8f, royalblue: 0x4169e1,
+ saddlebrown: 0x8b4513, salmon: 0xfa8072, sandybrown: 0xf4a460, seagreen: 0x2e8b57, seashell: 0xfff5ee,
+ sienna: 0xa0522d, silver: 0xc0c0c0, skyblue: 0x87ceeb, slateblue: 0x6a5acd, slategray: 0x708090,
+ slategrey: 0x708090, snow: 0xfffafa, springgreen: 0x00ff7f, steelblue: 0x4682b4, tan: 0xd2b48c, teal: 0x008080,
+ thistle: 0xd8bfd8, tomato: 0xff6347, turquoise: 0x40e0d0, violet: 0xee82ee, wheat: 0xf5deb3, white: 0xffffff,
+ whitesmoke: 0xf5f5f5, yellow: 0xffff00, yellowgreen: 0x9acd32,
};
export const MathUtils = {
@@ -970,4 +1761,76 @@ export const MathUtils = {
clamp: (v: number, lo: number, hi: number) => Math.min(hi, Math.max(lo, v)),
euclideanModulo: (n: number, m: number) => ((n % m) + m) % m,
lerp: (a: number, b: number, t: number) => a + (b - a) * t,
+ /** Maps `x` from the range [a1, a2] to [b1, b2]. */
+ mapLinear: (x: number, a1: number, a2: number, b1: number, b2: number) => b1 + ((x - a1) * (b2 - b1)) / (a2 - a1),
+ /** The fraction of `value` between `x` and `y`; 0 when the range is empty. */
+ inverseLerp: (x: number, y: number, value: number) => (x !== y ? (value - x) / (y - x) : 0),
+ /** Frame-rate independent damping towards `y` (`lambda` per second, `dt` in seconds). */
+ damp: (x: number, y: number, lambda: number, dt: number) => x + (y - x) * (1 - Math.exp(-lambda * dt)),
+ pingpong: (x: number, length = 1) => length - Math.abs((((x % (length * 2)) + length * 2) % (length * 2)) - length),
+ smoothstep(x: number, min: number, max: number): number {
+ if (x <= min) return 0;
+ if (x >= max) return 1;
+ x = (x - min) / (max - min);
+ return x * x * (3 - 2 * x);
+ },
+ smootherstep(x: number, min: number, max: number): number {
+ if (x <= min) return 0;
+ if (x >= max) return 1;
+ x = (x - min) / (max - min);
+ return x * x * x * (x * (x * 6 - 15) + 10);
+ },
+ /** A random integer in [low, high]. */
+ randInt: (low: number, high: number) => low + Math.floor(Math.random() * (high - low + 1)),
+ /** A random float in [low, high). */
+ randFloat: (low: number, high: number) => low + Math.random() * (high - low),
+ /** A random float in (-range / 2, range / 2]. */
+ randFloatSpread: (range: number) => range * (0.5 - Math.random()),
+ /** Deterministic pseudo-random float in [0, 1) (Mulberry32); passing `s` reseeds. */
+ seededRandom(s?: number): number {
+ if (s !== undefined) seed = s;
+ let t = (seed += 0x6d2b79f5);
+ t = Math.imul(t ^ (t >>> 15), t | 1);
+ t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
+ },
+ /** An RFC 4122 version 4 UUID, lowercase. */
+ generateUUID(): string {
+ const d0 = (Math.random() * 0xffffffff) | 0, d1 = (Math.random() * 0xffffffff) | 0;
+ const d2 = (Math.random() * 0xffffffff) | 0, d3 = (Math.random() * 0xffffffff) | 0;
+ const h = (v: number) => HEX[v & 0xff];
+ return (
+ h(d0) + h(d0 >> 8) + h(d0 >> 16) + h(d0 >> 24) + "-" + h(d1) + h(d1 >> 8) + "-" +
+ h(((d1 >> 16) & 0x0f) | 0x40) + h(d1 >> 24) + "-" + h((d2 & 0x3f) | 0x80) + h(d2 >> 8) + "-" +
+ h(d2 >> 16) + h(d2 >> 24) + h(d3) + h(d3 >> 8) + h(d3 >> 16) + h(d3 >> 24)
+ );
+ },
+ isPowerOfTwo: (value: number) => (value & (value - 1)) === 0 && value !== 0,
+ ceilPowerOfTwo: (value: number) => Math.pow(2, Math.ceil(Math.log(value) / Math.LN2)),
+ floorPowerOfTwo: (value: number) => Math.pow(2, Math.floor(Math.log(value) / Math.LN2)),
+ /** A float in [0, 1] (or [-1, 1]) as the normalized integer `array`'s component type stores. */
+ normalize(value: number, array: ArrayLike<number>): number {
+ if (array.constructor === Float32Array) return value;
+ return Math.round(value * normalizationScale(array));
+ },
+ /** A normalized integer from `array`'s component type, as a float in [0, 1] (or [-1, 1] when signed). */
+ denormalize(value: number, array: ArrayLike<number>): number {
+ if (array.constructor === Float32Array) return value;
+ return Math.max(value / normalizationScale(array), -1);
+ },
};
+
+function normalizationScale(array: ArrayLike<number>): number {
+ switch (array.constructor) {
+ case Uint32Array: return 4294967295;
+ case Uint16Array: return 65535;
+ case Uint8Array: case Uint8ClampedArray: return 255;
+ case Int32Array: return 2147483647;
+ case Int16Array: return 32767;
+ case Int8Array: return 127;
+ }
+ throw new Error("THREE.MathUtils: Invalid component type.");
+}
+
+let seed = 1234567;
+const HEX = Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, "0"));
diff --git a/packages/scene/src/raycaster.ts b/packages/scene/src/raycaster.ts
index b21cea0..f702649 100644
--- a/packages/scene/src/raycaster.ts
+++ b/packages/scene/src/raycaster.ts
@@ -9,7 +9,7 @@
// what a shape overlaps or meets when moved. Both see the world as the engine has it, with or without a tick since
// the last change; what the running script changed in the scene reaches the engine when it returns (docs/RUNTIME.md,
// World handlers).
-import { getEngineBodies, InstancedMesh, Mesh, Object3D, type PerspectiveCamera, physicsBodies, physicsQuery, ProceduralGeometry, ProceduralMesh } from "./core.ts";
+import { getEngineBodies, InstancedMesh, Layers, Mesh, Object3D, onLayers, type PerspectiveCamera, physicsBodies, physicsQuery, ProceduralGeometry, ProceduralMesh } from "./core.ts";
import { Box3, Matrix4, Quaternion, Ray, Vector2, Vector3 } from "./math.ts";
import type { BufferGeometry } from "./geometry.ts";
@@ -84,6 +84,9 @@ export class Raycaster {
near: number;
far: number;
camera: PerspectiveCamera | null = null;
+ /** three.js: `intersectObject(s)` tests only objects on one of these layers (layer 0 alone by default); their
+ * children are visited whatever the parent's layers. */
+ layers = new Layers();
params = { Mesh: {}, Line: { threshold: 1 }, Points: { threshold: 1 } };
constructor(origin?: Vector3, direction?: Vector3, near = 0, far = Infinity) {
this.ray = new Ray(origin?.clone(), direction?.clone());
@@ -132,6 +135,13 @@ export class Raycaster {
private visit(o: Object3D, recursive: boolean, out: Intersection[]): void {
o.updateWorldMatrix(true, false);
+ // (An object on none of the ray's layers is not tested; its children still are, as three.js.)
+ if (onLayers(o, this.layers)) this.test(o, out);
+ if (recursive) for (const c of o.children) this.visit(c, true, out);
+ }
+
+ /** The ray against the object itself. */
+ private test(o: Object3D, out: Intersection[]): void {
if (o instanceof InstancedMesh) {
if (!(o.geometry instanceof ProceduralGeometry)) {
const m = new Matrix4();
@@ -147,7 +157,6 @@ export class Raycaster {
} else if (o instanceof ProceduralMesh) {
this.boxes(o, o.geometry.boxes, o.matrixWorld, out);
}
- if (recursive) for (const c of o.children) this.visit(c, true, out);
}
private local(world: Matrix4): Ray {
diff --git a/packages/scene/test/three-compat-attribute-normalized.test.ts b/packages/scene/test/three-compat-attribute-normalized.test.ts
new file mode 100644
index 0000000..0155e65
--- /dev/null
+++ b/packages/scene/test/three-compat-attribute-normalized.test.ts
@@ -0,0 +1,51 @@
+// BufferAttribute normalized component access, as three.js r187 has it.
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import * as REF from "three";
+import * as THREE from "../src/index.ts";
+
+const arrays = () => [new Uint8Array(4), new Int8Array(4), new Uint16Array(4), new Int16Array(4), new Uint32Array(4), new Int32Array(4), new Float32Array(4)];
+
+test("a normalized attribute's getters read 0..1 (-1..1), its setters store integers, as three.js does", () => {
+ for (const [ours, ref] of arrays().map((a, i) => [a, arrays()[i]] as const)) {
+ const a = new THREE.BufferAttribute(ours, 4, true);
+ const r = new REF.BufferAttribute(ref, 4, true);
+ a.setXYZW(0, 0.5, 1, 0.25, ours instanceof Uint8Array || ours instanceof Uint16Array || ours instanceof Uint32Array ? 0 : -1);
+ r.setXYZW(0, 0.5, 1, 0.25, ref instanceof Uint8Array || ref instanceof Uint16Array || ref instanceof Uint32Array ? 0 : -1);
+ const name = ours.constructor.name;
+ assert.deepEqual([...a.array], [...r.array], `${name}: stored`);
+ assert.deepEqual([a.getX(0), a.getY(0), a.getZ(0), a.getW(0)], [r.getX(0), r.getY(0), r.getZ(0), r.getW(0)], `${name}: read`);
+ a.setX(0, 0.1).setY(0, 0.2).setZ(0, 0.3).setW(0, 0.4).setComponent(0, 1, 0.6);
+ r.setX(0, 0.1).setY(0, 0.2).setZ(0, 0.3).setW(0, 0.4).setComponent(0, 1, 0.6);
+ assert.deepEqual([...a.array], [...r.array], `${name}: single setters`);
+ assert.equal(a.getComponent(0, 1), r.getComponent(0, 1), `${name}: getComponent`);
+ a.setXY(0, 0.7, 0.8);
+ r.setXY(0, 0.7, 0.8);
+ assert.deepEqual([...a.array], [...r.array], `${name}: setXY`);
+ }
+});
+
+test("a normalized attribute's lowest signed value reads -1, as three.js clamps it", () => {
+ const a = new THREE.BufferAttribute(new Int8Array([-128, 127]), 1, true);
+ assert.equal(a.getX(0), -1);
+ assert.equal(a.getX(1), 1);
+});
+
+test("set, copyAt and the array stay raw; an attribute not normalized reads what it stores", () => {
+ const a = new THREE.BufferAttribute(new Uint8Array(3), 3, true);
+ a.set([255, 128, 0]);
+ assert.deepEqual([...a.array], [255, 128, 0]);
+ const plain = new THREE.BufferAttribute(new Uint8Array([200, 1, 2]), 3);
+ assert.equal(plain.getX(0), 200);
+ plain.setY(0, 7);
+ assert.equal(plain.array[1], 7);
+});
+
+test("applyMatrix4 on a normalized attribute works in 0..1 and stores integers, as three.js does", () => {
+ const a = new THREE.BufferAttribute(new Uint8Array([255, 0, 0]), 3, true);
+ const r = new REF.BufferAttribute(new Uint8Array([255, 0, 0]), 3, true);
+ a.applyMatrix4(new THREE.Matrix4().makeScale(0.5, 1, 1));
+ r.applyMatrix4(new REF.Matrix4().makeScale(0.5, 1, 1));
+ assert.deepEqual([...a.array], [...r.array]);
+ assert.deepEqual([...a.array], [128, 0, 0]);
+});
diff --git a/packages/scene/test/three-compat-attribute-types.test.ts b/packages/scene/test/three-compat-attribute-types.test.ts
new file mode 100644
index 0000000..f0d5cb9
--- /dev/null
+++ b/packages/scene/test/three-compat-attribute-types.test.ts
@@ -0,0 +1,36 @@
+// The typed BufferAttribute subclasses three.js r187 has.
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import * as REF from "three";
+import * as THREE from "../src/index.ts";
+
+const kinds = ["Int8", "Uint8", "Uint8Clamped", "Int16", "Uint16", "Int32", "Uint32", "Float32"] as const;
+
+test("each typed BufferAttribute stores its array type from a plain array or a count, as three.js does", () => {
+ for (const k of kinds) {
+ const Ours = (THREE as unknown as Record<string, new (a: ArrayLike<number> | number, s: number, n?: boolean) => THREE.BufferAttribute>)[`${k}BufferAttribute`];
+ const Ref = (REF as unknown as Record<string, new (a: ArrayLike<number> | number, s: number, n?: boolean) => REF.BufferAttribute>)[`${k}BufferAttribute`];
+ assert.ok(Ours, `${k}BufferAttribute exists`);
+ const values = [1, 2, 3, 300, -5, 7];
+ const a = new Ours(values, 3, true), r = new Ref(values, 3, true);
+ assert.equal(a.array.constructor, r.array.constructor, `${k}: array type`);
+ assert.deepEqual([...a.array], [...r.array], `${k}: values converted as the typed array does`);
+ assert.equal(a.count, r.count);
+ assert.equal(a.normalized, true);
+ assert.ok(a instanceof THREE.BufferAttribute);
+ const sized = new Ours(4, 2);
+ assert.equal(sized.array.constructor, r.array.constructor);
+ assert.equal(sized.array.length, 4);
+ const c = a.clone();
+ assert.ok(c instanceof Ours, `${k}: clone keeps the subclass`);
+ assert.deepEqual([...c.array], [...a.array]);
+ }
+});
+
+test("a Uint8 colour attribute on a geometry is kept as it is", () => {
+ const g = new THREE.BufferGeometry();
+ const color = new THREE.Uint8BufferAttribute([255, 0, 0], 3, true);
+ g.setAttribute("color", color);
+ assert.equal(g.getAttribute("color"), color);
+ assert.ok(g.getAttribute("color")!.array instanceof Uint8Array);
+});
diff --git a/packages/scene/test/three-compat-box3-sphere.test.ts b/packages/scene/test/three-compat-box3-sphere.test.ts
new file mode 100644
index 0000000..5d6b0bf
--- /dev/null
+++ b/packages/scene/test/three-compat-box3-sphere.test.ts
@@ -0,0 +1,34 @@
+// Box3 point and sphere queries, parity with three.js r187.
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import * as THREE from "../src/index.ts";
+
+const box = () => new THREE.Box3(new THREE.Vector3(-1, 0, 2), new THREE.Vector3(3, 4, 6));
+
+test("Box3.clampPoint and distanceToPoint measure to the nearest point of the box", () => {
+ const b = box();
+ const target = new THREE.Vector3();
+ assert.strictEqual(b.clampPoint(new THREE.Vector3(5, -2, 4), target), target);
+ assert.deepEqual(target.toArray(), [3, 0, 4]);
+ assert.deepEqual(b.clampPoint(new THREE.Vector3(0, 1, 3), new THREE.Vector3()).toArray(), [0, 1, 3]);
+ assert.equal(b.distanceToPoint(new THREE.Vector3(0, 1, 3)), 0);
+ assert.equal(b.distanceToPoint(new THREE.Vector3(6, 8, 4)), 5);
+ assert.equal(new THREE.Box3().distanceToPoint(new THREE.Vector3()), Infinity);
+});
+
+test("Box3.intersectsSphere is true when the sphere reaches the box", () => {
+ const b = box();
+ assert.equal(b.intersectsSphere(new THREE.Sphere(new THREE.Vector3(6, 8, 4), 5)), true);
+ assert.equal(b.intersectsSphere(new THREE.Sphere(new THREE.Vector3(6, 8, 4), 4.99)), false);
+ assert.equal(b.intersectsSphere(new THREE.Sphere(new THREE.Vector3(1, 2, 4), 0)), true);
+});
+
+test("Box3.getBoundingSphere wraps the box, and is empty for an empty box", () => {
+ const s = new THREE.Sphere();
+ assert.strictEqual(box().getBoundingSphere(s), s);
+ assert.deepEqual(s.center.toArray(), [1, 2, 4]);
+ assert.equal(s.radius, Math.sqrt(48) / 2);
+ new THREE.Box3().getBoundingSphere(s);
+ assert.deepEqual(s.center.toArray(), [0, 0, 0]);
+ assert.equal(s.radius, -1);
+});
diff --git a/packages/scene/test/three-compat-camera.test.ts b/packages/scene/test/three-compat-camera.test.ts
index dde67bf..07e6e1b 100644
--- a/packages/scene/test/three-compat-camera.test.ts
+++ b/packages/scene/test/three-compat-camera.test.ts
@@ -1,4 +1,4 @@
-// three.js compatibility: PerspectiveCamera.setFocalLength, as three.js r187 has it (the snippet-level suite is three-compat.test.ts).
+// three.js compatibility: PerspectiveCamera focal length and film size, as three.js r187 has them (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";
@@ -14,3 +14,17 @@ test("PerspectiveCamera.setFocalLength uses film height and aspect, as three.js
camera.setFocalLength(35);
assert.ok(Math.abs(camera.fov - 90) < 1e-10, "portrait: full 70 mm gauge at 35 mm focal length");
});
+
+test("PerspectiveCamera.getFocalLength, getFilmWidth and getFilmHeight, as three.js has them", () => {
+ const camera = new THREE.PerspectiveCamera(50, 2, 0.1, 100);
+ assert.equal(camera.getFilmWidth(), 35, "landscape: the full gauge across");
+ assert.equal(camera.getFilmHeight(), 17.5, "landscape: the gauge over the aspect, up");
+ camera.setFocalLength(24);
+ assert.ok(Math.abs(camera.getFocalLength() - 24) < 1e-10, "round-trips setFocalLength");
+
+ camera.aspect = 0.5;
+ assert.equal(camera.getFilmWidth(), 17.5, "portrait: the gauge times the aspect, across");
+ assert.equal(camera.getFilmHeight(), 35, "portrait: the full gauge up");
+ camera.fov = 90;
+ assert.ok(Math.abs(camera.getFocalLength() - 17.5) < 1e-10, "90 degrees over 35 mm of film: 17.5 mm");
+});
diff --git a/packages/scene/test/three-compat-color-ops.test.ts b/packages/scene/test/three-compat-color-ops.test.ts
new file mode 100644
index 0000000..4c754d7
--- /dev/null
+++ b/packages/scene/test/three-compat-color-ops.test.ts
@@ -0,0 +1,39 @@
+// three.js compatibility: Color arithmetic and accessors, as three.js r187 has them (src/math/Color.js).
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import * as THREE from "../src/index.ts";
+
+test("Color: isColor, setScalar, setFromVector3 and applyMatrix3 work on linear components", () => {
+ const c = new THREE.Color();
+ assert.equal(c.isColor, true);
+ assert.equal(c.setScalar(0.25), c, "returns the receiver");
+ assert.deepEqual(c.toArray(), [0.25, 0.25, 0.25]);
+ assert.deepEqual(c.setFromVector3(new THREE.Vector3(0.1, 0.2, 0.3)).toArray(), [0.1, 0.2, 0.3]);
+ // Column-major: swap red and blue, double green.
+ const m = { elements: [0, 0, 1, 0, 2, 0, 1, 0, 0] };
+ assert.deepEqual(new THREE.Color().setRGB(1, 0.5, 0.25).applyMatrix3(m).toArray(), [0.25, 1, 1]);
+});
+
+test("Color: addColors, addScalar and sub, with sub clamping at zero", () => {
+ const a = new THREE.Color().setRGB(0.5, 0.25, 0);
+ const b = new THREE.Color().setRGB(0.25, 0.5, 1);
+ const c = new THREE.Color().setRGB(9, 9, 9);
+ assert.deepEqual(c.addColors(a, b).toArray(), [0.75, 0.75, 1], "ignores the receiver's value");
+ assert.deepEqual(a.toArray(), [0.5, 0.25, 0], "does not mutate color1");
+ assert.deepEqual(c.addScalar(0.25).toArray(), [1, 1, 1.25]);
+ assert.deepEqual(new THREE.Color().setRGB(0.5, 0.25, 0).sub(b).toArray(), [0.25, 0, 0]);
+});
+
+test("Color: getHexString, getRGB, fromBufferAttribute, toJSON and iteration", () => {
+ const c = new THREE.Color(0x0080ff);
+ assert.equal(c.getHexString(), "0080ff");
+ assert.equal(new THREE.Color(0x000001).getHexString(), "000001", "zero-padded to six digits");
+ const target = { r: 0, g: 0, b: 0 };
+ assert.equal(c.getRGB(target), target, "returns the target");
+ assert.deepEqual(target, { r: c.r, g: c.g, b: c.b }, "linear components");
+ assert.equal(c.toJSON(), 0x0080ff);
+ assert.equal(JSON.stringify({ c }), `{"c":${0x0080ff}}`);
+ assert.deepEqual([...new THREE.Color().setRGB(0.1, 0.2, 0.3)], [0.1, 0.2, 0.3]);
+ const attr = new THREE.BufferAttribute(new Float32Array([0, 0, 0, 0.5, 0.25, 1]), 3);
+ assert.deepEqual(new THREE.Color().fromBufferAttribute(attr, 1).toArray(), [0.5, 0.25, 1]);
+});
diff --git a/packages/scene/test/three-compat-color-srgb.test.ts b/packages/scene/test/three-compat-color-srgb.test.ts
new file mode 100644
index 0000000..86710d8
--- /dev/null
+++ b/packages/scene/test/three-compat-color-srgb.test.ts
@@ -0,0 +1,38 @@
+// three.js compatibility: Color sRGB conversions and color keywords, as three.js r187 has them (src/math/Color.js).
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import * as THREE from "../src/index.ts";
+
+// The encode uses three.js's 0.41666 exponent, so round trips land within ~1e-5.
+const close = (a: number[], b: number[], msg?: string) =>
+ a.forEach((v, k) => assert.ok(Math.abs(v - b[k]) < 1e-4, `${msg ?? ""} [${k}] ${v} vs ${b[k]}`));
+
+test("Color: copySRGBToLinear / copyLinearToSRGB and the in-place converts", () => {
+ const encoded = new THREE.Color().setRGB(0.5, 0.04, 1);
+ const linear = new THREE.Color().copySRGBToLinear(encoded);
+ close(linear.toArray(), [0.21404114, 0.04 / 12.92, 1], "sRGB 0.5 decodes to ~0.214; the toe is linear");
+ assert.deepEqual(encoded.toArray(), [0.5, 0.04, 1], "does not mutate the source");
+ close(new THREE.Color().copyLinearToSRGB(linear).toArray(), [0.5, 0.04, 1], "round trip");
+ const c = new THREE.Color().setRGB(0.5, 0.04, 1);
+ assert.equal(c.convertSRGBToLinear(), c, "returns the receiver");
+ close(c.toArray(), linear.toArray());
+ close(c.convertLinearToSRGB().toArray(), [0.5, 0.04, 1]);
+});
+
+test("Color: setColorName and NAMES carry the full CSS keyword table", () => {
+ assert.equal(Object.keys(THREE.Color.NAMES).length, 148);
+ assert.equal(THREE.Color.NAMES.rebeccapurple, 0x663399);
+ assert.equal(new THREE.Color().setColorName("CornflowerBlue").getHex(), 0x6495ed, "case-insensitive");
+ assert.equal(new THREE.Color("teal").getHex(), 0x008080, "the constructor accepts every keyword");
+ const warn = console.warn;
+ let warned = 0;
+ console.warn = () => void warned++;
+ try {
+ const c = new THREE.Color().setRGB(0.1, 0.2, 0.3);
+ assert.equal(c.setColorName("notacolor"), c);
+ assert.deepEqual(c.toArray(), [0.1, 0.2, 0.3], "an unknown name leaves the color unchanged");
+ } finally {
+ console.warn = warn;
+ }
+ assert.equal(warned, 1, "and warns");
+});
diff --git a/packages/scene/test/three-compat-copy-rotation-order.test.ts b/packages/scene/test/three-compat-copy-rotation-order.test.ts
new file mode 100644
index 0000000..c9fbbdd
--- /dev/null
+++ b/packages/scene/test/three-compat-copy-rotation-order.test.ts
@@ -0,0 +1,38 @@
+// three.js r187 parity: Object3D.copy / clone take the source's rotation order with its angles.
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import * as THREE from "../src/index.ts";
+
+const near = (a: number, b: number, what: string) => assert.ok(Math.abs(a - b) < 1e-9, `${what}: ${a} vs ${b}`);
+
+test("Object3D.clone keeps rotation.order and the angles in it, as three.js does", () => {
+ const source = new THREE.Object3D();
+ source.rotation.set(0.3, 0.5, 0.1, "YXZ");
+ const c = source.clone();
+
+ assert.equal(c.rotation.order, "YXZ");
+ [c.rotation.x, c.rotation.y, c.rotation.z].forEach((v, i) => near(v, [0.3, 0.5, 0.1][i], `[${i}]`));
+ assert.deepEqual(c.quaternion.toArray(), source.quaternion.toArray(), "the quaternion copied exactly");
+});
+
+test("Object3D.copy onto an object with another order takes the source's", () => {
+ const source = new THREE.Group();
+ source.rotation.set(-0.2, 1.1, 0.4, "ZYX");
+ const target = new THREE.Group();
+ target.rotation.set(0.7, 0, 0, "XZY");
+ target.copy(source);
+
+ assert.equal(target.rotation.order, "ZYX");
+ [target.rotation.x, target.rotation.y, target.rotation.z].forEach((v, i) => near(v, [-0.2, 1.1, 0.4][i], `[${i}]`));
+ assert.deepEqual(target.quaternion.toArray(), source.quaternion.toArray());
+});
+
+test("A copied mesh keeps its order through a later rotation edit", () => {
+ const source = new THREE.Mesh(new THREE.BoxGeometry(), new THREE.MeshStandardMaterial());
+ source.rotation.set(0, 0.6, 0, "YXZ");
+ const c = source.clone();
+ c.rotation.x = 0.25;
+ assert.equal(c.rotation.order, "YXZ");
+ const expected = new THREE.Quaternion().setFromEuler(new THREE.Euler(0.25, 0.6, 0, "YXZ"));
+ near(Math.abs(c.quaternion.dot(expected)), 1, "the quaternion follows the YXZ rotation");
+});
diff --git a/packages/scene/test/three-compat-euler.test.ts b/packages/scene/test/three-compat-euler.test.ts
index 7a10731..69da5d8 100644
--- a/packages/scene/test/three-compat-euler.test.ts
+++ b/packages/scene/test/three-compat-euler.test.ts
@@ -13,3 +13,46 @@ test("Euler.order: assigning the order keeps Object3D.quaternion in sync, as thr
"YXZ recomposes the quaternion to (0.5, 0.5, -0.5, 0.5)");
assert.equal(object.rotation.order, "YXZ", "setting the order preserves the chosen order");
});
+
+const ORDERS: THREE.EulerOrder[] = ["XYZ", "YXZ", "ZXY", "ZYX", "YZX", "XZY"];
+const near = (a: number, b: number) => Math.abs(a - b) < 1e-9;
+
+test("Euler.setFromQuaternion: round-trips all six orders, as three.js r187 does", () => {
+ for (const order of ORDERS) {
+ const source = new THREE.Euler(0.3, -0.7, 1.1, order);
+ const q = new THREE.Quaternion().setFromEuler(source);
+ const back = new THREE.Euler().setFromQuaternion(q, order);
+ assert.equal(back.order, order);
+ assert.ok(near(back.x, 0.3) && near(back.y, -0.7) && near(back.z, 1.1), `${order}: ${back.toArray()}`);
+ const viaMatrix = new THREE.Euler(0, 0, 0, order).setFromRotationMatrix(new THREE.Matrix4().makeRotationFromQuaternion(q));
+ assert.ok(viaMatrix.equals(back), `${order}: the matrix path defaults to the Euler's own order`);
+ }
+});
+
+test("Object3D.rotation keeps its order when the quaternion changes, as three.js does", () => {
+ const object = new THREE.Object3D();
+ object.rotation.order = "YXZ";
+ object.quaternion.setFromEuler(new THREE.Euler(0.2, 0.4, -0.5, "YXZ"));
+ assert.equal(object.rotation.order, "YXZ");
+ assert.ok(near(object.rotation.x, 0.2) && near(object.rotation.y, 0.4) && near(object.rotation.z, -0.5));
+});
+
+test("Euler.copy / clone / equals / toArray / fromArray / setFromVector3 / reorder", () => {
+ const a = new THREE.Euler(1, 2, 3, "ZYX");
+ const b = a.clone();
+ assert.ok(b !== a && b.equals(a));
+ assert.ok(!b.equals(new THREE.Euler(1, 2, 3, "XYZ")));
+ assert.ok(new THREE.Euler().copy(a).equals(a));
+ assert.deepEqual(a.toArray(), [1, 2, 3, "ZYX"]);
+ assert.deepEqual(a.toArray([9, 9], 2), [9, 9, 1, 2, 3, "ZYX"]);
+ const c = new THREE.Euler(0, 0, 0, "YZX").fromArray([4, 5, 6]);
+ assert.ok(c.equals(new THREE.Euler(4, 5, 6, "YZX")), "a missing order keeps the current one");
+ assert.equal(c.fromArray([4, 5, 6, "XZY"]).order, "XZY");
+ assert.ok(new THREE.Euler().setFromVector3(new THREE.Vector3(7, 8, 9), "ZXY").equals(new THREE.Euler(7, 8, 9, "ZXY")));
+
+ const e = new THREE.Euler(0.3, -0.4, 0.5, "XYZ");
+ const before = new THREE.Quaternion().setFromEuler(e);
+ e.reorder("ZXY");
+ assert.equal(e.order, "ZXY");
+ assert.ok(Math.abs(Math.abs(new THREE.Quaternion().setFromEuler(e).dot(before)) - 1) < 1e-12, "reorder keeps the rotation");
+});
diff --git a/packages/scene/test/three-compat-interleaved.test.ts b/packages/scene/test/three-compat-interleaved.test.ts
new file mode 100644
index 0000000..3d42322
--- /dev/null
+++ b/packages/scene/test/three-compat-interleaved.test.ts
@@ -0,0 +1,64 @@
+// InterleavedBuffer / InterleavedBufferAttribute, as three.js r187 has them.
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import * as REF from "three";
+import * as THREE from "../src/index.ts";
+
+// Two vertices: position xyz, then uv.
+const data = () => new Float32Array([1, 2, 3, 0.25, 0.5, 4, 5, 6, 0.75, 1]);
+
+test("an interleaved attribute reads and writes its numbers at offset within the stride, as three.js does", () => {
+ const ib = new THREE.InterleavedBuffer(data(), 5), rb = new REF.InterleavedBuffer(data(), 5);
+ const pos = new THREE.InterleavedBufferAttribute(ib, 3, 0), rpos = new REF.InterleavedBufferAttribute(rb, 3, 0);
+ const uv = new THREE.InterleavedBufferAttribute(ib, 2, 3), ruv = new REF.InterleavedBufferAttribute(rb, 2, 3);
+ assert.equal(ib.count, rb.count);
+ assert.equal(pos.count, 2);
+ assert.equal(pos.array, ib.array);
+ assert.deepEqual([pos.getX(1), pos.getY(1), pos.getZ(1)], [rpos.getX(1), rpos.getY(1), rpos.getZ(1)]);
+ assert.deepEqual([uv.getX(0), uv.getY(0), uv.getComponent(1, 1)], [ruv.getX(0), ruv.getY(0), ruv.getComponent(1, 1)]);
+ pos.setXYZ(0, 7, 8, 9).setX(1, -1);
+ rpos.setXYZ(0, 7, 8, 9).setX(1, -1);
+ uv.setXY(1, 0.1, 0.2).setComponent(0, 0, 0.3);
+ ruv.setXY(1, 0.1, 0.2).setComponent(0, 0, 0.3);
+ assert.deepEqual([...ib.array], [...rb.array]);
+ pos.applyMatrix4(new THREE.Matrix4().makeTranslation(1, 0, 0));
+ rpos.applyMatrix4(new REF.Matrix4().makeTranslation(1, 0, 0));
+ assert.deepEqual([...ib.array], [...rb.array], "applyMatrix4 leaves the other attribute's numbers alone");
+});
+
+test("a normalized interleaved attribute works in 0..1, as three.js does", () => {
+ const ib = new THREE.InterleavedBuffer(new Uint8Array(8), 4), rb = new REF.InterleavedBuffer(new Uint8Array(8), 4);
+ const c = new THREE.InterleavedBufferAttribute(ib, 3, 1, true), rc = new REF.InterleavedBufferAttribute(rb, 3, 1, true);
+ c.setXYZ(1, 1, 0.5, 0);
+ rc.setXYZ(1, 1, 0.5, 0);
+ assert.deepEqual([...ib.array], [...rb.array]);
+ assert.equal(c.getY(1), rc.getY(1));
+});
+
+test("needsUpdate bumps the buffer's version; clone de-interleaves into a BufferAttribute", () => {
+ const ib = new THREE.InterleavedBuffer(data(), 5);
+ const uv = new THREE.InterleavedBufferAttribute(ib, 2, 3);
+ uv.needsUpdate = true;
+ assert.equal(ib.version, 1);
+ const flat = uv.clone();
+ assert.ok(flat instanceof THREE.BufferAttribute);
+ assert.deepEqual([...flat.array], [0.25, 0.5, 0.75, 1]);
+ assert.equal(flat.itemSize, 2);
+ const copy = ib.clone();
+ assert.notEqual(copy.array, ib.array);
+ assert.deepEqual([...copy.array], [...ib.array]);
+ assert.equal(copy.stride, 5);
+ const other = new THREE.InterleavedBuffer(new Float32Array(10), 5).copyAt(0, ib, 1);
+ assert.deepEqual([...other.array.slice(0, 5)], [4, 5, 6, 0.75, 1]);
+});
+
+test("a geometry takes interleaved attributes de-interleaved", () => {
+ const ib = new THREE.InterleavedBuffer(new Float32Array([0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1]), 5);
+ const g = new THREE.BufferGeometry();
+ g.setAttribute("position", new THREE.InterleavedBufferAttribute(ib, 3, 0));
+ g.setAttribute("uv", new THREE.InterleavedBufferAttribute(ib, 2, 3));
+ assert.deepEqual([...g.positions], [0, 0, 0, 1, 0, 0, 0, 1, 0]);
+ assert.deepEqual([...g.uvs], [0, 0, 1, 0, 0, 1]);
+ assert.equal(g.vertexCount, 3);
+ assert.ok(g.getAttribute("position") instanceof THREE.BufferAttribute);
+});
diff --git a/packages/scene/test/three-compat-layers.test.ts b/packages/scene/test/three-compat-layers.test.ts
new file mode 100644
index 0000000..eabb2ef
--- /dev/null
+++ b/packages/scene/test/three-compat-layers.test.ts
@@ -0,0 +1,67 @@
+// three.js r187 parity: Layers, Object3D.layers (copied by value) and Raycaster.layers.
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import * as THREE from "../src/index.ts";
+
+test("Layers: the mask operations, as three.js has them", () => {
+ const l = new THREE.Layers();
+ assert.equal(l.mask, 1, "layer 0 alone to begin with");
+ l.enable(3);
+ assert.equal(l.mask, 0b1001);
+ assert.ok(l.isEnabled(0) && l.isEnabled(3) && !l.isEnabled(1));
+ l.toggle(0);
+ assert.equal(l.mask, 0b1000);
+ l.disable(3);
+ assert.equal(l.mask, 0);
+ l.set(31);
+ assert.equal(l.mask, 0x80000000, "set: one layer, the mask unsigned");
+ l.enableAll();
+ assert.equal(l.mask, -1, "enableAll: 0xffffffff | 0, as three.js");
+ assert.ok(l.isEnabled(31));
+ l.disableAll();
+ assert.equal(l.mask, 0);
+
+ const a = new THREE.Layers(), b = new THREE.Layers();
+ b.set(2);
+ assert.equal(a.test(b), false);
+ a.enable(2);
+ assert.equal(a.test(b), true);
+});
+
+test("Object3D.layers: on layer 0; copy and clone take the mask by value", () => {
+ const o = new THREE.Mesh(new THREE.BoxGeometry(), new THREE.MeshStandardMaterial());
+ assert.ok(o.layers instanceof THREE.Layers);
+ assert.equal(o.layers.mask, 1);
+ o.layers.set(4);
+ const c = o.clone();
+ assert.equal(c.layers.mask, 1 << 4);
+ assert.notEqual(c.layers, o.layers, "its own Layers");
+ c.layers.enable(0);
+ assert.equal(o.layers.mask, 1 << 4, "the source is untouched");
+
+ const target = new THREE.Group();
+ target.layers.set(7);
+ target.copy(new THREE.Group());
+ assert.equal(target.layers.mask, 1, "a source never given layers copies layer 0");
+});
+
+test("Raycaster.layers: objects on none of the ray's layers are not hit; their children still are", () => {
+ const box = () => new THREE.Mesh(new THREE.BoxGeometry(1, 1, 1), new THREE.MeshStandardMaterial());
+ const near = box(), far = box();
+ near.position.set(0, 0, -3);
+ far.position.set(0, 0, -3); // under `near`: 6 m away
+ near.add(far);
+ const scene = new THREE.Scene();
+ scene.add(near);
+
+ const ray = new THREE.Raycaster(new THREE.Vector3(0, 0, 0), new THREE.Vector3(0, 0, -1));
+ assert.deepEqual(ray.intersectObject(scene).map((h) => h.object), [near, near, far, far]);
+
+ near.layers.set(1);
+ assert.deepEqual(ray.intersectObject(scene).map((h) => h.object), [far, far], "the child is still tested");
+
+ ray.layers.enable(1);
+ assert.equal(ray.intersectObject(scene)[0].object, near);
+ ray.layers.set(5);
+ assert.equal(ray.intersectObject(scene).length, 0);
+});
diff --git a/packages/scene/test/three-compat-light-dispose.test.ts b/packages/scene/test/three-compat-light-dispose.test.ts
new file mode 100644
index 0000000..67fb534
--- /dev/null
+++ b/packages/scene/test/three-compat-light-dispose.test.ts
@@ -0,0 +1,23 @@
+// three.js compatibility: every light has dispose(), 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("Lights: dispose() exists on every light and on its shadow, as three.js has it", () => {
+ const lights = [
+ new THREE.DirectionalLight(),
+ new THREE.PointLight(),
+ new THREE.SpotLight(),
+ new THREE.RectAreaLight(),
+ new THREE.AmbientLight(),
+ new THREE.HemisphereLight(),
+ ];
+ for (const light of lights) {
+ // three.js cleanup code: traverse the scene and dispose of what it finds.
+ const scene = new THREE.Scene().add(light);
+ scene.traverse((o) => (o as { dispose?: () => void }).dispose?.());
+ assert.doesNotThrow(() => light.dispose(), `${light.type}.dispose`);
+ assert.equal(light.parent, scene, `${light.type}: dispose frees, it does not detach`);
+ if (light instanceof THREE.Light) assert.doesNotThrow(() => light.shadow.dispose(), `${light.type}.shadow.dispose`);
+ }
+});
diff --git a/packages/scene/test/three-compat-material.test.ts b/packages/scene/test/three-compat-material.test.ts
new file mode 100644
index 0000000..65c4f7d
--- /dev/null
+++ b/packages/scene/test/three-compat-material.test.ts
@@ -0,0 +1,24 @@
+// three.js compatibility: MeshPhysicalMaterial.reflectivity, 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";
+
+const close = (a: number, b: number, msg: string) => assert.ok(Math.abs(a - b) < 1e-12, `${msg}: ${a} vs ${b}`);
+
+test("MeshPhysicalMaterial.reflectivity maps to and from ior, as three.js does", () => {
+ const m = new THREE.MeshPhysicalMaterial();
+ close(m.reflectivity, 0.5, "ior 1.5 is reflectivity 0.5");
+
+ m.reflectivity = 1;
+ close(m.ior, 7 / 3, "reflectivity 1 is ior 2.333");
+ m.reflectivity = 0;
+ close(m.ior, 1, "reflectivity 0 is ior 1");
+ m.ior = 1000;
+ assert.equal(m.reflectivity, 1, "clamped to 1 above ior 2.333");
+
+ const p = new THREE.MeshPhysicalMaterial({ reflectivity: 0.8 });
+ close(p.ior, 1.32 / 0.68, "the constructor's reflectivity sets ior");
+ const c = p.clone();
+ close(c.reflectivity, 0.8, "a clone keeps it");
+ assert.equal(Object.keys(c).includes("reflectivity"), false, "reflectivity stays derived, not an own field");
+});
diff --git a/packages/scene/test/three-compat-mathutils.test.ts b/packages/scene/test/three-compat-mathutils.test.ts
index d1ba37e..937a356 100644
--- a/packages/scene/test/three-compat-mathutils.test.ts
+++ b/packages/scene/test/three-compat-mathutils.test.ts
@@ -9,3 +9,86 @@ test("MathUtils.euclideanModulo: negative dividends return Euclidean residues",
assert.equal(THREE.MathUtils.euclideanModulo(12, 5), 2);
assert.equal(THREE.MathUtils.euclideanModulo(10, 5), 0);
});
+
+// three.js r187 src/math/MathUtils.js: the scalar helpers three.js code reaches for.
+test("MathUtils: mapLinear, inverseLerp, damp and pingpong match three.js", () => {
+ const M = THREE.MathUtils;
+ assert.equal(M.mapLinear(5, 0, 10, 100, 200), 150);
+ assert.equal(M.mapLinear(-5, 0, 10, 0, 1), -0.5, "extrapolates outside the range");
+ assert.equal(M.inverseLerp(2, 4, 3), 0.5);
+ assert.equal(M.inverseLerp(2, 2, 3), 0, "empty range gives 0, not NaN");
+ assert.equal(M.damp(0, 10, 0, 1), 0, "lambda 0 does not move");
+ assert.ok(Math.abs(M.damp(0, 10, 1, 1) - 10 * (1 - Math.exp(-1))) < 1e-12);
+ assert.equal(M.pingpong(0.25), 0.25);
+ assert.equal(M.pingpong(1.25), 0.75);
+ assert.equal(M.pingpong(-0.25), 0.25);
+ assert.equal(M.pingpong(5, 2), 1);
+});
+
+test("MathUtils: smoothstep and smootherstep clamp and ease, as three.js", () => {
+ const M = THREE.MathUtils;
+ assert.equal(M.smoothstep(-1, 0, 1), 0);
+ assert.equal(M.smoothstep(2, 0, 1), 1);
+ assert.equal(M.smoothstep(0.5, 0, 1), 0.5);
+ assert.equal(M.smoothstep(0.25, 0, 1), 0.15625);
+ assert.equal(M.smootherstep(0.5, 0, 1), 0.5);
+ assert.equal(M.smootherstep(0.25, 0, 1), 0.103515625);
+ assert.equal(M.smootherstep(3, 0, 2), 1);
+});
+
+test("MathUtils: random helpers stay in range; seededRandom is three.js's Mulberry32", () => {
+ const M = THREE.MathUtils;
+ for (let k = 0; k < 200; k++) {
+ const i = M.randInt(-2, 2);
+ assert.ok(Number.isInteger(i) && i >= -2 && i <= 2);
+ const f = M.randFloat(1, 3);
+ assert.ok(f >= 1 && f < 3);
+ const s = M.randFloatSpread(4);
+ assert.ok(s > -2 && s <= 2);
+ }
+ const a = [M.seededRandom(42), M.seededRandom(), M.seededRandom()];
+ const b = [M.seededRandom(42), M.seededRandom(), M.seededRandom()];
+ assert.deepEqual(a, b, "reseeding repeats the sequence");
+ assert.ok(a.every((v) => v >= 0 && v < 1));
+ // Mulberry32 with state 42: first output, computed from the reference algorithm.
+ let t = (42 + 0x6d2b79f5) | 0;
+ t = Math.imul(t ^ (t >>> 15), t | 1);
+ t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
+ assert.equal(a[0], ((t ^ (t >>> 14)) >>> 0) / 4294967296);
+});
+
+test("MathUtils: generateUUID gives lowercase version-4 UUIDs", () => {
+ const ids = new Set<string>();
+ for (let k = 0; k < 50; k++) {
+ const id = THREE.MathUtils.generateUUID();
+ assert.match(id, /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/);
+ ids.add(id);
+ }
+ assert.equal(ids.size, 50);
+});
+
+test("MathUtils: power-of-two helpers, as three.js", () => {
+ const M = THREE.MathUtils;
+ assert.equal(M.isPowerOfTwo(1), true);
+ assert.equal(M.isPowerOfTwo(1024), true);
+ assert.equal(M.isPowerOfTwo(0), false);
+ assert.equal(M.isPowerOfTwo(6), false);
+ assert.equal(M.ceilPowerOfTwo(5), 8);
+ assert.equal(M.ceilPowerOfTwo(8), 8);
+ assert.equal(M.floorPowerOfTwo(5), 4);
+ assert.equal(M.floorPowerOfTwo(8), 8);
+});
+
+test("MathUtils: normalize and denormalize follow the array's component type", () => {
+ const M = THREE.MathUtils;
+ assert.equal(M.normalize(0.3, new Float32Array(1)), 0.3, "float arrays pass through");
+ assert.equal(M.normalize(1, new Uint8Array(1)), 255);
+ assert.equal(M.normalize(0.5, new Uint16Array(1)), 32768);
+ assert.equal(M.normalize(-1, new Int8Array(1)), -127);
+ assert.equal(M.denormalize(255, new Uint8Array(1)), 1);
+ assert.equal(M.denormalize(65535, new Uint16Array(1)), 1);
+ assert.equal(M.denormalize(-128, new Int8Array(1)), -1, "the most negative integer clamps to -1");
+ assert.equal(M.denormalize(-32767, new Int16Array(1)), -1);
+ assert.equal(M.denormalize(0.3, new Float32Array(1)), 0.3);
+ assert.throws(() => M.normalize(1, new Float64Array(1)), "unsupported component types throw");
+});
diff --git a/packages/scene/test/three-compat-matrix3.test.ts b/packages/scene/test/three-compat-matrix3.test.ts
new file mode 100644
index 0000000..c23cb11
--- /dev/null
+++ b/packages/scene/test/three-compat-matrix3.test.ts
@@ -0,0 +1,57 @@
+// three.js r187 Matrix3 parity: the class, Matrix4.setFromMatrix3 and Vector3.applyMatrix3/applyNormalMatrix.
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import * as THREE from "../src/index.ts";
+
+const near = (actual: number[], expected: number[]): void => {
+ assert.equal(actual.length, expected.length);
+ actual.forEach((v, k) => assert.ok(Math.abs(v - expected[k]) < 1e-12, `element ${k}: ${v} vs ${expected[k]}`));
+};
+
+test("Matrix3 takes row-major arguments and stores column-major elements, as three.js does", () => {
+ const matrix = new THREE.Matrix3(1, 2, 3, 4, 5, 6, 7, 8, 10);
+ assert.equal(matrix.isMatrix3, true);
+ assert.deepEqual(matrix.elements, [1, 4, 7, 2, 5, 8, 3, 6, 10]);
+ assert.deepEqual(new THREE.Matrix3().elements, [1, 0, 0, 0, 1, 0, 0, 0, 1]);
+ assert.equal(matrix.determinant(), -3);
+ assert.ok(matrix.clone().equals(matrix));
+ assert.notStrictEqual(matrix.clone().elements, matrix.elements);
+ assert.deepEqual(matrix.clone().transpose().toArray(), [1, 2, 3, 4, 5, 6, 7, 8, 10]);
+ assert.deepEqual(new THREE.Matrix3().fromArray([0, 9, 8, 7, 6, 5, 4, 3, 2, 1], 1).toArray(), [9, 8, 7, 6, 5, 4, 3, 2, 1]);
+ assert.deepEqual(matrix.clone().multiplyScalar(2).toArray(), [2, 8, 14, 4, 10, 16, 6, 12, 20]);
+ assert.deepEqual(matrix.clone().identity().toArray(), [1, 0, 0, 0, 1, 0, 0, 0, 1]);
+});
+
+test("Matrix3 multiply, premultiply and invert, as three.js does", () => {
+ const a = new THREE.Matrix3(1, 2, 3, 4, 5, 6, 7, 8, 10);
+ const b = new THREE.Matrix3(2, 0, 1, 1, 3, 0, 0, 1, 4);
+ // Row-major a * b.
+ assert.deepEqual(a.clone().multiply(b).toArray(), new THREE.Matrix3(4, 9, 13, 13, 21, 28, 22, 34, 47).toArray());
+ assert.deepEqual(a.clone().premultiply(b).toArray(), new THREE.Matrix3().multiplyMatrices(b, a).toArray());
+ near(a.clone().invert().multiply(a).toArray(), [1, 0, 0, 0, 1, 0, 0, 0, 1]);
+ assert.deepEqual(new THREE.Matrix3(1, 2, 3, 2, 4, 6, 0, 0, 1).invert().toArray(), [0, 0, 0, 0, 0, 0, 0, 0, 0]);
+});
+
+test("Matrix3.setFromMatrix4 and Matrix4.setFromMatrix3 move the upper 3x3, as three.js does", () => {
+ const m4 = new THREE.Matrix4().set(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16);
+ const m3 = new THREE.Matrix3().setFromMatrix4(m4);
+ assert.deepEqual(m3.toArray(), [1, 5, 9, 2, 6, 10, 3, 7, 11]);
+ const back = new THREE.Matrix4().setPosition(1, 2, 3);
+ assert.strictEqual(back.setFromMatrix3(m3), back);
+ assert.deepEqual(back.toArray(), [1, 5, 9, 0, 2, 6, 10, 0, 3, 7, 11, 0, 0, 0, 0, 1]);
+});
+
+test("Matrix3.getNormalMatrix keeps normals perpendicular under non-uniform scale, as three.js does", () => {
+ const world = new THREE.Matrix4().compose(
+ new THREE.Vector3(4, 5, 6),
+ new THREE.Quaternion().setFromAxisAngle(new THREE.Vector3(0, 0, 1), 0.5),
+ new THREE.Vector3(3, 1, 1),
+ );
+ // The plane x = y, with tangent (1, 1, 0) and normal (1, -1, 0).
+ const tangent = new THREE.Vector3(1, 1, 0).transformDirection(world);
+ const normal = new THREE.Vector3(1, -1, 0).normalize().applyNormalMatrix(new THREE.Matrix3().getNormalMatrix(world));
+ assert.ok(Math.abs(normal.length() - 1) < 1e-12);
+ assert.ok(Math.abs(normal.dot(tangent)) < 1e-12);
+ const scaled = new THREE.Vector3(1, 2, 3).applyMatrix3(new THREE.Matrix3(2, 0, 0, 0, 3, 0, 1, 0, 1));
+ assert.deepEqual(scaled.toArray(), [2, 6, 4]);
+});
diff --git a/packages/scene/test/three-compat-matrix4-basis.test.ts b/packages/scene/test/three-compat-matrix4-basis.test.ts
new file mode 100644
index 0000000..d3f521c
--- /dev/null
+++ b/packages/scene/test/three-compat-matrix4-basis.test.ts
@@ -0,0 +1,49 @@
+// three.js r187 Matrix4 makeBasis, extractBasis, extractRotation, makeRotationAxis and determinantAffine parity.
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import * as THREE from "../src/index.ts";
+
+const near = (actual: number[], expected: number[]): void => {
+ assert.equal(actual.length, expected.length);
+ actual.forEach((v, k) => assert.ok(Math.abs(v - expected[k]) < 1e-12, `element ${k}: ${v} vs ${expected[k]}`));
+};
+
+test("Matrix4.makeBasis writes the axes as columns and clears translation, as three.js does", () => {
+ const matrix = new THREE.Matrix4().setPosition(7, 8, 9);
+ const result = matrix.makeBasis(new THREE.Vector3(1, 2, 3), new THREE.Vector3(4, 5, 6), new THREE.Vector3(7, 8, 10));
+ assert.strictEqual(result, matrix);
+ assert.deepEqual(matrix.toArray(), [1, 2, 3, 0, 4, 5, 6, 0, 7, 8, 10, 0, 0, 0, 0, 1]);
+ assert.equal(matrix.determinantAffine(), -3);
+});
+
+test("Matrix4.extractBasis reads the columns back, and unit axes for a singular matrix, as three.js r187 does", () => {
+ const x = new THREE.Vector3(), y = new THREE.Vector3(), z = new THREE.Vector3();
+ const matrix = new THREE.Matrix4().makeBasis(new THREE.Vector3(1, 2, 3), new THREE.Vector3(4, 5, 6), new THREE.Vector3(7, 8, 10));
+ assert.strictEqual(matrix.extractBasis(x, y, z), matrix);
+ assert.deepEqual([x.toArray(), y.toArray(), z.toArray()], [[1, 2, 3], [4, 5, 6], [7, 8, 10]]);
+
+ new THREE.Matrix4().makeScale(2, 0, 3).extractBasis(x, y, z);
+ assert.deepEqual([x.toArray(), y.toArray(), z.toArray()], [[1, 0, 0], [0, 1, 0], [0, 0, 1]]);
+});
+
+test("Matrix4.extractRotation drops scale and translation, and is identity for a singular matrix, as three.js r187 does", () => {
+ const quaternion = new THREE.Quaternion().setFromAxisAngle(new THREE.Vector3(0, 1, 0), 0.6);
+ const rotation = new THREE.Matrix4().makeRotationFromQuaternion(quaternion);
+ const transform = new THREE.Matrix4().compose(new THREE.Vector3(5, 6, 7), quaternion, new THREE.Vector3(2, 3, 4));
+ const extracted = new THREE.Matrix4().setPosition(1, 1, 1);
+ assert.strictEqual(extracted.extractRotation(transform), extracted);
+ near(extracted.toArray(), rotation.toArray());
+
+ const singular = new THREE.Matrix4().extractRotation(new THREE.Matrix4().makeScale(0, 1, 1).setPosition(5, 6, 7));
+ assert.deepEqual(singular.toArray(), new THREE.Matrix4().toArray());
+});
+
+test("Matrix4.makeRotationAxis matches the axis rotations and the axis-angle quaternion, as three.js does", () => {
+ near(new THREE.Matrix4().makeRotationAxis(new THREE.Vector3(1, 0, 0), 0.4).toArray(), new THREE.Matrix4().makeRotationX(0.4).toArray());
+ near(new THREE.Matrix4().makeRotationAxis(new THREE.Vector3(0, 1, 0), -1.1).toArray(), new THREE.Matrix4().makeRotationY(-1.1).toArray());
+ const axis = new THREE.Vector3(1, 2, -2).normalize();
+ const fromQuaternion = new THREE.Matrix4().makeRotationFromQuaternion(new THREE.Quaternion().setFromAxisAngle(axis, 2.3));
+ const matrix = new THREE.Matrix4().setPosition(3, 3, 3);
+ assert.strictEqual(matrix.makeRotationAxis(axis, 2.3), matrix);
+ near(matrix.toArray(), fromQuaternion.toArray());
+});
diff --git a/packages/scene/test/three-compat-matrix4-scale.test.ts b/packages/scene/test/three-compat-matrix4-scale.test.ts
new file mode 100644
index 0000000..673b50c
--- /dev/null
+++ b/packages/scene/test/three-compat-matrix4-scale.test.ts
@@ -0,0 +1,30 @@
+// three.js r187 Matrix4 scale, getMaxScaleOnAxis and multiplyScalar parity.
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import * as THREE from "../src/index.ts";
+
+const rowMajor = (): THREE.Matrix4 => new THREE.Matrix4().set(
+ 1, 2, 3, 4,
+ 5, 6, 7, 8,
+ 9, 10, 11, 12,
+ 13, 14, 15, 16,
+);
+
+test("Matrix4.scale multiplies the first three columns in place, as three.js does", () => {
+ const matrix = rowMajor();
+ assert.strictEqual(matrix.scale(new THREE.Vector3(2, 3, 4)), matrix);
+ assert.deepEqual(matrix.toArray(), [2, 10, 18, 26, 6, 18, 30, 42, 12, 28, 44, 60, 4, 8, 12, 16]);
+});
+
+test("Matrix4.multiplyScalar multiplies every element in place, as three.js does", () => {
+ const matrix = rowMajor();
+ assert.strictEqual(matrix.multiplyScalar(2), matrix);
+ assert.deepEqual(matrix.toArray(), [2, 10, 18, 26, 4, 12, 20, 28, 6, 14, 22, 30, 8, 16, 24, 32]);
+});
+
+test("Matrix4.getMaxScaleOnAxis returns the longest basis column, as three.js does", () => {
+ const matrix = new THREE.Matrix4().makeRotationY(0.7).scale(new THREE.Vector3(2, -5, 3)).setPosition(100, 200, 300);
+ assert.ok(Math.abs(matrix.getMaxScaleOnAxis() - 5) < 1e-12);
+ assert.equal(new THREE.Matrix4().getMaxScaleOnAxis(), 1);
+ assert.equal(rowMajor().getMaxScaleOnAxis(), Math.sqrt(3 * 3 + 7 * 7 + 11 * 11));
+});
diff --git a/packages/scene/test/three-compat-plane.test.ts b/packages/scene/test/three-compat-plane.test.ts
new file mode 100644
index 0000000..7d19a6f
--- /dev/null
+++ b/packages/scene/test/three-compat-plane.test.ts
@@ -0,0 +1,77 @@
+// Plane, and the Ray's plane methods, as three.js r187 has them.
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import * as THREE from "../src/index.ts";
+
+const near = (a: THREE.Vector3, b: number[]) => assert.ok(a.distanceTo(new THREE.Vector3(b[0], b[1], b[2])) < 1e-12, `${a.toArray()} vs ${b}`);
+
+test("Plane: construction, distances and projection", () => {
+ const p = new THREE.Plane();
+ assert.deepEqual(p.normal.toArray(), [1, 0, 0]);
+ assert.equal(p.constant, 0);
+
+ // y = 2, facing +y.
+ p.setFromNormalAndCoplanarPoint(new THREE.Vector3(0, 1, 0), new THREE.Vector3(5, 2, -3));
+ assert.equal(p.constant, -2);
+ assert.equal(p.distanceToPoint(new THREE.Vector3(0, 5, 0)), 3);
+ assert.equal(p.distanceToPoint(new THREE.Vector3(0, -1, 0)), -3);
+ near(p.projectPoint(new THREE.Vector3(1, 7, 4)), [1, 2, 4]);
+ near(p.coplanarPoint(), [0, 2, 0]);
+ assert.equal(p.distanceToSphere(new THREE.Sphere(new THREE.Vector3(0, 5, 0), 1)), 2);
+ assert.equal(p.intersectsSphere(new THREE.Sphere(new THREE.Vector3(0, 5, 0), 3)), true);
+ assert.equal(p.intersectsSphere(new THREE.Sphere(new THREE.Vector3(0, 5, 0), 2.9)), false);
+
+ const box = new THREE.Box3(new THREE.Vector3(-1, 1, -1), new THREE.Vector3(1, 3, 1));
+ assert.equal(p.intersectsBox(box), true);
+ assert.equal(p.intersectsBox(new THREE.Box3(new THREE.Vector3(-1, 2.5, -1), new THREE.Vector3(1, 3, 1))), false);
+
+ const q = p.clone().negate();
+ assert.deepEqual(q.normal.toArray(), [-0, -1, -0]);
+ assert.equal(q.constant, 2);
+ assert.equal(p.equals(p.clone()), true);
+ assert.equal(p.equals(q), false);
+
+ // setComponents + normalize scale both parts.
+ const r = new THREE.Plane().setComponents(0, 0, 2, 4).normalize();
+ assert.deepEqual(r.normal.toArray(), [0, 0, 1]);
+ assert.equal(r.constant, 2);
+
+ p.translate(new THREE.Vector3(9, 1, 9));
+ assert.equal(p.constant, -3);
+});
+
+test("Plane.setFromCoplanarPoints: faces the side the points run counter-clockwise from", () => {
+ const p = new THREE.Plane().setFromCoplanarPoints(new THREE.Vector3(0, 0, 1), new THREE.Vector3(1, 0, 1), new THREE.Vector3(0, 1, 1));
+ near(p.normal, [0, 0, 1]);
+ assert.equal(p.constant, -1);
+});
+
+test("Plane.applyMatrix4: the normal goes through the normal matrix", () => {
+ // The plane x + y = 0 (normal (1,1,0)/√2), scaled 2x along x and moved by (1, 0, 0).
+ const m = new THREE.Matrix4().compose(new THREE.Vector3(1, 0, 0), new THREE.Quaternion(), new THREE.Vector3(2, 1, 1));
+ const p = new THREE.Plane(new THREE.Vector3(1, 1, 0).normalize(), 0).applyMatrix4(m);
+ // Points (t, -t, z) map to (2t + 1, -t, z): the plane x + 2y = 1.
+ near(p.normal, [1 / Math.sqrt(5), 2 / Math.sqrt(5), 0]);
+ assert.ok(Math.abs(p.constant + 1 / Math.sqrt(5)) < 1e-12);
+ for (const t of [-3, 0.5, 2]) assert.ok(Math.abs(p.distanceToPoint(new THREE.Vector3(2 * t + 1, -t, 7))) < 1e-12);
+});
+
+test("Ray.intersectPlane / distanceToPlane / intersectsPlane", () => {
+ const ground = new THREE.Plane(new THREE.Vector3(0, 1, 0), 0);
+ const down = new THREE.Ray(new THREE.Vector3(1, 4, 2), new THREE.Vector3(0, -1, 0));
+ assert.equal(down.distanceToPlane(ground), 4);
+ near(down.intersectPlane(ground, new THREE.Vector3())!, [1, 0, 2]);
+ assert.equal(down.intersectsPlane(ground), true);
+
+ const up = new THREE.Ray(new THREE.Vector3(1, 4, 2), new THREE.Vector3(0, 1, 0));
+ assert.equal(up.distanceToPlane(ground), null);
+ assert.equal(up.intersectPlane(ground, new THREE.Vector3()), null);
+ assert.equal(up.intersectsPlane(ground), false);
+
+ const parallel = new THREE.Ray(new THREE.Vector3(0, 1, 0), new THREE.Vector3(1, 0, 0));
+ assert.equal(parallel.distanceToPlane(ground), null);
+ assert.equal(parallel.intersectsPlane(ground), false);
+ const onIt = new THREE.Ray(new THREE.Vector3(3, 0, 0), new THREE.Vector3(1, 0, 0));
+ assert.equal(onIt.distanceToPlane(ground), 0);
+ assert.equal(onIt.intersectsPlane(ground), true);
+});
diff --git a/packages/scene/test/three-compat-quaternion-ops.test.ts b/packages/scene/test/three-compat-quaternion-ops.test.ts
index 9b76228..f6f67d0 100644
--- a/packages/scene/test/three-compat-quaternion-ops.test.ts
+++ b/packages/scene/test/three-compat-quaternion-ops.test.ts
@@ -31,3 +31,26 @@ test("Quaternion.setFromUnitVectors: quarter-turn, opposite axes, and identity",
assert.ok(unchanged.angleTo(new THREE.Quaternion()) < 1e-12);
assert.ok(Math.abs(unchanged.dot(unchanged) - 1) < 1e-12);
});
+
+test("Quaternion.identity / conjugate / length / lengthSq / slerpQuaternions / toArray(array, offset), as three.js has them", () => {
+ const q = new THREE.Quaternion(1, 2, 3, 4);
+ assert.equal(q.lengthSq(), 30);
+ assert.ok(Math.abs(q.length() - Math.sqrt(30)) < 1e-12);
+ assert.deepEqual(q.clone().conjugate().toArray(), [-1, -2, -3, 4]);
+ assert.deepEqual(q.clone().identity().toArray(), [0, 0, 0, 1]);
+ assert.deepEqual(q.toArray([9], 1), [9, 1, 2, 3, 4]);
+ const into = new Float32Array(4);
+ assert.equal(q.toArray(into), into);
+ assert.deepEqual([...into], [1, 2, 3, 4]);
+
+ const a = new THREE.Quaternion();
+ const b = new THREE.Quaternion().setFromAxisAngle(new THREE.Vector3(0, 1, 0), Math.PI / 2);
+ const mid = new THREE.Quaternion().slerpQuaternions(a, b, 0.5);
+ const expected = new THREE.Quaternion().setFromAxisAngle(new THREE.Vector3(0, 1, 0), Math.PI / 4);
+ assert.ok(Math.abs(mid.dot(expected) - 1) < 1e-12);
+ assert.deepEqual(a.toArray(), [0, 0, 0, 1], "the inputs are left alone");
+
+ const object = new THREE.Object3D();
+ object.quaternion.slerpQuaternions(a, b, 1);
+ assert.ok(Math.abs(object.rotation.y - Math.PI / 2) < 1e-9, "the object's rotation follows");
+});
diff --git a/packages/scene/test/three-compat-sphere-queries.test.ts b/packages/scene/test/three-compat-sphere-queries.test.ts
new file mode 100644
index 0000000..111ed9c
--- /dev/null
+++ b/packages/scene/test/three-compat-sphere-queries.test.ts
@@ -0,0 +1,46 @@
+// Sphere set, emptiness, point and sphere queries and transforms, parity with three.js r187.
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import * as THREE from "../src/index.ts";
+
+test("Sphere.set, copy, equals, isEmpty and makeEmpty", () => {
+ const s = new THREE.Sphere();
+ assert.equal(s.isSphere, true);
+ assert.equal(s.isEmpty(), true);
+ const c = new THREE.Vector3(1, 2, 3);
+ assert.strictEqual(s.set(c, 0), s);
+ assert.notStrictEqual(s.center, c);
+ assert.equal(s.isEmpty(), false);
+ const t = new THREE.Sphere().copy(s);
+ assert.equal(t.equals(s), true);
+ t.radius = 0.5;
+ assert.equal(t.equals(s), false);
+ assert.strictEqual(t.makeEmpty(), t);
+ assert.deepEqual(t.center.toArray(), [0, 0, 0]);
+ assert.equal(t.radius, -1);
+ assert.equal(t.isEmpty(), true);
+});
+
+test("Sphere.containsPoint, distanceToPoint and intersectsSphere", () => {
+ const s = new THREE.Sphere(new THREE.Vector3(1, 0, 0), 2);
+ assert.equal(s.containsPoint(new THREE.Vector3(3, 0, 0)), true);
+ assert.equal(s.containsPoint(new THREE.Vector3(3.01, 0, 0)), false);
+ assert.equal(s.distanceToPoint(new THREE.Vector3(1, 5, 0)), 3);
+ assert.equal(s.distanceToPoint(new THREE.Vector3(1, 0, 0)), -2);
+ assert.equal(s.intersectsSphere(new THREE.Sphere(new THREE.Vector3(1, 0, 5), 3)), true);
+ assert.equal(s.intersectsSphere(new THREE.Sphere(new THREE.Vector3(1, 0, 5), 2.99)), false);
+});
+
+test("Sphere.applyMatrix4 scales the radius by the largest axis scale; translate moves the centre", () => {
+ const m = new THREE.Matrix4().compose(
+ new THREE.Vector3(10, 0, 0),
+ new THREE.Quaternion().setFromAxisAngle(new THREE.Vector3(0, 0, 1), Math.PI / 2),
+ new THREE.Vector3(1, 3, 2),
+ );
+ const s = new THREE.Sphere(new THREE.Vector3(1, 0, 0), 2);
+ assert.strictEqual(s.applyMatrix4(m), s);
+ assert.ok(Math.abs(s.center.x - 10) < 1e-12 && Math.abs(s.center.y - 1) < 1e-12 && s.center.z === 0);
+ assert.ok(Math.abs(s.radius - 6) < 1e-12);
+ assert.strictEqual(s.translate(new THREE.Vector3(0, 0, 4)), s);
+ assert.equal(s.center.z, 4);
+});
diff --git a/packages/scene/test/three-compat-vector2-arith.test.ts b/packages/scene/test/three-compat-vector2-arith.test.ts
new file mode 100644
index 0000000..13c3773
--- /dev/null
+++ b/packages/scene/test/three-compat-vector2-arith.test.ts
@@ -0,0 +1,61 @@
+// Vector2's component-wise arithmetic and plane geometry, checked against three.js r187 itself on the same inputs.
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import * as THREE from "three";
+import * as TRT from "../src/index.ts";
+
+// Each case runs on both libraries, so the constructor is typed loosely.
+type Ctor = new (x?: number, y?: number) => any;
+type V2 = { x: number; y: number; toArray(): number[] };
+const cases: Array<[string, (V: Ctor) => unknown]> = [
+ ["setX / setY", (V) => new V(1, 2).setX(-4).setY(-0)],
+ ["setComponent / getComponent", (V) => [0, 1].map((i) => new V(7, -8).setComponent(i, 3).getComponent(i))],
+ ["addScalar", (V) => new V(1, -2).addScalar(0.5)],
+ ["addVectors", (V) => new V().addVectors(new V(1, 2), new V(-4, 0.25))],
+ ["addScaledVector", (V) => new V(1, 2).addScaledVector(new V(-4, 0.25), 2)],
+ ["subScalar", (V) => new V(1, -2).subScalar(2)],
+ ["subVectors", (V) => new V().subVectors(new V(1, 2), new V(-4, 0.25))],
+ ["multiply", (V) => new V(1, -2).multiply(new V(4, 5))],
+ ["divide", (V) => new V(1, -2).divide(new V(4, 0))],
+ ["divideScalar", (V) => new V(1, -2).divideScalar(4)],
+ ["min", (V) => new V(1, -2).min(new V(0, 5))],
+ ["max", (V) => new V(1, -2).max(new V(0, 5))],
+ ["clamp", (V) => new V(-5, 9).clamp(new V(-1, 0), new V(1, 2))],
+ ["clampScalar", (V) => new V(-5, 0.5).clampScalar(-1, 2)],
+ ["clampLength above", (V) => new V(3, 4).clampLength(1, 2)],
+ ["clampLength below", (V) => new V(0.3, 0.4).clampLength(1, 2)],
+ ["clampLength of zero", (V) => new V(0, 0).clampLength(1, 2)],
+ ["floor", (V) => new V(-1.5, -0.2).floor()],
+ ["ceil", (V) => new V(-1.5, -0.2).ceil()],
+ ["round", (V) => new V(-1.5, 2.5).round()],
+ ["negate", (V) => new V(1, 0).negate()],
+ ["lengthSq", (V) => new V(3, -4).lengthSq()],
+ ["manhattanLength", (V) => new V(1, -2).manhattanLength()],
+ ["setLength", (V) => new V(3, 4).setLength(10)],
+ ["angle", (V) => [[1, 0], [0, 1], [-1, 0], [0, -1], [1, -1], [0, 0], [-1, -0]].map(([x, y]) => new V(x, y).angle())],
+ ["angleTo", (V) => [new V(1, 0).angleTo(new V(0, 2)), new V(1, 1).angleTo(new V(-2, -2)), new V().angleTo(new V(1, 0))]],
+ ["distanceToSquared", (V) => new V(1, 2).distanceToSquared(new V(4, 6))],
+ ["manhattanDistanceTo", (V) => new V(1, 2).manhattanDistanceTo(new V(4, -6))],
+ ["lerpVectors", (V) => new V().lerpVectors(new V(0, 10), new V(4, -10), 0.25)],
+ ["rotateAround", (V) => new V(2, 1).rotateAround(new V(1, 1), Math.PI / 3)],
+];
+
+const plain = (r: unknown) => (r && typeof r === "object" && "toArray" in r ? (r as V2).toArray() : r);
+
+for (const [name, run] of cases) {
+ test(`Vector2.${name} matches three.js`, () => {
+ assert.deepEqual(plain(run(TRT.Vector2)), plain(run(THREE.Vector2)));
+ });
+}
+
+test("Vector2's arithmetic is chainable and returns the same vector", () => {
+ const v = new TRT.Vector2(1, 2);
+ assert.equal(v.addScalar(1).subScalar(1).multiply(new TRT.Vector2(1, 1)).negate().floor().setX(0).rotateAround(new TRT.Vector2(), 1), v);
+});
+
+test("set / getComponent throw on an out-of-range index, as three.js does", () => {
+ for (const V of [TRT.Vector2, THREE.Vector2] as Ctor[]) {
+ assert.throws(() => new V().getComponent(2), /index is out of range: 2/);
+ assert.throws(() => new V().setComponent(2, 1), /index is out of range: 2/);
+ }
+});
diff --git a/packages/scene/test/three-compat-vector3-arith.test.ts b/packages/scene/test/three-compat-vector3-arith.test.ts
new file mode 100644
index 0000000..31acfeb
--- /dev/null
+++ b/packages/scene/test/three-compat-vector3-arith.test.ts
@@ -0,0 +1,68 @@
+// Vector3's component-wise arithmetic, checked against three.js r187 itself on the same inputs.
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import * as THREE from "three";
+import * as TRT from "../src/index.ts";
+
+// Each case runs on both libraries, so the constructor is typed loosely.
+type Ctor = new (x?: number, y?: number, z?: number) => any;
+type V3 = { x: number; y: number; z: number; toArray(): number[] };
+const cases: Array<[string, (V: Ctor) => unknown]> = [
+ ["setX / setY / setZ", (V) => new V(1, 2, 3).setX(-4).setY(5.5).setZ(-0)],
+ ["getComponent", (V) => [0, 1, 2].map((i) => new V(7, -8, 9).getComponent(i))],
+ ["addScalar", (V) => new V(1, -2, 3).addScalar(0.5)],
+ ["addVectors", (V) => new V().addVectors(new V(1, 2, 3), new V(-4, 0.25, 6))],
+ ["subScalar", (V) => new V(1, -2, 3).subScalar(2)],
+ ["multiply", (V) => new V(1, -2, 3).multiply(new V(4, 5, -6))],
+ ["multiplyVectors", (V) => new V().multiplyVectors(new V(1, -2, 3), new V(4, 5, -6))],
+ ["divide", (V) => new V(1, -2, 3).divide(new V(4, 0, -6))],
+ ["divideScalar", (V) => new V(1, -2, 3).divideScalar(4)],
+ ["divideScalar by zero", (V) => new V(1, -2, 0).divideScalar(0)],
+ ["min", (V) => new V(1, -2, 3).min(new V(0, 5, 3))],
+ ["max", (V) => new V(1, -2, 3).max(new V(0, 5, 3))],
+ ["clamp", (V) => new V(-5, 0.5, 9).clamp(new V(-1, 0, 0), new V(1, 1, 2))],
+ ["clampScalar", (V) => new V(-5, 0.5, 9).clampScalar(-1, 2)],
+ ["clampLength above", (V) => new V(3, 4, 0).clampLength(1, 2)],
+ ["clampLength below", (V) => new V(0.3, 0.4, 0).clampLength(1, 2)],
+ ["clampLength of zero", (V) => new V(0, 0, 0).clampLength(1, 2)],
+ ["floor", (V) => new V(-1.5, 1.5, -0.2).floor()],
+ ["ceil", (V) => new V(-1.5, 1.5, -0.2).ceil()],
+ ["round", (V) => new V(-1.5, 1.5, 2.5).round()],
+ ["roundToZero", (V) => new V(-1.7, 1.7, -0.2).roundToZero()],
+ ["negate", (V) => new V(1, -2, 0).negate()],
+ ["manhattanLength", (V) => new V(1, -2, 3).manhattanLength()],
+ ["setLength", (V) => new V(0, 3, 4).setLength(10)],
+ ["setLength of zero", (V) => new V(0, 0, 0).setLength(10)],
+ ["lerpVectors", (V) => new V().lerpVectors(new V(0, 10, -2), new V(4, -10, 2), 0.25)],
+ ["distanceToSquared", (V) => new V(1, 2, 3).distanceToSquared(new V(4, 6, 3))],
+ ["manhattanDistanceTo", (V) => new V(1, 2, 3).manhattanDistanceTo(new V(4, -6, 3))],
+ ["equals", (V) => [new V(1, 2, 3).equals(new V(1, 2, 3)), new V(1, 2, 3).equals(new V(1, 2, 3.0001))]],
+];
+
+const plain = (r: unknown) => (r && typeof r === "object" && "toArray" in r ? (r as V3).toArray() : r);
+
+for (const [name, run] of cases) {
+ test(`Vector3.${name} matches three.js`, () => {
+ assert.deepEqual(plain(run(TRT.Vector3)), plain(run(THREE.Vector3)));
+ });
+}
+
+test("Vector3's arithmetic is chainable and returns the same vector", () => {
+ const v = new TRT.Vector3(1, 2, 3);
+ assert.equal(v.addScalar(1).subScalar(1).multiply(new TRT.Vector3(1, 1, 1)).negate().floor().setX(0), v);
+});
+
+test("getComponent throws on an out-of-range index, as three.js does", () => {
+ assert.throws(() => new TRT.Vector3().getComponent(3), /index is out of range: 3/);
+ assert.throws(() => new THREE.Vector3().getComponent(3), /index is out of range: 3/);
+});
+
+test("arithmetic on an object's position reports the change: the object's matrix follows", () => {
+ const o = new TRT.Object3D();
+ o.position.set(1, 2, 3);
+ o.updateMatrixWorld();
+ o.position.multiplyScalar(2).addScalar(1).negate();
+ o.updateMatrixWorld();
+ assert.deepEqual(o.position.toArray(), [-3, -5, -7]);
+ assert.deepEqual([o.matrixWorld.elements[12], o.matrixWorld.elements[13], o.matrixWorld.elements[14]], [-3, -5, -7]);
+});
diff --git a/packages/voxel/src/native.ts b/packages/voxel/src/native.ts
index 086f4e8..1f94b52 100644
--- a/packages/voxel/src/native.ts
+++ b/packages/voxel/src/native.ts
@@ -193,7 +193,7 @@ export class VoxelBody extends Object3D {
};
Object.defineProperty(this, "position", { configurable: true, enumerable: true, get: () => (pull(), p) });
Object.defineProperty(this, "quaternion", { configurable: true, enumerable: true, get: () => (pull(), q) });
- Object.defineProperty(this, "rotation", { configurable: true, enumerable: true, get: () => (pull(), e.setFromQuaternion(q, false), e) });
+ Object.defineProperty(this, "rotation", { configurable: true, enumerable: true, get: () => (pull(), e.setFromQuaternion(q, undefined, false), e) });
}
/** @internal The engine's record of it, taken in. */