@flare-engine/core 0.4.11 → 0.4.12
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/dist/index.d.mts +13 -5
- package/dist/index.d.mts.map +1 -1
- package/dist/index.d.ts +13 -5
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +30 -25
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +30 -25
- package/dist/index.mjs.map +1 -1
- package/package.json +3 -3
package/dist/index.d.mts
CHANGED
|
@@ -61,6 +61,7 @@ export declare class GameLoop {
|
|
|
61
61
|
private accumulator;
|
|
62
62
|
private maxDt;
|
|
63
63
|
private rafId;
|
|
64
|
+
private framePending;
|
|
64
65
|
private lastTime;
|
|
65
66
|
private _hasFixedDt;
|
|
66
67
|
/** External tick function — set this for testing or custom scheduling. */
|
|
@@ -95,15 +96,21 @@ export declare class GameLoop {
|
|
|
95
96
|
/** Process a single frame. Exposed for testing. */
|
|
96
97
|
step(rawDt: number): void;
|
|
97
98
|
private scheduleFrame;
|
|
99
|
+
private readonly onFrame;
|
|
98
100
|
}
|
|
99
101
|
/**
|
|
100
|
-
* AppLifecycle
|
|
102
|
+
* AppLifecycle is a manual adapter between the host's app-state events and the game loop.
|
|
101
103
|
*
|
|
102
|
-
*
|
|
103
|
-
*
|
|
104
|
-
*
|
|
104
|
+
* It subscribes to nothing. The host calls `background()`, `foreground()` and
|
|
105
|
+
* `memoryWarning()` itself, for example from a React Native `AppState` listener or a
|
|
106
|
+
* web `visibilitychange` handler it writes.
|
|
105
107
|
*
|
|
106
|
-
*
|
|
108
|
+
* - `background()` pauses the loop if it was running and unpaused, and remembers that it did
|
|
109
|
+
* - `foreground()` resumes the loop only if `background()` paused it
|
|
110
|
+
* - each method emits its matching signal: `onBackground`, `onForeground`, `onMemoryWarning`
|
|
111
|
+
*
|
|
112
|
+
* The first frame after a resume does not see the time spent in the background:
|
|
113
|
+
* `GameLoop.resume()` resets the loop's last timestamp.
|
|
107
114
|
*/
|
|
108
115
|
export declare class AppLifecycle {
|
|
109
116
|
/** Fires when app enters background. */
|
|
@@ -216,6 +223,7 @@ export declare class Pool<T> {
|
|
|
216
223
|
* When no capacity was configured, behaves identically to acquire().
|
|
217
224
|
*/
|
|
218
225
|
tryAcquire(): T | null;
|
|
226
|
+
private take;
|
|
219
227
|
/** Return an object to the pool. Calls reset if configured. */
|
|
220
228
|
release(item: T): void;
|
|
221
229
|
/** Pre-allocate objects into the pool. Does not count toward live. */
|
package/dist/index.d.mts.map
CHANGED
|
@@ -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":";;;;;;qBAYa;;EAEX;;EAGA;;EAGA;;EAGA;;EAGA;;EAGA;;EAGA;UAEQ;UACA;;EAGR,OAAO;;EAkBP,SAAS,eAAe;;EAUxB,OAAO,kBAAkB;;EAUzB;UAUQ;;;UClFO;;EAEf;;EAEA;;;;;;;;qBASW;WACF,OAAK;;WAGL,eAAa;;WAEb,UAAQ;;WAER,cAAY;;WAEZ,aAAW;;WAEX,cAAY;UAEb;UACA;UACA;UACA;UACA;UACA;UACA;;EAGR,QAAQ,WAAW;;EAEnB,cAAc;EAEF,YAAA,SAAS;;EAUrB;;EAUA;;
|
|
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":";;;;;;qBAYa;;EAEX;;EAGA;;EAGA;;EAGA;;EAGA;;EAGA;;EAGA;UAEQ;UACA;;EAGR,OAAO;;EAkBP,SAAS,eAAe;;EAUxB,OAAO,kBAAkB;;EAUzB;UAUQ;;;UClFO;;EAEf;;EAEA;;;;;;;;qBASW;WACF,OAAK;;WAGL,eAAa;;WAEb,UAAQ;;WAER,cAAY;;WAEZ,aAAW;;WAEX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
private rafId;
|
|
64
|
+
private framePending;
|
|
64
65
|
private lastTime;
|
|
65
66
|
private _hasFixedDt;
|
|
66
67
|
/** External tick function — set this for testing or custom scheduling. */
|
|
@@ -95,15 +96,21 @@ export declare class GameLoop {
|
|
|
95
96
|
/** Process a single frame. Exposed for testing. */
|
|
96
97
|
step(rawDt: number): void;
|
|
97
98
|
private scheduleFrame;
|
|
99
|
+
private readonly onFrame;
|
|
98
100
|
}
|
|
99
101
|
/**
|
|
100
|
-
* AppLifecycle
|
|
102
|
+
* AppLifecycle is a manual adapter between the host's app-state events and the game loop.
|
|
101
103
|
*
|
|
102
|
-
*
|
|
103
|
-
*
|
|
104
|
-
*
|
|
104
|
+
* It subscribes to nothing. The host calls `background()`, `foreground()` and
|
|
105
|
+
* `memoryWarning()` itself, for example from a React Native `AppState` listener or a
|
|
106
|
+
* web `visibilitychange` handler it writes.
|
|
105
107
|
*
|
|
106
|
-
*
|
|
108
|
+
* - `background()` pauses the loop if it was running and unpaused, and remembers that it did
|
|
109
|
+
* - `foreground()` resumes the loop only if `background()` paused it
|
|
110
|
+
* - each method emits its matching signal: `onBackground`, `onForeground`, `onMemoryWarning`
|
|
111
|
+
*
|
|
112
|
+
* The first frame after a resume does not see the time spent in the background:
|
|
113
|
+
* `GameLoop.resume()` resets the loop's last timestamp.
|
|
107
114
|
*/
|
|
108
115
|
export declare class AppLifecycle {
|
|
109
116
|
/** Fires when app enters background. */
|
|
@@ -216,6 +223,7 @@ export declare class Pool<T> {
|
|
|
216
223
|
* When no capacity was configured, behaves identically to acquire().
|
|
217
224
|
*/
|
|
218
225
|
tryAcquire(): T | null;
|
|
226
|
+
private take;
|
|
219
227
|
/** Return an object to the pool. Calls reset if configured. */
|
|
220
228
|
release(item: T): void;
|
|
221
229
|
/** Pre-allocate objects into the pool. Does not count toward live. */
|
package/dist/index.d.ts.map
CHANGED
|
@@ -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":";;;;;;qBAYa;;EAEX;;EAGA;;EAGA;;EAGA;;EAGA;;EAGA;;EAGA;UAEQ;UACA;;EAGR,OAAO;;EAkBP,SAAS,eAAe;;EAUxB,OAAO,kBAAkB;;EAUzB;UAUQ;;;UClFO;;EAEf;;EAEA;;;;;;;;qBASW;WACF,OAAK;;WAGL,eAAa;;WAEb,UAAQ;;WAER,cAAY;;WAEZ,aAAW;;WAEX,cAAY;UAEb;UACA;UACA;UACA;UACA;UACA;UACA;;EAGR,QAAQ,WAAW;;EAEnB,cAAc;EAEF,YAAA,SAAS;;EAUrB;;EAUA;;
|
|
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":";;;;;;qBAYa;;EAEX;;EAGA;;EAGA;;EAGA;;EAGA;;EAGA;;EAGA;UAEQ;UACA;;EAGR,OAAO;;EAkBP,SAAS,eAAe;;EAUxB,OAAO,kBAAkB;;EAUzB;UAUQ;;;UClFO;;EAEf;;EAEA;;;;;;;;qBASW;WACF,OAAK;;WAGL,eAAa;;WAEb,UAAQ;;WAER,cAAY;;WAEZ,aAAW;;WAEX,cAAY;UAEb;UACA;UACA;UACA;UACA;UACA;UACA;UACA;;EAGR,QAAQ,WAAW;;EAEnB,cAAc;EAEF,YAAA,SAAS;;EAUrB;;EAUA;;EAYA;;EAMA;;MAOI;;MAKA;;;;;;;;;;;;MAeA;;EAKJ,KAAK;UA2BG;mBAOS;;;;;;;;;;;;;;;;qBCpIN;;WAEF,cAAY;;WAEZ,cAAY;;WAEZ,iBAAe;UAEhB;UACA;UACA;EAEI,YAAA,MAAM;;EAKlB;;EAWA;;EASA;;;;;;;;;;UC7Ce;;WAEN;;;;;;WAMA;;;;;;WAMA;;;;;;WAMA;;EAET;;;KAIU,sCAAsC;;KAGtC,qBAAqB,UAAU;;;;;qBAgC9B;UACH;;EAGR,MAAM,KAAK,qBAAqB;;EAqChC,OAAO;;EAyBP;;MAUI;UAII;;UAQA;UAiBA;;;UCxJO;;;;;EAKf;;;;;;;;;;qBAWW,KAAK;UACR;UACA;UACA;UACA;UACA;UACA;UACA;;;;;;EAOI,YAAA,eAAe,GAAG,SAAS,MAAM,YAAY,UAAU;;EAUnE,WAAW;;;;;;EASX,cAAc;UAKN;;EAcR,QAAQ,MAAM;;EAYd,QAAQ;;MAOJ;;MAKA;;;;MAOA;;EAKJ;;;KC3HU;;UAGK;;EAEf;;EAEA;;EAEA,YAAY;;;;;;;;;qBAUD;;WAEF;;WAEA;;EAET,WAAW;;EAGX;;EAGA,UAAU;;WAGD,UAAQ;;EAGjB;;EAEA;;EAEA;;EAEA;UAEQ;UACA;EAEI,YAAA,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
|
@@ -2,13 +2,18 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
|
2
2
|
let _flare_engine_events = require("@flare-engine/events");
|
|
3
3
|
// src/app-lifecycle.ts
|
|
4
4
|
/**
|
|
5
|
-
* AppLifecycle
|
|
5
|
+
* AppLifecycle is a manual adapter between the host's app-state events and the game loop.
|
|
6
6
|
*
|
|
7
|
-
*
|
|
8
|
-
*
|
|
9
|
-
*
|
|
7
|
+
* It subscribes to nothing. The host calls `background()`, `foreground()` and
|
|
8
|
+
* `memoryWarning()` itself, for example from a React Native `AppState` listener or a
|
|
9
|
+
* web `visibilitychange` handler it writes.
|
|
10
10
|
*
|
|
11
|
-
*
|
|
11
|
+
* - `background()` pauses the loop if it was running and unpaused, and remembers that it did
|
|
12
|
+
* - `foreground()` resumes the loop only if `background()` paused it
|
|
13
|
+
* - each method emits its matching signal: `onBackground`, `onForeground`, `onMemoryWarning`
|
|
14
|
+
*
|
|
15
|
+
* The first frame after a resume does not see the time spent in the background:
|
|
16
|
+
* `GameLoop.resume()` resets the loop's last timestamp.
|
|
12
17
|
*/
|
|
13
18
|
var AppLifecycle = class {
|
|
14
19
|
/** Fires when app enters background. */
|
|
@@ -275,6 +280,7 @@ var GameLoop = class {
|
|
|
275
280
|
accumulator = 0;
|
|
276
281
|
maxDt;
|
|
277
282
|
rafId = 0;
|
|
283
|
+
framePending = false;
|
|
278
284
|
lastTime = 0;
|
|
279
285
|
_hasFixedDt = false;
|
|
280
286
|
/** External tick function — set this for testing or custom scheduling. */
|
|
@@ -306,6 +312,7 @@ var GameLoop = class {
|
|
|
306
312
|
(this.cancelTick ?? cancelAnimationFrame)(this.rafId);
|
|
307
313
|
this.rafId = 0;
|
|
308
314
|
}
|
|
315
|
+
this.framePending = false;
|
|
309
316
|
}
|
|
310
317
|
/** Pause — signals stop firing but loop stays alive. */
|
|
311
318
|
pause() {
|
|
@@ -360,19 +367,22 @@ var GameLoop = class {
|
|
|
360
367
|
}
|
|
361
368
|
scheduleFrame() {
|
|
362
369
|
const request = this.tick ?? requestAnimationFrame;
|
|
363
|
-
this.
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
const rawDt = (time - this.lastTime) / 1e3;
|
|
370
|
+
this.framePending = true;
|
|
371
|
+
this.rafId = request(this.onFrame);
|
|
372
|
+
}
|
|
373
|
+
onFrame = (time) => {
|
|
374
|
+
this.framePending = false;
|
|
375
|
+
if (!this.running) return;
|
|
376
|
+
if (this.lastTime === 0) {
|
|
371
377
|
this.lastTime = time;
|
|
372
|
-
this.step(rawDt);
|
|
373
378
|
this.scheduleFrame();
|
|
374
|
-
|
|
375
|
-
|
|
379
|
+
return;
|
|
380
|
+
}
|
|
381
|
+
const rawDt = (time - this.lastTime) / 1e3;
|
|
382
|
+
this.lastTime = time;
|
|
383
|
+
this.step(rawDt);
|
|
384
|
+
if (this.running && !this.framePending) this.scheduleFrame();
|
|
385
|
+
};
|
|
376
386
|
};
|
|
377
387
|
// src/pool.ts
|
|
378
388
|
/**
|
|
@@ -423,15 +433,7 @@ var Pool = class {
|
|
|
423
433
|
}
|
|
424
434
|
/** Get an object from the pool (or create a new one). Never throws; may exceed capacity. */
|
|
425
435
|
acquire() {
|
|
426
|
-
this.
|
|
427
|
-
let item;
|
|
428
|
-
if (this.items.length > 0) item = this.items.pop();
|
|
429
|
-
else {
|
|
430
|
-
this._created++;
|
|
431
|
-
item = this.factory();
|
|
432
|
-
}
|
|
433
|
-
this._liveSet?.delete(item);
|
|
434
|
-
return item;
|
|
436
|
+
return this.take();
|
|
435
437
|
}
|
|
436
438
|
/**
|
|
437
439
|
* Get an object from the pool only if the live count is below capacity.
|
|
@@ -440,6 +442,9 @@ var Pool = class {
|
|
|
440
442
|
*/
|
|
441
443
|
tryAcquire() {
|
|
442
444
|
if (this._capacity !== void 0 && this._live >= this._capacity) return null;
|
|
445
|
+
return this.take();
|
|
446
|
+
}
|
|
447
|
+
take() {
|
|
443
448
|
this._live++;
|
|
444
449
|
let item;
|
|
445
450
|
if (this.items.length > 0) item = this.items.pop();
|
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; 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,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AAK,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;EAGnB;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 is a manual adapter between the host's app-state events and the game loop.\n *\n * It subscribes to nothing. The host calls `background()`, `foreground()` and\n * `memoryWarning()` itself, for example from a React Native `AppState` listener or a\n * web `visibilitychange` handler it writes.\n *\n * - `background()` pauses the loop if it was running and unpaused, and remembers that it did\n * - `foreground()` resumes the loop only if `background()` paused it\n * - each method emits its matching signal: `onBackground`, `onForeground`, `onMemoryWarning`\n *\n * The first frame after a resume does not see the time spent in the background:\n * `GameLoop.resume()` resets the loop's last timestamp.\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 framePending = false;\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 this.framePending = false;\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.framePending = true;\n this.rafId = request(this.onFrame);\n }\n\n // Created once per loop and handed to every request, so a running loop allocates no closure per frame.\n private readonly onFrame = (time: number): void => {\n this.framePending = false;\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 // A handler may have stopped the loop, or restarted it and already scheduled\n // the next frame; scheduling again here would start a second frame chain.\n if (this.running && !this.framePending) this.scheduleFrame();\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 return this.take();\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 return this.take();\n }\n\n private take(): 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 /** 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":";;;;;;;;;;;;;;;;;AAiBA,IA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,OAAO;GACL,IAAI,MAAM,IAAI,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;EAGnB;CACF;AACF"}
|
package/dist/index.mjs
CHANGED
|
@@ -1,13 +1,18 @@
|
|
|
1
1
|
import { Signal } from "@flare-engine/events";
|
|
2
2
|
// src/app-lifecycle.ts
|
|
3
3
|
/**
|
|
4
|
-
* AppLifecycle
|
|
4
|
+
* AppLifecycle is a manual adapter between the host's app-state events and the game loop.
|
|
5
5
|
*
|
|
6
|
-
*
|
|
7
|
-
*
|
|
8
|
-
*
|
|
6
|
+
* It subscribes to nothing. The host calls `background()`, `foreground()` and
|
|
7
|
+
* `memoryWarning()` itself, for example from a React Native `AppState` listener or a
|
|
8
|
+
* web `visibilitychange` handler it writes.
|
|
9
9
|
*
|
|
10
|
-
*
|
|
10
|
+
* - `background()` pauses the loop if it was running and unpaused, and remembers that it did
|
|
11
|
+
* - `foreground()` resumes the loop only if `background()` paused it
|
|
12
|
+
* - each method emits its matching signal: `onBackground`, `onForeground`, `onMemoryWarning`
|
|
13
|
+
*
|
|
14
|
+
* The first frame after a resume does not see the time spent in the background:
|
|
15
|
+
* `GameLoop.resume()` resets the loop's last timestamp.
|
|
11
16
|
*/
|
|
12
17
|
var AppLifecycle = class {
|
|
13
18
|
/** Fires when app enters background. */
|
|
@@ -274,6 +279,7 @@ var GameLoop = class {
|
|
|
274
279
|
accumulator = 0;
|
|
275
280
|
maxDt;
|
|
276
281
|
rafId = 0;
|
|
282
|
+
framePending = false;
|
|
277
283
|
lastTime = 0;
|
|
278
284
|
_hasFixedDt = false;
|
|
279
285
|
/** External tick function — set this for testing or custom scheduling. */
|
|
@@ -305,6 +311,7 @@ var GameLoop = class {
|
|
|
305
311
|
(this.cancelTick ?? cancelAnimationFrame)(this.rafId);
|
|
306
312
|
this.rafId = 0;
|
|
307
313
|
}
|
|
314
|
+
this.framePending = false;
|
|
308
315
|
}
|
|
309
316
|
/** Pause — signals stop firing but loop stays alive. */
|
|
310
317
|
pause() {
|
|
@@ -359,19 +366,22 @@ var GameLoop = class {
|
|
|
359
366
|
}
|
|
360
367
|
scheduleFrame() {
|
|
361
368
|
const request = this.tick ?? requestAnimationFrame;
|
|
362
|
-
this.
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
const rawDt = (time - this.lastTime) / 1e3;
|
|
369
|
+
this.framePending = true;
|
|
370
|
+
this.rafId = request(this.onFrame);
|
|
371
|
+
}
|
|
372
|
+
onFrame = (time) => {
|
|
373
|
+
this.framePending = false;
|
|
374
|
+
if (!this.running) return;
|
|
375
|
+
if (this.lastTime === 0) {
|
|
370
376
|
this.lastTime = time;
|
|
371
|
-
this.step(rawDt);
|
|
372
377
|
this.scheduleFrame();
|
|
373
|
-
|
|
374
|
-
|
|
378
|
+
return;
|
|
379
|
+
}
|
|
380
|
+
const rawDt = (time - this.lastTime) / 1e3;
|
|
381
|
+
this.lastTime = time;
|
|
382
|
+
this.step(rawDt);
|
|
383
|
+
if (this.running && !this.framePending) this.scheduleFrame();
|
|
384
|
+
};
|
|
375
385
|
};
|
|
376
386
|
// src/pool.ts
|
|
377
387
|
/**
|
|
@@ -422,15 +432,7 @@ var Pool = class {
|
|
|
422
432
|
}
|
|
423
433
|
/** Get an object from the pool (or create a new one). Never throws; may exceed capacity. */
|
|
424
434
|
acquire() {
|
|
425
|
-
this.
|
|
426
|
-
let item;
|
|
427
|
-
if (this.items.length > 0) item = this.items.pop();
|
|
428
|
-
else {
|
|
429
|
-
this._created++;
|
|
430
|
-
item = this.factory();
|
|
431
|
-
}
|
|
432
|
-
this._liveSet?.delete(item);
|
|
433
|
-
return item;
|
|
435
|
+
return this.take();
|
|
434
436
|
}
|
|
435
437
|
/**
|
|
436
438
|
* Get an object from the pool only if the live count is below capacity.
|
|
@@ -439,6 +441,9 @@ var Pool = class {
|
|
|
439
441
|
*/
|
|
440
442
|
tryAcquire() {
|
|
441
443
|
if (this._capacity !== void 0 && this._live >= this._capacity) return null;
|
|
444
|
+
return this.take();
|
|
445
|
+
}
|
|
446
|
+
take() {
|
|
442
447
|
this._live++;
|
|
443
448
|
let item;
|
|
444
449
|
if (this.items.length > 0) item = this.items.pop();
|
package/dist/index.mjs.map
CHANGED
|
@@ -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; 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 }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AAI,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;EAGnB;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 is a manual adapter between the host's app-state events and the game loop.\n *\n * It subscribes to nothing. The host calls `background()`, `foreground()` and\n * `memoryWarning()` itself, for example from a React Native `AppState` listener or a\n * web `visibilitychange` handler it writes.\n *\n * - `background()` pauses the loop if it was running and unpaused, and remembers that it did\n * - `foreground()` resumes the loop only if `background()` paused it\n * - each method emits its matching signal: `onBackground`, `onForeground`, `onMemoryWarning`\n *\n * The first frame after a resume does not see the time spent in the background:\n * `GameLoop.resume()` resets the loop's last timestamp.\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 framePending = false;\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 this.framePending = false;\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.framePending = true;\n this.rafId = request(this.onFrame);\n }\n\n // Created once per loop and handed to every request, so a running loop allocates no closure per frame.\n private readonly onFrame = (time: number): void => {\n this.framePending = false;\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 // A handler may have stopped the loop, or restarted it and already scheduled\n // the next frame; scheduling again here would start a second frame chain.\n if (this.running && !this.framePending) this.scheduleFrame();\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 return this.take();\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 return this.take();\n }\n\n private take(): 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 /** 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":";;;;;;;;;;;;;;;;AAiBA,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,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;;AC7CA,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,WAAW,cAAc,IAAI,KAAK;EACpF;EAGA,KAAK,cAAc,KAAK,EAAE;CAC5B;;CAGA,SAAS,OAAe,UAAkC;EACxD,MAAM,QAAuB;GAAE,WAAW;GAAO;GAAU,UAAU;EAAE;EACvE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
+
"version": "0.4.12",
|
|
4
4
|
"description": "GameLoop, Clock, AppLifecycle, Pool, Coroutines",
|
|
5
5
|
"keywords": ["flare-engine", "game-loop", "coroutines", "pool", "react-native", "typescript"],
|
|
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.4.
|
|
41
|
-
"@flare-engine/events": "^0.4.
|
|
40
|
+
"@flare-engine/math": "^0.4.12",
|
|
41
|
+
"@flare-engine/events": "^0.4.12"
|
|
42
42
|
},
|
|
43
43
|
"engines": {
|
|
44
44
|
"node": ">=20"
|