@waica/engine 0.13.0 → 0.14.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -6,6 +6,47 @@ Waica's public engine core: entities and components, the game loop, scene and pr
6
6
  import { Component, Game, loadScene } from '@waica/engine'
7
7
  ```
8
8
 
9
+ ## Logical spatial queries
10
+
11
+ Every `Game` owns one stable `game.query` service. Queries use logical XY coordinates, including in isometric scenes, and return typed live engine objects:
12
+
13
+ ```ts
14
+ import { Component, type CollisionBody, type Entity, type Game } from '@waica/engine'
15
+
16
+ declare const game: Game
17
+ declare const player: Entity
18
+
19
+ class Faction extends Component {
20
+ name = 'neutral'
21
+ }
22
+
23
+ const search: CollisionBody = { x: 0, y: 0, width: 8, height: 6 }
24
+ const nearby = game.query.area(search, {
25
+ with: [Faction] as const,
26
+ exclude: player,
27
+ where: (entity) => entity.get(Faction).name !== 'friendly',
28
+ })
29
+
30
+ // `with` makes this non-optional at compile time.
31
+ nearby[0]?.get(Faction).name
32
+ ```
33
+
34
+ | Method | Spatial domain | Result |
35
+ | --- | --- | --- |
36
+ | `area(body, filter?)` | Hitbox collision outlines | All overlapping Hitbox owners |
37
+ | `point(x, y, filter?)` | Hitbox collision outlines | All strict point containers |
38
+ | `nearest(x, y, filter?)` | Entity logical transforms | The nearest Entity or `null` |
39
+ | `ray(x, y, dx, dy, maxDistance, filter?)` | Direct and source-derived Solids | The first `RayHit` or `null` |
40
+ | `Pointer` picking | Sprite visuals in projected/render space | The front-most visual owner |
41
+
42
+ Every filter can require all classes in `with`, reject any class in `without`, exclude one Entity, a readonly Entity array, or a `ReadonlySet` by identity, and apply a final `where` predicate. `nearest` also accepts inclusive `maxDistance` and passes `{ distance }` to `where`. Filters compose conjunctively. Ray filters apply to each Solid's owner; for example, a generated Tilemap Solid can match `with: [Tilemap]`, but only an owner with a direct Solid matches `with: [Solid]`.
43
+
44
+ Calls eagerly snapshot candidates that are alive at call start. Results preserve scene/source order, and ties keep the first candidate. Later spawns do not enter a result and later destruction does not remove it. Returned Entity, Component, and Solid references remain live; a `RayHit`'s distance, point, and normal are detached query-time values.
45
+
46
+ Invalid inputs fail closed without throwing: invalid `area` bodies and non-finite point coordinates return `[]`; invalid nearest coordinates or radii return `null`; and ray returns `null` for non-finite values, a zero direction, or a negative distance. Nearest permits positive `Infinity`; ray distance must be finite and may be zero. Zero-area candidate geometry never matches.
47
+
48
+ Area and point intentionally use the collision system's polygonally approximated circle/ellipse outline. Ray queries intersect circle-shaped Solids as analytic ellipses and return their exact outward unit normal.
49
+
9
50
  ## Component lifecycle
10
51
 
11
52
  Waica keeps the lifecycle boundaries distinct:
@@ -1,3 +1,4 @@
1
+ import { SIMULATION_TIME_EPSILON } from '../fixed-step.js';
1
2
  /**
2
3
  * Advances a clip through time. Pure logic (no three, no DOM) so it can
3
4
  * be tested deterministically.
@@ -16,7 +17,11 @@ export class ClipPlayer {
16
17
  /** Advances the clock and returns the sheet frame to show. */
17
18
  advance(dt) {
18
19
  this.t += dt;
19
- const idx = Math.floor(this.t * this.fps);
20
+ // this.t is a sum of SIMULATION_STEP-sized dts, which float error can
21
+ // leave a hair under an exact multiple of a frame's duration; without
22
+ // the epsilon, floor(t * fps) holds some frames one step short and
23
+ // others one step long instead of a flat, even count per frame.
24
+ const idx = Math.floor((this.t + SIMULATION_TIME_EPSILON) * this.fps);
20
25
  const n = this.frames.length;
21
26
  const clamped = this.loop ? idx % n : Math.min(idx, n - 1);
22
27
  return this.frames[clamped] ?? 0;
@@ -0,0 +1,5 @@
1
+ import type { CollisionBody } from './collision-shape.js';
2
+ import type { Hitbox } from './components/hitbox.js';
3
+ import type { Solid } from './components/solid.js';
4
+ /** Package-internal conversion shared by trigger dispatch and spatial queries. */
5
+ export declare function collisionBody(component: Hitbox | Solid): CollisionBody;
@@ -0,0 +1,11 @@
1
+ /** Package-internal conversion shared by trigger dispatch and spatial queries. */
2
+ export function collisionBody(component) {
3
+ return {
4
+ x: component.entity.position.x + component.offsetX,
5
+ y: component.entity.position.y + component.offsetY,
6
+ width: component.width,
7
+ height: component.height,
8
+ shape: component.shape,
9
+ points: component.points,
10
+ };
11
+ }
@@ -0,0 +1,9 @@
1
+ /**
2
+ * Milliseconds per display frame at `hz`, for driving `Game`'s real
3
+ * animation-loop callback in a test. No epsilon pad: frame-rate snapping
4
+ * (`snapElapsedToStep`) is what makes a measured duration this close to a
5
+ * whole number of Simulation Steps count as exactly that many, not a float
6
+ * nudge chosen to dodge the exact boundary — `1000 / 60 / 1000 === 1 / 60`
7
+ * bit-for-bit already, before snapping even applies.
8
+ */
9
+ export declare const frameMs: (hz: number) => number;
@@ -0,0 +1,9 @@
1
+ /**
2
+ * Milliseconds per display frame at `hz`, for driving `Game`'s real
3
+ * animation-loop callback in a test. No epsilon pad: frame-rate snapping
4
+ * (`snapElapsedToStep`) is what makes a measured duration this close to a
5
+ * whole number of Simulation Steps count as exactly that many, not a float
6
+ * nudge chosen to dodge the exact boundary — `1000 / 60 / 1000 === 1 / 60`
7
+ * bit-for-bit already, before snapping even applies.
8
+ */
9
+ export const frameMs = (hz) => 1000 / hz;
@@ -0,0 +1,93 @@
1
+ /**
2
+ * The Simulation Step (ADR 0014): the fixed slice of game time by which the
3
+ * engine advances every component update, however often the display
4
+ * refreshes. An engine constant, not a project setting — the archetypes'
5
+ * feel is tuned against it, and the Runtime Bridge's `step` means exactly
6
+ * one of these.
7
+ */
8
+ export declare const SIMULATION_STEP: number;
9
+ /**
10
+ * The most steps one render frame may run. Beyond it the elapsed time is
11
+ * dropped, never repaid: a machine that cannot keep up falls behind the
12
+ * wall clock instead of spiralling into ever-longer frames. Six steps is
13
+ * 100 ms, the same ceiling the old per-frame clamp imposed.
14
+ */
15
+ export declare const MAX_STEPS_PER_FRAME = 6;
16
+ /**
17
+ * Floating-point slack for comparing a value built by summing many
18
+ * SIMULATION_STEP-sized deltas (a state's `elapsed`, a countdown, a clip's
19
+ * playback clock) against a target duration. Each addition can leave the
20
+ * sum a hair under the mathematically exact value — 15 additions of 1/60
21
+ * give 0.24999999999999997, not 0.25 — by an error on the order of 1e-15,
22
+ * many orders of magnitude below this. Large enough to call a step-multiple
23
+ * duration exact, far too small to ever mistake a genuinely later step for
24
+ * an earlier one.
25
+ */
26
+ export declare const SIMULATION_TIME_EPSILON = 1e-9;
27
+ /**
28
+ * Cap on same-tick, chained processing that could otherwise spin forever
29
+ * on a degenerate cycle: StateMachine settling a chain of transitions
30
+ * within one `onUpdate` (land → idle → run…) and Game draining a chain of
31
+ * `loadSceneByName` calls queued from a scene's own `onReady` within one
32
+ * frame. Shared so the two call sites' caps stay in lockstep instead of
33
+ * matching only by coincidence; eight is comfortably more hops than any
34
+ * real content chains in a single update.
35
+ */
36
+ export declare const MAX_CHAINED_HOPS = 8;
37
+ export interface SimulationSteps {
38
+ /** Whole steps this frame runs, 0 through MAX_STEPS_PER_FRAME. */
39
+ steps: number;
40
+ /** Seconds carried into the next frame; 0 whenever the cap was hit. */
41
+ remainder: number;
42
+ }
43
+ /**
44
+ * Pure accumulator: from the time retained after the last frame and the
45
+ * seconds elapsed since it, how many whole steps to run now and what to
46
+ * keep. Hitting the cap discards the whole remainder (CA-2). A non-finite
47
+ * or negative `elapsed` (a NaN timestamp delta, a backwards clock) is
48
+ * treated as zero rather than poisoning the remainder or yielding negative
49
+ * steps — hardening against inputs a real rAF timestamp never produces.
50
+ */
51
+ export declare function consumeSimulationSteps(remainder: number, elapsed: number): SimulationSteps;
52
+ /**
53
+ * How far a measured frame duration may sit from a whole number of
54
+ * Simulation Steps and still count as exactly that many (round 2
55
+ * correctness fix). Sized to absorb not just the sub-millisecond jitter a
56
+ * real 60 Hz `requestAnimationFrame` shows on Chromium — timestamp
57
+ * coarsening and float noise there put it at roughly 0.1-0.3 ms — but also
58
+ * the coarser 1-2 ms `requestAnimationFrame` timestamp rounding Firefox
59
+ * and Safari apply (their privacy/fingerprinting mitigation), without ever
60
+ * mistaking a genuine partial step for one of these snaps.
61
+ */
62
+ export declare const STEP_SNAP_TOLERANCE = 0.0025;
63
+ export interface SnapResult {
64
+ /** The elapsed time to feed the accumulator: snapped, and possibly resynced. */
65
+ elapsed: number;
66
+ /** Time discarded by snapping so far, still owed to (or by) the wall clock. */
67
+ residual: number;
68
+ }
69
+ /**
70
+ * Frame-rate snapping (ADR 0014, round 2 correctness): a measured frame
71
+ * duration that lands within STEP_SNAP_TOLERANCE of an exact multiple of
72
+ * SIMULATION_STEP is treated as exactly that multiple. Without this, a
73
+ * display refreshing at exactly 60.00 Hz can measure e.g. 16.6666 ms
74
+ * instead of the true 16.6667 ms — `consumeSimulationSteps` then floors the
75
+ * whole-steps count to 0 that frame and 2 the next, a routine 0/2-step
76
+ * judder at the one refresh rate ADR 0014 calls exact; on Firefox and
77
+ * Safari the same judder shows up permanently, every frame, because their
78
+ * coarser timestamp rounding never lands as close to the exact multiple as
79
+ * a 0.25 ms tolerance required. Applied to the raw per-frame measurement
80
+ * before it ever reaches the accumulator, so `consumeSimulationSteps`
81
+ * itself — and CA-2's 0.034 s / 0.0999 s / 0.005 s examples, each well
82
+ * outside the tolerance — are untouched.
83
+ *
84
+ * Every snap discards `elapsed - target`, which is carried forward in
85
+ * `residual` (round 3 correctness) instead of vanishing: a display a hair
86
+ * off 60.00 Hz — 59.94 Hz, the common NTSC-derived panel rate, discards
87
+ * ~0.017 ms every frame — would otherwise drift from the wall clock
88
+ * without bound (measured: -3.6 s/h at 59.94 Hz). Once the accumulated
89
+ * residual reaches a whole Simulation Step, one step is repaid into
90
+ * `elapsed` right away and subtracted back out of the residual, so the
91
+ * simulation is never more than about one step away from the wall clock.
92
+ */
93
+ export declare function snapElapsedToStep(elapsed: number, residual: number): SnapResult;
@@ -0,0 +1,109 @@
1
+ /**
2
+ * The Simulation Step (ADR 0014): the fixed slice of game time by which the
3
+ * engine advances every component update, however often the display
4
+ * refreshes. An engine constant, not a project setting — the archetypes'
5
+ * feel is tuned against it, and the Runtime Bridge's `step` means exactly
6
+ * one of these.
7
+ */
8
+ export const SIMULATION_STEP = 1 / 60;
9
+ /**
10
+ * The most steps one render frame may run. Beyond it the elapsed time is
11
+ * dropped, never repaid: a machine that cannot keep up falls behind the
12
+ * wall clock instead of spiralling into ever-longer frames. Six steps is
13
+ * 100 ms, the same ceiling the old per-frame clamp imposed.
14
+ */
15
+ export const MAX_STEPS_PER_FRAME = 6;
16
+ /**
17
+ * Floating-point slack for comparing a value built by summing many
18
+ * SIMULATION_STEP-sized deltas (a state's `elapsed`, a countdown, a clip's
19
+ * playback clock) against a target duration. Each addition can leave the
20
+ * sum a hair under the mathematically exact value — 15 additions of 1/60
21
+ * give 0.24999999999999997, not 0.25 — by an error on the order of 1e-15,
22
+ * many orders of magnitude below this. Large enough to call a step-multiple
23
+ * duration exact, far too small to ever mistake a genuinely later step for
24
+ * an earlier one.
25
+ */
26
+ export const SIMULATION_TIME_EPSILON = 1e-9;
27
+ /**
28
+ * Cap on same-tick, chained processing that could otherwise spin forever
29
+ * on a degenerate cycle: StateMachine settling a chain of transitions
30
+ * within one `onUpdate` (land → idle → run…) and Game draining a chain of
31
+ * `loadSceneByName` calls queued from a scene's own `onReady` within one
32
+ * frame. Shared so the two call sites' caps stay in lockstep instead of
33
+ * matching only by coincidence; eight is comfortably more hops than any
34
+ * real content chains in a single update.
35
+ */
36
+ export const MAX_CHAINED_HOPS = 8;
37
+ /**
38
+ * Pure accumulator: from the time retained after the last frame and the
39
+ * seconds elapsed since it, how many whole steps to run now and what to
40
+ * keep. Hitting the cap discards the whole remainder (CA-2). A non-finite
41
+ * or negative `elapsed` (a NaN timestamp delta, a backwards clock) is
42
+ * treated as zero rather than poisoning the remainder or yielding negative
43
+ * steps — hardening against inputs a real rAF timestamp never produces.
44
+ */
45
+ export function consumeSimulationSteps(remainder, elapsed) {
46
+ const safeElapsed = Number.isFinite(elapsed) && elapsed > 0 ? elapsed : 0;
47
+ const available = remainder + safeElapsed;
48
+ const whole = Math.floor(available / SIMULATION_STEP);
49
+ if (whole >= MAX_STEPS_PER_FRAME)
50
+ return { steps: MAX_STEPS_PER_FRAME, remainder: 0 };
51
+ return { steps: whole, remainder: available - whole * SIMULATION_STEP };
52
+ }
53
+ /**
54
+ * How far a measured frame duration may sit from a whole number of
55
+ * Simulation Steps and still count as exactly that many (round 2
56
+ * correctness fix). Sized to absorb not just the sub-millisecond jitter a
57
+ * real 60 Hz `requestAnimationFrame` shows on Chromium — timestamp
58
+ * coarsening and float noise there put it at roughly 0.1-0.3 ms — but also
59
+ * the coarser 1-2 ms `requestAnimationFrame` timestamp rounding Firefox
60
+ * and Safari apply (their privacy/fingerprinting mitigation), without ever
61
+ * mistaking a genuine partial step for one of these snaps.
62
+ */
63
+ export const STEP_SNAP_TOLERANCE = 0.0025; // seconds (2.5 ms)
64
+ /**
65
+ * Snapping considers only these small step counts: a display sitting
66
+ * exactly on one of the first few Simulation Step boundaries (60 Hz → 1,
67
+ * 30 Hz → 2, and so on) is the case timestamp jitter can push a hair off:
68
+ * higher counts already mean a hitch, where a fraction of a millisecond
69
+ * doesn't matter and forcing a snap would be presumptuous.
70
+ */
71
+ const SNAPPABLE_STEPS = 4;
72
+ /**
73
+ * Frame-rate snapping (ADR 0014, round 2 correctness): a measured frame
74
+ * duration that lands within STEP_SNAP_TOLERANCE of an exact multiple of
75
+ * SIMULATION_STEP is treated as exactly that multiple. Without this, a
76
+ * display refreshing at exactly 60.00 Hz can measure e.g. 16.6666 ms
77
+ * instead of the true 16.6667 ms — `consumeSimulationSteps` then floors the
78
+ * whole-steps count to 0 that frame and 2 the next, a routine 0/2-step
79
+ * judder at the one refresh rate ADR 0014 calls exact; on Firefox and
80
+ * Safari the same judder shows up permanently, every frame, because their
81
+ * coarser timestamp rounding never lands as close to the exact multiple as
82
+ * a 0.25 ms tolerance required. Applied to the raw per-frame measurement
83
+ * before it ever reaches the accumulator, so `consumeSimulationSteps`
84
+ * itself — and CA-2's 0.034 s / 0.0999 s / 0.005 s examples, each well
85
+ * outside the tolerance — are untouched.
86
+ *
87
+ * Every snap discards `elapsed - target`, which is carried forward in
88
+ * `residual` (round 3 correctness) instead of vanishing: a display a hair
89
+ * off 60.00 Hz — 59.94 Hz, the common NTSC-derived panel rate, discards
90
+ * ~0.017 ms every frame — would otherwise drift from the wall clock
91
+ * without bound (measured: -3.6 s/h at 59.94 Hz). Once the accumulated
92
+ * residual reaches a whole Simulation Step, one step is repaid into
93
+ * `elapsed` right away and subtracted back out of the residual, so the
94
+ * simulation is never more than about one step away from the wall clock.
95
+ */
96
+ export function snapElapsedToStep(elapsed, residual) {
97
+ for (let steps = 1; steps <= SNAPPABLE_STEPS; steps += 1) {
98
+ const target = steps * SIMULATION_STEP;
99
+ if (Math.abs(elapsed - target) < STEP_SNAP_TOLERANCE) {
100
+ const pending = residual + (elapsed - target);
101
+ if (Math.abs(pending) >= SIMULATION_STEP) {
102
+ const repaid = Math.sign(pending) * SIMULATION_STEP;
103
+ return { elapsed: target + repaid, residual: pending - repaid };
104
+ }
105
+ return { elapsed: target, residual: pending };
106
+ }
107
+ }
108
+ return { elapsed, residual };
109
+ }
package/dist/game.d.ts CHANGED
@@ -8,6 +8,7 @@ import { Emitter } from './events.js';
8
8
  import { Input, type InputBindings } from './input.js';
9
9
  import { Pointer } from './pointer.js';
10
10
  import { type SceneJson, type SceneRegistry, type SceneRenderJson } from './scene.js';
11
+ import { type SpatialQuery } from './spatial-query.js';
11
12
  import { Stats, type StatValue } from './stats.js';
12
13
  import { GameUi } from './ui.js';
13
14
  /** Fixed game resolution: the view keeps this aspect, letterboxed. */
@@ -58,6 +59,7 @@ export declare class Game {
58
59
  readonly camera: THREE.OrthographicCamera;
59
60
  readonly input: Input;
60
61
  readonly pointer: Pointer;
62
+ readonly query: SpatialQuery;
61
63
  readonly entities: Entity[];
62
64
  readonly events: Emitter;
63
65
  readonly stats: Stats;
@@ -77,6 +79,14 @@ export declare class Game {
77
79
  private readonly resizeObserver;
78
80
  private readonly updateFns;
79
81
  private readonly invalidUpdateCompositions;
82
+ /**
83
+ * componentUpdateSchedule's result for the last composition signature seen
84
+ * per entity: the resolve (Tarjan SCC + Kahn sort) it's built from is pure
85
+ * for a fixed composition, so a signature match skips it entirely. Only
86
+ * ever holds a successful resolution — an invalid composition is never
87
+ * cached, since invalidUpdateCompositions already dedupes its console.error.
88
+ */
89
+ private readonly updateScheduleCache;
80
90
  private readonly resolution;
81
91
  /** The constructor's viewHeight — unloadScene() restores it. */
82
92
  private readonly baseViewHeight;
@@ -84,7 +94,12 @@ export declare class Game {
84
94
  private sceneCamera;
85
95
  private renderSort;
86
96
  private sceneProjection;
97
+ /** Timestamp of the last animation frame; null until the loop's first frame seeds it. */
87
98
  private lastTime;
99
+ /** Seconds of elapsed time not yet worth a whole Simulation Step (ADR 0014). */
100
+ private stepRemainder;
101
+ /** Seconds discarded by frame-rate snapping, not yet repaid (round 3 correctness). */
102
+ private snapResidual;
88
103
  private runtimeBridge;
89
104
  /** Host-registered scenes by name, resolved by loadSceneByName. Session-scoped. */
90
105
  private sceneCatalog;
@@ -134,7 +149,12 @@ export declare class Game {
134
149
  loadParams(url: string): Promise<void>;
135
150
  /** Applies persisted overrides to a freshly added component. */
136
151
  applyParamOverrides(entity: Entity, component: Component): void;
137
- /** Registers a function that runs once per frame. Returns the unsubscribe. */
152
+ /**
153
+ * Registers a function that runs once per Simulation Step, with the step
154
+ * as its dt (ADR 0014). While the Game is not simulating (the editor's edit
155
+ * mode) it runs once per render frame instead, so a host can keep drawing
156
+ * its overlays. Returns the unsubscribe.
157
+ */
138
158
  onUpdate(fn: UpdateFn): () => void;
139
159
  /**
140
160
  * Adopts a scene's render block. Called by loadScene; without a block the
@@ -157,9 +177,46 @@ export declare class Game {
157
177
  setViewHeight(value: number): void;
158
178
  /** Shuts the game down completely (loop, input, GPU). */
159
179
  dispose(): void;
180
+ /**
181
+ * Real-time playback for the Runtime Bridge: the same clock-driven loop
182
+ * as start(), sharing the accumulator, with `onStep` told after every
183
+ * Simulation Step so the bridge counts frames exactly as paused stepping
184
+ * does (CA-7). No wall-clock catch-up: the first frame only seeds the
185
+ * clock (CA-3).
186
+ */
160
187
  private resumeRuntime;
188
+ /** Forgets the clock and any partial step, so the next frame runs no burst. */
189
+ private resetClock;
190
+ /**
191
+ * One animation frame (ADR 0014): the elapsed wall-clock time joins the
192
+ * retained remainder, and as many whole Simulation Steps as it holds run
193
+ * — capped, with the excess dropped, so a hitch can neither spiral nor
194
+ * play in slow motion. Not simulating: no time accrues at all. The
195
+ * measured duration is frame-rate-snapped first (round 2 correctness) so
196
+ * sub-millisecond timestamp jitter at an exact cadence like 60 Hz can't
197
+ * flip the whole-steps floor and judder 0/2/0/2.
198
+ */
161
199
  private tick;
200
+ /**
201
+ * Runs `steps` Simulation Steps back to back, then the once-per-frame
202
+ * tail: audio activity and placements, the UI overlay and the render
203
+ * (CA-5). A queued scene swap flushes at the very start of the frame —
204
+ * loadSceneByName's contract — and again before every step after the
205
+ * first (CA-4), so two steps in one frame never see the same press
206
+ * twice or the outgoing scene once too often; a frame that runs zero
207
+ * steps (round 2 correctness) still flushes, so it never renders/
208
+ * audio-places the outgoing scene one frame longer than it should.
209
+ */
162
210
  private runFrame;
211
+ /**
212
+ * One Simulation Step: the Component Update Schedule (ADR 0004) in full,
213
+ * collisions, the scene camera and the host's callbacks, every one of
214
+ * them handed exactly SIMULATION_STEP (CA-1); then the input frame ends.
215
+ */
216
+ private simulateStep;
217
+ /** Closes a step (real or the non-simulating stand-in): host callbacks, then the input frame. */
218
+ private finishStep;
219
+ private runHostUpdates;
163
220
  private flushPendingSceneLoad;
164
221
  private unregisterRuntimeBridge;
165
222
  /** Under y-sort, re-derives every participant's z from layer band + entity Y. */