@waica/engine 0.15.0 → 0.17.0

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
@@ -170,3 +170,57 @@ class PathFinder extends Component {
170
170
  ```
171
171
 
172
172
  The return value still passes through the bounded safe projector; it is not serialized with arbitrary `toJSON()`. The package root exports the Runtime Snapshot, projection marker, metadata, control and activation types plus `RUNTIME_BRIDGE_PROTOCOL_VERSION` and `RUNTIME_PROJECTION_LIMITS`.
173
+
174
+ ## game.time: simulated timers and tweens
175
+
176
+ Every `Game` owns a `time: GameTime` service — `after`, `every`, a single-number `tween`, and a `now` reader — advanced only by Simulation Steps (ADR 0014), never by the wall clock:
177
+
178
+ ```ts
179
+ const stun = game.time.after(0.3, () => fsm.goto('idle'), { owner: entity })
180
+ game.time.every(1, () => game.stats.set('clock', game.time.now), { scope: 'session' })
181
+ game.time.tween({
182
+ from: 0, to: 1, seconds: 0.5, easing: 'quadOut',
183
+ onUpdate: (v) => { overlay.opacity = v },
184
+ onComplete: () => game.loadSceneByName('b'),
185
+ owner: entity,
186
+ })
187
+ stun.remaining // seconds left, counting down
188
+ game.time.now // seconds of Game Time since the Game started
189
+ ```
190
+
191
+ - **`after(seconds, callback, options?)`** runs `callback` once, `seconds` of Game Time later (0 or a negative duration: the start of the next step). **`every(seconds, callback, options?)`** runs it every `max(seconds, 1/60)`, first one interval after creation, with no drift. **`tween(options)`** carries `from` to `to` over `seconds`, calling `onUpdate(value)` synchronously on creation and again on every later step, finishing with exactly `to` then `onComplete()`. Easing is `'linear'` (default), `'quadIn'`/`'quadOut'`/`'quadInOut'`, `'cubicIn'`/`'cubicOut'`/`'cubicInOut'`, `'sineInOut'`, or a custom `(t) => number`.
192
+ - All three return a `TimerHandle`: `cancel()`, `active`, `elapsed`, `remaining` (seconds of Game Time). `cancel()` — and owner/scene cancellation — leaves a tween's last applied value in place and never calls `onComplete`.
193
+ - **Step placement.** At the start of every Simulation Step, before the Component Update Schedule, `game.time` advances `now`, runs every due timer (due time, then creation order), then advances every tween that existed before that step (creation order). Work a callback creates is never run or advanced in that same step.
194
+ - **Scope.** A timer or tween is scene-scoped by default: `unloadScene()` and every scene load — including a Game's first — cancel it, running no callback. `{ scope: 'session' }` survives a scene change. `{ owner: entity }` cancels it immediately when that entity is destroyed, whatever its scope; an owner already dead at scheduling time yields an inactive handle. `game.dispose()` cancels everything in both scopes. This is the opposite default from `game.onUpdate`/`game.events` (ADR 0011), which survive a scene change by construction, and the same one `game.audio.play()` uses (ADR 0012) — see ADR 0017 for why timers follow audio's rule rather than the host-subscription one: a timer's callback almost always closes over the scene that scheduled it.
195
+ - **No Promises.** Nothing here returns one, and nothing is async — a `.then` continuation is not step-exact (it runs after the whole synchronous frame), which is exactly what `game.time` exists to avoid. Compose delays with `after`, not `await`.
196
+
197
+ ## game.ui.attach: Anchored Pieces
198
+
199
+ A UI Piece shown with `game.ui.show(name)` is a screen-space singleton. `game.ui.attach(piece, entity, options?)` instead creates an **Anchored Piece**: a new instance of the piece that follows `entity` across the screen, with its own shadow root and its own values. Every call is a new instance — five orcs can each carry a `health-bar` — and the screen piece of the same name is never mounted, shown or changed by it.
200
+
201
+ ```ts
202
+ const hit = game.ui.attach('damage-number', orc, { offset: [0, 1.2], seconds: 0.8, values: { amount: 3 } })
203
+ const bar = game.ui.attach('health-bar', orc, { offset: [0, 1.4], values: { current: 7, max: 10 } })
204
+ bar.set('current', 6) // {{current}} and --current update live
205
+ bar.remove()
206
+ ```
207
+
208
+ ```html
209
+ <style>
210
+ .bar { position: absolute; transform: translate(-50%, -100%); width: calc(1.2 * var(--waica-unit)); height: 4px; background: #0008 }
211
+ .fill { width: calc(var(--current) / var(--max) * 100%); height: 100%; background: #ef476f }
212
+ </style>
213
+ <div class="bar"><div class="fill"></div></div>
214
+ ```
215
+
216
+ - **Options.** `offset: [x, y]` (default `[0, 0]`) is in world units, added to the entity's render point in render space: `[0, 1]` is one unit up on screen, under `projection: 'isometric'` too. `seconds` gives the instance its own lifetime (below). `values` are the instance's own values.
217
+ - **Handle.** `set(name, value)`, `remove()`, `alive` and `element` — the piece's content root inside the instance's shadow root, `null` once removed.
218
+ - **Placement.** Once per render frame — after the isometric projection and the camera step, before the render, never per Simulation Step — each instance's shadow host is placed as a zero-size box at its anchor point, converted to whole CSS pixels from the top-left corner of the game viewport; the piece's own CSS centres itself around that point (e.g. `transform: translate(-50%, -100%)`). A move therefore shows on the next frame, not before. All instances live in one layer fitted to the game viewport — the whole canvas, or the letterboxed rectangle under a fixed `resolution` — with `overflow: hidden`, so they never draw over the letterbox bars.
219
+ - **Per-instance values.** Inside an instance, `{{name}}` renders the instance's own value when it has one and the Game stat of that name otherwise (booleans as ✓/✕, missing as empty); `set` updates it in place, and a stat change still updates every placeholder with no instance value. Every number value is also published as the custom property `--name` on the instance (`values: { current: 7, max: 10 }` gives `--current: 7` and `--max: 10`), booleans as `1`/`0`; strings are text only. There are no binding expressions: arithmetic belongs in CSS `calc()`.
220
+ - **`--waica-unit`.** Every frame, the anchored layer carries `--waica-unit` inline, and every instance inherits it through its shadow host: CSS pixels per world unit, the game viewport's CSS height divided by the current view height. It follows camera zoom and the letterbox scale, so `calc(1.1 * var(--waica-unit))` sizes a piece in world units while everything else keeps its CSS pixel size.
221
+ - **Draw order.** The anchored layer sits below every screen-space piece. Within it, every frame, the instance lower on screen draws on top, like y-sort; equal heights keep creation order, later on top.
222
+ - **Lifetime.** Without `seconds`, an instance is removed before its entity's `destroy()` returns. With `seconds: S`, it is removed exactly when a `game.time.after(S, …)` scheduled at the same moment would fire — it counts Game Time (ADR 0017), so it never runs out while the Game is paused or not simulating, and until then it counts in `game.time.pending`. If its entity is destroyed first, it lingers frozen where the entity was at `destroy()` time (still moving with the camera) until it expires. `unloadScene()`, every scene load that unloads and `game.dispose()` remove every instance: none outlives its scene. `remove()` is immediate; `set` and `remove` on a removed handle are silent no-ops. CSS animations and transitions inside an instance follow Game Time, not the wall clock: every frame each is paused at the Game Time since it started (the attach, for those the piece starts with), so a paused Game freezes a damage number mid-flight — it resumes from there, even after the overlay hid while not simulating — and `step { frames: N }` advances it by N/60 s.
223
+ - **Invalid attach never throws.** An undefined piece name logs one `[waica]` warning per name per Game; an entity that is no longer `alive` logs one per call. Both return a handle with `alive: false` and `element: null` that mounts nothing. To attach only when the project defines the piece, as `Interactable` does with `npc-bubble` and `interact-prompt`, check `game.ui.has(name)` first.
224
+ - **Runtime Snapshot.** Every snapshot carries `ui: { shown, anchored }`: the visible screen pieces by name, and each live instance in creation order as `{ piece, entity, x, y, clipped, values }`, with the pixel coordinates of its last placement; `values` are bounded like component state (a string over 4 KiB becomes a `$waica: 'truncated'` marker), and once every entity is cut the 1 MiB snapshot cap drops instances from the end.
225
+
226
+ The trade-off is ADR 0018's: Anchored Pieces are HTML drawn over the game view, not text rendered in the three scene. They always draw above the world — a label behind a tree draws over it — hide with the rest of the UI overlay while the Game is not simulating (including the editor's edit mode), and do not align to a pixel-art grid.
@@ -0,0 +1,122 @@
1
+ import type { Entity } from './entity.js';
2
+ import type { PointerCamera, PointerResolution } from './pointer.js';
3
+ import type { RuntimeSnapshotUi } from './runtime-inspection.js';
4
+ import type { Stats, StatValue } from './stats.js';
5
+ /** Options for `game.ui.attach` (issue #72). */
6
+ export interface AttachOptions {
7
+ /**
8
+ * World units added to the entity's render point, in render space:
9
+ * `[0, 1]` is one unit up on screen, under isometric projection too.
10
+ * Default `[0, 0]`. Pixel fine-tuning belongs in the piece's CSS.
11
+ */
12
+ offset?: [number, number];
13
+ /**
14
+ * Seconds of Game Time the instance lives for (ADR 0017). It outlives its
15
+ * entity, frozen where the entity last was, until then. Absent: the
16
+ * instance dies with its entity.
17
+ */
18
+ seconds?: number;
19
+ /**
20
+ * The instance's own values: `{{name}}` reads these before the Game's
21
+ * stats, and every number (verbatim) or boolean (`1`/`0`) is also
22
+ * published as the custom property `--name` on the instance.
23
+ */
24
+ values?: Record<string, StatValue>;
25
+ }
26
+ /** One Anchored Piece, as `game.ui.attach` hands it back. */
27
+ export interface AnchoredPieceHandle {
28
+ /** Sets one of the instance's own values: its `{{name}}` text and `--name` update in place. */
29
+ set(name: string, value: StatValue): void;
30
+ /** Removes the instance now. `set` and `remove` on a removed handle are silent no-ops. */
31
+ remove(): void;
32
+ /** False once removed, and from the start on an invalid attach. */
33
+ readonly alive: boolean;
34
+ /** The piece's content root inside the instance's own shadow root; null once removed. */
35
+ readonly element: HTMLElement | null;
36
+ }
37
+ /** A rectangle in CSS px, relative to the canvas's top-left corner. */
38
+ export interface ViewportRect {
39
+ x: number;
40
+ y: number;
41
+ width: number;
42
+ height: number;
43
+ }
44
+ /** What the Game tells the anchored layer each time it places: read live, never cached. */
45
+ export interface AnchorView {
46
+ camera: PointerCamera;
47
+ /** The game viewport: see gameViewport. */
48
+ viewport: ViewportRect;
49
+ projection: 'isometric' | null;
50
+ }
51
+ /**
52
+ * The game viewport (issue #72): the rectangle the renderer draws into —
53
+ * the whole canvas without a fixed resolution, the largest centred rect
54
+ * with its aspect (letterbox) with one. The same math as Game.resize() and
55
+ * the Pointer's letterbox, whose screen→world mapping placement inverts.
56
+ */
57
+ export declare function gameViewport(width: number, height: number, resolution: PointerResolution | null): ViewportRect;
58
+ /** What GameUi lends the anchored layer: its catalog, the stats and its overlay. */
59
+ export interface AnchoredPiecesDeps {
60
+ stats: Stats;
61
+ /** A piece's HTML source, or undefined when the piece was never defined. */
62
+ source(name: string): string | undefined;
63
+ /** GameUi's overlay, mounted on demand. */
64
+ overlay(): HTMLElement;
65
+ }
66
+ /**
67
+ * Anchored Pieces (issue #72, ADR 0018) — instances of a UI Piece, as many
68
+ * as needed, each following an entity in one layer of GameUi's overlay,
69
+ * each with its own shadow root and its own values ahead of the Game's stats.
70
+ * Owned by GameUi, which reaches it through `attach`; the Game drives the
71
+ * rest through `anchoredPiecesOf` (ui.ts): `connect` once, `place` every
72
+ * render frame.
73
+ */
74
+ export declare class AnchoredPieces {
75
+ private readonly deps;
76
+ private readonly instances;
77
+ /** Undefined piece names already warned about: one warning per name per Game. */
78
+ private readonly warnedPieces;
79
+ private layer?;
80
+ private view;
81
+ constructor(deps: AnchoredPiecesDeps);
82
+ /** Called once by the Game: where the camera, viewport and projection are read from. */
83
+ connect(view: () => AnchorView): void;
84
+ attach(piece: string, entity: Entity, options?: AttachOptions): AnchoredPieceHandle;
85
+ /**
86
+ * Called by the Game before an entity's destroy() returns: its instances
87
+ * go with it, except those given `seconds`, which stay frozen at its
88
+ * current anchor point until they expire.
89
+ */
90
+ release(entity: Entity): void;
91
+ /**
92
+ * The live instances for the Runtime Snapshot, in creation order, with
93
+ * the coordinates of their last placement — or, for one attached since
94
+ * the last render frame, where the next frame will place it.
95
+ */
96
+ snapshot(): RuntimeSnapshotUi['anchored'];
97
+ /** Removes every instance, lingering ones too (GameUi.unloadScene). */
98
+ clear(): void;
99
+ /** Removes every instance and forgets the layer along with the overlay (GameUi.dispose). */
100
+ dispose(): void;
101
+ /**
102
+ * Called by the Game once per render frame, after the isometric pass and
103
+ * before the render (never per Simulation Step, never on attach): fits
104
+ * the layer to the game viewport, sets the frame's `--waica-unit` on it
105
+ * (every instance inherits it through its shadow host) and puts every
106
+ * instance's zero-size shadow host at its anchor point, its CSS
107
+ * animations set to Game Time (followGameTime).
108
+ */
109
+ place(): void;
110
+ private bind;
111
+ /** Writes a name's current value — the instance's own, else the Game stat — into its placeholders. */
112
+ private render;
113
+ private set;
114
+ private remove;
115
+ private handleFor;
116
+ /**
117
+ * The single layer every instance lives in, kept as the overlay's first
118
+ * child — even when a screen piece created the overlay first — so every
119
+ * screen-space piece draws above every anchored instance.
120
+ */
121
+ private mountLayer;
122
+ }
@@ -0,0 +1,330 @@
1
+ import { projectIsometric } from './projection.js';
2
+ import { placeholders, renderStat } from './ui-bindings.js';
3
+ /**
4
+ * The game viewport (issue #72): the rectangle the renderer draws into —
5
+ * the whole canvas without a fixed resolution, the largest centred rect
6
+ * with its aspect (letterbox) with one. The same math as Game.resize() and
7
+ * the Pointer's letterbox, whose screen→world mapping placement inverts.
8
+ */
9
+ export function gameViewport(width, height, resolution) {
10
+ if (!resolution)
11
+ return { x: 0, y: 0, width, height };
12
+ const aspect = resolution.width / resolution.height;
13
+ const vw = Math.min(width, height * aspect);
14
+ const vh = vw / aspect;
15
+ return { x: (width - vw) / 2, y: (height - vh) / 2, width: vw, height: vh };
16
+ }
17
+ /** The handle of an invalid attach (CA-7): nothing mounted, nothing to change. */
18
+ const INERT_HANDLE = Object.freeze({
19
+ set() { },
20
+ remove() { },
21
+ alive: false,
22
+ element: null,
23
+ });
24
+ /** A GameUi no Game connected has no viewport: nothing it holds is ever placed. */
25
+ const UNPLACED = { x: 0, y: 0, clipped: true, depth: 0 };
26
+ /**
27
+ * Anchored Pieces (issue #72, ADR 0018) — instances of a UI Piece, as many
28
+ * as needed, each following an entity in one layer of GameUi's overlay,
29
+ * each with its own shadow root and its own values ahead of the Game's stats.
30
+ * Owned by GameUi, which reaches it through `attach`; the Game drives the
31
+ * rest through `anchoredPiecesOf` (ui.ts): `connect` once, `place` every
32
+ * render frame.
33
+ */
34
+ export class AnchoredPieces {
35
+ deps;
36
+ instances = [];
37
+ /** Undefined piece names already warned about: one warning per name per Game. */
38
+ warnedPieces = new Set();
39
+ layer;
40
+ view = null;
41
+ constructor(deps) {
42
+ this.deps = deps;
43
+ }
44
+ /** Called once by the Game: where the camera, viewport and projection are read from. */
45
+ connect(view) {
46
+ this.view = view;
47
+ }
48
+ attach(piece, entity, options = {}) {
49
+ const html = this.deps.source(piece);
50
+ if (html === undefined && !this.warnedPieces.has(piece)) {
51
+ this.warnedPieces.add(piece);
52
+ console.warn(`[waica] cannot attach unknown ui piece: "${piece}"`);
53
+ }
54
+ if (!entity.alive) {
55
+ console.warn(`[waica] cannot attach ui piece "${piece}" to destroyed entity "${entity.name}"`);
56
+ }
57
+ if (html === undefined || !entity.alive)
58
+ return INERT_HANDLE;
59
+ const host = document.createElement('div');
60
+ host.style.cssText = 'position:absolute;left:0;top:0;width:0;height:0;pointer-events:none';
61
+ const shadow = host.attachShadow({ mode: 'open' });
62
+ const root = document.createElement('div');
63
+ root.style.display = 'contents';
64
+ root.innerHTML = html;
65
+ shadow.append(root);
66
+ const offset = options.offset ?? [0, 0];
67
+ const instance = {
68
+ piece,
69
+ entity,
70
+ offset: [offset[0], offset[1]],
71
+ values: new Map(Object.entries(options.values ?? {})),
72
+ host,
73
+ root,
74
+ texts: new Map(),
75
+ unsubs: [],
76
+ born: entity.game.time.now,
77
+ clocks: new WeakMap(),
78
+ named: new WeakMap(),
79
+ expiry: null,
80
+ frozen: null,
81
+ placed: null,
82
+ alive: true,
83
+ };
84
+ this.bind(instance);
85
+ for (const [name, value] of instance.values)
86
+ publish(host, name, value);
87
+ this.mountLayer().append(host);
88
+ this.instances.push(instance);
89
+ if (options.seconds !== undefined) {
90
+ // Not owned by the entity: it must outlive it. Scene-scoped, like the
91
+ // instance itself. A duration game.time rejects (it warns) leaves the
92
+ // instance to die with its entity instead of lingering forever.
93
+ const expiry = entity.game.time.after(options.seconds, () => this.remove(instance));
94
+ instance.expiry = expiry.active ? expiry : null;
95
+ }
96
+ return this.handleFor(instance);
97
+ }
98
+ /**
99
+ * Called by the Game before an entity's destroy() returns: its instances
100
+ * go with it, except those given `seconds`, which stay frozen at its
101
+ * current anchor point until they expire.
102
+ */
103
+ release(entity) {
104
+ for (const instance of this.instances.filter((candidate) => candidate.entity === entity)) {
105
+ if (instance.expiry)
106
+ instance.frozen = anchorPoint(instance, this.view?.().projection ?? null);
107
+ else
108
+ this.remove(instance);
109
+ }
110
+ }
111
+ /**
112
+ * The live instances for the Runtime Snapshot, in creation order, with
113
+ * the coordinates of their last placement — or, for one attached since
114
+ * the last render frame, where the next frame will place it.
115
+ */
116
+ snapshot() {
117
+ return this.instances.map((instance) => {
118
+ const { x, y, clipped } = instance.placed ?? (this.view ? locate(instance, this.view()) : UNPLACED);
119
+ return {
120
+ piece: instance.piece,
121
+ entity: instance.entity.name,
122
+ x,
123
+ y,
124
+ clipped,
125
+ values: Object.fromEntries(instance.values),
126
+ };
127
+ });
128
+ }
129
+ /** Removes every instance, lingering ones too (GameUi.unloadScene). */
130
+ clear() {
131
+ for (const instance of [...this.instances])
132
+ this.remove(instance);
133
+ }
134
+ /** Removes every instance and forgets the layer along with the overlay (GameUi.dispose). */
135
+ dispose() {
136
+ this.clear();
137
+ this.layer = undefined;
138
+ }
139
+ /**
140
+ * Called by the Game once per render frame, after the isometric pass and
141
+ * before the render (never per Simulation Step, never on attach): fits
142
+ * the layer to the game viewport, sets the frame's `--waica-unit` on it
143
+ * (every instance inherits it through its shadow host) and puts every
144
+ * instance's zero-size shadow host at its anchor point, its CSS
145
+ * animations set to Game Time (followGameTime).
146
+ */
147
+ place() {
148
+ const layer = this.layer;
149
+ if (!layer || !this.view)
150
+ return;
151
+ const view = this.view();
152
+ const { camera, viewport } = view;
153
+ layer.style.left = `${viewport.x}px`;
154
+ layer.style.top = `${viewport.y}px`;
155
+ layer.style.width = `${viewport.width}px`;
156
+ layer.style.height = `${viewport.height}px`;
157
+ // The camera frames exactly viewHeight world units vertically (Game.resize).
158
+ layer.style.setProperty('--waica-unit', `${viewport.height / (camera.top - camera.bottom)}px`);
159
+ // Before any instance's style writes below: getAnimations() flushes style.
160
+ for (const instance of this.instances)
161
+ followGameTime(instance);
162
+ const byDepth = [];
163
+ for (const instance of this.instances) {
164
+ const placement = locate(instance, view);
165
+ instance.placed = placement;
166
+ instance.host.style.left = `${placement.x}px`;
167
+ instance.host.style.top = `${placement.y}px`;
168
+ byDepth.push([instance, placement.depth]);
169
+ }
170
+ // Lower on screen draws on top, like y-sort; the sort is stable, so
171
+ // equal heights keep creation order, later on top.
172
+ byDepth.sort(([, a], [, b]) => a - b);
173
+ for (const [index, [instance]] of byDepth.entries())
174
+ instance.host.style.zIndex = String(index + 1);
175
+ }
176
+ bind(instance) {
177
+ for (const [name, text] of placeholders(instance.root)) {
178
+ const texts = instance.texts.get(name);
179
+ if (texts)
180
+ texts.push(text);
181
+ else
182
+ instance.texts.set(name, [text]);
183
+ }
184
+ for (const name of instance.texts.keys()) {
185
+ this.render(instance, name);
186
+ instance.unsubs.push(this.deps.stats.onChange(name, () => {
187
+ if (!instance.values.has(name))
188
+ this.render(instance, name);
189
+ }));
190
+ }
191
+ }
192
+ /** Writes a name's current value — the instance's own, else the Game stat — into its placeholders. */
193
+ render(instance, name) {
194
+ const value = instance.values.has(name) ? instance.values.get(name) : this.deps.stats.get(name);
195
+ for (const text of instance.texts.get(name) ?? [])
196
+ text.nodeValue = renderStat(value);
197
+ }
198
+ set(instance, name, value) {
199
+ if (!instance.alive)
200
+ return;
201
+ instance.values.set(name, value);
202
+ this.render(instance, name);
203
+ publish(instance.host, name, value);
204
+ }
205
+ remove(instance) {
206
+ if (!instance.alive)
207
+ return;
208
+ instance.alive = false;
209
+ instance.expiry?.cancel();
210
+ for (const off of instance.unsubs)
211
+ off();
212
+ instance.host.remove();
213
+ this.instances.splice(this.instances.indexOf(instance), 1);
214
+ }
215
+ handleFor(instance) {
216
+ const pieces = this;
217
+ return {
218
+ set(name, value) {
219
+ pieces.set(instance, name, value);
220
+ },
221
+ remove() {
222
+ pieces.remove(instance);
223
+ },
224
+ get alive() {
225
+ return instance.alive;
226
+ },
227
+ get element() {
228
+ return instance.alive ? instance.root : null;
229
+ },
230
+ };
231
+ }
232
+ /**
233
+ * The single layer every instance lives in, kept as the overlay's first
234
+ * child — even when a screen piece created the overlay first — so every
235
+ * screen-space piece draws above every anchored instance.
236
+ */
237
+ mountLayer() {
238
+ if (this.layer)
239
+ return this.layer;
240
+ const layer = document.createElement('div');
241
+ // Until the first frame fits it to the game viewport, it covers the overlay.
242
+ // Its own stacking context (z-index:0) keeps every instance's z-index
243
+ // below the screen-piece shells that follow it.
244
+ layer.style.cssText =
245
+ 'position:absolute;left:0;top:0;width:100%;height:100%;overflow:hidden;z-index:0;pointer-events:none';
246
+ this.deps.overlay().prepend(layer);
247
+ this.layer = layer;
248
+ return layer;
249
+ }
250
+ }
251
+ /** The entity's render point plus the offset, in render space — or the point frozen at its destroy(). */
252
+ function anchorPoint(instance, projection) {
253
+ if (instance.frozen)
254
+ return instance.frozen;
255
+ const { x, y } = instance.entity.position;
256
+ const render = projection === 'isometric' ? projectIsometric(x, y) : { x, y };
257
+ return { x: render.x + instance.offset[0], y: render.y + instance.offset[1] };
258
+ }
259
+ /**
260
+ * The anchor point in whole CSS px from the game viewport's top-left
261
+ * corner: the exact inverse of the Pointer's screen→world mapping.
262
+ */
263
+ function locate(instance, view) {
264
+ const anchor = anchorPoint(instance, view.projection);
265
+ const { camera, viewport } = view;
266
+ const nx = (anchor.x - (camera.position.x + camera.left)) / (camera.right - camera.left);
267
+ const ny = (camera.position.y + camera.top - anchor.y) / (camera.top - camera.bottom);
268
+ return {
269
+ x: whole(nx * viewport.width),
270
+ y: whole(ny * viewport.height),
271
+ clipped: nx < 0 || nx > 1 || ny < 0 || ny > 1,
272
+ depth: ny,
273
+ };
274
+ }
275
+ /**
276
+ * Drives the instance's CSS animations from Game Time instead of the
277
+ * document timeline: each is paused at the Game Time elapsed since it
278
+ * started, so a frame that runs no Simulation Step leaves it exactly where
279
+ * it was. One there at the first placement started with the instance (its
280
+ * attach); a later one (a transition a set() started) with the frame it
281
+ * first shows up in. Called before the frame updates `placed`. A DOM
282
+ * without the Web Animations API (happy-dom returns none) is left alone.
283
+ */
284
+ function followGameTime(instance) {
285
+ const animations = instance.host.shadowRoot?.getAnimations?.() ?? [];
286
+ const now = instance.entity.game.time.now;
287
+ const firstSeen = instance.placed ? now : instance.born;
288
+ for (const animation of animations) {
289
+ const start = animationStart(instance, animation, firstSeen);
290
+ animation.pause();
291
+ animation.currentTime = (now - start) * 1000;
292
+ }
293
+ }
294
+ /**
295
+ * The Game Time `animation` counts from, recorded as `firstSeen` the first
296
+ * time it is met. A named CSS animation is known by its target element and
297
+ * name, not by object: hiding the overlay (not simulating) cancels it, and
298
+ * the new one the browser makes when it shows again resumes mid-flight. A
299
+ * transition, or anything else without a name, is known by object.
300
+ */
301
+ function animationStart(instance, animation, firstSeen) {
302
+ const name = 'animationName' in animation ? animation.animationName : undefined;
303
+ const effect = animation.effect;
304
+ const target = effect && 'target' in effect ? effect.target : null;
305
+ if (typeof name === 'string' && target instanceof Element) {
306
+ let byName = instance.named.get(target);
307
+ if (!byName)
308
+ instance.named.set(target, (byName = new Map()));
309
+ const start = byName.get(name) ?? firstSeen;
310
+ byName.set(name, start);
311
+ return start;
312
+ }
313
+ const start = instance.clocks.get(animation) ?? firstSeen;
314
+ instance.clocks.set(animation, start);
315
+ return start;
316
+ }
317
+ /** Rounds to a whole pixel, never -0. */
318
+ function whole(value) {
319
+ return Math.round(value) || 0;
320
+ }
321
+ /** Numbers verbatim and booleans as 1/0 become `--name`; a string publishes nothing. */
322
+ function publish(host, name, value) {
323
+ const property = `--${name}`;
324
+ if (typeof value === 'number')
325
+ host.style.setProperty(property, String(value));
326
+ else if (typeof value === 'boolean')
327
+ host.style.setProperty(property, value ? '1' : '0');
328
+ else
329
+ host.style.removeProperty(property);
330
+ }
@@ -12,7 +12,7 @@ export interface ParamSpec {
12
12
  /** Allowed values for a string param; rendered as a dropdown. Takes precedence over ref. */
13
13
  options?: string[];
14
14
  /** Project value this string param names; rendered and validated as a typed reference. */
15
- ref?: 'prefab' | 'stat' | 'action' | 'clip' | 'sound';
15
+ ref?: 'prefab' | 'stat' | 'action' | 'clip' | 'sound' | 'ui';
16
16
  }
17
17
  export interface ComponentClass<T extends Component = Component> {
18
18
  new (): T;
package/dist/entity.js CHANGED
@@ -55,6 +55,10 @@ export class Entity {
55
55
  if (this.destroyed)
56
56
  return;
57
57
  this.destroyed = true;
58
+ // Immediately, before any onDestroy hook runs, whatever the scope
59
+ // (ADR 0017, CA-5) — `alive` is already false by the time any of this
60
+ // entity's own timers/tweens could observe it.
61
+ this.game.time.cancelOwnedBy(this);
58
62
  for (const c of [...this.components])
59
63
  c.onDestroy?.();
60
64
  this.components.length = 0;