@flare-engine/core 0.2.1 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,491 +1,579 @@
1
- "use strict";
2
- var __defProp = Object.defineProperty;
3
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
- var __getOwnPropNames = Object.getOwnPropertyNames;
5
- var __hasOwnProp = Object.prototype.hasOwnProperty;
6
- var __export = (target, all) => {
7
- for (var name in all)
8
- __defProp(target, name, { get: all[name], enumerable: true });
9
- };
10
- var __copyProps = (to, from, except, desc) => {
11
- if (from && typeof from === "object" || typeof from === "function") {
12
- for (let key of __getOwnPropNames(from))
13
- if (!__hasOwnProp.call(to, key) && key !== except)
14
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
- }
16
- return to;
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ let _flare_engine_events = require("@flare-engine/events");
3
+ //#region src/app-lifecycle.ts
4
+ /**
5
+ * AppLifecycle bridges React Native AppState to the game loop.
6
+ *
7
+ * - Auto-pauses the loop when app goes to background
8
+ * - Auto-resumes when app returns to foreground
9
+ * - Caps dt on resume to prevent huge time jumps
10
+ *
11
+ * In non-RN environments (tests, web), use the manual methods.
12
+ */
13
+ var AppLifecycle = class {
14
+ /** Fires when app enters background. */
15
+ onBackground = new _flare_engine_events.Signal();
16
+ /** Fires when app returns to foreground. */
17
+ onForeground = new _flare_engine_events.Signal();
18
+ /** Fires on memory warning (RN-specific). */
19
+ onMemoryWarning = new _flare_engine_events.Signal();
20
+ loop;
21
+ wasRunningBeforeBackground = false;
22
+ _inBackground = false;
23
+ constructor(loop) {
24
+ this.loop = loop;
25
+ }
26
+ /** Call when app goes to background. */
27
+ background() {
28
+ if (this._inBackground) return;
29
+ this._inBackground = true;
30
+ this.wasRunningBeforeBackground = this.loop.isRunning && !this.loop.isPaused;
31
+ if (this.wasRunningBeforeBackground) this.loop.pause();
32
+ this.onBackground.emit();
33
+ }
34
+ /** Call when app returns to foreground. */
35
+ foreground() {
36
+ this._inBackground = false;
37
+ if (this.wasRunningBeforeBackground) this.loop.resume();
38
+ this.onForeground.emit();
39
+ }
40
+ /** Call on memory warning. */
41
+ memoryWarning() {
42
+ this.onMemoryWarning.emit();
43
+ }
17
44
  };
18
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
-
20
- // src/index.ts
21
- var index_exports = {};
22
- __export(index_exports, {
23
- AppLifecycle: () => AppLifecycle,
24
- Clock: () => Clock,
25
- CoroutineManager: () => CoroutineManager,
26
- GameLoop: () => GameLoop,
27
- Pool: () => Pool,
28
- ScreenManager: () => ScreenManager
29
- });
30
- module.exports = __toCommonJS(index_exports);
31
-
32
- // src/clock.ts
45
+ //#endregion
46
+ //#region src/clock.ts
33
47
  var Clock = class {
34
- /** Unscaled delta time in seconds since last frame. */
35
- rawDt = 0;
36
- /** Scaled delta time in seconds (rawDt * timescale). */
37
- dt = 0;
38
- /** Fixed timestep in seconds for physics updates (default 1/60). */
39
- fixedDt = 1 / 60;
40
- /** Total elapsed time in seconds (scaled). */
41
- elapsed = 0;
42
- /** Smoothed frames per second. */
43
- fps = 0;
44
- /** Time scale multiplier. 1 = normal, 0 = paused, 0.5 = slow-mo. */
45
- timescale = 1;
46
- /** Current frame number (monotonically increasing). */
47
- frame = 0;
48
- schedules = [];
49
- fpsAlpha = 0.9;
50
- /** Called once per frame by the GameLoop with raw unscaled dt. */
51
- update(rawDt) {
52
- this.rawDt = rawDt;
53
- this.dt = rawDt * this.timescale;
54
- this.elapsed += this.dt;
55
- this.frame++;
56
- if (rawDt > 0) {
57
- const instantFps = 1 / rawDt;
58
- this.fps = this.fps === 0 ? instantFps : this.fps * this.fpsAlpha + instantFps * (1 - this.fpsAlpha);
59
- }
60
- this.tickSchedules(this.dt);
61
- }
62
- /** Schedule a one-shot callback after `delay` seconds (scaled time). */
63
- schedule(delay, callback) {
64
- const entry = { remaining: delay, callback, interval: 0 };
65
- this.schedules.push(entry);
66
- return () => {
67
- const idx = this.schedules.indexOf(entry);
68
- if (idx !== -1) this.schedules.splice(idx, 1);
69
- };
70
- }
71
- /** Schedule a repeating callback every `interval` seconds (scaled time). */
72
- repeat(interval, callback) {
73
- const entry = { remaining: interval, callback, interval };
74
- this.schedules.push(entry);
75
- return () => {
76
- const idx = this.schedules.indexOf(entry);
77
- if (idx !== -1) this.schedules.splice(idx, 1);
78
- };
79
- }
80
- /** Reset clock to initial state. */
81
- reset() {
82
- this.rawDt = 0;
83
- this.dt = 0;
84
- this.elapsed = 0;
85
- this.fps = 0;
86
- this.frame = 0;
87
- this.timescale = 1;
88
- this.schedules.length = 0;
89
- }
90
- tickSchedules(dt) {
91
- for (let i = this.schedules.length - 1; i >= 0; i--) {
92
- const entry = this.schedules[i];
93
- entry.remaining -= dt;
94
- if (entry.remaining <= 0) {
95
- entry.callback();
96
- if (entry.interval > 0) {
97
- entry.remaining += entry.interval;
98
- } else {
99
- this.schedules.splice(i, 1);
100
- }
101
- }
102
- }
103
- }
48
+ /** Unscaled delta time in seconds since last frame. */
49
+ rawDt = 0;
50
+ /** Scaled delta time in seconds (rawDt * timescale). */
51
+ dt = 0;
52
+ /** Fixed timestep in seconds for physics updates (default 1/60). */
53
+ fixedDt = 1 / 60;
54
+ /** Total elapsed time in seconds (scaled). */
55
+ elapsed = 0;
56
+ /** Smoothed frames per second. */
57
+ fps = 0;
58
+ /** Time scale multiplier. 1 = normal, 0 = paused, 0.5 = slow-mo. */
59
+ timescale = 1;
60
+ /** Current frame number (monotonically increasing). */
61
+ frame = 0;
62
+ schedules = [];
63
+ fpsAlpha = .9;
64
+ /** Called once per frame by the GameLoop with raw unscaled dt. */
65
+ update(rawDt) {
66
+ this.rawDt = rawDt;
67
+ this.dt = rawDt * this.timescale;
68
+ this.elapsed += this.dt;
69
+ this.frame++;
70
+ if (rawDt > 0) {
71
+ const instantFps = 1 / rawDt;
72
+ this.fps = this.fps === 0 ? instantFps : this.fps * this.fpsAlpha + instantFps * (1 - this.fpsAlpha);
73
+ }
74
+ this.tickSchedules(this.dt);
75
+ }
76
+ /** Schedule a one-shot callback after `delay` seconds (scaled time). */
77
+ schedule(delay, callback) {
78
+ const entry = {
79
+ remaining: delay,
80
+ callback,
81
+ interval: 0
82
+ };
83
+ this.schedules.push(entry);
84
+ return () => {
85
+ const idx = this.schedules.indexOf(entry);
86
+ if (idx !== -1) this.schedules.splice(idx, 1);
87
+ };
88
+ }
89
+ /** Schedule a repeating callback every `interval` seconds (scaled time). */
90
+ repeat(interval, callback) {
91
+ const entry = {
92
+ remaining: interval,
93
+ callback,
94
+ interval
95
+ };
96
+ this.schedules.push(entry);
97
+ return () => {
98
+ const idx = this.schedules.indexOf(entry);
99
+ if (idx !== -1) this.schedules.splice(idx, 1);
100
+ };
101
+ }
102
+ /** Reset clock to initial state. */
103
+ reset() {
104
+ this.rawDt = 0;
105
+ this.dt = 0;
106
+ this.elapsed = 0;
107
+ this.fps = 0;
108
+ this.frame = 0;
109
+ this.timescale = 1;
110
+ this.schedules.length = 0;
111
+ }
112
+ tickSchedules(dt) {
113
+ for (let i = this.schedules.length - 1; i >= 0; i--) {
114
+ const entry = this.schedules[i];
115
+ if (entry === void 0) continue;
116
+ entry.remaining -= dt;
117
+ if (entry.remaining <= 0) {
118
+ entry.callback();
119
+ if (entry.interval > 0) entry.remaining += entry.interval;
120
+ else {
121
+ const idx = this.schedules.indexOf(entry);
122
+ if (idx !== -1) this.schedules.splice(idx, 1);
123
+ }
124
+ }
125
+ }
126
+ }
104
127
  };
105
-
106
- // src/game-loop.ts
107
- var import_events = require("@flare-engine/events");
128
+ //#endregion
129
+ //#region src/coroutine.ts
130
+ /**
131
+ * CoroutineManager runs generator-based coroutines.
132
+ * Call update(dt) each frame to advance all active coroutines.
133
+ */
134
+ var CoroutineManager = class {
135
+ coroutines = [];
136
+ /** Start a new coroutine. Returns a handle to check status or cancel. */
137
+ start(gen) {
138
+ const state = {
139
+ gen,
140
+ waitTime: 0,
141
+ waitingForPromise: false,
142
+ done: false
143
+ };
144
+ this.coroutines.push(state);
145
+ this.advance(state);
146
+ return {
147
+ get done() {
148
+ return state.done;
149
+ },
150
+ cancel() {
151
+ state.done = true;
152
+ }
153
+ };
154
+ }
155
+ /** Update all running coroutines. Call once per frame with scaled dt. */
156
+ update(dt) {
157
+ for (let i = this.coroutines.length - 1; i >= 0; i--) {
158
+ const state = this.coroutines[i];
159
+ if (state === void 0) continue;
160
+ if (state.done) {
161
+ this.coroutines.splice(i, 1);
162
+ continue;
163
+ }
164
+ if (state.waitingForPromise) continue;
165
+ if (state.waitTime > 0) {
166
+ state.waitTime -= dt;
167
+ if (state.waitTime > 0) continue;
168
+ }
169
+ this.advance(state);
170
+ if (state.done) this.coroutines.splice(i, 1);
171
+ }
172
+ }
173
+ /** Cancel all running coroutines. */
174
+ clear() {
175
+ for (const state of this.coroutines) state.done = true;
176
+ this.coroutines.length = 0;
177
+ }
178
+ /** Number of active coroutines. */
179
+ get count() {
180
+ return this.coroutines.length;
181
+ }
182
+ advance(state) {
183
+ const result = state.gen.next();
184
+ if (result.done) {
185
+ state.done = true;
186
+ return;
187
+ }
188
+ const value = result.value;
189
+ if (typeof value === "number") state.waitTime = value;
190
+ else if (value instanceof Promise) {
191
+ state.waitingForPromise = true;
192
+ value.then(() => {
193
+ state.waitingForPromise = false;
194
+ }, () => {
195
+ state.done = true;
196
+ });
197
+ }
198
+ }
199
+ };
200
+ //#endregion
201
+ //#region src/game-loop.ts
202
+ /**
203
+ * GameLoop drives the update cycle using fixed + variable timestep.
204
+ *
205
+ * Fixed updates run at a constant rate (accumulator pattern).
206
+ * Variable updates run once per frame with the actual dt.
207
+ */
108
208
  var GameLoop = class {
109
- clock = new Clock();
110
- /** Fixed-timestep update (physics, deterministic logic). */
111
- onFixedUpdate = new import_events.Signal();
112
- /** Variable-timestep update (movement, AI, game logic). */
113
- onUpdate = new import_events.Signal();
114
- /** Runs after onUpdate (camera follow, post-processing logic). */
115
- onLateUpdate = new import_events.Signal();
116
- /** Runs before rendering. */
117
- onPreRender = new import_events.Signal();
118
- /** Runs after rendering. */
119
- onPostRender = new import_events.Signal();
120
- running = false;
121
- paused = false;
122
- accumulator = 0;
123
- maxDt;
124
- rafId = 0;
125
- lastTime = 0;
126
- /** External tick function — set this for testing or custom scheduling. */
127
- tick;
128
- /** External cancel function — paired with tick. */
129
- cancelTick;
130
- constructor(config) {
131
- this.maxDt = config?.maxDt ?? 0.25;
132
- if (config?.fixedDt !== void 0) {
133
- this.clock.fixedDt = config.fixedDt;
134
- }
135
- }
136
- /** Start the game loop. */
137
- start() {
138
- if (this.running) return;
139
- this.running = true;
140
- this.paused = false;
141
- this.lastTime = 0;
142
- this.accumulator = 0;
143
- this.scheduleFrame();
144
- }
145
- /** Stop the game loop entirely and reset. */
146
- stop() {
147
- this.running = false;
148
- this.paused = false;
149
- if (this.rafId !== 0) {
150
- const cancel = this.cancelTick ?? cancelAnimationFrame;
151
- cancel(this.rafId);
152
- this.rafId = 0;
153
- }
154
- }
155
- /** Pause — signals stop firing but loop stays alive. */
156
- pause() {
157
- if (!this.running || this.paused) return;
158
- this.paused = true;
159
- }
160
- /** Resume from pause. */
161
- resume() {
162
- if (!this.running || !this.paused) return;
163
- this.paused = false;
164
- this.lastTime = 0;
165
- }
166
- /** Whether the loop is currently running (started and not stopped). */
167
- get isRunning() {
168
- return this.running;
169
- }
170
- /** Whether the loop is paused. */
171
- get isPaused() {
172
- return this.paused;
173
- }
174
- /** Process a single frame. Exposed for testing. */
175
- step(rawDt) {
176
- if (this.paused) return;
177
- const capped = Math.min(rawDt, this.maxDt);
178
- this.clock.update(capped);
179
- const dt = this.clock.dt;
180
- const fixedDt = this.clock.fixedDt;
181
- this.accumulator += dt;
182
- while (this.accumulator >= fixedDt) {
183
- this.onFixedUpdate.emit(fixedDt);
184
- this.accumulator -= fixedDt;
185
- }
186
- this.onUpdate.emit(dt);
187
- this.onLateUpdate.emit(dt);
188
- this.onPreRender.emit();
189
- this.onPostRender.emit();
190
- }
191
- scheduleFrame() {
192
- const request = this.tick ?? requestAnimationFrame;
193
- this.rafId = request((time) => {
194
- if (!this.running) return;
195
- if (this.lastTime === 0) {
196
- this.lastTime = time;
197
- this.scheduleFrame();
198
- return;
199
- }
200
- const rawDt = (time - this.lastTime) / 1e3;
201
- this.lastTime = time;
202
- this.step(rawDt);
203
- this.scheduleFrame();
204
- });
205
- }
209
+ clock = new Clock();
210
+ /** Fixed-timestep update (physics, deterministic logic). */
211
+ onFixedUpdate = new _flare_engine_events.Signal();
212
+ /** Variable-timestep update (movement, AI, game logic). */
213
+ onUpdate = new _flare_engine_events.Signal();
214
+ /** Runs after onUpdate (camera follow, post-processing logic). */
215
+ onLateUpdate = new _flare_engine_events.Signal();
216
+ /** Runs before rendering. */
217
+ onPreRender = new _flare_engine_events.Signal();
218
+ /** Runs after rendering. */
219
+ onPostRender = new _flare_engine_events.Signal();
220
+ running = false;
221
+ paused = false;
222
+ accumulator = 0;
223
+ maxDt;
224
+ rafId = 0;
225
+ lastTime = 0;
226
+ _hasFixedDt = false;
227
+ /** External tick function — set this for testing or custom scheduling. */
228
+ tick;
229
+ /** External cancel function — paired with tick. */
230
+ cancelTick;
231
+ constructor(config) {
232
+ this.maxDt = config?.maxDt ?? .25;
233
+ if (config?.fixedDt !== void 0) {
234
+ if (config.fixedDt <= 0) throw new Error("GameLoop: fixedDt must be > 0");
235
+ this.clock.fixedDt = config.fixedDt;
236
+ this._hasFixedDt = true;
237
+ }
238
+ }
239
+ /** Start the game loop. */
240
+ start() {
241
+ if (this.running) return;
242
+ this.running = true;
243
+ this.paused = false;
244
+ this.lastTime = 0;
245
+ this.accumulator = 0;
246
+ this.scheduleFrame();
247
+ }
248
+ /** Stop the game loop entirely and reset. */
249
+ stop() {
250
+ this.running = false;
251
+ this.paused = false;
252
+ if (this.rafId !== 0) {
253
+ (this.cancelTick ?? cancelAnimationFrame)(this.rafId);
254
+ this.rafId = 0;
255
+ }
256
+ }
257
+ /** Pause — signals stop firing but loop stays alive. */
258
+ pause() {
259
+ if (!this.running || this.paused) return;
260
+ this.paused = true;
261
+ }
262
+ /** Resume from pause. */
263
+ resume() {
264
+ if (!this.running || !this.paused) return;
265
+ this.paused = false;
266
+ this.lastTime = 0;
267
+ }
268
+ /** Whether the loop is currently running (started and not stopped). */
269
+ get isRunning() {
270
+ return this.running;
271
+ }
272
+ /** Whether the loop is paused. */
273
+ get isPaused() {
274
+ return this.paused;
275
+ }
276
+ /**
277
+ * Post-step residual fraction for physics interpolation.
278
+ *
279
+ * After fixed updates drain the accumulator, `alpha` is the fraction of a
280
+ * fixed step that has elapsed since the last fixed tick — always in [0, 1).
281
+ * Read in `onPreRender` to lerp between the previous and current physics
282
+ * state for smooth visuals at any display refresh rate.
283
+ *
284
+ * Returns 0 when no fixed step was configured (i.e. `fixedDt` was not
285
+ * passed to the constructor).
286
+ */
287
+ get alpha() {
288
+ return this._hasFixedDt ? this.accumulator / this.clock.fixedDt : 0;
289
+ }
290
+ /** Process a single frame. Exposed for testing. */
291
+ step(rawDt) {
292
+ if (this.paused) return;
293
+ const capped = Math.min(rawDt, this.maxDt);
294
+ this.clock.update(capped);
295
+ const dt = this.clock.dt;
296
+ const fixedDt = this.clock.fixedDt;
297
+ if (fixedDt <= 0) throw new Error("GameLoop: fixedDt must be > 0");
298
+ this.accumulator += dt;
299
+ while (this.accumulator >= fixedDt) {
300
+ this.onFixedUpdate.emit(fixedDt);
301
+ this.accumulator -= fixedDt;
302
+ }
303
+ this.onUpdate.emit(dt);
304
+ this.onLateUpdate.emit(dt);
305
+ this.onPreRender.emit();
306
+ this.onPostRender.emit();
307
+ }
308
+ scheduleFrame() {
309
+ const request = this.tick ?? requestAnimationFrame;
310
+ this.rafId = request((time) => {
311
+ if (!this.running) return;
312
+ if (this.lastTime === 0) {
313
+ this.lastTime = time;
314
+ this.scheduleFrame();
315
+ return;
316
+ }
317
+ const rawDt = (time - this.lastTime) / 1e3;
318
+ this.lastTime = time;
319
+ this.step(rawDt);
320
+ this.scheduleFrame();
321
+ });
322
+ }
206
323
  };
207
-
208
- // src/app-lifecycle.ts
209
- var import_events2 = require("@flare-engine/events");
210
- var AppLifecycle = class {
211
- /** Fires when app enters background. */
212
- onBackground = new import_events2.Signal();
213
- /** Fires when app returns to foreground. */
214
- onForeground = new import_events2.Signal();
215
- /** Fires on memory warning (RN-specific). */
216
- onMemoryWarning = new import_events2.Signal();
217
- loop;
218
- wasRunningBeforeBackground = false;
219
- constructor(loop) {
220
- this.loop = loop;
221
- }
222
- /** Call when app goes to background. */
223
- background() {
224
- this.wasRunningBeforeBackground = this.loop.isRunning && !this.loop.isPaused;
225
- if (this.wasRunningBeforeBackground) {
226
- this.loop.pause();
227
- }
228
- this.onBackground.emit();
229
- }
230
- /** Call when app returns to foreground. */
231
- foreground() {
232
- if (this.wasRunningBeforeBackground) {
233
- this.loop.resume();
234
- }
235
- this.onForeground.emit();
236
- }
237
- /** Call on memory warning. */
238
- memoryWarning() {
239
- this.onMemoryWarning.emit();
240
- }
324
+ //#endregion
325
+ //#region src/pool.ts
326
+ /**
327
+ * Dev-flag access for `release()`, which runs once per released object.
328
+ *
329
+ * JSC has no inline cache for an unresolvable global identifier, so reading the
330
+ * bare `__DEV__` identifier behind a `typeof` guard costs ~270 ns *per
331
+ * evaluation* wherever the global is undeclared. React Native always defines it;
332
+ * web/CanvasKit and any Node or Bun consumer does not. A property miss on
333
+ * `globalThis` is inline-cached at ~0.46 ns and stays togglable at runtime
334
+ * exactly as before. Measured B28 (on JSC — V8 was never measured), PERF-10.
335
+ *
336
+ * Phrased without the literal old expression so `tests/pool-dist.test.ts` can
337
+ * count its occurrences in the built artifact: exactly one must survive, the
338
+ * constructor's.
339
+ *
340
+ * The constructor below deliberately keeps the identifier form: it runs once
341
+ * per pool, where ~270 ns is free, and it is the site a bundler can
342
+ * constant-fold for dead-code elimination.
343
+ */
344
+ const G = globalThis;
345
+ /**
346
+ * Generic object pool for zero-alloc gameplay.
347
+ *
348
+ * - acquire() returns a recycled or newly created object (uncapped)
349
+ * - tryAcquire() returns null when the live count is at capacity
350
+ * - release(obj) returns it to the pool
351
+ * - prewarm(count) pre-allocates objects
352
+ */
353
+ var Pool = class {
354
+ items = [];
355
+ factory;
356
+ resetFn;
357
+ _capacity;
358
+ _live = 0;
359
+ _created = 0;
360
+ _liveSet;
361
+ /**
362
+ * @param factory Function to create a new instance.
363
+ * @param reset Optional function to reset an object before reuse.
364
+ * @param options Optional pool configuration (capacity cap).
365
+ */
366
+ constructor(factory, reset, options) {
367
+ this.factory = factory;
368
+ this.resetFn = reset;
369
+ this._capacity = options?.capacity;
370
+ if (typeof __DEV__ !== "undefined" && __DEV__) this._liveSet = /* @__PURE__ */ new Set();
371
+ }
372
+ /** Get an object from the pool (or create a new one). Never throws; may exceed capacity. */
373
+ acquire() {
374
+ this._live++;
375
+ let item;
376
+ if (this.items.length > 0) item = this.items.pop();
377
+ else {
378
+ this._created++;
379
+ item = this.factory();
380
+ }
381
+ this._liveSet?.delete(item);
382
+ return item;
383
+ }
384
+ /**
385
+ * Get an object from the pool only if the live count is below capacity.
386
+ * Returns null when at cap — the caller must handle null (no allocation occurs).
387
+ * When no capacity was configured, behaves identically to acquire().
388
+ */
389
+ tryAcquire() {
390
+ if (this._capacity !== void 0 && this._live >= this._capacity) return null;
391
+ this._live++;
392
+ let item;
393
+ if (this.items.length > 0) item = this.items.pop();
394
+ else {
395
+ this._created++;
396
+ item = this.factory();
397
+ }
398
+ this._liveSet?.delete(item);
399
+ return item;
400
+ }
401
+ /** Return an object to the pool. Calls reset if configured. */
402
+ release(item) {
403
+ if (G.__DEV__) {
404
+ if (!this._liveSet) this._liveSet = /* @__PURE__ */ new Set();
405
+ if (this._liveSet.has(item)) throw new Error("[Pool] double-release detected");
406
+ this._liveSet.add(item);
407
+ }
408
+ this._live--;
409
+ if (this.resetFn) this.resetFn(item);
410
+ this.items.push(item);
411
+ }
412
+ /** Pre-allocate objects into the pool. Does not count toward live. */
413
+ prewarm(count) {
414
+ for (let i = 0; i < count; i++) this.items.push(this.factory());
415
+ }
416
+ /** Number of available objects currently in the pool (not live). */
417
+ get available() {
418
+ return this.items.length;
419
+ }
420
+ /** Number of currently live (acquired, not yet released) objects. */
421
+ get live() {
422
+ return this._live;
423
+ }
424
+ /** Cumulative number of factory calls made by acquire()/tryAcquire().
425
+ * prewarm() is deliberately excluded: this counter exists to detect
426
+ * steady-state allocation, so compare it before and after a frame. */
427
+ get created() {
428
+ return this._created;
429
+ }
430
+ /** Clear all pooled objects. Does not affect live count. */
431
+ clear() {
432
+ this.items.length = 0;
433
+ this._liveSet?.clear();
434
+ }
241
435
  };
242
-
243
- // src/screen.ts
244
- var import_events3 = require("@flare-engine/events");
436
+ //#endregion
437
+ //#region src/screen.ts
438
+ /**
439
+ * ScreenManager maps a fixed design resolution to the actual device screen.
440
+ *
441
+ * - FIT: letterbox (scale to fit, black bars)
442
+ * - FILL: crop (scale to fill, content cropped)
443
+ * - STRETCH: distort (stretch to fill, aspect ratio distorted)
444
+ */
245
445
  var ScreenManager = class {
246
- /** Design resolution width. */
247
- designWidth;
248
- /** Design resolution height. */
249
- designHeight;
250
- /** Current scale mode. */
251
- scaleMode;
252
- /** Device pixel ratio. */
253
- pixelRatio = 1;
254
- /** Safe area insets (top, right, bottom, left) in device pixels. */
255
- safeArea = { x: 0, y: 0, width: 0, height: 0 };
256
- /** Fires when screen dimensions change. */
257
- onResize = new import_events3.Signal();
258
- /** Computed scale factor X (design → screen). */
259
- scaleX = 1;
260
- /** Computed scale factor Y (design → screen). */
261
- scaleY = 1;
262
- /** Offset X in screen pixels (for letterboxing). */
263
- offsetX = 0;
264
- /** Offset Y in screen pixels (for letterboxing). */
265
- offsetY = 0;
266
- screenWidth = 0;
267
- screenHeight = 0;
268
- constructor(config) {
269
- this.designWidth = config.designWidth;
270
- this.designHeight = config.designHeight;
271
- this.scaleMode = config.scaleMode ?? "fit";
272
- }
273
- safeInsetTop = 0;
274
- safeInsetRight = 0;
275
- safeInsetBottom = 0;
276
- safeInsetLeft = 0;
277
- /** Update with actual device screen dimensions. Call on mount and resize. */
278
- resize(screenWidth, screenHeight, pixelRatio) {
279
- this.screenWidth = screenWidth;
280
- this.screenHeight = screenHeight;
281
- if (pixelRatio !== void 0) this.pixelRatio = pixelRatio;
282
- this.recalculate();
283
- this.recalculateSafeArea();
284
- this.onResize.emit();
285
- }
286
- /**
287
- * Set safe-area insets in screen pixels. Call this from the RN host with values from
288
- * `react-native-safe-area-context`. Populates `safeArea` as the usable region.
289
- */
290
- setSafeAreaInsets(top, right, bottom, left) {
291
- this.safeInsetTop = top;
292
- this.safeInsetRight = right;
293
- this.safeInsetBottom = bottom;
294
- this.safeInsetLeft = left;
295
- this.recalculateSafeArea();
296
- this.onResize.emit();
297
- }
298
- recalculateSafeArea() {
299
- this.safeArea.x = this.safeInsetLeft;
300
- this.safeArea.y = this.safeInsetTop;
301
- this.safeArea.width = Math.max(0, this.screenWidth - this.safeInsetLeft - this.safeInsetRight);
302
- this.safeArea.height = Math.max(
303
- 0,
304
- this.screenHeight - this.safeInsetTop - this.safeInsetBottom
305
- );
306
- }
307
- /** Convert design-space point to screen-space. */
308
- designToScreen(point) {
309
- return {
310
- x: point.x * this.scaleX + this.offsetX,
311
- y: point.y * this.scaleY + this.offsetY
312
- };
313
- }
314
- /** Convert screen-space point to design-space. */
315
- screenToDesign(point) {
316
- return {
317
- x: (point.x - this.offsetX) / this.scaleX,
318
- y: (point.y - this.offsetY) / this.scaleY
319
- };
320
- }
321
- /** Viewport rect in design coordinates (visible area). */
322
- get viewport() {
323
- if (this.scaleMode === "fill") {
324
- const visibleW = this.screenWidth / this.scaleX;
325
- const visibleH = this.screenHeight / this.scaleY;
326
- return {
327
- x: (this.designWidth - visibleW) / 2,
328
- y: (this.designHeight - visibleH) / 2,
329
- width: visibleW,
330
- height: visibleH
331
- };
332
- }
333
- return { x: 0, y: 0, width: this.designWidth, height: this.designHeight };
334
- }
335
- recalculate() {
336
- const ratioX = this.screenWidth / this.designWidth;
337
- const ratioY = this.screenHeight / this.designHeight;
338
- switch (this.scaleMode) {
339
- case "fit": {
340
- const scale = Math.min(ratioX, ratioY);
341
- this.scaleX = scale;
342
- this.scaleY = scale;
343
- this.offsetX = (this.screenWidth - this.designWidth * scale) / 2;
344
- this.offsetY = (this.screenHeight - this.designHeight * scale) / 2;
345
- break;
346
- }
347
- case "fill": {
348
- const scale = Math.max(ratioX, ratioY);
349
- this.scaleX = scale;
350
- this.scaleY = scale;
351
- this.offsetX = (this.screenWidth - this.designWidth * scale) / 2;
352
- this.offsetY = (this.screenHeight - this.designHeight * scale) / 2;
353
- break;
354
- }
355
- case "stretch": {
356
- this.scaleX = ratioX;
357
- this.scaleY = ratioY;
358
- this.offsetX = 0;
359
- this.offsetY = 0;
360
- break;
361
- }
362
- }
363
- }
364
- };
365
-
366
- // src/coroutine.ts
367
- var CoroutineManager = class {
368
- coroutines = [];
369
- /** Start a new coroutine. Returns a handle to check status or cancel. */
370
- start(gen) {
371
- const state = {
372
- gen,
373
- waitTime: 0,
374
- waitingForPromise: false,
375
- done: false
376
- };
377
- this.coroutines.push(state);
378
- this.advance(state);
379
- const handle = {
380
- get done() {
381
- return state.done;
382
- },
383
- cancel() {
384
- state.done = true;
385
- }
386
- };
387
- return handle;
388
- }
389
- /** Update all running coroutines. Call once per frame with scaled dt. */
390
- update(dt) {
391
- for (let i = this.coroutines.length - 1; i >= 0; i--) {
392
- const state = this.coroutines[i];
393
- if (state.done) {
394
- this.coroutines.splice(i, 1);
395
- continue;
396
- }
397
- if (state.waitingForPromise) continue;
398
- if (state.waitTime > 0) {
399
- state.waitTime -= dt;
400
- if (state.waitTime > 0) continue;
401
- }
402
- this.advance(state);
403
- if (state.done) {
404
- this.coroutines.splice(i, 1);
405
- }
406
- }
407
- }
408
- /** Cancel all running coroutines. */
409
- clear() {
410
- for (const state of this.coroutines) {
411
- state.done = true;
412
- }
413
- this.coroutines.length = 0;
414
- }
415
- /** Number of active coroutines. */
416
- get count() {
417
- return this.coroutines.length;
418
- }
419
- advance(state) {
420
- const result = state.gen.next();
421
- if (result.done) {
422
- state.done = true;
423
- return;
424
- }
425
- const value = result.value;
426
- if (typeof value === "number") {
427
- state.waitTime = value;
428
- } else if (value instanceof Promise) {
429
- state.waitingForPromise = true;
430
- value.then(
431
- () => {
432
- state.waitingForPromise = false;
433
- },
434
- () => {
435
- state.done = true;
436
- }
437
- );
438
- }
439
- }
446
+ /** Design resolution width. */
447
+ designWidth;
448
+ /** Design resolution height. */
449
+ designHeight;
450
+ /** Current scale mode. */
451
+ scaleMode;
452
+ /** Device pixel ratio. */
453
+ pixelRatio = 1;
454
+ /** Safe area insets (top, right, bottom, left) in device pixels. */
455
+ safeArea = {
456
+ x: 0,
457
+ y: 0,
458
+ width: 0,
459
+ height: 0
460
+ };
461
+ /** Fires when screen dimensions change. */
462
+ onResize = new _flare_engine_events.Signal();
463
+ /** Computed scale factor X (design → screen). */
464
+ scaleX = 1;
465
+ /** Computed scale factor Y (design → screen). */
466
+ scaleY = 1;
467
+ /** Offset X in screen pixels (for letterboxing). */
468
+ offsetX = 0;
469
+ /** Offset Y in screen pixels (for letterboxing). */
470
+ offsetY = 0;
471
+ screenWidth = 0;
472
+ screenHeight = 0;
473
+ constructor(config) {
474
+ this.designWidth = config.designWidth;
475
+ this.designHeight = config.designHeight;
476
+ this.scaleMode = config.scaleMode ?? "fit";
477
+ }
478
+ safeInsetTop = 0;
479
+ safeInsetRight = 0;
480
+ safeInsetBottom = 0;
481
+ safeInsetLeft = 0;
482
+ /** Update with actual device screen dimensions. Call on mount and resize. */
483
+ resize(screenWidth, screenHeight, pixelRatio) {
484
+ this.screenWidth = screenWidth;
485
+ this.screenHeight = screenHeight;
486
+ if (pixelRatio !== void 0) this.pixelRatio = pixelRatio;
487
+ this.recalculate();
488
+ this.recalculateSafeArea();
489
+ this.onResize.emit();
490
+ }
491
+ /**
492
+ * Set safe-area insets in screen pixels. Call this from the RN host with values from
493
+ * `react-native-safe-area-context`. Populates `safeArea` as the usable region.
494
+ */
495
+ setSafeAreaInsets(top, right, bottom, left) {
496
+ this.safeInsetTop = top;
497
+ this.safeInsetRight = right;
498
+ this.safeInsetBottom = bottom;
499
+ this.safeInsetLeft = left;
500
+ this.recalculateSafeArea();
501
+ this.onResize.emit();
502
+ }
503
+ recalculateSafeArea() {
504
+ this.safeArea.x = this.safeInsetLeft;
505
+ this.safeArea.y = this.safeInsetTop;
506
+ this.safeArea.width = Math.max(0, this.screenWidth - this.safeInsetLeft - this.safeInsetRight);
507
+ this.safeArea.height = Math.max(0, this.screenHeight - this.safeInsetTop - this.safeInsetBottom);
508
+ }
509
+ /** Convert design-space point to screen-space. */
510
+ designToScreen(point) {
511
+ return {
512
+ x: point.x * this.scaleX + this.offsetX,
513
+ y: point.y * this.scaleY + this.offsetY
514
+ };
515
+ }
516
+ /** Convert screen-space point to design-space. */
517
+ screenToDesign(point) {
518
+ return {
519
+ x: (point.x - this.offsetX) / this.scaleX,
520
+ y: (point.y - this.offsetY) / this.scaleY
521
+ };
522
+ }
523
+ /** Viewport rect in design coordinates (visible area). */
524
+ get viewport() {
525
+ if (this.scaleMode === "fill") {
526
+ const visibleW = this.screenWidth / this.scaleX;
527
+ const visibleH = this.screenHeight / this.scaleY;
528
+ return {
529
+ x: (this.designWidth - visibleW) / 2,
530
+ y: (this.designHeight - visibleH) / 2,
531
+ width: visibleW,
532
+ height: visibleH
533
+ };
534
+ }
535
+ return {
536
+ x: 0,
537
+ y: 0,
538
+ width: this.designWidth,
539
+ height: this.designHeight
540
+ };
541
+ }
542
+ recalculate() {
543
+ const ratioX = this.screenWidth / this.designWidth;
544
+ const ratioY = this.screenHeight / this.designHeight;
545
+ switch (this.scaleMode) {
546
+ case "fit": {
547
+ const scale = Math.min(ratioX, ratioY);
548
+ this.scaleX = scale;
549
+ this.scaleY = scale;
550
+ this.offsetX = (this.screenWidth - this.designWidth * scale) / 2;
551
+ this.offsetY = (this.screenHeight - this.designHeight * scale) / 2;
552
+ break;
553
+ }
554
+ case "fill": {
555
+ const scale = Math.max(ratioX, ratioY);
556
+ this.scaleX = scale;
557
+ this.scaleY = scale;
558
+ this.offsetX = (this.screenWidth - this.designWidth * scale) / 2;
559
+ this.offsetY = (this.screenHeight - this.designHeight * scale) / 2;
560
+ break;
561
+ }
562
+ case "stretch":
563
+ this.scaleX = ratioX;
564
+ this.scaleY = ratioY;
565
+ this.offsetX = 0;
566
+ this.offsetY = 0;
567
+ break;
568
+ }
569
+ }
440
570
  };
571
+ //#endregion
572
+ exports.AppLifecycle = AppLifecycle;
573
+ exports.Clock = Clock;
574
+ exports.CoroutineManager = CoroutineManager;
575
+ exports.GameLoop = GameLoop;
576
+ exports.Pool = Pool;
577
+ exports.ScreenManager = ScreenManager;
441
578
 
442
- // src/pool.ts
443
- var Pool = class {
444
- items = [];
445
- factory;
446
- resetFn;
447
- /**
448
- * @param factory Function to create a new instance.
449
- * @param reset Optional function to reset an object before reuse.
450
- */
451
- constructor(factory, reset) {
452
- this.factory = factory;
453
- this.resetFn = reset;
454
- }
455
- /** Get an object from the pool (or create a new one). */
456
- acquire() {
457
- if (this.items.length > 0) {
458
- return this.items.pop();
459
- }
460
- return this.factory();
461
- }
462
- /** Return an object to the pool. Calls reset if configured. */
463
- release(item) {
464
- if (this.resetFn) this.resetFn(item);
465
- this.items.push(item);
466
- }
467
- /** Pre-allocate objects into the pool. */
468
- prewarm(count) {
469
- for (let i = 0; i < count; i++) {
470
- this.items.push(this.factory());
471
- }
472
- }
473
- /** Number of available objects in the pool. */
474
- get available() {
475
- return this.items.length;
476
- }
477
- /** Clear all pooled objects. */
478
- clear() {
479
- this.items.length = 0;
480
- }
481
- };
482
- // Annotate the CommonJS export names for ESM import in node:
483
- 0 && (module.exports = {
484
- AppLifecycle,
485
- Clock,
486
- CoroutineManager,
487
- GameLoop,
488
- Pool,
489
- ScreenManager
490
- });
491
579
  //# sourceMappingURL=index.js.map