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: Color.lerpColors, as three.js has it (#120)

Kevin Rajan8b4f4ea3db0c
diff --git a/packages/scene/src/math.ts b/packages/scene/src/math.ts
index 313d094..1016557 100644
--- a/packages/scene/src/math.ts
+++ b/packages/scene/src/math.ts
@@ -566,6 +566,14 @@ export class Color {
lerp(c: Color, t: number): this {
return this.setRGB(this.r + (c.r - this.r) * t, this.g + (c.g - this.g) * t, this.b + (c.b - this.b) * t);
}
+ /** Interpolates two source colors in linear RGB, regardless of this color's previous value. */
+ lerpColors(color1: Color, color2: Color, alpha: number): this {
+ return this.setRGB(
+ color1.r + (color2.r - color1.r) * alpha,
+ color1.g + (color2.g - color1.g) * alpha,
+ color1.b + (color2.b - color1.b) * alpha,
+ );
+ }
add(c: Color): this {
return this.setRGB(this.r + c.r, this.g + c.g, this.b + c.b);
}
diff --git a/packages/scene/test/three-compat-color.test.ts b/packages/scene/test/three-compat-color.test.ts
new file mode 100644
index 0000000..9c1344f
--- /dev/null
+++ b/packages/scene/test/three-compat-color.test.ts
@@ -0,0 +1,16 @@
+// three.js compatibility: Color.lerpColors, 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("Color: lerpColors uses two source colors rather than the receiver, as three.js does", () => {
+ const red = new THREE.Color().setRGB(1, 0, 0);
+ const blue = new THREE.Color().setRGB(0, 0, 1);
+ const mixed = new THREE.Color().setRGB(0, 1, 0);
+ assert.equal(mixed.lerpColors(red, blue, 0.25), mixed, "returns the receiver");
+ assert.deepEqual(mixed.toArray(), [0.75, 0, 0.25], "mixes linear RGB, not the receiver's original green");
+ assert.deepEqual(mixed.lerpColors(red, blue, 0).toArray(), [1, 0, 0], "alpha zero gives color1");
+ assert.deepEqual(mixed.lerpColors(red, blue, 1).toArray(), [0, 0, 1], "alpha one gives color2");
+ assert.deepEqual(red.toArray(), [1, 0, 0], "does not mutate color1");
+ assert.deepEqual(blue.toArray(), [0, 0, 1], "does not mutate color2");
+});