@zylem/game-lib 0.6.3 → 0.7.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 (97) hide show
  1. package/README.md +3 -1
  2. package/dist/actions.d.ts +255 -8
  3. package/dist/actions.js +1 -772
  4. package/dist/audio.d.ts +13 -0
  5. package/dist/audio.js +1 -0
  6. package/dist/base-node-life-cycle-CnJ-7zX-.d.ts +143 -0
  7. package/dist/behavior.d.ts +3 -0
  8. package/dist/behavior.js +1 -0
  9. package/dist/chunk-4QLJUQSJ.js +1 -0
  10. package/dist/chunk-73VZQZUL.js +1 -0
  11. package/dist/chunk-A34ZG3L4.js +1 -0
  12. package/dist/chunk-CDPY4VOQ.js +1 -0
  13. package/dist/chunk-DR6XXZE7.js +19 -0
  14. package/dist/chunk-FM5TBEPO.js +1 -0
  15. package/dist/chunk-G2IIMSUH.js +1 -0
  16. package/dist/chunk-MSC2BEO5.js +1 -0
  17. package/dist/chunk-NIH5CONO.js +1 -0
  18. package/dist/chunk-ONWXGBWB.js +1 -0
  19. package/dist/chunk-QEDQDR27.js +1 -0
  20. package/dist/chunk-QXVH6POE.js +1 -0
  21. package/dist/chunk-RXDTAWI2.js +29 -0
  22. package/dist/chunk-WKHW2QO2.js +1 -0
  23. package/dist/chunk-XRP4JJXL.js +1 -0
  24. package/dist/chunk-YHEWKN7N.js +1 -0
  25. package/dist/chunk-YHKXQ2ZN.js +1 -0
  26. package/dist/core.d.ts +206 -13
  27. package/dist/core.js +24 -9160
  28. package/dist/debug.d.ts +24 -0
  29. package/dist/debug.js +1 -0
  30. package/dist/default-controls-BGc61yYl.d.ts +111 -0
  31. package/dist/entity-DNkYKfdp.d.ts +1043 -0
  32. package/dist/entity-type-map-C94h2TDW.d.ts +781 -0
  33. package/dist/entity.d.ts +265 -0
  34. package/dist/entity.js +1 -0
  35. package/dist/events.d.ts +172 -0
  36. package/dist/events.js +1 -0
  37. package/dist/game-Cuj5gy7U.d.ts +1590 -0
  38. package/dist/game-default-PZLLHYL7.js +1 -0
  39. package/dist/game-interfaces-tfpM5NBk.d.ts +90 -0
  40. package/dist/globals.d.ts +104 -0
  41. package/dist/globals.js +1 -0
  42. package/dist/graphics.d.ts +83 -0
  43. package/dist/graphics.js +1 -0
  44. package/dist/input-ui.d.ts +34 -0
  45. package/dist/input-ui.js +1 -0
  46. package/dist/input.d.ts +72 -0
  47. package/dist/input.js +1 -0
  48. package/dist/material-Wz83vTTp.d.ts +151 -0
  49. package/dist/runtime.d.ts +433 -0
  50. package/dist/runtime.js +1 -0
  51. package/dist/web-components.d.ts +67 -0
  52. package/dist/web-components.js +9 -0
  53. package/dist/world-C9zdyl5d.d.ts +103 -0
  54. package/dist/zylem-stage-runtime-Cs-UDEVU.d.ts +777 -0
  55. package/package.json +54 -41
  56. package/dist/actions.js.map +0 -1
  57. package/dist/behavior/platformer-3d.d.ts +0 -296
  58. package/dist/behavior/platformer-3d.js +0 -518
  59. package/dist/behavior/platformer-3d.js.map +0 -1
  60. package/dist/behavior/ricochet-2d.d.ts +0 -274
  61. package/dist/behavior/ricochet-2d.js +0 -394
  62. package/dist/behavior/ricochet-2d.js.map +0 -1
  63. package/dist/behavior/screen-wrap.d.ts +0 -86
  64. package/dist/behavior/screen-wrap.js +0 -195
  65. package/dist/behavior/screen-wrap.js.map +0 -1
  66. package/dist/behavior/thruster.d.ts +0 -10
  67. package/dist/behavior/thruster.js +0 -234
  68. package/dist/behavior/thruster.js.map +0 -1
  69. package/dist/behavior/world-boundary-2d.d.ts +0 -141
  70. package/dist/behavior/world-boundary-2d.js +0 -181
  71. package/dist/behavior/world-boundary-2d.js.map +0 -1
  72. package/dist/behavior-descriptor-BWNWmIjv.d.ts +0 -142
  73. package/dist/blueprints-BWGz8fII.d.ts +0 -26
  74. package/dist/camera-B5e4c78l.d.ts +0 -468
  75. package/dist/camera.d.ts +0 -6
  76. package/dist/camera.js +0 -1406
  77. package/dist/camera.js.map +0 -1
  78. package/dist/composition-DrzFrbqI.d.ts +0 -218
  79. package/dist/core-DAkskq6Y.d.ts +0 -498
  80. package/dist/core.js.map +0 -1
  81. package/dist/entities-DC9ce_vx.d.ts +0 -416
  82. package/dist/entities.d.ts +0 -9
  83. package/dist/entities.js +0 -4069
  84. package/dist/entities.js.map +0 -1
  85. package/dist/entity-BpbZqg19.d.ts +0 -1100
  86. package/dist/entity-Bq_eNEDI.d.ts +0 -28
  87. package/dist/entity-types-DAu8sGJH.d.ts +0 -26
  88. package/dist/global-change-Dc8uCKi2.d.ts +0 -25
  89. package/dist/main.d.ts +0 -654
  90. package/dist/main.js +0 -13355
  91. package/dist/main.js.map +0 -1
  92. package/dist/stage-types-BFsm3qsZ.d.ts +0 -567
  93. package/dist/stage.d.ts +0 -51
  94. package/dist/stage.js +0 -5738
  95. package/dist/stage.js.map +0 -1
  96. package/dist/thruster-DhRaJnoL.d.ts +0 -172
  97. package/dist/world-Be5m1XC1.d.ts +0 -31
@@ -0,0 +1,1590 @@
1
+ import { d as InputPlayerNumber, e as InputProvider, a as Inputs, U as UpdateFunction, h as SetupFunction, j as DestroyFunction, S as SetupContext, f as UpdateContext, D as DestroyContext, g as LoadingEvent, l as IGame } from './base-node-life-cycle-CnJ-7zX-.js';
2
+ import { G as GameInputConfig, B as BaseGlobals, Z as ZylemGameConfig } from './game-interfaces-tfpM5NBk.js';
3
+ import { G as GameEntity, I as GameEntityOptions, W as WasmStageRuntimeOptions, M as BaseNode, p as WasmStageRuntime, _ as GameEntityLifeCycle } from './entity-DNkYKfdp.js';
4
+ import { Object3D, BufferGeometry, Material, Group, Vector3, Texture, Color } from 'three';
5
+ import { S as StageEntity, Z as ZylemWorld } from './world-C9zdyl5d.js';
6
+ import { k as CameraPerspective, j as CameraContext, g as CameraPose, P as PerspectiveType, o as ZylemCamera, C as CameraBehavior, l as CameraAction, m as CameraPipelineState, e as RendererType, V as Viewport, S as StageRuntimeAdapter, R as RuntimeDebugBinding, p as ZylemScene, f as CameraManager, q as RendererManager } from './zylem-stage-runtime-Cs-UDEVU.js';
7
+ import { RigidBody, Collider } from '@dimforge/rapier3d-compat';
8
+ import { a as Vec3Input, b as Vec2Input, o as ZylemShader, V as Vec3Components } from './material-Wz83vTTp.js';
9
+ import { BehaviorSystem, BehaviorEntityLink, BehaviorSystemFactory } from '@zylem/behaviors/core';
10
+ import { ac as EntityTypeMap } from './entity-type-map-C94h2TDW.js';
11
+ import { StageEvents, GameEvents } from './events.js';
12
+ import { D as DefaultTouchControlsOptions } from './default-controls-BGc61yYl.js';
13
+
14
+ declare class InputManager {
15
+ private inputMap;
16
+ private currentInputs;
17
+ private previousInputs;
18
+ private readonly targetElement?;
19
+ private readonly mouseTargetElement?;
20
+ constructor(config?: GameInputConfig, options?: {
21
+ targetElement?: HTMLElement;
22
+ mouseTargetElement?: HTMLElement;
23
+ });
24
+ /**
25
+ * Reconfigure keyboard and mouse providers at runtime without affecting gamepad providers.
26
+ * Disposes existing keyboard/mouse providers and creates new ones from the given config.
27
+ */
28
+ configure(config: GameInputConfig): void;
29
+ addInputProvider(playerNumber: InputPlayerNumber, provider: InputProvider): void;
30
+ dispose(): void;
31
+ getInputs(delta: number): Inputs;
32
+ private buildPlayerEntries;
33
+ private addConfigurableProviders;
34
+ private createConfigurableProviders;
35
+ private mergeInputs;
36
+ }
37
+
38
+ /**
39
+ * This class is an alternative to {@link Clock} with a different API design and behavior.
40
+ * The goal is to avoid the conceptual flaws that became apparent in `Clock` over time.
41
+ *
42
+ * - `Timer` has an `update()` method that updates its internal state. That makes it possible to
43
+ * call `getDelta()` and `getElapsed()` multiple times per simulation step without getting different values.
44
+ * - The class can make use of the Page Visibility API to avoid large time delta values when the app
45
+ * is inactive (e.g. tab switched or browser hidden).
46
+ *
47
+ * ```js
48
+ * const timer = new Timer();
49
+ * timer.connect( document ); // use Page Visibility API
50
+ * ```
51
+ *
52
+ * @three_import import { Timer } from 'three/addons/misc/Timer.js';
53
+ */
54
+ declare class Timer {
55
+ protected _previousTime: number;
56
+ protected _currentTime: number;
57
+ protected _startTime: number;
58
+ protected _delta: number;
59
+ protected _elapsed: number;
60
+ protected _timescale: number;
61
+ protected _document: Document | null;
62
+ protected _pageVisibilityHandler: (() => void) | null;
63
+ /**
64
+ * Constructs a new timer.
65
+ */
66
+ constructor();
67
+ /**
68
+ * Connect the timer to the given document.Calling this method is not mandatory to
69
+ * use the timer but enables the usage of the Page Visibility API to avoid large time
70
+ * delta values.
71
+ *
72
+ * @param {Document} document - The document.
73
+ */
74
+ connect(document: Document): void;
75
+ /**
76
+ * Disconnects the timer from the DOM and also disables the usage of the Page Visibility API.
77
+ */
78
+ disconnect(): void;
79
+ /**
80
+ * Returns the time delta in seconds.
81
+ *
82
+ * @return {number} The time delta in second.
83
+ */
84
+ getDelta(): number;
85
+ /**
86
+ * Returns the elapsed time in seconds.
87
+ *
88
+ * @return {number} The elapsed time in second.
89
+ */
90
+ getElapsed(): number;
91
+ /**
92
+ * Returns the timescale.
93
+ *
94
+ * @return {number} The timescale.
95
+ */
96
+ getTimescale(): number;
97
+ /**
98
+ * Sets the given timescale which scale the time delta computation
99
+ * in `update()`.
100
+ *
101
+ * @param {number} timescale - The timescale to set.
102
+ * @return {Timer} A reference to this timer.
103
+ */
104
+ setTimescale(timescale: number): Timer;
105
+ /**
106
+ * Resets the time computation for the current simulation step.
107
+ *
108
+ * @return {Timer} A reference to this timer.
109
+ */
110
+ reset(): Timer;
111
+ /**
112
+ * Can be used to free all internal resources. Usually called when
113
+ * the timer instance isn't required anymore.
114
+ */
115
+ dispose(): void;
116
+ /**
117
+ * Updates the internal state of the timer. This method should be called
118
+ * once per simulation step and before you perform queries against the timer
119
+ * (e.g. via `getDelta()`).
120
+ *
121
+ * @param {number} timestamp - The current time in milliseconds. Can be obtained
122
+ * from the `requestAnimationFrame` callback argument. If not provided, the current
123
+ * time will be determined with `performance.now`.
124
+ * @return {Timer} A reference to this timer.
125
+ */
126
+ update(timestamp?: number): Timer;
127
+ }
128
+
129
+ /**
130
+ * Configuration for batch key generation
131
+ */
132
+ interface BatchKeyConfig {
133
+ geometryType: string;
134
+ dimensions: Record<string, number>;
135
+ materialPath?: string | null;
136
+ shaderType?: 'standard' | 'custom';
137
+ colorHex?: number;
138
+ }
139
+ /**
140
+ * Manages instanced mesh batching for entities
141
+ */
142
+ declare class InstanceManager {
143
+ private batches;
144
+ private entityToBatch;
145
+ private scene;
146
+ /** Default initial capacity for new batches */
147
+ static DEFAULT_CAPACITY: number;
148
+ /** Factor to grow batch when full */
149
+ static GROWTH_FACTOR: number;
150
+ /**
151
+ * Set the scene to add instanced meshes to
152
+ */
153
+ setScene(scene: Object3D): void;
154
+ /**
155
+ * Generate a batch key from configuration
156
+ */
157
+ static generateBatchKey(config: BatchKeyConfig): string;
158
+ static generateEntityBatchKey(entity: Pick<GameEntity<GameEntityOptions>, 'options' | 'materials'> & {
159
+ constructor: any;
160
+ }): string;
161
+ /**
162
+ * Register an entity with the instance manager
163
+ * @returns The instance index, or -1 if registration failed
164
+ */
165
+ register(entity: GameEntity<any>, geometry: BufferGeometry, material: Material, batchKey: string): number;
166
+ /**
167
+ * Unregister an entity from the instance manager
168
+ */
169
+ unregister(entity: GameEntity<any>): void;
170
+ /**
171
+ * Mark an entity's transform as dirty (needs syncing)
172
+ */
173
+ markDirty(entity: GameEntity<any>): void;
174
+ /**
175
+ * Update all dirty instance transforms
176
+ * Call this once per frame
177
+ */
178
+ /**
179
+ * Update all active instance transforms
180
+ * Call this once per frame
181
+ */
182
+ update(): void;
183
+ private updateInstanceMatrix;
184
+ /**
185
+ * Get batch info for an entity
186
+ */
187
+ getBatchInfo(entity: GameEntity<any>): {
188
+ batchKey: string;
189
+ instanceId: number;
190
+ } | null;
191
+ /**
192
+ * Get statistics about current batching
193
+ */
194
+ getStats(): {
195
+ batchCount: number;
196
+ totalInstances: number;
197
+ batches: {
198
+ key: string;
199
+ count: number;
200
+ capacity: number;
201
+ }[];
202
+ };
203
+ /**
204
+ * Dispose all batches and release resources
205
+ */
206
+ dispose(): void;
207
+ /**
208
+ * Create a new batch group
209
+ */
210
+ private createBatch;
211
+ /**
212
+ * Grow a batch's capacity
213
+ */
214
+ private growBatch;
215
+ }
216
+
217
+ /**
218
+ * Base entity interface - shared across modules to prevent circular dependencies
219
+ */
220
+ interface BaseEntityInterface {
221
+ uuid: string;
222
+ name: string;
223
+ group: Group | null | undefined;
224
+ body: RigidBody | null | undefined;
225
+ collider: Collider | null | undefined;
226
+ }
227
+ /**
228
+ * Game entity interface - minimal interface to break circular dependencies
229
+ */
230
+ interface GameEntityInterface extends BaseEntityInterface {
231
+ type: string;
232
+ isStatic: boolean;
233
+ setPosition(x: number, y: number, z: number): void;
234
+ setRotation(x: number, y: number, z: number): void;
235
+ setScale(x: number, y: number, z: number): void;
236
+ }
237
+
238
+ /**
239
+ * Provides BaseNode-like lifecycle without ECS/children. Consumers implement
240
+ * the protected hooks and may assign public setup/update/destroy callbacks.
241
+ */
242
+ declare abstract class LifeCycleBase<TSelf> {
243
+ update: UpdateFunction<TSelf>;
244
+ setup: SetupFunction<TSelf>;
245
+ destroy: DestroyFunction<TSelf>;
246
+ protected abstract _setup(context: SetupContext<TSelf>): void;
247
+ protected abstract _update(context: UpdateContext<TSelf>): void;
248
+ protected abstract _destroy(context: DestroyContext<TSelf>): void;
249
+ nodeSetup(context: SetupContext<TSelf>): void;
250
+ nodeUpdate(context: UpdateContext<TSelf>): void;
251
+ nodeDestroy(context: DestroyContext<TSelf>): void;
252
+ }
253
+
254
+ /**
255
+ * Configuration for the third-person perspective.
256
+ */
257
+ interface ThirdPersonOptions {
258
+ /** Distance behind the target. Default 8. */
259
+ distance?: number;
260
+ /** Height above the target. Default 5. */
261
+ height?: number;
262
+ /** Lateral offset from the target (shoulder cam). Default 0. */
263
+ shoulderOffset?: number;
264
+ /** Key in CameraContext.targets to follow. Default 'primary'. */
265
+ targetKey?: string;
266
+ /** Perspective field of view. Default 75. */
267
+ fov?: number;
268
+ /** Padding multiplier when framing multiple targets. Default 1.5. */
269
+ paddingFactor?: number;
270
+ /** Minimum camera distance when multi-framing. Default 5. */
271
+ minDistance?: number;
272
+ /** Fallback camera position when no targets exist (e.g. the user-specified initial position). */
273
+ initialPosition?: Vec3Input;
274
+ /** Fallback lookAt point when no targets exist. */
275
+ initialLookAt?: Vec3Input;
276
+ /**
277
+ * Seconds the camera lags behind the target's actual position. The camera
278
+ * samples target moves from `now - trailDelay` so brief, fast Y motion
279
+ * (jump apex / fall start) doesn't get tracked 1:1 — eliminates the
280
+ * shimmer-on-fall effect at high refresh rates. 0 disables the trail and
281
+ * restores instantaneous tracking. Default 0.1 (100 ms).
282
+ */
283
+ trailDelay?: number;
284
+ /**
285
+ * Maximum number of samples to keep in the trailing ring buffer.
286
+ * Sized to cover ~1 s at 120 Hz; larger only matters if `trailDelay` is
287
+ * raised significantly. Default 120.
288
+ */
289
+ trailBufferSize?: number;
290
+ }
291
+ /**
292
+ * Third-person 3D perspective.
293
+ *
294
+ * - 0 targets: returns a static pose behind the origin.
295
+ * - 1 target: camera positioned behind and above the target, looking at it.
296
+ * - 2+ targets: weighted-centroid framing with dynamic distance.
297
+ */
298
+ declare class ThirdPersonPerspective implements CameraPerspective {
299
+ readonly id = "third-person";
300
+ /**
301
+ * Slightly looser than the previous 0.15 to compose better with the
302
+ * trailing-delay follow: the trail absorbs short, fast moves and the
303
+ * damping smooths the rest.
304
+ */
305
+ readonly defaults: {
306
+ damping: number;
307
+ };
308
+ private opts;
309
+ private initialPosition?;
310
+ private initialLookAt?;
311
+ /** Per-target ring buffers for trailing-delay sampling, keyed by target key. */
312
+ private _trailBuffers;
313
+ constructor(options?: ThirdPersonOptions);
314
+ getBasePose(ctx: CameraContext): CameraPose;
315
+ /**
316
+ * No targets: use the user-specified initial position if available,
317
+ * otherwise fall back to a default pose behind the origin.
318
+ */
319
+ private staticPose;
320
+ /**
321
+ * Single target: position = trailedTarget + offset, lookAt = trailedTarget.
322
+ *
323
+ * The trailed position lags `targetPos` by `trailDelay` seconds (default
324
+ * 100 ms), so transient spikes in target Y (the start of a fall, jump apex)
325
+ * don't propagate into the camera every frame. Both `position` and
326
+ * `lookAt` are derived from the same trailed point so the relative offset
327
+ * is preserved exactly.
328
+ */
329
+ private singleTargetPose;
330
+ /**
331
+ * Multi-target: compute centroid (using trailed positions) and adjust
332
+ * distance to frame all targets.
333
+ */
334
+ private multiTargetPose;
335
+ /**
336
+ * Push the current target position into the per-target ring buffer and
337
+ * return a position interpolated at `now - trailDelay`.
338
+ *
339
+ * - When `trailDelay` is 0 the call short-circuits and returns `targetPos`
340
+ * unchanged (no allocation, no buffer growth).
341
+ * - During the warmup window (the first `trailDelay` seconds of life)
342
+ * the oldest sample is returned so the camera starts from rest rather
343
+ * than snapping to the live target.
344
+ */
345
+ private getTrailedPosition;
346
+ }
347
+
348
+ /**
349
+ * Configuration for the fixed 2D perspective.
350
+ */
351
+ interface Fixed2DOptions {
352
+ /** Fixed camera position. Default (0, 0, 10). */
353
+ position?: Vec3Input;
354
+ /** Orthographic zoom (frustum size). Default 10. */
355
+ zoom?: number;
356
+ }
357
+ /**
358
+ * Fixed 2D perspective.
359
+ *
360
+ * Returns a static orthographic pose looking down the Z-axis.
361
+ * No target following -- the camera stays at the configured position.
362
+ */
363
+ declare class Fixed2DPerspective implements CameraPerspective {
364
+ readonly id = "fixed-2d";
365
+ readonly defaults: {
366
+ damping: number;
367
+ };
368
+ private opts;
369
+ constructor(options?: Fixed2DOptions);
370
+ getBasePose(_ctx: CameraContext): CameraPose;
371
+ }
372
+
373
+ /**
374
+ * Configuration for the first-person perspective.
375
+ */
376
+ interface FirstPersonOptions {
377
+ /** Vertical offset above the target entity's position (eye height). @default 1.7 */
378
+ eyeHeight?: number;
379
+ /** Default field of view in degrees. @default 75 */
380
+ defaultFov?: number;
381
+ /** Maximum pitch angle in radians. @default Math.PI/2 - 0.01 */
382
+ pitchLimit?: number;
383
+ /** Lerp speed for smooth look-at transitions. @default 5 */
384
+ lookAtLerpSpeed?: number;
385
+ /** Lerp speed for FOV zoom transitions. @default 8 */
386
+ fovLerpSpeed?: number;
387
+ /** Key in CameraContext.targets to follow. @default 'primary' */
388
+ targetKey?: string;
389
+ /** Fallback position when no target entity is attached. */
390
+ initialPosition?: Vec3Input;
391
+ /** Fallback look-at point used to derive initial yaw/pitch when no target. */
392
+ initialLookAt?: Vec3Input;
393
+ /**
394
+ * Vertical (eye-height) smoothing factor in 0..1, applied per 60Hz frame.
395
+ * 1 = instant snap (no smoothing), lower = smoother. Hides physics
396
+ * micro-jitter and Rapier sub-step Y corrections without adding perceptible
397
+ * input lag. Smooths only Y; X/Z still snap to the target every frame so
398
+ * horizontal aim is never laggy.
399
+ * @default 1 (disabled)
400
+ */
401
+ verticalSmoothing?: number;
402
+ }
403
+ /**
404
+ * First-person camera perspective.
405
+ *
406
+ * Position is derived from the attached target entity (+ eye height).
407
+ * Rotation is driven via `look()` / `setLook()` methods called by game code
408
+ * or a future FPS behavior. Supports smooth FOV zoom and lerp'd look-at.
409
+ */
410
+ declare class FirstPersonPerspective implements CameraPerspective {
411
+ readonly id = "first-person";
412
+ readonly defaults: {
413
+ damping: number;
414
+ };
415
+ private opts;
416
+ /** Fallback position when no target entity is attached. Mutate directly for manual movement. */
417
+ initialPosition?: Vector3;
418
+ private initialLookAt?;
419
+ private _yaw;
420
+ private _pitch;
421
+ private _currentFov;
422
+ private _targetFov;
423
+ private _lookAtTarget;
424
+ private _lookAtLerpSpeed;
425
+ private _currentRotation;
426
+ private _rotationInitialized;
427
+ private _smoothedY;
428
+ constructor(options?: FirstPersonOptions);
429
+ /** Accumulate yaw and pitch deltas. Pitch is clamped to the configured limit. */
430
+ look(deltaYaw: number, deltaPitch: number): void;
431
+ /** Set absolute yaw and pitch. Pitch is clamped to the configured limit. */
432
+ setLook(yaw: number, pitch: number): void;
433
+ /** Current yaw in radians. */
434
+ get yaw(): number;
435
+ /** Current pitch in radians. */
436
+ get pitch(): number;
437
+ /** Set the target FOV for a smooth zoom transition (e.g. sniper scope). */
438
+ zoom(fov: number): void;
439
+ /** Return to the default FOV. */
440
+ resetZoom(): void;
441
+ /** Current field of view. */
442
+ get currentFov(): number;
443
+ /**
444
+ * Enable smooth look-at toward a world position.
445
+ * The camera will slerp from the current rotation toward the look-at direction.
446
+ */
447
+ lookAt(target: Vector3, lerpSpeed?: number): void;
448
+ /** Disable look-at and return to manual yaw/pitch control. */
449
+ clearLookAt(): void;
450
+ getBasePose(ctx: CameraContext): CameraPose;
451
+ private computePosition;
452
+ /**
453
+ * Low-pass filter the eye Y so Rapier sub-step corrections and probe-driven
454
+ * micro-bobs don't show up as visible head jitter. X/Z are left un-smoothed
455
+ * so horizontal aim remains 1:1 with input.
456
+ */
457
+ private smoothVertical;
458
+ private computeRotation;
459
+ private lerpFov;
460
+ private deriveYawPitchFromLookAt;
461
+ private deriveYawPitchFromQuaternion;
462
+ }
463
+
464
+ /**
465
+ * Perspective-specific options union.
466
+ * Extend as new perspective types are added.
467
+ */
468
+ type PerspectiveOptions = ThirdPersonOptions | Fixed2DOptions | FirstPersonOptions;
469
+ /**
470
+ * Factory: create a CameraPerspective from a PerspectiveType string.
471
+ * Unrecognized types default to ThirdPersonPerspective.
472
+ */
473
+ declare function createPerspective(type: PerspectiveType, options?: PerspectiveOptions): CameraPerspective;
474
+
475
+ interface CameraOptions {
476
+ perspective?: PerspectiveType;
477
+ position?: Vec3Input;
478
+ target?: Vec3Input;
479
+ zoom?: number;
480
+ screenResolution?: Vec2Input;
481
+ /**
482
+ * Renderer type.
483
+ *
484
+ * @deprecated game-lib always renders with WebGPU (Three.js keeps its own
485
+ * internal WebGL2 fallback for devices without WebGPU). This option is
486
+ * ignored and retained only for backward compatibility.
487
+ * @default 'webgpu'
488
+ */
489
+ rendererType?: RendererType;
490
+ /**
491
+ * Enable orbital controls for this camera.
492
+ * Can be toggled at runtime via enableOrbitalControls() / disableOrbitalControls().
493
+ * @default false
494
+ */
495
+ useOrbitalControls?: boolean;
496
+ /**
497
+ * Viewport in normalized coordinates (0-1).
498
+ * Defines where this camera renders on the canvas.
499
+ * @default { x: 0, y: 0, width: 1, height: 1 } (fullscreen)
500
+ */
501
+ viewport?: Viewport;
502
+ /**
503
+ * Optional name for camera manager lookup.
504
+ */
505
+ name?: string;
506
+ /**
507
+ * Initial behaviors to attach to the camera pipeline.
508
+ * Keys are used for idempotent add/remove.
509
+ */
510
+ behaviors?: Record<string, CameraBehavior>;
511
+ /**
512
+ * Pipeline smoothing factor (0-1).
513
+ * 1 = instant snap, 0 = no movement.
514
+ * @default 0.15
515
+ */
516
+ damping?: number;
517
+ /**
518
+ * When set, the camera renders to an offscreen texture instead of a
519
+ * screen viewport. Use with setCameraFeed() to display the feed on
520
+ * an in-scene mesh (jumbotron, security monitor, portal, etc.).
521
+ *
522
+ * @default undefined (renders to screen)
523
+ */
524
+ renderToTexture?: {
525
+ /** Texture width in pixels. @default 512 */
526
+ width?: number;
527
+ /** Texture height in pixels. @default 512 */
528
+ height?: number;
529
+ };
530
+ /**
531
+ * When true, this camera will not activate orbital controls in debug mode.
532
+ * The pipeline (and its behaviors) will always run for this camera.
533
+ * Use for cameras with custom behaviors (e.g. FPS mouse-look) that must
534
+ * control the camera through the pipeline rather than debug orbit controls.
535
+ * @default false
536
+ */
537
+ skipDebugOrbit?: boolean;
538
+ }
539
+ /**
540
+ * CameraWrapper is the user-facing camera handle returned by createCamera().
541
+ * It provides convenience methods for target management, orbital controls,
542
+ * viewport configuration, and the camera pose pipeline.
543
+ */
544
+ declare class CameraWrapper {
545
+ cameraRef: ZylemCamera;
546
+ constructor(camera: ZylemCamera);
547
+ /**
548
+ * Add a target entity for the camera to follow/frame.
549
+ * With multiple targets, the camera auto-frames to include all of them.
550
+ */
551
+ addTarget(entity: StageEntity): void;
552
+ /**
553
+ * Remove a target entity from the camera.
554
+ */
555
+ removeTarget(entity: StageEntity): void;
556
+ /**
557
+ * Clear all targets. Camera will look at world origin.
558
+ */
559
+ clearTargets(): void;
560
+ /**
561
+ * Enable orbital controls for this camera.
562
+ * Allows the user to orbit, pan, and zoom the camera.
563
+ */
564
+ enableOrbitalControls(): void;
565
+ /**
566
+ * Disable orbital controls for this camera.
567
+ */
568
+ disableOrbitalControls(): void;
569
+ /**
570
+ * Set the viewport for this camera (normalized 0-1 coordinates).
571
+ * @param x Left edge (0 = left of canvas)
572
+ * @param y Bottom edge (0 = bottom of canvas)
573
+ * @param width Width as fraction of canvas
574
+ * @param height Height as fraction of canvas
575
+ */
576
+ setViewport(x: number, y: number, width: number, height: number): void;
577
+ /**
578
+ * Add or replace a behavior by key (idempotent).
579
+ * Behaviors modify the desired camera pose each frame.
580
+ *
581
+ * @param key Unique key for this behavior (used for replacement/removal).
582
+ * @param behavior The CameraBehavior implementation.
583
+ */
584
+ addBehavior(key: string, behavior: CameraBehavior): void;
585
+ /**
586
+ * Remove a behavior by key.
587
+ */
588
+ removeBehavior(key: string): boolean;
589
+ /**
590
+ * Add a transient action (screenshake, recoil, etc.).
591
+ * Actions apply additive deltas and self-expire when isDone() returns true.
592
+ */
593
+ addAction(action: CameraAction): void;
594
+ /**
595
+ * Switch the camera's active perspective at runtime.
596
+ * The first frame after switching snaps to the new pose (no lerp).
597
+ *
598
+ * @param type Perspective type string (e.g. Perspectives.ThirdPerson).
599
+ * @param options Perspective-specific options (distance, height, zoom, etc.).
600
+ */
601
+ setPerspective(type: PerspectiveType, options?: PerspectiveOptions): void;
602
+ /**
603
+ * Retrieve the active perspective instance, cast to the desired type.
604
+ * Useful for calling perspective-specific methods (e.g. FirstPersonPerspective.look()).
605
+ *
606
+ * @example
607
+ * const fps = camera.getPerspective<FirstPersonPerspective>();
608
+ * fps.look(dx, dy);
609
+ */
610
+ getPerspective<T extends CameraPerspective = CameraPerspective>(): T;
611
+ /**
612
+ * Return a debug snapshot of the camera pipeline state.
613
+ * Includes: active perspective, desired/final pose, behavior keys, action count.
614
+ */
615
+ getState(): CameraPipelineState;
616
+ /**
617
+ * Get the offscreen render texture for this camera.
618
+ * Returns null if the camera was not created with renderToTexture.
619
+ * Use with setCameraFeed() or apply directly to a mesh material.
620
+ */
621
+ getRenderTexture(): Texture | null;
622
+ }
623
+ /**
624
+ * Create a camera with the given options.
625
+ * Returns a CameraWrapper for convenient access to camera features.
626
+ */
627
+ declare function createCamera(options: CameraOptions): CameraWrapper;
628
+
629
+ type AddEntityFactory = (params: {
630
+ position: Vector3;
631
+ normal?: Vector3;
632
+ }) => Promise<any> | any;
633
+ interface StageDebugDelegateOptions {
634
+ maxRayDistance?: number;
635
+ addEntityFactory?: AddEntityFactory | null;
636
+ }
637
+ /**
638
+ * Self-managing debug delegate that subscribes to `debugState` internally.
639
+ *
640
+ * When debug is enabled it lazily initializes visuals and DOM listeners.
641
+ * When debug is disabled it tears down visuals but stays alive so it can
642
+ * re-activate without being recreated. Call `dispose()` to fully tear down.
643
+ */
644
+ declare class StageDebugDelegate {
645
+ private stage;
646
+ private options;
647
+ private mouseNdc;
648
+ private raycaster;
649
+ private isMouseDown;
650
+ private domDisposeFns;
651
+ private domListenersAttached;
652
+ private debugCursor;
653
+ private debugLines;
654
+ private runtimeDebugLines;
655
+ private cameraDebugDelegate;
656
+ private debugStateUnsubscribe;
657
+ constructor(stage: ZylemStage, options?: StageDebugDelegateOptions);
658
+ private syncWithDebugState;
659
+ /** Initialize DOM listeners and camera debug delegate when debug is turned on. */
660
+ private activate;
661
+ /** Tear down visuals and camera debug delegate when debug is turned off. */
662
+ private deactivate;
663
+ private initDebugVisuals;
664
+ private disposeDebugVisuals;
665
+ update(): void;
666
+ /** Full teardown — unsubscribes from debugState and cleans up all resources. */
667
+ dispose(): void;
668
+ private handleActionOnHit;
669
+ private attachDomListeners;
670
+ }
671
+
672
+ /** Source for the unified-Stage wasm runtime: bytes, fetch URL, or a builder. */
673
+ type StageWasmSource = ArrayBuffer | RequestInfo | URL | (() => Promise<ArrayBuffer | RequestInfo | URL>);
674
+ /** Authoring-side configuration for the unified-Stage wasm runtime. */
675
+ interface StageWasmRuntimeConfig {
676
+ /** wasm bytes (ArrayBuffer) or a URL/`fetch` input that resolves to bytes. */
677
+ source: StageWasmSource;
678
+ /** Forwarded to {@link WasmStageRuntime} construction. */
679
+ options?: Omit<WasmStageRuntimeOptions, 'imports'>;
680
+ }
681
+ type StageGLTFAssetLoaderConfig = {
682
+ meshopt?: boolean;
683
+ ktx2TranscoderPath?: URL | string;
684
+ };
685
+ type StageAssetLoaderConfig = {
686
+ gltf?: StageGLTFAssetLoaderConfig;
687
+ };
688
+ /**
689
+ * Stage configuration type for user-facing options.
690
+ */
691
+ type StageConfigLike = Partial<{
692
+ inputs: Record<string, string[]>;
693
+ backgroundColor: Color | string;
694
+ backgroundImage: string | null;
695
+ backgroundShader: ZylemShader;
696
+ gravity: Vector3 | Vec3Components;
697
+ variables: Record<string, any>;
698
+ /** Physics update rate in Hz (default 60). */
699
+ physicsRate: number;
700
+ assetLoaders: StageAssetLoaderConfig;
701
+ runtimeAdapter: StageRuntimeAdapter;
702
+ /** Binds stage debug policy into wasm runtime adapters (see {@link RuntimeDebugBinding}). */
703
+ runtimeDebugBinding?: RuntimeDebugBinding;
704
+ /**
705
+ * When set, the stage instantiates a {@link WasmStageRuntime} from the given
706
+ * source during `load()`. Behavior descriptors that have been ported to the
707
+ * unified-Stage Rust runtime read this via `BehaviorSystemContext.wasmStage`.
708
+ */
709
+ wasmRuntime?: StageWasmRuntimeConfig;
710
+ /**
711
+ * When `false`, the engine's built-in ambient + directional lights are
712
+ * suppressed so the stage can be lit entirely via `createLight(...)`
713
+ * entities. Defaults to `true`.
714
+ */
715
+ defaultLighting: boolean;
716
+ }>;
717
+ /**
718
+ * Factory for authoring stage configuration objects in user code.
719
+ * Returns a plain object that can be passed to `createStage(...)`.
720
+ */
721
+ declare function stageConfig(config: StageConfigLike): StageConfigLike;
722
+
723
+ /**
724
+ * Delegate for managing loading events and progress within a stage.
725
+ * Handles subscription to loading events and broadcasting progress.
726
+ * Emits to game event bus for game-level observation.
727
+ */
728
+ declare class StageLoadingDelegate {
729
+ private loadingHandlers;
730
+ private stageName?;
731
+ private stageIndex?;
732
+ /**
733
+ * Set stage context for event bus emissions.
734
+ */
735
+ setStageContext(stageName: string, stageIndex: number): void;
736
+ /**
737
+ * Subscribe to loading events.
738
+ *
739
+ * @param callback Invoked for each loading event (start, progress, complete)
740
+ * @returns Unsubscribe function
741
+ */
742
+ onLoading(callback: (event: LoadingEvent) => void): () => void;
743
+ /**
744
+ * Emit a loading event to all subscribers and to the game event bus.
745
+ *
746
+ * @param event The loading event to broadcast
747
+ */
748
+ emit(event: LoadingEvent): void;
749
+ /**
750
+ * Emit a start loading event.
751
+ */
752
+ emitStart(message?: string): void;
753
+ /**
754
+ * Emit a progress loading event.
755
+ */
756
+ emitProgress(message: string, current: number, total: number): void;
757
+ /**
758
+ * Emit a complete loading event.
759
+ */
760
+ emitComplete(message?: string): void;
761
+ /**
762
+ * Clear all loading handlers.
763
+ */
764
+ dispose(): void;
765
+ }
766
+
767
+ /**
768
+ * Delegate for handling deferred model loading in entities.
769
+ * Subscribes to model:loaded events and adds entity groups to the scene
770
+ * when they become available after async loading completes.
771
+ */
772
+ declare class StageEntityModelDelegate {
773
+ private scene;
774
+ private onEntityReady;
775
+ private pendingEntities;
776
+ private modelLoadedHandler;
777
+ /**
778
+ * Initialize the delegate with the scene reference and start listening.
779
+ */
780
+ attach(scene: ZylemScene, onEntityReady?: (entity: GameEntity<any>) => void): void;
781
+ /**
782
+ * Register an entity for observation.
783
+ * When its model loads, the group will be added to the scene.
784
+ */
785
+ observe(entity: GameEntity<any>): void;
786
+ /**
787
+ * Unregister an entity (e.g., when removed before model loads).
788
+ */
789
+ unobserve(entityId: string): void;
790
+ /**
791
+ * Handle model loaded event - add group to scene if entity is pending.
792
+ */
793
+ private handleModelLoaded;
794
+ /**
795
+ * Cleanup all subscriptions and pending entities.
796
+ */
797
+ dispose(): void;
798
+ }
799
+
800
+ type NodeLike$1 = {
801
+ create: Function;
802
+ };
803
+ type StageEntityInput = NodeLike$1 | Promise<any> | (() => NodeLike$1 | Promise<any>);
804
+ /**
805
+ * Runtime context provided by ZylemStage after scene and world are initialized.
806
+ */
807
+ interface EntityDelegateContext {
808
+ scene: ZylemScene;
809
+ world: ZylemWorld;
810
+ instanceManager: InstanceManager | null;
811
+ /** Resolved camera for entity setup contexts. */
812
+ camera: ZylemCamera;
813
+ runtimeAdapter?: StageRuntimeAdapter | null;
814
+ /** Optional unified-Stage wasm runtime (Phase 2+ of the runtime-only migration). */
815
+ wasmStage?: WasmStageRuntime | null;
816
+ }
817
+ /**
818
+ * Delegate responsible for entity spawning, tracking, queuing, removal, and lookup.
819
+ *
820
+ * Owns all entity-related state and exposes it to ZylemStage for orchestration
821
+ * and to external consumers (debug delegate, transform system) via public getters.
822
+ */
823
+ declare class StageEntityDelegate {
824
+ private static readonly EMPTY_BEHAVIOR_LINKS;
825
+ /** Entities queued before load completes. */
826
+ children: BaseNode[];
827
+ /** UUID → BaseNode map of all live entities. */
828
+ readonly childrenMap: Map<string, BaseNode>;
829
+ /** UUID → BaseNode map populated when debug mode is active. */
830
+ readonly debugMap: Map<string, BaseNode>;
831
+ private pendingEntities;
832
+ private pendingPromises;
833
+ private _isLoaded;
834
+ private entityAddedHandlers;
835
+ /** ECS behavior systems auto-registered from entity refs or manually added. */
836
+ readonly behaviorSystems: BehaviorSystem[];
837
+ readonly behaviorSystemByKey: Map<symbol, BehaviorSystem>;
838
+ readonly registeredSystemKeys: Set<symbol>;
839
+ readonly behaviorEntityIndex: Map<symbol, Set<BehaviorEntityLink>>;
840
+ private readonly behaviorLinksByUuid;
841
+ private scene;
842
+ private world;
843
+ private instanceManager;
844
+ private camera;
845
+ private runtimeAdapter;
846
+ /** Unified-Stage wasm runtime; shared with descriptor `systemFactory` calls. */
847
+ wasmStage: WasmStageRuntime | null;
848
+ private loadingDelegate;
849
+ private entityModelDelegate;
850
+ constructor(loadingDelegate: StageLoadingDelegate, entityModelDelegate: StageEntityModelDelegate);
851
+ get isLoaded(): boolean;
852
+ set isLoaded(value: boolean);
853
+ /**
854
+ * Bind runtime context after scene and world are initialized.
855
+ * Must be called before any spawn/enqueue operations.
856
+ */
857
+ attach(context: EntityDelegateContext): void;
858
+ /**
859
+ * Create, register, and add an entity to the scene/world.
860
+ * Safe to call only after `attach` when scene/world exist.
861
+ */
862
+ spawnEntity(child: BaseNode): Promise<void>;
863
+ handleLateModelReady(entity: GameEntity<any>): void;
864
+ /**
865
+ * Register an entity for instanced rendering if opted in with `batched: true`.
866
+ */
867
+ private tryRegisterInstance;
868
+ private maybeAttachEntityPhysics;
869
+ /** Add the entity to internal maps and notify listeners. */
870
+ addEntityToStage(entity: BaseNode): void;
871
+ /**
872
+ * Remove an entity and its resources by its UUID.
873
+ * @returns true if removed, false if not found or stage not ready
874
+ */
875
+ removeEntityByUuid(uuid: string): boolean;
876
+ /** Get an entity by its name; returns null if not found. */
877
+ getEntityByName(name: string): BaseNode | null;
878
+ /** Build a serializable state snapshot for an entity. */
879
+ buildEntityState(child: BaseNode): Partial<BaseEntityInterface>;
880
+ /**
881
+ * Subscribe to entity-added events.
882
+ * @param callback Invoked for each entity when added
883
+ * @param options.replayExisting If true and stage already loaded, replays existing entities
884
+ * @returns Unsubscribe function
885
+ */
886
+ onEntityAdded(callback: (entity: BaseNode) => void, options?: {
887
+ replayExisting?: boolean;
888
+ }): () => void;
889
+ /**
890
+ * Enqueue items to be spawned. Items can be:
891
+ * - BaseNode instances (immediate or deferred until load)
892
+ * - Factory functions returning BaseNode or Promise<BaseNode>
893
+ * - Promises resolving to BaseNode
894
+ */
895
+ enqueue(...items: StageEntityInput[]): void;
896
+ private handleEntityImmediatelyOrQueue;
897
+ private handlePromiseWithSpawnOnResolve;
898
+ /**
899
+ * Generator that yields between entity loads for real-time progress updates.
900
+ */
901
+ private entityLoadGenerator;
902
+ /** Yields to the event loop via MessageChannel (~0.1ms vs ~4ms for setTimeout). */
903
+ private yieldToEventLoop;
904
+ /**
905
+ * Runs the entity load generator, yielding to the event loop in batches.
906
+ * Emits progress events through the loading delegate.
907
+ */
908
+ runEntityLoadGenerator(): Promise<void>;
909
+ /**
910
+ * Register an ECS behavior system to run each frame.
911
+ * @param systemOrFactory A BehaviorSystem instance or factory function
912
+ */
913
+ registerSystem(systemOrFactory: BehaviorSystem | BehaviorSystemFactory): void;
914
+ /**
915
+ * Destroy all entities and clear internal state.
916
+ * Called by ZylemStage._destroy().
917
+ */
918
+ destroyAll(): void;
919
+ private registerBehaviorLinks;
920
+ private unregisterBehaviorLinks;
921
+ }
922
+
923
+ interface ZylemStageConfig {
924
+ inputs: Record<string, string[]>;
925
+ backgroundColor: Color | string;
926
+ backgroundImage: string | null;
927
+ backgroundShader: any | null;
928
+ gravity: Vector3 | Vec3Components;
929
+ variables: Record<string, any>;
930
+ /** Physics update rate in Hz (default 60). */
931
+ physicsRate: number;
932
+ /** Optional runtime loader configuration for stage-managed assets. */
933
+ assetLoaders?: StageAssetLoaderConfig;
934
+ /** Optional runtime adapter for wasm-driven simulation/rendering. */
935
+ runtimeAdapter?: StageRuntimeAdapter;
936
+ /** Optional debug binding for wasm runtime adapters (heat tint, etc.). */
937
+ runtimeDebugBinding?: RuntimeDebugBinding;
938
+ /**
939
+ * Optional unified-Stage wasm runtime configuration. When set, the stage
940
+ * instantiates a {@link WasmStageRuntime} during `load()` and exposes it
941
+ * to behavior systems via `BehaviorSystemContext.wasmStage`.
942
+ */
943
+ wasmRuntime?: StageWasmRuntimeConfig;
944
+ /**
945
+ * When `false`, suppress the engine's built-in ambient + directional
946
+ * lights so the stage owns its lighting rig entirely (usually via
947
+ * `createLight(...)` entities). Defaults to `true`.
948
+ */
949
+ defaultLighting: boolean;
950
+ stageRef?: Stage;
951
+ }
952
+ type StageOptionItem = Partial<ZylemStageConfig> | CameraWrapper | StageEntityInput;
953
+ type StageOptions = [] | [Partial<ZylemStageConfig>, ...StageOptionItem[]];
954
+ type StageState = ZylemStageConfig & {
955
+ entities: GameEntityInterface[];
956
+ };
957
+ /**
958
+ * ZylemStage orchestrates scene, physics world, entities, and lifecycle.
959
+ *
960
+ * Responsibilities:
961
+ * - Manage stage configuration (background, inputs, gravity, variables)
962
+ * - Initialize and own `ZylemScene` and `ZylemWorld`
963
+ * - Coordinate delegates for entities, camera, loading, debug, and models
964
+ * - Drive per-frame updates and transform system
965
+ */
966
+ declare class ZylemStage extends LifeCycleBase<ZylemStage> {
967
+ type: string;
968
+ state: StageState;
969
+ gravity: Vector3 | Vec3Components;
970
+ world: ZylemWorld | null;
971
+ scene: ZylemScene | null;
972
+ instanceManager: InstanceManager | null;
973
+ /** Unified-Stage wasm runtime; non-null only when `wasmRuntime` was configured. */
974
+ wasmStage: WasmStageRuntime | null;
975
+ debugDelegate: StageDebugDelegate | null;
976
+ uuid: string;
977
+ wrapperRef: Stage | null;
978
+ camera?: CameraWrapper;
979
+ cameras: CameraWrapper[];
980
+ cameraRef?: ZylemCamera | null;
981
+ /** Camera manager for multi-camera support */
982
+ cameraManagerRef: CameraManager | null;
983
+ /** Shared renderer manager (injected by the game) */
984
+ rendererManager: RendererManager | null;
985
+ runtimeAdapter: StageRuntimeAdapter | null;
986
+ private cameraDelegate;
987
+ private loadingDelegate;
988
+ private entityModelDelegate;
989
+ private readonly childUpdateParams;
990
+ /** Entity management delegate — public for external consumers (debug, transform system). */
991
+ readonly entityDelegate: StageEntityDelegate;
992
+ /**
993
+ * Create a new stage.
994
+ * @param options Stage options: partial config, camera, and initial entities or factories
995
+ */
996
+ constructor(options?: StageOptions);
997
+ private setState;
998
+ /**
999
+ * Resolve the active renderer, preferring the shared renderer manager and
1000
+ * falling back to the camera's own renderer.
1001
+ */
1002
+ private resolveRenderer;
1003
+ /**
1004
+ * Load and initialize the stage's scene and world.
1005
+ * Uses generator pattern to yield control to event loop for real-time progress.
1006
+ * @param id DOM element id for the renderer container
1007
+ * @param camera Optional camera override
1008
+ */
1009
+ load(id: string, camera?: ZylemCamera | null, rendererManager?: RendererManager | null): Promise<void>;
1010
+ /**
1011
+ * Idempotency guard for `_setup`. The initial stage is currently set up
1012
+ * twice — once when `ZylemGame.loadStage` runs for non-initial stages
1013
+ * (so every stage gets a `StageDebugDelegate`, stage.onSetup callbacks,
1014
+ * etc.), and once from `ZylemGame.start()` for the very first stage.
1015
+ * Keeping a flag here lets both call sites invoke `stage.start(...)`
1016
+ * safely; the second call is a no-op.
1017
+ */
1018
+ hasSetup: boolean;
1019
+ protected _setup(params: SetupContext<ZylemStage>): void;
1020
+ protected _update(params: UpdateContext<ZylemStage>): void;
1021
+ outOfLoop(): void;
1022
+ /** Update debug overlays and helpers if enabled. */
1023
+ debugUpdate(): void;
1024
+ /** Cleanup owned resources when the stage is destroyed. */
1025
+ protected _destroy(params: DestroyContext<ZylemStage>): void;
1026
+ /** Forward to entity delegate. */
1027
+ spawnEntity(child: BaseNode): Promise<void>;
1028
+ /** Forward to entity delegate. */
1029
+ buildEntityState(child: BaseNode): Partial<BaseEntityInterface>;
1030
+ /** Forward to entity delegate. */
1031
+ onEntityAdded(callback: (entity: BaseNode) => void, options?: {
1032
+ replayExisting?: boolean;
1033
+ }): () => void;
1034
+ onLoading(callback: (event: LoadingEvent) => void): () => void;
1035
+ /**
1036
+ * Register an ECS behavior system to run each frame.
1037
+ * @param systemOrFactory A BehaviorSystem instance or factory function
1038
+ * @returns this for chaining
1039
+ */
1040
+ registerSystem(systemOrFactory: BehaviorSystem | BehaviorSystemFactory): this;
1041
+ /** Forward to entity delegate. */
1042
+ removeEntityByUuid(uuid: string): boolean;
1043
+ /** Forward to entity delegate. */
1044
+ getEntityByName(name: string): BaseNode<any, any> | null;
1045
+ /** Forward to entity delegate. */
1046
+ enqueue(...items: StageEntityInput[]): void;
1047
+ logMissingEntities(): void;
1048
+ private runtimeContext;
1049
+ /**
1050
+ * Resolve a {@link StageWasmRuntimeConfig} into a live {@link WasmStageRuntime}.
1051
+ * Accepts wasm bytes (`ArrayBuffer`), a fetch URL, or a deferred async
1052
+ * builder so demos can `?url`-import a Vite asset without forcing the engine
1053
+ * to bundle the wasm itself.
1054
+ */
1055
+ private loadWasmStage;
1056
+ /** Add a camera to this stage's camera manager. */
1057
+ addCamera(camera: ZylemCamera, name?: string): string | null;
1058
+ /** Remove a camera from this stage's camera manager. */
1059
+ removeCamera(nameOrRef: string | ZylemCamera): boolean;
1060
+ /** Set the active camera by name or reference. */
1061
+ setActiveCamera(nameOrRef: string | ZylemCamera): boolean;
1062
+ /** Get a camera by name from the camera manager. */
1063
+ getCamera(name: string): ZylemCamera | null;
1064
+ /** Resize renderer viewport. */
1065
+ resize(width: number, height: number): void;
1066
+ }
1067
+
1068
+ type NodeLike = {
1069
+ create: Function;
1070
+ };
1071
+ type AnyNode = NodeLike | Promise<NodeLike>;
1072
+ type EntityInput = AnyNode | (() => AnyNode) | (() => Promise<any>);
1073
+ declare class Stage {
1074
+ wrappedStage: ZylemStage | null;
1075
+ options: StageOptionItem[];
1076
+ private _pendingEntities;
1077
+ private setupCallbacks;
1078
+ private updateCallbacks;
1079
+ private destroyCallbacks;
1080
+ private pendingLoadingCallbacks;
1081
+ private eventDelegate;
1082
+ /** Per-stage input configuration overrides. Merged with game-level defaults on stage load. */
1083
+ inputConfig: GameInputConfig | null;
1084
+ /**
1085
+ * Callback set by the game to trigger input reconfiguration
1086
+ * when this stage's input config changes at runtime.
1087
+ * @internal
1088
+ */
1089
+ onInputConfigChanged: (() => void) | null;
1090
+ constructor(options: StageOptions);
1091
+ /**
1092
+ * Set composable input configuration for this stage.
1093
+ * Multiple configs are deep-merged (later configs win on key conflicts).
1094
+ * If this stage is currently active, the change takes effect immediately.
1095
+ * @example stage.setInputConfiguration(useArrowsForAxes('p1'), useWASDForDirections('p2'));
1096
+ */
1097
+ setInputConfiguration(...configs: GameInputConfig[]): this;
1098
+ load(id: string, camera?: ZylemCamera | CameraWrapper | null, rendererManager?: RendererManager | null): Promise<void>;
1099
+ private applyLifecycleCallbacks;
1100
+ addEntities(entities: BaseNode[]): Promise<void>;
1101
+ add(...inputs: Array<EntityInput>): void;
1102
+ private addToBlueprints;
1103
+ private addToStage;
1104
+ start(params: SetupContext<ZylemStage>): void;
1105
+ onUpdate(...callbacks: UpdateFunction<ZylemStage>[]): this;
1106
+ onSetup(...callbacks: SetupFunction<ZylemStage>[]): this;
1107
+ onDestroy(...callbacks: DestroyFunction<ZylemStage>[]): this;
1108
+ onLoading(callback: (event: LoadingEvent) => void): () => void;
1109
+ /**
1110
+ * Find an entity by name on the current stage.
1111
+ * @param name The name of the entity to find
1112
+ * @param type Optional type symbol for type inference (e.g., TEXT_TYPE, SPRITE_TYPE)
1113
+ * @returns The entity if found, or undefined
1114
+ * @example stage.getEntityByName('scoreText', TEXT_TYPE)
1115
+ */
1116
+ getEntityByName<T extends symbol | void = void>(name: string, type?: T): T extends keyof EntityTypeMap ? EntityTypeMap[T] | undefined : BaseNode | undefined;
1117
+ /**
1118
+ * Add a camera to this stage.
1119
+ * @param camera The ZylemCamera or CameraWrapper to add
1120
+ * @param name Optional name for lookup
1121
+ */
1122
+ addCamera(camera: ZylemCamera | CameraWrapper, name?: string): string | null;
1123
+ /**
1124
+ * Remove a camera from this stage by name or reference.
1125
+ */
1126
+ removeCamera(nameOrRef: string | ZylemCamera | CameraWrapper): boolean;
1127
+ /**
1128
+ * Set the active camera by name or reference.
1129
+ */
1130
+ setActiveCamera(nameOrRef: string | ZylemCamera | CameraWrapper): boolean;
1131
+ /**
1132
+ * Get a camera by name from the camera manager.
1133
+ */
1134
+ getCamera(name: string): ZylemCamera | null;
1135
+ /**
1136
+ * Dispatch an event from the stage.
1137
+ * Events are emitted both locally and to the global event bus.
1138
+ */
1139
+ dispatch<K extends keyof StageEvents>(event: K, payload: StageEvents[K]): void;
1140
+ /**
1141
+ * Listen for events on this stage instance.
1142
+ * @returns Unsubscribe function
1143
+ */
1144
+ listen<K extends keyof StageEvents>(event: K, handler: (payload: StageEvents[K]) => void): () => void;
1145
+ /**
1146
+ * Clean up stage resources including event subscriptions.
1147
+ */
1148
+ dispose(): void;
1149
+ }
1150
+ /**
1151
+ * Create a stage with optional camera
1152
+ */
1153
+ declare function createStage(...options: StageOptions): Stage;
1154
+
1155
+ /**
1156
+ * Stage state interface - minimal to prevent circular dependencies
1157
+ */
1158
+ interface StageStateInterface {
1159
+ backgroundColor: Color;
1160
+ backgroundImage: string | null;
1161
+ inputs: {
1162
+ p1: string[];
1163
+ p2: string[];
1164
+ };
1165
+ variables: Record<string, any>;
1166
+ gravity: Vector3 | Vec3Components;
1167
+ entities: Partial<BaseEntityInterface>[];
1168
+ stageRef?: any;
1169
+ }
1170
+ /**
1171
+ * Minimal stage interface to break circular dependencies
1172
+ */
1173
+ interface StageInterface {
1174
+ uuid: string;
1175
+ children: any[];
1176
+ state: StageStateInterface;
1177
+ }
1178
+
1179
+ declare const AspectRatio: {
1180
+ readonly FourByThree: number;
1181
+ readonly SixteenByNine: number;
1182
+ readonly NineBySixteen: number;
1183
+ readonly TwentyOneByNine: number;
1184
+ readonly OneByOne: number;
1185
+ };
1186
+ type AspectRatioValue = (typeof AspectRatio)[keyof typeof AspectRatio] | number;
1187
+ /**
1188
+ * AspectRatioDelegate manages sizing a canvas to fit within a container
1189
+ * while preserving a target aspect ratio. It notifies a consumer via
1190
+ * onResize when the final width/height are applied so renderers/cameras
1191
+ * can update their viewports.
1192
+ */
1193
+ declare class AspectRatioDelegate {
1194
+ container: HTMLElement;
1195
+ canvas: HTMLCanvasElement;
1196
+ aspectRatio: number;
1197
+ onResize?: (width: number, height: number) => void;
1198
+ private handleResizeBound;
1199
+ private resizeObserver;
1200
+ constructor(params: {
1201
+ container: HTMLElement;
1202
+ canvas: HTMLCanvasElement;
1203
+ aspectRatio: AspectRatioValue;
1204
+ onResize?: (width: number, height: number) => void;
1205
+ });
1206
+ /** Attach window resize listener and apply once. */
1207
+ attach(): void;
1208
+ /** Detach window resize listener. */
1209
+ detach(): void;
1210
+ /** Compute the largest size that fits container while preserving aspect. */
1211
+ measure(): {
1212
+ width: number;
1213
+ height: number;
1214
+ };
1215
+ /** Apply measured size to canvas and notify. */
1216
+ apply(): void;
1217
+ }
1218
+
1219
+ interface ViewportSize {
1220
+ width: number;
1221
+ height: number;
1222
+ }
1223
+
1224
+ type RetroResolution = {
1225
+ key: string;
1226
+ width: number;
1227
+ height: number;
1228
+ notes?: string;
1229
+ };
1230
+ type RetroPreset = {
1231
+ displayAspect: number;
1232
+ resolutions: RetroResolution[];
1233
+ };
1234
+ /**
1235
+ * Retro, console, and device display presets.
1236
+ * displayAspect represents the intended display aspect (letterboxing target),
1237
+ * not necessarily the raw pixel aspect of internal buffers.
1238
+ */
1239
+ declare const RetroPresets: Record<string, RetroPreset>;
1240
+ type RetroPresetKey = keyof typeof RetroPresets;
1241
+ declare function getDisplayAspect(preset: RetroPresetKey): number;
1242
+ declare function getPresetResolution(preset: RetroPresetKey, key?: string): RetroResolution | undefined;
1243
+ declare function parseResolution(text: string): {
1244
+ width: number;
1245
+ height: number;
1246
+ } | null;
1247
+
1248
+ /**
1249
+ * Resolution descriptor for the game's internal render buffer.
1250
+ * - `string` : a "WxH" literal or a known retro preset (e.g. `'NES'`).
1251
+ * - `{ width, height }` : explicit pixel dimensions.
1252
+ * - `'native'` : skip internal-resolution scaling — render at the
1253
+ * canvas' CSS size × DPR (i.e. 1:1 with the device viewport).
1254
+ */
1255
+ type ResolutionInput = string | {
1256
+ width: number;
1257
+ height: number;
1258
+ } | 'native';
1259
+ type DeviceProfile = 'auto' | 'desktop' | 'mobile';
1260
+ interface ResolveGameConfigRuntime {
1261
+ deviceProfile?: DeviceProfile;
1262
+ viewportSize?: ViewportSize;
1263
+ }
1264
+ type GameDeviceConfig = Partial<{
1265
+ /** numeric value or key in AspectRatio */
1266
+ aspectRatio: AspectRatioValue | keyof typeof AspectRatio;
1267
+ /** console/display preset to derive aspect ratio */
1268
+ preset: RetroPresetKey;
1269
+ /** lock internal render buffer for this device profile */
1270
+ resolution: ResolutionInput;
1271
+ /**
1272
+ * Auto-merge built-in virtual touch controls into the resolved input
1273
+ * config. The provider auto-enables on mobile devices via
1274
+ * `enabled: 'auto'`, so on desktop runtimes the UI stays dormant.
1275
+ * - `true` : default joystick + A/B layout, default theme.
1276
+ * - options object : forwarded to `defaultTouchControls('p1', ...)`.
1277
+ * - `false` / unset: no auto-injection (caller wires controls manually).
1278
+ */
1279
+ controls: boolean | DefaultTouchControlsOptions;
1280
+ }>;
1281
+ type GameConfigLike = Partial<{
1282
+ id: string;
1283
+ globals: Record<string, any>;
1284
+ stages: StageInterface[];
1285
+ debug: boolean;
1286
+ time: number;
1287
+ input: GameInputConfig;
1288
+ /** numeric value or key in AspectRatio */
1289
+ aspectRatio: AspectRatioValue | keyof typeof AspectRatio;
1290
+ /** console/display preset to derive aspect ratio */
1291
+ preset: RetroPresetKey;
1292
+ /** lock internal render buffer to this desktop/default resolution */
1293
+ resolution: ResolutionInput;
1294
+ /** mobile-specific aspect/preset/resolution overrides */
1295
+ mobile: GameDeviceConfig;
1296
+ fullscreen: boolean;
1297
+ /** CSS background value for document body */
1298
+ bodyBackground: string;
1299
+ /** existing container by reference */
1300
+ container: HTMLElement;
1301
+ /** create/find container by id */
1302
+ containerId: string;
1303
+ /** optional canvas if caller wants to manage it */
1304
+ canvas: HTMLCanvasElement;
1305
+ }>;
1306
+ declare class GameConfig {
1307
+ id: string;
1308
+ globals: Record<string, any>;
1309
+ stages: StageInterface[];
1310
+ debug: boolean;
1311
+ time: number;
1312
+ input: GameInputConfig | undefined;
1313
+ aspectRatio: number;
1314
+ internalResolution: {
1315
+ width: number;
1316
+ height: number;
1317
+ } | undefined;
1318
+ fullscreen: boolean;
1319
+ bodyBackground: string | undefined;
1320
+ container: HTMLElement;
1321
+ containerId?: string | undefined;
1322
+ canvas?: HTMLCanvasElement | undefined;
1323
+ constructor(id: string, globals: Record<string, any>, stages: StageInterface[], debug: boolean, time: number, input: GameInputConfig | undefined, aspectRatio: number, internalResolution: {
1324
+ width: number;
1325
+ height: number;
1326
+ } | undefined, fullscreen: boolean, bodyBackground: string | undefined, container: HTMLElement, containerId?: string | undefined, canvas?: HTMLCanvasElement | undefined);
1327
+ }
1328
+ /**
1329
+ * Factory for authoring configuration objects in user code.
1330
+ * Returns a plain object that can be passed to `game(...)`.
1331
+ */
1332
+ declare function gameConfig(config: GameConfigLike): GameConfigLike;
1333
+
1334
+ interface GameCanvasOptions {
1335
+ id: string;
1336
+ container?: HTMLElement;
1337
+ containerId?: string;
1338
+ canvas?: HTMLCanvasElement;
1339
+ bodyBackground?: string;
1340
+ fullscreen?: boolean;
1341
+ aspectRatio: AspectRatioValue | number;
1342
+ }
1343
+ /**
1344
+ * GameCanvas is a DOM delegate that owns:
1345
+ * - container lookup/creation and styling (including fullscreen centering)
1346
+ * - body background application
1347
+ * - canvas mounting into container
1348
+ * - aspect ratio sizing via AspectRatioDelegate
1349
+ */
1350
+ declare class GameCanvas {
1351
+ id: string;
1352
+ container: HTMLElement;
1353
+ canvas: HTMLCanvasElement;
1354
+ bodyBackground?: string;
1355
+ fullscreen: boolean;
1356
+ aspectRatio: number;
1357
+ private ratioDelegate;
1358
+ private overlayContainer;
1359
+ constructor(options: GameCanvasOptions);
1360
+ applyBodyBackground(): void;
1361
+ mountCanvas(): void;
1362
+ mountRenderer(rendererDom: HTMLCanvasElement, onResize: (width: number, height: number) => void): void;
1363
+ getOverlayContainer(): HTMLElement;
1364
+ centerIfFullscreen(): void;
1365
+ attachAspectRatio(onResize: (width: number, height: number) => void): void;
1366
+ setAspectRatio(aspectRatio: number): void;
1367
+ reapplyLayout(): void;
1368
+ destroy(): void;
1369
+ private mountChildren;
1370
+ private ensureOverlayContainer;
1371
+ private ensureContainer;
1372
+ }
1373
+
1374
+ /**
1375
+ * Game-level loading event that includes stage context.
1376
+ */
1377
+ interface GameLoadingEvent {
1378
+ type: 'start' | 'progress' | 'complete';
1379
+ stageName?: string;
1380
+ stageIndex?: number;
1381
+ message: string;
1382
+ progress: number;
1383
+ current?: number;
1384
+ total?: number;
1385
+ }
1386
+
1387
+ type ZylemGameOptions<TGlobals extends BaseGlobals> = ZylemGameConfig<Stage, ZylemGame<TGlobals>, TGlobals> & Partial<GameConfig>;
1388
+ declare class ZylemGame<TGlobals extends BaseGlobals> {
1389
+ id: string;
1390
+ initialGlobals: TGlobals;
1391
+ customSetup: ((params: SetupContext<ZylemGame<TGlobals>, TGlobals>) => void) | null;
1392
+ customUpdate: ((params: UpdateContext<ZylemGame<TGlobals>, TGlobals>) => void) | null;
1393
+ customDestroy: ((params: DestroyContext<ZylemGame<TGlobals>, TGlobals>) => void) | null;
1394
+ stages: Stage[];
1395
+ stageMap: Map<string, Stage>;
1396
+ currentStageId: string;
1397
+ previousTimeStamp: number;
1398
+ totalTime: number;
1399
+ timer: Timer;
1400
+ inputManager: InputManager;
1401
+ wrapperRef: Game<TGlobals>;
1402
+ globalInputConfig: GameInputConfig | undefined;
1403
+ defaultCamera: ZylemCamera | null;
1404
+ /** Shared renderer manager for all stages */
1405
+ rendererManager: RendererManager | null;
1406
+ container: HTMLElement | null;
1407
+ canvas: HTMLCanvasElement | null;
1408
+ aspectRatioDelegate: AspectRatioDelegate | null;
1409
+ resolvedConfig: GameConfig | null;
1410
+ gameCanvas: GameCanvas | null;
1411
+ private animationFrameId;
1412
+ private isDisposed;
1413
+ /**
1414
+ * True once `start()` has been invoked for this game's initial stage.
1415
+ * Used by `loadStage` to decide whether to drive the stage's `_setup`
1416
+ * lifecycle directly (for subsequent stages loaded via `nextStage`
1417
+ * / `loadStage`) or defer to `start()` (for the very first stage).
1418
+ */
1419
+ private hasStarted;
1420
+ private debugDelegate;
1421
+ private loadingDelegate;
1422
+ private rendererObserver;
1423
+ private eventBusUnsubscribes;
1424
+ private readonly gameUpdateParams;
1425
+ private readonly stageSetupParams;
1426
+ private readonly stageUpdateParams;
1427
+ private readonly frameCallback;
1428
+ private readonly sourceOptions;
1429
+ private displayRuntime;
1430
+ static FRAME_LIMIT: number;
1431
+ static FRAME_DURATION: number;
1432
+ static MAX_DELTA_SECONDS: number;
1433
+ constructor(options: ZylemGameOptions<TGlobals>, wrapperRef: Game<TGlobals>, displayRuntime?: ResolveGameConfigRuntime);
1434
+ setDisplayRuntime(runtime: ResolveGameConfigRuntime): void;
1435
+ loadGameCanvas(config: GameConfig): void;
1436
+ loadDebugOptions(options: ZylemGameOptions<TGlobals>): void;
1437
+ loadStage(stage: Stage, stageIndex?: number): Promise<void>;
1438
+ /**
1439
+ * Merges game-level global input config with the stage's per-stage overrides
1440
+ * and reconfigures the InputManager.
1441
+ */
1442
+ applyInputConfig(stage: Stage): void;
1443
+ /**
1444
+ * Update the game-level global input config and re-apply to the current stage.
1445
+ */
1446
+ setGlobalInputConfig(config: GameInputConfig): void;
1447
+ unloadCurrentStage(): void;
1448
+ setGlobals(options: ZylemGameConfig<Stage, ZylemGame<TGlobals>, TGlobals>): void;
1449
+ params(): UpdateContext<ZylemGame<TGlobals>, TGlobals>;
1450
+ start(): void;
1451
+ /**
1452
+ * Execute a single frame update.
1453
+ * This method can be called directly for testing or from the game loop.
1454
+ * @param deltaTime Optional delta time in seconds. If not provided, uses timer delta.
1455
+ */
1456
+ step(deltaTime?: number): void;
1457
+ loop(timestamp: number): void;
1458
+ dispose(): void;
1459
+ outOfLoop(): void;
1460
+ getStage(id: string): Stage | undefined;
1461
+ currentStage(): Stage | undefined;
1462
+ /**
1463
+ * Subscribe to loading events from the game.
1464
+ * Events include stage context (stageName, stageIndex).
1465
+ * @param callback Invoked for each loading event
1466
+ * @returns Unsubscribe function
1467
+ */
1468
+ onLoading(callback: (event: GameLoadingEvent) => void): () => void;
1469
+ /**
1470
+ * Build the stage config payload for the current stage.
1471
+ */
1472
+ private buildStageConfigPayload;
1473
+ /**
1474
+ * Build the entities payload for the current stage.
1475
+ */
1476
+ private buildEntitiesPayload;
1477
+ /**
1478
+ * Emit a state:dispatch event to the zylemEventBus.
1479
+ * Called after stage load and on global state changes.
1480
+ */
1481
+ private emitStateDispatch;
1482
+ /**
1483
+ * Subscribe to the game event bus for stage loading and state events.
1484
+ * Emits events to zylemEventBus for cross-package communication.
1485
+ */
1486
+ private subscribeToEventBus;
1487
+ }
1488
+
1489
+ type GameOptions<TGlobals extends BaseGlobals> = Array<ZylemGameConfig<Stage, any, TGlobals> | GameConfigLike | Stage | GameEntityLifeCycle | BaseNode>;
1490
+
1491
+ declare class Game<TGlobals extends BaseGlobals> implements IGame<TGlobals> {
1492
+ private wrappedGame;
1493
+ options: GameOptions<TGlobals>;
1494
+ private setupCallbacks;
1495
+ private updateCallbacks;
1496
+ private destroyCallbacks;
1497
+ private pendingLoadingCallbacks;
1498
+ private globalChangeCallbacks;
1499
+ private globalChangesCallbacks;
1500
+ private activeGlobalSubscriptions;
1501
+ private eventDelegate;
1502
+ /** Pending global input config set before the game starts. */
1503
+ private pendingInputConfig;
1504
+ private displayRuntime;
1505
+ refErrorMessage: string;
1506
+ constructor(options: GameOptions<TGlobals>);
1507
+ onSetup(...callbacks: Array<SetupFunction<ZylemGame<TGlobals>, TGlobals>>): this;
1508
+ onUpdate(...callbacks: Array<UpdateFunction<ZylemGame<TGlobals>, TGlobals>>): this;
1509
+ onDestroy(...callbacks: Array<DestroyFunction<ZylemGame<TGlobals>, TGlobals>>): this;
1510
+ /**
1511
+ * Set composable input configuration as global defaults for the entire game.
1512
+ * Multiple configs are deep-merged (later configs win on key conflicts).
1513
+ * Per-stage overrides (via stage.setInputConfiguration) are merged on top.
1514
+ * Can be called before or after start().
1515
+ * @example game.setInputConfiguration(useArrowsForAxes('p1'), useWASDForDirections('p2'));
1516
+ */
1517
+ setInputConfiguration(...configs: GameInputConfig[]): this;
1518
+ start(): Promise<this>;
1519
+ setDisplayRuntime(runtime: Partial<ResolveGameConfigRuntime>): this;
1520
+ setDeviceProfile(profile: DeviceProfile): this;
1521
+ setViewportSize(width: number, height: number): this;
1522
+ private load;
1523
+ private setOverrides;
1524
+ /**
1525
+ * Subscribe to changes on a global value. Subscriptions are registered
1526
+ * when the game starts and cleaned up when disposed.
1527
+ * The callback receives the value and the current stage.
1528
+ * @example game.onGlobalChange('score', (val, stage) => console.log(val));
1529
+ */
1530
+ onGlobalChange<T = unknown>(path: string, callback: (value: T, stage: Stage | null) => void): this;
1531
+ /**
1532
+ * Subscribe to changes on multiple global paths. Subscriptions are registered
1533
+ * when the game starts and cleaned up when disposed.
1534
+ * The callback receives the values and the current stage.
1535
+ * @example game.onGlobalChanges(['score', 'lives'], ([score, lives], stage) => console.log(score, lives));
1536
+ */
1537
+ onGlobalChanges<T extends unknown[] = unknown[]>(paths: string[], callback: (values: T, stage: Stage | null) => void): this;
1538
+ /**
1539
+ * Register all stored global change callbacks.
1540
+ * Called internally during start().
1541
+ */
1542
+ private registerGlobalSubscriptions;
1543
+ /**
1544
+ * Get the current stage wrapper.
1545
+ */
1546
+ getCurrentStage(): Stage | null;
1547
+ pause(): Promise<void>;
1548
+ resume(): Promise<void>;
1549
+ /**
1550
+ * Execute a single frame update.
1551
+ * Useful for testing or manual frame stepping.
1552
+ * @param deltaTime Optional delta time in seconds (defaults to 1/60)
1553
+ */
1554
+ step(deltaTime?: number): void;
1555
+ reset(): Promise<void>;
1556
+ previousStage(): void;
1557
+ loadStageFromId(stageId: string): Promise<void>;
1558
+ nextStage(): void;
1559
+ goToStage(): Promise<void>;
1560
+ end(): Promise<void>;
1561
+ dispose(): void;
1562
+ /**
1563
+ * Dispatch an event from the game.
1564
+ * Events are emitted both locally and to the global event bus.
1565
+ */
1566
+ dispatch<K extends keyof GameEvents>(event: K, payload: GameEvents[K]): void;
1567
+ /**
1568
+ * Listen for events on this game instance.
1569
+ * @returns Unsubscribe function
1570
+ */
1571
+ listen<K extends keyof GameEvents>(event: K, handler: (payload: GameEvents[K]) => void): () => void;
1572
+ /**
1573
+ * Subscribe to loading events from the game.
1574
+ * Events include stage context (stageName, stageIndex).
1575
+ * @param callback Invoked for each loading event
1576
+ * @returns Unsubscribe function
1577
+ */
1578
+ onLoading(callback: (event: GameLoadingEvent) => void): () => void;
1579
+ }
1580
+ /**
1581
+ * create a new game
1582
+ * @param options GameOptions - Array of IGameOptions, Stage, GameEntity, or BaseNode objects
1583
+ * @param options.id Game name string (when using IGameOptions)
1584
+ * @param options.globals Game globals object (when using IGameOptions)
1585
+ * @param options.stages Array of stage objects (when using IGameOptions)
1586
+ * @returns Game
1587
+ */
1588
+ declare function createGame<TGlobals extends BaseGlobals>(...options: GameOptions<TGlobals>): Game<TGlobals>;
1589
+
1590
+ export { AspectRatio as A, CameraWrapper as C, type DeviceProfile as D, Fixed2DPerspective as F, Game as G, type PerspectiveOptions as P, type ResolutionInput as R, Stage as S, ThirdPersonPerspective as T, type StageStateInterface as a, type GameLoadingEvent as b, createGame as c, type GameConfigLike as d, type GameDeviceConfig as e, type ResolveGameConfigRuntime as f, gameConfig as g, createStage as h, type StageConfigLike as i, type StageOptions as j, createCamera as k, type CameraOptions as l, FirstPersonPerspective as m, createPerspective as n, type ThirdPersonOptions as o, type Fixed2DOptions as p, type FirstPersonOptions as q, type AspectRatioValue as r, stageConfig as s, getDisplayAspect as t, getPresetResolution as u, parseResolution as v, type RetroPreset as w, type RetroPresetKey as x, type RetroResolution as y };