@flare-engine/core 0.3.1 → 0.4.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
@@ -26,6 +26,49 @@ const b = bullets.acquire();
26
26
  bullets.release(b);
27
27
  ```
28
28
 
29
+ ## Coroutines
30
+
31
+ `yield` a number to wait that many scaled seconds, `undefined` to wait one frame, or a Promise to
32
+ wait for it. A coroutine ends exactly one of three ways — completed, `cancelled`, or `failed` — and
33
+ `handle.done` is true for all three. `cancel()` and `clear()` both close the generator (a scene
34
+ teardown is a cancel from the coroutine's point of view), so a `finally` block is the place for
35
+ cleanup — it runs on completion, on cancel, on teardown and on failure alike. A rejected Promise is
36
+ thrown into the generator; catch it to keep going, or let it end the coroutine with `failed` set:
37
+
38
+ ```ts
39
+ import { CoroutineManager } from '@flare-engine/core';
40
+
41
+ const coroutines = new CoroutineManager();
42
+ let bannerVisible = false;
43
+
44
+ const handle = coroutines.start(
45
+ (function* () {
46
+ try {
47
+ bannerVisible = true;
48
+ yield 2; // seconds, scaled time
49
+ yield fetch('/api/score'); // a rejection is thrown into the generator
50
+ yield undefined; // one frame
51
+ } finally {
52
+ bannerVisible = false; // runs on completion, cancel(), clear() and failure
53
+ }
54
+ })(),
55
+ );
56
+
57
+ // each frame
58
+ coroutines.update(1 / 60);
59
+
60
+ if (handle.failed) {
61
+ console.warn('score fetch failed', handle.error);
62
+ } else if (handle.cancelled) {
63
+ // ended early — cancel(), or the scene's clear() tore it down
64
+ }
65
+ handle.cancel(); // no-op once done; otherwise the finally block runs now
66
+ ```
67
+
68
+ Failures are never re-raised as unhandled rejections — the handle is the only channel, so keep it
69
+ if you need to know. Test `handle.failed` rather than `handle.error`: a bare `reject()` rejects
70
+ with `undefined`.
71
+
29
72
  See [API spec](https://github.com/grzott/flare-engine/blob/main/docs/design/api-specs.md#flare-enginecore--3kb-gzip).
30
73
 
31
74
  ## License
package/dist/index.d.mts CHANGED
@@ -135,13 +135,31 @@ declare class AppLifecycle {
135
135
  *
136
136
  * - yield number → wait N seconds (scaled time)
137
137
  * - yield undefined → wait 1 frame
138
- * - yield Promise → wait until resolved
138
+ * - yield Promise → wait until resolved; a rejection is thrown into the generator
139
139
  */
140
- /** A running coroutine handle. */
140
+ /** A running coroutine handle. Ends exactly one of three ways: completed, cancelled, or failed. */
141
141
  interface CoroutineHandle {
142
- /** Whether the coroutine has completed or been cancelled. */
142
+ /** Whether the coroutine has finished — completed, cancelled, or failed. */
143
143
  readonly done: boolean;
144
- /** Cancel the coroutine. It will not resume. */
144
+ /**
145
+ * Whether `cancel()` or `clear()` ended the coroutine before it completed. Implies `done`;
146
+ * mutually exclusive with `failed`. A cancel issued from inside the running body reports the
147
+ * same way as one issued from outside.
148
+ */
149
+ readonly cancelled: boolean;
150
+ /**
151
+ * Whether a rejected `yield Promise` ended the coroutine without the generator recovering.
152
+ * Implies `done`; mutually exclusive with `cancelled`. The failure is never re-raised as an
153
+ * unhandled rejection; this is the channel.
154
+ */
155
+ readonly failed: boolean;
156
+ /**
157
+ * What the generator threw when `failed` — the rejection reason, unless a `catch`/`finally`
158
+ * block threw something else. `undefined` while running, after a clean finish, or after a
159
+ * cancel. Test `failed` rather than `error`: a bare `reject()` rejects with `undefined`.
160
+ */
161
+ readonly error: unknown;
162
+ /** Cancel the coroutine. Its pending `finally` blocks run; it will not resume. */
145
163
  cancel(): void;
146
164
  }
147
165
  /** Yield type for coroutine generators. */
@@ -158,11 +176,14 @@ declare class CoroutineManager {
158
176
  start(gen: CoroutineGenerator): CoroutineHandle;
159
177
  /** Update all running coroutines. Call once per frame with scaled dt. */
160
178
  update(dt: number): void;
161
- /** Cancel all running coroutines. */
179
+ /** Cancel all running coroutines. Each one's pending `finally` blocks run. */
162
180
  clear(): void;
163
181
  /** Number of active coroutines. */
164
182
  get count(): number;
165
183
  private advance;
184
+ /** Resume the generator by throwing a rejected promise's reason into it. */
185
+ private advanceWithError;
186
+ private dispatch;
166
187
  }
167
188
  //#endregion
168
189
  //#region src/pool.d.ts
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.mts","names":[],"sources":["../src/clock.ts","../src/game-loop.ts","../src/app-lifecycle.ts","../src/coroutine.ts","../src/pool.ts","../src/screen.ts"],"mappings":";;;;;;;cAYa;;EAEX;;EAGA;;EAGA;;EAGA;;EAGA;;EAGA;;EAGA;UAEQ;UACA;;EAGR,OAAO;;EAkBP,SAAS,eAAe;;EAUxB,OAAO,kBAAkB;;EAUzB;UAUQ;;;;;UClFO;;EAEf;;EAEA;;;;;;;;cASW;WACF,OAAK;;WAGL,eAAa;;WAEb,UAAQ;;WAER,cAAY;;WAEZ,aAAW;;WAEX,cAAY;UAEb;UACA;UACA;UACA;UACA;UACA;UACA;;EAGR,QAAQ,WAAW;;EAEnB,cAAc;cAEF,SAAS;;EAUrB;;EAUA;;EAWA;;EAMA;;MAOI;;MAKA;;;;;;;;;;;;MAeA;;EAKJ,KAAK;UA2BG;;;;;;;;;;;;;cChIG;;WAEF,cAAY;;WAEZ,cAAY;;WAEZ,iBAAe;UAEhB;UACA;UACA;cAEI,MAAM;;EAKlB;;EAWA;;EASA;;;;;;;;;;;;UCxCe;;WAEN;;EAET;;;KAIU,sCAAsC;;KAGtC,qBAAqB,UAAU;;;;;cAa9B;UACH;;EAGR,MAAM,KAAK,qBAAqB;;EAwBhC,OAAO;;EAyBP;;MAQI;UAII;;;;;UC3EO;;;;;EAKf;;;;;;;;;;cAWW,KAAK;UACR;UACA;UACA;UACA;UACA;UACA;UACA;;;;;;cAOI,eAAe,GAAG,SAAS,MAAM,YAAY,UAAU;;EAUnE,WAAW;;;;;;EAkBX,cAAc;;EAed,QAAQ,MAAM;;EAYd,QAAQ;;MAOJ;;MAKA;;;;MAOA;;EAKJ;;;;;KChIU;;UAGK;;EAEf;;EAEA;;EAEA,YAAY;;;;;;;;;cAUD;;WAEF;;WAEA;;EAET,WAAW;;EAGX;;EAGA,UAAU;;WAGD,UAAQ;;EAGjB;;EAEA;;EAEA;;EAEA;UAEQ;UACA;cAEI,QAAQ;UAMZ;UACA;UACA;UACA;;EAGR,OAAO,qBAAqB,sBAAsB;;;;;EAalD,kBAAkB,aAAa,eAAe,gBAAgB;UAStD;;EAWR,eAAe,OAAO,OAAO;;EAQ7B,eAAe,OAAO,OAAO;;MAQzB,YAAY;UAeR"}
1
+ {"version":3,"file":"index.d.mts","names":[],"sources":["../src/clock.ts","../src/game-loop.ts","../src/app-lifecycle.ts","../src/coroutine.ts","../src/pool.ts","../src/screen.ts"],"mappings":";;;;;;;cAYa;;EAEX;;EAGA;;EAGA;;EAGA;;EAGA;;EAGA;;EAGA;UAEQ;UACA;;EAGR,OAAO;;EAkBP,SAAS,eAAe;;EAUxB,OAAO,kBAAkB;;EAUzB;UAUQ;;;;;UClFO;;EAEf;;EAEA;;;;;;;;cASW;WACF,OAAK;;WAGL,eAAa;;WAEb,UAAQ;;WAER,cAAY;;WAEZ,aAAW;;WAEX,cAAY;UAEb;UACA;UACA;UACA;UACA;UACA;UACA;;EAGR,QAAQ,WAAW;;EAEnB,cAAc;cAEF,SAAS;;EAUrB;;EAUA;;EAWA;;EAMA;;MAOI;;MAKA;;;;;;;;;;;;MAeA;;EAKJ,KAAK;UA2BG;;;;;;;;;;;;;cChIG;;WAEF,cAAY;;WAEZ,cAAY;;WAEZ,iBAAe;UAEhB;UACA;UACA;cAEI,MAAM;;EAKlB;;EAWA;;EASA;;;;;;;;;;;;UCxCe;;WAEN;;;;;;WAMA;;;;;;WAMA;;;;;;WAMA;;EAET;;;KAIU,sCAAsC;;KAGtC,qBAAqB,UAAU;;;;;cAgC9B;UACH;;EAGR,MAAM,KAAK,qBAAqB;;EAqChC,OAAO;;EAyBP;;MAUI;UAII;;UAQA;UAiBA;;;;;UCxJO;;;;;EAKf;;;;;;;;;;cAWW,KAAK;UACR;UACA;UACA;UACA;UACA;UACA;UACA;;;;;;cAOI,eAAe,GAAG,SAAS,MAAM,YAAY,UAAU;;EAUnE,WAAW;;;;;;EAkBX,cAAc;;EAed,QAAQ,MAAM;;EAYd,QAAQ;;MAOJ;;MAKA;;;;MAOA;;EAKJ;;;;;KChIU;;UAGK;;EAEf;;EAEA;;EAEA,YAAY;;;;;;;;;cAUD;;WAEF;;WAEA;;EAET,WAAW;;EAGX;;EAGA,UAAU;;WAGD,UAAQ;;EAGjB;;EAEA;;EAEA;;EAEA;UAEQ;UACA;cAEI,QAAQ;UAMZ;UACA;UACA;UACA;;EAGR,OAAO,qBAAqB,sBAAsB;;;;;EAalD,kBAAkB,aAAa,eAAe,gBAAgB;UAStD;;EAWR,eAAe,OAAO,OAAO;;EAQ7B,eAAe,OAAO,OAAO;;MAQzB,YAAY;UAeR"}
package/dist/index.d.ts CHANGED
@@ -135,13 +135,31 @@ declare class AppLifecycle {
135
135
  *
136
136
  * - yield number → wait N seconds (scaled time)
137
137
  * - yield undefined → wait 1 frame
138
- * - yield Promise → wait until resolved
138
+ * - yield Promise → wait until resolved; a rejection is thrown into the generator
139
139
  */
140
- /** A running coroutine handle. */
140
+ /** A running coroutine handle. Ends exactly one of three ways: completed, cancelled, or failed. */
141
141
  interface CoroutineHandle {
142
- /** Whether the coroutine has completed or been cancelled. */
142
+ /** Whether the coroutine has finished — completed, cancelled, or failed. */
143
143
  readonly done: boolean;
144
- /** Cancel the coroutine. It will not resume. */
144
+ /**
145
+ * Whether `cancel()` or `clear()` ended the coroutine before it completed. Implies `done`;
146
+ * mutually exclusive with `failed`. A cancel issued from inside the running body reports the
147
+ * same way as one issued from outside.
148
+ */
149
+ readonly cancelled: boolean;
150
+ /**
151
+ * Whether a rejected `yield Promise` ended the coroutine without the generator recovering.
152
+ * Implies `done`; mutually exclusive with `cancelled`. The failure is never re-raised as an
153
+ * unhandled rejection; this is the channel.
154
+ */
155
+ readonly failed: boolean;
156
+ /**
157
+ * What the generator threw when `failed` — the rejection reason, unless a `catch`/`finally`
158
+ * block threw something else. `undefined` while running, after a clean finish, or after a
159
+ * cancel. Test `failed` rather than `error`: a bare `reject()` rejects with `undefined`.
160
+ */
161
+ readonly error: unknown;
162
+ /** Cancel the coroutine. Its pending `finally` blocks run; it will not resume. */
145
163
  cancel(): void;
146
164
  }
147
165
  /** Yield type for coroutine generators. */
@@ -158,11 +176,14 @@ declare class CoroutineManager {
158
176
  start(gen: CoroutineGenerator): CoroutineHandle;
159
177
  /** Update all running coroutines. Call once per frame with scaled dt. */
160
178
  update(dt: number): void;
161
- /** Cancel all running coroutines. */
179
+ /** Cancel all running coroutines. Each one's pending `finally` blocks run. */
162
180
  clear(): void;
163
181
  /** Number of active coroutines. */
164
182
  get count(): number;
165
183
  private advance;
184
+ /** Resume the generator by throwing a rejected promise's reason into it. */
185
+ private advanceWithError;
186
+ private dispatch;
166
187
  }
167
188
  //#endregion
168
189
  //#region src/pool.d.ts
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","names":[],"sources":["../src/clock.ts","../src/game-loop.ts","../src/app-lifecycle.ts","../src/coroutine.ts","../src/pool.ts","../src/screen.ts"],"mappings":";;;;;;;cAYa;;EAEX;;EAGA;;EAGA;;EAGA;;EAGA;;EAGA;;EAGA;UAEQ;UACA;;EAGR,OAAO;;EAkBP,SAAS,eAAe;;EAUxB,OAAO,kBAAkB;;EAUzB;UAUQ;;;;;UClFO;;EAEf;;EAEA;;;;;;;;cASW;WACF,OAAK;;WAGL,eAAa;;WAEb,UAAQ;;WAER,cAAY;;WAEZ,aAAW;;WAEX,cAAY;UAEb;UACA;UACA;UACA;UACA;UACA;UACA;;EAGR,QAAQ,WAAW;;EAEnB,cAAc;cAEF,SAAS;;EAUrB;;EAUA;;EAWA;;EAMA;;MAOI;;MAKA;;;;;;;;;;;;MAeA;;EAKJ,KAAK;UA2BG;;;;;;;;;;;;;cChIG;;WAEF,cAAY;;WAEZ,cAAY;;WAEZ,iBAAe;UAEhB;UACA;UACA;cAEI,MAAM;;EAKlB;;EAWA;;EASA;;;;;;;;;;;;UCxCe;;WAEN;;EAET;;;KAIU,sCAAsC;;KAGtC,qBAAqB,UAAU;;;;;cAa9B;UACH;;EAGR,MAAM,KAAK,qBAAqB;;EAwBhC,OAAO;;EAyBP;;MAQI;UAII;;;;;UC3EO;;;;;EAKf;;;;;;;;;;cAWW,KAAK;UACR;UACA;UACA;UACA;UACA;UACA;UACA;;;;;;cAOI,eAAe,GAAG,SAAS,MAAM,YAAY,UAAU;;EAUnE,WAAW;;;;;;EAkBX,cAAc;;EAed,QAAQ,MAAM;;EAYd,QAAQ;;MAOJ;;MAKA;;;;MAOA;;EAKJ;;;;;KChIU;;UAGK;;EAEf;;EAEA;;EAEA,YAAY;;;;;;;;;cAUD;;WAEF;;WAEA;;EAET,WAAW;;EAGX;;EAGA,UAAU;;WAGD,UAAQ;;EAGjB;;EAEA;;EAEA;;EAEA;UAEQ;UACA;cAEI,QAAQ;UAMZ;UACA;UACA;UACA;;EAGR,OAAO,qBAAqB,sBAAsB;;;;;EAalD,kBAAkB,aAAa,eAAe,gBAAgB;UAStD;;EAWR,eAAe,OAAO,OAAO;;EAQ7B,eAAe,OAAO,OAAO;;MAQzB,YAAY;UAeR"}
1
+ {"version":3,"file":"index.d.ts","names":[],"sources":["../src/clock.ts","../src/game-loop.ts","../src/app-lifecycle.ts","../src/coroutine.ts","../src/pool.ts","../src/screen.ts"],"mappings":";;;;;;;cAYa;;EAEX;;EAGA;;EAGA;;EAGA;;EAGA;;EAGA;;EAGA;UAEQ;UACA;;EAGR,OAAO;;EAkBP,SAAS,eAAe;;EAUxB,OAAO,kBAAkB;;EAUzB;UAUQ;;;;;UClFO;;EAEf;;EAEA;;;;;;;;cASW;WACF,OAAK;;WAGL,eAAa;;WAEb,UAAQ;;WAER,cAAY;;WAEZ,aAAW;;WAEX,cAAY;UAEb;UACA;UACA;UACA;UACA;UACA;UACA;;EAGR,QAAQ,WAAW;;EAEnB,cAAc;cAEF,SAAS;;EAUrB;;EAUA;;EAWA;;EAMA;;MAOI;;MAKA;;;;;;;;;;;;MAeA;;EAKJ,KAAK;UA2BG;;;;;;;;;;;;;cChIG;;WAEF,cAAY;;WAEZ,cAAY;;WAEZ,iBAAe;UAEhB;UACA;UACA;cAEI,MAAM;;EAKlB;;EAWA;;EASA;;;;;;;;;;;;UCxCe;;WAEN;;;;;;WAMA;;;;;;WAMA;;;;;;WAMA;;EAET;;;KAIU,sCAAsC;;KAGtC,qBAAqB,UAAU;;;;;cAgC9B;UACH;;EAGR,MAAM,KAAK,qBAAqB;;EAqChC,OAAO;;EAyBP;;MAUI;UAII;;UAQA;UAiBA;;;;;UCxJO;;;;;EAKf;;;;;;;;;;cAWW,KAAK;UACR;UACA;UACA;UACA;UACA;UACA;UACA;;;;;;cAOI,eAAe,GAAG,SAAS,MAAM,YAAY,UAAU;;EAUnE,WAAW;;;;;;EAkBX,cAAc;;EAed,QAAQ,MAAM;;EAYd,QAAQ;;MAOJ;;MAKA;;;;MAOA;;EAKJ;;;;;KChIU;;UAGK;;EAEf;;EAEA;;EAEA,YAAY;;;;;;;;;cAUD;;WAEF;;WAEA;;EAET,WAAW;;EAGX;;EAGA,UAAU;;WAGD,UAAQ;;EAGjB;;EAEA;;EAEA;;EAEA;UAEQ;UACA;cAEI,QAAQ;UAMZ;UACA;UACA;UACA;;EAGR,OAAO,qBAAqB,sBAAsB;;;;;EAalD,kBAAkB,aAAa,eAAe,gBAAgB;UAStD;;EAWR,eAAe,OAAO,OAAO;;EAQ7B,eAAe,OAAO,OAAO;;MAQzB,YAAY;UAeR"}
package/dist/index.js CHANGED
@@ -128,6 +128,19 @@ var Clock = class {
128
128
  //#endregion
129
129
  //#region src/coroutine.ts
130
130
  /**
131
+ * Marks the coroutine cancelled and closes its generator so pending `finally` blocks run.
132
+ * A generator cannot be closed while its body is executing (`gen.return()` throws
133
+ * "Generator is already running"), so a cancel that arrives from inside the body is only
134
+ * marked here and closed by `dispatch()` once the body suspends. Shared by `cancel()` and
135
+ * `clear()` — a scene teardown is a cancel from the coroutine's point of view.
136
+ */
137
+ function closeCoroutine(state) {
138
+ if (state.done) return;
139
+ state.done = true;
140
+ state.cancelled = true;
141
+ if (!state.running) state.gen.return();
142
+ }
143
+ /**
131
144
  * CoroutineManager runs generator-based coroutines.
132
145
  * Call update(dt) each frame to advance all active coroutines.
133
146
  */
@@ -139,7 +152,11 @@ var CoroutineManager = class {
139
152
  gen,
140
153
  waitTime: 0,
141
154
  waitingForPromise: false,
142
- done: false
155
+ running: false,
156
+ done: false,
157
+ cancelled: false,
158
+ failed: false,
159
+ error: void 0
143
160
  };
144
161
  this.coroutines.push(state);
145
162
  this.advance(state);
@@ -147,8 +164,17 @@ var CoroutineManager = class {
147
164
  get done() {
148
165
  return state.done;
149
166
  },
167
+ get cancelled() {
168
+ return state.cancelled;
169
+ },
170
+ get failed() {
171
+ return state.failed;
172
+ },
173
+ get error() {
174
+ return state.error;
175
+ },
150
176
  cancel() {
151
- state.done = true;
177
+ closeCoroutine(state);
152
178
  }
153
179
  };
154
180
  }
@@ -170,17 +196,45 @@ var CoroutineManager = class {
170
196
  if (state.done) this.coroutines.splice(i, 1);
171
197
  }
172
198
  }
173
- /** Cancel all running coroutines. */
199
+ /** Cancel all running coroutines. Each one's pending `finally` blocks run. */
174
200
  clear() {
175
- for (const state of this.coroutines) state.done = true;
176
- this.coroutines.length = 0;
201
+ let state = this.coroutines.pop();
202
+ while (state !== void 0) {
203
+ closeCoroutine(state);
204
+ state = this.coroutines.pop();
205
+ }
177
206
  }
178
207
  /** Number of active coroutines. */
179
208
  get count() {
180
209
  return this.coroutines.length;
181
210
  }
182
211
  advance(state) {
212
+ state.running = true;
183
213
  const result = state.gen.next();
214
+ state.running = false;
215
+ this.dispatch(state, result);
216
+ }
217
+ /** Resume the generator by throwing a rejected promise's reason into it. */
218
+ advanceWithError(state, err) {
219
+ let result;
220
+ state.running = true;
221
+ try {
222
+ result = state.gen.throw(err);
223
+ } catch (thrown) {
224
+ state.running = false;
225
+ state.done = true;
226
+ state.failed = true;
227
+ state.error = thrown;
228
+ return;
229
+ }
230
+ state.running = false;
231
+ this.dispatch(state, result);
232
+ }
233
+ dispatch(state, result) {
234
+ if (state.done) {
235
+ if (!result.done) state.gen.return();
236
+ return;
237
+ }
184
238
  if (result.done) {
185
239
  state.done = true;
186
240
  return;
@@ -191,8 +245,10 @@ var CoroutineManager = class {
191
245
  state.waitingForPromise = true;
192
246
  value.then(() => {
193
247
  state.waitingForPromise = false;
194
- }, () => {
195
- state.done = true;
248
+ }, (err) => {
249
+ if (state.done) return;
250
+ state.waitingForPromise = false;
251
+ this.advanceWithError(state, err);
196
252
  });
197
253
  }
198
254
  }
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["Signal","Signal","Signal"],"sources":["../src/app-lifecycle.ts","../src/clock.ts","../src/coroutine.ts","../src/game-loop.ts","../src/pool.ts","../src/screen.ts"],"sourcesContent":["import { Signal } from '@flare-engine/events';\nimport type { GameLoop } from './game-loop.js';\n\n/**\n * AppLifecycle bridges React Native AppState to the game loop.\n *\n * - Auto-pauses the loop when app goes to background\n * - Auto-resumes when app returns to foreground\n * - Caps dt on resume to prevent huge time jumps\n *\n * In non-RN environments (tests, web), use the manual methods.\n */\nexport class AppLifecycle {\n /** Fires when app enters background. */\n readonly onBackground = new Signal<void>();\n /** Fires when app returns to foreground. */\n readonly onForeground = new Signal<void>();\n /** Fires on memory warning (RN-specific). */\n readonly onMemoryWarning = new Signal<void>();\n\n private loop: GameLoop;\n private wasRunningBeforeBackground = false;\n private _inBackground = false;\n\n constructor(loop: GameLoop) {\n this.loop = loop;\n }\n\n /** Call when app goes to background. */\n background(): void {\n if (this._inBackground) return;\n this._inBackground = true;\n this.wasRunningBeforeBackground = this.loop.isRunning && !this.loop.isPaused;\n if (this.wasRunningBeforeBackground) {\n this.loop.pause();\n }\n this.onBackground.emit();\n }\n\n /** Call when app returns to foreground. */\n foreground(): void {\n this._inBackground = false;\n if (this.wasRunningBeforeBackground) {\n this.loop.resume();\n }\n this.onForeground.emit();\n }\n\n /** Call on memory warning. */\n memoryWarning(): void {\n this.onMemoryWarning.emit();\n }\n}\n","/**\n * Clock tracks frame timing: delta time, elapsed time, fps, timescale.\n * One instance per GameLoop. Updated once per frame.\n */\n\n/** Scheduled callback entry. */\ninterface ScheduleEntry {\n remaining: number;\n callback: () => void;\n interval: number; // 0 = one-shot\n}\n\nexport class Clock {\n /** Unscaled delta time in seconds since last frame. */\n rawDt = 0;\n\n /** Scaled delta time in seconds (rawDt * timescale). */\n dt = 0;\n\n /** Fixed timestep in seconds for physics updates (default 1/60). */\n fixedDt = 1 / 60;\n\n /** Total elapsed time in seconds (scaled). */\n elapsed = 0;\n\n /** Smoothed frames per second. */\n fps = 0;\n\n /** Time scale multiplier. 1 = normal, 0 = paused, 0.5 = slow-mo. */\n timescale = 1;\n\n /** Current frame number (monotonically increasing). */\n frame = 0;\n\n private schedules: ScheduleEntry[] = [];\n private fpsAlpha = 0.9;\n\n /** Called once per frame by the GameLoop with raw unscaled dt. */\n update(rawDt: number): void {\n this.rawDt = rawDt;\n this.dt = rawDt * this.timescale;\n this.elapsed += this.dt;\n this.frame++;\n\n // Exponential moving average FPS\n if (rawDt > 0) {\n const instantFps = 1 / rawDt;\n this.fps =\n this.fps === 0 ? instantFps : this.fps * this.fpsAlpha + instantFps * (1 - this.fpsAlpha);\n }\n\n // Process scheduled callbacks\n this.tickSchedules(this.dt);\n }\n\n /** Schedule a one-shot callback after `delay` seconds (scaled time). */\n schedule(delay: number, callback: () => void): () => void {\n const entry: ScheduleEntry = { remaining: delay, callback, interval: 0 };\n this.schedules.push(entry);\n return () => {\n const idx = this.schedules.indexOf(entry);\n if (idx !== -1) this.schedules.splice(idx, 1);\n };\n }\n\n /** Schedule a repeating callback every `interval` seconds (scaled time). */\n repeat(interval: number, callback: () => void): () => void {\n const entry: ScheduleEntry = { remaining: interval, callback, interval };\n this.schedules.push(entry);\n return () => {\n const idx = this.schedules.indexOf(entry);\n if (idx !== -1) this.schedules.splice(idx, 1);\n };\n }\n\n /** Reset clock to initial state. */\n reset(): void {\n this.rawDt = 0;\n this.dt = 0;\n this.elapsed = 0;\n this.fps = 0;\n this.frame = 0;\n this.timescale = 1;\n this.schedules.length = 0;\n }\n\n private tickSchedules(dt: number): void {\n for (let i = this.schedules.length - 1; i >= 0; i--) {\n const entry = this.schedules[i];\n if (entry === undefined) continue;\n entry.remaining -= dt;\n if (entry.remaining <= 0) {\n entry.callback();\n if (entry.interval > 0) {\n entry.remaining += entry.interval;\n } else {\n const idx = this.schedules.indexOf(entry);\n if (idx !== -1) this.schedules.splice(idx, 1);\n }\n }\n }\n }\n}\n","/**\n * Generator-based coroutines for game logic.\n *\n * - yield number → wait N seconds (scaled time)\n * - yield undefined → wait 1 frame\n * - yield Promise → wait until resolved\n */\n\n/** A running coroutine handle. */\nexport interface CoroutineHandle {\n /** Whether the coroutine has completed or been cancelled. */\n readonly done: boolean;\n /** Cancel the coroutine. It will not resume. */\n cancel(): void;\n}\n\n/** Yield type for coroutine generators. */\nexport type CoroutineYield = number | undefined | Promise<unknown>;\n\n/** A coroutine generator function. */\nexport type CoroutineGenerator = Generator<CoroutineYield, void, unknown>;\n\ninterface CoroutineState {\n gen: CoroutineGenerator;\n waitTime: number;\n waitingForPromise: boolean;\n done: boolean;\n}\n\n/**\n * CoroutineManager runs generator-based coroutines.\n * Call update(dt) each frame to advance all active coroutines.\n */\nexport class CoroutineManager {\n private coroutines: CoroutineState[] = [];\n\n /** Start a new coroutine. Returns a handle to check status or cancel. */\n start(gen: CoroutineGenerator): CoroutineHandle {\n const state: CoroutineState = {\n gen,\n waitTime: 0,\n waitingForPromise: false,\n done: false,\n };\n this.coroutines.push(state);\n\n // Advance to first yield immediately\n this.advance(state);\n\n const handle: CoroutineHandle = {\n get done() {\n return state.done;\n },\n cancel() {\n state.done = true;\n },\n };\n return handle;\n }\n\n /** Update all running coroutines. Call once per frame with scaled dt. */\n update(dt: number): void {\n for (let i = this.coroutines.length - 1; i >= 0; i--) {\n const state = this.coroutines[i];\n if (state === undefined) continue;\n if (state.done) {\n this.coroutines.splice(i, 1);\n continue;\n }\n\n if (state.waitingForPromise) continue;\n\n if (state.waitTime > 0) {\n state.waitTime -= dt;\n if (state.waitTime > 0) continue;\n }\n\n this.advance(state);\n\n if (state.done) {\n this.coroutines.splice(i, 1);\n }\n }\n }\n\n /** Cancel all running coroutines. */\n clear(): void {\n for (const state of this.coroutines) {\n state.done = true;\n }\n this.coroutines.length = 0;\n }\n\n /** Number of active coroutines. */\n get count(): number {\n return this.coroutines.length;\n }\n\n private advance(state: CoroutineState): void {\n const result = state.gen.next();\n if (result.done) {\n state.done = true;\n return;\n }\n\n const value = result.value;\n if (typeof value === 'number') {\n state.waitTime = value;\n } else if (value instanceof Promise) {\n state.waitingForPromise = true;\n value.then(\n () => {\n state.waitingForPromise = false;\n },\n () => {\n // On rejection, stop the coroutine\n state.done = true;\n },\n );\n }\n // undefined → wait 1 frame (will advance next update)\n }\n}\n","import { Signal } from '@flare-engine/events';\nimport { Clock } from './clock.js';\n\n/** Configuration for the game loop. */\nexport interface GameLoopConfig {\n /** Fixed timestep in seconds (default 1/60). */\n fixedDt?: number;\n /** Maximum raw dt cap in seconds to prevent spiral of death (default 0.25). */\n maxDt?: number;\n}\n\n/**\n * GameLoop drives the update cycle using fixed + variable timestep.\n *\n * Fixed updates run at a constant rate (accumulator pattern).\n * Variable updates run once per frame with the actual dt.\n */\nexport class GameLoop {\n readonly clock = new Clock();\n\n /** Fixed-timestep update (physics, deterministic logic). */\n readonly onFixedUpdate = new Signal<number>();\n /** Variable-timestep update (movement, AI, game logic). */\n readonly onUpdate = new Signal<number>();\n /** Runs after onUpdate (camera follow, post-processing logic). */\n readonly onLateUpdate = new Signal<number>();\n /** Runs before rendering. */\n readonly onPreRender = new Signal<void>();\n /** Runs after rendering. */\n readonly onPostRender = new Signal<void>();\n\n private running = false;\n private paused = false;\n private accumulator = 0;\n private maxDt: number;\n private rafId = 0;\n private lastTime = 0;\n private _hasFixedDt = false;\n\n /** External tick function — set this for testing or custom scheduling. */\n tick: ((callback: (time: number) => void) => number) | undefined;\n /** External cancel function — paired with tick. */\n cancelTick: ((id: number) => void) | undefined;\n\n constructor(config?: GameLoopConfig) {\n this.maxDt = config?.maxDt ?? 0.25;\n if (config?.fixedDt !== undefined) {\n if (config.fixedDt <= 0) throw new Error('GameLoop: fixedDt must be > 0');\n this.clock.fixedDt = config.fixedDt;\n this._hasFixedDt = true;\n }\n }\n\n /** Start the game loop. */\n start(): void {\n if (this.running) return;\n this.running = true;\n this.paused = false;\n this.lastTime = 0;\n this.accumulator = 0;\n this.scheduleFrame();\n }\n\n /** Stop the game loop entirely and reset. */\n stop(): void {\n this.running = false;\n this.paused = false;\n if (this.rafId !== 0) {\n const cancel = this.cancelTick ?? cancelAnimationFrame;\n cancel(this.rafId);\n this.rafId = 0;\n }\n }\n\n /** Pause — signals stop firing but loop stays alive. */\n pause(): void {\n if (!this.running || this.paused) return;\n this.paused = true;\n }\n\n /** Resume from pause. */\n resume(): void {\n if (!this.running || !this.paused) return;\n this.paused = false;\n this.lastTime = 0; // Reset so next frame doesn't have a huge dt\n }\n\n /** Whether the loop is currently running (started and not stopped). */\n get isRunning(): boolean {\n return this.running;\n }\n\n /** Whether the loop is paused. */\n get isPaused(): boolean {\n return this.paused;\n }\n\n /**\n * Post-step residual fraction for physics interpolation.\n *\n * After fixed updates drain the accumulator, `alpha` is the fraction of a\n * fixed step that has elapsed since the last fixed tick — always in [0, 1).\n * Read in `onPreRender` to lerp between the previous and current physics\n * state for smooth visuals at any display refresh rate.\n *\n * Returns 0 when no fixed step was configured (i.e. `fixedDt` was not\n * passed to the constructor).\n */\n get alpha(): number {\n return this._hasFixedDt ? this.accumulator / this.clock.fixedDt : 0;\n }\n\n /** Process a single frame. Exposed for testing. */\n step(rawDt: number): void {\n if (this.paused) return;\n\n // Cap the dt to avoid spiral of death\n const capped = Math.min(rawDt, this.maxDt);\n this.clock.update(capped);\n\n const dt = this.clock.dt;\n const fixedDt = this.clock.fixedDt;\n if (fixedDt <= 0) throw new Error('GameLoop: fixedDt must be > 0');\n\n // Fixed update accumulator\n this.accumulator += dt;\n while (this.accumulator >= fixedDt) {\n this.onFixedUpdate.emit(fixedDt);\n this.accumulator -= fixedDt;\n }\n\n // Variable update\n this.onUpdate.emit(dt);\n this.onLateUpdate.emit(dt);\n\n // Render\n this.onPreRender.emit();\n this.onPostRender.emit();\n }\n\n private scheduleFrame(): void {\n const request = this.tick ?? requestAnimationFrame;\n this.rafId = request((time: number) => {\n if (!this.running) return;\n\n if (this.lastTime === 0) {\n this.lastTime = time;\n this.scheduleFrame();\n return;\n }\n\n const rawDt = (time - this.lastTime) / 1000;\n this.lastTime = time;\n\n this.step(rawDt);\n this.scheduleFrame();\n });\n }\n}\n","declare const __DEV__: boolean | undefined;\n\n/**\n * Dev-flag access for `release()`, which runs once per released object.\n *\n * JSC has no inline cache for an unresolvable global identifier, so reading the\n * bare `__DEV__` identifier behind a `typeof` guard costs ~270 ns *per\n * evaluation* wherever the global is undeclared. React Native always defines it;\n * web/CanvasKit and any Node or Bun consumer does not. A property miss on\n * `globalThis` is inline-cached at ~0.46 ns and stays togglable at runtime\n * exactly as before. Measured B28 (on JSC — V8 was never measured), PERF-10.\n *\n * Phrased without the literal old expression so `tests/pool-dist.test.ts` can\n * count its occurrences in the built artifact: exactly one must survive, the\n * constructor's.\n *\n * The constructor below deliberately keeps the identifier form: it runs once\n * per pool, where ~270 ns is free, and it is the site a bundler can\n * constant-fold for dead-code elimination.\n */\nconst G = globalThis as { __DEV__?: boolean };\n\n/** Options for Pool construction. */\nexport interface PoolOptions {\n /**\n * Maximum number of simultaneously live (acquired) objects.\n * Enforced ONLY by `tryAcquire()` — `acquire()` is uncapped.\n */\n capacity?: number;\n}\n\n/**\n * Generic object pool for zero-alloc gameplay.\n *\n * - acquire() returns a recycled or newly created object (uncapped)\n * - tryAcquire() returns null when the live count is at capacity\n * - release(obj) returns it to the pool\n * - prewarm(count) pre-allocates objects\n */\nexport class Pool<T> {\n private items: T[] = [];\n private factory: () => T;\n private resetFn: ((item: T) => void) | undefined;\n private _capacity: number | undefined;\n private _live = 0;\n private _created = 0;\n private _liveSet: Set<T> | undefined;\n\n /**\n * @param factory Function to create a new instance.\n * @param reset Optional function to reset an object before reuse.\n * @param options Optional pool configuration (capacity cap).\n */\n constructor(factory: () => T, reset?: (item: T) => void, options?: PoolOptions) {\n this.factory = factory;\n this.resetFn = reset;\n this._capacity = options?.capacity;\n if (typeof __DEV__ !== 'undefined' && __DEV__) {\n this._liveSet = new Set();\n }\n }\n\n /** Get an object from the pool (or create a new one). Never throws; may exceed capacity. */\n acquire(): T {\n this._live++;\n let item: T;\n if (this.items.length > 0) {\n item = this.items.pop()!;\n } else {\n this._created++;\n item = this.factory();\n }\n this._liveSet?.delete(item);\n return item;\n }\n\n /**\n * Get an object from the pool only if the live count is below capacity.\n * Returns null when at cap — the caller must handle null (no allocation occurs).\n * When no capacity was configured, behaves identically to acquire().\n */\n tryAcquire(): T | null {\n if (this._capacity !== undefined && this._live >= this._capacity) return null;\n this._live++;\n let item: T;\n if (this.items.length > 0) {\n item = this.items.pop()!;\n } else {\n this._created++;\n item = this.factory();\n }\n this._liveSet?.delete(item);\n return item;\n }\n\n /** Return an object to the pool. Calls reset if configured. */\n release(item: T): void {\n if (G.__DEV__) {\n if (!this._liveSet) this._liveSet = new Set();\n if (this._liveSet.has(item)) throw new Error('[Pool] double-release detected');\n this._liveSet.add(item);\n }\n this._live--;\n if (this.resetFn) this.resetFn(item);\n this.items.push(item);\n }\n\n /** Pre-allocate objects into the pool. Does not count toward live. */\n prewarm(count: number): void {\n for (let i = 0; i < count; i++) {\n this.items.push(this.factory());\n }\n }\n\n /** Number of available objects currently in the pool (not live). */\n get available(): number {\n return this.items.length;\n }\n\n /** Number of currently live (acquired, not yet released) objects. */\n get live(): number {\n return this._live;\n }\n\n /** Cumulative number of factory calls made by acquire()/tryAcquire().\n * prewarm() is deliberately excluded: this counter exists to detect\n * steady-state allocation, so compare it before and after a frame. */\n get created(): number {\n return this._created;\n }\n\n /** Clear all pooled objects. Does not affect live count. */\n clear(): void {\n this.items.length = 0;\n this._liveSet?.clear();\n }\n}\n","import { Signal } from '@flare-engine/events';\nimport type { Rect, Vec2 } from '@flare-engine/math';\n\n/** Scale mode for mapping design resolution to device screen. */\nexport type ScaleMode = 'fit' | 'fill' | 'stretch';\n\n/** Screen configuration. */\nexport interface ScreenConfig {\n /** Design resolution width in logical pixels. */\n designWidth: number;\n /** Design resolution height in logical pixels. */\n designHeight: number;\n /** How to fit design resolution to device (default: 'fit'). */\n scaleMode?: ScaleMode;\n}\n\n/**\n * ScreenManager maps a fixed design resolution to the actual device screen.\n *\n * - FIT: letterbox (scale to fit, black bars)\n * - FILL: crop (scale to fill, content cropped)\n * - STRETCH: distort (stretch to fill, aspect ratio distorted)\n */\nexport class ScreenManager {\n /** Design resolution width. */\n readonly designWidth: number;\n /** Design resolution height. */\n readonly designHeight: number;\n /** Current scale mode. */\n scaleMode: ScaleMode;\n\n /** Device pixel ratio. */\n pixelRatio = 1;\n\n /** Safe area insets (top, right, bottom, left) in device pixels. */\n safeArea: Rect = { x: 0, y: 0, width: 0, height: 0 };\n\n /** Fires when screen dimensions change. */\n readonly onResize = new Signal<void>();\n\n /** Computed scale factor X (design → screen). */\n scaleX = 1;\n /** Computed scale factor Y (design → screen). */\n scaleY = 1;\n /** Offset X in screen pixels (for letterboxing). */\n offsetX = 0;\n /** Offset Y in screen pixels (for letterboxing). */\n offsetY = 0;\n\n private screenWidth = 0;\n private screenHeight = 0;\n\n constructor(config: ScreenConfig) {\n this.designWidth = config.designWidth;\n this.designHeight = config.designHeight;\n this.scaleMode = config.scaleMode ?? 'fit';\n }\n\n private safeInsetTop = 0;\n private safeInsetRight = 0;\n private safeInsetBottom = 0;\n private safeInsetLeft = 0;\n\n /** Update with actual device screen dimensions. Call on mount and resize. */\n resize(screenWidth: number, screenHeight: number, pixelRatio?: number): void {\n this.screenWidth = screenWidth;\n this.screenHeight = screenHeight;\n if (pixelRatio !== undefined) this.pixelRatio = pixelRatio;\n this.recalculate();\n this.recalculateSafeArea();\n this.onResize.emit();\n }\n\n /**\n * Set safe-area insets in screen pixels. Call this from the RN host with values from\n * `react-native-safe-area-context`. Populates `safeArea` as the usable region.\n */\n setSafeAreaInsets(top: number, right: number, bottom: number, left: number): void {\n this.safeInsetTop = top;\n this.safeInsetRight = right;\n this.safeInsetBottom = bottom;\n this.safeInsetLeft = left;\n this.recalculateSafeArea();\n this.onResize.emit();\n }\n\n private recalculateSafeArea(): void {\n this.safeArea.x = this.safeInsetLeft;\n this.safeArea.y = this.safeInsetTop;\n this.safeArea.width = Math.max(0, this.screenWidth - this.safeInsetLeft - this.safeInsetRight);\n this.safeArea.height = Math.max(\n 0,\n this.screenHeight - this.safeInsetTop - this.safeInsetBottom,\n );\n }\n\n /** Convert design-space point to screen-space. */\n designToScreen(point: Vec2): Vec2 {\n return {\n x: point.x * this.scaleX + this.offsetX,\n y: point.y * this.scaleY + this.offsetY,\n };\n }\n\n /** Convert screen-space point to design-space. */\n screenToDesign(point: Vec2): Vec2 {\n return {\n x: (point.x - this.offsetX) / this.scaleX,\n y: (point.y - this.offsetY) / this.scaleY,\n };\n }\n\n /** Viewport rect in design coordinates (visible area). */\n get viewport(): Rect {\n if (this.scaleMode === 'fill') {\n // In fill mode, the visible area is smaller than design\n const visibleW = this.screenWidth / this.scaleX;\n const visibleH = this.screenHeight / this.scaleY;\n return {\n x: (this.designWidth - visibleW) / 2,\n y: (this.designHeight - visibleH) / 2,\n width: visibleW,\n height: visibleH,\n };\n }\n return { x: 0, y: 0, width: this.designWidth, height: this.designHeight };\n }\n\n private recalculate(): void {\n const ratioX = this.screenWidth / this.designWidth;\n const ratioY = this.screenHeight / this.designHeight;\n\n switch (this.scaleMode) {\n case 'fit': {\n const scale = Math.min(ratioX, ratioY);\n this.scaleX = scale;\n this.scaleY = scale;\n this.offsetX = (this.screenWidth - this.designWidth * scale) / 2;\n this.offsetY = (this.screenHeight - this.designHeight * scale) / 2;\n break;\n }\n case 'fill': {\n const scale = Math.max(ratioX, ratioY);\n this.scaleX = scale;\n this.scaleY = scale;\n this.offsetX = (this.screenWidth - this.designWidth * scale) / 2;\n this.offsetY = (this.screenHeight - this.designHeight * scale) / 2;\n break;\n }\n case 'stretch': {\n this.scaleX = ratioX;\n this.scaleY = ratioY;\n this.offsetX = 0;\n this.offsetY = 0;\n break;\n }\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;AAYA,IAAa,eAAb,MAA0B;;CAExB,eAAwB,IAAIA,qBAAAA,OAAa;;CAEzC,eAAwB,IAAIA,qBAAAA,OAAa;;CAEzC,kBAA2B,IAAIA,qBAAAA,OAAa;CAE5C;CACA,6BAAqC;CACrC,gBAAwB;CAExB,YAAY,MAAgB;EAC1B,KAAK,OAAO;CACd;;CAGA,aAAmB;EACjB,IAAI,KAAK,eAAe;EACxB,KAAK,gBAAgB;EACrB,KAAK,6BAA6B,KAAK,KAAK,aAAa,CAAC,KAAK,KAAK;EACpE,IAAI,KAAK,4BACP,KAAK,KAAK,MAAM;EAElB,KAAK,aAAa,KAAK;CACzB;;CAGA,aAAmB;EACjB,KAAK,gBAAgB;EACrB,IAAI,KAAK,4BACP,KAAK,KAAK,OAAO;EAEnB,KAAK,aAAa,KAAK;CACzB;;CAGA,gBAAsB;EACpB,KAAK,gBAAgB,KAAK;CAC5B;AACF;;;ACxCA,IAAa,QAAb,MAAmB;;CAEjB,QAAQ;;CAGR,KAAK;;CAGL,UAAU,IAAI;;CAGd,UAAU;;CAGV,MAAM;;CAGN,YAAY;;CAGZ,QAAQ;CAER,YAAqC,CAAC;CACtC,WAAmB;;CAGnB,OAAO,OAAqB;EAC1B,KAAK,QAAQ;EACb,KAAK,KAAK,QAAQ,KAAK;EACvB,KAAK,WAAW,KAAK;EACrB,KAAK;EAGL,IAAI,QAAQ,GAAG;GACb,MAAM,aAAa,IAAI;GACvB,KAAK,MACH,KAAK,QAAQ,IAAI,aAAa,KAAK,MAAM,KAAK,W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ACd,KAAK,SAAS;IACd,KAAK,WAAW,KAAK,cAAc,KAAK,cAAc,SAAS;IAC/D,KAAK,WAAW,KAAK,eAAe,KAAK,eAAe,SAAS;IACjE;GACF;GACA,KAAK,QAAQ;IACX,MAAM,QAAQ,KAAK,IAAI,QAAQ,MAAM;IACrC,KAAK,SAAS;IACd,KAAK,SAAS;IACd,KAAK,WAAW,KAAK,cAAc,KAAK,cAAc,SAAS;IAC/D,KAAK,WAAW,KAAK,eAAe,KAAK,eAAe,SAAS;IACjE;GACF;GACA,KAAK;IACH,KAAK,SAAS;IACd,KAAK,SAAS;IACd,KAAK,UAAU;IACf,KAAK,UAAU;IACf;EAEJ;CACF;AACF"}
1
+ {"version":3,"file":"index.js","names":["Signal","Signal","Signal"],"sources":["../src/app-lifecycle.ts","../src/clock.ts","../src/coroutine.ts","../src/game-loop.ts","../src/pool.ts","../src/screen.ts"],"sourcesContent":["import { Signal } from '@flare-engine/events';\nimport type { GameLoop } from './game-loop.js';\n\n/**\n * AppLifecycle bridges React Native AppState to the game loop.\n *\n * - Auto-pauses the loop when app goes to background\n * - Auto-resumes when app returns to foreground\n * - Caps dt on resume to prevent huge time jumps\n *\n * In non-RN environments (tests, web), use the manual methods.\n */\nexport class AppLifecycle {\n /** Fires when app enters background. */\n readonly onBackground = new Signal<void>();\n /** Fires when app returns to foreground. */\n readonly onForeground = new Signal<void>();\n /** Fires on memory warning (RN-specific). */\n readonly onMemoryWarning = new Signal<void>();\n\n private loop: GameLoop;\n private wasRunningBeforeBackground = false;\n private _inBackground = false;\n\n constructor(loop: GameLoop) {\n this.loop = loop;\n }\n\n /** Call when app goes to background. */\n background(): void {\n if (this._inBackground) return;\n this._inBackground = true;\n this.wasRunningBeforeBackground = this.loop.isRunning && !this.loop.isPaused;\n if (this.wasRunningBeforeBackground) {\n this.loop.pause();\n }\n this.onBackground.emit();\n }\n\n /** Call when app returns to foreground. */\n foreground(): void {\n this._inBackground = false;\n if (this.wasRunningBeforeBackground) {\n this.loop.resume();\n }\n this.onForeground.emit();\n }\n\n /** Call on memory warning. */\n memoryWarning(): void {\n this.onMemoryWarning.emit();\n }\n}\n","/**\n * Clock tracks frame timing: delta time, elapsed time, fps, timescale.\n * One instance per GameLoop. Updated once per frame.\n */\n\n/** Scheduled callback entry. */\ninterface ScheduleEntry {\n remaining: number;\n callback: () => void;\n interval: number; // 0 = one-shot\n}\n\nexport class Clock {\n /** Unscaled delta time in seconds since last frame. */\n rawDt = 0;\n\n /** Scaled delta time in seconds (rawDt * timescale). */\n dt = 0;\n\n /** Fixed timestep in seconds for physics updates (default 1/60). */\n fixedDt = 1 / 60;\n\n /** Total elapsed time in seconds (scaled). */\n elapsed = 0;\n\n /** Smoothed frames per second. */\n fps = 0;\n\n /** Time scale multiplier. 1 = normal, 0 = paused, 0.5 = slow-mo. */\n timescale = 1;\n\n /** Current frame number (monotonically increasing). */\n frame = 0;\n\n private schedules: ScheduleEntry[] = [];\n private fpsAlpha = 0.9;\n\n /** Called once per frame by the GameLoop with raw unscaled dt. */\n update(rawDt: number): void {\n this.rawDt = rawDt;\n this.dt = rawDt * this.timescale;\n this.elapsed += this.dt;\n this.frame++;\n\n // Exponential moving average FPS\n if (rawDt > 0) {\n const instantFps = 1 / rawDt;\n this.fps =\n this.fps === 0 ? instantFps : this.fps * this.fpsAlpha + instantFps * (1 - this.fpsAlpha);\n }\n\n // Process scheduled callbacks\n this.tickSchedules(this.dt);\n }\n\n /** Schedule a one-shot callback after `delay` seconds (scaled time). */\n schedule(delay: number, callback: () => void): () => void {\n const entry: ScheduleEntry = { remaining: delay, callback, interval: 0 };\n this.schedules.push(entry);\n return () => {\n const idx = this.schedules.indexOf(entry);\n if (idx !== -1) this.schedules.splice(idx, 1);\n };\n }\n\n /** Schedule a repeating callback every `interval` seconds (scaled time). */\n repeat(interval: number, callback: () => void): () => void {\n const entry: ScheduleEntry = { remaining: interval, callback, interval };\n this.schedules.push(entry);\n return () => {\n const idx = this.schedules.indexOf(entry);\n if (idx !== -1) this.schedules.splice(idx, 1);\n };\n }\n\n /** Reset clock to initial state. */\n reset(): void {\n this.rawDt = 0;\n this.dt = 0;\n this.elapsed = 0;\n this.fps = 0;\n this.frame = 0;\n this.timescale = 1;\n this.schedules.length = 0;\n }\n\n private tickSchedules(dt: number): void {\n for (let i = this.schedules.length - 1; i >= 0; i--) {\n const entry = this.schedules[i];\n if (entry === undefined) continue;\n entry.remaining -= dt;\n if (entry.remaining <= 0) {\n entry.callback();\n if (entry.interval > 0) {\n entry.remaining += entry.interval;\n } else {\n const idx = this.schedules.indexOf(entry);\n if (idx !== -1) this.schedules.splice(idx, 1);\n }\n }\n }\n }\n}\n","/**\n * Generator-based coroutines for game logic.\n *\n * - yield number → wait N seconds (scaled time)\n * - yield undefined → wait 1 frame\n * - yield Promise → wait until resolved; a rejection is thrown into the generator\n */\n\n/** A running coroutine handle. Ends exactly one of three ways: completed, cancelled, or failed. */\nexport interface CoroutineHandle {\n /** Whether the coroutine has finished — completed, cancelled, or failed. */\n readonly done: boolean;\n /**\n * Whether `cancel()` or `clear()` ended the coroutine before it completed. Implies `done`;\n * mutually exclusive with `failed`. A cancel issued from inside the running body reports the\n * same way as one issued from outside.\n */\n readonly cancelled: boolean;\n /**\n * Whether a rejected `yield Promise` ended the coroutine without the generator recovering.\n * Implies `done`; mutually exclusive with `cancelled`. The failure is never re-raised as an\n * unhandled rejection; this is the channel.\n */\n readonly failed: boolean;\n /**\n * What the generator threw when `failed` — the rejection reason, unless a `catch`/`finally`\n * block threw something else. `undefined` while running, after a clean finish, or after a\n * cancel. Test `failed` rather than `error`: a bare `reject()` rejects with `undefined`.\n */\n readonly error: unknown;\n /** Cancel the coroutine. Its pending `finally` blocks run; it will not resume. */\n cancel(): void;\n}\n\n/** Yield type for coroutine generators. */\nexport type CoroutineYield = number | undefined | Promise<unknown>;\n\n/** A coroutine generator function. */\nexport type CoroutineGenerator = Generator<CoroutineYield, void, unknown>;\n\ninterface CoroutineState {\n gen: CoroutineGenerator;\n waitTime: number;\n waitingForPromise: boolean;\n /** True while the generator body is executing — `gen.return()` would throw. */\n running: boolean;\n done: boolean;\n cancelled: boolean;\n failed: boolean;\n error: unknown;\n}\n\n/**\n * Marks the coroutine cancelled and closes its generator so pending `finally` blocks run.\n * A generator cannot be closed while its body is executing (`gen.return()` throws\n * \"Generator is already running\"), so a cancel that arrives from inside the body is only\n * marked here and closed by `dispatch()` once the body suspends. Shared by `cancel()` and\n * `clear()` — a scene teardown is a cancel from the coroutine's point of view.\n */\nfunction closeCoroutine(state: CoroutineState): void {\n if (state.done) return;\n state.done = true;\n state.cancelled = true;\n if (!state.running) state.gen.return();\n}\n\n/**\n * CoroutineManager runs generator-based coroutines.\n * Call update(dt) each frame to advance all active coroutines.\n */\nexport class CoroutineManager {\n private coroutines: CoroutineState[] = [];\n\n /** Start a new coroutine. Returns a handle to check status or cancel. */\n start(gen: CoroutineGenerator): CoroutineHandle {\n const state: CoroutineState = {\n gen,\n waitTime: 0,\n waitingForPromise: false,\n running: false,\n done: false,\n cancelled: false,\n failed: false,\n error: undefined,\n };\n this.coroutines.push(state);\n\n // Advance to first yield immediately\n this.advance(state);\n\n const handle: CoroutineHandle = {\n get done() {\n return state.done;\n },\n get cancelled() {\n return state.cancelled;\n },\n get failed() {\n return state.failed;\n },\n get error() {\n return state.error;\n },\n cancel() {\n closeCoroutine(state);\n },\n };\n return handle;\n }\n\n /** Update all running coroutines. Call once per frame with scaled dt. */\n update(dt: number): void {\n for (let i = this.coroutines.length - 1; i >= 0; i--) {\n const state = this.coroutines[i];\n if (state === undefined) continue;\n if (state.done) {\n this.coroutines.splice(i, 1);\n continue;\n }\n\n if (state.waitingForPromise) continue;\n\n if (state.waitTime > 0) {\n state.waitTime -= dt;\n if (state.waitTime > 0) continue;\n }\n\n this.advance(state);\n\n if (state.done) {\n this.coroutines.splice(i, 1);\n }\n }\n }\n\n /** Cancel all running coroutines. Each one's pending `finally` blocks run. */\n clear(): void {\n // Pop rather than iterate: a finally block may start() another coroutine, which must close too\n let state = this.coroutines.pop();\n while (state !== undefined) {\n closeCoroutine(state);\n state = this.coroutines.pop();\n }\n }\n\n /** Number of active coroutines. */\n get count(): number {\n return this.coroutines.length;\n }\n\n private advance(state: CoroutineState): void {\n state.running = true;\n const result = state.gen.next();\n state.running = false;\n this.dispatch(state, result);\n }\n\n /** Resume the generator by throwing a rejected promise's reason into it. */\n private advanceWithError(state: CoroutineState, err: unknown): void {\n let result: IteratorResult<CoroutineYield, void>;\n state.running = true;\n try {\n result = state.gen.throw(err);\n } catch (thrown) {\n // The generator did not recover: it is closed and its finally blocks have already run\n state.running = false;\n state.done = true;\n state.failed = true;\n state.error = thrown;\n return;\n }\n state.running = false;\n this.dispatch(state, result);\n }\n\n private dispatch(state: CoroutineState, result: IteratorResult<CoroutineYield, void>): void {\n if (state.done) {\n // cancel()/clear() ran inside the body; the generator is suspended now, so close it\n if (!result.done) state.gen.return();\n return;\n }\n if (result.done) {\n state.done = true;\n return;\n }\n\n const value = result.value;\n if (typeof value === 'number') {\n state.waitTime = value;\n } else if (value instanceof Promise) {\n state.waitingForPromise = true;\n value.then(\n () => {\n state.waitingForPromise = false;\n },\n (err: unknown) => {\n // Cancelled while waiting: the generator is already closed\n if (state.done) return;\n state.waitingForPromise = false;\n this.advanceWithError(state, err);\n },\n );\n }\n // undefined → wait 1 frame (will advance next update)\n }\n}\n","import { Signal } from '@flare-engine/events';\nimport { Clock } from './clock.js';\n\n/** Configuration for the game loop. */\nexport interface GameLoopConfig {\n /** Fixed timestep in seconds (default 1/60). */\n fixedDt?: number;\n /** Maximum raw dt cap in seconds to prevent spiral of death (default 0.25). */\n maxDt?: number;\n}\n\n/**\n * GameLoop drives the update cycle using fixed + variable timestep.\n *\n * Fixed updates run at a constant rate (accumulator pattern).\n * Variable updates run once per frame with the actual dt.\n */\nexport class GameLoop {\n readonly clock = new Clock();\n\n /** Fixed-timestep update (physics, deterministic logic). */\n readonly onFixedUpdate = new Signal<number>();\n /** Variable-timestep update (movement, AI, game logic). */\n readonly onUpdate = new Signal<number>();\n /** Runs after onUpdate (camera follow, post-processing logic). */\n readonly onLateUpdate = new Signal<number>();\n /** Runs before rendering. */\n readonly onPreRender = new Signal<void>();\n /** Runs after rendering. */\n readonly onPostRender = new Signal<void>();\n\n private running = false;\n private paused = false;\n private accumulator = 0;\n private maxDt: number;\n private rafId = 0;\n private lastTime = 0;\n private _hasFixedDt = false;\n\n /** External tick function — set this for testing or custom scheduling. */\n tick: ((callback: (time: number) => void) => number) | undefined;\n /** External cancel function — paired with tick. */\n cancelTick: ((id: number) => void) | undefined;\n\n constructor(config?: GameLoopConfig) {\n this.maxDt = config?.maxDt ?? 0.25;\n if (config?.fixedDt !== undefined) {\n if (config.fixedDt <= 0) throw new Error('GameLoop: fixedDt must be > 0');\n this.clock.fixedDt = config.fixedDt;\n this._hasFixedDt = true;\n }\n }\n\n /** Start the game loop. */\n start(): void {\n if (this.running) return;\n this.running = true;\n this.paused = false;\n this.lastTime = 0;\n this.accumulator = 0;\n this.scheduleFrame();\n }\n\n /** Stop the game loop entirely and reset. */\n stop(): void {\n this.running = false;\n this.paused = false;\n if (this.rafId !== 0) {\n const cancel = this.cancelTick ?? cancelAnimationFrame;\n cancel(this.rafId);\n this.rafId = 0;\n }\n }\n\n /** Pause — signals stop firing but loop stays alive. */\n pause(): void {\n if (!this.running || this.paused) return;\n this.paused = true;\n }\n\n /** Resume from pause. */\n resume(): void {\n if (!this.running || !this.paused) return;\n this.paused = false;\n this.lastTime = 0; // Reset so next frame doesn't have a huge dt\n }\n\n /** Whether the loop is currently running (started and not stopped). */\n get isRunning(): boolean {\n return this.running;\n }\n\n /** Whether the loop is paused. */\n get isPaused(): boolean {\n return this.paused;\n }\n\n /**\n * Post-step residual fraction for physics interpolation.\n *\n * After fixed updates drain the accumulator, `alpha` is the fraction of a\n * fixed step that has elapsed since the last fixed tick — always in [0, 1).\n * Read in `onPreRender` to lerp between the previous and current physics\n * state for smooth visuals at any display refresh rate.\n *\n * Returns 0 when no fixed step was configured (i.e. `fixedDt` was not\n * passed to the constructor).\n */\n get alpha(): number {\n return this._hasFixedDt ? this.accumulator / this.clock.fixedDt : 0;\n }\n\n /** Process a single frame. Exposed for testing. */\n step(rawDt: number): void {\n if (this.paused) return;\n\n // Cap the dt to avoid spiral of death\n const capped = Math.min(rawDt, this.maxDt);\n this.clock.update(capped);\n\n const dt = this.clock.dt;\n const fixedDt = this.clock.fixedDt;\n if (fixedDt <= 0) throw new Error('GameLoop: fixedDt must be > 0');\n\n // Fixed update accumulator\n this.accumulator += dt;\n while (this.accumulator >= fixedDt) {\n this.onFixedUpdate.emit(fixedDt);\n this.accumulator -= fixedDt;\n }\n\n // Variable update\n this.onUpdate.emit(dt);\n this.onLateUpdate.emit(dt);\n\n // Render\n this.onPreRender.emit();\n this.onPostRender.emit();\n }\n\n private scheduleFrame(): void {\n const request = this.tick ?? requestAnimationFrame;\n this.rafId = request((time: number) => {\n if (!this.running) return;\n\n if (this.lastTime === 0) {\n this.lastTime = time;\n this.scheduleFrame();\n return;\n }\n\n const rawDt = (time - this.lastTime) / 1000;\n this.lastTime = time;\n\n this.step(rawDt);\n this.scheduleFrame();\n });\n }\n}\n","declare const __DEV__: boolean | undefined;\n\n/**\n * Dev-flag access for `release()`, which runs once per released object.\n *\n * JSC has no inline cache for an unresolvable global identifier, so reading the\n * bare `__DEV__` identifier behind a `typeof` guard costs ~270 ns *per\n * evaluation* wherever the global is undeclared. React Native always defines it;\n * web/CanvasKit and any Node or Bun consumer does not. A property miss on\n * `globalThis` is inline-cached at ~0.46 ns and stays togglable at runtime\n * exactly as before. Measured B28 (on JSC — V8 was never measured), PERF-10.\n *\n * Phrased without the literal old expression so `tests/pool-dist.test.ts` can\n * count its occurrences in the built artifact: exactly one must survive, the\n * constructor's.\n *\n * The constructor below deliberately keeps the identifier form: it runs once\n * per pool, where ~270 ns is free, and it is the site a bundler can\n * constant-fold for dead-code elimination.\n */\nconst G = globalThis as { __DEV__?: boolean };\n\n/** Options for Pool construction. */\nexport interface PoolOptions {\n /**\n * Maximum number of simultaneously live (acquired) objects.\n * Enforced ONLY by `tryAcquire()` — `acquire()` is uncapped.\n */\n capacity?: number;\n}\n\n/**\n * Generic object pool for zero-alloc gameplay.\n *\n * - acquire() returns a recycled or newly created object (uncapped)\n * - tryAcquire() returns null when the live count is at capacity\n * - release(obj) returns it to the pool\n * - prewarm(count) pre-allocates objects\n */\nexport class Pool<T> {\n private items: T[] = [];\n private factory: () => T;\n private resetFn: ((item: T) => void) | undefined;\n private _capacity: number | undefined;\n private _live = 0;\n private _created = 0;\n private _liveSet: Set<T> | undefined;\n\n /**\n * @param factory Function to create a new instance.\n * @param reset Optional function to reset an object before reuse.\n * @param options Optional pool configuration (capacity cap).\n */\n constructor(factory: () => T, reset?: (item: T) => void, options?: PoolOptions) {\n this.factory = factory;\n this.resetFn = reset;\n this._capacity = options?.capacity;\n if (typeof __DEV__ !== 'undefined' && __DEV__) {\n this._liveSet = new Set();\n }\n }\n\n /** Get an object from the pool (or create a new one). Never throws; may exceed capacity. */\n acquire(): T {\n this._live++;\n let item: T;\n if (this.items.length > 0) {\n item = this.items.pop()!;\n } else {\n this._created++;\n item = this.factory();\n }\n this._liveSet?.delete(item);\n return item;\n }\n\n /**\n * Get an object from the pool only if the live count is below capacity.\n * Returns null when at cap — the caller must handle null (no allocation occurs).\n * When no capacity was configured, behaves identically to acquire().\n */\n tryAcquire(): T | null {\n if (this._capacity !== undefined && this._live >= this._capacity) return null;\n this._live++;\n let item: T;\n if (this.items.length > 0) {\n item = this.items.pop()!;\n } else {\n this._created++;\n item = this.factory();\n }\n this._liveSet?.delete(item);\n return item;\n }\n\n /** Return an object to the pool. Calls reset if configured. */\n release(item: T): void {\n if (G.__DEV__) {\n if (!this._liveSet) this._liveSet = new Set();\n if (this._liveSet.has(item)) throw new Error('[Pool] double-release detected');\n this._liveSet.add(item);\n }\n this._live--;\n if (this.resetFn) this.resetFn(item);\n this.items.push(item);\n }\n\n /** Pre-allocate objects into the pool. Does not count toward live. */\n prewarm(count: number): void {\n for (let i = 0; i < count; i++) {\n this.items.push(this.factory());\n }\n }\n\n /** Number of available objects currently in the pool (not live). */\n get available(): number {\n return this.items.length;\n }\n\n /** Number of currently live (acquired, not yet released) objects. */\n get live(): number {\n return this._live;\n }\n\n /** Cumulative number of factory calls made by acquire()/tryAcquire().\n * prewarm() is deliberately excluded: this counter exists to detect\n * steady-state allocation, so compare it before and after a frame. */\n get created(): number {\n return this._created;\n }\n\n /** Clear all pooled objects. Does not affect live count. */\n clear(): void {\n this.items.length = 0;\n this._liveSet?.clear();\n }\n}\n","import { Signal } from '@flare-engine/events';\nimport type { Rect, Vec2 } from '@flare-engine/math';\n\n/** Scale mode for mapping design resolution to device screen. */\nexport type ScaleMode = 'fit' | 'fill' | 'stretch';\n\n/** Screen configuration. */\nexport interface ScreenConfig {\n /** Design resolution width in logical pixels. */\n designWidth: number;\n /** Design resolution height in logical pixels. */\n designHeight: number;\n /** How to fit design resolution to device (default: 'fit'). */\n scaleMode?: ScaleMode;\n}\n\n/**\n * ScreenManager maps a fixed design resolution to the actual device screen.\n *\n * - FIT: letterbox (scale to fit, black bars)\n * - FILL: crop (scale to fill, content cropped)\n * - STRETCH: distort (stretch to fill, aspect ratio distorted)\n */\nexport class ScreenManager {\n /** Design resolution width. */\n readonly designWidth: number;\n /** Design resolution height. */\n readonly designHeight: number;\n /** Current scale mode. */\n scaleMode: ScaleMode;\n\n /** Device pixel ratio. */\n pixelRatio = 1;\n\n /** Safe area insets (top, right, bottom, left) in device pixels. */\n safeArea: Rect = { x: 0, y: 0, width: 0, height: 0 };\n\n /** Fires when screen dimensions change. */\n readonly onResize = new Signal<void>();\n\n /** Computed scale factor X (design → screen). */\n scaleX = 1;\n /** Computed scale factor Y (design → screen). */\n scaleY = 1;\n /** Offset X in screen pixels (for letterboxing). */\n offsetX = 0;\n /** Offset Y in screen pixels (for letterboxing). */\n offsetY = 0;\n\n private screenWidth = 0;\n private screenHeight = 0;\n\n constructor(config: ScreenConfig) {\n this.designWidth = config.designWidth;\n this.designHeight = config.designHeight;\n this.scaleMode = config.scaleMode ?? 'fit';\n }\n\n private safeInsetTop = 0;\n private safeInsetRight = 0;\n private safeInsetBottom = 0;\n private safeInsetLeft = 0;\n\n /** Update with actual device screen dimensions. Call on mount and resize. */\n resize(screenWidth: number, screenHeight: number, pixelRatio?: number): void {\n this.screenWidth = screenWidth;\n this.screenHeight = screenHeight;\n if (pixelRatio !== undefined) this.pixelRatio = pixelRatio;\n this.recalculate();\n this.recalculateSafeArea();\n this.onResize.emit();\n }\n\n /**\n * Set safe-area insets in screen pixels. Call this from the RN host with values from\n * `react-native-safe-area-context`. Populates `safeArea` as the usable region.\n */\n setSafeAreaInsets(top: number, right: number, bottom: number, left: number): void {\n this.safeInsetTop = top;\n this.safeInsetRight = right;\n this.safeInsetBottom = bottom;\n this.safeInsetLeft = left;\n this.recalculateSafeArea();\n this.onResize.emit();\n }\n\n private recalculateSafeArea(): void {\n this.safeArea.x = this.safeInsetLeft;\n this.safeArea.y = this.safeInsetTop;\n this.safeArea.width = Math.max(0, this.screenWidth - this.safeInsetLeft - this.safeInsetRight);\n this.safeArea.height = Math.max(\n 0,\n this.screenHeight - this.safeInsetTop - this.safeInsetBottom,\n );\n }\n\n /** Convert design-space point to screen-space. */\n designToScreen(point: Vec2): Vec2 {\n return {\n x: point.x * this.scaleX + this.offsetX,\n y: point.y * this.scaleY + this.offsetY,\n };\n }\n\n /** Convert screen-space point to design-space. */\n screenToDesign(point: Vec2): Vec2 {\n return {\n x: (point.x - this.offsetX) / this.scaleX,\n y: (point.y - this.offsetY) / this.scaleY,\n };\n }\n\n /** Viewport rect in design coordinates (visible area). */\n get viewport(): Rect {\n if (this.scaleMode === 'fill') {\n // In fill mode, the visible area is smaller than design\n const visibleW = this.screenWidth / this.scaleX;\n const visibleH = this.screenHeight / this.scaleY;\n return {\n x: (this.designWidth - visibleW) / 2,\n y: (this.designHeight - visibleH) / 2,\n width: visibleW,\n height: visibleH,\n };\n }\n return { x: 0, y: 0, width: this.designWidth, height: this.designHeight };\n }\n\n private recalculate(): void {\n const ratioX = this.screenWidth / this.designWidth;\n const ratioY = this.screenHeight / this.designHeight;\n\n switch (this.scaleMode) {\n case 'fit': {\n const scale = Math.min(ratioX, ratioY);\n this.scaleX = scale;\n this.scaleY = scale;\n this.offsetX = (this.screenWidth - this.designWidth * scale) / 2;\n this.offsetY = (this.screenHeight - this.designHeight * scale) / 2;\n break;\n }\n case 'fill': {\n const scale = Math.max(ratioX, ratioY);\n this.scaleX = scale;\n this.scaleY = scale;\n this.offsetX = (this.screenWidth - this.designWidth * scale) / 2;\n this.offsetY = (this.screenHeight - this.designHeight * scale) / 2;\n break;\n }\n case 'stretch': {\n this.scaleX = ratioX;\n this.scaleY = ratioY;\n this.offsetX = 0;\n this.offsetY = 0;\n break;\n }\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;AAYA,IAAa,eAAb,MAA0B;;CAExB,eAAwB,IAAIA,qBAAAA,OAAa;;CAEzC,eAAwB,IAAIA,qBAAAA,OAAa;;CAEzC,kBAA2B,IAAIA,qBAAAA,OAAa;CAE5C;CACA,6BAAqC;CACrC,gBAAwB;CAExB,YAAY,MAAgB;EAC1B,KAAK,OAAO;CACd;;CAGA,aAAmB;EACjB,IAAI,KAAK,eAAe;EACxB,KAAK,gBAAgB;EACrB,KAAK,6BAA6B,KAAK,KAAK,aAAa,CAAC,KAAK,KAAK;EACpE,IAAI,KAAK,4BACP,KAAK,KAAK,MAAM;EAElB,KAAK,aAAa,KAAK;CACzB;;CAGA,aAAmB;EACjB,KAAK,gBAAgB;EACrB,IAAI,KAAK,4BACP,KAAK,KAAK,OAAO;EAEnB,KAAK,aAAa,KAAK;CACzB;;CAGA,gBAAsB;EACpB,KAAK,gBAAgB,KAAK;CAC5B;AACF;;;ACxCA,IAAa,QAAb,MAAmB;;CAEjB,QAAQ;;CAGR,KAAK;;CAGL,UAAU,IAAI;;CAGd,UAAU;;CAGV,MA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/D,KAAK,WAAW,KAAK,eAAe,KAAK,eAAe,SAAS;IACjE;GACF;GACA,KAAK,QAAQ;IACX,MAAM,QAAQ,KAAK,IAAI,QAAQ,MAAM;IACrC,KAAK,SAAS;IACd,KAAK,SAAS;IACd,KAAK,WAAW,KAAK,cAAc,KAAK,cAAc,SAAS;IAC/D,KAAK,WAAW,KAAK,eAAe,KAAK,eAAe,SAAS;IACjE;GACF;GACA,KAAK;IACH,KAAK,SAAS;IACd,KAAK,SAAS;IACd,KAAK,UAAU;IACf,KAAK,UAAU;IACf;EAEJ;CACF;AACF"}
package/dist/index.mjs CHANGED
@@ -127,6 +127,19 @@ var Clock = class {
127
127
  //#endregion
128
128
  //#region src/coroutine.ts
129
129
  /**
130
+ * Marks the coroutine cancelled and closes its generator so pending `finally` blocks run.
131
+ * A generator cannot be closed while its body is executing (`gen.return()` throws
132
+ * "Generator is already running"), so a cancel that arrives from inside the body is only
133
+ * marked here and closed by `dispatch()` once the body suspends. Shared by `cancel()` and
134
+ * `clear()` — a scene teardown is a cancel from the coroutine's point of view.
135
+ */
136
+ function closeCoroutine(state) {
137
+ if (state.done) return;
138
+ state.done = true;
139
+ state.cancelled = true;
140
+ if (!state.running) state.gen.return();
141
+ }
142
+ /**
130
143
  * CoroutineManager runs generator-based coroutines.
131
144
  * Call update(dt) each frame to advance all active coroutines.
132
145
  */
@@ -138,7 +151,11 @@ var CoroutineManager = class {
138
151
  gen,
139
152
  waitTime: 0,
140
153
  waitingForPromise: false,
141
- done: false
154
+ running: false,
155
+ done: false,
156
+ cancelled: false,
157
+ failed: false,
158
+ error: void 0
142
159
  };
143
160
  this.coroutines.push(state);
144
161
  this.advance(state);
@@ -146,8 +163,17 @@ var CoroutineManager = class {
146
163
  get done() {
147
164
  return state.done;
148
165
  },
166
+ get cancelled() {
167
+ return state.cancelled;
168
+ },
169
+ get failed() {
170
+ return state.failed;
171
+ },
172
+ get error() {
173
+ return state.error;
174
+ },
149
175
  cancel() {
150
- state.done = true;
176
+ closeCoroutine(state);
151
177
  }
152
178
  };
153
179
  }
@@ -169,17 +195,45 @@ var CoroutineManager = class {
169
195
  if (state.done) this.coroutines.splice(i, 1);
170
196
  }
171
197
  }
172
- /** Cancel all running coroutines. */
198
+ /** Cancel all running coroutines. Each one's pending `finally` blocks run. */
173
199
  clear() {
174
- for (const state of this.coroutines) state.done = true;
175
- this.coroutines.length = 0;
200
+ let state = this.coroutines.pop();
201
+ while (state !== void 0) {
202
+ closeCoroutine(state);
203
+ state = this.coroutines.pop();
204
+ }
176
205
  }
177
206
  /** Number of active coroutines. */
178
207
  get count() {
179
208
  return this.coroutines.length;
180
209
  }
181
210
  advance(state) {
211
+ state.running = true;
182
212
  const result = state.gen.next();
213
+ state.running = false;
214
+ this.dispatch(state, result);
215
+ }
216
+ /** Resume the generator by throwing a rejected promise's reason into it. */
217
+ advanceWithError(state, err) {
218
+ let result;
219
+ state.running = true;
220
+ try {
221
+ result = state.gen.throw(err);
222
+ } catch (thrown) {
223
+ state.running = false;
224
+ state.done = true;
225
+ state.failed = true;
226
+ state.error = thrown;
227
+ return;
228
+ }
229
+ state.running = false;
230
+ this.dispatch(state, result);
231
+ }
232
+ dispatch(state, result) {
233
+ if (state.done) {
234
+ if (!result.done) state.gen.return();
235
+ return;
236
+ }
183
237
  if (result.done) {
184
238
  state.done = true;
185
239
  return;
@@ -190,8 +244,10 @@ var CoroutineManager = class {
190
244
  state.waitingForPromise = true;
191
245
  value.then(() => {
192
246
  state.waitingForPromise = false;
193
- }, () => {
194
- state.done = true;
247
+ }, (err) => {
248
+ if (state.done) return;
249
+ state.waitingForPromise = false;
250
+ this.advanceWithError(state, err);
195
251
  });
196
252
  }
197
253
  }
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":[],"sources":["../src/app-lifecycle.ts","../src/clock.ts","../src/coroutine.ts","../src/game-loop.ts","../src/pool.ts","../src/screen.ts"],"sourcesContent":["import { Signal } from '@flare-engine/events';\nimport type { GameLoop } from './game-loop.js';\n\n/**\n * AppLifecycle bridges React Native AppState to the game loop.\n *\n * - Auto-pauses the loop when app goes to background\n * - Auto-resumes when app returns to foreground\n * - Caps dt on resume to prevent huge time jumps\n *\n * In non-RN environments (tests, web), use the manual methods.\n */\nexport class AppLifecycle {\n /** Fires when app enters background. */\n readonly onBackground = new Signal<void>();\n /** Fires when app returns to foreground. */\n readonly onForeground = new Signal<void>();\n /** Fires on memory warning (RN-specific). */\n readonly onMemoryWarning = new Signal<void>();\n\n private loop: GameLoop;\n private wasRunningBeforeBackground = false;\n private _inBackground = false;\n\n constructor(loop: GameLoop) {\n this.loop = loop;\n }\n\n /** Call when app goes to background. */\n background(): void {\n if (this._inBackground) return;\n this._inBackground = true;\n this.wasRunningBeforeBackground = this.loop.isRunning && !this.loop.isPaused;\n if (this.wasRunningBeforeBackground) {\n this.loop.pause();\n }\n this.onBackground.emit();\n }\n\n /** Call when app returns to foreground. */\n foreground(): void {\n this._inBackground = false;\n if (this.wasRunningBeforeBackground) {\n this.loop.resume();\n }\n this.onForeground.emit();\n }\n\n /** Call on memory warning. */\n memoryWarning(): void {\n this.onMemoryWarning.emit();\n }\n}\n","/**\n * Clock tracks frame timing: delta time, elapsed time, fps, timescale.\n * One instance per GameLoop. Updated once per frame.\n */\n\n/** Scheduled callback entry. */\ninterface ScheduleEntry {\n remaining: number;\n callback: () => void;\n interval: number; // 0 = one-shot\n}\n\nexport class Clock {\n /** Unscaled delta time in seconds since last frame. */\n rawDt = 0;\n\n /** Scaled delta time in seconds (rawDt * timescale). */\n dt = 0;\n\n /** Fixed timestep in seconds for physics updates (default 1/60). */\n fixedDt = 1 / 60;\n\n /** Total elapsed time in seconds (scaled). */\n elapsed = 0;\n\n /** Smoothed frames per second. */\n fps = 0;\n\n /** Time scale multiplier. 1 = normal, 0 = paused, 0.5 = slow-mo. */\n timescale = 1;\n\n /** Current frame number (monotonically increasing). */\n frame = 0;\n\n private schedules: ScheduleEntry[] = [];\n private fpsAlpha = 0.9;\n\n /** Called once per frame by the GameLoop with raw unscaled dt. */\n update(rawDt: number): void {\n this.rawDt = rawDt;\n this.dt = rawDt * this.timescale;\n this.elapsed += this.dt;\n this.frame++;\n\n // Exponential moving average FPS\n if (rawDt > 0) {\n const instantFps = 1 / rawDt;\n this.fps =\n this.fps === 0 ? instantFps : this.fps * this.fpsAlpha + instantFps * (1 - this.fpsAlpha);\n }\n\n // Process scheduled callbacks\n this.tickSchedules(this.dt);\n }\n\n /** Schedule a one-shot callback after `delay` seconds (scaled time). */\n schedule(delay: number, callback: () => void): () => void {\n const entry: ScheduleEntry = { remaining: delay, callback, interval: 0 };\n this.schedules.push(entry);\n return () => {\n const idx = this.schedules.indexOf(entry);\n if (idx !== -1) this.schedules.splice(idx, 1);\n };\n }\n\n /** Schedule a repeating callback every `interval` seconds (scaled time). */\n repeat(interval: number, callback: () => void): () => void {\n const entry: ScheduleEntry = { remaining: interval, callback, interval };\n this.schedules.push(entry);\n return () => {\n const idx = this.schedules.indexOf(entry);\n if (idx !== -1) this.schedules.splice(idx, 1);\n };\n }\n\n /** Reset clock to initial state. */\n reset(): void {\n this.rawDt = 0;\n this.dt = 0;\n this.elapsed = 0;\n this.fps = 0;\n this.frame = 0;\n this.timescale = 1;\n this.schedules.length = 0;\n }\n\n private tickSchedules(dt: number): void {\n for (let i = this.schedules.length - 1; i >= 0; i--) {\n const entry = this.schedules[i];\n if (entry === undefined) continue;\n entry.remaining -= dt;\n if (entry.remaining <= 0) {\n entry.callback();\n if (entry.interval > 0) {\n entry.remaining += entry.interval;\n } else {\n const idx = this.schedules.indexOf(entry);\n if (idx !== -1) this.schedules.splice(idx, 1);\n }\n }\n }\n }\n}\n","/**\n * Generator-based coroutines for game logic.\n *\n * - yield number → wait N seconds (scaled time)\n * - yield undefined → wait 1 frame\n * - yield Promise → wait until resolved\n */\n\n/** A running coroutine handle. */\nexport interface CoroutineHandle {\n /** Whether the coroutine has completed or been cancelled. */\n readonly done: boolean;\n /** Cancel the coroutine. It will not resume. */\n cancel(): void;\n}\n\n/** Yield type for coroutine generators. */\nexport type CoroutineYield = number | undefined | Promise<unknown>;\n\n/** A coroutine generator function. */\nexport type CoroutineGenerator = Generator<CoroutineYield, void, unknown>;\n\ninterface CoroutineState {\n gen: CoroutineGenerator;\n waitTime: number;\n waitingForPromise: boolean;\n done: boolean;\n}\n\n/**\n * CoroutineManager runs generator-based coroutines.\n * Call update(dt) each frame to advance all active coroutines.\n */\nexport class CoroutineManager {\n private coroutines: CoroutineState[] = [];\n\n /** Start a new coroutine. Returns a handle to check status or cancel. */\n start(gen: CoroutineGenerator): CoroutineHandle {\n const state: CoroutineState = {\n gen,\n waitTime: 0,\n waitingForPromise: false,\n done: false,\n };\n this.coroutines.push(state);\n\n // Advance to first yield immediately\n this.advance(state);\n\n const handle: CoroutineHandle = {\n get done() {\n return state.done;\n },\n cancel() {\n state.done = true;\n },\n };\n return handle;\n }\n\n /** Update all running coroutines. Call once per frame with scaled dt. */\n update(dt: number): void {\n for (let i = this.coroutines.length - 1; i >= 0; i--) {\n const state = this.coroutines[i];\n if (state === undefined) continue;\n if (state.done) {\n this.coroutines.splice(i, 1);\n continue;\n }\n\n if (state.waitingForPromise) continue;\n\n if (state.waitTime > 0) {\n state.waitTime -= dt;\n if (state.waitTime > 0) continue;\n }\n\n this.advance(state);\n\n if (state.done) {\n this.coroutines.splice(i, 1);\n }\n }\n }\n\n /** Cancel all running coroutines. */\n clear(): void {\n for (const state of this.coroutines) {\n state.done = true;\n }\n this.coroutines.length = 0;\n }\n\n /** Number of active coroutines. */\n get count(): number {\n return this.coroutines.length;\n }\n\n private advance(state: CoroutineState): void {\n const result = state.gen.next();\n if (result.done) {\n state.done = true;\n return;\n }\n\n const value = result.value;\n if (typeof value === 'number') {\n state.waitTime = value;\n } else if (value instanceof Promise) {\n state.waitingForPromise = true;\n value.then(\n () => {\n state.waitingForPromise = false;\n },\n () => {\n // On rejection, stop the coroutine\n state.done = true;\n },\n );\n }\n // undefined → wait 1 frame (will advance next update)\n }\n}\n","import { Signal } from '@flare-engine/events';\nimport { Clock } from './clock.js';\n\n/** Configuration for the game loop. */\nexport interface GameLoopConfig {\n /** Fixed timestep in seconds (default 1/60). */\n fixedDt?: number;\n /** Maximum raw dt cap in seconds to prevent spiral of death (default 0.25). */\n maxDt?: number;\n}\n\n/**\n * GameLoop drives the update cycle using fixed + variable timestep.\n *\n * Fixed updates run at a constant rate (accumulator pattern).\n * Variable updates run once per frame with the actual dt.\n */\nexport class GameLoop {\n readonly clock = new Clock();\n\n /** Fixed-timestep update (physics, deterministic logic). */\n readonly onFixedUpdate = new Signal<number>();\n /** Variable-timestep update (movement, AI, game logic). */\n readonly onUpdate = new Signal<number>();\n /** Runs after onUpdate (camera follow, post-processing logic). */\n readonly onLateUpdate = new Signal<number>();\n /** Runs before rendering. */\n readonly onPreRender = new Signal<void>();\n /** Runs after rendering. */\n readonly onPostRender = new Signal<void>();\n\n private running = false;\n private paused = false;\n private accumulator = 0;\n private maxDt: number;\n private rafId = 0;\n private lastTime = 0;\n private _hasFixedDt = false;\n\n /** External tick function — set this for testing or custom scheduling. */\n tick: ((callback: (time: number) => void) => number) | undefined;\n /** External cancel function — paired with tick. */\n cancelTick: ((id: number) => void) | undefined;\n\n constructor(config?: GameLoopConfig) {\n this.maxDt = config?.maxDt ?? 0.25;\n if (config?.fixedDt !== undefined) {\n if (config.fixedDt <= 0) throw new Error('GameLoop: fixedDt must be > 0');\n this.clock.fixedDt = config.fixedDt;\n this._hasFixedDt = true;\n }\n }\n\n /** Start the game loop. */\n start(): void {\n if (this.running) return;\n this.running = true;\n this.paused = false;\n this.lastTime = 0;\n this.accumulator = 0;\n this.scheduleFrame();\n }\n\n /** Stop the game loop entirely and reset. */\n stop(): void {\n this.running = false;\n this.paused = false;\n if (this.rafId !== 0) {\n const cancel = this.cancelTick ?? cancelAnimationFrame;\n cancel(this.rafId);\n this.rafId = 0;\n }\n }\n\n /** Pause — signals stop firing but loop stays alive. */\n pause(): void {\n if (!this.running || this.paused) return;\n this.paused = true;\n }\n\n /** Resume from pause. */\n resume(): void {\n if (!this.running || !this.paused) return;\n this.paused = false;\n this.lastTime = 0; // Reset so next frame doesn't have a huge dt\n }\n\n /** Whether the loop is currently running (started and not stopped). */\n get isRunning(): boolean {\n return this.running;\n }\n\n /** Whether the loop is paused. */\n get isPaused(): boolean {\n return this.paused;\n }\n\n /**\n * Post-step residual fraction for physics interpolation.\n *\n * After fixed updates drain the accumulator, `alpha` is the fraction of a\n * fixed step that has elapsed since the last fixed tick — always in [0, 1).\n * Read in `onPreRender` to lerp between the previous and current physics\n * state for smooth visuals at any display refresh rate.\n *\n * Returns 0 when no fixed step was configured (i.e. `fixedDt` was not\n * passed to the constructor).\n */\n get alpha(): number {\n return this._hasFixedDt ? this.accumulator / this.clock.fixedDt : 0;\n }\n\n /** Process a single frame. Exposed for testing. */\n step(rawDt: number): void {\n if (this.paused) return;\n\n // Cap the dt to avoid spiral of death\n const capped = Math.min(rawDt, this.maxDt);\n this.clock.update(capped);\n\n const dt = this.clock.dt;\n const fixedDt = this.clock.fixedDt;\n if (fixedDt <= 0) throw new Error('GameLoop: fixedDt must be > 0');\n\n // Fixed update accumulator\n this.accumulator += dt;\n while (this.accumulator >= fixedDt) {\n this.onFixedUpdate.emit(fixedDt);\n this.accumulator -= fixedDt;\n }\n\n // Variable update\n this.onUpdate.emit(dt);\n this.onLateUpdate.emit(dt);\n\n // Render\n this.onPreRender.emit();\n this.onPostRender.emit();\n }\n\n private scheduleFrame(): void {\n const request = this.tick ?? requestAnimationFrame;\n this.rafId = request((time: number) => {\n if (!this.running) return;\n\n if (this.lastTime === 0) {\n this.lastTime = time;\n this.scheduleFrame();\n return;\n }\n\n const rawDt = (time - this.lastTime) / 1000;\n this.lastTime = time;\n\n this.step(rawDt);\n this.scheduleFrame();\n });\n }\n}\n","declare const __DEV__: boolean | undefined;\n\n/**\n * Dev-flag access for `release()`, which runs once per released object.\n *\n * JSC has no inline cache for an unresolvable global identifier, so reading the\n * bare `__DEV__` identifier behind a `typeof` guard costs ~270 ns *per\n * evaluation* wherever the global is undeclared. React Native always defines it;\n * web/CanvasKit and any Node or Bun consumer does not. A property miss on\n * `globalThis` is inline-cached at ~0.46 ns and stays togglable at runtime\n * exactly as before. Measured B28 (on JSC — V8 was never measured), PERF-10.\n *\n * Phrased without the literal old expression so `tests/pool-dist.test.ts` can\n * count its occurrences in the built artifact: exactly one must survive, the\n * constructor's.\n *\n * The constructor below deliberately keeps the identifier form: it runs once\n * per pool, where ~270 ns is free, and it is the site a bundler can\n * constant-fold for dead-code elimination.\n */\nconst G = globalThis as { __DEV__?: boolean };\n\n/** Options for Pool construction. */\nexport interface PoolOptions {\n /**\n * Maximum number of simultaneously live (acquired) objects.\n * Enforced ONLY by `tryAcquire()` — `acquire()` is uncapped.\n */\n capacity?: number;\n}\n\n/**\n * Generic object pool for zero-alloc gameplay.\n *\n * - acquire() returns a recycled or newly created object (uncapped)\n * - tryAcquire() returns null when the live count is at capacity\n * - release(obj) returns it to the pool\n * - prewarm(count) pre-allocates objects\n */\nexport class Pool<T> {\n private items: T[] = [];\n private factory: () => T;\n private resetFn: ((item: T) => void) | undefined;\n private _capacity: number | undefined;\n private _live = 0;\n private _created = 0;\n private _liveSet: Set<T> | undefined;\n\n /**\n * @param factory Function to create a new instance.\n * @param reset Optional function to reset an object before reuse.\n * @param options Optional pool configuration (capacity cap).\n */\n constructor(factory: () => T, reset?: (item: T) => void, options?: PoolOptions) {\n this.factory = factory;\n this.resetFn = reset;\n this._capacity = options?.capacity;\n if (typeof __DEV__ !== 'undefined' && __DEV__) {\n this._liveSet = new Set();\n }\n }\n\n /** Get an object from the pool (or create a new one). Never throws; may exceed capacity. */\n acquire(): T {\n this._live++;\n let item: T;\n if (this.items.length > 0) {\n item = this.items.pop()!;\n } else {\n this._created++;\n item = this.factory();\n }\n this._liveSet?.delete(item);\n return item;\n }\n\n /**\n * Get an object from the pool only if the live count is below capacity.\n * Returns null when at cap — the caller must handle null (no allocation occurs).\n * When no capacity was configured, behaves identically to acquire().\n */\n tryAcquire(): T | null {\n if (this._capacity !== undefined && this._live >= this._capacity) return null;\n this._live++;\n let item: T;\n if (this.items.length > 0) {\n item = this.items.pop()!;\n } else {\n this._created++;\n item = this.factory();\n }\n this._liveSet?.delete(item);\n return item;\n }\n\n /** Return an object to the pool. Calls reset if configured. */\n release(item: T): void {\n if (G.__DEV__) {\n if (!this._liveSet) this._liveSet = new Set();\n if (this._liveSet.has(item)) throw new Error('[Pool] double-release detected');\n this._liveSet.add(item);\n }\n this._live--;\n if (this.resetFn) this.resetFn(item);\n this.items.push(item);\n }\n\n /** Pre-allocate objects into the pool. Does not count toward live. */\n prewarm(count: number): void {\n for (let i = 0; i < count; i++) {\n this.items.push(this.factory());\n }\n }\n\n /** Number of available objects currently in the pool (not live). */\n get available(): number {\n return this.items.length;\n }\n\n /** Number of currently live (acquired, not yet released) objects. */\n get live(): number {\n return this._live;\n }\n\n /** Cumulative number of factory calls made by acquire()/tryAcquire().\n * prewarm() is deliberately excluded: this counter exists to detect\n * steady-state allocation, so compare it before and after a frame. */\n get created(): number {\n return this._created;\n }\n\n /** Clear all pooled objects. Does not affect live count. */\n clear(): void {\n this.items.length = 0;\n this._liveSet?.clear();\n }\n}\n","import { Signal } from '@flare-engine/events';\nimport type { Rect, Vec2 } from '@flare-engine/math';\n\n/** Scale mode for mapping design resolution to device screen. */\nexport type ScaleMode = 'fit' | 'fill' | 'stretch';\n\n/** Screen configuration. */\nexport interface ScreenConfig {\n /** Design resolution width in logical pixels. */\n designWidth: number;\n /** Design resolution height in logical pixels. */\n designHeight: number;\n /** How to fit design resolution to device (default: 'fit'). */\n scaleMode?: ScaleMode;\n}\n\n/**\n * ScreenManager maps a fixed design resolution to the actual device screen.\n *\n * - FIT: letterbox (scale to fit, black bars)\n * - FILL: crop (scale to fill, content cropped)\n * - STRETCH: distort (stretch to fill, aspect ratio distorted)\n */\nexport class ScreenManager {\n /** Design resolution width. */\n readonly designWidth: number;\n /** Design resolution height. */\n readonly designHeight: number;\n /** Current scale mode. */\n scaleMode: ScaleMode;\n\n /** Device pixel ratio. */\n pixelRatio = 1;\n\n /** Safe area insets (top, right, bottom, left) in device pixels. */\n safeArea: Rect = { x: 0, y: 0, width: 0, height: 0 };\n\n /** Fires when screen dimensions change. */\n readonly onResize = new Signal<void>();\n\n /** Computed scale factor X (design → screen). */\n scaleX = 1;\n /** Computed scale factor Y (design → screen). */\n scaleY = 1;\n /** Offset X in screen pixels (for letterboxing). */\n offsetX = 0;\n /** Offset Y in screen pixels (for letterboxing). */\n offsetY = 0;\n\n private screenWidth = 0;\n private screenHeight = 0;\n\n constructor(config: ScreenConfig) {\n this.designWidth = config.designWidth;\n this.designHeight = config.designHeight;\n this.scaleMode = config.scaleMode ?? 'fit';\n }\n\n private safeInsetTop = 0;\n private safeInsetRight = 0;\n private safeInsetBottom = 0;\n private safeInsetLeft = 0;\n\n /** Update with actual device screen dimensions. Call on mount and resize. */\n resize(screenWidth: number, screenHeight: number, pixelRatio?: number): void {\n this.screenWidth = screenWidth;\n this.screenHeight = screenHeight;\n if (pixelRatio !== undefined) this.pixelRatio = pixelRatio;\n this.recalculate();\n this.recalculateSafeArea();\n this.onResize.emit();\n }\n\n /**\n * Set safe-area insets in screen pixels. Call this from the RN host with values from\n * `react-native-safe-area-context`. Populates `safeArea` as the usable region.\n */\n setSafeAreaInsets(top: number, right: number, bottom: number, left: number): void {\n this.safeInsetTop = top;\n this.safeInsetRight = right;\n this.safeInsetBottom = bottom;\n this.safeInsetLeft = left;\n this.recalculateSafeArea();\n this.onResize.emit();\n }\n\n private recalculateSafeArea(): void {\n this.safeArea.x = this.safeInsetLeft;\n this.safeArea.y = this.safeInsetTop;\n this.safeArea.width = Math.max(0, this.screenWidth - this.safeInsetLeft - this.safeInsetRight);\n this.safeArea.height = Math.max(\n 0,\n this.screenHeight - this.safeInsetTop - this.safeInsetBottom,\n );\n }\n\n /** Convert design-space point to screen-space. */\n designToScreen(point: Vec2): Vec2 {\n return {\n x: point.x * this.scaleX + this.offsetX,\n y: point.y * this.scaleY + this.offsetY,\n };\n }\n\n /** Convert screen-space point to design-space. */\n screenToDesign(point: Vec2): Vec2 {\n return {\n x: (point.x - this.offsetX) / this.scaleX,\n y: (point.y - this.offsetY) / this.scaleY,\n };\n }\n\n /** Viewport rect in design coordinates (visible area). */\n get viewport(): Rect {\n if (this.scaleMode === 'fill') {\n // In fill mode, the visible area is smaller than design\n const visibleW = this.screenWidth / this.scaleX;\n const visibleH = this.screenHeight / this.scaleY;\n return {\n x: (this.designWidth - visibleW) / 2,\n y: (this.designHeight - visibleH) / 2,\n width: visibleW,\n height: visibleH,\n };\n }\n return { x: 0, y: 0, width: this.designWidth, height: this.designHeight };\n }\n\n private recalculate(): void {\n const ratioX = this.screenWidth / this.designWidth;\n const ratioY = this.screenHeight / this.designHeight;\n\n switch (this.scaleMode) {\n case 'fit': {\n const scale = Math.min(ratioX, ratioY);\n this.scaleX = scale;\n this.scaleY = scale;\n this.offsetX = (this.screenWidth - this.designWidth * scale) / 2;\n this.offsetY = (this.screenHeight - this.designHeight * scale) / 2;\n break;\n }\n case 'fill': {\n const scale = Math.max(ratioX, ratioY);\n this.scaleX = scale;\n this.scaleY = scale;\n this.offsetX = (this.screenWidth - this.designWidth * scale) / 2;\n this.offsetY = (this.screenHeight - this.designHeight * scale) / 2;\n break;\n }\n case 'stretch': {\n this.scaleX = ratioX;\n this.scaleY = ratioY;\n this.offsetX = 0;\n this.offsetY = 0;\n break;\n }\n }\n }\n}\n"],"mappings":";;;;;;;;;;;AAYA,IAAa,eAAb,MAA0B;;CAExB,eAAwB,IAAI,OAAa;;CAEzC,eAAwB,IAAI,OAAa;;CAEzC,kBAA2B,IAAI,OAAa;CAE5C;CACA,6BAAqC;CACrC,gBAAwB;CAExB,YAAY,MAAgB;EAC1B,KAAK,OAAO;CACd;;CAGA,aAAmB;EACjB,IAAI,KAAK,eAAe;EACxB,KAAK,gBAAgB;EACrB,KAAK,6BAA6B,KAAK,KAAK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AAI,KAAK,WAAW,KAAK;GACnC,IAAI,MAAM,IAAI,KAAK,WAAW,KAAK;EACrC;CACF;;CAGA,IAAI,WAAiB;EACnB,IAAI,KAAK,cAAc,QAAQ;GAE7B,MAAM,WAAW,KAAK,cAAc,KAAK;GACzC,MAAM,WAAW,KAAK,eAAe,KAAK;GAC1C,OAAO;IACL,IAAI,KAAK,cAAc,YAAY;IACnC,IAAI,KAAK,eAAe,YAAY;IACpC,OAAO;IACP,QAAQ;GACV;EACF;EACA,OAAO;GAAE,GAAG;GAAG,GAAG;GAAG,OAAO,KAAK;GAAa,QAAQ,KAAK;EAAa;CAC1E;CAEA,cAA4B;EAC1B,MAAM,SAAS,KAAK,cAAc,KAAK;EACvC,MAAM,SAAS,KAAK,eAAe,KAAK;EAExC,QAAQ,KAAK,WAAb;GACE,KAAK,OAAO;IACV,MAAM,QAAQ,KAAK,IAAI,QAAQ,MAAM;IACrC,KAAK,SAAS;IACd,KAAK,SAAS;IACd,KAAK,WAAW,KAAK,cAAc,KAAK,cAAc,SAAS;IAC/D,KAAK,WAAW,KAAK,eAAe,KAAK,eAAe,SAAS;IACjE;GACF;GACA,KAAK,QAAQ;IACX,MAAM,QAAQ,KAAK,IAAI,QAAQ,MAAM;IACrC,KAAK,SAAS;IACd,KAAK,SAAS;IACd,KAAK,WAAW,KAAK,cAAc,KAAK,cAAc,SAAS;IAC/D,KAAK,WAAW,KAAK,eAAe,KAAK,eAAe,SAAS;IACjE;GACF;GACA,KAAK;IACH,KAAK,SAAS;IACd,KAAK,SAAS;IACd,KAAK,UAAU;IACf,KAAK,UAAU;IACf;EAEJ;CACF;AACF"}
1
+ {"version":3,"file":"index.mjs","names":[],"sources":["../src/app-lifecycle.ts","../src/clock.ts","../src/coroutine.ts","../src/game-loop.ts","../src/pool.ts","../src/screen.ts"],"sourcesContent":["import { Signal } from '@flare-engine/events';\nimport type { GameLoop } from './game-loop.js';\n\n/**\n * AppLifecycle bridges React Native AppState to the game loop.\n *\n * - Auto-pauses the loop when app goes to background\n * - Auto-resumes when app returns to foreground\n * - Caps dt on resume to prevent huge time jumps\n *\n * In non-RN environments (tests, web), use the manual methods.\n */\nexport class AppLifecycle {\n /** Fires when app enters background. */\n readonly onBackground = new Signal<void>();\n /** Fires when app returns to foreground. */\n readonly onForeground = new Signal<void>();\n /** Fires on memory warning (RN-specific). */\n readonly onMemoryWarning = new Signal<void>();\n\n private loop: GameLoop;\n private wasRunningBeforeBackground = false;\n private _inBackground = false;\n\n constructor(loop: GameLoop) {\n this.loop = loop;\n }\n\n /** Call when app goes to background. */\n background(): void {\n if (this._inBackground) return;\n this._inBackground = true;\n this.wasRunningBeforeBackground = this.loop.isRunning && !this.loop.isPaused;\n if (this.wasRunningBeforeBackground) {\n this.loop.pause();\n }\n this.onBackground.emit();\n }\n\n /** Call when app returns to foreground. */\n foreground(): void {\n this._inBackground = false;\n if (this.wasRunningBeforeBackground) {\n this.loop.resume();\n }\n this.onForeground.emit();\n }\n\n /** Call on memory warning. */\n memoryWarning(): void {\n this.onMemoryWarning.emit();\n }\n}\n","/**\n * Clock tracks frame timing: delta time, elapsed time, fps, timescale.\n * One instance per GameLoop. Updated once per frame.\n */\n\n/** Scheduled callback entry. */\ninterface ScheduleEntry {\n remaining: number;\n callback: () => void;\n interval: number; // 0 = one-shot\n}\n\nexport class Clock {\n /** Unscaled delta time in seconds since last frame. */\n rawDt = 0;\n\n /** Scaled delta time in seconds (rawDt * timescale). */\n dt = 0;\n\n /** Fixed timestep in seconds for physics updates (default 1/60). */\n fixedDt = 1 / 60;\n\n /** Total elapsed time in seconds (scaled). */\n elapsed = 0;\n\n /** Smoothed frames per second. */\n fps = 0;\n\n /** Time scale multiplier. 1 = normal, 0 = paused, 0.5 = slow-mo. */\n timescale = 1;\n\n /** Current frame number (monotonically increasing). */\n frame = 0;\n\n private schedules: ScheduleEntry[] = [];\n private fpsAlpha = 0.9;\n\n /** Called once per frame by the GameLoop with raw unscaled dt. */\n update(rawDt: number): void {\n this.rawDt = rawDt;\n this.dt = rawDt * this.timescale;\n this.elapsed += this.dt;\n this.frame++;\n\n // Exponential moving average FPS\n if (rawDt > 0) {\n const instantFps = 1 / rawDt;\n this.fps =\n this.fps === 0 ? instantFps : this.fps * this.fpsAlpha + instantFps * (1 - this.fpsAlpha);\n }\n\n // Process scheduled callbacks\n this.tickSchedules(this.dt);\n }\n\n /** Schedule a one-shot callback after `delay` seconds (scaled time). */\n schedule(delay: number, callback: () => void): () => void {\n const entry: ScheduleEntry = { remaining: delay, callback, interval: 0 };\n this.schedules.push(entry);\n return () => {\n const idx = this.schedules.indexOf(entry);\n if (idx !== -1) this.schedules.splice(idx, 1);\n };\n }\n\n /** Schedule a repeating callback every `interval` seconds (scaled time). */\n repeat(interval: number, callback: () => void): () => void {\n const entry: ScheduleEntry = { remaining: interval, callback, interval };\n this.schedules.push(entry);\n return () => {\n const idx = this.schedules.indexOf(entry);\n if (idx !== -1) this.schedules.splice(idx, 1);\n };\n }\n\n /** Reset clock to initial state. */\n reset(): void {\n this.rawDt = 0;\n this.dt = 0;\n this.elapsed = 0;\n this.fps = 0;\n this.frame = 0;\n this.timescale = 1;\n this.schedules.length = 0;\n }\n\n private tickSchedules(dt: number): void {\n for (let i = this.schedules.length - 1; i >= 0; i--) {\n const entry = this.schedules[i];\n if (entry === undefined) continue;\n entry.remaining -= dt;\n if (entry.remaining <= 0) {\n entry.callback();\n if (entry.interval > 0) {\n entry.remaining += entry.interval;\n } else {\n const idx = this.schedules.indexOf(entry);\n if (idx !== -1) this.schedules.splice(idx, 1);\n }\n }\n }\n }\n}\n","/**\n * Generator-based coroutines for game logic.\n *\n * - yield number → wait N seconds (scaled time)\n * - yield undefined → wait 1 frame\n * - yield Promise → wait until resolved; a rejection is thrown into the generator\n */\n\n/** A running coroutine handle. Ends exactly one of three ways: completed, cancelled, or failed. */\nexport interface CoroutineHandle {\n /** Whether the coroutine has finished — completed, cancelled, or failed. */\n readonly done: boolean;\n /**\n * Whether `cancel()` or `clear()` ended the coroutine before it completed. Implies `done`;\n * mutually exclusive with `failed`. A cancel issued from inside the running body reports the\n * same way as one issued from outside.\n */\n readonly cancelled: boolean;\n /**\n * Whether a rejected `yield Promise` ended the coroutine without the generator recovering.\n * Implies `done`; mutually exclusive with `cancelled`. The failure is never re-raised as an\n * unhandled rejection; this is the channel.\n */\n readonly failed: boolean;\n /**\n * What the generator threw when `failed` — the rejection reason, unless a `catch`/`finally`\n * block threw something else. `undefined` while running, after a clean finish, or after a\n * cancel. Test `failed` rather than `error`: a bare `reject()` rejects with `undefined`.\n */\n readonly error: unknown;\n /** Cancel the coroutine. Its pending `finally` blocks run; it will not resume. */\n cancel(): void;\n}\n\n/** Yield type for coroutine generators. */\nexport type CoroutineYield = number | undefined | Promise<unknown>;\n\n/** A coroutine generator function. */\nexport type CoroutineGenerator = Generator<CoroutineYield, void, unknown>;\n\ninterface CoroutineState {\n gen: CoroutineGenerator;\n waitTime: number;\n waitingForPromise: boolean;\n /** True while the generator body is executing — `gen.return()` would throw. */\n running: boolean;\n done: boolean;\n cancelled: boolean;\n failed: boolean;\n error: unknown;\n}\n\n/**\n * Marks the coroutine cancelled and closes its generator so pending `finally` blocks run.\n * A generator cannot be closed while its body is executing (`gen.return()` throws\n * \"Generator is already running\"), so a cancel that arrives from inside the body is only\n * marked here and closed by `dispatch()` once the body suspends. Shared by `cancel()` and\n * `clear()` — a scene teardown is a cancel from the coroutine's point of view.\n */\nfunction closeCoroutine(state: CoroutineState): void {\n if (state.done) return;\n state.done = true;\n state.cancelled = true;\n if (!state.running) state.gen.return();\n}\n\n/**\n * CoroutineManager runs generator-based coroutines.\n * Call update(dt) each frame to advance all active coroutines.\n */\nexport class CoroutineManager {\n private coroutines: CoroutineState[] = [];\n\n /** Start a new coroutine. Returns a handle to check status or cancel. */\n start(gen: CoroutineGenerator): CoroutineHandle {\n const state: CoroutineState = {\n gen,\n waitTime: 0,\n waitingForPromise: false,\n running: false,\n done: false,\n cancelled: false,\n failed: false,\n error: undefined,\n };\n this.coroutines.push(state);\n\n // Advance to first yield immediately\n this.advance(state);\n\n const handle: CoroutineHandle = {\n get done() {\n return state.done;\n },\n get cancelled() {\n return state.cancelled;\n },\n get failed() {\n return state.failed;\n },\n get error() {\n return state.error;\n },\n cancel() {\n closeCoroutine(state);\n },\n };\n return handle;\n }\n\n /** Update all running coroutines. Call once per frame with scaled dt. */\n update(dt: number): void {\n for (let i = this.coroutines.length - 1; i >= 0; i--) {\n const state = this.coroutines[i];\n if (state === undefined) continue;\n if (state.done) {\n this.coroutines.splice(i, 1);\n continue;\n }\n\n if (state.waitingForPromise) continue;\n\n if (state.waitTime > 0) {\n state.waitTime -= dt;\n if (state.waitTime > 0) continue;\n }\n\n this.advance(state);\n\n if (state.done) {\n this.coroutines.splice(i, 1);\n }\n }\n }\n\n /** Cancel all running coroutines. Each one's pending `finally` blocks run. */\n clear(): void {\n // Pop rather than iterate: a finally block may start() another coroutine, which must close too\n let state = this.coroutines.pop();\n while (state !== undefined) {\n closeCoroutine(state);\n state = this.coroutines.pop();\n }\n }\n\n /** Number of active coroutines. */\n get count(): number {\n return this.coroutines.length;\n }\n\n private advance(state: CoroutineState): void {\n state.running = true;\n const result = state.gen.next();\n state.running = false;\n this.dispatch(state, result);\n }\n\n /** Resume the generator by throwing a rejected promise's reason into it. */\n private advanceWithError(state: CoroutineState, err: unknown): void {\n let result: IteratorResult<CoroutineYield, void>;\n state.running = true;\n try {\n result = state.gen.throw(err);\n } catch (thrown) {\n // The generator did not recover: it is closed and its finally blocks have already run\n state.running = false;\n state.done = true;\n state.failed = true;\n state.error = thrown;\n return;\n }\n state.running = false;\n this.dispatch(state, result);\n }\n\n private dispatch(state: CoroutineState, result: IteratorResult<CoroutineYield, void>): void {\n if (state.done) {\n // cancel()/clear() ran inside the body; the generator is suspended now, so close it\n if (!result.done) state.gen.return();\n return;\n }\n if (result.done) {\n state.done = true;\n return;\n }\n\n const value = result.value;\n if (typeof value === 'number') {\n state.waitTime = value;\n } else if (value instanceof Promise) {\n state.waitingForPromise = true;\n value.then(\n () => {\n state.waitingForPromise = false;\n },\n (err: unknown) => {\n // Cancelled while waiting: the generator is already closed\n if (state.done) return;\n state.waitingForPromise = false;\n this.advanceWithError(state, err);\n },\n );\n }\n // undefined → wait 1 frame (will advance next update)\n }\n}\n","import { Signal } from '@flare-engine/events';\nimport { Clock } from './clock.js';\n\n/** Configuration for the game loop. */\nexport interface GameLoopConfig {\n /** Fixed timestep in seconds (default 1/60). */\n fixedDt?: number;\n /** Maximum raw dt cap in seconds to prevent spiral of death (default 0.25). */\n maxDt?: number;\n}\n\n/**\n * GameLoop drives the update cycle using fixed + variable timestep.\n *\n * Fixed updates run at a constant rate (accumulator pattern).\n * Variable updates run once per frame with the actual dt.\n */\nexport class GameLoop {\n readonly clock = new Clock();\n\n /** Fixed-timestep update (physics, deterministic logic). */\n readonly onFixedUpdate = new Signal<number>();\n /** Variable-timestep update (movement, AI, game logic). */\n readonly onUpdate = new Signal<number>();\n /** Runs after onUpdate (camera follow, post-processing logic). */\n readonly onLateUpdate = new Signal<number>();\n /** Runs before rendering. */\n readonly onPreRender = new Signal<void>();\n /** Runs after rendering. */\n readonly onPostRender = new Signal<void>();\n\n private running = false;\n private paused = false;\n private accumulator = 0;\n private maxDt: number;\n private rafId = 0;\n private lastTime = 0;\n private _hasFixedDt = false;\n\n /** External tick function — set this for testing or custom scheduling. */\n tick: ((callback: (time: number) => void) => number) | undefined;\n /** External cancel function — paired with tick. */\n cancelTick: ((id: number) => void) | undefined;\n\n constructor(config?: GameLoopConfig) {\n this.maxDt = config?.maxDt ?? 0.25;\n if (config?.fixedDt !== undefined) {\n if (config.fixedDt <= 0) throw new Error('GameLoop: fixedDt must be > 0');\n this.clock.fixedDt = config.fixedDt;\n this._hasFixedDt = true;\n }\n }\n\n /** Start the game loop. */\n start(): void {\n if (this.running) return;\n this.running = true;\n this.paused = false;\n this.lastTime = 0;\n this.accumulator = 0;\n this.scheduleFrame();\n }\n\n /** Stop the game loop entirely and reset. */\n stop(): void {\n this.running = false;\n this.paused = false;\n if (this.rafId !== 0) {\n const cancel = this.cancelTick ?? cancelAnimationFrame;\n cancel(this.rafId);\n this.rafId = 0;\n }\n }\n\n /** Pause — signals stop firing but loop stays alive. */\n pause(): void {\n if (!this.running || this.paused) return;\n this.paused = true;\n }\n\n /** Resume from pause. */\n resume(): void {\n if (!this.running || !this.paused) return;\n this.paused = false;\n this.lastTime = 0; // Reset so next frame doesn't have a huge dt\n }\n\n /** Whether the loop is currently running (started and not stopped). */\n get isRunning(): boolean {\n return this.running;\n }\n\n /** Whether the loop is paused. */\n get isPaused(): boolean {\n return this.paused;\n }\n\n /**\n * Post-step residual fraction for physics interpolation.\n *\n * After fixed updates drain the accumulator, `alpha` is the fraction of a\n * fixed step that has elapsed since the last fixed tick — always in [0, 1).\n * Read in `onPreRender` to lerp between the previous and current physics\n * state for smooth visuals at any display refresh rate.\n *\n * Returns 0 when no fixed step was configured (i.e. `fixedDt` was not\n * passed to the constructor).\n */\n get alpha(): number {\n return this._hasFixedDt ? this.accumulator / this.clock.fixedDt : 0;\n }\n\n /** Process a single frame. Exposed for testing. */\n step(rawDt: number): void {\n if (this.paused) return;\n\n // Cap the dt to avoid spiral of death\n const capped = Math.min(rawDt, this.maxDt);\n this.clock.update(capped);\n\n const dt = this.clock.dt;\n const fixedDt = this.clock.fixedDt;\n if (fixedDt <= 0) throw new Error('GameLoop: fixedDt must be > 0');\n\n // Fixed update accumulator\n this.accumulator += dt;\n while (this.accumulator >= fixedDt) {\n this.onFixedUpdate.emit(fixedDt);\n this.accumulator -= fixedDt;\n }\n\n // Variable update\n this.onUpdate.emit(dt);\n this.onLateUpdate.emit(dt);\n\n // Render\n this.onPreRender.emit();\n this.onPostRender.emit();\n }\n\n private scheduleFrame(): void {\n const request = this.tick ?? requestAnimationFrame;\n this.rafId = request((time: number) => {\n if (!this.running) return;\n\n if (this.lastTime === 0) {\n this.lastTime = time;\n this.scheduleFrame();\n return;\n }\n\n const rawDt = (time - this.lastTime) / 1000;\n this.lastTime = time;\n\n this.step(rawDt);\n this.scheduleFrame();\n });\n }\n}\n","declare const __DEV__: boolean | undefined;\n\n/**\n * Dev-flag access for `release()`, which runs once per released object.\n *\n * JSC has no inline cache for an unresolvable global identifier, so reading the\n * bare `__DEV__` identifier behind a `typeof` guard costs ~270 ns *per\n * evaluation* wherever the global is undeclared. React Native always defines it;\n * web/CanvasKit and any Node or Bun consumer does not. A property miss on\n * `globalThis` is inline-cached at ~0.46 ns and stays togglable at runtime\n * exactly as before. Measured B28 (on JSC — V8 was never measured), PERF-10.\n *\n * Phrased without the literal old expression so `tests/pool-dist.test.ts` can\n * count its occurrences in the built artifact: exactly one must survive, the\n * constructor's.\n *\n * The constructor below deliberately keeps the identifier form: it runs once\n * per pool, where ~270 ns is free, and it is the site a bundler can\n * constant-fold for dead-code elimination.\n */\nconst G = globalThis as { __DEV__?: boolean };\n\n/** Options for Pool construction. */\nexport interface PoolOptions {\n /**\n * Maximum number of simultaneously live (acquired) objects.\n * Enforced ONLY by `tryAcquire()` — `acquire()` is uncapped.\n */\n capacity?: number;\n}\n\n/**\n * Generic object pool for zero-alloc gameplay.\n *\n * - acquire() returns a recycled or newly created object (uncapped)\n * - tryAcquire() returns null when the live count is at capacity\n * - release(obj) returns it to the pool\n * - prewarm(count) pre-allocates objects\n */\nexport class Pool<T> {\n private items: T[] = [];\n private factory: () => T;\n private resetFn: ((item: T) => void) | undefined;\n private _capacity: number | undefined;\n private _live = 0;\n private _created = 0;\n private _liveSet: Set<T> | undefined;\n\n /**\n * @param factory Function to create a new instance.\n * @param reset Optional function to reset an object before reuse.\n * @param options Optional pool configuration (capacity cap).\n */\n constructor(factory: () => T, reset?: (item: T) => void, options?: PoolOptions) {\n this.factory = factory;\n this.resetFn = reset;\n this._capacity = options?.capacity;\n if (typeof __DEV__ !== 'undefined' && __DEV__) {\n this._liveSet = new Set();\n }\n }\n\n /** Get an object from the pool (or create a new one). Never throws; may exceed capacity. */\n acquire(): T {\n this._live++;\n let item: T;\n if (this.items.length > 0) {\n item = this.items.pop()!;\n } else {\n this._created++;\n item = this.factory();\n }\n this._liveSet?.delete(item);\n return item;\n }\n\n /**\n * Get an object from the pool only if the live count is below capacity.\n * Returns null when at cap — the caller must handle null (no allocation occurs).\n * When no capacity was configured, behaves identically to acquire().\n */\n tryAcquire(): T | null {\n if (this._capacity !== undefined && this._live >= this._capacity) return null;\n this._live++;\n let item: T;\n if (this.items.length > 0) {\n item = this.items.pop()!;\n } else {\n this._created++;\n item = this.factory();\n }\n this._liveSet?.delete(item);\n return item;\n }\n\n /** Return an object to the pool. Calls reset if configured. */\n release(item: T): void {\n if (G.__DEV__) {\n if (!this._liveSet) this._liveSet = new Set();\n if (this._liveSet.has(item)) throw new Error('[Pool] double-release detected');\n this._liveSet.add(item);\n }\n this._live--;\n if (this.resetFn) this.resetFn(item);\n this.items.push(item);\n }\n\n /** Pre-allocate objects into the pool. Does not count toward live. */\n prewarm(count: number): void {\n for (let i = 0; i < count; i++) {\n this.items.push(this.factory());\n }\n }\n\n /** Number of available objects currently in the pool (not live). */\n get available(): number {\n return this.items.length;\n }\n\n /** Number of currently live (acquired, not yet released) objects. */\n get live(): number {\n return this._live;\n }\n\n /** Cumulative number of factory calls made by acquire()/tryAcquire().\n * prewarm() is deliberately excluded: this counter exists to detect\n * steady-state allocation, so compare it before and after a frame. */\n get created(): number {\n return this._created;\n }\n\n /** Clear all pooled objects. Does not affect live count. */\n clear(): void {\n this.items.length = 0;\n this._liveSet?.clear();\n }\n}\n","import { Signal } from '@flare-engine/events';\nimport type { Rect, Vec2 } from '@flare-engine/math';\n\n/** Scale mode for mapping design resolution to device screen. */\nexport type ScaleMode = 'fit' | 'fill' | 'stretch';\n\n/** Screen configuration. */\nexport interface ScreenConfig {\n /** Design resolution width in logical pixels. */\n designWidth: number;\n /** Design resolution height in logical pixels. */\n designHeight: number;\n /** How to fit design resolution to device (default: 'fit'). */\n scaleMode?: ScaleMode;\n}\n\n/**\n * ScreenManager maps a fixed design resolution to the actual device screen.\n *\n * - FIT: letterbox (scale to fit, black bars)\n * - FILL: crop (scale to fill, content cropped)\n * - STRETCH: distort (stretch to fill, aspect ratio distorted)\n */\nexport class ScreenManager {\n /** Design resolution width. */\n readonly designWidth: number;\n /** Design resolution height. */\n readonly designHeight: number;\n /** Current scale mode. */\n scaleMode: ScaleMode;\n\n /** Device pixel ratio. */\n pixelRatio = 1;\n\n /** Safe area insets (top, right, bottom, left) in device pixels. */\n safeArea: Rect = { x: 0, y: 0, width: 0, height: 0 };\n\n /** Fires when screen dimensions change. */\n readonly onResize = new Signal<void>();\n\n /** Computed scale factor X (design → screen). */\n scaleX = 1;\n /** Computed scale factor Y (design → screen). */\n scaleY = 1;\n /** Offset X in screen pixels (for letterboxing). */\n offsetX = 0;\n /** Offset Y in screen pixels (for letterboxing). */\n offsetY = 0;\n\n private screenWidth = 0;\n private screenHeight = 0;\n\n constructor(config: ScreenConfig) {\n this.designWidth = config.designWidth;\n this.designHeight = config.designHeight;\n this.scaleMode = config.scaleMode ?? 'fit';\n }\n\n private safeInsetTop = 0;\n private safeInsetRight = 0;\n private safeInsetBottom = 0;\n private safeInsetLeft = 0;\n\n /** Update with actual device screen dimensions. Call on mount and resize. */\n resize(screenWidth: number, screenHeight: number, pixelRatio?: number): void {\n this.screenWidth = screenWidth;\n this.screenHeight = screenHeight;\n if (pixelRatio !== undefined) this.pixelRatio = pixelRatio;\n this.recalculate();\n this.recalculateSafeArea();\n this.onResize.emit();\n }\n\n /**\n * Set safe-area insets in screen pixels. Call this from the RN host with values from\n * `react-native-safe-area-context`. Populates `safeArea` as the usable region.\n */\n setSafeAreaInsets(top: number, right: number, bottom: number, left: number): void {\n this.safeInsetTop = top;\n this.safeInsetRight = right;\n this.safeInsetBottom = bottom;\n this.safeInsetLeft = left;\n this.recalculateSafeArea();\n this.onResize.emit();\n }\n\n private recalculateSafeArea(): void {\n this.safeArea.x = this.safeInsetLeft;\n this.safeArea.y = this.safeInsetTop;\n this.safeArea.width = Math.max(0, this.screenWidth - this.safeInsetLeft - this.safeInsetRight);\n this.safeArea.height = Math.max(\n 0,\n this.screenHeight - this.safeInsetTop - this.safeInsetBottom,\n );\n }\n\n /** Convert design-space point to screen-space. */\n designToScreen(point: Vec2): Vec2 {\n return {\n x: point.x * this.scaleX + this.offsetX,\n y: point.y * this.scaleY + this.offsetY,\n };\n }\n\n /** Convert screen-space point to design-space. */\n screenToDesign(point: Vec2): Vec2 {\n return {\n x: (point.x - this.offsetX) / this.scaleX,\n y: (point.y - this.offsetY) / this.scaleY,\n };\n }\n\n /** Viewport rect in design coordinates (visible area). */\n get viewport(): Rect {\n if (this.scaleMode === 'fill') {\n // In fill mode, the visible area is smaller than design\n const visibleW = this.screenWidth / this.scaleX;\n const visibleH = this.screenHeight / this.scaleY;\n return {\n x: (this.designWidth - visibleW) / 2,\n y: (this.designHeight - visibleH) / 2,\n width: visibleW,\n height: visibleH,\n };\n }\n return { x: 0, y: 0, width: this.designWidth, height: this.designHeight };\n }\n\n private recalculate(): void {\n const ratioX = this.screenWidth / this.designWidth;\n const ratioY = this.screenHeight / this.designHeight;\n\n switch (this.scaleMode) {\n case 'fit': {\n const scale = Math.min(ratioX, ratioY);\n this.scaleX = scale;\n this.scaleY = scale;\n this.offsetX = (this.screenWidth - this.designWidth * scale) / 2;\n this.offsetY = (this.screenHeight - this.designHeight * scale) / 2;\n break;\n }\n case 'fill': {\n const scale = Math.max(ratioX, ratioY);\n this.scaleX = scale;\n this.scaleY = scale;\n this.offsetX = (this.screenWidth - this.designWidth * scale) / 2;\n this.offsetY = (this.screenHeight - this.designHeight * scale) / 2;\n break;\n }\n case 'stretch': {\n this.scaleX = ratioX;\n this.scaleY = ratioY;\n this.offsetX = 0;\n this.offsetY = 0;\n break;\n }\n }\n }\n}\n"],"mappings":";;;;;;;;;;;AAYA,IAAa,eAAb,MAA0B;;CAExB,eAAwB,IAAI,OAAa;;CAEzC,eAAwB,IAAI,OAAa;;CAEzC,kBAA2B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ACzC,MAAM,WAAW,KAAK,eAAe,KAAK;GAC1C,OAAO;IACL,IAAI,KAAK,cAAc,YAAY;IACnC,IAAI,KAAK,eAAe,YAAY;IACpC,OAAO;IACP,QAAQ;GACV;EACF;EACA,OAAO;GAAE,GAAG;GAAG,GAAG;GAAG,OAAO,KAAK;GAAa,QAAQ,KAAK;EAAa;CAC1E;CAEA,cAA4B;EAC1B,MAAM,SAAS,KAAK,cAAc,KAAK;EACvC,MAAM,SAAS,KAAK,eAAe,KAAK;EAExC,QAAQ,KAAK,WAAb;GACE,KAAK,OAAO;IACV,MAAM,QAAQ,KAAK,IAAI,QAAQ,MAAM;IACrC,KAAK,SAAS;IACd,KAAK,SAAS;IACd,KAAK,WAAW,KAAK,cAAc,KAAK,cAAc,SAAS;IAC/D,KAAK,WAAW,KAAK,eAAe,KAAK,eAAe,SAAS;IACjE;GACF;GACA,KAAK,QAAQ;IACX,MAAM,QAAQ,KAAK,IAAI,QAAQ,MAAM;IACrC,KAAK,SAAS;IACd,KAAK,SAAS;IACd,KAAK,WAAW,KAAK,cAAc,KAAK,cAAc,SAAS;IAC/D,KAAK,WAAW,KAAK,eAAe,KAAK,eAAe,SAAS;IACjE;GACF;GACA,KAAK;IACH,KAAK,SAAS;IACd,KAAK,SAAS;IACd,KAAK,UAAU;IACf,KAAK,UAAU;IACf;EAEJ;CACF;AACF"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@flare-engine/core",
3
- "version": "0.3.1",
3
+ "version": "0.4.0",
4
4
  "description": "GameLoop, Clock, AppLifecycle, Pool, Coroutines",
5
5
  "keywords": ["flare-engine", "game-loop", "coroutines", "pool"],
6
6
  "license": "Apache-2.0",
@@ -37,8 +37,8 @@
37
37
  "typecheck": "tsc --noEmit"
38
38
  },
39
39
  "dependencies": {
40
- "@flare-engine/math": "^0.3.1",
41
- "@flare-engine/events": "^0.3.1"
40
+ "@flare-engine/math": "^0.4.0",
41
+ "@flare-engine/events": "^0.4.0"
42
42
  },
43
43
  "engines": {
44
44
  "node": ">=20"