@zylem/game-lib 0.7.0 → 0.8.2

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 (98) hide show
  1. package/README.md +15 -1
  2. package/dist/actions.d.ts +71 -8
  3. package/dist/actions.js +1 -1
  4. package/dist/api/game-lib.api.json +55350 -0
  5. package/dist/api/game-lib.api.md +4608 -0
  6. package/dist/api/game-lib.d.ts +8447 -0
  7. package/dist/api/game-lib.typedoc.json +352456 -0
  8. package/dist/audio.js +1 -1
  9. package/dist/{base-node-life-cycle-CnJ-7zX-.d.ts → base-node-life-cycle-BK9xebT9.d.ts} +18 -4
  10. package/dist/behavior.d.ts +2 -3
  11. package/dist/behavior.js +1 -1
  12. package/dist/blueprints-TbGY-h53.d.ts +162 -0
  13. package/dist/chunk-3PRBSSTS.js +24 -0
  14. package/dist/chunk-47DG7I7M.js +1 -0
  15. package/dist/chunk-7GYFZKK7.js +1 -0
  16. package/dist/chunk-7QF6YTEZ.js +1 -0
  17. package/dist/chunk-7WRQ2UAN.js +1 -0
  18. package/dist/chunk-BH53MBAZ.js +1 -0
  19. package/dist/chunk-BIGH6D34.js +0 -0
  20. package/dist/chunk-CD7ZOZ35.js +1 -0
  21. package/dist/chunk-CFVRRRZZ.js +1 -0
  22. package/dist/chunk-CM5YRNBJ.js +19 -0
  23. package/dist/chunk-COM6HJ2L.js +1 -0
  24. package/dist/chunk-D2PATZCC.js +1 -0
  25. package/dist/chunk-DFLI7ICU.js +0 -0
  26. package/dist/chunk-EVYHPR3J.js +1 -0
  27. package/dist/chunk-IPWUDOV5.js +1 -0
  28. package/dist/chunk-JNFFTNMH.js +1 -0
  29. package/dist/chunk-JQKS42G4.js +1 -0
  30. package/dist/chunk-KVSJE4XD.js +1 -0
  31. package/dist/chunk-MZZCDXFB.js +1 -0
  32. package/dist/chunk-ORIDWL3T.js +0 -0
  33. package/dist/{chunk-RXDTAWI2.js → chunk-PCFF4LLO.js} +1 -1
  34. package/dist/chunk-QB3NL7VQ.js +1 -0
  35. package/dist/chunk-TAUWDQZF.js +9 -0
  36. package/dist/chunk-UG22Z42P.js +1 -0
  37. package/dist/chunk-VS2D4B3W.js +1 -0
  38. package/dist/chunk-WQ3WMMZD.js +1 -0
  39. package/dist/chunk-XK63E4SX.js +1 -0
  40. package/dist/chunk-YAOXFYOD.js +1 -0
  41. package/dist/chunk-ZRT3ZQVH.js +1 -0
  42. package/dist/collision-builder-B_tm8OVy.d.ts +49 -0
  43. package/dist/core.d.ts +45 -30
  44. package/dist/core.js +1 -24
  45. package/dist/debug-state-DRoeasG2.d.ts +17 -0
  46. package/dist/debug.d.ts +71 -19
  47. package/dist/debug.js +1 -1
  48. package/dist/{default-controls-BGc61yYl.d.ts → default-controls-CAKJ5zlo.d.ts} +3 -3
  49. package/dist/entity-B9yZeBm4.d.ts +34 -0
  50. package/dist/{entity-DNkYKfdp.d.ts → entity-BGEq1yfC.d.ts} +91 -444
  51. package/dist/{entity-type-map-C94h2TDW.d.ts → entity-type-map-CW6RHQkx.d.ts} +153 -6
  52. package/dist/entity.d.ts +15 -10
  53. package/dist/entity.js +1 -1
  54. package/dist/events.d.ts +10 -1
  55. package/dist/events.js +1 -1
  56. package/dist/{game-Cuj5gy7U.d.ts → game-DbqBQiFC.d.ts} +460 -135
  57. package/dist/game-default-6AZZCNST.js +1 -0
  58. package/dist/{game-interfaces-tfpM5NBk.d.ts → game-interfaces-vF5sRi1n.d.ts} +8 -2
  59. package/dist/globals.d.ts +12 -1
  60. package/dist/globals.js +1 -1
  61. package/dist/graphics.d.ts +16 -46
  62. package/dist/graphics.js +1 -1
  63. package/dist/input-ui.d.ts +5 -4
  64. package/dist/input-ui.js +1 -1
  65. package/dist/input.d.ts +48 -4
  66. package/dist/input.js +1 -1
  67. package/dist/{material-Wz83vTTp.d.ts → material-DbSuZBbP.d.ts} +25 -50
  68. package/dist/public.d.ts +38 -0
  69. package/dist/public.js +1 -0
  70. package/dist/runtime.d.ts +7 -381
  71. package/dist/runtime.js +1 -1
  72. package/dist/schema/entity.schema.json +244 -0
  73. package/dist/schema/game-config.schema.json +643 -0
  74. package/dist/schema/input-config.schema.json +517 -0
  75. package/dist/schema/stage-config.schema.json +93 -0
  76. package/dist/schema/stage.schema.json +271 -0
  77. package/dist/schema.d.ts +550 -0
  78. package/dist/schema.js +1 -0
  79. package/dist/stage-transition-CmGpV4tc.d.ts +46 -0
  80. package/dist/vector-DN6zlPoE.d.ts +161 -0
  81. package/dist/web-components.d.ts +15 -12
  82. package/dist/web-components.js +1 -9
  83. package/dist/{zylem-stage-runtime-Cs-UDEVU.d.ts → zylem-camera-Du2UPW9O.d.ts} +74 -264
  84. package/package.json +28 -20
  85. package/dist/chunk-73VZQZUL.js +0 -1
  86. package/dist/chunk-A34ZG3L4.js +0 -1
  87. package/dist/chunk-CDPY4VOQ.js +0 -1
  88. package/dist/chunk-DR6XXZE7.js +0 -19
  89. package/dist/chunk-FM5TBEPO.js +0 -1
  90. package/dist/chunk-G2IIMSUH.js +0 -1
  91. package/dist/chunk-MSC2BEO5.js +0 -1
  92. package/dist/chunk-NIH5CONO.js +0 -1
  93. package/dist/chunk-ONWXGBWB.js +0 -1
  94. package/dist/chunk-QEDQDR27.js +0 -1
  95. package/dist/chunk-WKHW2QO2.js +0 -1
  96. package/dist/chunk-YHKXQ2ZN.js +0 -1
  97. package/dist/game-default-PZLLHYL7.js +0 -1
  98. package/dist/world-C9zdyl5d.d.ts +0 -103
package/dist/core.d.ts CHANGED
@@ -1,25 +1,38 @@
1
- import { S as Stage, a as StageStateInterface, C as CameraWrapper } from './game-Cuj5gy7U.js';
2
- export { A as AspectRatio, r as AspectRatioValue, l as CameraOptions, D as DeviceProfile, q as FirstPersonOptions, m as FirstPersonPerspective, p as Fixed2DOptions, F as Fixed2DPerspective, G as Game, d as GameConfigLike, e as GameDeviceConfig, b as GameLoadingEvent, P as PerspectiveOptions, R as ResolutionInput, f as ResolveGameConfigRuntime, w as RetroPreset, x as RetroPresetKey, y as RetroResolution, i as StageConfigLike, j as StageOptions, o as ThirdPersonOptions, T as ThirdPersonPerspective, k as createCamera, c as createGame, n as createPerspective, h as createStage, g as gameConfig, t as getDisplayAspect, u as getPresetResolution, v as parseResolution, s as stageConfig } from './game-Cuj5gy7U.js';
3
- export { G as GameInputConfig, b as GameInputPlayerConfig, K as KeyboardMapping, M as MouseConfig, c as MouseMapping, d as VirtualTouchButtonConfig, a as VirtualTouchButtonSlot, e as VirtualTouchButtonsConfig, V as VirtualTouchConfig, f as VirtualTouchJoystickConfig, g as VirtualTouchJoysticksConfig, h as VirtualTouchPosition, i as VirtualTouchStyle, Z as ZylemGameConfig } from './game-interfaces-tfpM5NBk.js';
1
+ import { B as Stage, E as StageStateInterface, C as CameraWrapper } from './game-DbqBQiFC.js';
2
+ export { A as AspectRatio, q as AspectRatioValue, k as CameraManager, j as CameraOptions, D as DeviceProfile, p as FirstPersonOptions, l as FirstPersonPerspective, o as Fixed2DOptions, F as Fixed2DPerspective, G as Game, b as GameConfigLike, d as GameDeviceConfig, a as GameLoadingEvent, P as PerspectiveOptions, y as RenderBundleManager, z as RenderStrategyManager, R as ResolutionInput, e as ResolveGameConfigRuntime, v as RetroPreset, w as RetroPresetKey, x as RetroResolution, S as StageConfigLike, h as StageOptions, n as ThirdPersonOptions, T as ThirdPersonPerspective, i as createCamera, c as createGame, m as createPerspective, f as createStage, g as gameConfig, r as getDisplayAspect, t as getPresetResolution, u as parseResolution, s as stageConfig } from './game-DbqBQiFC.js';
3
+ export { G as GameInputConfig, a as GameInputPlayerConfig, K as KeyboardMapping, M as MouseConfig, b as MouseMapping, V as VirtualTouchButtonConfig, d as VirtualTouchButtonSlot, c as VirtualTouchButtonsConfig, e as VirtualTouchConfig, f as VirtualTouchJoystickConfig, g as VirtualTouchJoysticksConfig, h as VirtualTouchPosition, i as VirtualTouchStyle, Z as ZylemGameConfig } from './game-interfaces-vF5sRi1n.js';
4
4
  import { Vector2 } from 'three';
5
- import { G as GameEntity, M as BaseNode, Z as NodeInterface } from './entity-DNkYKfdp.js';
6
- import * as _sinclair_typebox from '@sinclair/typebox';
7
- import { Static } from '@sinclair/typebox';
8
- import { C as CameraBehavior } from './zylem-stage-runtime-Cs-UDEVU.js';
9
- export { l as CameraAction, j as CameraContext, f as CameraManager, k as CameraPerspective, n as CameraPipeline, m as CameraPipelineState, g as CameraPose, P as PerspectiveType, d as Perspectives, h as PoseDelta, e as RendererType, T as TransformLike, V as Viewport, Z as ZylemRenderer, i as isWebGPUSupported } from './zylem-stage-runtime-Cs-UDEVU.js';
10
- import { a as Vec3Input, c as Vec3 } from './material-Wz83vTTp.js';
11
- export { f as VEC2_ONE, g as VEC2_ZERO, h as VEC3_ONE, i as VEC3_ZERO, d as Vec2, e as Vec2Components, b as Vec2Input, V as Vec3Components, n as normalizeVec2, j as normalizeVec3, t as toRapierVector3, k as toThreeVector2, l as toThreeVector3 } from './material-Wz83vTTp.js';
12
- import { S as StageEntity } from './world-C9zdyl5d.js';
13
- import { S as SetupContext, L as LoadedContext, f as UpdateContext, D as DestroyContext, C as CleanupContext } from './base-node-life-cycle-CnJ-7zX-.js';
14
- export { g as LoadingEvent } from './base-node-life-cycle-CnJ-7zX-.js';
15
- import '@dimforge/rapier3d-compat';
5
+ import { G as GameEntity, B as BaseNode, N as NodeInterface, a as GameEntityOptions } from './entity-BGEq1yfC.js';
6
+ import { S as StageBlueprint } from './blueprints-TbGY-h53.js';
7
+ import { a as SetupContext, k as LoadedContext, U as UpdateContext, D as DestroyContext, l as CleanupContext } from './base-node-life-cycle-BK9xebT9.js';
8
+ export { L as LoadingEvent, S as StageNavigationOptions } from './base-node-life-cycle-BK9xebT9.js';
9
+ export { S as StageTransitionConfig, a as StageTransitionEasing, Z as ZylemTransitionShader, c as crossfadeTransitionShader } from './stage-transition-CmGpV4tc.js';
10
+ import { f as CameraBehavior } from './zylem-camera-Du2UPW9O.js';
11
+ export { g as CameraAction, d as CameraContext, e as CameraPerspective, j as CameraPipeline, h as CameraPipelineState, C as CameraPose, P as PerspectiveType, a as Perspectives, c as PoseDelta, T as TransformLike, V as Viewport, b as ZylemRenderer, i as isWebGPUSupported } from './zylem-camera-Du2UPW9O.js';
12
+ import { e as Vec3Input, c as Vec3 } from './vector-DN6zlPoE.js';
13
+ export { f as VEC2_ONE, g as VEC2_ZERO, h as VEC3_ONE, i as VEC3_ZERO, V as Vec2, a as Vec2Components, b as Vec2Input, d as Vec3Components, n as normalizeVec2, j as normalizeVec3, t as toThreeVector2, k as toThreeVector3 } from './vector-DN6zlPoE.js';
14
+ import { S as StageEntity } from './entity-B9yZeBm4.js';
15
+ import './entity-type-map-CW6RHQkx.js';
16
+ import './material-DbSuZBbP.js';
17
+ import 'three/webgpu';
16
18
  import '@zylem/behaviors/core';
17
- import './entity-type-map-C94h2TDW.js';
18
19
  import '@zylem/behaviors/particle-emitter';
20
+ import 'three/addons/lines/webgpu/Line2.js';
19
21
  import './events.js';
20
22
  import 'mitt';
21
- import './default-controls-BGc61yYl.js';
22
- import 'three/webgpu';
23
+ import './default-controls-CAKJ5zlo.js';
24
+ import './collision-builder-B_tm8OVy.js';
25
+ import '@sinclair/typebox';
26
+
27
+ /**
28
+ * Authoring helper for spawning entities into a live stage at runtime.
29
+ *
30
+ * Wraps an entity factory so game code can spawn at absolute coordinates or
31
+ * relative to an existing entity (using its physics body's position/rotation),
32
+ * automatically adding the resulting instance to the stage. Exists to keep
33
+ * gameplay spawn logic (e.g. firing projectiles) declarative and decoupled
34
+ * from the stage's internal entity-management plumbing.
35
+ */
23
36
 
24
37
  interface EntitySpawner {
25
38
  spawn: (stage: Stage, x: number, y: number) => Promise<GameEntity<any>>;
@@ -27,18 +40,7 @@ interface EntitySpawner {
27
40
  }
28
41
  declare function entitySpawner(factory: (x: number, y: number) => Promise<any> | GameEntity<any>): EntitySpawner;
29
42
 
30
- declare const StageSchema: _sinclair_typebox.TObject<{
31
- id: _sinclair_typebox.TString;
32
- name: _sinclair_typebox.TOptional<_sinclair_typebox.TString>;
33
- entities: _sinclair_typebox.TArray<_sinclair_typebox.TObject<{
34
- id: _sinclair_typebox.TString;
35
- type: _sinclair_typebox.TString;
36
- position: _sinclair_typebox.TOptional<_sinclair_typebox.TTuple<[_sinclair_typebox.TNumber, _sinclair_typebox.TNumber]>>;
37
- data: _sinclair_typebox.TOptional<_sinclair_typebox.TRecord<_sinclair_typebox.TString, _sinclair_typebox.TAny>>;
38
- }>>;
39
- assets: _sinclair_typebox.TOptional<_sinclair_typebox.TArray<_sinclair_typebox.TString>>;
40
- }>;
41
- type StageBlueprint = Static<typeof StageSchema>;
43
+ declare function setStageFrameProfilerEnabled(value: boolean): void;
42
44
 
43
45
  declare const stageState: {
44
46
  previous: StageBlueprint | null;
@@ -201,9 +203,22 @@ declare class Vessel extends BaseNode<{}, Vessel> {
201
203
  */
202
204
  declare function vessel(...args: Array<BaseNode>): Vessel;
203
205
 
206
+ /** How an entity's mesh is drawn: scene-direct, WebGPU bundle, or instanced pack. */
207
+ type RenderCategory = 'none' | 'environment' | 'pack';
208
+ type RenderCategoryOptions = Pick<GameEntityOptions, 'category'>;
209
+ /** Resolve the render category for an entity. Defaults to `none`. */
210
+ declare function resolveRenderCategory(options?: RenderCategoryOptions | null): RenderCategory;
211
+ /** Whether the entity opts into a managed render path (bundle or instanced). */
212
+ declare function usesManagedRenderPath(options?: RenderCategoryOptions | null): boolean;
213
+ /** Whether the entity is already registered on a managed render path. */
214
+ declare function isManagedRenderEntity(entity: {
215
+ isInstanced?: boolean;
216
+ isBundled?: boolean;
217
+ }): boolean;
218
+
204
219
  /**
205
220
  * @deprecated Use Vec3 from ../vector instead.
206
221
  */
207
222
  type Vect3 = Vec3;
208
223
 
209
- export { CameraBehavior, type CameraFeedOptions, CameraWrapper, type FollowTargetOptions, STAGE_STATE_CHANGE, SetupContext, type StageBlueprint, StageEntity, StageManager, type StageStateChangeEvent, UpdateContext, Vec3, Vec3Input, type Vect3, createFollowTarget, dispatchStageState, entitySpawner, initStageStateDispatcher, setCameraFeed, stageState, vessel };
224
+ export { CameraBehavior, type CameraFeedOptions, CameraWrapper, type FollowTargetOptions, type RenderCategory, STAGE_STATE_CHANGE, SetupContext, StageBlueprint, StageEntity, StageManager, type StageStateChangeEvent, UpdateContext, Vec3, Vec3Input, type Vect3, createFollowTarget, dispatchStageState, entitySpawner, initStageStateDispatcher, isManagedRenderEntity, resolveRenderCategory, setCameraFeed, setStageFrameProfilerEnabled, stageState, usesManagedRenderPath, vessel };
package/dist/core.js CHANGED
@@ -1,24 +1 @@
1
- import{a as Be,b as de,c as Ve,d as he,e as He,f as Oe,g as _e,h as Ne,i as Fe,j as Ue,k as Xe,l as Ye,m as Ze,n as Je,o as M,p as C}from"./chunk-QEDQDR27.js";import"./chunk-A34ZG3L4.js";import{a as f,b as pe,c as Y}from"./chunk-CDPY4VOQ.js";import{h as ge}from"./chunk-NIH5CONO.js";import{a as Z,m as K}from"./chunk-ONWXGBWB.js";import"./chunk-DR6XXZE7.js";import{a as me,b as y}from"./chunk-YHEWKN7N.js";import"./chunk-QXVH6POE.js";import"./chunk-73VZQZUL.js";import"./chunk-YHKXQ2ZN.js";import{c as v}from"./chunk-WKHW2QO2.js";import{c as ae,d as I,e as oe,h as se,i as re,j as le,k as X,l as w,m as ue}from"./chunk-4QLJUQSJ.js";import{a as Ie,b as Me,c as Pe,d as Le,g as ke,h as De,i as ze,j as J,k as Ae}from"./chunk-G2IIMSUH.js";import"./chunk-FM5TBEPO.js";import"./chunk-XRP4JJXL.js";import{g as ce}from"./chunk-RXDTAWI2.js";import{k as g}from"./chunk-MSC2BEO5.js";function Ke(){return{pressed:!1,released:!1,held:0}}function $e(){return{value:0,held:0}}function P(a){let e=new Map;if(!a)return e;for(let[t,n]of Object.entries(a)){if(!n||n.length===0)continue;let i=[];for(let o of n){let[r,s]=(o||"").split(".");if(!r||!s)continue;let l=r.toLowerCase(),u=s.toLowerCase();if(l==="buttons"){let p={a:"A",b:"B",x:"X",y:"Y",start:"Start",select:"Select",l:"L",r:"R"}[u];p&&i.push({category:"buttons",property:p})}else if(l==="directions"){let p={up:"Up",down:"Down",left:"Left",right:"Right"}[u];p&&i.push({category:"directions",property:p})}else if(l==="shoulders"){let p={ltrigger:"LTrigger",rtrigger:"RTrigger"}[u];p&&i.push({category:"shoulders",property:p})}else if(l==="axes"){let p={left:{property:"Horizontal",direction:-1},right:{property:"Horizontal",direction:1},up:{property:"Vertical",direction:-1},down:{property:"Vertical",direction:1},secondaryleft:{property:"SecondaryHorizontal",direction:-1},secondaryright:{property:"SecondaryHorizontal",direction:1},secondaryup:{property:"SecondaryVertical",direction:-1},secondarydown:{property:"SecondaryVertical",direction:1}}[u];p&&i.push({category:"axes",property:p.property,axisDirection:p.direction})}}i.length>0&&e.set(t,i)}return e}function d(a,e){return!a&&!e?Ke():a?e?{pressed:a.pressed||e.pressed,released:a.released||e.released,held:a.held+e.held}:{...a}:{...e}}function h(a,e){return!a&&!e?$e():a?e?{value:a.value+e.value,held:a.held+e.held}:{...a}:{...e}}var b=class{keyStates=new Map;keyButtonStates=new Map;analogStates=new Map;compiledMapping;includeDefaultBase=!0;onKeyDown=({key:e})=>this.keyStates.set(e,!0);onKeyUp=({key:e})=>this.keyStates.set(e,!1);constructor(e,t){this.includeDefaultBase=t?.includeDefaultBase??!0,this.compiledMapping=P(e??null),window.addEventListener("keydown",this.onKeyDown),window.addEventListener("keyup",this.onKeyUp)}dispose(){window.removeEventListener("keydown",this.onKeyDown),window.removeEventListener("keyup",this.onKeyUp),this.keyStates.clear(),this.keyButtonStates.clear(),this.analogStates.clear()}isKeyPressed(e){return this.keyStates.get(e)||!1}handleButtonState(e,t){let n=this.keyButtonStates.get(e);n||(n={pressed:!1,released:!1,held:0},this.keyButtonStates.set(e,n));let i=this.isKeyPressed(e);return n.pressed=i&&n.held===0,n.released=!i&&n.held>0,n.held=i?n.held+t:0,n}handleAnalogState(e,t,n){let i=`${e}:${t}`,o=this.analogStates.get(i);return o||(o={value:0,held:0},this.analogStates.set(i,o)),o.value=this.getAxisValue(e,t),o.held=o.value!==0?o.held+n:0,o}applyCustomMapping(e,t){if(this.compiledMapping.size===0)return e;let n=new Map;for(let[i,o]of this.compiledMapping.entries()){let r=null;for(let s of o)if(s.category==="axes")n.has(s.property)||n.set(s.property,0),this.isKeyPressed(i)&&n.set(s.property,n.get(s.property)+s.axisDirection);else{r||(r=this.handleButtonState(i,t));let l=e[s.category]??={};l[s.property]=d(l[s.property],r)}}if(n.size>0){e.axes||(e.axes={});for(let[i,o]of n.entries()){let r=`custom:${i}`,s=this.analogStates.get(r);s||(s={value:0,held:0},this.analogStates.set(r,s)),s.value=o,s.held=o!==0?s.held+t:0,e.axes[i]=h(e.axes[i],s)}}return e}getInput(e){let t={};return this.includeDefaultBase&&(t.buttons={A:this.handleButtonState("z",e),B:this.handleButtonState("x",e),X:this.handleButtonState("a",e),Y:this.handleButtonState("s",e),Start:this.handleButtonState(" ",e),Select:this.handleButtonState("Enter",e),L:this.handleButtonState("q",e),R:this.handleButtonState("e",e)},t.directions={Up:this.handleButtonState("ArrowUp",e),Down:this.handleButtonState("ArrowDown",e),Left:this.handleButtonState("ArrowLeft",e),Right:this.handleButtonState("ArrowRight",e)},t.shoulders={LTrigger:this.handleButtonState("Q",e),RTrigger:this.handleButtonState("E",e)}),this.applyCustomMapping(t,e)}getName(){return"keyboard"}getAxisValue(e,t){return(this.isKeyPressed(t)?1:0)-(this.isKeyPressed(e)?1:0)}isConnected(){return!0}};var L=class{gamepadIndex;connected=!1;buttonStates={};analogStates={};onConnected=e=>{e.gamepad.index===this.gamepadIndex&&(this.connected=!0)};onDisconnected=e=>{e.gamepad.index===this.gamepadIndex&&(this.connected=!1)};constructor(e){this.gamepadIndex=e,window.addEventListener("gamepadconnected",this.onConnected),window.addEventListener("gamepaddisconnected",this.onDisconnected)}dispose(){window.removeEventListener("gamepadconnected",this.onConnected),window.removeEventListener("gamepaddisconnected",this.onDisconnected),this.buttonStates={},this.analogStates={}}handleButtonState(e,t,n){let i=this.buttonStates[e];i||(i={pressed:!1,released:!1,held:0},this.buttonStates[e]=i);let o=t.buttons[e].pressed;return i.pressed=o&&i.held===0,i.released=!o&&i.held>0,i.held=o?i.held+n:0,i}handleAnalogState(e,t,n){let i=this.analogStates[e];return i||(i={value:0,held:0},this.analogStates[e]=i),i.value=t.axes[e],i.held=i.value!==0?i.held+n:0,i}getInput(e){let t=navigator.getGamepads()[this.gamepadIndex];return t?{buttons:{A:this.handleButtonState(0,t,e),B:this.handleButtonState(1,t,e),X:this.handleButtonState(2,t,e),Y:this.handleButtonState(3,t,e),Start:this.handleButtonState(9,t,e),Select:this.handleButtonState(8,t,e),L:this.handleButtonState(4,t,e),R:this.handleButtonState(5,t,e)},directions:{Up:this.handleButtonState(12,t,e),Down:this.handleButtonState(13,t,e),Left:this.handleButtonState(14,t,e),Right:this.handleButtonState(15,t,e)},axes:{Horizontal:this.handleAnalogState(0,t,e),Vertical:this.handleAnalogState(1,t,e),SecondaryHorizontal:this.handleAnalogState(2,t,e),SecondaryVertical:this.handleAnalogState(3,t,e)},shoulders:{LTrigger:this.handleButtonState(6,t,e),RTrigger:this.handleButtonState(7,t,e)}}:{}}getName(){return`gamepad-${this.gamepadIndex+1}`}isConnected(){return this.connected}};var We=.002,x=class{buttonStates=new Map;analogStates=new Map;compiledMapping;movementX=0;movementY=0;pointerX=0;pointerY=0;mouseButtonDown=new Set;sensitivity;usePointerLock;isLocked=!1;targetElement;onMouseMove=e=>{this.movementX+=e.movementX,this.movementY+=e.movementY,this.pointerX=e.clientX/window.innerWidth,this.pointerY=e.clientY/window.innerHeight};onMouseDown=e=>{let t=e.target;t instanceof HTMLCanvasElement&&this.targetElement.contains(t)&&(this.mouseButtonDown.add(e.button),this.usePointerLock&&!this.isLocked&&this.targetElement.requestPointerLock())};onMouseUp=e=>{this.mouseButtonDown.delete(e.button)};onContextMenu=e=>{e.preventDefault()};onPointerLockChange=()=>{this.isLocked=document.pointerLockElement===this.targetElement};constructor(e,t){this.sensitivity=e?.sensitivity??We,this.usePointerLock=e?.pointerLock??!1,this.compiledMapping=P(e?.mapping??null),this.targetElement=t??document.body,window.addEventListener("mousemove",this.onMouseMove),this.targetElement.addEventListener("mousedown",this.onMouseDown),this.targetElement.addEventListener("mouseup",this.onMouseUp),this.targetElement.addEventListener("contextmenu",this.onContextMenu),this.usePointerLock&&document.addEventListener("pointerlockchange",this.onPointerLockChange)}dispose(){window.removeEventListener("mousemove",this.onMouseMove),this.targetElement.removeEventListener("mousedown",this.onMouseDown),this.targetElement.removeEventListener("mouseup",this.onMouseUp),this.targetElement.removeEventListener("contextmenu",this.onContextMenu),document.removeEventListener("pointerlockchange",this.onPointerLockChange),this.isLocked&&document.exitPointerLock(),this.buttonStates.clear(),this.analogStates.clear(),this.mouseButtonDown.clear(),this.movementX=0,this.movementY=0}handleMouseButton(e,t){let n=this.buttonStates.get(e);n||(n={pressed:!1,released:!1,held:0},this.buttonStates.set(e,n));let i=this.mouseButtonDown.has(e);return n.pressed=i&&n.held===0,n.released=!i&&n.held>0,n.held=i?n.held+t:0,n}handleMovementAxis(e,t){let n=this.analogStates.get(e);n||(n={value:0,held:0},this.analogStates.set(e,n));let i=e==="x"?this.movementX:this.movementY;return n.value=Math.max(-1,Math.min(1,i*this.sensitivity)),n.held=n.value!==0?n.held+t:0,n}applyCustomMapping(e,t){if(this.compiledMapping.size===0)return e;let n=new Map,i={leftbutton:()=>this.handleMouseButton(0,t),rightbutton:()=>this.handleMouseButton(2,t),middlebutton:()=>this.handleMouseButton(1,t)};for(let[o,r]of this.compiledMapping.entries()){let s=o.toLowerCase();for(let l of r)if(l.category==="axes")n.has(l.property)||n.set(l.property,0),s==="movex"?n.set(l.property,n.get(l.property)+Math.max(-1,Math.min(1,this.movementX*this.sensitivity))*l.axisDirection):s==="movey"?n.set(l.property,n.get(l.property)+Math.max(-1,Math.min(1,this.movementY*this.sensitivity))*l.axisDirection):s in i&&this.mouseButtonDown.has(this.buttonIndexForAction(s))&&n.set(l.property,n.get(l.property)+l.axisDirection);else{let u=i[s];if(u){let m=u();if(m){let p=e[l.category]??={};p[l.property]=d(p[l.property],m)}}}}if(n.size>0){e.axes||(e.axes={});for(let[o,r]of n.entries()){let s=`custom:${o}`,l=this.analogStates.get(s);l||(l={value:0,held:0},this.analogStates.set(s,l)),l.value=Math.max(-1,Math.min(1,r)),l.held=r!==0?l.held+t:0,e.axes[o]=h(e.axes[o],l)}}return e}buttonIndexForAction(e){switch(e){case"leftbutton":return 0;case"middlebutton":return 1;case"rightbutton":return 2;default:return-1}}getInput(e){let t={axes:{Horizontal:{value:0,held:0},Vertical:{value:0,held:0},SecondaryHorizontal:this.handleMovementAxis("x",e),SecondaryVertical:this.handleMovementAxis("y",e)},shoulders:{LTrigger:this.handleMouseButton(0,e),RTrigger:this.handleMouseButton(2,e)},pointer:{x:this.pointerX,y:this.pointerY}};return this.movementX=0,this.movementY=0,this.applyCustomMapping(t,e)}getName(){return"mouse"}isConnected(){return!0}};function G(a={}){if(typeof window>"u"||typeof navigator>"u")return!1;let e=navigator.userAgent,t=/android/i.test(e)||/iPad|iPhone|iPod/.test(e),n="ontouchstart"in window||navigator.maxTouchPoints>0,i=typeof window.matchMedia=="function"?window.matchMedia("(pointer: coarse)").matches:!1,o=a.viewportSize?.width??window.innerWidth??0,r=a.viewportSize?.height??window.innerHeight??0,s=Math.max(o,r),l=s===0||s<=1024;return a.allowViewportOnly&&a.viewportSize?l:t||(n||i)&&l}var je=["A","B","X","Y","Start","Select","L","R","LTrigger","RTrigger","Up","Down","Left","Right"],qe=new Set(["flex","flexGrow","flexShrink","fontWeight","lineHeight","opacity","order","zIndex","zoom"]),Qe={A:{size:72,label:"A",position:{right:98,bottom:44}},B:{size:72,label:"B",position:{right:24,bottom:108}},X:{size:72,label:"X",position:{right:172,bottom:108}},Y:{size:72,label:"Y",position:{right:98,bottom:172}},Start:{size:64,label:"Start",position:{left:"50%",top:24,transform:"translateX(28px)"}},Select:{size:64,label:"Select",position:{left:"50%",top:24,transform:"translateX(-108px)"}},L:{size:62,label:"L",position:{left:28,bottom:184}},R:{size:62,label:"R",position:{right:236,bottom:184}},LTrigger:{size:76,label:"LT",position:{left:24,top:24}},RTrigger:{size:76,label:"RT",position:{right:24,top:24}},Up:{enabled:!1,size:64,label:"Up"},Down:{enabled:!1,size:64,label:"Down"},Left:{enabled:!1,size:64,label:"Left"},Right:{enabled:!1,size:64,label:"Right"}},et={left:{size:140,thumbSize:58,maxDistance:44,deadzone:.12,directionThreshold:.34,horizontalAxis:"Horizontal",verticalAxis:"Vertical",emitDirections:!0,position:{left:24,bottom:24}},right:{size:140,thumbSize:58,maxDistance:44,deadzone:.12,directionThreshold:.34,horizontalAxis:"SecondaryHorizontal",verticalAxis:"SecondaryVertical",emitDirections:!1,position:{right:24,bottom:236}}},T=class{config;targetElement;buttonStates=new Map;analogStates=new Map;buttons=new Map;joysticks=new Map;rootElement=null;enabled=!1;onPointerMove=e=>{for(let t of this.joysticks.values())t.pointerId===e.pointerId&&(this.consumeEvent(e),this.updateJoystickFromPoint(t,e.clientX,e.clientY))};onPointerUp=e=>{for(let t of this.buttons.values())t.pointerId===e.pointerId&&(this.consumeEvent(e),this.releaseButton(t));for(let t of this.joysticks.values())t.pointerId===e.pointerId&&(this.consumeEvent(e),this.releaseJoystick(t))};onWindowBlur=()=>{for(let e of this.buttons.values())this.releaseButton(e);for(let e of this.joysticks.values())this.releaseJoystick(e)};constructor(e,t){this.config=e??{},this.targetElement=t??document.body,this.enabled=this.resolveEnabledState(),this.enabled&&(this.mountControls(),window.addEventListener("pointermove",this.onPointerMove),window.addEventListener("pointerup",this.onPointerUp),window.addEventListener("pointercancel",this.onPointerUp),window.addEventListener("blur",this.onWindowBlur))}getInput(e){if(!this.enabled)return{};let t={};for(let n of this.buttons.values()){let i=this.handleButtonState(`button:${n.slot}`,n.pointerId!==null,e);this.assignButtonState(t,this.resolveButtonTarget(n.slot),i)}for(let n of this.joysticks.values()){let i=this.handleAnalogState(`joystick:${n.id}:x`,n.valueX,e),o=this.handleAnalogState(`joystick:${n.id}:y`,n.valueY,e);this.assignAxisState(t,n.config.horizontalAxis,i),this.assignAxisState(t,n.config.verticalAxis,o),n.config.emitDirections&&(this.assignButtonState(t,this.resolveButtonTarget("Left"),this.handleButtonState(`joystick:${n.id}:left`,n.valueX<=-n.config.directionThreshold,e)),this.assignButtonState(t,this.resolveButtonTarget("Right"),this.handleButtonState(`joystick:${n.id}:right`,n.valueX>=n.config.directionThreshold,e)),this.assignButtonState(t,this.resolveButtonTarget("Up"),this.handleButtonState(`joystick:${n.id}:up`,n.valueY<=-n.config.directionThreshold,e)),this.assignButtonState(t,this.resolveButtonTarget("Down"),this.handleButtonState(`joystick:${n.id}:down`,n.valueY>=n.config.directionThreshold,e)))}return t}getName(){return"virtual-touch"}isConnected(){return this.enabled}dispose(){window.removeEventListener("pointermove",this.onPointerMove),window.removeEventListener("pointerup",this.onPointerUp),window.removeEventListener("pointercancel",this.onPointerUp),window.removeEventListener("blur",this.onWindowBlur),this.rootElement?.remove(),this.rootElement=null,this.buttons.clear(),this.joysticks.clear(),this.buttonStates.clear(),this.analogStates.clear()}resolveEnabledState(){return typeof window>"u"||typeof document>"u"?!1:this.config.enabled===!0?!0:this.config.enabled===!1?!1:G()}mountControls(){this.rootElement=document.createElement("div"),this.rootElement.className="zylem-virtual-touch",this.rootElement.dataset.zylemTouchRoot="true",this.rootElement.style.position="absolute",this.rootElement.style.inset="0",this.rootElement.style.pointerEvents="none",this.rootElement.style.touchAction="none",this.rootElement.style.userSelect="none",this.rootElement.style.WebkitUserSelect="none",this.rootElement.style.WebkitTouchCallout="none",this.rootElement.style.color="rgba(245, 247, 255, 0.96)",this.rootElement.style.zIndex="20",this.appendClassName(this.rootElement,this.config.className),R(this.rootElement,this.config.style),this.rootElement.addEventListener("contextmenu",e=>e.preventDefault());for(let[e,t]of this.resolveButtons())this.rootElement.appendChild(this.createButton(e,t));for(let[e,t]of this.resolveJoysticks())this.rootElement.appendChild(this.createJoystick(e,t));this.targetElement.appendChild(this.rootElement)}resolveButtons(){if(this.config.buttons===!1)return[];let e=this.config.buttons,t=[];for(let n of je){let i=Qe[n],o=e?.[n];if(o===!1)continue;let r={...i,...o??{},style:{...i.style,...o?.style},position:{...i.position,...o?.position},label:o?.label??i.label??n,size:o?.size??i.size??72};r.enabled!==!1&&t.push([n,r])}return t}resolveJoysticks(){if(this.config.joysticks===!1)return[];let e=this.config.joysticks,t=[];for(let n of["left","right"]){let i=et[n],o=e?.[n];if(o===!1)continue;let r={...i,...o??{},style:{...i.style,...o?.style},position:{...i.position,...o?.position},svg:{...i.svg,...o?.svg},size:o?.size??i.size??140,thumbSize:o?.thumbSize??i.thumbSize??58,maxDistance:o?.maxDistance??i.maxDistance??44,deadzone:o?.deadzone??i.deadzone??.12,directionThreshold:o?.directionThreshold??i.directionThreshold??.34,horizontalAxis:o?.horizontalAxis??i.horizontalAxis??"Horizontal",verticalAxis:o?.verticalAxis??i.verticalAxis??"Vertical",emitDirections:o?.emitDirections??i.emitDirections??!1};r.enabled!==!1&&t.push([n,r])}return t}createButton(e,t){let n=document.createElement("button"),i=document.createElement("div");n.type="button",n.ariaLabel=t.label,n.className=`zylem-virtual-touch__button zylem-virtual-touch__button--${e}`,n.dataset.zylemTouchButton=e,n.dataset.active="false",n.style.position="absolute",n.style.width=`${t.size}px`,n.style.height=`${t.size}px`,n.style.padding="0",n.style.margin="0",n.style.border="0",n.style.background="transparent",n.style.pointerEvents="auto",n.style.touchAction="none",n.style.cursor="pointer",n.style.appearance="none",n.style.outline="none",n.style.userSelect="none",n.style.WebkitTapHighlightColor="transparent",R(n,t.position),R(n,t.style),this.appendClassName(n,t.className),i.className="zylem-virtual-touch__button-content",i.style.width="100%",i.style.height="100%",i.style.pointerEvents="none",i.style.transform="scale(1)",i.style.transformOrigin="center",i.style.transition="transform 120ms ease, opacity 120ms ease",i.style.opacity="0.92",i.innerHTML=t.svg??nt(t.label),n.appendChild(i),n.addEventListener("pointerdown",r=>{if(!fe(r))return;let s=this.buttons.get(e);!s||s.pointerId!==null||(this.consumeEvent(r),s.pointerId=r.pointerId,this.updateButtonVisual(s,!0))});let o={slot:e,config:t,element:n,content:i,pointerId:null};return this.buttons.set(e,o),n}createJoystick(e,t){let n=document.createElement("div"),i=document.createElement("div"),o=document.createElement("div");n.className=`zylem-virtual-touch__joystick zylem-virtual-touch__joystick--${e}`,n.dataset.zylemTouchJoystick=e,n.dataset.active="false",n.style.position="absolute",n.style.width=`${t.size}px`,n.style.height=`${t.size}px`,n.style.pointerEvents="auto",n.style.touchAction="none",n.style.userSelect="none",R(n,t.position),R(n,t.style),this.appendClassName(n,t.className),i.className="zylem-virtual-touch__joystick-base",i.style.position="absolute",i.style.inset="0",i.style.pointerEvents="none",i.style.opacity="0.88",i.style.transition="opacity 120ms ease",i.innerHTML=t.svg?.base??it(),o.className="zylem-virtual-touch__joystick-thumb",o.style.position="absolute",o.style.left="50%",o.style.top="50%",o.style.width=`${t.thumbSize}px`,o.style.height=`${t.thumbSize}px`,o.style.pointerEvents="none",o.style.transform="translate(-50%, -50%) translate(0px, 0px)",o.style.transition="transform 60ms linear, opacity 120ms ease",o.style.opacity="0.94",o.innerHTML=t.svg?.thumb??at(),n.append(i,o);let r={id:e,config:t,element:n,base:i,thumb:o,pointerId:null,centerX:0,centerY:0,rawX:0,rawY:0,valueX:0,valueY:0};return this.joysticks.set(e,r),n.addEventListener("pointerdown",s=>{if(!fe(s))return;let l=this.joysticks.get(e);if(!l||l.pointerId!==null)return;this.consumeEvent(s);let u=l.element.getBoundingClientRect();l.pointerId=s.pointerId,l.centerX=u.left+u.width/2,l.centerY=u.top+u.height/2,this.updateJoystickVisual(l,!0),this.updateJoystickFromPoint(l,s.clientX,s.clientY)}),n}handleButtonState(e,t,n){let i=this.buttonStates.get(e);return i||(i={pressed:!1,released:!1,held:0},this.buttonStates.set(e,i)),i.pressed=t&&i.held===0,i.released=!t&&i.held>0,i.held=t?i.held+n:0,i}handleAnalogState(e,t,n){let i=this.analogStates.get(e);return i||(i={value:0,held:0},this.analogStates.set(e,i)),i.value=t,i.held=t!==0?i.held+n:0,i}assignAxisState(e,t,n){e.axes||(e.axes={}),e.axes[t]=h(e.axes[t],n)}assignButtonState(e,t,n){if(t.category==="buttons"){e.buttons??={},e.buttons[t.property]=d(e.buttons[t.property],n);return}if(t.category==="directions"){e.directions??={},e.directions[t.property]=d(e.directions[t.property],n);return}e.shoulders??={},e.shoulders[t.property]=d(e.shoulders[t.property],n)}resolveButtonTarget(e){switch(e){case"LTrigger":case"RTrigger":return{category:"shoulders",property:e};case"Up":case"Down":case"Left":case"Right":return{category:"directions",property:e};default:return{category:"buttons",property:e}}}updateJoystickFromPoint(e,t,n){let i=t-e.centerX,o=n-e.centerY,r=Math.hypot(i,o),s=e.config.maxDistance,l=r>s&&r>0?s/r:1;e.rawX=i*l,e.rawY=o*l;let u=tt(e.rawX/s,e.rawY/s,e.config.deadzone);e.valueX=u.x,e.valueY=u.y,e.thumb.style.transform=`translate(-50%, -50%) translate(${e.rawX}px, ${e.rawY}px)`}releaseButton(e){e.pointerId=null,this.updateButtonVisual(e,!1)}releaseJoystick(e){e.pointerId=null,e.rawX=0,e.rawY=0,e.valueX=0,e.valueY=0,e.thumb.style.transform="translate(-50%, -50%) translate(0px, 0px)",this.updateJoystickVisual(e,!1)}updateButtonVisual(e,t){e.element.dataset.active=String(t),e.content.style.transform=t?"scale(0.94)":"scale(1)",e.content.style.opacity=t?"1":"0.92"}updateJoystickVisual(e,t){e.element.dataset.active=String(t),e.base.style.opacity=t?"1":"0.88",e.thumb.style.opacity=t?"1":"0.94"}consumeEvent(e){e.cancelable&&e.preventDefault(),e.stopPropagation()}appendClassName(e,t){t&&(e.className=`${e.className} ${t}`.trim())}};function R(a,e){if(e)for(let[t,n]of Object.entries(e)){if(n==null)continue;let i=typeof n=="number"&&!qe.has(t)?`${n}px`:String(n);t.includes("-")?a.style.setProperty(t,i):a.style[t]=i}}function tt(a,e,t){let n=Math.hypot(a,e);if(n===0||n<=t)return{x:0,y:0};let o=Math.min(1,(n-t)/Math.max(1-t,1e-4))/n;return{x:a*o,y:e*o}}function nt(a){let e=ot(a);return`
2
- <svg viewBox="0 0 100 100" width="100%" height="100%" aria-hidden="true">
3
- <circle cx="50" cy="50" r="45" fill="rgba(12,18,24,0.72)" stroke="currentColor" stroke-width="4" />
4
- <circle cx="50" cy="50" r="34" fill="rgba(255,255,255,0.06)" stroke="rgba(255,255,255,0.12)" stroke-width="1.5" />
5
- <text
6
- x="50"
7
- y="56"
8
- text-anchor="middle"
9
- font-family="ui-sans-serif, system-ui, sans-serif"
10
- font-size="${e.length>2?24:34}"
11
- font-weight="700"
12
- fill="currentColor"
13
- >${e}</text>
14
- </svg>
15
- `}function it(){return`
16
- <svg viewBox="0 0 140 140" width="100%" height="100%" aria-hidden="true">
17
- <circle cx="70" cy="70" r="62" fill="rgba(10,16,20,0.64)" stroke="currentColor" stroke-width="4" />
18
- <circle cx="70" cy="70" r="40" fill="rgba(255,255,255,0.04)" stroke="rgba(255,255,255,0.12)" stroke-width="1.5" />
19
- </svg>
20
- `}function at(){return`
21
- <svg viewBox="0 0 64 64" width="100%" height="100%" aria-hidden="true">
22
- <circle cx="32" cy="32" r="28" fill="rgba(22,30,38,0.9)" stroke="currentColor" stroke-width="3.5" />
23
- </svg>
24
- `}function ot(a){return a.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;").replaceAll("'","&#39;")}function fe(a){return a.pointerType==="touch"}var k=class{inputMap=new Map;currentInputs={};previousInputs={};targetElement;mouseTargetElement;constructor(e,t){this.targetElement=t?.targetElement,this.mouseTargetElement=t?.mouseTargetElement??t?.targetElement;let n=this.buildPlayerEntries(e);for(let{player:i,config:o,gamepadIndex:r,isP1:s}of n)this.addConfigurableProviders(i,o,s),this.addInputProvider(i,new L(r))}configure(e){let t=this.buildPlayerEntries(e);for(let{player:n,config:i,isP1:o}of t){let s=(this.inputMap.get(n)??[]).filter(l=>l instanceof b||l instanceof x||l instanceof T?(l.dispose(),!1):!0);this.inputMap.set(n,[...this.createConfigurableProviders(i,o),...s])}}addInputProvider(e,t){this.inputMap.has(e)||this.inputMap.set(e,[]),this.inputMap.get(e)?.push(t)}dispose(){for(let e of this.inputMap.values())for(let t of e)t.dispose?.();this.inputMap.clear(),this.currentInputs={},this.previousInputs={}}getInputs(e){let t={};return this.inputMap.forEach((n,i)=>{let o=`p${i}`,r=n.reduce((s,l)=>{let u=l.getInput(e);return this.mergeInputs(s,u)},{});t[o]={playerNumber:i,...r}}),t}buildPlayerEntries(e){return[{player:1,config:e?.p1,gamepadIndex:0,isP1:!0},{player:2,config:e?.p2,gamepadIndex:1,isP1:!1},{player:3,config:e?.p3,gamepadIndex:2,isP1:!1},{player:4,config:e?.p4,gamepadIndex:3,isP1:!1},{player:5,config:e?.p5,gamepadIndex:4,isP1:!1},{player:6,config:e?.p6,gamepadIndex:5,isP1:!1},{player:7,config:e?.p7,gamepadIndex:6,isP1:!1},{player:8,config:e?.p8,gamepadIndex:7,isP1:!1}]}addConfigurableProviders(e,t,n){for(let i of this.createConfigurableProviders(t,n))this.addInputProvider(e,i)}createConfigurableProviders(e,t){let n=[];if(e?.key){let i=e.includeDefaults??t;n.push(new b(e.key,{includeDefaultBase:i}))}else t&&n.push(new b);return e?.mouse&&n.push(new x(e.mouse,this.mouseTargetElement)),e?.touch&&n.push(new T(e.touch,this.targetElement)),n}mergeInputs(e,t){return{buttons:{A:d(e.buttons?.A,t.buttons?.A),B:d(e.buttons?.B,t.buttons?.B),X:d(e.buttons?.X,t.buttons?.X),Y:d(e.buttons?.Y,t.buttons?.Y),Start:d(e.buttons?.Start,t.buttons?.Start),Select:d(e.buttons?.Select,t.buttons?.Select),L:d(e.buttons?.L,t.buttons?.L),R:d(e.buttons?.R,t.buttons?.R)},directions:{Up:d(e.directions?.Up,t.directions?.Up),Down:d(e.directions?.Down,t.directions?.Down),Left:d(e.directions?.Left,t.directions?.Left),Right:d(e.directions?.Right,t.directions?.Right)},axes:{Horizontal:h(e.axes?.Horizontal,t.axes?.Horizontal),Vertical:h(e.axes?.Vertical,t.axes?.Vertical),SecondaryHorizontal:h(e.axes?.SecondaryHorizontal,t.axes?.SecondaryHorizontal),SecondaryVertical:h(e.axes?.SecondaryVertical,t.axes?.SecondaryVertical)},shoulders:{LTrigger:d(e.shoulders?.LTrigger,t.shoulders?.LTrigger),RTrigger:d(e.shoulders?.RTrigger,t.shoulders?.RTrigger)},pointer:t.pointer??e.pointer}}};var D=class{_previousTime;_currentTime;_startTime;_delta;_elapsed;_timescale;_document;_pageVisibilityHandler;constructor(){this._previousTime=0,this._currentTime=0,this._startTime=$(),this._delta=0,this._elapsed=0,this._timescale=1,this._document=null,this._pageVisibilityHandler=null}connect(e){this._document=e,e.hidden!==void 0&&(this._pageVisibilityHandler=st.bind(this),e.addEventListener("visibilitychange",this._pageVisibilityHandler,!1))}disconnect(){this._pageVisibilityHandler!==null&&(this._document.removeEventListener("visibilitychange",this._pageVisibilityHandler),this._pageVisibilityHandler=null),this._document=null}getDelta(){return this._delta/1e3}getElapsed(){return this._elapsed/1e3}getTimescale(){return this._timescale}setTimescale(e){return this._timescale=e,this}reset(){return this._currentTime=$()-this._startTime,this}dispose(){this.disconnect()}update(e){return this._pageVisibilityHandler!==null&&this._document.hidden===!0?this._delta=0:(this._previousTime=this._currentTime,this._currentTime=(e!==void 0?e:$())-this._startTime,this._delta=(this._currentTime-this._previousTime)*this._timescale,this._elapsed+=this._delta),this}};function $(){return performance.now()}function st(){this._document.hidden===!1&&this.reset()}var E={FourByThree:1.3333333333333333,SixteenByNine:1.7777777777777777,NineBySixteen:.5625,TwentyOneByNine:2.3333333333333335,OneByOne:1},z=class{container;canvas;aspectRatio;onResize;handleResizeBound;resizeObserver=null;constructor(e){this.container=e.container,this.canvas=e.canvas,this.aspectRatio=(typeof e.aspectRatio=="number",e.aspectRatio),this.onResize=e.onResize,this.handleResizeBound=this.apply.bind(this)}attach(){window.addEventListener("resize",this.handleResizeBound),typeof ResizeObserver<"u"&&(this.resizeObserver=new ResizeObserver(this.handleResizeBound),this.resizeObserver.observe(this.container)),this.apply()}detach(){window.removeEventListener("resize",this.handleResizeBound),this.resizeObserver?.disconnect(),this.resizeObserver=null}measure(){let e=this.container.getBoundingClientRect(),t=Math.round(e.width||this.container.clientWidth||0),n=Math.round(e.height||this.container.clientHeight||0);if(t>0&&n>0){if(t/n>this.aspectRatio){let u=n;return{width:Math.round(u*this.aspectRatio),height:u}}let s=t,l=Math.round(s/this.aspectRatio);return{width:s,height:l}}if(t>0){let r=t,s=Math.round(r/this.aspectRatio);return{width:r,height:s}}if(n>0){let r=n;return{width:Math.round(r*this.aspectRatio),height:r}}let i=window.innerWidth,o=Math.round(i/this.aspectRatio);return{width:i,height:o}}apply(){let{width:e,height:t}=this.measure();this.canvas.style.width=`${e}px`,this.canvas.style.height=`${t}px`,this.onResize?.(e,t)}};var ye={NES:{displayAspect:1.3333333333333333,resolutions:[{key:"256x240",width:256,height:240,notes:"Standard NTSC; effective 240p."}]},SNES:{displayAspect:1.3333333333333333,resolutions:[{key:"256x224",width:256,height:224,notes:"Common 240p-equivalent mode."},{key:"512x448",width:512,height:448,notes:"Hi-res interlaced (480i)."}]},N64:{displayAspect:1.3333333333333333,resolutions:[{key:"320x240",width:320,height:240,notes:"Common 240p mode."},{key:"640x480",width:640,height:480,notes:"Higher resolution (480i)."}]},PS1:{displayAspect:1.3333333333333333,resolutions:[{key:"320x240",width:320,height:240,notes:"Progressive 240p common."},{key:"640x480",width:640,height:480,notes:"Interlaced 480i for higher detail."}]},PS2:{displayAspect:1.3333333333333333,resolutions:[{key:"640x480",width:640,height:480,notes:"480i/480p baseline."},{key:"720x480",width:720,height:480,notes:"480p (widescreen capable in some titles)."},{key:"1280x720",width:1280,height:720,notes:"720p (select titles)."}]},PS5:{displayAspect:1.7777777777777777,resolutions:[{key:"720x480",width:720,height:480,notes:"Legacy compatibility."},{key:"1280x720",width:1280,height:720,notes:"720p."},{key:"1920x1080",width:1920,height:1080,notes:"1080p."},{key:"2560x1440",width:2560,height:1440,notes:"1440p."},{key:"3840x2160",width:3840,height:2160,notes:"4K (up to 120Hz)."},{key:"7680x4320",width:7680,height:4320,notes:"8K (limited)."}]},XboxOne:{displayAspect:1.7777777777777777,resolutions:[{key:"1280x720",width:1280,height:720,notes:"720p (original)."},{key:"1920x1080",width:1920,height:1080,notes:"1080p (original)."},{key:"3840x2160",width:3840,height:2160,notes:"4K UHD (S/X models)."}]},MobilePortrait:{displayAspect:.5625,resolutions:[{key:"360x640",width:360,height:640,notes:"Low-density phone portrait baseline."},{key:"720x1280",width:720,height:1280,notes:"HD phone portrait."},{key:"1080x1920",width:1080,height:1920,notes:"Full HD phone portrait."}]}};function W(a){return ye[a].displayAspect}function j(a,e){let t=ye[a]?.resolutions||[];if(!e)return t[0];let n=e.toLowerCase().replace(/\s+/g,"").replace("\xD7","x");return t.find(i=>i.key.toLowerCase()===n)}function q(a){if(!a)return null;let t=String(a).toLowerCase().trim().replace(/\s+/g,"").replace("\xD7","x").match(/^(\d+)x(\d+)$/);if(!t)return null;let n=parseInt(t[1],10),i=parseInt(t[2],10);return!Number.isFinite(n)||!Number.isFinite(i)?null:{width:n,height:i}}var Q=null,ee=class{constructor(e,t,n,i,o,r,s,l,u,m,p,S,U){this.id=e;this.globals=t;this.stages=n;this.debug=i;this.time=o;this.input=r;this.aspectRatio=s;this.internalResolution=l;this.fullscreen=u;this.bodyBackground=m;this.container=p;this.containerId=S;this.canvas=U}};function rt(a={}){return a.deviceProfile==="mobile"?!0:a.deviceProfile==="desktop"?!1:a.viewportSize?G({viewportSize:a.viewportSize,allowViewportOnly:!0}):G()}function lt(a,e){if(e)return e;if(a){let i=document.getElementById(a);if(i)return i}let t=a||"zylem-root",n=document.createElement("main");return n.setAttribute("id",t),n.style.position="relative",n.style.width="100%",n.style.height="100%",document.body.appendChild(n),n}function ut(a){let e=a?.id??"zylem";return{id:e,globals:a?.globals??{},stages:a?.stages??[],debug:!!a?.debug,time:a?.time??0,input:a?.input,aspectRatio:E.SixteenByNine,fullscreen:!0,bodyBackground:"#000000",containerId:e}}var ve=360;function be(a,e){if(!a)return;if(typeof a=="string"){if(a==="native")return Q;let i=q(a);if(i)return i;if(e){let o=j(e,a);if(o)return{width:o.width,height:o.height}}return}let t=a.width,n=a.height;if(Number.isFinite(t)&&Number.isFinite(n))return{width:t,height:n}}function pt(a,e,t,n){if(typeof a=="number")return a;if(typeof a=="string")return E[a]??t;if(e)try{return W(e)||t}catch{return t}return n?n.width/n.height:t}function dt(a){let e=Number.isFinite(a)&&a>0?a:E.SixteenByNine;if(e>=1){let i=ve;return{width:Math.round(i*e),height:i}}let t=ve,n=Math.round(t/e);return{width:t,height:n}}function B(a,e={}){let t=ut({id:a?.id??"zylem",debug:!!a?.debug,time:a?.time??0,input:a?.input,stages:a?.stages??[],globals:a?.globals??{}}),n=a?.containerId??t.containerId,i=lt(n,a?.container??null),o=a?.mobile,r=rt(e),s=r?o?.preset??a?.preset:a?.preset,l=be(a?.resolution,a?.preset),u=be(o?.resolution,o?.preset??a?.preset),m=(r?Se(u):void 0)??Se(l),p=r?o?.aspectRatio??a?.aspectRatio:a?.aspectRatio,S=pt(p,s,t.aspectRatio,m),U=ct(r,u,l,S),Ge=a?.fullscreen??t.fullscreen,Re=a?.bodyBackground??t.bodyBackground,Te=a?.canvas??void 0,Ee=mt(a?.input??t.input,o?.controls);return new ee(a?.id??t.id,a?.globals??t.globals,a?.stages??t.stages,!!(a?.debug??t.debug),a?.time??t.time,Ee,S,U,Ge,Re,i,n,Te)}function Se(a){if(a)return a}function ct(a,e,t,n){if(a)return e===Q?void 0:e??dt(n);if(t!==Q)return t}function mt(a,e){if(!e)return a;let n=ce("p1",{enabled:"auto",...e===!0?{}:e});return g(n,a??{})}function ht(a){return{...a}}var A=class{id;container;canvas;bodyBackground;fullscreen;aspectRatio;ratioDelegate=null;overlayContainer=null;constructor(e){this.id=e.id,this.container=this.ensureContainer(e.containerId??e.id,e.container),this.canvas=e.canvas??document.createElement("canvas"),this.bodyBackground=e.bodyBackground,this.fullscreen=!!e.fullscreen,this.aspectRatio=(typeof e.aspectRatio=="number",e.aspectRatio)}applyBodyBackground(){this.bodyBackground&&(document.body.style.background=this.bodyBackground)}mountCanvas(){this.mountChildren(this.canvas)}mountRenderer(e,t){this.mountChildren(e),this.canvas=e,this.attachAspectRatio(t)}getOverlayContainer(){return this.ensureOverlayContainer()}centerIfFullscreen(){if(!this.fullscreen)return;let e=this.container.style;e.display="flex",e.alignItems="center",e.justifyContent="center",e.position="relative",e.inset="0"}attachAspectRatio(e){this.ratioDelegate?(this.ratioDelegate.canvas=this.canvas,this.ratioDelegate.onResize=e,this.ratioDelegate.aspectRatio=this.aspectRatio,this.ratioDelegate.apply()):(this.ratioDelegate=new z({container:this.container,canvas:this.canvas,aspectRatio:this.aspectRatio,onResize:e}),this.ratioDelegate.attach())}setAspectRatio(e){this.aspectRatio=e,this.ratioDelegate&&(this.ratioDelegate.aspectRatio=e,this.ratioDelegate.apply())}reapplyLayout(){this.ratioDelegate?.apply()}destroy(){this.ratioDelegate?.detach(),this.ratioDelegate=null}mountChildren(e){for(;this.container.firstChild;)this.container.removeChild(this.container.firstChild);this.container.appendChild(e),this.container.appendChild(this.ensureOverlayContainer())}ensureOverlayContainer(){if(this.overlayContainer)return this.overlayContainer;let e=document.createElement("div");return e.dataset.zylemOverlayRoot="true",e.style.position="absolute",e.style.inset="0",e.style.pointerEvents="none",e.style.touchAction="none",e.style.zIndex="10",this.overlayContainer=e,e}ensureContainer(e,t){if(t)return t;if(e){let o=document.getElementById(e);if(o)return o}let n=e||this.id||"zylem-root",i=document.createElement("main");return i.setAttribute("id",n),i.style.position="relative",i.style.width="100%",i.style.height="100%",document.body.appendChild(i),i}};import gt from"stats.js";import{subscribe as ft}from"valtio/vanilla";var V=class{statsRef=null;unsubscribe=null;constructor(){this.updateDebugUI(),this.unsubscribe=ft(f,()=>{this.updateDebugUI()})}begin(){this.statsRef?.begin()}end(){this.statsRef?.end()}updateDebugUI(){f.enabled&&!this.statsRef?(this.statsRef=new gt,this.statsRef.showPanel(0),this.statsRef.dom.style.position="absolute",this.statsRef.dom.style.bottom="0",this.statsRef.dom.style.right="0",this.statsRef.dom.style.top="auto",this.statsRef.dom.style.left="auto",document.body.appendChild(this.statsRef.dom)):!f.enabled&&this.statsRef&&(this.statsRef.dom.parentNode&&this.statsRef.dom.parentNode.removeChild(this.statsRef.dom),this.statsRef=null)}dispose(){this.unsubscribe&&(this.unsubscribe(),this.unsubscribe=null),this.statsRef?.dom?.parentNode&&this.statsRef.dom.parentNode.removeChild(this.statsRef.dom),this.statsRef=null}};var H=class{loadingHandlers=[];stageLoadingUnsubscribes=[];onLoading(e){return this.loadingHandlers.push(e),()=>{this.loadingHandlers=this.loadingHandlers.filter(t=>t!==e)}}emit(e){for(let n of this.loadingHandlers)try{n(e)}catch(i){console.error("Game loading handler failed",i)}let t=`loading:${e.type}`;y.emit(t,e)}wireStageLoading(e,t){let n=e.onLoading(i=>{this.emit({type:i.type,message:i.message??"",progress:i.progress??0,current:i.current,total:i.total,stageName:e.uuid??`Stage ${t}`,stageIndex:t})});typeof n=="function"&&this.stageLoadingUnsubscribes.push(n)}unwireAllStages(){for(let e of this.stageLoadingUnsubscribes)try{e()}catch{}this.stageLoadingUnsubscribes=[]}dispose(){this.unwireAllStages(),this.loadingHandlers=[]}};var O=class{container=null;camera=null;rendererManager=null;gameCanvas=null;config=null;stage=null;mounted=!1;setGameCanvas(e){this.gameCanvas=e,this.tryMount()}setConfig(e){this.config=e,this.tryMount()}setContainer(e){this.container=e,this.tryMount()}setStage(e){this.stage=e,this.mounted&&this.gameCanvas?.reapplyLayout()}setCamera(e){this.camera=e,this.tryMount()}setRendererManager(e){this.rendererManager=e,this.tryMount()}tryMount(){this.mounted||!this.container||!this.gameCanvas||(this.rendererManager?this.mountWithRendererManager():this.camera&&this.mountWithCamera())}mountWithRendererManager(){if(!this.rendererManager||!this.gameCanvas)return;let e=this.rendererManager.getDomElement();this.gameCanvas.mountRenderer(e,(t,n)=>{if(!this.rendererManager)return;let i=this.config?.internalResolution;if(i)this.rendererManager.setPixelRatio(1),this.rendererManager.resize(i.width,i.height),this.stage?.resize(i.width,i.height);else{let o=window.devicePixelRatio||1;this.rendererManager.setPixelRatio(o),this.rendererManager.resize(t,n),this.stage?.resize(t,n)}}),this.mounted=!0}mountWithCamera(){if(!this.camera||!this.gameCanvas)return;let e=this.camera.getDomElement();this.gameCanvas.mountRenderer(e,(t,n)=>{if(!this.camera)return;let i=this.config?.internalResolution;if(i)this.camera.setPixelRatio(1),this.camera.resize(i.width,i.height);else{let o=window.devicePixelRatio||1;this.camera.setPixelRatio(o),this.camera.resize(t,n)}}),this.mounted=!0}reset(){this.camera=null,this.stage=null,this.mounted=!1}dispose(){this.container=null,this.camera=null,this.rendererManager=null,this.gameCanvas=null,this.config=null,this.stage=null,this.mounted=!1}};var _=class a{id;initialGlobals={};customSetup=null;customUpdate=null;customDestroy=null;stages=[];stageMap=new Map;currentStageId="";previousTimeStamp=0;totalTime=0;timer;inputManager;wrapperRef;globalInputConfig;defaultCamera=null;rendererManager=null;container=null;canvas=null;aspectRatioDelegate=null;resolvedConfig=null;gameCanvas=null;animationFrameId=null;isDisposed=!1;hasStarted=!1;debugDelegate=null;loadingDelegate=new H;rendererObserver=new O;eventBusUnsubscribes=[];gameUpdateParams={};stageSetupParams={};stageUpdateParams={};frameCallback=e=>this.loop(e);sourceOptions;displayRuntime;static FRAME_LIMIT=120;static FRAME_DURATION=1e3/a.FRAME_LIMIT;static MAX_DELTA_SECONDS=1/30;constructor(e,t,n={}){this.wrapperRef=t,this.timer=new D,this.timer.connect(document),this.sourceOptions={...e},this.displayRuntime={...n};let i=B(e,this.displayRuntime);this.globalInputConfig=i.input,this.id=i.id,this.stages=i.stages||[],this.container=i.container,this.canvas=i.canvas??null,this.resolvedConfig=i,this.loadGameCanvas(i),this.container=this.gameCanvas?.container??this.container,this.inputManager=new k(i.input,{targetElement:this.gameCanvas?.getOverlayContainer(),mouseTargetElement:this.gameCanvas?.container}),this.loadDebugOptions(e),this.setGlobals(e)}setDisplayRuntime(e){this.displayRuntime={...e};let t=B(this.sourceOptions,this.displayRuntime);this.resolvedConfig=t,this.rendererObserver.setConfig(t),this.gameCanvas?.setAspectRatio(t.aspectRatio),this.emitStateDispatch("@game:display-config")}loadGameCanvas(e){this.gameCanvas=new A({id:e.id,container:e.container,containerId:e.containerId,canvas:this.canvas??void 0,bodyBackground:e.bodyBackground,fullscreen:e.fullscreen,aspectRatio:e.aspectRatio}),this.gameCanvas.applyBodyBackground(),this.gameCanvas.mountCanvas(),this.gameCanvas.centerIfFullscreen(),this.rendererObserver.setGameCanvas(this.gameCanvas),this.resolvedConfig&&this.rendererObserver.setConfig(this.resolvedConfig),this.container&&this.rendererObserver.setContainer(this.container),this.subscribeToEventBus()}loadDebugOptions(e){e.debug!==void 0&&(f.enabled=!!e.debug),this.debugDelegate=new V}async loadStage(e,t=0){this.unloadCurrentStage();let n=e.options[0];if(this.loadingDelegate.wireStageLoading(e,t),this.rendererManager||(this.rendererManager=new de,await this.rendererManager.initRenderer()),await e.load(this.id,n?.camera,this.rendererManager),this.stageMap.set(e.wrappedStage.uuid,e),this.currentStageId=e.wrappedStage.uuid,this.defaultCamera=e.wrappedStage.cameraRef,this.rendererObserver.setStage(e.wrappedStage??null),this.rendererManager&&this.rendererObserver.setRendererManager(this.rendererManager),this.applyInputConfig(e),e.onInputConfigChanged=()=>this.applyInputConfig(e),this.hasStarted&&e.wrappedStage&&!e.wrappedStage.hasSetup){let i=this.params(),o={...this.stageSetupParams};o.inputs=i.inputs,o.globals=i.globals,o.camera=i.camera,o.stage=i.stage,o.game=i.game,o.me=e.wrappedStage,e.start(o)}this.emitStateDispatch("@stage:loaded")}applyInputConfig(e){let t=g(this.globalInputConfig??{},e.inputConfig??{});this.inputManager.configure(t)}setGlobalInputConfig(e){this.globalInputConfig=e;let t=this.currentStage();t&&this.applyInputConfig(t)}unloadCurrentStage(){if(!this.currentStageId)return;let e=this.getStage(this.currentStageId);if(e){if(e.onInputConfigChanged=null,e?.wrappedStage){try{e.wrappedStage.nodeDestroy({me:e.wrappedStage,globals:I.globals})}catch(t){console.error("Failed to destroy previous stage",t)}e.wrappedStage=null}e.dispose(),this.stageMap.delete(this.currentStageId),this.currentStageId="",this.defaultCamera=null,this.rendererObserver.reset()}}setGlobals(e){this.initialGlobals={...e.globals};for(let t in this.initialGlobals){let n=this.initialGlobals[t];n===void 0&&console.error(`global ${t} is undefined`),oe(t,n)}}params(){let e=this.currentStage(),t=this.timer.getDelta(),n=this.inputManager.getInputs(t),i=e?.wrappedStage?.cameraRef||this.defaultCamera,o=this.gameUpdateParams;return o.delta=t,o.inputs=n,o.globals=le(),o.me=this,o.camera=i,o.stage=e,o.game=this.wrapperRef,o}start(){let e=this.currentStage(),t=this.params(),n=this.stageSetupParams;n.inputs=t.inputs,n.globals=t.globals,n.camera=t.camera,n.stage=t.stage,n.game=t.game,n.me=e.wrappedStage,e.start(n),this.customSetup&&this.customSetup(t),this.hasStarted=!0,this.loop(0)}step(e){let t=this.currentStage();if(!t||!t.wrappedStage)return;let n=this.params(),i=e!==void 0?e:n.delta,o=Math.min(Math.max(i,0),a.MAX_DELTA_SECONDS);n.delta=o,this.customUpdate&&this.customUpdate(n);let r=this.stageUpdateParams;r.delta=n.delta,r.inputs=n.inputs,r.globals=n.globals,r.camera=n.camera,r.stage=n.stage,r.game=n.game,r.me=t.wrappedStage,t.wrappedStage?.nodeUpdate(r),this.totalTime+=o,I.time=this.totalTime}loop(e){this.debugDelegate?.begin(),pe()||(this.timer.update(e),this.step(),this.previousTimeStamp=e),this.debugDelegate?.end(),this.outOfLoop(),this.isDisposed||(this.animationFrameId=requestAnimationFrame(this.frameCallback))}dispose(){this.isDisposed=!0,this.animationFrameId!==null&&(cancelAnimationFrame(this.animationFrameId),this.animationFrameId=null),this.unloadCurrentStage(),this.debugDelegate&&(this.debugDelegate.dispose(),this.debugDelegate=null),this.eventBusUnsubscribes.forEach(e=>e()),this.eventBusUnsubscribes=[],this.rendererObserver.dispose(),this.inputManager.dispose(),this.rendererManager&&(this.rendererManager.dispose(),this.rendererManager=null),this.timer.dispose(),this.customDestroy&&this.customDestroy({me:this,globals:I.globals}),w()}outOfLoop(){let e=this.currentStage();e&&e.wrappedStage.outOfLoop()}getStage(e){return this.stageMap.get(e)}currentStage(){return this.getStage(this.currentStageId)}onLoading(e){return this.loadingDelegate.onLoading(e)}buildStageConfigPayload(){let e=this.currentStage();if(!e?.wrappedStage)return null;let t=e.wrappedStage.state,n=t.backgroundColor,i=typeof n=="string"?n:`#${n.getHexString()}`;return{id:e.wrappedStage.uuid,backgroundColor:i,backgroundImage:t.backgroundImage,gravity:{x:t.gravity.x,y:t.gravity.y,z:t.gravity.z},inputs:t.inputs,variables:t.variables}}buildEntitiesPayload(){let e=this.currentStage();if(!e?.wrappedStage)return null;let t=[];return e.wrappedStage.entityDelegate.childrenMap.forEach(n=>{let i=n.constructor.type,o=i?String(i).replace("Symbol(","").replace(")",""):"Unknown",r=n.position??{x:0,y:0,z:0},s=n.rotation??{x:0,y:0,z:0},l=n.scale??{x:1,y:1,z:1};t.push({uuid:n.uuid,name:n.name||"Unnamed",type:o,position:{x:r.x??0,y:r.y??0,z:r.z??0},rotation:{x:s.x??0,y:s.y??0,z:s.z??0},scale:{x:l.x??1,y:l.y??1,z:l.z??1}})}),t}emitStateDispatch(e,t,n){let i={scope:"game",path:e,value:t,previousValue:n,config:this.resolvedConfig?{id:this.resolvedConfig.id,aspectRatio:this.resolvedConfig.aspectRatio,fullscreen:this.resolvedConfig.fullscreen,bodyBackground:this.resolvedConfig.bodyBackground,internalResolution:this.resolvedConfig.internalResolution,debug:this.resolvedConfig.debug}:null,stageConfig:this.buildStageConfigPayload(),entities:this.buildEntitiesPayload()};y.emit("state:dispatch",i)}subscribeToEventBus(){this.eventBusUnsubscribes.push(ae.on("game:state:updated",e=>{this.emitStateDispatch(e.path,e.value,e.previousValue)}))}};async function we(a){let{getGameDefaultConfig:e}=await import("./game-default-PZLLHYL7.js"),t={...e()},n=[],i=[],o=[];Object.values(a).forEach(s=>{if(s instanceof M)i.push(s);else if(s instanceof K)o.push(s);else if(s instanceof Z)o.push(s);else if(s?.constructor?.name==="Object"&&typeof s=="object"){let l=Object.assign({...e()},{...s});n.push(l)}}),n.forEach(s=>{t=Object.assign(t,{...s})});let r=t;return r.input=n[0].input,i.forEach(s=>{s.addEntities(o)}),i.length?r.stages=i:r.stages[0].addEntities(o),r}function Ce(a){return!!a.find(t=>t instanceof M)}function te(a){for(let e of a)if(e&&typeof e=="object"&&!(e instanceof M)&&!(e instanceof Z)&&!(e instanceof K)){let t=e;if(t.globals)return t.globals}}import{proxy as yt}from"valtio/vanilla";import{get as vt,set as bt}from"idb-keyval";import{pack as St,unpack as wt}from"msgpackr";var c=yt({previous:null,current:null,next:null,isLoading:!1}),N={staticRegistry:new Map,registerStaticStage(a,e){this.staticRegistry.set(a,e)},async loadStageData(a){try{let e=await vt(a);if(e)return wt(e)}catch(e){console.warn(`Failed to load stage ${a} from storage`,e)}if(this.staticRegistry.has(a))return this.staticRegistry.get(a);throw new Error(`Stage ${a} not found in storage and static loading not fully implemented.`)},async transitionForward(a,e){if(!c.isLoading){c.isLoading=!0;try{c.current&&await bt(c.current.id,St(c.current)),c.previous=c.current,c.current=c.next,c.current?.id!==a&&(e?c.current=await e(a):c.current=await this.loadStageData(a)),c.next=null}catch(t){console.error("Failed to transition stage:",t)}finally{c.isLoading=!1}}},async preloadNext(a,e){e?c.next=await e(a):c.next=await this.loadStageData(a)}};var ne={async createFromBlueprint(a){let e=C({});if(a.entities)for(let t of a.entities)try{let n=await ge.createFromBlueprint(t);e.add(n)}catch(n){console.error(`Failed to create entity ${t.id} for stage ${a.id}`,n)}return e}};var F=class{wrappedGame=null;options;setupCallbacks=[];updateCallbacks=[];destroyCallbacks=[];pendingLoadingCallbacks=[];globalChangeCallbacks=[];globalChangesCallbacks=[];activeGlobalSubscriptions=[];eventDelegate=new me;pendingInputConfig=null;displayRuntime={};refErrorMessage="lost reference to game";constructor(e){this.options=e,Ce(e)||this.options.push(C());let t=te(e);t&&X(t)}onSetup(...e){return this.setupCallbacks.push(...e),this}onUpdate(...e){return this.updateCallbacks.push(...e),this}onDestroy(...e){return this.destroyCallbacks.push(...e),this}setInputConfiguration(...e){let t=g(...e);return this.pendingInputConfig=t,this.wrappedGame&&this.wrappedGame.setGlobalInputConfig(t),this}async start(){w();let e=te(this.options);e&&X(e);let t=await this.load();return this.wrappedGame=t,this.setOverrides(),this.registerGlobalSubscriptions(),t.start(),this}setDisplayRuntime(e){return this.displayRuntime={...this.displayRuntime,...e},this.wrappedGame&&this.wrappedGame.setDisplayRuntime(this.displayRuntime),this}setDeviceProfile(e){return this.setDisplayRuntime({deviceProfile:e})}setViewportSize(e,t){return this.setDisplayRuntime({viewportSize:{width:e,height:t}})}async load(){let e=await we(this.options),t=B(e,this.displayRuntime);this.pendingInputConfig&&(t.input=g(t.input??{},this.pendingInputConfig));let n=new _({...e,...t},this,this.displayRuntime);for(let i of this.pendingLoadingCallbacks)n.onLoading(i);return await n.loadStage(e.stages[0]),n}setOverrides(){if(!this.wrappedGame){console.error(this.refErrorMessage);return}this.wrappedGame.customSetup=e=>{this.setupCallbacks.forEach(t=>t(e))},this.wrappedGame.customUpdate=e=>{this.updateCallbacks.forEach(t=>t(e))},this.wrappedGame.customDestroy=e=>{this.destroyCallbacks.forEach(t=>t(e))}}onGlobalChange(e,t){return this.globalChangeCallbacks.push({path:e,callback:t}),this}onGlobalChanges(e,t){return this.globalChangesCallbacks.push({paths:e,callback:t}),this}registerGlobalSubscriptions(){for(let{path:e,callback:t}of this.globalChangeCallbacks){let n=se(e,i=>{t(i,this.getCurrentStage())});this.activeGlobalSubscriptions.push(n)}for(let{paths:e,callback:t}of this.globalChangesCallbacks){let n=re(e,i=>{t(i,this.getCurrentStage())});this.activeGlobalSubscriptions.push(n)}}getCurrentStage(){return this.wrappedGame?.currentStage()??null}async pause(){Y(!0)}async resume(){Y(!1),this.wrappedGame&&(this.wrappedGame.previousTimeStamp=0,this.wrappedGame.timer.reset())}step(e=1/60){if(!this.wrappedGame){console.error(this.refErrorMessage);return}this.wrappedGame.step(e)}async reset(){if(!this.wrappedGame){console.error(this.refErrorMessage);return}await this.wrappedGame.loadStage(this.wrappedGame.stages[0])}previousStage(){if(!this.wrappedGame){console.error(this.refErrorMessage);return}let e=this.wrappedGame.currentStageId,t=this.wrappedGame.stages.findIndex(i=>i.wrappedStage?.uuid===e),n=this.wrappedGame.stages[t-1];if(!n){console.error("previous stage called on first stage");return}this.wrappedGame.loadStage(n)}async loadStageFromId(e){if(!this.wrappedGame){console.error(this.refErrorMessage);return}try{let t=await N.loadStageData(e),n=await ne.createFromBlueprint(t);await this.wrappedGame.loadStage(n),c.current=t}catch(t){console.error(`Failed to load stage ${e}`,t)}}nextStage(){if(!this.wrappedGame){console.error(this.refErrorMessage);return}if(c.next){console.log("next stage called");let i=c.next.id;if(N.transitionForward(i),c.current){ne.createFromBlueprint(c.current).then(o=>{this.wrappedGame?.loadStage(o)});return}}let e=this.wrappedGame.currentStageId,t=this.wrappedGame.stages.findIndex(i=>i.wrappedStage?.uuid===e),n=this.wrappedGame.stages[t+1];if(!n){console.error("next stage called on last stage");return}this.wrappedGame.loadStage(n)}async goToStage(){}async end(){}dispose(){this.eventDelegate.dispose();for(let e of this.activeGlobalSubscriptions)e();this.activeGlobalSubscriptions=[],this.wrappedGame&&(this.wrappedGame.dispose(),this.wrappedGame=null),ue(),w()}dispatch(e,t){this.eventDelegate.dispatch(e,t),y.emit(e,t)}listen(e,t){return this.eventDelegate.listen(e,t)}onLoading(e){return this.wrappedGame?this.wrappedGame.onLoading(e):(this.pendingLoadingCallbacks.push(e),()=>{this.pendingLoadingCallbacks=this.pendingLoadingCallbacks.filter(t=>t!==e),this.wrappedGame})}};function Ct(...a){return new F(a)}import{Euler as xt,Quaternion as Gt,Vector2 as Rt}from"three";function Tt(a){return{spawn:async(e,t,n)=>{let i=await Promise.resolve(a(t,n));return e.add(i),i},spawnRelative:async(e,t,n=new Rt(0,1))=>{if(!e.body){console.warn("body missing for entity during spawnRelative");return}let{x:i,y:o,z:r}=e.body.translation(),s=e._rotation2DAngle??0;try{let p=e.body.rotation(),S=new Gt(p.x,p.y,p.z,p.w);s=new xt().setFromQuaternion(S,"XYZ").z}catch{}let l=Math.sin(-s)*(n.x??0),u=Math.cos(-s)*(n.y??0),m=await Promise.resolve(a(i+l,o+u));return t.add(m),m}}}import{subscribe as Et}from"valtio/vanilla";var ie="STAGE_STATE_CHANGE";function Bt(){return Et(v,()=>{let a={entities:v.entities,variables:v.variables};window.dispatchEvent(new CustomEvent(ie,{detail:a}))})}function It(){let a={entities:v.entities,variables:v.variables};window.dispatchEvent(new CustomEvent(ie,{detail:a}))}import{MathUtils as Mt,Vector3 as Pt}from"three";var xe={targetKey:"primary",offset:new Pt(0,0,0),lerpFactor:.1};function Lt(a){let e={...xe,...a,offset:J(a?.offset,xe.offset)},t=null;return{priority:0,enabled:!0,onAttach(){t=null},update(n,i){let o=n.targets[e.targetKey];if(!o)return i;let r=o.position.clone().add(e.offset),s=he(i);if(!t)t=r.clone();else{let l=Mt.clamp(e.lerpFactor,0,1),u=1-Math.pow(1-l,n.dt*60);t.lerp(r,u)}return s.position.copy(t),s.lookAt=o.position.clone(),s},onDetach(){t=null}}}import{MeshBasicMaterial as kt}from"three";function Dt(a,e,t){let n=e.cameraRef;if(!n.renderTarget){let r=t?.width??512,s=t?.height??512;n.createRenderTarget(r,s)}let i=n.getRenderTexture();if(!i){console.warn("setCameraFeed: Failed to obtain render texture from camera.");return}if(!a.mesh){console.warn("setCameraFeed: Entity has no mesh to apply the camera feed to.");return}let o=new kt({map:i});a.mesh.material=o}export{E as AspectRatio,Ue as CameraManager,He as CameraPipeline,Xe as CameraWrapper,Ne as FirstPersonPerspective,_e as Fixed2DPerspective,F as Game,Ve as Perspectives,ie as STAGE_STATE_CHANGE,N as StageManager,Oe as ThirdPersonPerspective,Me as VEC2_ONE,Ie as VEC2_ZERO,Le as VEC3_ONE,Pe as VEC3_ZERO,Ye as createCamera,Lt as createFollowTarget,Ct as createGame,Fe as createPerspective,C as createStage,It as dispatchStageState,Tt as entitySpawner,ht as gameConfig,W as getDisplayAspect,j as getPresetResolution,Bt as initStageStateDispatcher,Be as isWebGPUSupported,ke as normalizeVec2,De as normalizeVec3,q as parseResolution,Dt as setCameraFeed,Ze as stageConfig,c as stageState,Ae as toRapierVector3,ze as toThreeVector2,J as toThreeVector3,Je as vessel};
1
+ import{a as b,b as c,c as d,d as e,e as f,f as H,g as I,h as J,i as K,j as L,k as M,l as N,m as O,n as P,o as Q}from"./chunk-3PRBSSTS.js";import{a as g}from"./chunk-7GYFZKK7.js";import"./chunk-COM6HJ2L.js";import{a,c as h,d as i,e as j,f as s,g as t,h as u,i as v,k as w,l as x,m as y,n as z,o as A,p as B,q as C,r as D,s as E,t as F,v as G}from"./chunk-CFVRRRZZ.js";import"./chunk-VS2D4B3W.js";import"./chunk-JQKS42G4.js";import"./chunk-YAOXFYOD.js";import"./chunk-MZZCDXFB.js";import"./chunk-KVSJE4XD.js";import"./chunk-CM5YRNBJ.js";import"./chunk-YHEWKN7N.js";import"./chunk-QXVH6POE.js";import"./chunk-EVYHPR3J.js";import"./chunk-D2PATZCC.js";import"./chunk-4QLJUQSJ.js";import{a as k,b as l,c as m,d as n,g as o,h as p,i as q,j as r}from"./chunk-7WRQ2UAN.js";import"./chunk-BH53MBAZ.js";import"./chunk-XRP4JJXL.js";import"./chunk-PCFF4LLO.js";import"./chunk-UG22Z42P.js";export{b as AspectRatio,B as CameraManager,w as CameraPipeline,C as CameraWrapper,z as FirstPersonPerspective,y as Fixed2DPerspective,J as Game,v as Perspectives,s as RenderBundleManager,t as RenderStrategyManager,M as STAGE_STATE_CHANGE,I as StageManager,x as ThirdPersonPerspective,l as VEC2_ONE,k as VEC2_ZERO,n as VEC3_ONE,m as VEC3_ZERO,D as createCamera,P as createFollowTarget,K as createGame,A as createPerspective,G as createStage,g as crossfadeTransitionShader,O as dispatchStageState,L as entitySpawner,f as gameConfig,c as getDisplayAspect,d as getPresetResolution,N as initStageStateDispatcher,j as isManagedRenderEntity,a as isWebGPUSupported,o as normalizeVec2,p as normalizeVec3,e as parseResolution,h as resolveRenderCategory,Q as setCameraFeed,u as setStageFrameProfilerEnabled,E as stageConfig,H as stageState,q as toThreeVector2,r as toThreeVector3,i as usesManagedRenderPath,F as vessel};
@@ -0,0 +1,17 @@
1
+ import { G as GameEntity } from './entity-BGEq1yfC.js';
2
+
3
+ type DebugTools = 'select' | 'translate' | 'rotate' | 'scale' | 'delete' | 'none';
4
+ interface DebugState {
5
+ enabled: boolean;
6
+ paused: boolean;
7
+ tool: DebugTools;
8
+ selectedEntity: GameEntity<any> | null;
9
+ hoveredEntity: GameEntity<any> | null;
10
+ flags: Set<string>;
11
+ }
12
+ declare const debugState: DebugState;
13
+ declare function setPaused(paused: boolean): void;
14
+ declare function setDebugTool(tool: DebugTools): void;
15
+ declare function setSelectedEntity(entity: GameEntity<any> | null): void;
16
+
17
+ export { type DebugTools as D, setPaused as a, setSelectedEntity as b, debugState as d, setDebugTool as s };
package/dist/debug.d.ts CHANGED
@@ -1,24 +1,76 @@
1
- import { G as GameEntity } from './entity-DNkYKfdp.js';
2
- import 'three';
3
- import '@dimforge/rapier3d-compat';
4
- import './material-Wz83vTTp.js';
5
- import 'three/webgpu';
6
- import './base-node-life-cycle-CnJ-7zX-.js';
1
+ export { D as DebugTools, d as debugState, s as setDebugTool, a as setPaused, b as setSelectedEntity } from './debug-state-DRoeasG2.js';
2
+ import { Object3D, Vector3 } from 'three';
3
+ import { G as GameEntity } from './entity-BGEq1yfC.js';
4
+ import { WebGPURenderer } from 'three/webgpu';
5
+ import '@zylem/behaviors/core';
6
+ import './vector-DN6zlPoE.js';
7
+ import './material-DbSuZBbP.js';
8
+ import './collision-builder-B_tm8OVy.js';
9
+ import './base-node-life-cycle-BK9xebT9.js';
10
+ import './stage-transition-CmGpV4tc.js';
7
11
  import './events.js';
8
12
  import 'mitt';
9
- import '@zylem/behaviors/core';
10
13
 
11
- type DebugTools = 'select' | 'translate' | 'rotate' | 'scale' | 'delete' | 'none';
12
- interface DebugState {
13
- enabled: boolean;
14
- paused: boolean;
15
- tool: DebugTools;
16
- selectedEntity: GameEntity<any> | null;
17
- hoveredEntity: GameEntity<any> | null;
18
- flags: Set<string>;
14
+ /**
15
+ * Context registered by the active stage so the editor can focus entities
16
+ * without importing stage internals.
17
+ */
18
+ interface EntityFocusContext {
19
+ /** Resolve a live entity by UUID from the current stage. */
20
+ resolveEntity(uuid: string): GameEntity<any> | null;
21
+ /** Frame the debug camera on an Object3D (group/mesh). */
22
+ frameObject(object: Object3D): void;
23
+ /** Ensure debugMap / orbit wiring is ready (e.g. enable debug visuals). */
24
+ ensureDebugReady?(): void;
25
+ }
26
+ /**
27
+ * Register the active stage's focus context. Returns an unregister function.
28
+ */
29
+ declare function registerEntityFocusContext(context: EntityFocusContext): () => void;
30
+ /**
31
+ * Select an entity by UUID and frame the debug camera to fit it.
32
+ * Enables debug mode so orbit controls are active.
33
+ *
34
+ * @returns true if the entity was found and framed
35
+ */
36
+ declare function focusEntity(uuid: string): boolean;
37
+
38
+ interface ObjectBounds {
39
+ width: number;
40
+ height: number;
41
+ depth: number;
42
+ center: Vector3;
43
+ maxDim: number;
44
+ }
45
+
46
+ interface EntityThumbnailResult {
47
+ dataUrl: string;
48
+ bounds: Pick<ObjectBounds, 'width' | 'height' | 'depth'>;
49
+ }
50
+ interface EntityThumbnailCacheEntry extends EntityThumbnailResult {
51
+ uuid: string;
52
+ }
53
+ /**
54
+ * Generates and caches entity thumbnail previews for the editor entity list.
55
+ * Renders a cloned Object3D into an offscreen RenderTarget on the shared WebGPU renderer.
56
+ */
57
+ declare class EntityThumbnailCache {
58
+ private cache;
59
+ private inFlight;
60
+ private renderer;
61
+ private size;
62
+ constructor(size?: number);
63
+ setRenderer(renderer: WebGPURenderer | null): void;
64
+ get(uuid: string): EntityThumbnailCacheEntry | null;
65
+ invalidate(uuid: string): void;
66
+ clear(): void;
67
+ /**
68
+ * Return a cached thumbnail or generate one asynchronously.
69
+ */
70
+ ensure(uuid: string, object: Object3D | null | undefined): Promise<EntityThumbnailCacheEntry | null>;
71
+ private render;
19
72
  }
20
- declare const debugState: DebugState;
21
- declare function setPaused(paused: boolean): void;
22
- declare function setDebugTool(tool: DebugTools): void;
73
+ /** Shared cache used by the running game to feed editor entity payloads. */
74
+ declare const entityThumbnailCache: EntityThumbnailCache;
23
75
 
24
- export { type DebugTools, debugState, setDebugTool, setPaused };
76
+ export { type EntityFocusContext, EntityThumbnailCache, type EntityThumbnailCacheEntry, type EntityThumbnailResult, entityThumbnailCache, focusEntity, registerEntityFocusContext };
package/dist/debug.js CHANGED
@@ -1 +1 @@
1
- import{a as e,c as o,e as t}from"./chunk-CDPY4VOQ.js";export{e as debugState,t as setDebugTool,o as setPaused};
1
+ import"./chunk-DFLI7ICU.js";import{a as e,b as f}from"./chunk-COM6HJ2L.js";import{c as g,d as h}from"./chunk-VS2D4B3W.js";import{a,c as b,e as c,f as d}from"./chunk-JQKS42G4.js";export{e as EntityThumbnailCache,a as debugState,f as entityThumbnailCache,h as focusEntity,g as registerEntityFocusContext,c as setDebugTool,b as setPaused,d as setSelectedEntity};
@@ -1,5 +1,5 @@
1
- import { I as InputPlayer } from './base-node-life-cycle-CnJ-7zX-.js';
2
- import { a as VirtualTouchButtonSlot, V as VirtualTouchConfig, G as GameInputConfig } from './game-interfaces-tfpM5NBk.js';
1
+ import { b as InputPlayer } from './base-node-life-cycle-BK9xebT9.js';
2
+ import { d as VirtualTouchButtonSlot, e as VirtualTouchConfig, G as GameInputConfig } from './game-interfaces-vF5sRi1n.js';
3
3
 
4
4
  /**
5
5
  * Color tokens consumed by the SVG factories in `svg-assets.ts` and the
@@ -108,4 +108,4 @@ interface DefaultTouchControlsOptions {
108
108
  */
109
109
  declare function defaultTouchControls(player?: InputPlayer, options?: DefaultTouchControlsOptions): GameInputConfig;
110
110
 
111
- export { type DefaultTouchControlsOptions as D, type JoystickSelection as J, type TouchTheme as T, type TouchThemeName as a, resolveButtonAccent as b, defaultTouchControls as d, resolveTouchTheme as r, touchThemes as t };
111
+ export { type DefaultTouchControlsOptions as D, type JoystickSelection as J, type TouchTheme as T, resolveButtonAccent as a, type TouchThemeName as b, defaultTouchControls as d, resolveTouchTheme as r, touchThemes as t };
@@ -0,0 +1,34 @@
1
+ import { Group, Mesh } from 'three';
2
+ import { l as SimulationBody } from './vector-DN6zlPoE.js';
3
+
4
+ type LifecycleFunction<T> = (params?: any) => void;
5
+ interface Entity<T = any> {
6
+ setup: (entity: T) => void;
7
+ destroy: () => void;
8
+ update: LifecycleFunction<T>;
9
+ type: string;
10
+ _collision?: (entity: any, other: any, globals?: any) => void;
11
+ _destroy?: (globals?: any) => void;
12
+ name?: string;
13
+ tag?: Set<string>;
14
+ }
15
+ interface StageEntity extends Entity {
16
+ uuid: string;
17
+ body: SimulationBody;
18
+ group: Group;
19
+ mesh: Mesh;
20
+ instanceId: number;
21
+ isInstanced?: boolean;
22
+ isBundled?: boolean;
23
+ /**
24
+ * When true, `syncRenderPoses` leaves the entity's Three.js transform alone.
25
+ * Used for camera-parented viewmodels so physics pose sync cannot overwrite
26
+ * the local offset.
27
+ */
28
+ skipRenderPoseSync?: boolean;
29
+ controlledRotation: boolean;
30
+ name: string;
31
+ markedForRemoval: boolean;
32
+ }
33
+
34
+ export type { Entity as E, LifecycleFunction as L, StageEntity as S };