@energy8platform/game-engine 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (80) hide show
  1. package/README.md +1134 -0
  2. package/dist/animation.cjs.js +505 -0
  3. package/dist/animation.cjs.js.map +1 -0
  4. package/dist/animation.d.ts +235 -0
  5. package/dist/animation.esm.js +500 -0
  6. package/dist/animation.esm.js.map +1 -0
  7. package/dist/assets.cjs.js +148 -0
  8. package/dist/assets.cjs.js.map +1 -0
  9. package/dist/assets.d.ts +97 -0
  10. package/dist/assets.esm.js +146 -0
  11. package/dist/assets.esm.js.map +1 -0
  12. package/dist/audio.cjs.js +345 -0
  13. package/dist/audio.cjs.js.map +1 -0
  14. package/dist/audio.d.ts +135 -0
  15. package/dist/audio.esm.js +343 -0
  16. package/dist/audio.esm.js.map +1 -0
  17. package/dist/core.cjs.js +1832 -0
  18. package/dist/core.cjs.js.map +1 -0
  19. package/dist/core.d.ts +633 -0
  20. package/dist/core.esm.js +1827 -0
  21. package/dist/core.esm.js.map +1 -0
  22. package/dist/debug.cjs.js +298 -0
  23. package/dist/debug.cjs.js.map +1 -0
  24. package/dist/debug.d.ts +114 -0
  25. package/dist/debug.esm.js +295 -0
  26. package/dist/debug.esm.js.map +1 -0
  27. package/dist/index.cjs.js +3623 -0
  28. package/dist/index.cjs.js.map +1 -0
  29. package/dist/index.d.ts +1607 -0
  30. package/dist/index.esm.js +3598 -0
  31. package/dist/index.esm.js.map +1 -0
  32. package/dist/ui.cjs.js +1081 -0
  33. package/dist/ui.cjs.js.map +1 -0
  34. package/dist/ui.d.ts +387 -0
  35. package/dist/ui.esm.js +1072 -0
  36. package/dist/ui.esm.js.map +1 -0
  37. package/dist/vite.cjs.js +125 -0
  38. package/dist/vite.cjs.js.map +1 -0
  39. package/dist/vite.d.ts +42 -0
  40. package/dist/vite.esm.js +122 -0
  41. package/dist/vite.esm.js.map +1 -0
  42. package/package.json +107 -0
  43. package/src/animation/Easing.ts +116 -0
  44. package/src/animation/SpineHelper.ts +162 -0
  45. package/src/animation/Timeline.ts +138 -0
  46. package/src/animation/Tween.ts +225 -0
  47. package/src/animation/index.ts +4 -0
  48. package/src/assets/AssetManager.ts +174 -0
  49. package/src/assets/index.ts +2 -0
  50. package/src/audio/AudioManager.ts +366 -0
  51. package/src/audio/index.ts +1 -0
  52. package/src/core/EventEmitter.ts +47 -0
  53. package/src/core/GameApplication.ts +306 -0
  54. package/src/core/Scene.ts +48 -0
  55. package/src/core/SceneManager.ts +258 -0
  56. package/src/core/index.ts +4 -0
  57. package/src/debug/DevBridge.ts +259 -0
  58. package/src/debug/FPSOverlay.ts +102 -0
  59. package/src/debug/index.ts +3 -0
  60. package/src/index.ts +71 -0
  61. package/src/input/InputManager.ts +171 -0
  62. package/src/input/index.ts +1 -0
  63. package/src/loading/CSSPreloader.ts +155 -0
  64. package/src/loading/LoadingScene.ts +356 -0
  65. package/src/loading/index.ts +2 -0
  66. package/src/state/StateMachine.ts +228 -0
  67. package/src/state/index.ts +1 -0
  68. package/src/types.ts +218 -0
  69. package/src/ui/BalanceDisplay.ts +155 -0
  70. package/src/ui/Button.ts +199 -0
  71. package/src/ui/Label.ts +111 -0
  72. package/src/ui/Modal.ts +134 -0
  73. package/src/ui/Panel.ts +125 -0
  74. package/src/ui/ProgressBar.ts +121 -0
  75. package/src/ui/Toast.ts +124 -0
  76. package/src/ui/WinDisplay.ts +133 -0
  77. package/src/ui/index.ts +16 -0
  78. package/src/viewport/ViewportManager.ts +241 -0
  79. package/src/viewport/index.ts +1 -0
  80. package/src/vite/index.ts +153 -0
@@ -0,0 +1,3623 @@
1
+ 'use strict';
2
+
3
+ var pixi_js = require('pixi.js');
4
+ var gameSdk = require('@energy8platform/game-sdk');
5
+
6
+ // ─── Scale Modes ───────────────────────────────────────────
7
+ exports.ScaleMode = void 0;
8
+ (function (ScaleMode) {
9
+ /** Fit inside container, maintain aspect ratio (letterbox/pillarbox) */
10
+ ScaleMode["FIT"] = "FIT";
11
+ /** Fill container, maintain aspect ratio (crop edges) */
12
+ ScaleMode["FILL"] = "FILL";
13
+ /** Stretch to fill (distorts) */
14
+ ScaleMode["STRETCH"] = "STRETCH";
15
+ })(exports.ScaleMode || (exports.ScaleMode = {}));
16
+ // ─── Orientation ───────────────────────────────────────────
17
+ exports.Orientation = void 0;
18
+ (function (Orientation) {
19
+ Orientation["LANDSCAPE"] = "landscape";
20
+ Orientation["PORTRAIT"] = "portrait";
21
+ Orientation["ANY"] = "any";
22
+ })(exports.Orientation || (exports.Orientation = {}));
23
+ // ─── Transition Types ──────────────────────────────────────
24
+ exports.TransitionType = void 0;
25
+ (function (TransitionType) {
26
+ TransitionType["NONE"] = "none";
27
+ TransitionType["FADE"] = "fade";
28
+ TransitionType["SLIDE_LEFT"] = "slide-left";
29
+ TransitionType["SLIDE_RIGHT"] = "slide-right";
30
+ })(exports.TransitionType || (exports.TransitionType = {}));
31
+
32
+ /**
33
+ * Minimal typed event emitter.
34
+ * Used internally by GameApplication, SceneManager, AudioManager, etc.
35
+ */
36
+ // eslint-disable-next-line @typescript-eslint/no-empty-object-type
37
+ class EventEmitter {
38
+ listeners = new Map();
39
+ on(event, handler) {
40
+ if (!this.listeners.has(event)) {
41
+ this.listeners.set(event, new Set());
42
+ }
43
+ this.listeners.get(event).add(handler);
44
+ return this;
45
+ }
46
+ once(event, handler) {
47
+ const wrapper = (data) => {
48
+ this.off(event, wrapper);
49
+ handler(data);
50
+ };
51
+ return this.on(event, wrapper);
52
+ }
53
+ off(event, handler) {
54
+ this.listeners.get(event)?.delete(handler);
55
+ return this;
56
+ }
57
+ emit(event, data) {
58
+ const handlers = this.listeners.get(event);
59
+ if (handlers) {
60
+ for (const handler of handlers) {
61
+ handler(data);
62
+ }
63
+ }
64
+ }
65
+ removeAllListeners(event) {
66
+ if (event) {
67
+ this.listeners.delete(event);
68
+ }
69
+ else {
70
+ this.listeners.clear();
71
+ }
72
+ return this;
73
+ }
74
+ }
75
+
76
+ /**
77
+ * Collection of easing functions for use with Tween and Timeline.
78
+ *
79
+ * All functions take a progress value t (0..1) and return the eased value.
80
+ */
81
+ const Easing = {
82
+ linear: (t) => t,
83
+ easeInQuad: (t) => t * t,
84
+ easeOutQuad: (t) => t * (2 - t),
85
+ easeInOutQuad: (t) => (t < 0.5 ? 2 * t * t : -1 + (4 - 2 * t) * t),
86
+ easeInCubic: (t) => t * t * t,
87
+ easeOutCubic: (t) => --t * t * t + 1,
88
+ easeInOutCubic: (t) => t < 0.5 ? 4 * t * t * t : (t - 1) * (2 * t - 2) * (2 * t - 2) + 1,
89
+ easeInQuart: (t) => t * t * t * t,
90
+ easeOutQuart: (t) => 1 - --t * t * t * t,
91
+ easeInOutQuart: (t) => t < 0.5 ? 8 * t * t * t * t : 1 - 8 * --t * t * t * t,
92
+ easeInSine: (t) => 1 - Math.cos((t * Math.PI) / 2),
93
+ easeOutSine: (t) => Math.sin((t * Math.PI) / 2),
94
+ easeInOutSine: (t) => -(Math.cos(Math.PI * t) - 1) / 2,
95
+ easeInExpo: (t) => (t === 0 ? 0 : Math.pow(2, 10 * t - 10)),
96
+ easeOutExpo: (t) => (t === 1 ? 1 : 1 - Math.pow(2, -10 * t)),
97
+ easeInOutExpo: (t) => t === 0
98
+ ? 0
99
+ : t === 1
100
+ ? 1
101
+ : t < 0.5
102
+ ? Math.pow(2, 20 * t - 10) / 2
103
+ : (2 - Math.pow(2, -20 * t + 10)) / 2,
104
+ easeInBack: (t) => {
105
+ const c1 = 1.70158;
106
+ const c3 = c1 + 1;
107
+ return c3 * t * t * t - c1 * t * t;
108
+ },
109
+ easeOutBack: (t) => {
110
+ const c1 = 1.70158;
111
+ const c3 = c1 + 1;
112
+ return 1 + c3 * Math.pow(t - 1, 3) + c1 * Math.pow(t - 1, 2);
113
+ },
114
+ easeInOutBack: (t) => {
115
+ const c1 = 1.70158;
116
+ const c2 = c1 * 1.525;
117
+ return t < 0.5
118
+ ? (Math.pow(2 * t, 2) * ((c2 + 1) * 2 * t - c2)) / 2
119
+ : (Math.pow(2 * t - 2, 2) * ((c2 + 1) * (t * 2 - 2) + c2) + 2) / 2;
120
+ },
121
+ easeOutBounce: (t) => {
122
+ const n1 = 7.5625;
123
+ const d1 = 2.75;
124
+ if (t < 1 / d1)
125
+ return n1 * t * t;
126
+ if (t < 2 / d1)
127
+ return n1 * (t -= 1.5 / d1) * t + 0.75;
128
+ if (t < 2.5 / d1)
129
+ return n1 * (t -= 2.25 / d1) * t + 0.9375;
130
+ return n1 * (t -= 2.625 / d1) * t + 0.984375;
131
+ },
132
+ easeInBounce: (t) => 1 - Easing.easeOutBounce(1 - t),
133
+ easeInOutBounce: (t) => t < 0.5
134
+ ? (1 - Easing.easeOutBounce(1 - 2 * t)) / 2
135
+ : (1 + Easing.easeOutBounce(2 * t - 1)) / 2,
136
+ easeOutElastic: (t) => {
137
+ const c4 = (2 * Math.PI) / 3;
138
+ return t === 0
139
+ ? 0
140
+ : t === 1
141
+ ? 1
142
+ : Math.pow(2, -10 * t) * Math.sin((t * 10 - 0.75) * c4) + 1;
143
+ },
144
+ easeInElastic: (t) => {
145
+ const c4 = (2 * Math.PI) / 3;
146
+ return t === 0
147
+ ? 0
148
+ : t === 1
149
+ ? 1
150
+ : -Math.pow(2, 10 * t - 10) * Math.sin((t * 10 - 10.75) * c4);
151
+ },
152
+ };
153
+
154
+ /**
155
+ * Lightweight tween system integrated with PixiJS Ticker.
156
+ * Zero external dependencies — no GSAP required.
157
+ *
158
+ * All tweens return a Promise that resolves on completion.
159
+ *
160
+ * @example
161
+ * ```ts
162
+ * // Fade in a sprite
163
+ * await Tween.to(sprite, { alpha: 1, y: 100 }, 500, Easing.easeOutBack);
164
+ *
165
+ * // Move and wait
166
+ * await Tween.to(sprite, { x: 500 }, 300);
167
+ *
168
+ * // From a starting value
169
+ * await Tween.from(sprite, { scale: 0, alpha: 0 }, 400);
170
+ * ```
171
+ */
172
+ class Tween {
173
+ static _tweens = [];
174
+ static _tickerAdded = false;
175
+ /**
176
+ * Animate properties from current values to target values.
177
+ *
178
+ * @param target - Object to animate (Sprite, Container, etc.)
179
+ * @param props - Target property values
180
+ * @param duration - Duration in milliseconds
181
+ * @param easing - Easing function (default: easeOutQuad)
182
+ * @param onUpdate - Progress callback (0..1)
183
+ */
184
+ static to(target, props, duration, easing, onUpdate) {
185
+ return new Promise((resolve) => {
186
+ // Capture starting values
187
+ const from = {};
188
+ for (const key of Object.keys(props)) {
189
+ from[key] = Tween.getProperty(target, key);
190
+ }
191
+ const tween = {
192
+ target,
193
+ from,
194
+ to: { ...props },
195
+ duration: Math.max(1, duration),
196
+ easing: easing ?? Easing.easeOutQuad,
197
+ elapsed: 0,
198
+ delay: 0,
199
+ resolve,
200
+ onUpdate,
201
+ };
202
+ Tween._tweens.push(tween);
203
+ Tween.ensureTicker();
204
+ });
205
+ }
206
+ /**
207
+ * Animate properties from given values to current values.
208
+ */
209
+ static from(target, props, duration, easing, onUpdate) {
210
+ // Capture current values as "to"
211
+ const to = {};
212
+ for (const key of Object.keys(props)) {
213
+ to[key] = Tween.getProperty(target, key);
214
+ Tween.setProperty(target, key, props[key]);
215
+ }
216
+ return Tween.to(target, to, duration, easing, onUpdate);
217
+ }
218
+ /**
219
+ * Animate from one set of values to another.
220
+ */
221
+ static fromTo(target, fromProps, toProps, duration, easing, onUpdate) {
222
+ // Set starting values
223
+ for (const key of Object.keys(fromProps)) {
224
+ Tween.setProperty(target, key, fromProps[key]);
225
+ }
226
+ return Tween.to(target, toProps, duration, easing, onUpdate);
227
+ }
228
+ /**
229
+ * Wait for a given duration (useful in timelines).
230
+ */
231
+ static delay(ms) {
232
+ return new Promise((resolve) => setTimeout(resolve, ms));
233
+ }
234
+ /**
235
+ * Kill all tweens on a target.
236
+ */
237
+ static killTweensOf(target) {
238
+ Tween._tweens = Tween._tweens.filter((tw) => {
239
+ if (tw.target === target) {
240
+ tw.resolve();
241
+ return false;
242
+ }
243
+ return true;
244
+ });
245
+ }
246
+ /**
247
+ * Kill all active tweens.
248
+ */
249
+ static killAll() {
250
+ for (const tw of Tween._tweens) {
251
+ tw.resolve();
252
+ }
253
+ Tween._tweens.length = 0;
254
+ }
255
+ /** Number of active tweens */
256
+ static get activeTweens() {
257
+ return Tween._tweens.length;
258
+ }
259
+ // ─── Internal ──────────────────────────────────────────
260
+ static ensureTicker() {
261
+ if (Tween._tickerAdded)
262
+ return;
263
+ Tween._tickerAdded = true;
264
+ pixi_js.Ticker.shared.add(Tween.tick);
265
+ }
266
+ static tick = (ticker) => {
267
+ const dt = ticker.deltaMS;
268
+ const completed = [];
269
+ for (const tw of Tween._tweens) {
270
+ tw.elapsed += dt;
271
+ if (tw.elapsed < tw.delay)
272
+ continue;
273
+ const raw = Math.min((tw.elapsed - tw.delay) / tw.duration, 1);
274
+ const t = tw.easing(raw);
275
+ // Interpolate each property
276
+ for (const key of Object.keys(tw.to)) {
277
+ const start = tw.from[key];
278
+ const end = tw.to[key];
279
+ const value = start + (end - start) * t;
280
+ Tween.setProperty(tw.target, key, value);
281
+ }
282
+ tw.onUpdate?.(raw);
283
+ if (raw >= 1) {
284
+ completed.push(tw);
285
+ }
286
+ }
287
+ // Remove completed tweens
288
+ for (const tw of completed) {
289
+ const idx = Tween._tweens.indexOf(tw);
290
+ if (idx !== -1)
291
+ Tween._tweens.splice(idx, 1);
292
+ tw.resolve();
293
+ }
294
+ // Remove ticker when no active tweens
295
+ if (Tween._tweens.length === 0 && Tween._tickerAdded) {
296
+ pixi_js.Ticker.shared.remove(Tween.tick);
297
+ Tween._tickerAdded = false;
298
+ }
299
+ };
300
+ /**
301
+ * Get a potentially nested property (supports 'scale.x', 'position.y', etc.)
302
+ */
303
+ static getProperty(target, key) {
304
+ const parts = key.split('.');
305
+ let obj = target;
306
+ for (let i = 0; i < parts.length - 1; i++) {
307
+ obj = obj[parts[i]];
308
+ }
309
+ return obj[parts[parts.length - 1]] ?? 0;
310
+ }
311
+ /**
312
+ * Set a potentially nested property.
313
+ */
314
+ static setProperty(target, key, value) {
315
+ const parts = key.split('.');
316
+ let obj = target;
317
+ for (let i = 0; i < parts.length - 1; i++) {
318
+ obj = obj[parts[i]];
319
+ }
320
+ obj[parts[parts.length - 1]] = value;
321
+ }
322
+ }
323
+
324
+ /**
325
+ * Manages the scene stack and transitions between scenes.
326
+ *
327
+ * @example
328
+ * ```ts
329
+ * const scenes = new SceneManager(app.stage);
330
+ * scenes.register('loading', LoadingScene);
331
+ * scenes.register('game', GameScene);
332
+ * await scenes.goto('loading');
333
+ * ```
334
+ */
335
+ class SceneManager extends EventEmitter {
336
+ /** Root container that scenes are added to */
337
+ root;
338
+ registry = new Map();
339
+ stack = [];
340
+ _transitioning = false;
341
+ /** Current viewport dimensions — set by ViewportManager */
342
+ _width = 0;
343
+ _height = 0;
344
+ constructor(root) {
345
+ super();
346
+ if (root)
347
+ this.root = root;
348
+ }
349
+ /** @internal Set the root container (called by GameApplication after PixiJS init) */
350
+ setRoot(root) {
351
+ this.root = root;
352
+ }
353
+ /** Register a scene class by key */
354
+ register(key, ctor) {
355
+ this.registry.set(key, ctor);
356
+ return this;
357
+ }
358
+ /** Get the current (topmost) scene entry */
359
+ get current() {
360
+ return this.stack.length > 0 ? this.stack[this.stack.length - 1] : null;
361
+ }
362
+ /** Get the current scene key */
363
+ get currentKey() {
364
+ return this.current?.key ?? null;
365
+ }
366
+ /** Whether a scene transition is in progress */
367
+ get isTransitioning() {
368
+ return this._transitioning;
369
+ }
370
+ /**
371
+ * Navigate to a scene, replacing the entire stack.
372
+ */
373
+ async goto(key, data, transition) {
374
+ const prevKey = this.currentKey;
375
+ // Exit all current scenes
376
+ while (this.stack.length > 0) {
377
+ await this.popInternal(false);
378
+ }
379
+ // Enter new scene
380
+ await this.pushInternal(key, data, transition);
381
+ this.emit('change', { from: prevKey, to: key });
382
+ }
383
+ /**
384
+ * Push a scene onto the stack (the previous scene stays underneath).
385
+ * Useful for overlays, modals, pause screens.
386
+ */
387
+ async push(key, data, transition) {
388
+ const prevKey = this.currentKey;
389
+ await this.pushInternal(key, data, transition);
390
+ this.emit('change', { from: prevKey, to: key });
391
+ }
392
+ /**
393
+ * Pop the top scene from the stack.
394
+ */
395
+ async pop(transition) {
396
+ if (this.stack.length <= 1) {
397
+ console.warn('[SceneManager] Cannot pop the last scene');
398
+ return;
399
+ }
400
+ const prevKey = this.currentKey;
401
+ await this.popInternal(true, transition);
402
+ this.emit('change', { from: prevKey, to: this.currentKey });
403
+ }
404
+ /**
405
+ * Replace the top scene with a new one.
406
+ */
407
+ async replace(key, data, transition) {
408
+ const prevKey = this.currentKey;
409
+ await this.popInternal(false);
410
+ await this.pushInternal(key, data, transition);
411
+ this.emit('change', { from: prevKey, to: key });
412
+ }
413
+ /**
414
+ * Called every frame by GameApplication.
415
+ */
416
+ update(dt) {
417
+ // Update only the top scene
418
+ this.current?.scene.onUpdate?.(dt);
419
+ }
420
+ /**
421
+ * Called on viewport resize.
422
+ */
423
+ resize(width, height) {
424
+ this._width = width;
425
+ this._height = height;
426
+ // Notify all scenes in the stack
427
+ for (const entry of this.stack) {
428
+ entry.scene.onResize?.(width, height);
429
+ }
430
+ }
431
+ /**
432
+ * Destroy all scenes and clear the manager.
433
+ */
434
+ destroy() {
435
+ for (const entry of this.stack) {
436
+ entry.scene.onDestroy?.();
437
+ entry.scene.container.destroy({ children: true });
438
+ }
439
+ this.stack.length = 0;
440
+ this.registry.clear();
441
+ this.removeAllListeners();
442
+ }
443
+ // ─── Internal ──────────────────────────────────────────
444
+ createScene(key) {
445
+ const Ctor = this.registry.get(key);
446
+ if (!Ctor) {
447
+ throw new Error(`[SceneManager] Scene "${key}" is not registered`);
448
+ }
449
+ return new Ctor();
450
+ }
451
+ async pushInternal(key, data, transition) {
452
+ this._transitioning = true;
453
+ const scene = this.createScene(key);
454
+ this.root.addChild(scene.container);
455
+ // Set initial size
456
+ if (this._width && this._height) {
457
+ scene.onResize?.(this._width, this._height);
458
+ }
459
+ // Transition in
460
+ await this.transitionIn(scene.container, transition);
461
+ await scene.onEnter?.(data);
462
+ this.stack.push({ scene, key });
463
+ this._transitioning = false;
464
+ }
465
+ async popInternal(showTransition, transition) {
466
+ const entry = this.stack.pop();
467
+ if (!entry)
468
+ return;
469
+ this._transitioning = true;
470
+ await entry.scene.onExit?.();
471
+ if (showTransition) {
472
+ await this.transitionOut(entry.scene.container, transition);
473
+ }
474
+ entry.scene.onDestroy?.();
475
+ entry.scene.container.destroy({ children: true });
476
+ this._transitioning = false;
477
+ }
478
+ async transitionIn(container, config) {
479
+ const type = config?.type ?? exports.TransitionType.NONE;
480
+ const duration = config?.duration ?? 300;
481
+ if (type === exports.TransitionType.NONE || duration <= 0)
482
+ return;
483
+ if (type === exports.TransitionType.FADE) {
484
+ container.alpha = 0;
485
+ await Tween.to(container, { alpha: 1 }, duration, config?.easing);
486
+ }
487
+ else if (type === exports.TransitionType.SLIDE_LEFT) {
488
+ container.x = this._width;
489
+ await Tween.to(container, { x: 0 }, duration, config?.easing);
490
+ }
491
+ else if (type === exports.TransitionType.SLIDE_RIGHT) {
492
+ container.x = -this._width;
493
+ await Tween.to(container, { x: 0 }, duration, config?.easing);
494
+ }
495
+ }
496
+ async transitionOut(container, config) {
497
+ const type = config?.type ?? exports.TransitionType.FADE;
498
+ const duration = config?.duration ?? 300;
499
+ if (type === exports.TransitionType.NONE || duration <= 0)
500
+ return;
501
+ if (type === exports.TransitionType.FADE) {
502
+ await Tween.to(container, { alpha: 0 }, duration, config?.easing);
503
+ }
504
+ else if (type === exports.TransitionType.SLIDE_LEFT) {
505
+ await Tween.to(container, { x: -this._width }, duration, config?.easing);
506
+ }
507
+ else if (type === exports.TransitionType.SLIDE_RIGHT) {
508
+ await Tween.to(container, { x: this._width }, duration, config?.easing);
509
+ }
510
+ }
511
+ }
512
+
513
+ /**
514
+ * Manages game asset loading with progress tracking, bundle support, and
515
+ * automatic base path resolution from SDK's assetsUrl.
516
+ *
517
+ * Wraps PixiJS Assets API with a typed, game-oriented interface.
518
+ *
519
+ * @example
520
+ * ```ts
521
+ * const assets = new AssetManager('https://cdn.example.com/game/', manifest);
522
+ * await assets.init();
523
+ * await assets.loadBundle('preload', (p) => console.log(p));
524
+ * const texture = assets.get<Texture>('hero');
525
+ * ```
526
+ */
527
+ class AssetManager {
528
+ _initialized = false;
529
+ _basePath;
530
+ _manifest;
531
+ _loadedBundles = new Set();
532
+ constructor(basePath = '', manifest) {
533
+ this._basePath = basePath;
534
+ this._manifest = manifest ?? null;
535
+ }
536
+ /** Whether the asset system has been initialized */
537
+ get initialized() {
538
+ return this._initialized;
539
+ }
540
+ /** Base path for all assets (usually from SDK's assetsUrl) */
541
+ get basePath() {
542
+ return this._basePath;
543
+ }
544
+ /** Set of loaded bundle names */
545
+ get loadedBundles() {
546
+ return this._loadedBundles;
547
+ }
548
+ /**
549
+ * Initialize the asset system.
550
+ * Must be called before loading any assets.
551
+ */
552
+ async init() {
553
+ if (this._initialized)
554
+ return;
555
+ await pixi_js.Assets.init({
556
+ basePath: this._basePath || undefined,
557
+ texturePreference: {
558
+ resolution: Math.min(window.devicePixelRatio, 2),
559
+ format: ['webp', 'png'],
560
+ },
561
+ });
562
+ // Register bundles from manifest
563
+ if (this._manifest) {
564
+ for (const bundle of this._manifest.bundles) {
565
+ pixi_js.Assets.addBundle(bundle.name, bundle.assets.map((a) => ({
566
+ alias: a.alias,
567
+ src: a.src,
568
+ data: a.data,
569
+ })));
570
+ }
571
+ }
572
+ this._initialized = true;
573
+ }
574
+ /**
575
+ * Load a single bundle by name.
576
+ *
577
+ * @param name - Bundle name (must exist in the manifest)
578
+ * @param onProgress - Progress callback (0..1)
579
+ * @returns Loaded assets map
580
+ */
581
+ async loadBundle(name, onProgress) {
582
+ this.ensureInitialized();
583
+ const result = await pixi_js.Assets.loadBundle(name, onProgress);
584
+ this._loadedBundles.add(name);
585
+ return result;
586
+ }
587
+ /**
588
+ * Load multiple bundles simultaneously.
589
+ * Progress is aggregated across all bundles.
590
+ *
591
+ * @param names - Bundle names
592
+ * @param onProgress - Progress callback (0..1)
593
+ */
594
+ async loadBundles(names, onProgress) {
595
+ this.ensureInitialized();
596
+ const result = await pixi_js.Assets.loadBundle(names, onProgress);
597
+ for (const name of names) {
598
+ this._loadedBundles.add(name);
599
+ }
600
+ return result;
601
+ }
602
+ /**
603
+ * Load individual assets by URL or alias.
604
+ *
605
+ * @param urls - Asset URLs or aliases
606
+ * @param onProgress - Progress callback (0..1)
607
+ */
608
+ async load(urls, onProgress) {
609
+ this.ensureInitialized();
610
+ return pixi_js.Assets.load(urls, onProgress);
611
+ }
612
+ /**
613
+ * Get a loaded asset synchronously from cache.
614
+ *
615
+ * @param alias - Asset alias
616
+ * @throws if not loaded
617
+ */
618
+ get(alias) {
619
+ return pixi_js.Assets.get(alias);
620
+ }
621
+ /**
622
+ * Unload a bundle to free memory.
623
+ */
624
+ async unloadBundle(name) {
625
+ await pixi_js.Assets.unloadBundle(name);
626
+ this._loadedBundles.delete(name);
627
+ }
628
+ /**
629
+ * Start background loading a bundle (low-priority preload).
630
+ * Useful for loading bonus round assets while player is in base game.
631
+ */
632
+ async backgroundLoad(name) {
633
+ this.ensureInitialized();
634
+ await pixi_js.Assets.backgroundLoadBundle(name);
635
+ }
636
+ /**
637
+ * Get all bundle names from the manifest.
638
+ */
639
+ getBundleNames() {
640
+ return this._manifest?.bundles.map((b) => b.name) ?? [];
641
+ }
642
+ /**
643
+ * Check if a bundle is loaded.
644
+ */
645
+ isBundleLoaded(name) {
646
+ return this._loadedBundles.has(name);
647
+ }
648
+ ensureInitialized() {
649
+ if (!this._initialized) {
650
+ throw new Error('[AssetManager] Not initialized. Call init() first.');
651
+ }
652
+ }
653
+ }
654
+
655
+ /**
656
+ * Manages all game audio: music, SFX, UI sounds, ambient.
657
+ *
658
+ * Optional dependency on @pixi/sound — if not installed, AudioManager
659
+ * operates as a silent no-op (graceful degradation).
660
+ *
661
+ * Features:
662
+ * - Per-category volume control (music, sfx, ui, ambient)
663
+ * - Music crossfade and looping
664
+ * - Mobile audio unlock on first interaction
665
+ * - Mute state persistence in localStorage
666
+ * - Global mute/unmute
667
+ *
668
+ * @example
669
+ * ```ts
670
+ * const audio = new AudioManager({ music: 0.5, sfx: 0.8 });
671
+ * await audio.init();
672
+ * audio.playMusic('bg-music');
673
+ * audio.play('spin-click', 'sfx');
674
+ * ```
675
+ */
676
+ class AudioManager {
677
+ _soundModule = null;
678
+ _initialized = false;
679
+ _globalMuted = false;
680
+ _persist;
681
+ _storageKey;
682
+ _categories;
683
+ _currentMusic = null;
684
+ _unlocked = false;
685
+ _unlockHandler = null;
686
+ constructor(config) {
687
+ this._persist = config?.persist ?? true;
688
+ this._storageKey = config?.storageKey ?? 'ge_audio';
689
+ this._categories = {
690
+ music: { volume: config?.music ?? 0.7, muted: false },
691
+ sfx: { volume: config?.sfx ?? 1.0, muted: false },
692
+ ui: { volume: config?.ui ?? 0.8, muted: false },
693
+ ambient: { volume: config?.ambient ?? 0.5, muted: false },
694
+ };
695
+ // Restore persisted state
696
+ if (this._persist) {
697
+ this.restoreState();
698
+ }
699
+ }
700
+ /** Whether the audio system is initialized */
701
+ get initialized() {
702
+ return this._initialized;
703
+ }
704
+ /** Whether audio is globally muted */
705
+ get muted() {
706
+ return this._globalMuted;
707
+ }
708
+ /**
709
+ * Initialize the audio system.
710
+ * Dynamically imports @pixi/sound to keep it optional.
711
+ */
712
+ async init() {
713
+ if (this._initialized)
714
+ return;
715
+ try {
716
+ this._soundModule = await import('@pixi/sound');
717
+ this._initialized = true;
718
+ this.applyVolumes();
719
+ this.setupMobileUnlock();
720
+ }
721
+ catch {
722
+ console.warn('[AudioManager] @pixi/sound not available. Audio disabled.');
723
+ this._initialized = false;
724
+ }
725
+ }
726
+ /**
727
+ * Play a sound effect.
728
+ *
729
+ * @param alias - Sound alias (must be loaded via AssetManager)
730
+ * @param category - Audio category (default: 'sfx')
731
+ * @param options - Additional play options
732
+ */
733
+ play(alias, category = 'sfx', options) {
734
+ if (!this._initialized || !this._soundModule)
735
+ return;
736
+ if (this._globalMuted || this._categories[category].muted)
737
+ return;
738
+ const { sound } = this._soundModule;
739
+ const vol = (options?.volume ?? 1) * this._categories[category].volume;
740
+ try {
741
+ sound.play(alias, {
742
+ volume: vol,
743
+ loop: options?.loop ?? false,
744
+ speed: options?.speed ?? 1,
745
+ });
746
+ }
747
+ catch (e) {
748
+ console.warn(`[AudioManager] Failed to play "${alias}":`, e);
749
+ }
750
+ }
751
+ /**
752
+ * Play background music with optional crossfade.
753
+ *
754
+ * @param alias - Music alias
755
+ * @param fadeDuration - Crossfade duration in ms (default: 500)
756
+ */
757
+ playMusic(alias, fadeDuration = 500) {
758
+ if (!this._initialized || !this._soundModule)
759
+ return;
760
+ const { sound } = this._soundModule;
761
+ // Stop current music
762
+ if (this._currentMusic) {
763
+ try {
764
+ sound.stop(this._currentMusic);
765
+ }
766
+ catch {
767
+ // ignore
768
+ }
769
+ }
770
+ this._currentMusic = alias;
771
+ if (this._globalMuted || this._categories.music.muted)
772
+ return;
773
+ try {
774
+ sound.play(alias, {
775
+ volume: this._categories.music.volume,
776
+ loop: true,
777
+ });
778
+ }
779
+ catch (e) {
780
+ console.warn(`[AudioManager] Failed to play music "${alias}":`, e);
781
+ }
782
+ }
783
+ /**
784
+ * Stop current music.
785
+ */
786
+ stopMusic() {
787
+ if (!this._initialized || !this._soundModule || !this._currentMusic)
788
+ return;
789
+ const { sound } = this._soundModule;
790
+ try {
791
+ sound.stop(this._currentMusic);
792
+ }
793
+ catch {
794
+ // ignore
795
+ }
796
+ this._currentMusic = null;
797
+ }
798
+ /**
799
+ * Stop all sounds.
800
+ */
801
+ stopAll() {
802
+ if (!this._initialized || !this._soundModule)
803
+ return;
804
+ const { sound } = this._soundModule;
805
+ sound.stopAll();
806
+ this._currentMusic = null;
807
+ }
808
+ /**
809
+ * Set volume for a category.
810
+ */
811
+ setVolume(category, volume) {
812
+ this._categories[category].volume = Math.max(0, Math.min(1, volume));
813
+ this.applyVolumes();
814
+ this.saveState();
815
+ }
816
+ /**
817
+ * Get volume for a category.
818
+ */
819
+ getVolume(category) {
820
+ return this._categories[category].volume;
821
+ }
822
+ /**
823
+ * Mute a specific category.
824
+ */
825
+ muteCategory(category) {
826
+ this._categories[category].muted = true;
827
+ this.applyVolumes();
828
+ this.saveState();
829
+ }
830
+ /**
831
+ * Unmute a specific category.
832
+ */
833
+ unmuteCategory(category) {
834
+ this._categories[category].muted = false;
835
+ this.applyVolumes();
836
+ this.saveState();
837
+ }
838
+ /**
839
+ * Toggle mute for a category.
840
+ */
841
+ toggleCategory(category) {
842
+ this._categories[category].muted = !this._categories[category].muted;
843
+ this.applyVolumes();
844
+ this.saveState();
845
+ return this._categories[category].muted;
846
+ }
847
+ /**
848
+ * Mute all audio globally.
849
+ */
850
+ muteAll() {
851
+ this._globalMuted = true;
852
+ if (this._soundModule) {
853
+ this._soundModule.sound.muteAll();
854
+ }
855
+ this.saveState();
856
+ }
857
+ /**
858
+ * Unmute all audio globally.
859
+ */
860
+ unmuteAll() {
861
+ this._globalMuted = false;
862
+ if (this._soundModule) {
863
+ this._soundModule.sound.unmuteAll();
864
+ }
865
+ this.saveState();
866
+ }
867
+ /**
868
+ * Toggle global mute.
869
+ */
870
+ toggleMute() {
871
+ if (this._globalMuted) {
872
+ this.unmuteAll();
873
+ }
874
+ else {
875
+ this.muteAll();
876
+ }
877
+ return this._globalMuted;
878
+ }
879
+ /**
880
+ * Duck music volume (e.g., during big win presentation).
881
+ *
882
+ * @param factor - Volume multiplier (0..1), e.g. 0.3 = 30% of normal
883
+ */
884
+ duckMusic(factor) {
885
+ if (!this._initialized || !this._soundModule || !this._currentMusic)
886
+ return;
887
+ const { sound } = this._soundModule;
888
+ const vol = this._categories.music.volume * factor;
889
+ try {
890
+ sound.volume(this._currentMusic, vol);
891
+ }
892
+ catch {
893
+ // ignore
894
+ }
895
+ }
896
+ /**
897
+ * Restore music to normal volume after ducking.
898
+ */
899
+ unduckMusic() {
900
+ if (!this._initialized || !this._soundModule || !this._currentMusic)
901
+ return;
902
+ const { sound } = this._soundModule;
903
+ try {
904
+ sound.volume(this._currentMusic, this._categories.music.volume);
905
+ }
906
+ catch {
907
+ // ignore
908
+ }
909
+ }
910
+ /**
911
+ * Destroy the audio manager and free resources.
912
+ */
913
+ destroy() {
914
+ this.stopAll();
915
+ this.removeMobileUnlock();
916
+ if (this._soundModule) {
917
+ this._soundModule.sound.removeAll();
918
+ }
919
+ this._initialized = false;
920
+ }
921
+ // ─── Private ───────────────────────────────────────────
922
+ applyVolumes() {
923
+ if (!this._soundModule)
924
+ return;
925
+ const { sound } = this._soundModule;
926
+ sound.volumeAll = this._globalMuted ? 0 : 1;
927
+ }
928
+ setupMobileUnlock() {
929
+ if (this._unlocked)
930
+ return;
931
+ this._unlockHandler = () => {
932
+ if (!this._soundModule)
933
+ return;
934
+ const { sound } = this._soundModule;
935
+ // Resume WebAudio context
936
+ if (sound.context?.audioContext?.state === 'suspended') {
937
+ sound.context.audioContext.resume();
938
+ }
939
+ this._unlocked = true;
940
+ this.removeMobileUnlock();
941
+ };
942
+ const events = ['touchstart', 'mousedown', 'pointerdown', 'keydown'];
943
+ for (const event of events) {
944
+ document.addEventListener(event, this._unlockHandler, { once: true });
945
+ }
946
+ }
947
+ removeMobileUnlock() {
948
+ if (!this._unlockHandler)
949
+ return;
950
+ const events = ['touchstart', 'mousedown', 'pointerdown', 'keydown'];
951
+ for (const event of events) {
952
+ document.removeEventListener(event, this._unlockHandler);
953
+ }
954
+ this._unlockHandler = null;
955
+ }
956
+ saveState() {
957
+ if (!this._persist)
958
+ return;
959
+ try {
960
+ const state = {
961
+ globalMuted: this._globalMuted,
962
+ categories: this._categories,
963
+ };
964
+ localStorage.setItem(this._storageKey, JSON.stringify(state));
965
+ }
966
+ catch {
967
+ // localStorage may not be available
968
+ }
969
+ }
970
+ restoreState() {
971
+ try {
972
+ const raw = localStorage.getItem(this._storageKey);
973
+ if (!raw)
974
+ return;
975
+ const state = JSON.parse(raw);
976
+ if (typeof state.globalMuted === 'boolean') {
977
+ this._globalMuted = state.globalMuted;
978
+ }
979
+ if (state.categories) {
980
+ for (const key of ['music', 'sfx', 'ui', 'ambient']) {
981
+ if (state.categories[key]) {
982
+ this._categories[key] = {
983
+ volume: state.categories[key].volume ?? this._categories[key].volume,
984
+ muted: state.categories[key].muted ?? false,
985
+ };
986
+ }
987
+ }
988
+ }
989
+ }
990
+ catch {
991
+ // ignore
992
+ }
993
+ }
994
+ }
995
+
996
+ /**
997
+ * Manages responsive scaling of the game canvas to fit its container.
998
+ *
999
+ * Supports three scale modes:
1000
+ * - **FIT** — letterbox/pillarbox to maintain aspect ratio (industry standard)
1001
+ * - **FILL** — fill container, crop edges
1002
+ * - **STRETCH** — stretch to fill (distorts)
1003
+ *
1004
+ * Also handles:
1005
+ * - Orientation detection (landscape/portrait)
1006
+ * - Safe areas (mobile notch)
1007
+ * - ResizeObserver for smooth container resizing
1008
+ *
1009
+ * @example
1010
+ * ```ts
1011
+ * const viewport = new ViewportManager(app, container, {
1012
+ * designWidth: 1920,
1013
+ * designHeight: 1080,
1014
+ * scaleMode: ScaleMode.FIT,
1015
+ * orientation: Orientation.LANDSCAPE,
1016
+ * });
1017
+ *
1018
+ * viewport.on('resize', ({ width, height, scale }) => {
1019
+ * console.log(`New size: ${width}x${height} @ ${scale}x`);
1020
+ * });
1021
+ * ```
1022
+ */
1023
+ class ViewportManager extends EventEmitter {
1024
+ _app;
1025
+ _container;
1026
+ _config;
1027
+ _resizeObserver = null;
1028
+ _currentOrientation = exports.Orientation.LANDSCAPE;
1029
+ _currentWidth = 0;
1030
+ _currentHeight = 0;
1031
+ _currentScale = 1;
1032
+ _destroyed = false;
1033
+ _resizeTimeout = null;
1034
+ constructor(app, container, config) {
1035
+ super();
1036
+ this._app = app;
1037
+ this._container = container;
1038
+ this._config = config;
1039
+ this.setupObserver();
1040
+ }
1041
+ /** Current canvas width in game units */
1042
+ get width() {
1043
+ return this._currentWidth;
1044
+ }
1045
+ /** Current canvas height in game units */
1046
+ get height() {
1047
+ return this._currentHeight;
1048
+ }
1049
+ /** Current scale factor */
1050
+ get scale() {
1051
+ return this._currentScale;
1052
+ }
1053
+ /** Current orientation */
1054
+ get orientation() {
1055
+ return this._currentOrientation;
1056
+ }
1057
+ /** Design reference width */
1058
+ get designWidth() {
1059
+ return this._config.designWidth;
1060
+ }
1061
+ /** Design reference height */
1062
+ get designHeight() {
1063
+ return this._config.designHeight;
1064
+ }
1065
+ /**
1066
+ * Force a resize calculation. Called automatically on container size change.
1067
+ */
1068
+ refresh() {
1069
+ if (this._destroyed)
1070
+ return;
1071
+ const containerWidth = this._container.clientWidth || window.innerWidth;
1072
+ const containerHeight = this._container.clientHeight || window.innerHeight;
1073
+ if (containerWidth === 0 || containerHeight === 0)
1074
+ return;
1075
+ const { designWidth, designHeight, scaleMode } = this._config;
1076
+ const designRatio = designWidth / designHeight;
1077
+ const containerRatio = containerWidth / containerHeight;
1078
+ let gameWidth;
1079
+ let gameHeight;
1080
+ let scale;
1081
+ switch (scaleMode) {
1082
+ case exports.ScaleMode.FIT: {
1083
+ if (containerRatio > designRatio) {
1084
+ // Container is wider → pillarbox
1085
+ scale = containerHeight / designHeight;
1086
+ gameWidth = designWidth;
1087
+ gameHeight = designHeight;
1088
+ }
1089
+ else {
1090
+ // Container is taller → letterbox
1091
+ scale = containerWidth / designWidth;
1092
+ gameWidth = designWidth;
1093
+ gameHeight = designHeight;
1094
+ }
1095
+ break;
1096
+ }
1097
+ case exports.ScaleMode.FILL: {
1098
+ if (containerRatio > designRatio) {
1099
+ // Container is wider → crop top/bottom
1100
+ scale = containerWidth / designWidth;
1101
+ }
1102
+ else {
1103
+ // Container is taller → crop left/right
1104
+ scale = containerHeight / designHeight;
1105
+ }
1106
+ gameWidth = containerWidth / scale;
1107
+ gameHeight = containerHeight / scale;
1108
+ break;
1109
+ }
1110
+ case exports.ScaleMode.STRETCH: {
1111
+ gameWidth = designWidth;
1112
+ gameHeight = designHeight;
1113
+ scale = 1; // stretch is handled by CSS
1114
+ break;
1115
+ }
1116
+ default:
1117
+ gameWidth = designWidth;
1118
+ gameHeight = designHeight;
1119
+ scale = 1;
1120
+ }
1121
+ // Resize the renderer
1122
+ this._app.renderer.resize(Math.round(containerWidth), Math.round(containerHeight));
1123
+ // Scale the stage
1124
+ const stageScale = scaleMode === exports.ScaleMode.STRETCH
1125
+ ? Math.min(containerWidth / designWidth, containerHeight / designHeight)
1126
+ : scale;
1127
+ this._app.stage.scale.set(stageScale);
1128
+ // Center the stage for FIT mode
1129
+ if (scaleMode === exports.ScaleMode.FIT) {
1130
+ this._app.stage.x = Math.round((containerWidth - designWidth * stageScale) / 2);
1131
+ this._app.stage.y = Math.round((containerHeight - designHeight * stageScale) / 2);
1132
+ }
1133
+ else if (scaleMode === exports.ScaleMode.FILL) {
1134
+ this._app.stage.x = Math.round((containerWidth - gameWidth * stageScale) / 2);
1135
+ this._app.stage.y = Math.round((containerHeight - gameHeight * stageScale) / 2);
1136
+ }
1137
+ else {
1138
+ this._app.stage.x = 0;
1139
+ this._app.stage.y = 0;
1140
+ }
1141
+ this._currentWidth = gameWidth;
1142
+ this._currentHeight = gameHeight;
1143
+ this._currentScale = stageScale;
1144
+ // Check orientation
1145
+ const newOrientation = containerWidth >= containerHeight ? exports.Orientation.LANDSCAPE : exports.Orientation.PORTRAIT;
1146
+ if (newOrientation !== this._currentOrientation) {
1147
+ this._currentOrientation = newOrientation;
1148
+ this.emit('orientationChange', newOrientation);
1149
+ }
1150
+ this.emit('resize', {
1151
+ width: gameWidth,
1152
+ height: gameHeight,
1153
+ scale: stageScale,
1154
+ });
1155
+ }
1156
+ /**
1157
+ * Destroy the viewport manager.
1158
+ */
1159
+ destroy() {
1160
+ this._destroyed = true;
1161
+ this._resizeObserver?.disconnect();
1162
+ this._resizeObserver = null;
1163
+ if (this._resizeTimeout !== null) {
1164
+ clearTimeout(this._resizeTimeout);
1165
+ }
1166
+ this.removeAllListeners();
1167
+ }
1168
+ // ─── Private ───────────────────────────────────────────
1169
+ setupObserver() {
1170
+ if (typeof ResizeObserver !== 'undefined') {
1171
+ this._resizeObserver = new ResizeObserver(() => {
1172
+ this.debouncedRefresh();
1173
+ });
1174
+ this._resizeObserver.observe(this._container);
1175
+ }
1176
+ else {
1177
+ // Fallback for older browsers
1178
+ window.addEventListener('resize', this.onWindowResize);
1179
+ }
1180
+ }
1181
+ onWindowResize = () => {
1182
+ this.debouncedRefresh();
1183
+ };
1184
+ debouncedRefresh() {
1185
+ if (this._resizeTimeout !== null) {
1186
+ clearTimeout(this._resizeTimeout);
1187
+ }
1188
+ this._resizeTimeout = window.setTimeout(() => {
1189
+ this.refresh();
1190
+ this._resizeTimeout = null;
1191
+ }, 16); // ~1 frame
1192
+ }
1193
+ }
1194
+
1195
+ /**
1196
+ * Base class for all scenes.
1197
+ * Provides a root PixiJS Container and lifecycle hooks.
1198
+ *
1199
+ * @example
1200
+ * ```ts
1201
+ * class MenuScene extends Scene {
1202
+ * async onEnter() {
1203
+ * const bg = Sprite.from('menu-bg');
1204
+ * this.container.addChild(bg);
1205
+ * }
1206
+ *
1207
+ * onUpdate(dt: number) {
1208
+ * // per-frame logic
1209
+ * }
1210
+ *
1211
+ * onResize(width: number, height: number) {
1212
+ * // reposition UI
1213
+ * }
1214
+ * }
1215
+ * ```
1216
+ */
1217
+ class Scene {
1218
+ container;
1219
+ constructor() {
1220
+ this.container = new pixi_js.Container();
1221
+ this.container.label = this.constructor.name;
1222
+ }
1223
+ }
1224
+
1225
+ /**
1226
+ * Inline SVG logo with a loader bar (clip-animated for progress).
1227
+ * The clipPath rect width is set to 0 initially, expanded as loading progresses.
1228
+ */
1229
+ function buildLogoSVG() {
1230
+ return `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 250 200" fill="none" style="width:100%;height:auto;">
1231
+ <path d="m241 81.75h-19.28c-1.77 0-6.73 4.98-7.43 6.99l-4.36 12.22c-0.49 1.37 0.05 2.92 1.06 4.32-2.07 1.19-3.69 3.08-4.36 5.43l-3.25 10.41c-0.86 2.89 2.39 6.63 4.31 6.63h19.28c1.96 0 7.4-5.56 7.96-7.51l2.96-10.22c0.63-2.25 0.1-3.98-1.22-4.99 2.55-1.56 3.86-4.14 4.55-6.31l2.77-9.31c0.74-2.57-1.37-7.66-2.99-7.66zm-13.36 28.31-2.27 7.03h-8.28l2.58-8.28h8.28l-0.31 1.25zm4.06-16.97-2.11 6.7h-7.04l2.25-7.34h7.26l-0.36 0.64z" fill="url(#ls0)"/>
1232
+ <path d="m202.5 81.75-9.31 14.97-2.32-14.97h-11.82l4.32 25.15-0.57 4.91-8.64 26.44 15.31-12.76 5.63-16.48 19.96-27.26h-12.56z" fill="url(#ls1)"/>
1233
+ <path d="m174.2 81.75h-19.78l-5.75 5.16-10.79 33.2c-0.77 2.53 2.48 6.93 4.87 6.93h17.38c2.63 0 7.85-5.34 8.32-6.83l5.37-18.14h-15.17l-2.2 7.64h3.78l-2.25 7.2h-8.01l7.1-25.52h7.58l-1.48 8.4 12.78-5.98c1.28-0.63 1.97-3.99 1.61-6.61-0.36-2.34-1.64-5.45-3.36-5.45z" fill="url(#ls2)"/>
1234
+ <path d="m140.6 81.75h-70.6l-5.36 19.37-4.26-19.37h-46.76l2.95 5.88-10.58 39.28h26.84l2.95-9.52-15.63-0.13 2.55-8.34h8.74l8.47-9.81h-14.61l2.11-7.3h15.47l2.54-8.71 2.58 4.74-11.4 39.07h11.05l6.46-21.49 8.84 36.33 19.18-55.67-1.83-3.36 3.68 4.09-12.07 40.1h28.18l3.39-10.31h-17.01l2.67-8.03h9.98l7.58-9.52h-14.28l1.93-6.6h14.61l3.25-9.73 2.81 5.12-11.3 38.89h11.05l5.23-17.81h1.62l1.48 17.6h10.69l-1.48-16.81c4.75-1.28 7.52-5.9 8.64-9.81l2.95-11.3c0.86-2.73-1.43-6.85-3.3-6.85zm-9.8 17.3h-8.69l2.54-7.84h8.35l-2.2 7.84z" fill="url(#ls3)"/>
1235
+ <path d="m205.9 148.9h-122.6l-2.61-3.12h-32.4l-2.51 3.12h-1.59c-5.34 0-7.94 4.88-7.94 7.65v0.03c0 4.2 3.55 7.6 7.74 7.6h103.6l2.11 3.12h36.09l1.82-3.12h18.3c5.25 0 6.64-5.3 6.64-7.35v-0.25c0-4.23-2.9-7.68-6.64-7.68zm-0.7 12.83h-160.6c-3.69 0-6.11-2.58-6.11-5.47v-0.03c0-2.89 2.1-5.47 5.61-5.47h161.1c3.45 0 4.89 3.12 4.89 5.65v0.17c0 2.57-2.11 5.15-4.89 5.15z" fill="url(#ls4)"/>
1236
+ <clipPath id="ge-canvas-loader-clip">
1237
+ <rect id="ge-loader-rect" x="37" y="148" width="0" height="20"/>
1238
+ </clipPath>
1239
+ <path d="m204.5 152.6h-159.8c-2.78 0-4.45 1.69-4.45 3.99v0.11c0 2.04 1.42 3.43 3.64 3.43h160.6c2.88 0 3.67-2.07 3.67-3.43v-0.25c0-2.04-1.48-3.85-3.67-3.85z" fill="url(#ls5)" clip-path="url(#ge-canvas-loader-clip)"/>
1240
+ <text id="ge-loader-pct" x="125" y="196" text-anchor="middle" fill="rgba(255,255,255,0.7)" font-family="-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,sans-serif" font-size="8" font-weight="600" letter-spacing="1.5">0%</text>
1241
+ <defs>
1242
+ <linearGradient id="ls0" x1="223.7" x2="223.7" y1="81.75" y2="127.8" gradientUnits="userSpaceOnUse">
1243
+ <stop stop-color="#663BA6"/><stop stop-color="#7939C2" offset=".349"/><stop stop-color="#8A2FC0" offset=".6615"/><stop stop-color="#791BA3" offset="1"/>
1244
+ </linearGradient>
1245
+ <linearGradient id="ls1" x1="194.6" x2="194.6" y1="81.75" y2="138.3" gradientUnits="userSpaceOnUse">
1246
+ <stop stop-color="#663BA6"/><stop stop-color="#7939C2" offset=".349"/><stop stop-color="#8A2FC0" offset=".6615"/><stop stop-color="#791BA3" offset="1"/>
1247
+ </linearGradient>
1248
+ <linearGradient id="ls2" x1="157.8" x2="157.8" y1="81.75" y2="127" gradientUnits="userSpaceOnUse">
1249
+ <stop stop-color="#663BA6"/><stop stop-color="#7939C2" offset=".349"/><stop stop-color="#8A2FC0" offset=".6615"/><stop stop-color="#791BA3" offset="1"/>
1250
+ </linearGradient>
1251
+ <linearGradient id="ls3" x1="79.96" x2="79.96" y1="81.75" y2="141.8" gradientUnits="userSpaceOnUse">
1252
+ <stop stop-color="#663BA6"/><stop stop-color="#7939C2" offset=".349"/><stop stop-color="#8A2FC0" offset=".6615"/><stop stop-color="#791BA3" offset="1"/>
1253
+ </linearGradient>
1254
+ <linearGradient id="ls4" x1="36.18" x2="212.5" y1="156.6" y2="156.6" gradientUnits="userSpaceOnUse">
1255
+ <stop stop-color="#316FB0"/><stop stop-color="#1FCDE6" offset=".5"/><stop stop-color="#29FEE7" offset="1"/>
1256
+ </linearGradient>
1257
+ <linearGradient id="ls5" x1="40.27" x2="208.2" y1="156.4" y2="156.4" gradientUnits="userSpaceOnUse">
1258
+ <stop stop-color="#316FB0"/><stop stop-color="#1FCDE6" offset=".5"/><stop stop-color="#29FEE7" offset="1"/>
1259
+ </linearGradient>
1260
+ </defs>
1261
+ </svg>`;
1262
+ }
1263
+ /** Max width of the loader bar in SVG units */
1264
+ const LOADER_BAR_MAX_WIDTH = 174;
1265
+ /**
1266
+ * Built-in loading screen using the Energy8 SVG logo with animated loader bar.
1267
+ *
1268
+ * Renders as an HTML overlay on top of the canvas for crisp SVG quality.
1269
+ * The loader bar fill width is driven by asset loading progress.
1270
+ */
1271
+ class LoadingScene extends Scene {
1272
+ _engine;
1273
+ _targetScene;
1274
+ _targetData;
1275
+ _config;
1276
+ // HTML overlay
1277
+ _overlay = null;
1278
+ _loaderRect = null;
1279
+ _percentEl = null;
1280
+ _tapToStartEl = null;
1281
+ // State
1282
+ _displayedProgress = 0;
1283
+ _targetProgress = 0;
1284
+ _loadingComplete = false;
1285
+ _startTime = 0;
1286
+ async onEnter(data) {
1287
+ const { engine, targetScene, targetData } = data;
1288
+ this._engine = engine;
1289
+ this._targetScene = targetScene;
1290
+ this._targetData = targetData;
1291
+ this._config = engine.config.loading ?? {};
1292
+ this._startTime = Date.now();
1293
+ // Create the HTML overlay with the SVG logo
1294
+ this.createOverlay();
1295
+ // Initialize asset manager
1296
+ await this._engine.assets.init();
1297
+ // Initialize audio manager
1298
+ await this._engine.audio.init();
1299
+ // Phase 1: Load preload bundle
1300
+ const bundles = this._engine.assets.getBundleNames();
1301
+ const hasPreload = bundles.includes('preload');
1302
+ if (hasPreload) {
1303
+ const preloadAssets = this._engine.config.manifest?.bundles?.find((b) => b.name === 'preload')?.assets;
1304
+ if (preloadAssets && preloadAssets.length > 0) {
1305
+ await this._engine.assets.loadBundle('preload', (p) => {
1306
+ this._targetProgress = p * 0.15;
1307
+ });
1308
+ }
1309
+ else {
1310
+ this._targetProgress = 0.15;
1311
+ }
1312
+ }
1313
+ // Phase 2: Load remaining bundles
1314
+ const remainingBundles = bundles.filter((b) => b !== 'preload' && !this._engine.assets.isBundleLoaded(b));
1315
+ if (remainingBundles.length > 0) {
1316
+ const hasAssets = remainingBundles.some((name) => {
1317
+ const bundle = this._engine.config.manifest?.bundles?.find((b) => b.name === name);
1318
+ return bundle?.assets && bundle.assets.length > 0;
1319
+ });
1320
+ if (hasAssets) {
1321
+ await this._engine.assets.loadBundles(remainingBundles, (p) => {
1322
+ this._targetProgress = 0.15 + p * 0.85;
1323
+ });
1324
+ }
1325
+ }
1326
+ this._targetProgress = 1;
1327
+ this._loadingComplete = true;
1328
+ // Enforce minimum display time: spread the remaining progress fill
1329
+ // over the remaining time so the bar fills smoothly, not abruptly
1330
+ const minTime = this._config.minDisplayTime ?? 1500;
1331
+ const elapsed = Date.now() - this._startTime;
1332
+ const remaining = Math.max(0, minTime - elapsed);
1333
+ if (remaining > 0) {
1334
+ // Distribute fill animation over the remaining time
1335
+ await this.animateProgressTo(1, remaining);
1336
+ }
1337
+ // Final snap to 100%
1338
+ this._displayedProgress = 1;
1339
+ this.updateLoaderBar(1);
1340
+ // Show "Tap to Start" or transition directly
1341
+ if (this._config.tapToStart !== false) {
1342
+ await this.showTapToStart();
1343
+ }
1344
+ else {
1345
+ await this.transitionToGame();
1346
+ }
1347
+ }
1348
+ onUpdate(dt) {
1349
+ // Smooth progress bar fill via HTML (during active loading)
1350
+ if (!this._loadingComplete && this._displayedProgress < this._targetProgress) {
1351
+ this._displayedProgress = Math.min(this._displayedProgress + dt * 1.5, this._targetProgress);
1352
+ this.updateLoaderBar(this._displayedProgress);
1353
+ }
1354
+ }
1355
+ onResize(_width, _height) {
1356
+ // Overlay is CSS-based, auto-resizes
1357
+ }
1358
+ onDestroy() {
1359
+ this.removeOverlay();
1360
+ }
1361
+ // ─── HTML Overlay ──────────────────────────────────────
1362
+ createOverlay() {
1363
+ const bgColor = typeof this._config.backgroundColor === 'string'
1364
+ ? this._config.backgroundColor
1365
+ : typeof this._config.backgroundColor === 'number'
1366
+ ? `#${this._config.backgroundColor.toString(16).padStart(6, '0')}`
1367
+ : '#0a0a1a';
1368
+ const bgGradient = this._config.backgroundGradient ??
1369
+ `linear-gradient(135deg, ${bgColor} 0%, #1a1a3e 100%)`;
1370
+ this._overlay = document.createElement('div');
1371
+ this._overlay.id = '__ge-loading-overlay__';
1372
+ this._overlay.innerHTML = `
1373
+ <div class="ge-loading-content">
1374
+ ${buildLogoSVG()}
1375
+ </div>
1376
+ `;
1377
+ const style = document.createElement('style');
1378
+ style.id = '__ge-loading-style__';
1379
+ style.textContent = `
1380
+ #__ge-loading-overlay__ {
1381
+ position: absolute;
1382
+ top: 0; left: 0;
1383
+ width: 100%; height: 100%;
1384
+ background: ${bgGradient};
1385
+ display: flex;
1386
+ align-items: center;
1387
+ justify-content: center;
1388
+ z-index: 9999;
1389
+ transition: opacity 0.5s ease-out;
1390
+ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
1391
+ }
1392
+ #__ge-loading-overlay__.ge-fade-out {
1393
+ opacity: 0;
1394
+ pointer-events: none;
1395
+ }
1396
+ .ge-loading-content {
1397
+ display: flex;
1398
+ flex-direction: column;
1399
+ align-items: center;
1400
+ width: 75%;
1401
+ max-width: 650px;
1402
+ }
1403
+ .ge-loading-content svg {
1404
+ filter: drop-shadow(0 0 40px rgba(121, 57, 194, 0.5));
1405
+ cursor: default;
1406
+ }
1407
+
1408
+ .ge-svg-pulse {
1409
+ animation: ge-tap-pulse 1.2s ease-in-out infinite;
1410
+ }
1411
+ @keyframes ge-tap-pulse {
1412
+ 0%, 100% { opacity: 0.5; }
1413
+ 50% { opacity: 1; }
1414
+ }
1415
+ `;
1416
+ // Get the container that holds the canvas
1417
+ const container = this._engine.app?.canvas?.parentElement;
1418
+ if (container) {
1419
+ container.style.position = container.style.position || 'relative';
1420
+ container.appendChild(style);
1421
+ container.appendChild(this._overlay);
1422
+ }
1423
+ // Cache the SVG loader rect for progress updates
1424
+ this._loaderRect = this._overlay.querySelector('#ge-loader-rect');
1425
+ this._percentEl = this._overlay.querySelector('#ge-loader-pct');
1426
+ }
1427
+ removeOverlay() {
1428
+ this._overlay?.remove();
1429
+ document.getElementById('__ge-loading-style__')?.remove();
1430
+ this._overlay = null;
1431
+ this._loaderRect = null;
1432
+ this._percentEl = null;
1433
+ this._tapToStartEl = null;
1434
+ }
1435
+ // ─── Progress ──────────────────────────────────────────
1436
+ updateLoaderBar(progress) {
1437
+ if (this._loaderRect) {
1438
+ this._loaderRect.setAttribute('width', String(LOADER_BAR_MAX_WIDTH * progress));
1439
+ }
1440
+ if (this._percentEl) {
1441
+ const pct = Math.round(progress * 100);
1442
+ this._percentEl.textContent = `${pct}%`;
1443
+ }
1444
+ }
1445
+ /**
1446
+ * Smoothly animate the displayed progress from its current value to `target`
1447
+ * over `durationMs` using an easeOutCubic curve.
1448
+ */
1449
+ async animateProgressTo(target, durationMs) {
1450
+ const startVal = this._displayedProgress;
1451
+ const delta = target - startVal;
1452
+ if (delta <= 0 || durationMs <= 0)
1453
+ return;
1454
+ const startTime = Date.now();
1455
+ return new Promise((resolve) => {
1456
+ const tick = () => {
1457
+ const elapsed = Date.now() - startTime;
1458
+ const t = Math.min(elapsed / durationMs, 1);
1459
+ // easeOutCubic for a natural deceleration feel
1460
+ const eased = 1 - Math.pow(1 - t, 3);
1461
+ this._displayedProgress = startVal + delta * eased;
1462
+ this.updateLoaderBar(this._displayedProgress);
1463
+ if (t < 1) {
1464
+ requestAnimationFrame(tick);
1465
+ }
1466
+ else {
1467
+ resolve();
1468
+ }
1469
+ };
1470
+ requestAnimationFrame(tick);
1471
+ });
1472
+ }
1473
+ // ─── Tap to Start ─────────────────────────────────────
1474
+ async showTapToStart() {
1475
+ const tapText = this._config.tapToStartText ?? 'TAP TO START';
1476
+ // Reuse the same SVG text element — replace percentage with tap text
1477
+ if (this._percentEl) {
1478
+ const el = this._percentEl;
1479
+ el.textContent = tapText;
1480
+ el.setAttribute('fill', '#ffffff');
1481
+ el.classList.add('ge-svg-pulse');
1482
+ this._tapToStartEl = el;
1483
+ }
1484
+ // Make overlay clickable
1485
+ if (this._overlay) {
1486
+ this._overlay.style.cursor = 'pointer';
1487
+ }
1488
+ // Wait for tap
1489
+ return new Promise((resolve) => {
1490
+ const handler = async () => {
1491
+ this._overlay?.removeEventListener('click', handler);
1492
+ await this.transitionToGame();
1493
+ resolve();
1494
+ };
1495
+ // Listen on the full overlay for easier mobile tap
1496
+ this._overlay?.addEventListener('click', handler);
1497
+ });
1498
+ }
1499
+ // ─── Transition ────────────────────────────────────────
1500
+ async transitionToGame() {
1501
+ // Fade out the HTML overlay
1502
+ if (this._overlay) {
1503
+ this._overlay.classList.add('ge-fade-out');
1504
+ await new Promise((resolve) => {
1505
+ this._overlay.addEventListener('transitionend', () => resolve(), { once: true });
1506
+ // Safety timeout
1507
+ setTimeout(resolve, 600);
1508
+ });
1509
+ }
1510
+ // Remove overlay
1511
+ this.removeOverlay();
1512
+ // Navigate to the target scene
1513
+ await this._engine.scenes.goto(this._targetScene, this._targetData);
1514
+ }
1515
+ }
1516
+
1517
+ const PRELOADER_ID = '__ge-css-preloader__';
1518
+ /**
1519
+ * Inline SVG logo with animated loader bar.
1520
+ * The `#loader` path acts as the progress fill — animated via clipPath.
1521
+ */
1522
+ const LOGO_SVG = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 250 200" fill="none" class="ge-logo-svg">
1523
+ <path d="m241 81.75h-19.28c-1.77 0-6.73 4.98-7.43 6.99l-4.36 12.22c-0.49 1.37 0.05 2.92 1.06 4.32-2.07 1.19-3.69 3.08-4.36 5.43l-3.25 10.41c-0.86 2.89 2.39 6.63 4.31 6.63h19.28c1.96 0 7.4-5.56 7.96-7.51l2.96-10.22c0.63-2.25 0.1-3.98-1.22-4.99 2.55-1.56 3.86-4.14 4.55-6.31l2.77-9.31c0.74-2.57-1.37-7.66-2.99-7.66zm-13.36 28.31-2.27 7.03h-8.28l2.58-8.28h8.28l-0.31 1.25zm4.06-16.97-2.11 6.7h-7.04l2.25-7.34h7.26l-0.36 0.64z" fill="url(#pl0)"/>
1524
+ <path d="m202.5 81.75-9.31 14.97-2.32-14.97h-11.82l4.32 25.15-0.57 4.91-8.64 26.44 15.31-12.76 5.63-16.48 19.96-27.26h-12.56z" fill="url(#pl1)"/>
1525
+ <path d="m174.2 81.75h-19.78l-5.75 5.16-10.79 33.2c-0.77 2.53 2.48 6.93 4.87 6.93h17.38c2.63 0 7.85-5.34 8.32-6.83l5.37-18.14h-15.17l-2.2 7.64h3.78l-2.25 7.2h-8.01l7.1-25.52h7.58l-1.48 8.4 12.78-5.98c1.28-0.63 1.97-3.99 1.61-6.61-0.36-2.34-1.64-5.45-3.36-5.45z" fill="url(#pl2)"/>
1526
+ <path d="m140.6 81.75h-70.6l-5.36 19.37-4.26-19.37h-46.76l2.95 5.88-10.58 39.28h26.84l2.95-9.52-15.63-0.13 2.55-8.34h8.74l8.47-9.81h-14.61l2.11-7.3h15.47l2.54-8.71 2.58 4.74-11.4 39.07h11.05l6.46-21.49 8.84 36.33 19.18-55.67-1.83-3.36 3.68 4.09-12.07 40.1h28.18l3.39-10.31h-17.01l2.67-8.03h9.98l7.58-9.52h-14.28l1.93-6.6h14.61l3.25-9.73 2.81 5.12-11.3 38.89h11.05l5.23-17.81h1.62l1.48 17.6h10.69l-1.48-16.81c4.75-1.28 7.52-5.9 8.64-9.81l2.95-11.3c0.86-2.73-1.43-6.85-3.3-6.85zm-9.8 17.3h-8.69l2.54-7.84h8.35l-2.2 7.84z" fill="url(#pl3)"/>
1527
+ <path d="m205.9 148.9h-122.6l-2.61-3.12h-32.4l-2.51 3.12h-1.59c-5.34 0-7.94 4.88-7.94 7.65v0.03c0 4.2 3.55 7.6 7.74 7.6h103.6l2.11 3.12h36.09l1.82-3.12h18.3c5.25 0 6.64-5.3 6.64-7.35v-0.25c0-4.23-2.9-7.68-6.64-7.68zm-0.7 12.83h-160.6c-3.69 0-6.11-2.58-6.11-5.47v-0.03c0-2.89 2.1-5.47 5.61-5.47h161.1c3.45 0 4.89 3.12 4.89 5.65v0.17c0 2.57-2.11 5.15-4.89 5.15z" fill="url(#pl4)"/>
1528
+ <!-- Loader fill with clip for progress animation -->
1529
+ <clipPath id="ge-loader-clip">
1530
+ <rect x="37" y="148" width="0" height="20" class="ge-clip-rect"/>
1531
+ </clipPath>
1532
+ <path d="m204.5 152.6h-159.8c-2.78 0-4.45 1.69-4.45 3.99v0.11c0 2.04 1.42 3.43 3.64 3.43h160.6c2.88 0 3.67-2.07 3.67-3.43v-0.25c0-2.04-1.48-3.85-3.67-3.85z" fill="url(#pl5)" clip-path="url(#ge-loader-clip)"/>
1533
+ <text x="125" y="196" text-anchor="middle" fill="rgba(255,255,255,0.6)" font-family="-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,sans-serif" font-size="8" font-weight="600" letter-spacing="1.5" class="ge-preloader-svg-text">Loading...</text>
1534
+ <defs>
1535
+ <linearGradient id="pl0" x1="223.7" x2="223.7" y1="81.75" y2="127.8" gradientUnits="userSpaceOnUse">
1536
+ <stop stop-color="#663BA6"/><stop stop-color="#7939C2" offset=".349"/><stop stop-color="#8A2FC0" offset=".6615"/><stop stop-color="#791BA3" offset="1"/>
1537
+ </linearGradient>
1538
+ <linearGradient id="pl1" x1="194.6" x2="194.6" y1="81.75" y2="138.3" gradientUnits="userSpaceOnUse">
1539
+ <stop stop-color="#663BA6"/><stop stop-color="#7939C2" offset=".349"/><stop stop-color="#8A2FC0" offset=".6615"/><stop stop-color="#791BA3" offset="1"/>
1540
+ </linearGradient>
1541
+ <linearGradient id="pl2" x1="157.8" x2="157.8" y1="81.75" y2="127" gradientUnits="userSpaceOnUse">
1542
+ <stop stop-color="#663BA6"/><stop stop-color="#7939C2" offset=".349"/><stop stop-color="#8A2FC0" offset=".6615"/><stop stop-color="#791BA3" offset="1"/>
1543
+ </linearGradient>
1544
+ <linearGradient id="pl3" x1="79.96" x2="79.96" y1="81.75" y2="141.8" gradientUnits="userSpaceOnUse">
1545
+ <stop stop-color="#663BA6"/><stop stop-color="#7939C2" offset=".349"/><stop stop-color="#8A2FC0" offset=".6615"/><stop stop-color="#791BA3" offset="1"/>
1546
+ </linearGradient>
1547
+ <linearGradient id="pl4" x1="36.18" x2="212.5" y1="156.6" y2="156.6" gradientUnits="userSpaceOnUse">
1548
+ <stop stop-color="#316FB0"/><stop stop-color="#1FCDE6" offset=".5"/><stop stop-color="#29FEE7" offset="1"/>
1549
+ </linearGradient>
1550
+ <linearGradient id="pl5" x1="40.27" x2="208.2" y1="156.4" y2="156.4" gradientUnits="userSpaceOnUse">
1551
+ <stop stop-color="#316FB0"/><stop stop-color="#1FCDE6" offset=".5"/><stop stop-color="#29FEE7" offset="1"/>
1552
+ </linearGradient>
1553
+ </defs>
1554
+ </svg>`;
1555
+ /**
1556
+ * Creates a lightweight CSS-only preloader that appears instantly,
1557
+ * BEFORE PixiJS/WebGL is initialized.
1558
+ *
1559
+ * Displays the Energy8 logo SVG with an animated loader bar.
1560
+ */
1561
+ function createCSSPreloader(container, config) {
1562
+ if (document.getElementById(PRELOADER_ID))
1563
+ return;
1564
+ const bgColor = typeof config?.backgroundColor === 'string'
1565
+ ? config.backgroundColor
1566
+ : typeof config?.backgroundColor === 'number'
1567
+ ? `#${config.backgroundColor.toString(16).padStart(6, '0')}`
1568
+ : '#0a0a1a';
1569
+ const bgGradient = config?.backgroundGradient ?? `linear-gradient(135deg, ${bgColor} 0%, #1a1a3e 100%)`;
1570
+ const customHTML = config?.cssPreloaderHTML ?? '';
1571
+ const el = document.createElement('div');
1572
+ el.id = PRELOADER_ID;
1573
+ el.innerHTML = customHTML || `
1574
+ <div class="ge-preloader-content">
1575
+ ${LOGO_SVG}
1576
+ </div>
1577
+ `;
1578
+ const style = document.createElement('style');
1579
+ style.textContent = `
1580
+ #${PRELOADER_ID} {
1581
+ position: absolute;
1582
+ top: 0; left: 0;
1583
+ width: 100%; height: 100%;
1584
+ background: ${bgGradient};
1585
+ display: flex;
1586
+ align-items: center;
1587
+ justify-content: center;
1588
+ z-index: 10000;
1589
+ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
1590
+ transition: opacity 0.4s ease-out;
1591
+ }
1592
+
1593
+ #${PRELOADER_ID}.ge-preloader-hidden {
1594
+ opacity: 0;
1595
+ pointer-events: none;
1596
+ }
1597
+
1598
+ .ge-preloader-content {
1599
+ display: flex;
1600
+ flex-direction: column;
1601
+ align-items: center;
1602
+ width: 80%;
1603
+ max-width: 700px;
1604
+ }
1605
+
1606
+ .ge-logo-svg {
1607
+ width: 100%;
1608
+ height: auto;
1609
+ filter: drop-shadow(0 0 30px rgba(121, 57, 194, 0.4));
1610
+ }
1611
+
1612
+ /* Animate the loader clip-rect to shimmer while waiting */
1613
+ .ge-clip-rect {
1614
+ animation: ge-loader-fill 2s ease-in-out infinite;
1615
+ }
1616
+
1617
+ @keyframes ge-loader-fill {
1618
+ 0% { width: 0; }
1619
+ 50% { width: 174; }
1620
+ 100% { width: 0; }
1621
+ }
1622
+
1623
+ /* Animate the SVG text opacity */
1624
+ .ge-preloader-svg-text {
1625
+ animation: ge-pulse 1.5s ease-in-out infinite;
1626
+ }
1627
+
1628
+ @keyframes ge-pulse {
1629
+ 0%, 100% { opacity: 0.4; }
1630
+ 50% { opacity: 1; }
1631
+ }
1632
+ `;
1633
+ container.style.position = container.style.position || 'relative';
1634
+ container.appendChild(style);
1635
+ container.appendChild(el);
1636
+ }
1637
+ /**
1638
+ * Remove the CSS preloader with a smooth fade-out transition.
1639
+ */
1640
+ function removeCSSPreloader(container) {
1641
+ const el = document.getElementById(PRELOADER_ID);
1642
+ if (!el)
1643
+ return;
1644
+ el.classList.add('ge-preloader-hidden');
1645
+ // Remove after transition
1646
+ el.addEventListener('transitionend', () => {
1647
+ el.remove();
1648
+ // Also remove the style element
1649
+ const styles = container.querySelectorAll('style');
1650
+ for (const style of styles) {
1651
+ if (style.textContent?.includes(PRELOADER_ID)) {
1652
+ style.remove();
1653
+ }
1654
+ }
1655
+ });
1656
+ }
1657
+
1658
+ /**
1659
+ * The main entry point for a game built on @energy8platform/game-engine.
1660
+ *
1661
+ * Orchestrates the full lifecycle:
1662
+ * 1. Create PixiJS Application
1663
+ * 2. Initialize SDK (or run offline)
1664
+ * 3. Show CSS preloader → Canvas loading screen with progress bar
1665
+ * 4. Load asset manifest
1666
+ * 5. Transition to the first game scene
1667
+ *
1668
+ * @example
1669
+ * ```ts
1670
+ * import { GameApplication, ScaleMode } from '@energy8platform/game-engine';
1671
+ * import { GameScene } from './scenes/GameScene';
1672
+ *
1673
+ * const game = new GameApplication({
1674
+ * container: '#game',
1675
+ * designWidth: 1920,
1676
+ * designHeight: 1080,
1677
+ * scaleMode: ScaleMode.FIT,
1678
+ * manifest: { bundles: [
1679
+ * { name: 'preload', assets: [{ alias: 'logo', src: 'logo.png' }] },
1680
+ * { name: 'game', assets: [{ alias: 'bg', src: 'background.png' }] },
1681
+ * ]},
1682
+ * loading: { tapToStart: true },
1683
+ * });
1684
+ *
1685
+ * game.scenes.register('game', GameScene);
1686
+ * await game.start('game');
1687
+ * ```
1688
+ */
1689
+ class GameApplication extends EventEmitter {
1690
+ // ─── Public references ──────────────────────────────────
1691
+ /** PixiJS Application instance */
1692
+ app;
1693
+ /** Scene manager */
1694
+ scenes;
1695
+ /** Asset manager */
1696
+ assets;
1697
+ /** Audio manager */
1698
+ audio;
1699
+ /** Viewport manager */
1700
+ viewport;
1701
+ /** SDK instance (null in offline mode) */
1702
+ sdk = null;
1703
+ /** Data received from SDK initialization */
1704
+ initData = null;
1705
+ /** Configuration */
1706
+ config;
1707
+ // ─── Private state ──────────────────────────────────────
1708
+ _running = false;
1709
+ _destroyed = false;
1710
+ _container = null;
1711
+ constructor(config = {}) {
1712
+ super();
1713
+ this.config = {
1714
+ designWidth: 1920,
1715
+ designHeight: 1080,
1716
+ scaleMode: exports.ScaleMode.FIT,
1717
+ orientation: exports.Orientation.ANY,
1718
+ debug: false,
1719
+ ...config,
1720
+ };
1721
+ // Create SceneManager early so scenes can be registered before start()
1722
+ this.scenes = new SceneManager();
1723
+ }
1724
+ // ─── Public getters ─────────────────────────────────────
1725
+ /** Current game config from SDK (or null in offline mode) */
1726
+ get gameConfig() {
1727
+ return this.initData?.config ?? null;
1728
+ }
1729
+ /** Current session data */
1730
+ get session() {
1731
+ return this.initData?.session ?? null;
1732
+ }
1733
+ /** Current balance */
1734
+ get balance() {
1735
+ return this.sdk?.balance ?? 0;
1736
+ }
1737
+ /** Current currency */
1738
+ get currency() {
1739
+ return this.sdk?.currency ?? 'USD';
1740
+ }
1741
+ /** Whether the engine is running */
1742
+ get isRunning() {
1743
+ return this._running;
1744
+ }
1745
+ // ─── Lifecycle ──────────────────────────────────────────
1746
+ /**
1747
+ * Start the game engine. This is the main entry point.
1748
+ *
1749
+ * @param firstScene - Key of the first scene to show after loading (must be registered)
1750
+ * @param sceneData - Optional data to pass to the first scene's onEnter
1751
+ */
1752
+ async start(firstScene, sceneData) {
1753
+ if (this._running) {
1754
+ console.warn('[GameEngine] Already running');
1755
+ return;
1756
+ }
1757
+ try {
1758
+ // 1. Resolve container element
1759
+ this._container = this.resolveContainer();
1760
+ // 2. Show CSS preloader immediately (before PixiJS)
1761
+ createCSSPreloader(this._container, this.config.loading);
1762
+ // 3. Initialize PixiJS
1763
+ await this.initPixi();
1764
+ // 4. Initialize SDK (if enabled)
1765
+ await this.initSDK();
1766
+ // 5. Merge design dimensions from SDK config
1767
+ this.applySDKConfig();
1768
+ // 6. Initialize sub-systems
1769
+ this.initSubSystems();
1770
+ this.emit('initialized', undefined);
1771
+ // 7. Remove CSS preloader, show Canvas loading screen
1772
+ removeCSSPreloader(this._container);
1773
+ // 8. Load assets with loading screen
1774
+ await this.loadAssets(firstScene, sceneData);
1775
+ // 9. Start the game loop
1776
+ this._running = true;
1777
+ this.emit('started', undefined);
1778
+ }
1779
+ catch (err) {
1780
+ console.error('[GameEngine] Failed to start:', err);
1781
+ this.emit('error', err instanceof Error ? err : new Error(String(err)));
1782
+ throw err;
1783
+ }
1784
+ }
1785
+ /**
1786
+ * Destroy the engine and free all resources.
1787
+ */
1788
+ destroy() {
1789
+ if (this._destroyed)
1790
+ return;
1791
+ this._destroyed = true;
1792
+ this._running = false;
1793
+ this.scenes?.destroy();
1794
+ this.audio?.destroy();
1795
+ this.viewport?.destroy();
1796
+ this.sdk?.destroy();
1797
+ this.app?.destroy(true, { children: true, texture: true });
1798
+ this.removeAllListeners();
1799
+ this.emit('destroyed', undefined);
1800
+ }
1801
+ // ─── Private initialization steps ──────────────────────
1802
+ resolveContainer() {
1803
+ if (typeof this.config.container === 'string') {
1804
+ const el = document.querySelector(this.config.container);
1805
+ if (!el)
1806
+ throw new Error(`[GameEngine] Container "${this.config.container}" not found`);
1807
+ return el;
1808
+ }
1809
+ return this.config.container ?? document.body;
1810
+ }
1811
+ async initPixi() {
1812
+ this.app = new pixi_js.Application();
1813
+ const pixiOpts = {
1814
+ background: typeof this.config.loading?.backgroundColor === 'number'
1815
+ ? this.config.loading.backgroundColor
1816
+ : 0x000000,
1817
+ antialias: true,
1818
+ resolution: Math.min(window.devicePixelRatio, 2),
1819
+ autoDensity: true,
1820
+ ...this.config.pixi,
1821
+ };
1822
+ await this.app.init(pixiOpts);
1823
+ // Append canvas to container
1824
+ this._container.appendChild(this.app.canvas);
1825
+ // Set canvas style
1826
+ this.app.canvas.style.display = 'block';
1827
+ this.app.canvas.style.width = '100%';
1828
+ this.app.canvas.style.height = '100%';
1829
+ }
1830
+ async initSDK() {
1831
+ if (this.config.sdk === false) {
1832
+ // Offline / development mode — no SDK
1833
+ this.initData = null;
1834
+ return;
1835
+ }
1836
+ const sdkOpts = typeof this.config.sdk === 'object' ? this.config.sdk : {};
1837
+ this.sdk = new gameSdk.CasinoGameSDK(sdkOpts);
1838
+ // Perform the handshake
1839
+ this.initData = await this.sdk.ready();
1840
+ // Forward SDK events
1841
+ this.sdk.on('error', (err) => {
1842
+ this.emit('error', err);
1843
+ });
1844
+ }
1845
+ applySDKConfig() {
1846
+ // If SDK provides viewport dimensions, use them as design reference
1847
+ if (this.initData?.config?.viewport) {
1848
+ const vp = this.initData.config.viewport;
1849
+ if (!this.config.designWidth)
1850
+ this.config.designWidth = vp.width;
1851
+ if (!this.config.designHeight)
1852
+ this.config.designHeight = vp.height;
1853
+ }
1854
+ }
1855
+ initSubSystems() {
1856
+ // Asset Manager
1857
+ const basePath = this.initData?.assetsUrl ?? '';
1858
+ this.assets = new AssetManager(basePath, this.config.manifest);
1859
+ // Audio Manager
1860
+ this.audio = new AudioManager(this.config.audio);
1861
+ // Viewport Manager
1862
+ this.viewport = new ViewportManager(this.app, this._container, {
1863
+ designWidth: this.config.designWidth,
1864
+ designHeight: this.config.designHeight,
1865
+ scaleMode: this.config.scaleMode,
1866
+ orientation: this.config.orientation,
1867
+ });
1868
+ // Wire SceneManager to the PixiJS stage
1869
+ this.scenes.setRoot(this.app.stage);
1870
+ // Wire viewport resize → scene manager
1871
+ this.viewport.on('resize', ({ width, height }) => {
1872
+ this.scenes.resize(width, height);
1873
+ this.emit('resize', { width, height });
1874
+ });
1875
+ this.viewport.on('orientationChange', (orientation) => {
1876
+ this.emit('orientationChange', orientation);
1877
+ });
1878
+ // Connect ticker → scene updates
1879
+ this.app.ticker.add((ticker) => {
1880
+ // Always update scenes (loading screen needs onUpdate before _running=true)
1881
+ this.scenes.update(ticker.deltaTime / 60); // convert to seconds
1882
+ });
1883
+ // Trigger initial resize
1884
+ this.viewport.refresh();
1885
+ }
1886
+ async loadAssets(firstScene, sceneData) {
1887
+ // Register built-in loading scene
1888
+ this.scenes.register('__loading__', LoadingScene);
1889
+ // Enter loading scene
1890
+ await this.scenes.goto('__loading__', {
1891
+ engine: this,
1892
+ targetScene: firstScene,
1893
+ targetData: sceneData,
1894
+ });
1895
+ }
1896
+ }
1897
+
1898
+ /**
1899
+ * Generic finite state machine for game flow management.
1900
+ *
1901
+ * Supports:
1902
+ * - Typed context object shared across all states
1903
+ * - Async enter/exit hooks
1904
+ * - Per-frame update per state
1905
+ * - Transition guards
1906
+ * - Event emission on state change
1907
+ *
1908
+ * @example
1909
+ * ```ts
1910
+ * interface GameContext {
1911
+ * balance: number;
1912
+ * bet: number;
1913
+ * lastWin: number;
1914
+ * }
1915
+ *
1916
+ * const fsm = new StateMachine<GameContext>({ balance: 1000, bet: 10, lastWin: 0 });
1917
+ *
1918
+ * fsm.addState('idle', {
1919
+ * enter: (ctx) => console.log('Waiting for spin...'),
1920
+ * update: (ctx, dt) => { // optional per-frame },
1921
+ * });
1922
+ *
1923
+ * fsm.addState('spinning', {
1924
+ * enter: async (ctx) => {
1925
+ * const result = await sdk.play({ action: 'spin', bet: ctx.bet });
1926
+ * ctx.lastWin = result.totalWin;
1927
+ * await fsm.transition('presenting');
1928
+ * },
1929
+ * });
1930
+ *
1931
+ * fsm.addState('presenting', {
1932
+ * enter: async (ctx) => {
1933
+ * await showWinPresentation(ctx.lastWin);
1934
+ * await fsm.transition('idle');
1935
+ * },
1936
+ * });
1937
+ *
1938
+ * // Optional guard
1939
+ * fsm.addGuard('idle', 'spinning', (ctx) => ctx.balance >= ctx.bet);
1940
+ *
1941
+ * await fsm.start('idle');
1942
+ * ```
1943
+ */
1944
+ class StateMachine extends EventEmitter {
1945
+ _states = new Map();
1946
+ _guards = new Map();
1947
+ _current = null;
1948
+ _transitioning = false;
1949
+ _context;
1950
+ constructor(context) {
1951
+ super();
1952
+ this._context = context;
1953
+ }
1954
+ /** Current state name */
1955
+ get current() {
1956
+ return this._current;
1957
+ }
1958
+ /** Whether a transition is in progress */
1959
+ get isTransitioning() {
1960
+ return this._transitioning;
1961
+ }
1962
+ /** State machine context (shared data) */
1963
+ get context() {
1964
+ return this._context;
1965
+ }
1966
+ /**
1967
+ * Register a state with optional enter/exit/update hooks.
1968
+ */
1969
+ addState(name, config) {
1970
+ this._states.set(name, config);
1971
+ return this;
1972
+ }
1973
+ /**
1974
+ * Add a transition guard.
1975
+ * The guard function must return true to allow the transition.
1976
+ *
1977
+ * @param from - Source state
1978
+ * @param to - Target state
1979
+ * @param guard - Guard function
1980
+ */
1981
+ addGuard(from, to, guard) {
1982
+ this._guards.set(`${from}->${to}`, guard);
1983
+ return this;
1984
+ }
1985
+ /**
1986
+ * Start the state machine in the given initial state.
1987
+ */
1988
+ async start(initialState, data) {
1989
+ if (this._current !== null) {
1990
+ throw new Error('[StateMachine] Already started. Use transition() to change states.');
1991
+ }
1992
+ const state = this._states.get(initialState);
1993
+ if (!state) {
1994
+ throw new Error(`[StateMachine] State "${initialState}" not registered.`);
1995
+ }
1996
+ this._current = initialState;
1997
+ await state.enter?.(this._context, data);
1998
+ this.emit('transition', { from: null, to: initialState });
1999
+ }
2000
+ /**
2001
+ * Transition to a new state.
2002
+ *
2003
+ * @param to - Target state name
2004
+ * @param data - Optional data passed to the new state's enter hook
2005
+ * @returns true if the transition succeeded, false if blocked by a guard
2006
+ */
2007
+ async transition(to, data) {
2008
+ if (this._transitioning) {
2009
+ console.warn('[StateMachine] Transition already in progress');
2010
+ return false;
2011
+ }
2012
+ const from = this._current;
2013
+ // Check guard
2014
+ if (from !== null) {
2015
+ const guardKey = `${from}->${to}`;
2016
+ const guard = this._guards.get(guardKey);
2017
+ if (guard && !guard(this._context)) {
2018
+ return false;
2019
+ }
2020
+ }
2021
+ const toState = this._states.get(to);
2022
+ if (!toState) {
2023
+ throw new Error(`[StateMachine] State "${to}" not registered.`);
2024
+ }
2025
+ this._transitioning = true;
2026
+ try {
2027
+ // Exit current state
2028
+ if (from !== null) {
2029
+ const fromState = this._states.get(from);
2030
+ await fromState?.exit?.(this._context);
2031
+ }
2032
+ // Enter new state
2033
+ this._current = to;
2034
+ await toState.enter?.(this._context, data);
2035
+ this.emit('transition', { from, to });
2036
+ }
2037
+ catch (err) {
2038
+ this.emit('error', err instanceof Error ? err : new Error(String(err)));
2039
+ throw err;
2040
+ }
2041
+ finally {
2042
+ this._transitioning = false;
2043
+ }
2044
+ return true;
2045
+ }
2046
+ /**
2047
+ * Call the current state's update function.
2048
+ * Should be called from the game loop.
2049
+ */
2050
+ update(dt) {
2051
+ if (this._current === null)
2052
+ return;
2053
+ const state = this._states.get(this._current);
2054
+ state?.update?.(this._context, dt);
2055
+ }
2056
+ /**
2057
+ * Check if a state is registered.
2058
+ */
2059
+ hasState(name) {
2060
+ return this._states.has(name);
2061
+ }
2062
+ /**
2063
+ * Check if a transition is allowed (guard passes).
2064
+ */
2065
+ canTransition(to) {
2066
+ if (this._current === null)
2067
+ return false;
2068
+ const guardKey = `${this._current}->${to}`;
2069
+ const guard = this._guards.get(guardKey);
2070
+ if (!guard)
2071
+ return true;
2072
+ return guard(this._context);
2073
+ }
2074
+ /**
2075
+ * Reset the state machine (exit current state, clear current).
2076
+ */
2077
+ async reset() {
2078
+ if (this._current !== null) {
2079
+ const state = this._states.get(this._current);
2080
+ await state?.exit?.(this._context);
2081
+ }
2082
+ this._current = null;
2083
+ this._transitioning = false;
2084
+ }
2085
+ /**
2086
+ * Destroy the state machine.
2087
+ */
2088
+ async destroy() {
2089
+ await this.reset();
2090
+ this._states.clear();
2091
+ this._guards.clear();
2092
+ this.removeAllListeners();
2093
+ }
2094
+ }
2095
+
2096
+ /**
2097
+ * Sequential/parallel animation timeline built on top of Tween.
2098
+ *
2099
+ * @example
2100
+ * ```ts
2101
+ * const timeline = new Timeline();
2102
+ *
2103
+ * // Sequential: one after another
2104
+ * timeline
2105
+ * .to(sprite1, { alpha: 1 }, 300)
2106
+ * .to(sprite2, { x: 200 }, 500)
2107
+ * .delay(200)
2108
+ * .call(() => console.log('done'));
2109
+ *
2110
+ * // Parallel: all at once
2111
+ * timeline.parallel(
2112
+ * () => Tween.to(sprite1, { x: 100 }, 300),
2113
+ * () => Tween.to(sprite2, { y: 200 }, 300),
2114
+ * );
2115
+ *
2116
+ * await timeline.play();
2117
+ * ```
2118
+ */
2119
+ class Timeline {
2120
+ _steps = [];
2121
+ _playing = false;
2122
+ _cancelled = false;
2123
+ /**
2124
+ * Add a tween step (animate to target values).
2125
+ */
2126
+ to(target, props, duration, easing) {
2127
+ this._steps.push({
2128
+ fn: () => Tween.to(target, props, duration, easing),
2129
+ });
2130
+ return this;
2131
+ }
2132
+ /**
2133
+ * Add a tween step (animate from given values).
2134
+ */
2135
+ from(target, props, duration, easing) {
2136
+ this._steps.push({
2137
+ fn: () => Tween.from(target, props, duration, easing),
2138
+ });
2139
+ return this;
2140
+ }
2141
+ /**
2142
+ * Add a delay step.
2143
+ */
2144
+ delay(ms) {
2145
+ this._steps.push({
2146
+ fn: () => Tween.delay(ms),
2147
+ });
2148
+ return this;
2149
+ }
2150
+ /**
2151
+ * Add a callback step.
2152
+ */
2153
+ call(fn) {
2154
+ this._steps.push({
2155
+ fn: async () => {
2156
+ await fn();
2157
+ },
2158
+ });
2159
+ return this;
2160
+ }
2161
+ /**
2162
+ * Add a parallel step — all functions run simultaneously,
2163
+ * step completes when all are done.
2164
+ */
2165
+ parallel(...fns) {
2166
+ this._steps.push({
2167
+ fn: () => Promise.all(fns.map((f) => f())).then(() => { }),
2168
+ });
2169
+ return this;
2170
+ }
2171
+ /**
2172
+ * Play the timeline from start.
2173
+ * Returns a promise that resolves when all steps complete.
2174
+ */
2175
+ async play() {
2176
+ if (this._playing)
2177
+ return;
2178
+ this._playing = true;
2179
+ this._cancelled = false;
2180
+ for (const step of this._steps) {
2181
+ if (this._cancelled)
2182
+ break;
2183
+ await step.fn();
2184
+ }
2185
+ this._playing = false;
2186
+ }
2187
+ /**
2188
+ * Cancel the timeline.
2189
+ */
2190
+ cancel() {
2191
+ this._cancelled = true;
2192
+ }
2193
+ /**
2194
+ * Clear all steps.
2195
+ */
2196
+ clear() {
2197
+ this._steps.length = 0;
2198
+ this._cancelled = false;
2199
+ this._playing = false;
2200
+ return this;
2201
+ }
2202
+ /** Whether the timeline is currently playing */
2203
+ get isPlaying() {
2204
+ return this._playing;
2205
+ }
2206
+ }
2207
+
2208
+ /**
2209
+ * Helper for working with Spine animations in PixiJS v8.
2210
+ *
2211
+ * Optional — only works if @esotericsoftware/spine-pixi-v8 is installed.
2212
+ * Provides convenience methods for creating and playing Spine animations.
2213
+ *
2214
+ * @example
2215
+ * ```ts
2216
+ * // Load spine assets via AssetManager first
2217
+ * const spine = SpineHelper.create('char-data', 'char-atlas');
2218
+ * app.stage.addChild(spine);
2219
+ * await SpineHelper.playAnimation(spine, 'idle', true);
2220
+ * await SpineHelper.playAnimation(spine, 'win');
2221
+ * ```
2222
+ */
2223
+ class SpineHelper {
2224
+ static _SpineClass = null;
2225
+ static _loaded = false;
2226
+ /**
2227
+ * Ensure the Spine module is loaded.
2228
+ * Called automatically by create/playAnimation.
2229
+ */
2230
+ static async ensureLoaded() {
2231
+ if (SpineHelper._loaded)
2232
+ return !!SpineHelper._SpineClass;
2233
+ try {
2234
+ const spineModule = await import('@esotericsoftware/spine-pixi-v8');
2235
+ SpineHelper._SpineClass = spineModule.Spine;
2236
+ SpineHelper._loaded = true;
2237
+ return true;
2238
+ }
2239
+ catch {
2240
+ console.warn('[SpineHelper] @esotericsoftware/spine-pixi-v8 not available.');
2241
+ SpineHelper._loaded = true;
2242
+ return false;
2243
+ }
2244
+ }
2245
+ /**
2246
+ * Create a Spine display object.
2247
+ *
2248
+ * @param skeletonAlias - Alias of the loaded .skel/.json asset
2249
+ * @param atlasAlias - Alias of the loaded .atlas asset
2250
+ * @param options - Additional Spine options
2251
+ * @returns Spine container (or null if Spine is not available)
2252
+ */
2253
+ static async create(skeletonAlias, atlasAlias, options) {
2254
+ const available = await SpineHelper.ensureLoaded();
2255
+ if (!available || !SpineHelper._SpineClass)
2256
+ return null;
2257
+ const SpineClass = SpineHelper._SpineClass;
2258
+ // Use Spine.from for v4.2, constructor for v4.3+
2259
+ if (typeof SpineClass.from === 'function') {
2260
+ return SpineClass.from({
2261
+ skeleton: skeletonAlias,
2262
+ atlas: atlasAlias,
2263
+ scale: options?.scale,
2264
+ autoUpdate: options?.autoUpdate ?? true,
2265
+ });
2266
+ }
2267
+ return new SpineClass({
2268
+ skeleton: skeletonAlias,
2269
+ atlas: atlasAlias,
2270
+ scale: options?.scale,
2271
+ autoUpdate: options?.autoUpdate ?? true,
2272
+ });
2273
+ }
2274
+ /**
2275
+ * Play a named animation on a Spine object.
2276
+ * Returns a promise that resolves when the animation completes.
2277
+ * For looping animations, the promise never resolves.
2278
+ *
2279
+ * @param spine - Spine display object
2280
+ * @param animationName - Name of the animation
2281
+ * @param loop - Whether to loop (default: false)
2282
+ * @param track - Animation track (default: 0)
2283
+ */
2284
+ static playAnimation(spine, animationName, loop = false, track = 0) {
2285
+ return new Promise((resolve) => {
2286
+ if (!spine?.state) {
2287
+ resolve();
2288
+ return;
2289
+ }
2290
+ const entry = spine.state.setAnimation(track, animationName, loop);
2291
+ if (loop) {
2292
+ // Looping animations never complete — resolve immediately
2293
+ // so callers can fire-and-forget
2294
+ resolve();
2295
+ return;
2296
+ }
2297
+ // Wait for the animation to complete
2298
+ spine.state.addListener({
2299
+ complete: (completedEntry) => {
2300
+ if (completedEntry === entry) {
2301
+ resolve();
2302
+ }
2303
+ },
2304
+ });
2305
+ });
2306
+ }
2307
+ /**
2308
+ * Queue an animation after the current one finishes.
2309
+ *
2310
+ * @param spine - Spine display object
2311
+ * @param animationName - Animation name
2312
+ * @param delay - Mix duration / delay before starting
2313
+ * @param loop - Loop the queued animation
2314
+ * @param track - Animation track
2315
+ */
2316
+ static addAnimation(spine, animationName, delay = 0, loop = false, track = 0) {
2317
+ spine?.state?.addAnimation(track, animationName, loop, delay);
2318
+ }
2319
+ /**
2320
+ * Get all animation names available on a Spine skeleton.
2321
+ */
2322
+ static getAnimationNames(spine) {
2323
+ if (!spine?.skeleton?.data?.animations)
2324
+ return [];
2325
+ return spine.skeleton.data.animations.map((a) => a.name);
2326
+ }
2327
+ /**
2328
+ * Get all skin names available on a Spine skeleton.
2329
+ */
2330
+ static getSkinNames(spine) {
2331
+ if (!spine?.skeleton?.data?.skins)
2332
+ return [];
2333
+ return spine.skeleton.data.skins.map((s) => s.name);
2334
+ }
2335
+ /**
2336
+ * Set the active skin on a Spine skeleton.
2337
+ */
2338
+ static setSkin(spine, skinName) {
2339
+ spine?.skeleton?.setSkinByName(skinName);
2340
+ spine?.skeleton?.setSlotsToSetupPose();
2341
+ }
2342
+ }
2343
+
2344
+ /**
2345
+ * Unified input manager for touch, mouse, and keyboard.
2346
+ *
2347
+ * Features:
2348
+ * - Unified pointer events (works with touch + mouse)
2349
+ * - Swipe gesture detection
2350
+ * - Keyboard input with isKeyDown state
2351
+ * - Input locking (block input during animations)
2352
+ *
2353
+ * @example
2354
+ * ```ts
2355
+ * const input = new InputManager(app.canvas);
2356
+ *
2357
+ * input.on('tap', ({ x, y }) => console.log('Tapped at', x, y));
2358
+ * input.on('swipe', ({ direction }) => console.log('Swiped', direction));
2359
+ * input.on('keydown', ({ key }) => {
2360
+ * if (key === ' ') spin();
2361
+ * });
2362
+ *
2363
+ * // Block input during animations
2364
+ * input.lock();
2365
+ * await playAnimation();
2366
+ * input.unlock();
2367
+ * ```
2368
+ */
2369
+ class InputManager extends EventEmitter {
2370
+ _canvas;
2371
+ _locked = false;
2372
+ _keysDown = new Set();
2373
+ _destroyed = false;
2374
+ // Gesture tracking
2375
+ _pointerStart = null;
2376
+ _swipeThreshold = 50; // minimum distance in px
2377
+ _swipeMaxTime = 300; // max ms for swipe gesture
2378
+ constructor(canvas) {
2379
+ super();
2380
+ this._canvas = canvas;
2381
+ this.setupPointerEvents();
2382
+ this.setupKeyboardEvents();
2383
+ }
2384
+ /** Whether input is currently locked */
2385
+ get locked() {
2386
+ return this._locked;
2387
+ }
2388
+ /** Lock all input (e.g., during animations) */
2389
+ lock() {
2390
+ this._locked = true;
2391
+ }
2392
+ /** Unlock input */
2393
+ unlock() {
2394
+ this._locked = false;
2395
+ }
2396
+ /** Check if a key is currently pressed */
2397
+ isKeyDown(key) {
2398
+ return this._keysDown.has(key.toLowerCase());
2399
+ }
2400
+ /** Destroy the input manager */
2401
+ destroy() {
2402
+ this._destroyed = true;
2403
+ this._canvas.removeEventListener('pointerdown', this.onPointerDown);
2404
+ this._canvas.removeEventListener('pointerup', this.onPointerUp);
2405
+ this._canvas.removeEventListener('pointermove', this.onPointerMove);
2406
+ document.removeEventListener('keydown', this.onKeyDown);
2407
+ document.removeEventListener('keyup', this.onKeyUp);
2408
+ this._keysDown.clear();
2409
+ this.removeAllListeners();
2410
+ }
2411
+ // ─── Private: Pointer ──────────────────────────────────
2412
+ setupPointerEvents() {
2413
+ this._canvas.addEventListener('pointerdown', this.onPointerDown);
2414
+ this._canvas.addEventListener('pointerup', this.onPointerUp);
2415
+ this._canvas.addEventListener('pointermove', this.onPointerMove);
2416
+ }
2417
+ onPointerDown = (e) => {
2418
+ if (this._locked || this._destroyed)
2419
+ return;
2420
+ const pos = this.getCanvasPosition(e);
2421
+ this._pointerStart = { ...pos, time: Date.now() };
2422
+ this.emit('press', pos);
2423
+ };
2424
+ onPointerUp = (e) => {
2425
+ if (this._locked || this._destroyed)
2426
+ return;
2427
+ const pos = this.getCanvasPosition(e);
2428
+ this.emit('release', pos);
2429
+ // Check for tap vs swipe
2430
+ if (this._pointerStart) {
2431
+ const dx = pos.x - this._pointerStart.x;
2432
+ const dy = pos.y - this._pointerStart.y;
2433
+ const dist = Math.sqrt(dx * dx + dy * dy);
2434
+ const elapsed = Date.now() - this._pointerStart.time;
2435
+ if (dist > this._swipeThreshold && elapsed < this._swipeMaxTime) {
2436
+ // Swipe detected
2437
+ const absDx = Math.abs(dx);
2438
+ const absDy = Math.abs(dy);
2439
+ let direction;
2440
+ if (absDx > absDy) {
2441
+ direction = dx > 0 ? 'right' : 'left';
2442
+ }
2443
+ else {
2444
+ direction = dy > 0 ? 'down' : 'up';
2445
+ }
2446
+ this.emit('swipe', { direction, velocity: dist / elapsed });
2447
+ }
2448
+ else if (dist < 10) {
2449
+ // Tap (minimal movement)
2450
+ this.emit('tap', pos);
2451
+ }
2452
+ }
2453
+ this._pointerStart = null;
2454
+ };
2455
+ onPointerMove = (e) => {
2456
+ if (this._locked || this._destroyed)
2457
+ return;
2458
+ this.emit('move', this.getCanvasPosition(e));
2459
+ };
2460
+ getCanvasPosition(e) {
2461
+ const rect = this._canvas.getBoundingClientRect();
2462
+ return {
2463
+ x: e.clientX - rect.left,
2464
+ y: e.clientY - rect.top,
2465
+ };
2466
+ }
2467
+ // ─── Private: Keyboard ─────────────────────────────────
2468
+ setupKeyboardEvents() {
2469
+ document.addEventListener('keydown', this.onKeyDown);
2470
+ document.addEventListener('keyup', this.onKeyUp);
2471
+ }
2472
+ onKeyDown = (e) => {
2473
+ if (this._locked || this._destroyed)
2474
+ return;
2475
+ this._keysDown.add(e.key.toLowerCase());
2476
+ this.emit('keydown', { key: e.key, code: e.code });
2477
+ };
2478
+ onKeyUp = (e) => {
2479
+ if (this._destroyed)
2480
+ return;
2481
+ this._keysDown.delete(e.key.toLowerCase());
2482
+ if (this._locked)
2483
+ return;
2484
+ this.emit('keyup', { key: e.key, code: e.code });
2485
+ };
2486
+ }
2487
+
2488
+ const DEFAULT_COLORS = {
2489
+ normal: 0xffd700,
2490
+ hover: 0xffe44d,
2491
+ pressed: 0xccac00,
2492
+ disabled: 0x666666,
2493
+ };
2494
+ /**
2495
+ * Interactive button component with state management and animation.
2496
+ *
2497
+ * Supports both texture-based and Graphics-based rendering.
2498
+ *
2499
+ * @example
2500
+ * ```ts
2501
+ * const btn = new Button({
2502
+ * width: 200, height: 60, borderRadius: 12,
2503
+ * colors: { normal: 0x22aa22, hover: 0x33cc33 },
2504
+ * });
2505
+ *
2506
+ * btn.onTap = () => console.log('Clicked!');
2507
+ * scene.container.addChild(btn);
2508
+ * ```
2509
+ */
2510
+ class Button extends pixi_js.Container {
2511
+ _state = 'normal';
2512
+ _bg;
2513
+ _sprites = {};
2514
+ _config;
2515
+ /** Called when the button is tapped/clicked */
2516
+ onTap;
2517
+ /** Called when the button state changes */
2518
+ onStateChange;
2519
+ constructor(config = {}) {
2520
+ super();
2521
+ this._config = {
2522
+ width: 200,
2523
+ height: 60,
2524
+ borderRadius: 8,
2525
+ pressScale: 0.95,
2526
+ animationDuration: 100,
2527
+ ...config,
2528
+ };
2529
+ // Create Graphics background
2530
+ this._bg = new pixi_js.Graphics();
2531
+ this.addChild(this._bg);
2532
+ // Create texture sprites if provided
2533
+ if (config.textures) {
2534
+ for (const [state, tex] of Object.entries(config.textures)) {
2535
+ const texture = typeof tex === 'string' ? pixi_js.Texture.from(tex) : tex;
2536
+ const sprite = new pixi_js.Sprite(texture);
2537
+ sprite.anchor.set(0.5);
2538
+ sprite.visible = state === 'normal';
2539
+ this._sprites[state] = sprite;
2540
+ this.addChild(sprite);
2541
+ }
2542
+ }
2543
+ // Make interactive
2544
+ this.eventMode = 'static';
2545
+ this.cursor = 'pointer';
2546
+ // Set up hit area for Graphics-based
2547
+ this.pivot.set(this._config.width / 2, this._config.height / 2);
2548
+ // Bind events
2549
+ this.on('pointerover', this.onPointerOver);
2550
+ this.on('pointerout', this.onPointerOut);
2551
+ this.on('pointerdown', this.onPointerDown);
2552
+ this.on('pointerup', this.onPointerUp);
2553
+ this.on('pointertap', this.onPointerTap);
2554
+ // Initial render
2555
+ this.setState('normal');
2556
+ if (config.disabled) {
2557
+ this.disable();
2558
+ }
2559
+ }
2560
+ /** Current button state */
2561
+ get state() {
2562
+ return this._state;
2563
+ }
2564
+ /** Enable the button */
2565
+ enable() {
2566
+ if (this._state === 'disabled') {
2567
+ this.setState('normal');
2568
+ this.eventMode = 'static';
2569
+ this.cursor = 'pointer';
2570
+ }
2571
+ }
2572
+ /** Disable the button */
2573
+ disable() {
2574
+ this.setState('disabled');
2575
+ this.eventMode = 'none';
2576
+ this.cursor = 'default';
2577
+ }
2578
+ /** Whether the button is disabled */
2579
+ get disabled() {
2580
+ return this._state === 'disabled';
2581
+ }
2582
+ setState(state) {
2583
+ if (this._state === state)
2584
+ return;
2585
+ this._state = state;
2586
+ this.render();
2587
+ this.onStateChange?.(state);
2588
+ }
2589
+ render() {
2590
+ const { width, height, borderRadius, colors } = this._config;
2591
+ const colorMap = { ...DEFAULT_COLORS, ...colors };
2592
+ // Update Graphics
2593
+ this._bg.clear();
2594
+ this._bg.roundRect(0, 0, width, height, borderRadius).fill(colorMap[this._state]);
2595
+ // Add highlight for normal/hover
2596
+ if (this._state === 'normal' || this._state === 'hover') {
2597
+ this._bg
2598
+ .roundRect(2, 2, width - 4, height * 0.45, borderRadius)
2599
+ .fill({ color: 0xffffff, alpha: 0.1 });
2600
+ }
2601
+ // Update sprite visibility
2602
+ for (const [state, sprite] of Object.entries(this._sprites)) {
2603
+ if (sprite)
2604
+ sprite.visible = state === this._state;
2605
+ }
2606
+ // Fall back to normal sprite if state sprite doesn't exist
2607
+ if (!this._sprites[this._state] && this._sprites.normal) {
2608
+ this._sprites.normal.visible = true;
2609
+ }
2610
+ }
2611
+ onPointerOver = () => {
2612
+ if (this._state === 'disabled')
2613
+ return;
2614
+ this.setState('hover');
2615
+ };
2616
+ onPointerOut = () => {
2617
+ if (this._state === 'disabled')
2618
+ return;
2619
+ this.setState('normal');
2620
+ Tween.to(this.scale, { x: 1, y: 1 }, this._config.animationDuration);
2621
+ };
2622
+ onPointerDown = () => {
2623
+ if (this._state === 'disabled')
2624
+ return;
2625
+ this.setState('pressed');
2626
+ const s = this._config.pressScale;
2627
+ Tween.to(this.scale, { x: s, y: s }, this._config.animationDuration, Easing.easeOutQuad);
2628
+ };
2629
+ onPointerUp = () => {
2630
+ if (this._state === 'disabled')
2631
+ return;
2632
+ this.setState('hover');
2633
+ Tween.to(this.scale, { x: 1, y: 1 }, this._config.animationDuration, Easing.easeOutBack);
2634
+ };
2635
+ onPointerTap = () => {
2636
+ if (this._state === 'disabled')
2637
+ return;
2638
+ this.onTap?.();
2639
+ };
2640
+ }
2641
+
2642
+ /**
2643
+ * Horizontal progress bar with optional smooth fill animation.
2644
+ *
2645
+ * @example
2646
+ * ```ts
2647
+ * const bar = new ProgressBar({ width: 300, height: 20, fillColor: 0x22cc22 });
2648
+ * scene.container.addChild(bar);
2649
+ * bar.progress = 0.5; // 50%
2650
+ * ```
2651
+ */
2652
+ class ProgressBar extends pixi_js.Container {
2653
+ _track;
2654
+ _fill;
2655
+ _border;
2656
+ _config;
2657
+ _progress = 0;
2658
+ _displayedProgress = 0;
2659
+ constructor(config = {}) {
2660
+ super();
2661
+ this._config = {
2662
+ width: 300,
2663
+ height: 16,
2664
+ borderRadius: 8,
2665
+ fillColor: 0xffd700,
2666
+ trackColor: 0x333333,
2667
+ borderColor: 0x555555,
2668
+ borderWidth: 1,
2669
+ animated: true,
2670
+ animationSpeed: 0.1,
2671
+ ...config,
2672
+ };
2673
+ this._track = new pixi_js.Graphics();
2674
+ this._fill = new pixi_js.Graphics();
2675
+ this._border = new pixi_js.Graphics();
2676
+ this.addChild(this._track, this._fill, this._border);
2677
+ this.drawTrack();
2678
+ this.drawBorder();
2679
+ this.drawFill(0);
2680
+ }
2681
+ /** Get/set progress (0..1) */
2682
+ get progress() {
2683
+ return this._progress;
2684
+ }
2685
+ set progress(value) {
2686
+ this._progress = Math.max(0, Math.min(1, value));
2687
+ if (!this._config.animated) {
2688
+ this._displayedProgress = this._progress;
2689
+ this.drawFill(this._displayedProgress);
2690
+ }
2691
+ }
2692
+ /**
2693
+ * Call each frame if animated is true.
2694
+ */
2695
+ update(dt) {
2696
+ if (!this._config.animated)
2697
+ return;
2698
+ if (Math.abs(this._displayedProgress - this._progress) < 0.001) {
2699
+ this._displayedProgress = this._progress;
2700
+ return;
2701
+ }
2702
+ this._displayedProgress +=
2703
+ (this._progress - this._displayedProgress) * this._config.animationSpeed;
2704
+ this.drawFill(this._displayedProgress);
2705
+ }
2706
+ drawTrack() {
2707
+ const { width, height, borderRadius, trackColor } = this._config;
2708
+ this._track.clear();
2709
+ this._track.roundRect(0, 0, width, height, borderRadius).fill(trackColor);
2710
+ }
2711
+ drawBorder() {
2712
+ const { width, height, borderRadius, borderColor, borderWidth } = this._config;
2713
+ this._border.clear();
2714
+ this._border
2715
+ .roundRect(0, 0, width, height, borderRadius)
2716
+ .stroke({ color: borderColor, width: borderWidth });
2717
+ }
2718
+ drawFill(progress) {
2719
+ const { width, height, borderRadius, fillColor, borderWidth } = this._config;
2720
+ const innerWidth = width - borderWidth * 2;
2721
+ const innerHeight = height - borderWidth * 2;
2722
+ const fillWidth = Math.max(0, innerWidth * progress);
2723
+ this._fill.clear();
2724
+ if (fillWidth > 0) {
2725
+ this._fill.x = borderWidth;
2726
+ this._fill.y = borderWidth;
2727
+ this._fill.roundRect(0, 0, fillWidth, innerHeight, borderRadius - 1).fill(fillColor);
2728
+ // Highlight
2729
+ this._fill
2730
+ .roundRect(0, 0, fillWidth, innerHeight * 0.4, borderRadius - 1)
2731
+ .fill({ color: 0xffffff, alpha: 0.15 });
2732
+ }
2733
+ }
2734
+ }
2735
+
2736
+ /**
2737
+ * Enhanced text label with auto-fit scaling and currency formatting.
2738
+ *
2739
+ * @example
2740
+ * ```ts
2741
+ * const label = new Label({
2742
+ * text: 'BALANCE',
2743
+ * style: { fontSize: 24, fill: 0xffd700 },
2744
+ * maxWidth: 200,
2745
+ * autoFit: true,
2746
+ * });
2747
+ * ```
2748
+ */
2749
+ class Label extends pixi_js.Container {
2750
+ _text;
2751
+ _maxWidth;
2752
+ _autoFit;
2753
+ constructor(config = {}) {
2754
+ super();
2755
+ this._maxWidth = config.maxWidth ?? Infinity;
2756
+ this._autoFit = config.autoFit ?? false;
2757
+ this._text = new pixi_js.Text({
2758
+ text: config.text ?? '',
2759
+ style: {
2760
+ fontFamily: '-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',
2761
+ fontSize: 24,
2762
+ fill: 0xffffff,
2763
+ ...config.style,
2764
+ },
2765
+ });
2766
+ this._text.anchor.set(0.5);
2767
+ this.addChild(this._text);
2768
+ this.fitText();
2769
+ }
2770
+ /** Get/set the displayed text */
2771
+ get text() {
2772
+ return this._text.text;
2773
+ }
2774
+ set text(value) {
2775
+ this._text.text = value;
2776
+ this.fitText();
2777
+ }
2778
+ /** Get/set the text style */
2779
+ get style() {
2780
+ return this._text.style;
2781
+ }
2782
+ /** Set max width constraint */
2783
+ set maxWidth(value) {
2784
+ this._maxWidth = value;
2785
+ this.fitText();
2786
+ }
2787
+ /**
2788
+ * Format and display a number as currency.
2789
+ *
2790
+ * @param amount - The numeric amount
2791
+ * @param currency - Currency code (e.g., 'USD', 'EUR')
2792
+ * @param locale - Locale string (default: 'en-US')
2793
+ */
2794
+ setCurrency(amount, currency, locale = 'en-US') {
2795
+ try {
2796
+ this.text = new Intl.NumberFormat(locale, {
2797
+ style: 'currency',
2798
+ currency,
2799
+ minimumFractionDigits: 2,
2800
+ maximumFractionDigits: 2,
2801
+ }).format(amount);
2802
+ }
2803
+ catch {
2804
+ this.text = `${amount.toFixed(2)} ${currency}`;
2805
+ }
2806
+ }
2807
+ /**
2808
+ * Format a number with thousands separators.
2809
+ */
2810
+ setNumber(value, decimals = 0, locale = 'en-US') {
2811
+ this.text = new Intl.NumberFormat(locale, {
2812
+ minimumFractionDigits: decimals,
2813
+ maximumFractionDigits: decimals,
2814
+ }).format(value);
2815
+ }
2816
+ fitText() {
2817
+ if (!this._autoFit || this._maxWidth === Infinity)
2818
+ return;
2819
+ this._text.scale.set(1);
2820
+ if (this._text.width > this._maxWidth) {
2821
+ const scale = this._maxWidth / this._text.width;
2822
+ this._text.scale.set(scale);
2823
+ }
2824
+ }
2825
+ }
2826
+
2827
+ /**
2828
+ * Background panel that can use either Graphics or 9-slice sprite.
2829
+ *
2830
+ * @example
2831
+ * ```ts
2832
+ * // Simple colored panel
2833
+ * const panel = new Panel({ width: 400, height: 300, backgroundColor: 0x222222, borderRadius: 12 });
2834
+ *
2835
+ * // 9-slice panel (texture-based)
2836
+ * const panel = new Panel({
2837
+ * nineSliceTexture: 'panel-bg',
2838
+ * nineSliceBorders: [20, 20, 20, 20],
2839
+ * width: 400, height: 300,
2840
+ * });
2841
+ * ```
2842
+ */
2843
+ class Panel extends pixi_js.Container {
2844
+ _bg;
2845
+ _content;
2846
+ _config;
2847
+ constructor(config = {}) {
2848
+ super();
2849
+ this._config = {
2850
+ width: 400,
2851
+ height: 300,
2852
+ padding: 16,
2853
+ backgroundAlpha: 1,
2854
+ ...config,
2855
+ };
2856
+ // Create background
2857
+ if (config.nineSliceTexture) {
2858
+ const texture = typeof config.nineSliceTexture === 'string'
2859
+ ? pixi_js.Texture.from(config.nineSliceTexture)
2860
+ : config.nineSliceTexture;
2861
+ const [left, top, right, bottom] = config.nineSliceBorders ?? [10, 10, 10, 10];
2862
+ this._bg = new pixi_js.NineSliceSprite({
2863
+ texture,
2864
+ leftWidth: left,
2865
+ topHeight: top,
2866
+ rightWidth: right,
2867
+ bottomHeight: bottom,
2868
+ });
2869
+ this._bg.width = this._config.width;
2870
+ this._bg.height = this._config.height;
2871
+ }
2872
+ else {
2873
+ this._bg = new pixi_js.Graphics();
2874
+ this.drawGraphicsBg();
2875
+ }
2876
+ this._bg.alpha = this._config.backgroundAlpha;
2877
+ this.addChild(this._bg);
2878
+ // Content container with padding
2879
+ this._content = new pixi_js.Container();
2880
+ this._content.x = this._config.padding;
2881
+ this._content.y = this._config.padding;
2882
+ this.addChild(this._content);
2883
+ }
2884
+ /** Content container — add children here */
2885
+ get content() {
2886
+ return this._content;
2887
+ }
2888
+ /** Resize the panel */
2889
+ setSize(width, height) {
2890
+ this._config.width = width;
2891
+ this._config.height = height;
2892
+ if (this._bg instanceof pixi_js.Graphics) {
2893
+ this.drawGraphicsBg();
2894
+ }
2895
+ else {
2896
+ this._bg.width = width;
2897
+ this._bg.height = height;
2898
+ }
2899
+ }
2900
+ drawGraphicsBg() {
2901
+ const bg = this._bg;
2902
+ const { width, height, backgroundColor, borderRadius, borderColor, borderWidth, } = this._config;
2903
+ bg.clear();
2904
+ bg.roundRect(0, 0, width, height, borderRadius ?? 0).fill(backgroundColor ?? 0x1a1a2e);
2905
+ if (borderColor !== undefined && borderWidth) {
2906
+ bg.roundRect(0, 0, width, height, borderRadius ?? 0)
2907
+ .stroke({ color: borderColor, width: borderWidth });
2908
+ }
2909
+ }
2910
+ }
2911
+
2912
+ /**
2913
+ * Reactive balance display component.
2914
+ *
2915
+ * Automatically formats currency and can animate value changes
2916
+ * with a smooth countup/countdown effect.
2917
+ *
2918
+ * @example
2919
+ * ```ts
2920
+ * const balance = new BalanceDisplay({ currency: 'USD', animated: true });
2921
+ * balance.setValue(1000);
2922
+ *
2923
+ * // Wire to SDK
2924
+ * sdk.on('balanceUpdate', ({ balance: val }) => balance.setValue(val));
2925
+ * ```
2926
+ */
2927
+ class BalanceDisplay extends pixi_js.Container {
2928
+ _prefixLabel = null;
2929
+ _valueLabel;
2930
+ _config;
2931
+ _currentValue = 0;
2932
+ _displayedValue = 0;
2933
+ _animating = false;
2934
+ constructor(config = {}) {
2935
+ super();
2936
+ this._config = {
2937
+ currency: config.currency ?? 'USD',
2938
+ locale: config.locale ?? 'en-US',
2939
+ animated: config.animated ?? true,
2940
+ animationDuration: config.animationDuration ?? 500,
2941
+ };
2942
+ // Prefix label
2943
+ if (config.prefix) {
2944
+ this._prefixLabel = new Label({
2945
+ text: config.prefix,
2946
+ style: {
2947
+ fontSize: 16,
2948
+ fill: 0xaaaaaa,
2949
+ ...config.style,
2950
+ },
2951
+ });
2952
+ this.addChild(this._prefixLabel);
2953
+ }
2954
+ // Value label
2955
+ this._valueLabel = new Label({
2956
+ text: '0.00',
2957
+ style: {
2958
+ fontSize: 28,
2959
+ fontWeight: 'bold',
2960
+ fill: 0xffffff,
2961
+ ...config.style,
2962
+ },
2963
+ maxWidth: config.maxWidth,
2964
+ autoFit: !!config.maxWidth,
2965
+ });
2966
+ this.addChild(this._valueLabel);
2967
+ this.layoutLabels();
2968
+ }
2969
+ /** Current displayed value */
2970
+ get value() {
2971
+ return this._currentValue;
2972
+ }
2973
+ /**
2974
+ * Set the balance value. If animated, smoothly counts to the new value.
2975
+ */
2976
+ setValue(value) {
2977
+ const oldValue = this._currentValue;
2978
+ this._currentValue = value;
2979
+ if (this._config.animated && oldValue !== value) {
2980
+ this.animateValue(oldValue, value);
2981
+ }
2982
+ else {
2983
+ this._displayedValue = value;
2984
+ this.updateDisplay();
2985
+ }
2986
+ }
2987
+ /**
2988
+ * Set the currency code.
2989
+ */
2990
+ setCurrency(currency) {
2991
+ this._config.currency = currency;
2992
+ this.updateDisplay();
2993
+ }
2994
+ async animateValue(from, to) {
2995
+ this._animating = true;
2996
+ const duration = this._config.animationDuration;
2997
+ const startTime = Date.now();
2998
+ return new Promise((resolve) => {
2999
+ const tick = () => {
3000
+ const elapsed = Date.now() - startTime;
3001
+ const t = Math.min(elapsed / duration, 1);
3002
+ const eased = Easing.easeOutCubic(t);
3003
+ this._displayedValue = from + (to - from) * eased;
3004
+ this.updateDisplay();
3005
+ if (t < 1) {
3006
+ requestAnimationFrame(tick);
3007
+ }
3008
+ else {
3009
+ this._displayedValue = to;
3010
+ this.updateDisplay();
3011
+ this._animating = false;
3012
+ resolve();
3013
+ }
3014
+ };
3015
+ requestAnimationFrame(tick);
3016
+ });
3017
+ }
3018
+ updateDisplay() {
3019
+ this._valueLabel.setCurrency(this._displayedValue, this._config.currency, this._config.locale);
3020
+ }
3021
+ layoutLabels() {
3022
+ if (this._prefixLabel) {
3023
+ this._prefixLabel.y = -14;
3024
+ this._valueLabel.y = 14;
3025
+ }
3026
+ }
3027
+ }
3028
+
3029
+ /**
3030
+ * Win amount display with countup animation.
3031
+ *
3032
+ * Shows a dramatic countup from 0 to the win amount, with optional
3033
+ * scale pop effect — typical of slot games.
3034
+ *
3035
+ * @example
3036
+ * ```ts
3037
+ * const winDisplay = new WinDisplay({ currency: 'USD' });
3038
+ * scene.container.addChild(winDisplay);
3039
+ * await winDisplay.showWin(150.50); // countup animation
3040
+ * winDisplay.hide();
3041
+ * ```
3042
+ */
3043
+ class WinDisplay extends pixi_js.Container {
3044
+ _label;
3045
+ _config;
3046
+ _cancelCountup = false;
3047
+ constructor(config = {}) {
3048
+ super();
3049
+ this._config = {
3050
+ currency: config.currency ?? 'USD',
3051
+ locale: config.locale ?? 'en-US',
3052
+ countupDuration: config.countupDuration ?? 1500,
3053
+ popScale: config.popScale ?? 1.2,
3054
+ };
3055
+ this._label = new Label({
3056
+ text: '',
3057
+ style: {
3058
+ fontSize: 48,
3059
+ fontWeight: 'bold',
3060
+ fill: 0xffd700,
3061
+ stroke: { color: 0x000000, width: 3 },
3062
+ ...config.style,
3063
+ },
3064
+ });
3065
+ this.addChild(this._label);
3066
+ this.visible = false;
3067
+ }
3068
+ /**
3069
+ * Show a win with countup animation.
3070
+ *
3071
+ * @param amount - Win amount
3072
+ * @returns Promise that resolves when the animation completes
3073
+ */
3074
+ async showWin(amount) {
3075
+ this.visible = true;
3076
+ this._cancelCountup = false;
3077
+ this.alpha = 1;
3078
+ const duration = this._config.countupDuration;
3079
+ const startTime = Date.now();
3080
+ // Scale pop
3081
+ this.scale.set(0.5);
3082
+ return new Promise((resolve) => {
3083
+ const tick = () => {
3084
+ if (this._cancelCountup) {
3085
+ this.displayAmount(amount);
3086
+ resolve();
3087
+ return;
3088
+ }
3089
+ const elapsed = Date.now() - startTime;
3090
+ const t = Math.min(elapsed / duration, 1);
3091
+ const eased = Easing.easeOutCubic(t);
3092
+ // Countup
3093
+ const current = amount * eased;
3094
+ this.displayAmount(current);
3095
+ // Scale animation
3096
+ const scaleT = Math.min(elapsed / 300, 1);
3097
+ const scaleEased = Easing.easeOutBack(scaleT);
3098
+ const targetScale = 1;
3099
+ this.scale.set(0.5 + (targetScale - 0.5) * scaleEased);
3100
+ if (t < 1) {
3101
+ requestAnimationFrame(tick);
3102
+ }
3103
+ else {
3104
+ this.displayAmount(amount);
3105
+ this.scale.set(1);
3106
+ resolve();
3107
+ }
3108
+ };
3109
+ requestAnimationFrame(tick);
3110
+ });
3111
+ }
3112
+ /**
3113
+ * Skip the countup animation and show the final amount immediately.
3114
+ */
3115
+ skipCountup(amount) {
3116
+ this._cancelCountup = true;
3117
+ this.displayAmount(amount);
3118
+ this.scale.set(1);
3119
+ }
3120
+ /**
3121
+ * Hide the win display.
3122
+ */
3123
+ hide() {
3124
+ this.visible = false;
3125
+ this._label.text = '';
3126
+ }
3127
+ displayAmount(amount) {
3128
+ this._label.setCurrency(amount, this._config.currency, this._config.locale);
3129
+ }
3130
+ }
3131
+
3132
+ /**
3133
+ * Modal overlay component.
3134
+ * Shows content on top of a dark overlay with enter/exit animations.
3135
+ *
3136
+ * @example
3137
+ * ```ts
3138
+ * const modal = new Modal({ closeOnOverlay: true });
3139
+ * modal.content.addChild(settingsPanel);
3140
+ * modal.onClose = () => console.log('Closed');
3141
+ * await modal.show(1920, 1080);
3142
+ * ```
3143
+ */
3144
+ class Modal extends pixi_js.Container {
3145
+ _overlay;
3146
+ _contentContainer;
3147
+ _config;
3148
+ _showing = false;
3149
+ /** Called when the modal is closed */
3150
+ onClose;
3151
+ constructor(config = {}) {
3152
+ super();
3153
+ this._config = {
3154
+ overlayColor: 0x000000,
3155
+ overlayAlpha: 0.7,
3156
+ closeOnOverlay: true,
3157
+ animationDuration: 300,
3158
+ ...config,
3159
+ };
3160
+ // Overlay
3161
+ this._overlay = new pixi_js.Graphics();
3162
+ this._overlay.eventMode = 'static';
3163
+ this.addChild(this._overlay);
3164
+ if (this._config.closeOnOverlay) {
3165
+ this._overlay.on('pointertap', () => this.hide());
3166
+ }
3167
+ // Content container
3168
+ this._contentContainer = new pixi_js.Container();
3169
+ this.addChild(this._contentContainer);
3170
+ this.visible = false;
3171
+ }
3172
+ /** Content container — add your UI here */
3173
+ get content() {
3174
+ return this._contentContainer;
3175
+ }
3176
+ /** Whether the modal is currently showing */
3177
+ get isShowing() {
3178
+ return this._showing;
3179
+ }
3180
+ /**
3181
+ * Show the modal with animation.
3182
+ */
3183
+ async show(viewWidth, viewHeight) {
3184
+ this._showing = true;
3185
+ this.visible = true;
3186
+ // Draw overlay to cover full screen
3187
+ this._overlay.clear();
3188
+ this._overlay.rect(0, 0, viewWidth, viewHeight).fill(this._config.overlayColor);
3189
+ this._overlay.alpha = 0;
3190
+ // Center content
3191
+ this._contentContainer.x = viewWidth / 2;
3192
+ this._contentContainer.y = viewHeight / 2;
3193
+ this._contentContainer.alpha = 0;
3194
+ this._contentContainer.scale.set(0.8);
3195
+ // Animate in
3196
+ await Promise.all([
3197
+ Tween.to(this._overlay, { alpha: this._config.overlayAlpha }, this._config.animationDuration, Easing.easeOutCubic),
3198
+ Tween.to(this._contentContainer, { alpha: 1, 'scale.x': 1, 'scale.y': 1 }, this._config.animationDuration, Easing.easeOutBack),
3199
+ ]);
3200
+ }
3201
+ /**
3202
+ * Hide the modal with animation.
3203
+ */
3204
+ async hide() {
3205
+ if (!this._showing)
3206
+ return;
3207
+ await Promise.all([
3208
+ Tween.to(this._overlay, { alpha: 0 }, this._config.animationDuration * 0.7, Easing.easeInCubic),
3209
+ Tween.to(this._contentContainer, { alpha: 0, 'scale.x': 0.8, 'scale.y': 0.8 }, this._config.animationDuration * 0.7, Easing.easeInCubic),
3210
+ ]);
3211
+ this.visible = false;
3212
+ this._showing = false;
3213
+ this.onClose?.();
3214
+ }
3215
+ }
3216
+
3217
+ const TOAST_COLORS = {
3218
+ info: 0x3498db,
3219
+ success: 0x27ae60,
3220
+ warning: 0xf39c12,
3221
+ error: 0xe74c3c,
3222
+ };
3223
+ /**
3224
+ * Toast notification component for displaying transient messages.
3225
+ *
3226
+ * @example
3227
+ * ```ts
3228
+ * const toast = new Toast();
3229
+ * scene.container.addChild(toast);
3230
+ * await toast.show('Connection lost', 'error', 1920, 1080);
3231
+ * ```
3232
+ */
3233
+ class Toast extends pixi_js.Container {
3234
+ _bg;
3235
+ _text;
3236
+ _config;
3237
+ _dismissTimeout = null;
3238
+ constructor(config = {}) {
3239
+ super();
3240
+ this._config = {
3241
+ duration: 3000,
3242
+ bottomOffset: 60,
3243
+ ...config,
3244
+ };
3245
+ this._bg = new pixi_js.Graphics();
3246
+ this.addChild(this._bg);
3247
+ this._text = new pixi_js.Text({
3248
+ text: '',
3249
+ style: {
3250
+ fontFamily: '-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',
3251
+ fontSize: 16,
3252
+ fill: 0xffffff,
3253
+ },
3254
+ });
3255
+ this._text.anchor.set(0.5);
3256
+ this.addChild(this._text);
3257
+ this.visible = false;
3258
+ }
3259
+ /**
3260
+ * Show a toast message.
3261
+ */
3262
+ async show(message, type = 'info', viewWidth, viewHeight) {
3263
+ // Clear previous dismiss
3264
+ if (this._dismissTimeout) {
3265
+ clearTimeout(this._dismissTimeout);
3266
+ }
3267
+ this._text.text = message;
3268
+ const padding = 20;
3269
+ const width = Math.max(200, this._text.width + padding * 2);
3270
+ const height = 44;
3271
+ const radius = 8;
3272
+ this._bg.clear();
3273
+ this._bg.roundRect(-width / 2, -height / 2, width, height, radius).fill(TOAST_COLORS[type]);
3274
+ this._bg.roundRect(-width / 2, -height / 2, width, height, radius)
3275
+ .fill({ color: 0x000000, alpha: 0.2 });
3276
+ // Position
3277
+ if (viewWidth && viewHeight) {
3278
+ this.x = viewWidth / 2;
3279
+ this.y = viewHeight - this._config.bottomOffset;
3280
+ }
3281
+ this.visible = true;
3282
+ this.alpha = 0;
3283
+ this.y += 20;
3284
+ // Animate in
3285
+ await Tween.to(this, { alpha: 1, y: this.y - 20 }, 300, Easing.easeOutCubic);
3286
+ // Auto-dismiss
3287
+ if (this._config.duration > 0) {
3288
+ this._dismissTimeout = setTimeout(() => {
3289
+ this.dismiss();
3290
+ }, this._config.duration);
3291
+ }
3292
+ }
3293
+ /**
3294
+ * Dismiss the toast.
3295
+ */
3296
+ async dismiss() {
3297
+ if (!this.visible)
3298
+ return;
3299
+ if (this._dismissTimeout) {
3300
+ clearTimeout(this._dismissTimeout);
3301
+ this._dismissTimeout = null;
3302
+ }
3303
+ await Tween.to(this, { alpha: 0, y: this.y + 20 }, 200, Easing.easeInCubic);
3304
+ this.visible = false;
3305
+ }
3306
+ }
3307
+
3308
+ const DEFAULT_CONFIG = {
3309
+ balance: 10000,
3310
+ currency: 'USD',
3311
+ gameConfig: {
3312
+ id: 'dev-game',
3313
+ type: 'slot',
3314
+ version: '1.0.0',
3315
+ viewport: { width: 1920, height: 1080 },
3316
+ betLevels: [0.1, 0.2, 0.5, 1, 2, 5, 10, 20, 50],
3317
+ },
3318
+ assetsUrl: '/assets/',
3319
+ session: null,
3320
+ onPlay: () => ({}),
3321
+ networkDelay: 200,
3322
+ debug: true,
3323
+ };
3324
+ /**
3325
+ * Mock host bridge for local development.
3326
+ *
3327
+ * Intercepts postMessage communication from the SDK and responds
3328
+ * with mock data, simulating a real casino host environment.
3329
+ *
3330
+ * This allows games to be developed and tested without a real backend.
3331
+ *
3332
+ * @example
3333
+ * ```ts
3334
+ * // In your dev entry point or vite plugin
3335
+ * import { DevBridge } from '@energy8platform/game-engine/debug';
3336
+ *
3337
+ * const devBridge = new DevBridge({
3338
+ * balance: 5000,
3339
+ * currency: 'EUR',
3340
+ * gameConfig: { id: 'my-slot', type: 'slot', betLevels: [0.2, 0.5, 1, 2] },
3341
+ * onPlay: ({ action, bet }) => ({
3342
+ * totalWin: Math.random() > 0.5 ? bet * (Math.random() * 20) : 0,
3343
+ * data: {
3344
+ * matrix: generateRandomMatrix(5, 3, 10),
3345
+ * win_lines: [],
3346
+ * },
3347
+ * }),
3348
+ * });
3349
+ * devBridge.start();
3350
+ * ```
3351
+ */
3352
+ class DevBridge {
3353
+ _config;
3354
+ _balance;
3355
+ _roundCounter = 0;
3356
+ _listening = false;
3357
+ _handler = null;
3358
+ constructor(config = {}) {
3359
+ this._config = { ...DEFAULT_CONFIG, ...config };
3360
+ this._balance = this._config.balance;
3361
+ }
3362
+ /** Current mock balance */
3363
+ get balance() {
3364
+ return this._balance;
3365
+ }
3366
+ /** Start listening for SDK messages */
3367
+ start() {
3368
+ if (this._listening)
3369
+ return;
3370
+ this._handler = (e) => {
3371
+ this.handleMessage(e);
3372
+ };
3373
+ window.addEventListener('message', this._handler);
3374
+ this._listening = true;
3375
+ if (this._config.debug) {
3376
+ console.log('[DevBridge] Started — listening for SDK messages');
3377
+ }
3378
+ }
3379
+ /** Stop listening */
3380
+ stop() {
3381
+ if (this._handler) {
3382
+ window.removeEventListener('message', this._handler);
3383
+ this._handler = null;
3384
+ }
3385
+ this._listening = false;
3386
+ if (this._config.debug) {
3387
+ console.log('[DevBridge] Stopped');
3388
+ }
3389
+ }
3390
+ /** Set mock balance */
3391
+ setBalance(balance) {
3392
+ this._balance = balance;
3393
+ // Send balance update
3394
+ this.sendMessage('BALANCE_UPDATE', { balance: this._balance });
3395
+ }
3396
+ /** Destroy the dev bridge */
3397
+ destroy() {
3398
+ this.stop();
3399
+ }
3400
+ // ─── Message Handling ──────────────────────────────────
3401
+ handleMessage(e) {
3402
+ const data = e.data;
3403
+ // Only process bridge messages
3404
+ if (!data || data.__casino_bridge !== true)
3405
+ return;
3406
+ if (this._config.debug) {
3407
+ console.log('[DevBridge] ←', data.type, data.payload);
3408
+ }
3409
+ switch (data.type) {
3410
+ case 'GAME_READY':
3411
+ this.handleGameReady(data.id);
3412
+ break;
3413
+ case 'PLAY_REQUEST':
3414
+ this.handlePlayRequest(data.payload, data.id);
3415
+ break;
3416
+ case 'PLAY_RESULT_ACK':
3417
+ this.handlePlayAck(data.payload, data.id);
3418
+ break;
3419
+ case 'GET_BALANCE':
3420
+ this.handleGetBalance(data.id);
3421
+ break;
3422
+ case 'GET_STATE':
3423
+ this.handleGetState(data.id);
3424
+ break;
3425
+ case 'OPEN_DEPOSIT':
3426
+ this.handleOpenDeposit();
3427
+ break;
3428
+ default:
3429
+ if (this._config.debug) {
3430
+ console.log('[DevBridge] Unknown message type:', data.type);
3431
+ }
3432
+ }
3433
+ }
3434
+ handleGameReady(id) {
3435
+ const initData = {
3436
+ balance: this._balance,
3437
+ currency: this._config.currency,
3438
+ config: this._config.gameConfig,
3439
+ session: this._config.session,
3440
+ assetsUrl: this._config.assetsUrl,
3441
+ };
3442
+ this.delayedSend('INIT', initData, id);
3443
+ }
3444
+ handlePlayRequest(payload, id) {
3445
+ const { action, bet, roundId } = payload;
3446
+ // Deduct bet
3447
+ this._balance -= bet;
3448
+ this._roundCounter++;
3449
+ // Generate result
3450
+ const customResult = this._config.onPlay({ action, bet, roundId });
3451
+ const totalWin = customResult.totalWin ?? (Math.random() > 0.6 ? bet * (1 + Math.random() * 10) : 0);
3452
+ // Credit win
3453
+ this._balance += totalWin;
3454
+ const result = {
3455
+ roundId: roundId ?? `dev-round-${this._roundCounter}`,
3456
+ action,
3457
+ balanceAfter: this._balance,
3458
+ totalWin: Math.round(totalWin * 100) / 100,
3459
+ data: customResult.data ?? {},
3460
+ nextActions: customResult.nextActions ?? ['spin'],
3461
+ session: customResult.session ?? null,
3462
+ creditPending: false,
3463
+ };
3464
+ this.delayedSend('PLAY_RESULT', result, id);
3465
+ }
3466
+ handlePlayAck(_payload, _id) {
3467
+ if (this._config.debug) {
3468
+ console.log('[DevBridge] Play acknowledged');
3469
+ }
3470
+ }
3471
+ handleGetBalance(id) {
3472
+ this.delayedSend('BALANCE_RESPONSE', { balance: this._balance }, id);
3473
+ }
3474
+ handleGetState(id) {
3475
+ this.delayedSend('STATE_RESPONSE', this._config.session, id);
3476
+ }
3477
+ handleOpenDeposit() {
3478
+ if (this._config.debug) {
3479
+ console.log('[DevBridge] 💰 Open deposit requested (mock: adding 1000)');
3480
+ }
3481
+ this._balance += 1000;
3482
+ this.sendMessage('BALANCE_UPDATE', { balance: this._balance });
3483
+ }
3484
+ // ─── Communication ─────────────────────────────────────
3485
+ delayedSend(type, payload, id) {
3486
+ const delay = this._config.networkDelay;
3487
+ if (delay > 0) {
3488
+ setTimeout(() => this.sendMessage(type, payload, id), delay);
3489
+ }
3490
+ else {
3491
+ this.sendMessage(type, payload, id);
3492
+ }
3493
+ }
3494
+ sendMessage(type, payload, id) {
3495
+ const message = {
3496
+ __casino_bridge: true,
3497
+ type,
3498
+ payload,
3499
+ id,
3500
+ };
3501
+ if (this._config.debug) {
3502
+ console.log('[DevBridge] →', type, payload);
3503
+ }
3504
+ // Post to the same window (SDK listens on window)
3505
+ window.postMessage(message, '*');
3506
+ }
3507
+ }
3508
+
3509
+ /**
3510
+ * FPS overlay for debugging performance.
3511
+ *
3512
+ * Shows FPS, frame time, and draw call count in the corner of the screen.
3513
+ *
3514
+ * @example
3515
+ * ```ts
3516
+ * const fps = new FPSOverlay(app);
3517
+ * fps.show();
3518
+ * ```
3519
+ */
3520
+ class FPSOverlay {
3521
+ _app;
3522
+ _container;
3523
+ _fpsText;
3524
+ _visible = false;
3525
+ _samples = [];
3526
+ _maxSamples = 60;
3527
+ _lastUpdate = 0;
3528
+ _tickFn = null;
3529
+ constructor(app) {
3530
+ this._app = app;
3531
+ this._container = new pixi_js.Container();
3532
+ this._container.label = 'FPSOverlay';
3533
+ this._container.zIndex = 99999;
3534
+ this._fpsText = new pixi_js.Text({
3535
+ text: 'FPS: --',
3536
+ style: {
3537
+ fontFamily: 'monospace',
3538
+ fontSize: 14,
3539
+ fill: 0x00ff00,
3540
+ stroke: { color: 0x000000, width: 2 },
3541
+ },
3542
+ });
3543
+ this._fpsText.x = 8;
3544
+ this._fpsText.y = 8;
3545
+ this._container.addChild(this._fpsText);
3546
+ }
3547
+ /** Show the FPS overlay */
3548
+ show() {
3549
+ if (this._visible)
3550
+ return;
3551
+ this._visible = true;
3552
+ this._app.stage.addChild(this._container);
3553
+ this._tickFn = (ticker) => {
3554
+ this._samples.push(ticker.FPS);
3555
+ if (this._samples.length > this._maxSamples) {
3556
+ this._samples.shift();
3557
+ }
3558
+ // Update display every ~500ms
3559
+ const now = Date.now();
3560
+ if (now - this._lastUpdate > 500) {
3561
+ const avg = this._samples.reduce((a, b) => a + b, 0) / this._samples.length;
3562
+ const min = Math.min(...this._samples);
3563
+ this._fpsText.text = [
3564
+ `FPS: ${Math.round(avg)} (min: ${Math.round(min)})`,
3565
+ `Frame: ${ticker.deltaMS.toFixed(1)}ms`,
3566
+ ].join('\n');
3567
+ this._lastUpdate = now;
3568
+ }
3569
+ };
3570
+ this._app.ticker.add(this._tickFn);
3571
+ }
3572
+ /** Hide the FPS overlay */
3573
+ hide() {
3574
+ if (!this._visible)
3575
+ return;
3576
+ this._visible = false;
3577
+ this._container.removeFromParent();
3578
+ if (this._tickFn) {
3579
+ this._app.ticker.remove(this._tickFn);
3580
+ this._tickFn = null;
3581
+ }
3582
+ }
3583
+ /** Toggle visibility */
3584
+ toggle() {
3585
+ if (this._visible) {
3586
+ this.hide();
3587
+ }
3588
+ else {
3589
+ this.show();
3590
+ }
3591
+ }
3592
+ /** Destroy the overlay */
3593
+ destroy() {
3594
+ this.hide();
3595
+ this._container.destroy({ children: true });
3596
+ }
3597
+ }
3598
+
3599
+ exports.AssetManager = AssetManager;
3600
+ exports.AudioManager = AudioManager;
3601
+ exports.BalanceDisplay = BalanceDisplay;
3602
+ exports.Button = Button;
3603
+ exports.DevBridge = DevBridge;
3604
+ exports.Easing = Easing;
3605
+ exports.EventEmitter = EventEmitter;
3606
+ exports.FPSOverlay = FPSOverlay;
3607
+ exports.GameApplication = GameApplication;
3608
+ exports.InputManager = InputManager;
3609
+ exports.Label = Label;
3610
+ exports.LoadingScene = LoadingScene;
3611
+ exports.Modal = Modal;
3612
+ exports.Panel = Panel;
3613
+ exports.ProgressBar = ProgressBar;
3614
+ exports.Scene = Scene;
3615
+ exports.SceneManager = SceneManager;
3616
+ exports.SpineHelper = SpineHelper;
3617
+ exports.StateMachine = StateMachine;
3618
+ exports.Timeline = Timeline;
3619
+ exports.Toast = Toast;
3620
+ exports.Tween = Tween;
3621
+ exports.ViewportManager = ViewportManager;
3622
+ exports.WinDisplay = WinDisplay;
3623
+ //# sourceMappingURL=index.cjs.js.map