Skip to content

Commit a9ed552

Browse files
obiotclaude
andauthored
Light3d: take a Vector3d for direction and position (melonjs#1663)
Both were `[number, number, number]` read by index, so a `Vector3d` — the obvious thing to reach for when an option is named `direction` in a 3D engine — set all three components to `undefined`, `normalize()` kept them `NaN`, and the light contributed nothing. Silently: no warning, and the scene still renders with whatever else is lit. `color` on the same options object already accepts a `Color`, a CSS string or an array, so this makes the object consistent with itself rather than adding a new idea. The value is READ, not retained — the light keeps its own normalized vector, and moving yours afterwards does not steer it. Additive: widening the union leaves every array call compiling and on the identical path. The only behaviour that changes is passing a `Vector3d`, which produced no light at all. Three shipped examples got this wrong, which is why it is worth the branch. Closes melonjs#1661 Claude-Session: https://claude.ai/code/session_01NGvtaUNATVCVxD2qcbiY4t Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
1 parent e9c8cc9 commit a9ed552

4 files changed

Lines changed: 109 additions & 33 deletions

File tree

‎packages/melonjs/CHANGELOG.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,8 @@
99
- `save`: registered keys are reachable from TypeScript without a cast. The namespace was typed `Record<string, unknown>`, and that index signature swallowed its own members, so under `strict` `save.add()` was `unknown` and could not be called at all. `add()` now returns the namespace typed with the keys just registered, and chained calls accumulate
1010
- `audio.tone()` and `audio.noise()` take a `delay` in seconds, scheduled on the audio clock, so a multi-part sound — a stinger's second note, an explosion's double-tap — sequences without a `setTimeout`. A timer fires on the main thread and a busy frame slips the note; this is scheduled up front and is sample-accurate. Omitting it is unchanged
1111

12+
- `Light3d`: `direction` and `position` accept a `Vector3d` as well as an `[x, y, z]` array, so a value the game already holds goes straight in — `color` already took a `Color`, a string or an array. The vector is read, not retained. Passing one used to be read by index and silently produce a `NaN` direction, so the light contributed nothing ([#1661](https://github.com/melonjs/melonJS/issues/1661))
13+
1214
### Fixed
1315
- Renderable: opacity now cascades — `alpha` multiplies with the alpha already on the renderer instead of replacing it, so a child at 0.5 inside a parent at 0.5 draws at 0.25. **A nested renderable that was visibly opaque under a faded ancestor will now fade with it**
1416
- GLTFModel: a loaded model reported no bounds at all, so a model with a `Body` was filed in the broadphase away from where it stood and collided with nothing. Its extent now comes from the glTF bounding box, measured once at load

‎packages/melonjs/skills/melonjs-3d/SKILL.md‎

Lines changed: 16 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -478,19 +478,24 @@ default), `"ambient"`, `"point"` and `"spot"`.
478478
```js
479479
world.addChild(new Light3d({ type: "directional", direction: [0.3, 1, 0.2] }));
480480
world.addChild(new Light3d({ type: "ambient", intensity: 0.3 }));
481+
// a Vector3d works too, wherever the game already has one
482+
world.addChild(new Light3d({ type: "spot", position: torch.pos, range: 400 }));
481483
```
482484

483-
Both of that call's traps fail **silently**, and they compound:
484-
485-
- `new Light3d(0, 0, {…})` — JavaScript drops the extra arguments, so `options`
486-
becomes the number `0` and every setting in your literal is discarded. The
487-
light still appears, on pure defaults: a `type: "ambient"` written this way is
488-
a second DIRECTIONAL light, and the scene looks plausible enough that nobody
489-
checks.
490-
- `direction: new Vector3d(x, y, z)` — `direction` and `position` are `[x, y, z]`
491-
**arrays**, read by index. A `Vector3d` has no `[0]`, so the light's direction
492-
becomes `NaN` and it contributes nothing. (`color` is the odd one out: it does
493-
take a `Color`, a CSS string or an `[r, g, b]` array.)
485+
`direction` and `position` take an `[x, y, z]` array **or** a `Vector3d`, and
486+
`color` takes a `Color`, a CSS string or an `[r, g, b]` array — so a value the
487+
game already holds can go straight in. Each is read, not retained: move your
488+
vector afterwards and the light stays where it was.
489+
490+
Two things still bite, both silently:
491+
492+
- `new Light3d(0, 0, {…})` — the constructor takes **options alone**. JavaScript
493+
drops the extra arguments, so `options` becomes the number `0` and every
494+
setting in your literal is discarded. The light still appears, on pure
495+
defaults: a `type: "ambient"` written this way is a second DIRECTIONAL light,
496+
and the scene looks plausible enough that nobody checks. TypeScript stops
497+
checking a literal once the argument count is wrong, so nothing inside it is
498+
verified either.
494499
- **`direction` is where the light GOES, and this is a Y-down space** — so a sun
495500
overhead travels *downward* and its Y is **positive**. Get the sign wrong and
496501
the scene is lit from underneath: faces that should be in shade are bright,
@@ -504,11 +509,6 @@ Both of that call's traps fail **silently**, and they compound:
504509
`position` follows the same convention: a lamp above the floor has a
505510
**smaller** y than the floor.
506511

507-
They hide behind each other: TypeScript stops checking an object literal once
508-
the argument count is already wrong, so fixing the call reveals the `Vector3d`,
509-
and fixing that finally lets the sign show. A scene can go from "looks fine" to
510-
"entirely black" to "lit from below" across three apparently-correct edits.
511-
512512
Use **both halves**: with a key light but no ambient, the shadow side of a mesh
513513
goes black. With no `Light3d` in the world at all, a `lit: true` mesh falls back
514514
to a white ambient and renders fullbright — indistinguishable from unlit, which

‎packages/melonjs/src/lighting/light3d.ts‎

Lines changed: 45 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -24,15 +24,19 @@ export interface Light3dOptions {
2424
* late-afternoon sun. A negative Y lights everything from underneath,
2525
* which reads instantly as wrong and is the usual mistake here.
2626
*
27-
* An `[x, y, z]` array, read by index — a `Vector3d` has no `[0]`, so
28-
* passing one yields `NaN` and the light contributes nothing at all.
27+
* Either an `[x, y, z]` array or a {@link Vector3d} — as
28+
* {@link Light3dOptions.color} already takes several forms. The vector is
29+
* READ, not retained: {@link Light3d#direction} remains the engine's own,
30+
* and normalized, so mutating what you passed in afterwards changes
31+
* nothing.
2932
*/
30-
direction?: [number, number, number];
33+
direction?: [number, number, number] | Vector3d;
3134
/**
32-
* World-space position (point and spot lights), as an `[x, y, z]` array.
33-
* Y-down again: a lamp above the floor has a **smaller** y than the floor.
35+
* World-space position (point and spot lights), as an `[x, y, z]` array or
36+
* a {@link Vector3d}. Y-down again: a lamp above the floor has a
37+
* **smaller** y than the floor.
3438
*/
35-
position?: [number, number, number];
39+
position?: [number, number, number] | Vector3d;
3640
/**
3741
* light color — a {@link Color}, a CSS color string, or an `[r, g, b]`
3842
* array with components in `0..1` (the glTF convention). Defaults to white.
@@ -98,9 +102,41 @@ export interface Light3dOptions {
98102
* range: 800, innerConeAngle: 0.2, outerConeAngle: 0.45,
99103
* }));
100104
*
101-
* // animate the sun in-game (direction is the way light travels)
105+
* // `direction` and `position` also take a Vector3d, so a value the game
106+
* // already keeps can be handed over without unpacking it. It is READ, not
107+
* // retained — move the vector afterwards and the light does not follow.
108+
* app.world.addChild(new Light3d({
109+
* type: "spot",
110+
* position: torch.pos,
111+
* direction: new Vector3d(0, 1, 0.4),
112+
* }));
113+
*
114+
* // animate the sun in-game (direction is the way light travels). Y-down, so
115+
* // a positive Y is a sun overhead; a negative one lights from underneath.
102116
* sun.direction.set(Math.sin(t), 1, Math.cos(t)).normalize();
103117
*/
118+
/**
119+
* Read an `[x, y, z]` array or a {@link Vector3d} into `out`.
120+
*
121+
* Both forms are accepted for the same reason `color` accepts a {@link Color},
122+
* a CSS string or an array: a `Vector3d` is the obvious thing to reach for when
123+
* an option is named `direction`, and index-reading one silently produces
124+
* `NaN`. The value is copied, never retained.
125+
* @param out - the vector the light owns
126+
* @param value - what the caller passed
127+
* @returns `out`
128+
* @ignore
129+
* @internal
130+
*/
131+
function readVector(
132+
out: Vector3d,
133+
value: [number, number, number] | Vector3d,
134+
): Vector3d {
135+
return Array.isArray(value)
136+
? out.set(value[0], value[1], value[2])
137+
: out.set(value.x, value.y, value.z);
138+
}
139+
104140
export class Light3d extends Renderable {
105141
/** `"directional"`, `"ambient"`, `"point"` or `"spot"`. */
106142
override type: "directional" | "ambient" | "point" | "spot";
@@ -136,21 +172,13 @@ export class Light3d extends Renderable {
136172

137173
this.direction = new Vector3d(0, 1, 0);
138174
if (options.direction) {
139-
this.direction.set(
140-
options.direction[0],
141-
options.direction[1],
142-
options.direction[2],
143-
);
175+
readVector(this.direction, options.direction);
144176
}
145177
this.direction.normalize();
146178

147179
this.position = new Vector3d(0, 0, 0);
148180
if (options.position) {
149-
this.position.set(
150-
options.position[0],
151-
options.position[1],
152-
options.position[2],
153-
);
181+
readVector(this.position, options.position);
154182
}
155183

156184
if (options.color instanceof Color) {

‎packages/melonjs/tests/lighting3d.spec.js‎

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import {
66
Light3d,
77
Stage,
88
state,
9+
Vector3d,
910
video,
1011
} from "../src/index.js";
1112
import Renderable from "../src/renderable/renderable.js";
@@ -32,6 +33,51 @@ describe("Light3d", () => {
3233
expect([l.direction.x, l.direction.y, l.direction.z]).toEqual([0, 1, 0]);
3334
});
3435

36+
it("takes a Vector3d for direction, the same as an array", () => {
37+
const fromArray = new Light3d({ direction: [-0.35, 0.8, 0.45] });
38+
const fromVector = new Light3d({
39+
direction: new Vector3d(-0.35, 0.8, 0.45),
40+
});
41+
42+
// identical, not merely close: both go through the same normalize
43+
expect(fromVector.direction.x).toBe(fromArray.direction.x);
44+
expect(fromVector.direction.y).toBe(fromArray.direction.y);
45+
expect(fromVector.direction.z).toBe(fromArray.direction.z);
46+
// and it is a real direction rather than the NaN an index-read produced
47+
expect(Number.isFinite(fromVector.direction.x)).toBe(true);
48+
expect(fromVector.direction.length()).toBeCloseTo(1, 5);
49+
});
50+
51+
it("takes a Vector3d for position, the same as an array", () => {
52+
const fromArray = new Light3d({ type: "point", position: [120, -40, 60] });
53+
const fromVector = new Light3d({
54+
type: "point",
55+
position: new Vector3d(120, -40, 60),
56+
});
57+
expect([
58+
fromVector.position.x,
59+
fromVector.position.y,
60+
fromVector.position.z,
61+
]).toEqual([
62+
fromArray.position.x,
63+
fromArray.position.y,
64+
fromArray.position.z,
65+
]);
66+
});
67+
68+
it("reads the vector rather than retaining it", () => {
69+
// a caller's vector is theirs — moving it afterwards must not steer the
70+
// light, and the light must not be able to write back into it
71+
const mine = new Vector3d(0, 1, 0);
72+
const l = new Light3d({ type: "spot", position: mine, direction: mine });
73+
mine.set(99, 99, 99);
74+
75+
expect(l.position.x).toBe(0);
76+
expect(l.direction.y).toBeCloseTo(1, 5);
77+
expect(l.position).not.toBe(mine);
78+
expect(l.direction).not.toBe(mine);
79+
});
80+
3581
it("normalizes the direction on construction", () => {
3682
const l = new Light3d({ direction: [0, 5, 0] });
3783
expect(l.direction.length()).toBeCloseTo(1, 5);

0 commit comments

Comments
 (0)