@zylem/game-lib 0.8.8 → 0.8.9

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 (64) hide show
  1. package/LICENSE +21 -0
  2. package/dist/actions.d.ts +2 -2
  3. package/dist/actions.js +1 -1
  4. package/dist/api/game-lib.api.json +794 -175
  5. package/dist/api/game-lib.api.md +63 -11
  6. package/dist/api/game-lib.d.ts +180 -5
  7. package/dist/api/game-lib.typedoc.json +157334 -208944
  8. package/dist/audio.js +1 -1
  9. package/dist/behavior.js +1 -1
  10. package/dist/bridge.d.ts +31 -6
  11. package/dist/bridge.js +1 -1
  12. package/dist/catalog.d.ts +91 -3
  13. package/dist/catalog.js +1 -1
  14. package/dist/chunk-2HSR5XDQ.js +1 -0
  15. package/dist/{chunk-7NYP4YAG.js → chunk-6FGXC4T6.js} +1 -1
  16. package/dist/chunk-6XFXPIVB.js +1 -0
  17. package/dist/{chunk-YOVE25NW.js → chunk-7JSZEEAE.js} +1 -1
  18. package/dist/chunk-AXJTUVGC.js +24 -0
  19. package/dist/chunk-BWOZF5YK.js +1 -0
  20. package/dist/chunk-EYDC2PMO.js +1 -0
  21. package/dist/chunk-G3TBBZUI.js +1 -0
  22. package/dist/chunk-J6KD2G6F.js +1 -0
  23. package/dist/chunk-KP6DLLJO.js +1 -0
  24. package/dist/chunk-VUJXR5K5.js +1 -0
  25. package/dist/chunk-WOT6VMZA.js +1 -0
  26. package/dist/{chunk-BMRFDDMR.js → chunk-X7T7QRYP.js} +1 -1
  27. package/dist/chunk-YQS7CGXE.js +1 -0
  28. package/dist/{chunk-GHJQ2HKI.js → chunk-YVWDCZNT.js} +1 -1
  29. package/dist/core.d.ts +4 -4
  30. package/dist/core.js +1 -1
  31. package/dist/{debug-state-CpnNRUFh.d.ts → debug-state-Cg3f5FB6.d.ts} +1 -1
  32. package/dist/debug.d.ts +2 -2
  33. package/dist/debug.js +1 -1
  34. package/dist/{entity-XZNGBeca.d.ts → entity-XqvuWgPm.d.ts} +54 -0
  35. package/dist/{entity-type-map-CkkFMSrL.d.ts → entity-type-map-D6BeAdvg.d.ts} +1 -1
  36. package/dist/entity.d.ts +3 -3
  37. package/dist/entity.js +1 -1
  38. package/dist/events.js +1 -1
  39. package/dist/{game-BPOr7zTB.d.ts → game-DyKbOeck.d.ts} +74 -7
  40. package/dist/game-default-6YXFFZ2Q.js +1 -0
  41. package/dist/globals.js +1 -1
  42. package/dist/graphics.js +1 -1
  43. package/dist/input-ui.js +1 -1
  44. package/dist/input.js +1 -1
  45. package/dist/public.d.ts +6 -6
  46. package/dist/public.js +1 -1
  47. package/dist/runtime.js +1 -1
  48. package/dist/schema/entity.schema.json +24 -24
  49. package/dist/schema/game-config.schema.json +10 -10
  50. package/dist/schema/stage.schema.json +29 -29
  51. package/dist/schema.js +1 -1
  52. package/dist/web-components.d.ts +4 -4
  53. package/dist/web-components.js +1 -1
  54. package/package.json +28 -27
  55. package/dist/chunk-AE3CTVHY.js +0 -1
  56. package/dist/chunk-F5LROYZL.js +0 -24
  57. package/dist/chunk-HNCTOJP7.js +0 -1
  58. package/dist/chunk-IBJLPJLE.js +0 -1
  59. package/dist/chunk-MXO4VGDB.js +0 -1
  60. package/dist/chunk-QDQ4QMAI.js +0 -1
  61. package/dist/chunk-SAQA4SXW.js +0 -1
  62. package/dist/chunk-XK63E4SX.js +0 -1
  63. package/dist/chunk-ZTYNZ2N2.js +0 -1
  64. package/dist/game-default-7HCJJF5S.js +0 -1
package/dist/audio.js CHANGED
@@ -1 +1 @@
1
- import{a,b,c}from"./chunk-ZRT3ZQVH.js";export{c as Howl,b as pingPongBeep,a as ricochetSound};
1
+ import{a,b,c}from"./chunk-ZRT3ZQVH.js";import"./chunk-WOT6VMZA.js";export{c as Howl,b as pingPongBeep,a as ricochetSound};
package/dist/behavior.js CHANGED
@@ -1 +1 @@
1
- import{$,$a,A,Aa,B,Ba,C,Ca,D,Da,E,Ea,F,Fa,G,Ga,H,Ha,I,Ia,J,Ja,K,Ka,L,La,M,Ma,N,Na,O,Oa,P,Pa,Q,Qa,R,Ra,S,Sa,T,Ta,U,Ua,V,Va,W,Wa,X,Xa,Y,Ya,Z,Za,_,_a,a,aa,ab,b,ba,bb,c,ca,cb,d,da,db,e,ea,eb,f,fa,fb,g,ga,gb,h,ha,hb,i,ia,ib,j,ja,k,ka,l,la,m,ma,n,na,o,oa,p,pa,q,qa,r,ra,s,sa,t,ta,u,ua,v,va,w,wa,x,xa,y,ya,z,za}from"./chunk-XK63E4SX.js";export{a as BoundaryRicochet3DCoordinator,b as BoundaryRicochetCoordinator,c as CooldownBehavior,d as Destructible3DBehavior,e as DestructibleMesh,f as FirstPersonBehavior,g as FirstPersonEvent,h as FirstPersonFSM,k as FirstPersonPresentation,i as FirstPersonShooterCoordinator,j as FirstPersonState,l as FractureOptions,m as Jumper2DBehavior,n as Jumper2DEvent,o as Jumper2DFSM,p as Jumper2DState,q as Jumper3DBehavior,r as Jumper3DEvent,s as Jumper3DFSM,t as Jumper3DState,u as MultidirectionalSpaceShooterCoordinator,v as ParticleEmitterBehavior,w as Platformer2DBehavior,x as Platformer2DEvent,y as Platformer2DFSM,z as Platformer2DState,A as Platformer3DBehavior,B as Platformer3DEvent,C as Platformer3DFSM,D as Platformer3DState,$a as RUNTIME_BOUNDARY_2D_BEHAVIOR_KEY,ab as RUNTIME_DYNAMIC_CIRCLE_BODY_2D_BEHAVIOR_KEY,bb as RUNTIME_GOAL_ZONE_2D_BEHAVIOR_KEY,cb as RUNTIME_PLAYER_INPUT_2D_BEHAVIOR_KEY,db as RUNTIME_RICOCHET_2D_BEHAVIOR_KEY,eb as RUNTIME_TRIGGER_REGION_2D_BEHAVIOR_KEY,E as Ricochet2DBehavior,F as Ricochet2DEvent,G as Ricochet2DFSM,H as Ricochet2DState,I as Ricochet3DBehavior,J as Ricochet3DEvent,K as Ricochet3DFSM,L as Ricochet3DState,Va as RuntimeBoundary2DBehavior,Wa as RuntimeDynamicCircleBody2DBehavior,Xa as RuntimeGoalZone2DBehavior,Ya as RuntimePlayerInput2DBehavior,Za as RuntimeRicochet2DBehavior,_a as RuntimeTriggerRegion2DBehavior,M as ScreenVisibilityBehavior,N as ScreenVisibilityFSM,O as ScreenWrapBehavior,P as ScreenWrapEvent,Q as ScreenWrapFSM,R as ScreenWrapState,S as Shooter2DBehavior,T as ThrusterBehavior,U as ThrusterEvent,V as ThrusterFSM,W as ThrusterState,X as TopDownMovementBehavior,Y as TopDownShooterCoordinator,Z as WorldBoundary2DBehavior,_ as WorldBoundary2DEvent,$ as WorldBoundary2DFSM,aa as WorldBoundary2DState,ba as WorldBoundary3DBehavior,ca as WorldBoundary3DEvent,da as WorldBoundary3DFSM,ea as WorldBoundary3DState,fb as bindRuntimeDynamicCircleBody2DHandle,fa as computeWorldBoundary2DHits,ga as computeWorldBoundary3DHits,ha as createFirstPersonInputComponent,ia as createFirstPersonMovementComponent,ja as createFirstPersonStateComponent,ka as createJumpConfig2D,la as createJumpConfig3D,ma as createJumpInput2D,na as createJumpInput3D,oa as createJumpState2D,pa as createJumpState3D,qa as createPhysicsBodyComponent,ra as createPlatformer2DInputComponent,sa as createPlatformer2DMovementComponent,ta as createPlatformer2DStateComponent,ua as createPlatformer3DInputComponent,va as createPlatformer3DMovementComponent,wa as createPlatformer3DStateComponent,xa as createShooter2DStateComponent,ya as createThrusterInputComponent,za as createThrusterMovementComponent,Aa as createThrusterStateComponent,Ba as createTopDownMovementComponent,Ca as createTopDownMovementInputComponent,Da as createTopDownMovementStateComponent,Ea as createTransformComponent,Fa as defineBehavior,gb as emitRuntimeGoal,hb as emitRuntimeRicochet,ib as emitRuntimeTriggerRegionEnter,Ga as fireCooldown,Ha as fireShooter2DIfRequested,Ia as getCooldown,Ja as getCooldownStore,Ka as getEntityFacingAngle2D,La as hasAnyWorldBoundary2DHit,Ma as hasAnyWorldBoundary3DHit,Na as particleEffect,Oa as particlePresets,Pa as registerCooldown,Qa as resetCooldown,Ra as resolveAim2D,Sa as tickCooldowns,Ta as updateBoundaryRicochet,Ua as useBehavior};
1
+ import{a as Va,b as Wa,c as Xa,d as Ya,e as Za,f as _a,g as $a,h as ab,i as bb,j as cb,k as db,l as eb,m as fb,n as gb,o as hb,p as ib}from"./chunk-6XFXPIVB.js";import{$ as _,A as z,Aa as za,B as A,Ba as Aa,C as B,Ca as Ba,D as C,Da as Ca,E as D,Ea as Da,F as E,Fa as Ea,G as F,Ga as Fa,H as G,Ha as Ga,I as H,Ia as Ha,J as I,Ja as Ia,K as J,Ka as Ja,L as K,La as Ka,M as L,Ma as La,N as M,Na as Ma,O as N,Oa as Na,P as O,Pa as Oa,Q as P,Qa as Pa,R as Q,Ra as Qa,S as R,Sa as Ra,T as S,Ta as Sa,U as T,Ua as Ta,V as U,Va as Ua,W as V,X as W,Y as X,Z as Y,_ as Z,aa as $,b as a,ba as aa,c as b,ca as ba,d as c,da as ca,e as d,ea as da,f as e,fa as ea,g as f,ga as fa,h as g,ha as ga,i as h,ia as ha,j as i,ja as ia,k as j,ka as ja,l as k,la as ka,m as l,ma as la,n as m,na as ma,o as n,oa as na,p as o,pa as oa,q as p,qa as pa,r as q,ra as qa,s as r,sa as ra,t as s,ta as sa,u as t,ua as ta,v as u,va as ua,w as v,wa as va,x as w,xa as wa,y as x,ya as xa,z as y,za as ya}from"./chunk-VUJXR5K5.js";import"./chunk-WOT6VMZA.js";export{a as BoundaryRicochet3DCoordinator,b as BoundaryRicochetCoordinator,c as CooldownBehavior,d as Destructible3DBehavior,e as DestructibleMesh,f as FirstPersonBehavior,g as FirstPersonEvent,h as FirstPersonFSM,k as FirstPersonPresentation,i as FirstPersonShooterCoordinator,j as FirstPersonState,l as FractureOptions,m as Jumper2DBehavior,n as Jumper2DEvent,o as Jumper2DFSM,p as Jumper2DState,q as Jumper3DBehavior,r as Jumper3DEvent,s as Jumper3DFSM,t as Jumper3DState,u as MultidirectionalSpaceShooterCoordinator,v as ParticleEmitterBehavior,w as Platformer2DBehavior,x as Platformer2DEvent,y as Platformer2DFSM,z as Platformer2DState,A as Platformer3DBehavior,B as Platformer3DEvent,C as Platformer3DFSM,D as Platformer3DState,$a as RUNTIME_BOUNDARY_2D_BEHAVIOR_KEY,ab as RUNTIME_DYNAMIC_CIRCLE_BODY_2D_BEHAVIOR_KEY,bb as RUNTIME_GOAL_ZONE_2D_BEHAVIOR_KEY,cb as RUNTIME_PLAYER_INPUT_2D_BEHAVIOR_KEY,db as RUNTIME_RICOCHET_2D_BEHAVIOR_KEY,eb as RUNTIME_TRIGGER_REGION_2D_BEHAVIOR_KEY,E as Ricochet2DBehavior,F as Ricochet2DEvent,G as Ricochet2DFSM,H as Ricochet2DState,I as Ricochet3DBehavior,J as Ricochet3DEvent,K as Ricochet3DFSM,L as Ricochet3DState,Va as RuntimeBoundary2DBehavior,Wa as RuntimeDynamicCircleBody2DBehavior,Xa as RuntimeGoalZone2DBehavior,Ya as RuntimePlayerInput2DBehavior,Za as RuntimeRicochet2DBehavior,_a as RuntimeTriggerRegion2DBehavior,M as ScreenVisibilityBehavior,N as ScreenVisibilityFSM,O as ScreenWrapBehavior,P as ScreenWrapEvent,Q as ScreenWrapFSM,R as ScreenWrapState,S as Shooter2DBehavior,T as ThrusterBehavior,U as ThrusterEvent,V as ThrusterFSM,W as ThrusterState,X as TopDownMovementBehavior,Y as TopDownShooterCoordinator,Z as WorldBoundary2DBehavior,_ as WorldBoundary2DEvent,$ as WorldBoundary2DFSM,aa as WorldBoundary2DState,ba as WorldBoundary3DBehavior,ca as WorldBoundary3DEvent,da as WorldBoundary3DFSM,ea as WorldBoundary3DState,fb as bindRuntimeDynamicCircleBody2DHandle,fa as computeWorldBoundary2DHits,ga as computeWorldBoundary3DHits,ha as createFirstPersonInputComponent,ia as createFirstPersonMovementComponent,ja as createFirstPersonStateComponent,ka as createJumpConfig2D,la as createJumpConfig3D,ma as createJumpInput2D,na as createJumpInput3D,oa as createJumpState2D,pa as createJumpState3D,qa as createPhysicsBodyComponent,ra as createPlatformer2DInputComponent,sa as createPlatformer2DMovementComponent,ta as createPlatformer2DStateComponent,ua as createPlatformer3DInputComponent,va as createPlatformer3DMovementComponent,wa as createPlatformer3DStateComponent,xa as createShooter2DStateComponent,ya as createThrusterInputComponent,za as createThrusterMovementComponent,Aa as createThrusterStateComponent,Ba as createTopDownMovementComponent,Ca as createTopDownMovementInputComponent,Da as createTopDownMovementStateComponent,Ea as createTransformComponent,Fa as defineBehavior,gb as emitRuntimeGoal,hb as emitRuntimeRicochet,ib as emitRuntimeTriggerRegionEnter,Ga as fireCooldown,Ha as fireShooter2DIfRequested,Ia as getCooldown,Ja as getCooldownStore,Ka as getEntityFacingAngle2D,La as hasAnyWorldBoundary2DHit,Ma as hasAnyWorldBoundary3DHit,Na as particleEffect,Oa as particlePresets,Pa as registerCooldown,Qa as resetCooldown,Ra as resolveAim2D,Sa as tickCooldowns,Ta as updateBoundaryRicochet,Ua as useBehavior};
package/dist/bridge.d.ts CHANGED
@@ -1,6 +1,6 @@
1
- import { BridgePose, SceneOperationPayload, EntityApplySwatchPayload, GameConfigPayload, GameLoadingPayload, GameVariablePayload, GameNoticePayload, StageSnapshotPayload, EntitySummaryPayload, EntityThumbnailPayload, EntityTypeDescriptor } from '@zylem/bridge';
2
- export { BRIDGE_READY_EVENT, BridgeChannel, BridgeDebugTool, BridgeHandler, GameLoadingPayload as BridgeLoadingPayload, BridgeMessageType, BridgeMessages, BridgeVec3, EditorToGameMessages, EntityApplySwatchPayload, EntitySummaryPayload, EntityThumbnailPayload, GameConfigPayload, GameToEditorMessages, GameVariablePayload, StageConfigPayload, StageSnapshotPayload, ZylemBridge, announceBridgeReady, getZylemBridge } from '@zylem/bridge';
3
- import { G as GameEntity } from './entity-XZNGBeca.js';
1
+ import { BridgePose, SceneOperationPayload, BridgeNdc, EntitySummaryPayload, EntityApplySwatchPayload, SwatchApplyResult, SceneOperationEntry, GameConfigPayload, GameLoadingPayload, GameVariablePayload, GameNoticePayload, StageSnapshotPayload, EntityThumbnailPayload, EntityTypeDescriptor } from '@zylem/bridge';
2
+ export { BRIDGE_READY_EVENT, BridgeChannel, BridgeDebugTool, BridgeHandler, GameLoadingPayload as BridgeLoadingPayload, BridgeMessageType, BridgeMessages, BridgeNdc, BridgeVec3, EditorToGameMessages, EntityApplySwatchPayload, EntityPickPayload, EntityPickResultPayload, EntitySummaryPayload, EntitySwatchAppliedPayload, EntityThumbnailPayload, GameConfigPayload, GameToEditorMessages, GameVariablePayload, StageConfigPayload, StageSnapshotPayload, SwatchApplyFailureReason, SwatchApplyResult, SwatchKind, SwatchSpec, ZylemBridge, announceBridgeReady, applySwatchesToSelection, getZylemBridge } from '@zylem/bridge';
3
+ import { G as GameEntity } from './entity-XqvuWgPm.js';
4
4
  import 'three';
5
5
  import '@zylem/behaviors/core';
6
6
  import './simulation-body-zQw-emOr.js';
@@ -38,8 +38,24 @@ interface GameBridgeHost {
38
38
  createEntity?(typeId: string, props: Record<string, unknown> | undefined, pose: BridgePose | undefined): void;
39
39
  /** Undo or redo a committed scene operation (`scene:operation:apply`). */
40
40
  applySceneOperation?(op: SceneOperationPayload, direction: 'undo' | 'redo'): void;
41
- /** Attach a catalog shader or behavior to a live entity (`entity:apply-swatch`). */
42
- applySwatch?(payload: EntityApplySwatchPayload): void;
41
+ /**
42
+ * Raycast at normalized device coordinates and describe the entity hit
43
+ * (`entity:pick`). Hover should follow the pick only while pick mode is on.
44
+ */
45
+ pickEntity?(ndc: BridgeNdc): EntitySummaryPayload | null;
46
+ /**
47
+ * Apply every swatch to every uuid (`entity:apply-swatch`). Must report one
48
+ * result per uuid × swatch pair and return a `scene:operation` entry for
49
+ * each success so the batch is undoable as a single step.
50
+ */
51
+ applySwatches?(payload: EntityApplySwatchPayload & {
52
+ opId: string;
53
+ }): SwatchApplyOutcome;
54
+ }
55
+ /** What a host reports back from a swatch batch. */
56
+ interface SwatchApplyOutcome {
57
+ results: SwatchApplyResult[];
58
+ entries: SceneOperationEntry[];
43
59
  }
44
60
  declare class GameBridge {
45
61
  private channel;
@@ -64,6 +80,15 @@ declare class GameBridge {
64
80
  */
65
81
  connect(host: GameBridgeHost, announceTarget?: EventTarget): void;
66
82
  disconnect(): void;
83
+ /**
84
+ * Run a swatch batch and report back.
85
+ *
86
+ * Order matters for the consumer: selection changes first (so a following
87
+ * `entity:selection` describes the new targets), then the undo record, then
88
+ * the ack — a consumer that persists on `ok` sees the operation already on
89
+ * the stack.
90
+ */
91
+ private handleApplySwatch;
67
92
  /**
68
93
  * Publish only the parts of `debugState` the editor does not already know.
69
94
  * Values that arrived as editor commands are recorded on `editorKnown`
@@ -132,4 +157,4 @@ declare class GameBridge {
132
157
  wantsSceneOperations(): boolean;
133
158
  }
134
159
 
135
- export { GameBridge, type GameBridgeHost };
160
+ export { GameBridge, type GameBridgeHost, type SwatchApplyOutcome };
package/dist/bridge.js CHANGED
@@ -1 +1 @@
1
- import{a as b,b as c,c as d}from"./chunk-HNCTOJP7.js";import{f as a}from"./chunk-ZTYNZ2N2.js";import"./chunk-CBUQBP2U.js";import"./chunk-EVMLNMGU.js";export{d as BRIDGE_READY_EVENT,a as GameBridge,c as announceBridgeReady,b as getZylemBridge};
1
+ import{a as b,b as c,c as d,d as e}from"./chunk-J6KD2G6F.js";import{g as a}from"./chunk-G3TBBZUI.js";import"./chunk-CBUQBP2U.js";import"./chunk-EVMLNMGU.js";import"./chunk-WOT6VMZA.js";export{e as BRIDGE_READY_EVENT,a as GameBridge,c as announceBridgeReady,d as applySwatchesToSelection,b as getZylemBridge};
package/dist/catalog.d.ts CHANGED
@@ -1,10 +1,13 @@
1
- import { EntityTypeDescriptor } from '@zylem/bridge';
2
- export { EntityTypeDescriptor } from '@zylem/bridge';
1
+ import { EntityTypeDescriptor, SwatchKind } from '@zylem/bridge';
2
+ export { EntityTypeDescriptor, SwatchKind, SwatchSpec } from '@zylem/bridge';
3
3
  import { B as BaseNode } from './base-node-idopiSw5.js';
4
4
  import { c as Vec3 } from './vector-D3eDzvcA.js';
5
+ import { BehaviorDescriptor } from '@zylem/behaviors/core';
6
+ import { d as ZylemShader } from './material-CxxAyJYp.js';
5
7
  import './base-node-life-cycle-BK9xebT9.js';
6
8
  import 'three';
7
9
  import './stage-transition-CmGpV4tc.js';
10
+ import 'three/webgpu';
8
11
 
9
12
  /**
10
13
  * Runtime registry of placeable entity types, backing the editor's Add palette.
@@ -74,4 +77,89 @@ declare const BUILT_IN_ENTITY_TYPES: EntityTypeRegistration[];
74
77
  */
75
78
  declare function registerBuiltInEntityTypes(): () => void;
76
79
 
77
- export { BUILT_IN_ENTITY_TYPES, type EntityPlacementContext, type EntityTypeFactory, type EntityTypeRegistration, buildCatalogDescriptors, clearEntityRegistry, getEntityType, listEntityTypes, onEntityRegistryChanged, registerBuiltInEntityTypes, registerEntityType, registerEntityTypes };
80
+ /**
81
+ * Runtime registry of swatch sources: the shader factories and behavior
82
+ * descriptors that `entity:apply-swatch` messages can name.
83
+ *
84
+ * A swatch crosses the bridge as `{ kind, source, props }` where `source` is an
85
+ * export name such as `createLava` or `ThrusterBehavior`. game-lib does not
86
+ * depend on `@zylem/shaders`, and behaviors are keyed by symbol rather than
87
+ * string, so this map is how a bare name resolves back to something callable.
88
+ * Hosts fill it at boot (typically by walking the module namespaces they
89
+ * already import, see {@link registerSwatchSourcesFromModule}); game-lib
90
+ * pre-registers its own re-exported behaviors via
91
+ * {@link registerBuiltInBehaviorSwatchSources}.
92
+ *
93
+ * Mirrors `entity-registry.ts`: the factory stays on this side of the bridge
94
+ * and only serializable identifiers cross it.
95
+ */
96
+
97
+ /** A shader factory: turns catalog props into a `ZylemShader`. */
98
+ type SwatchShaderFactory = (props: Record<string, unknown>) => ZylemShader;
99
+ interface ShaderSwatchSource {
100
+ kind: 'shader';
101
+ /** Export name, e.g. `createLava`. */
102
+ id: string;
103
+ create: SwatchShaderFactory;
104
+ }
105
+ interface BehaviorSwatchSource {
106
+ kind: 'behavior';
107
+ /** Export name, e.g. `ThrusterBehavior`. */
108
+ id: string;
109
+ descriptor: BehaviorDescriptor<any, any>;
110
+ }
111
+ type SwatchSource = ShaderSwatchSource | BehaviorSwatchSource;
112
+ /**
113
+ * Register one swatch source, replacing any existing source of the same kind
114
+ * and id so a host can override a built-in.
115
+ *
116
+ * @returns An unregister function.
117
+ */
118
+ declare function registerSwatchSource(source: SwatchSource): () => void;
119
+ /** Register several sources at once, notifying listeners only after all of them. */
120
+ declare function registerSwatchSources(sources: SwatchSource[]): () => void;
121
+ declare function getSwatchSource(kind: 'shader', id: string): ShaderSwatchSource | null;
122
+ declare function getSwatchSource(kind: 'behavior', id: string): BehaviorSwatchSource | null;
123
+ declare function getSwatchSource(kind: SwatchKind, id: string): SwatchSource | null;
124
+ /** Every registered source, shaders first, in registration order. */
125
+ declare function listSwatchSources(kind?: SwatchKind): SwatchSource[];
126
+ /**
127
+ * Observe registry changes.
128
+ *
129
+ * @returns An unsubscribe function.
130
+ */
131
+ declare function onSwatchRegistryChanged(listener: () => void): () => void;
132
+ /** Test hook: drop every registration. */
133
+ declare function clearSwatchRegistry(): void;
134
+ /** Structural check for a `defineBehavior` descriptor. */
135
+ declare function isBehaviorDescriptor(value: unknown): value is BehaviorDescriptor<any, any>;
136
+ /**
137
+ * Register every plausible source found on a module namespace object.
138
+ *
139
+ * - `kind: 'behavior'`: every export that is a behavior descriptor.
140
+ * - `kind: 'shader'`: every function export; with `filter` a host can narrow
141
+ * this to, say, names starting with `create`.
142
+ *
143
+ * Export names become source ids, which is what makes the live path agree with
144
+ * generated code that imports the same names.
145
+ *
146
+ * @returns An unregister function for everything this call registered.
147
+ */
148
+ declare function registerSwatchSourcesFromModule(kind: SwatchKind, module: Record<string, unknown>, filter?: (exportName: string, value: unknown) => boolean): () => void;
149
+
150
+ /**
151
+ * Built-in swatch sources: every behavior descriptor game-lib re-exports from
152
+ * `@zylem/game-lib/behavior`, registered under its export name.
153
+ *
154
+ * Kept apart from `swatch-registry.ts` so the registry module does not pull the
155
+ * whole behavior barrel into every bundle; only games that call this (the
156
+ * `ZylemGame` constructor does) pay for it. Shaders are not built in — game-lib
157
+ * does not depend on `@zylem/shaders` — so hosts register those themselves.
158
+ */
159
+ /**
160
+ * Register the built-in behavior descriptors as swatch sources. Idempotent, so
161
+ * a second game on the page does not re-register them.
162
+ */
163
+ declare function registerBuiltInBehaviorSwatchSources(): () => void;
164
+
165
+ export { BUILT_IN_ENTITY_TYPES, type BehaviorSwatchSource, type EntityPlacementContext, type EntityTypeFactory, type EntityTypeRegistration, type ShaderSwatchSource, type SwatchShaderFactory, type SwatchSource, buildCatalogDescriptors, clearEntityRegistry, clearSwatchRegistry, getEntityType, getSwatchSource, isBehaviorDescriptor, listEntityTypes, listSwatchSources, onEntityRegistryChanged, onSwatchRegistryChanged, registerBuiltInBehaviorSwatchSources, registerBuiltInEntityTypes, registerEntityType, registerEntityTypes, registerSwatchSource, registerSwatchSources, registerSwatchSourcesFromModule };
package/dist/catalog.js CHANGED
@@ -1 +1 @@
1
- import{a as o,b as s}from"./chunk-QDQ4QMAI.js";import{a as t,b as e,c as y,d as i,e as r,f as n,g as p}from"./chunk-AE3CTVHY.js";import"./chunk-BMRFDDMR.js";import"./chunk-SAQA4SXW.js";import"./chunk-7NYP4YAG.js";import"./chunk-AIQ6IVT5.js";import"./chunk-QXVH6POE.js";import"./chunk-EVYHPR3J.js";import"./chunk-4QLJUQSJ.js";import"./chunk-7WRQ2UAN.js";import"./chunk-XRP4JJXL.js";export{o as BUILT_IN_ENTITY_TYPES,r as buildCatalogDescriptors,p as clearEntityRegistry,y as getEntityType,i as listEntityTypes,n as onEntityRegistryChanged,s as registerBuiltInEntityTypes,t as registerEntityType,e as registerEntityTypes};
1
+ import{a,b as S,c as T}from"./chunk-EYDC2PMO.js";import{a as t,b as e,c as r,d as i,e as o,f as y,g as c,h as s,i as p,j as h,k as n,l as g,m as w,n as u,o as E}from"./chunk-2HSR5XDQ.js";import"./chunk-X7T7QRYP.js";import"./chunk-KP6DLLJO.js";import"./chunk-6FGXC4T6.js";import"./chunk-AIQ6IVT5.js";import"./chunk-QXVH6POE.js";import"./chunk-EVYHPR3J.js";import"./chunk-VUJXR5K5.js";import"./chunk-4QLJUQSJ.js";import"./chunk-7WRQ2UAN.js";import"./chunk-XRP4JJXL.js";import"./chunk-WOT6VMZA.js";export{a as BUILT_IN_ENTITY_TYPES,o as buildCatalogDescriptors,c as clearEntityRegistry,w as clearSwatchRegistry,r as getEntityType,h as getSwatchSource,u as isBehaviorDescriptor,i as listEntityTypes,n as listSwatchSources,y as onEntityRegistryChanged,g as onSwatchRegistryChanged,T as registerBuiltInBehaviorSwatchSources,S as registerBuiltInEntityTypes,t as registerEntityType,e as registerEntityTypes,s as registerSwatchSource,p as registerSwatchSources,E as registerSwatchSourcesFromModule};
@@ -0,0 +1 @@
1
+ var o=new Map,d=new Set;function n(){for(let e of d)try{e()}catch(t){console.error("[zylem] entity registry listener failed",t)}}function S(e){return o.set(e.id,e),n(),()=>{o.get(e.id)===e&&(o.delete(e.id),n())}}function l(e){for(let t of e)o.set(t.id,t);return n(),()=>{for(let t of e)o.get(t.id)===t&&o.delete(t.id);n()}}function g(e){return o.get(e)??null}function y(){return[...o.values()]}function w(){return y().map(({create:e,...t})=>t)}function v(e){return d.add(e),()=>d.delete(e)}function x(){o.clear(),n()}var r={shader:new Map,behavior:new Map},p=new Set;function c(){for(let e of p)try{e()}catch(t){console.error("[zylem] swatch registry listener failed",t)}}function E(e){return r[e.kind].set(e.id,e),c(),()=>{r[e.kind].get(e.id)===e&&(r[e.kind].delete(e.id),c())}}function h(e){for(let t of e)r[t.kind].set(t.id,t);return c(),()=>{for(let t of e)r[t.kind].get(t.id)===t&&r[t.kind].delete(t.id);c()}}function b(e,t){return r[e].get(t)??null}function T(e){return e?[...r[e].values()]:[...r.shader.values(),...r.behavior.values()]}function k(e){return p.add(e),()=>p.delete(e)}function R(){r.shader.clear(),r.behavior.clear(),c()}function f(e){if(typeof e!="object"||e===null)return!1;let t=e;return typeof t.key=="symbol"&&typeof t.systemFactory=="function"&&typeof t.defaultOptions=="object"&&t.defaultOptions!==null}function B(e,t,u){let a=[];for(let[s,i]of Object.entries(t))u&&!u(s,i)||(e==="behavior"?f(i)&&a.push({kind:e,id:s,descriptor:i}):typeof i=="function"&&a.push({kind:e,id:s,create:i}));return h(a)}export{S as a,l as b,g as c,y as d,w as e,v as f,x as g,E as h,h as i,b as j,T as k,k as l,R as m,f as n,B as o};
@@ -16,4 +16,4 @@ void main() {
16
16
 
17
17
  gl_FragColor = texel;
18
18
  }
19
- `,O={vertex:C,fragment:D};import{Color as F,RepeatWrapping as v,SRGBColorSpace as te}from"three";import{MeshBasicNodeMaterial as re,MeshStandardNodeMaterial as P}from"three/webgpu";function G(s){let e=Object.keys(s).sort().reduce((t,r)=>(t[r]=s[r],t),{});return JSON.stringify(e)}function E(s){let e=0;for(let t=0;t<s.length;t++)e=Math.imul(31,e)+s.charCodeAt(t)|0;return e.toString(36)}import{LoadingManager as ee,Cache as k}from"three";import{TextureLoader as X,RepeatWrapping as B}from"three";var b=16,L=class{loader;constructor(){this.loader=new X}isSupported(e){let t=e.split(".").pop()?.toLowerCase();return["png","jpg","jpeg","gif","webp","bmp","tga"].includes(t||"")}async load(e,t){let r=await this.loader.loadAsync(e,a=>{t?.onProgress&&a.lengthComputable&&t.onProgress(a.loaded/a.total)});return t?.repeat&&r.repeat.copy(h(t.repeat,p)),r.wrapS=t?.wrapS??B,r.wrapT=t?.wrapT??B,t?.colorSpace!==void 0&&(r.colorSpace=t.colorSpace),r.anisotropy=t?.anisotropy??b,r}clone(e){let t=e.clone();return t.anisotropy=e.anisotropy||b,t.needsUpdate=!0,t}};import{GLTFLoader as J}from"three/addons/loaders/GLTFLoader.js";import{DRACOLoader as K}from"three/addons/loaders/DRACOLoader.js";import{KTX2Loader as Z}from"three/addons/loaders/KTX2Loader.js";import{MeshoptDecoder as $}from"three/addons/libs/meshopt_decoder.module.js";import{Mesh as j}from"three";import{clone as W}from"three/addons/utils/SkeletonUtils.js";function u(s){let e=W(s),t=[],r=[];s.traverse(a=>t.push(a)),e.traverse(a=>r.push(a));for(let a=0;a<t.length;a++){let o=t[a],n=r[a];!(o instanceof j)||!(n instanceof j)||(o.geometry?.clone&&(n.geometry=o.geometry.clone()),o.material&&(n.material=Array.isArray(o.material)?o.material.map(i=>i.clone()):o.material.clone()))}return e}function I(s){let e=s.indexOf("?"),t=s.indexOf("#"),r=[e,t].filter(a=>a>=0).reduce((a,o)=>Math.min(a,o),s.length);return s.slice(0,r)}function c(s){let e=I(s),t=e.lastIndexOf("/"),r=t>=0?e.slice(t+1):e,a=r.lastIndexOf(".");return a<0||a===r.length-1?null:r.slice(a+1).toLowerCase()}var V=["map","normalMap","roughnessMap","metalnessMap","emissiveMap","aoMap"],H="https://www.gstatic.com/draco/v1/decoders/",g=class{loader;dracoLoader;ktx2Loader=null;meshoptEnabled=!1;configuredRenderer=null;ktx2TranscoderPath=null;constructor(){this.dracoLoader=new K,this.dracoLoader.setDecoderPath(H),this.loader=new J,this.loader.setDRACOLoader(this.dracoLoader),this.setMeshoptEnabled(!0)}isSupported(e){let t=c(e);return["gltf","glb"].includes(t||"")}async configureRuntime({meshopt:e=!0,ktx2TranscoderPath:t,renderer:r=null}={}){this.setMeshoptEnabled(e!==!1);let a=this.normalizeTranscoderPath(t);if(!a){this.clearKTX2Loader();return}if(!r)throw new Error("GLTFLoaderAdapter.configureRuntime requires a renderer when ktx2TranscoderPath is provided.");(!this.ktx2Loader||this.ktx2TranscoderPath!==a)&&(this.clearKTX2Loader(),this.ktx2Loader=new Z,this.ktx2Loader.setTranscoderPath(a),this.loader.setKTX2Loader(this.ktx2Loader),this.ktx2TranscoderPath=a,this.configuredRenderer=null),!(!this.ktx2Loader||this.configuredRenderer===r)&&(this.ktx2Loader.detectSupport(r),this.configuredRenderer=r)}async load(e,t){return t?.useAsyncFetch?this.loadWithAsyncFetch(e,t):this.loadMainThread(e,t)}async loadWithAsyncFetch(e,t){try{let r=await fetch(e);if(!r.ok)throw new Error(`Failed to fetch ${e}: ${r.status} ${r.statusText}`);let a=await r.arrayBuffer(),o=await this.loader.parseAsync(a,e);return this.applyTextureAnisotropy(o.scene),{object:o.scene,animations:o.animations,gltf:o}}catch(r){return console.error(`Async fetch GLTF load failed for ${e}, falling back to loader.load():`,r),this.loadMainThread(e,t)}}async loadMainThread(e,t){return new Promise((r,a)=>{this.loader.load(e,o=>{this.applyTextureAnisotropy(o.scene),r({object:o.scene,animations:o.animations,gltf:o})},o=>{t?.onProgress&&o.lengthComputable&&t.onProgress(o.loaded/o.total)},o=>a(o))})}clone(e){return{object:u(e.object),animations:e.animations?.map(t=>t.clone()),gltf:e.gltf}}applyTextureAnisotropy(e){e.traverse(t=>{let r=t.material;if(!r)return;let a=Array.isArray(r)?r:[r];for(let o of a)for(let n of V){let i=o[n];if(i&&i.isTexture){let d=i;d.anisotropy=b,d.needsUpdate=!0}}})}setMeshoptEnabled(e){if(e){if(this.meshoptEnabled)return;this.loader.setMeshoptDecoder($),this.meshoptEnabled=!0;return}this.meshoptEnabled&&(this.loader.setMeshoptDecoder(void 0),this.meshoptEnabled=!1)}clearKTX2Loader(){this.ktx2Loader&&(this.ktx2Loader.dispose(),this.ktx2Loader=null),this.loader.setKTX2Loader(void 0),this.configuredRenderer=null,this.ktx2TranscoderPath=null}normalizeTranscoderPath(e){if(!e)return null;let t=String(e);return t.endsWith("/")?t:`${t}/`}};import{FBXLoader as _}from"three/addons/loaders/FBXLoader.js";var T=class{loader;constructor(){this.loader=new _}isSupported(e){return c(e)==="fbx"}async load(e,t){return t?.useAsyncFetch?this.loadWithAsyncFetch(e,t):this.loadMainThread(e,t)}async loadWithAsyncFetch(e,t){try{let r=await fetch(e);if(!r.ok)throw new Error(`Failed to fetch ${e}: ${r.status} ${r.statusText}`);let a=await r.arrayBuffer(),o=this.loader.parse(a,e);return{object:o,animations:o.animations||[]}}catch(r){return console.error(`Async fetch FBX load failed for ${e}, falling back to loader.load():`,r),this.loadMainThread(e,t)}}async loadMainThread(e,t){return new Promise((r,a)=>{this.loader.load(e,o=>{r({object:o,animations:o.animations||[]})},o=>{t?.onProgress&&o.lengthComputable&&t.onProgress(o.loaded/o.total)},o=>a(o))})}clone(e){return{object:u(e.object),animations:e.animations?.map(t=>t.clone())}}};import{OBJLoader as z}from"three/addons/loaders/OBJLoader.js";import{MTLLoader as Y}from"three/addons/loaders/MTLLoader.js";var y=class{loader;mtlLoader;constructor(){this.loader=new z,this.mtlLoader=new Y}isSupported(e){return c(e)==="obj"}async load(e,t){return t?.mtlPath&&await this.loadMTL(t.mtlPath),new Promise((r,a)=>{this.loader.load(e,o=>{r({object:o,animations:[]})},o=>{t?.onProgress&&o.lengthComputable&&t.onProgress(o.loaded/o.total)},o=>a(o))})}async loadMTL(e){return new Promise((t,r)=>{this.mtlLoader.load(e,a=>{a.preload(),this.loader.setMaterials(a),t()},void 0,a=>r(a))})}clone(e){return{object:u(e.object),animations:[]}}};import{AudioLoader as q}from"three";var x=class{loader;constructor(){this.loader=new q}isSupported(e){let t=c(e);return["mp3","ogg","wav","flac","aac","m4a"].includes(t||"")}async load(e,t){return new Promise((r,a)=>{this.loader.load(e,o=>r(o),o=>{t?.onProgress&&o.lengthComputable&&t.onProgress(o.loaded/o.total)},o=>a(o))})}};import{FileLoader as Q}from"three";var m=class{loader;constructor(){this.loader=new Q}isSupported(e){return!0}async load(e,t){let r=t?.responseType??"text";return this.loader.setResponseType(r),new Promise((a,o)=>{this.loader.load(e,n=>a(n),n=>{t?.onProgress&&n.lengthComputable&&t.onProgress(n.loaded/n.total)},n=>o(n))})}},M=class{fileLoader;constructor(){this.fileLoader=new m}isSupported(e){return c(e)==="json"}async load(e,t){return await this.fileLoader.load(e,{...t,responseType:"json"})}};var w=class s{static instance=null;textureCache=new Map;modelCache=new Map;audioCache=new Map;fileCache=new Map;jsonCache=new Map;pendingGLTFRuntimePath=null;pendingGLTFRuntimePromise=null;pendingGLTFRuntimeResolve=null;textureLoader;gltfLoader;fbxLoader;objLoader;audioLoader;fileLoader;jsonLoader;loadingManager;events;stats={texturesLoaded:0,modelsLoaded:0,audioLoaded:0,filesLoaded:0,cacheHits:0,cacheMisses:0};constructor(){this.textureLoader=new L,this.gltfLoader=new g,this.fbxLoader=new T,this.objLoader=new y,this.audioLoader=new x,this.fileLoader=new m,this.jsonLoader=new M,this.loadingManager=new ee,this.loadingManager.onProgress=(e,t,r)=>{this.events.emit("batch:progress",{loaded:t,total:r})},this.events=R(),k.enabled=!0}static getInstance(){return s.instance||(s.instance=new s),s.instance}static resetInstance(){s.instance&&(s.instance.clearCache(),s.instance=null)}async loadTexture(e,t){return this.loadWithCache(e,"texture",this.textureCache,()=>this.textureLoader.load(e,t),t,r=>{if(!t?.clone)return r;let a=this.textureLoader.clone(r);return t.repeat&&a.repeat.copy(h(t.repeat,p)),t.wrapS!==void 0&&(a.wrapS=t.wrapS),t.wrapT!==void 0&&(a.wrapT=t.wrapT),a})}async loadGLTF(e,t){return await this.waitForPreparedGLTFRuntime(),this.loadWithCache(e,"gltf",this.modelCache,()=>this.gltfLoader.load(e,t),t,r=>t?.clone?this.gltfLoader.clone(r):r)}prepareGLTFRuntime(e){let t=this.normalizeTranscoderPath(e?.ktx2TranscoderPath);t&&(this.pendingGLTFRuntimePath===t&&this.pendingGLTFRuntimePromise||(this.pendingGLTFRuntimePath=t,this.pendingGLTFRuntimePromise||(this.pendingGLTFRuntimePromise=new Promise(r=>{this.pendingGLTFRuntimeResolve=r}))))}async configureGLTFRuntime(e){await this.gltfLoader.configureRuntime(e);let t=this.normalizeTranscoderPath(e?.ktx2TranscoderPath);t&&e?.renderer&&this.resolvePreparedGLTFRuntime(t)}async loadFBX(e,t){return this.loadWithCache(e,"fbx",this.modelCache,()=>this.fbxLoader.load(e,t),t,r=>t?.clone?this.fbxLoader.clone(r):r)}async loadOBJ(e,t){let r=t?.mtlPath?`${e}:${t.mtlPath}`:e;return this.loadWithCache(r,"obj",this.modelCache,()=>this.objLoader.load(e,t),t,a=>t?.clone?this.objLoader.clone(a):a)}async loadModel(e,t){let r=c(e);switch(r){case"gltf":case"glb":return this.loadGLTF(e,t);case"fbx":return this.loadFBX(e,t);case"obj":return this.loadOBJ(e,t);default:throw new Error(`Unsupported model format: ${r}`)}}async loadAudio(e,t){return this.loadWithCache(e,"audio",this.audioCache,()=>this.audioLoader.load(e,t),t)}async loadFile(e,t){let r=t?.responseType?`${e}:${t.responseType}`:e;return this.loadWithCache(r,"file",this.fileCache,()=>this.fileLoader.load(e,t),t)}async loadJSON(e,t){return this.loadWithCache(e,"json",this.jsonCache,()=>this.jsonLoader.load(e,t),t)}async loadBatch(e){let t=new Map,r=e.map(async a=>{try{let o;switch(a.type){case"texture":o=await this.loadTexture(a.url,a.options);break;case"gltf":o=await this.loadGLTF(a.url,a.options);break;case"fbx":o=await this.loadFBX(a.url,a.options);break;case"obj":o=await this.loadOBJ(a.url,a.options);break;case"audio":o=await this.loadAudio(a.url,a.options);break;case"file":o=await this.loadFile(a.url,a.options);break;case"json":o=await this.loadJSON(a.url,a.options);break;default:throw new Error(`Unknown asset type: ${a.type}`)}t.set(a.url,o)}catch(o){throw this.events.emit("asset:error",{url:a.url,type:a.type,error:o}),o}});return await Promise.all(r),this.events.emit("batch:complete",{urls:e.map(a=>a.url)}),t}async preload(e){await this.loadBatch(e)}isCached(e){return this.textureCache.has(e)||this.modelCache.has(e)||this.audioCache.has(e)||this.fileCache.has(e)||this.jsonCache.has(e)}clearCache(e){e?(this.textureCache.delete(e),this.modelCache.delete(e),this.audioCache.delete(e),this.fileCache.delete(e),this.jsonCache.delete(e)):(this.textureCache.clear(),this.modelCache.clear(),this.audioCache.clear(),this.fileCache.clear(),this.jsonCache.clear(),k.clear(),this.pendingGLTFRuntimePath=null,this.pendingGLTFRuntimePromise=null,this.pendingGLTFRuntimeResolve=null)}getStats(){return{...this.stats}}on(e,t){this.events.on(e,t)}off(e,t){this.events.off(e,t)}async loadWithCache(e,t,r,a,o,n){o?.forceReload&&r.delete(e);let i=r.get(e);if(i){this.stats.cacheHits++,this.events.emit("asset:loaded",{url:e,type:t,fromCache:!0});let l=await i.promise;return n?n(l):l}this.stats.cacheMisses++,this.events.emit("asset:loading",{url:e,type:t});let d=a(),f={promise:d,loadedAt:Date.now()};r.set(e,f);try{let l=await d;return f.result=l,this.updateStats(t),this.events.emit("asset:loaded",{url:e,type:t,fromCache:!1}),n?n(l):l}catch(l){throw r.delete(e),this.events.emit("asset:error",{url:e,type:t,error:l}),l}}updateStats(e){switch(e){case"texture":this.stats.texturesLoaded++;break;case"gltf":case"fbx":case"obj":this.stats.modelsLoaded++;break;case"audio":this.stats.audioLoaded++;break;case"file":case"json":this.stats.filesLoaded++;break}}async waitForPreparedGLTFRuntime(){this.pendingGLTFRuntimePromise&&await this.pendingGLTFRuntimePromise}resolvePreparedGLTFRuntime(e){this.pendingGLTFRuntimePath&&this.pendingGLTFRuntimePath!==e||(this.pendingGLTFRuntimeResolve?.(),this.pendingGLTFRuntimeResolve=null,this.pendingGLTFRuntimePromise=null,this.pendingGLTFRuntimePath=null)}normalizeTranscoderPath(e){if(!e)return null;let t=String(e);return t.endsWith("/")?t:`${t}/`}},A=w.getInstance();import{uniform as vt,uv as Ot,time as wt,vec3 as At,vec4 as Ft,float as Pt,Fn as St}from"three/tsl";function ae(s){return"colorNode"in s}function N(s){return"fragment"in s&&"vertex"in s}function oe(s){return!!s&&N(s)&&s.vertex===O.vertex&&s.fragment===O.fragment}var U=class s{static sharedMaterialMap=new Map;static clearSharedMaterialCache(){s.sharedMaterialMap.clear()}materials=[];useTSL;constructor(e=!0){this.useTSL=e}trackSharedMaterial(e,t){let r=E(G(e)),a=s.sharedMaterialMap.get(r);if(a){let o=a.geometryMap.get(t);o?a.geometryMap.set(t,o+1):a.geometryMap.set(t,1)}else s.sharedMaterialMap.set(r,{geometryMap:new Map([[t,1]]),material:this.materials[0]})}build(e,t){let{path:r,normalMap:a,repeat:o,color:n,shader:i,opacity:d}=e,f=oe(i),l=!!i&&!f,S=!!r&&(!i||f);S?this.setTexture(r??null,o,!0,d,n):l&&i?ae(i)?this.setTSLShader(i,d):N(i)&&(console.warn("MaterialBuilder: GLSL shaders are not supported on the WebGPU renderer. Author custom shaders as TSL (ZylemTSLShader). Falling back to a default node material."),this.setColor(n??new F("#ffffff"),!0,d)):r&&this.setTexture(r,o,!0,d,n),n&&!S&&!l&&this.withColor(n,!0,d),this.materials.length===0&&this.setColor(new F("#ffffff"),!0,d),a&&this.materials.length>0&&this.setNormalMap(a,o),this.trackSharedMaterial(e,t)}withColor(e,t=!1,r){return this.setColor(e,t,r),this}withShader(e,t){return this.setShader(e,t),this}withTSLShader(e,t){return this.setTSLShader(e,t),this}applyOpacity(e,t,r=!1){t!==void 0&&(e.opacity=t),e.transparent=r||t!==void 0&&t<1,e.needsUpdate=!0}setTexture(e=null,t=p,r=!0,a,o){if(!e)return;let n=new P;o&&(n.color=o),this.applyOpacity(n,a),this.materials.push(n),A.loadTexture(e,{clone:!0,repeat:h(t,p),colorSpace:te}).then(i=>{i.wrapS=v,i.wrapT=v,n.map=i,n.needsUpdate=!0})}setNormalMap(e,t=p){let r=this.materials[this.materials.length-1];r&&A.loadTexture(e,{clone:!0,repeat:h(t,p)}).then(a=>{a.wrapS=v,a.wrapT=v,r instanceof P&&(r.normalMap=a,r.needsUpdate=!0)})}setColor(e,t=!0,r){let a=new P;a.color=e,this.applyOpacity(a,r),this.materials.push(a)}setShader(e,t){console.warn("MaterialBuilder.setShader: GLSL shaders are not supported on the WebGPU renderer. Author custom shaders as TSL (ZylemTSLShader). Falling back to a default node material."),this.setColor(new F("#ffffff"),!0,t)}setTSLShader(e,t){this.materials.push(se(e,t))}};function se(s,e){let t=new re;return t.colorNode=s.colorNode,s.positionNode&&(t.positionNode=s.positionNode),s.normalNode&&(t.normalNode=s.normalNode),s.blending!==void 0&&(t.blending=s.blending),s.side!==void 0&&(t.side=s.side),s.depthTest!==void 0&&(t.depthTest=s.depthTest),e!==void 0&&(t.opacity=e),t.transparent=!!s.transparent||e!==void 0&&e<1,t.needsUpdate=!0,t}export{C as a,O as b,G as c,E as d,b as e,c as f,A as g,ae as h,N as i,U as j,se as k,vt as l,Ot as m,wt as n,At as o,Ft as p,Pt as q,St as r};
19
+ `,O={vertex:C,fragment:D};import{Color as F,RepeatWrapping as v,SRGBColorSpace as te}from"three";import{MeshBasicNodeMaterial as re,MeshStandardNodeMaterial as P}from"three/webgpu";function G(s){let e=Object.keys(s).sort().reduce((t,r)=>(t[r]=s[r],t),{});return JSON.stringify(e)}function E(s){let e=0;for(let t=0;t<s.length;t++)e=Math.imul(31,e)+s.charCodeAt(t)|0;return e.toString(36)}import{LoadingManager as ee,Cache as k}from"three";import{TextureLoader as X,RepeatWrapping as B}from"three";var b=16,L=class{loader;constructor(){this.loader=new X}isSupported(e){let t=e.split(".").pop()?.toLowerCase();return["png","jpg","jpeg","gif","webp","bmp","tga"].includes(t||"")}async load(e,t){let r=await this.loader.loadAsync(e,a=>{t?.onProgress&&a.lengthComputable&&t.onProgress(a.loaded/a.total)});return t?.repeat&&r.repeat.copy(h(t.repeat,p)),r.wrapS=t?.wrapS??B,r.wrapT=t?.wrapT??B,t?.colorSpace!==void 0&&(r.colorSpace=t.colorSpace),r.anisotropy=t?.anisotropy??b,r}clone(e){let t=e.clone();return t.anisotropy=e.anisotropy||b,t.needsUpdate=!0,t}};import{GLTFLoader as J}from"three/addons/loaders/GLTFLoader.js";import{DRACOLoader as K}from"three/addons/loaders/DRACOLoader.js";import{KTX2Loader as Z}from"three/addons/loaders/KTX2Loader.js";import{MeshoptDecoder as $}from"three/addons/libs/meshopt_decoder.module.js";import{Mesh as j}from"three";import{clone as W}from"three/addons/utils/SkeletonUtils.js";function u(s){let e=W(s),t=[],r=[];s.traverse(a=>t.push(a)),e.traverse(a=>r.push(a));for(let a=0;a<t.length;a++){let o=t[a],n=r[a];!(o instanceof j)||!(n instanceof j)||(o.geometry?.clone&&(n.geometry=o.geometry.clone()),o.material&&(n.material=Array.isArray(o.material)?o.material.map(i=>i.clone()):o.material.clone()))}return e}function I(s){let e=s.indexOf("?"),t=s.indexOf("#"),r=[e,t].filter(a=>a>=0).reduce((a,o)=>Math.min(a,o),s.length);return s.slice(0,r)}function c(s){let e=I(s),t=e.lastIndexOf("/"),r=t>=0?e.slice(t+1):e,a=r.lastIndexOf(".");return a<0||a===r.length-1?null:r.slice(a+1).toLowerCase()}var V=["map","normalMap","roughnessMap","metalnessMap","emissiveMap","aoMap"],H="https://www.gstatic.com/draco/v1/decoders/",g=class{loader;dracoLoader;ktx2Loader=null;meshoptEnabled=!1;configuredRenderer=null;ktx2TranscoderPath=null;constructor(){this.dracoLoader=new K,this.dracoLoader.setDecoderPath(H),this.loader=new J,this.loader.setDRACOLoader(this.dracoLoader),this.setMeshoptEnabled(!0)}isSupported(e){let t=c(e);return["gltf","glb"].includes(t||"")}async configureRuntime({meshopt:e=!0,ktx2TranscoderPath:t,renderer:r=null}={}){this.setMeshoptEnabled(e!==!1);let a=this.normalizeTranscoderPath(t);if(!a){this.clearKTX2Loader();return}if(!r)throw new Error("GLTFLoaderAdapter.configureRuntime requires a renderer when ktx2TranscoderPath is provided.");(!this.ktx2Loader||this.ktx2TranscoderPath!==a)&&(this.clearKTX2Loader(),this.ktx2Loader=new Z,this.ktx2Loader.setTranscoderPath(a),this.loader.setKTX2Loader(this.ktx2Loader),this.ktx2TranscoderPath=a,this.configuredRenderer=null),!(!this.ktx2Loader||this.configuredRenderer===r)&&(this.ktx2Loader.detectSupport(r),this.configuredRenderer=r)}async load(e,t){return t?.useAsyncFetch?this.loadWithAsyncFetch(e,t):this.loadMainThread(e,t)}async loadWithAsyncFetch(e,t){try{let r=await fetch(e);if(!r.ok)throw new Error(`Failed to fetch ${e}: ${r.status} ${r.statusText}`);let a=await r.arrayBuffer(),o=await this.loader.parseAsync(a,e);return this.applyTextureAnisotropy(o.scene),{object:o.scene,animations:o.animations,gltf:o}}catch(r){return console.error(`Async fetch GLTF load failed for ${e}, falling back to loader.load():`,r),this.loadMainThread(e,t)}}async loadMainThread(e,t){return new Promise((r,a)=>{this.loader.load(e,o=>{this.applyTextureAnisotropy(o.scene),r({object:o.scene,animations:o.animations,gltf:o})},o=>{t?.onProgress&&o.lengthComputable&&t.onProgress(o.loaded/o.total)},o=>a(o))})}clone(e){return{object:u(e.object),animations:e.animations?.map(t=>t.clone()),gltf:e.gltf}}applyTextureAnisotropy(e){e.traverse(t=>{let r=t.material;if(!r)return;let a=Array.isArray(r)?r:[r];for(let o of a)for(let n of V){let i=o[n];if(i&&i.isTexture){let d=i;d.anisotropy=b,d.needsUpdate=!0}}})}setMeshoptEnabled(e){if(e){if(this.meshoptEnabled)return;this.loader.setMeshoptDecoder($),this.meshoptEnabled=!0;return}this.meshoptEnabled&&(this.loader.setMeshoptDecoder(void 0),this.meshoptEnabled=!1)}clearKTX2Loader(){this.ktx2Loader&&(this.ktx2Loader.dispose(),this.ktx2Loader=null),this.loader.setKTX2Loader(void 0),this.configuredRenderer=null,this.ktx2TranscoderPath=null}normalizeTranscoderPath(e){if(!e)return null;let t=String(e);return t.endsWith("/")?t:`${t}/`}};import{FBXLoader as _}from"three/addons/loaders/FBXLoader.js";var T=class{loader;constructor(){this.loader=new _}isSupported(e){return c(e)==="fbx"}async load(e,t){return t?.useAsyncFetch?this.loadWithAsyncFetch(e,t):this.loadMainThread(e,t)}async loadWithAsyncFetch(e,t){try{let r=await fetch(e);if(!r.ok)throw new Error(`Failed to fetch ${e}: ${r.status} ${r.statusText}`);let a=await r.arrayBuffer(),o=this.loader.parse(a,e);return{object:o,animations:o.animations||[]}}catch(r){return console.error(`Async fetch FBX load failed for ${e}, falling back to loader.load():`,r),this.loadMainThread(e,t)}}async loadMainThread(e,t){return new Promise((r,a)=>{this.loader.load(e,o=>{r({object:o,animations:o.animations||[]})},o=>{t?.onProgress&&o.lengthComputable&&t.onProgress(o.loaded/o.total)},o=>a(o))})}clone(e){return{object:u(e.object),animations:e.animations?.map(t=>t.clone())}}};import{OBJLoader as z}from"three/addons/loaders/OBJLoader.js";import{MTLLoader as Y}from"three/addons/loaders/MTLLoader.js";var y=class{loader;mtlLoader;constructor(){this.loader=new z,this.mtlLoader=new Y}isSupported(e){return c(e)==="obj"}async load(e,t){return t?.mtlPath&&await this.loadMTL(t.mtlPath),new Promise((r,a)=>{this.loader.load(e,o=>{r({object:o,animations:[]})},o=>{t?.onProgress&&o.lengthComputable&&t.onProgress(o.loaded/o.total)},o=>a(o))})}async loadMTL(e){return new Promise((t,r)=>{this.mtlLoader.load(e,a=>{a.preload(),this.loader.setMaterials(a),t()},void 0,a=>r(a))})}clone(e){return{object:u(e.object),animations:[]}}};import{AudioLoader as q}from"three";var x=class{loader;constructor(){this.loader=new q}isSupported(e){let t=c(e);return["mp3","ogg","wav","flac","aac","m4a"].includes(t||"")}async load(e,t){return new Promise((r,a)=>{this.loader.load(e,o=>r(o),o=>{t?.onProgress&&o.lengthComputable&&t.onProgress(o.loaded/o.total)},o=>a(o))})}};import{FileLoader as Q}from"three";var m=class{loader;constructor(){this.loader=new Q}isSupported(e){return!0}async load(e,t){let r=t?.responseType??"text";return this.loader.setResponseType(r),new Promise((a,o)=>{this.loader.load(e,n=>a(n),n=>{t?.onProgress&&n.lengthComputable&&t.onProgress(n.loaded/n.total)},n=>o(n))})}},M=class{fileLoader;constructor(){this.fileLoader=new m}isSupported(e){return c(e)==="json"}async load(e,t){return await this.fileLoader.load(e,{...t,responseType:"json"})}};var w=class s{static instance=null;textureCache=new Map;modelCache=new Map;audioCache=new Map;fileCache=new Map;jsonCache=new Map;pendingGLTFRuntimePath=null;pendingGLTFRuntimePromise=null;pendingGLTFRuntimeResolve=null;textureLoader;gltfLoader;fbxLoader;objLoader;audioLoader;fileLoader;jsonLoader;loadingManager;events;stats={texturesLoaded:0,modelsLoaded:0,audioLoaded:0,filesLoaded:0,cacheHits:0,cacheMisses:0};constructor(){this.textureLoader=new L,this.gltfLoader=new g,this.fbxLoader=new T,this.objLoader=new y,this.audioLoader=new x,this.fileLoader=new m,this.jsonLoader=new M,this.loadingManager=new ee,this.loadingManager.onProgress=(e,t,r)=>{this.events.emit("batch:progress",{loaded:t,total:r})},this.events=R(),k.enabled=!0}static getInstance(){return s.instance||(s.instance=new s),s.instance}static resetInstance(){s.instance&&(s.instance.clearCache(),s.instance=null)}async loadTexture(e,t){return this.loadWithCache(e,"texture",this.textureCache,()=>this.textureLoader.load(e,t),t,r=>{if(!t?.clone)return r;let a=this.textureLoader.clone(r);return t.repeat&&a.repeat.copy(h(t.repeat,p)),t.wrapS!==void 0&&(a.wrapS=t.wrapS),t.wrapT!==void 0&&(a.wrapT=t.wrapT),a})}async loadGLTF(e,t){return await this.waitForPreparedGLTFRuntime(),this.loadWithCache(e,"gltf",this.modelCache,()=>this.gltfLoader.load(e,t),t,r=>t?.clone?this.gltfLoader.clone(r):r)}prepareGLTFRuntime(e){let t=this.normalizeTranscoderPath(e?.ktx2TranscoderPath);t&&(this.pendingGLTFRuntimePath===t&&this.pendingGLTFRuntimePromise||(this.pendingGLTFRuntimePath=t,this.pendingGLTFRuntimePromise||(this.pendingGLTFRuntimePromise=new Promise(r=>{this.pendingGLTFRuntimeResolve=r}))))}async configureGLTFRuntime(e){await this.gltfLoader.configureRuntime(e);let t=this.normalizeTranscoderPath(e?.ktx2TranscoderPath);t&&e?.renderer&&this.resolvePreparedGLTFRuntime(t)}async loadFBX(e,t){return this.loadWithCache(e,"fbx",this.modelCache,()=>this.fbxLoader.load(e,t),t,r=>t?.clone?this.fbxLoader.clone(r):r)}async loadOBJ(e,t){let r=t?.mtlPath?`${e}:${t.mtlPath}`:e;return this.loadWithCache(r,"obj",this.modelCache,()=>this.objLoader.load(e,t),t,a=>t?.clone?this.objLoader.clone(a):a)}async loadModel(e,t){let r=c(e);switch(r){case"gltf":case"glb":return this.loadGLTF(e,t);case"fbx":return this.loadFBX(e,t);case"obj":return this.loadOBJ(e,t);default:throw new Error(`Unsupported model format: ${r}`)}}async loadAudio(e,t){return this.loadWithCache(e,"audio",this.audioCache,()=>this.audioLoader.load(e,t),t)}async loadFile(e,t){let r=t?.responseType?`${e}:${t.responseType}`:e;return this.loadWithCache(r,"file",this.fileCache,()=>this.fileLoader.load(e,t),t)}async loadJSON(e,t){return this.loadWithCache(e,"json",this.jsonCache,()=>this.jsonLoader.load(e,t),t)}async loadBatch(e){let t=new Map,r=e.map(async a=>{try{let o;switch(a.type){case"texture":o=await this.loadTexture(a.url,a.options);break;case"gltf":o=await this.loadGLTF(a.url,a.options);break;case"fbx":o=await this.loadFBX(a.url,a.options);break;case"obj":o=await this.loadOBJ(a.url,a.options);break;case"audio":o=await this.loadAudio(a.url,a.options);break;case"file":o=await this.loadFile(a.url,a.options);break;case"json":o=await this.loadJSON(a.url,a.options);break;default:throw new Error(`Unknown asset type: ${a.type}`)}t.set(a.url,o)}catch(o){throw this.events.emit("asset:error",{url:a.url,type:a.type,error:o}),o}});return await Promise.all(r),this.events.emit("batch:complete",{urls:e.map(a=>a.url)}),t}async preload(e){await this.loadBatch(e)}isCached(e){return this.textureCache.has(e)||this.modelCache.has(e)||this.audioCache.has(e)||this.fileCache.has(e)||this.jsonCache.has(e)}clearCache(e){e?(this.textureCache.delete(e),this.modelCache.delete(e),this.audioCache.delete(e),this.fileCache.delete(e),this.jsonCache.delete(e)):(this.textureCache.clear(),this.modelCache.clear(),this.audioCache.clear(),this.fileCache.clear(),this.jsonCache.clear(),k.clear(),this.pendingGLTFRuntimePath=null,this.pendingGLTFRuntimePromise=null,this.pendingGLTFRuntimeResolve=null)}getStats(){return{...this.stats}}on(e,t){this.events.on(e,t)}off(e,t){this.events.off(e,t)}async loadWithCache(e,t,r,a,o,n){o?.forceReload&&r.delete(e);let i=r.get(e);if(i){this.stats.cacheHits++,this.events.emit("asset:loaded",{url:e,type:t,fromCache:!0});let l=await i.promise;return n?n(l):l}this.stats.cacheMisses++,this.events.emit("asset:loading",{url:e,type:t});let d=a(),f={promise:d,loadedAt:Date.now()};r.set(e,f);try{let l=await d;return f.result=l,this.updateStats(t),this.events.emit("asset:loaded",{url:e,type:t,fromCache:!1}),n?n(l):l}catch(l){throw r.delete(e),this.events.emit("asset:error",{url:e,type:t,error:l}),l}}updateStats(e){switch(e){case"texture":this.stats.texturesLoaded++;break;case"gltf":case"fbx":case"obj":this.stats.modelsLoaded++;break;case"audio":this.stats.audioLoaded++;break;case"file":case"json":this.stats.filesLoaded++;break}}async waitForPreparedGLTFRuntime(){this.pendingGLTFRuntimePromise&&await this.pendingGLTFRuntimePromise}resolvePreparedGLTFRuntime(e){this.pendingGLTFRuntimePath&&this.pendingGLTFRuntimePath!==e||(this.pendingGLTFRuntimeResolve?.(),this.pendingGLTFRuntimeResolve=null,this.pendingGLTFRuntimePromise=null,this.pendingGLTFRuntimePath=null)}normalizeTranscoderPath(e){if(!e)return null;let t=String(e);return t.endsWith("/")?t:`${t}/`}},A=w.getInstance();import{uniform as vt,uv as Ot,time as wt,vec3 as At,vec4 as Ft,float as Pt,Fn as St}from"three/tsl";function ae(s){return"colorNode"in s}function N(s){return"fragment"in s&&"vertex"in s}function oe(s){return!!s&&N(s)&&s.vertex===O.vertex&&s.fragment===O.fragment}var U=class s{static sharedMaterialMap=new Map;static clearSharedMaterialCache(){s.sharedMaterialMap.clear()}materials=[];useTSL;constructor(e=!0){this.useTSL=e}trackSharedMaterial(e,t){let r=E(G(e)),a=s.sharedMaterialMap.get(r);if(a){let o=a.geometryMap.get(t);o?a.geometryMap.set(t,o+1):a.geometryMap.set(t,1)}else s.sharedMaterialMap.set(r,{geometryMap:new Map([[t,1]]),material:this.materials[0]})}build(e,t){let{path:r,normalMap:a,repeat:o,color:n,shader:i,opacity:d}=e,f=oe(i),l=!!i&&!f,S=!!r&&(!i||f);S?this.setTexture(r??null,o,!0,d,n):l&&i?ae(i)?this.setTSLShader(i,d):N(i)&&(console.warn("MaterialBuilder: GLSL shaders are not supported on the WebGPU renderer. Author custom shaders as TSL (ZylemTSLShader). Falling back to a default node material."),this.setColor(n??new F("#ffffff"),!0,d)):r&&this.setTexture(r,o,!0,d,n),n&&!S&&!l&&this.withColor(n,!0,d),this.materials.length===0&&this.setColor(new F("#ffffff"),!0,d),a&&this.materials.length>0&&this.setNormalMap(a,o),this.trackSharedMaterial(e,t)}withColor(e,t=!1,r){return this.setColor(e,t,r),this}withShader(e,t){return this.setShader(e,t),this}withTSLShader(e,t){return this.setTSLShader(e,t),this}applyOpacity(e,t,r=!1){t!==void 0&&(e.opacity=t),e.transparent=r||t!==void 0&&t<1,e.needsUpdate=!0}setTexture(e=null,t=p,r=!0,a,o){if(!e)return;let n=new P;o&&(n.color=o),this.applyOpacity(n,a),this.materials.push(n),A.loadTexture(e,{clone:!0,repeat:h(t,p),colorSpace:te}).then(i=>{i.wrapS=v,i.wrapT=v,n.map=i,n.needsUpdate=!0})}setNormalMap(e,t=p){let r=this.materials[this.materials.length-1];r&&A.loadTexture(e,{clone:!0,repeat:h(t,p)}).then(a=>{a.wrapS=v,a.wrapT=v,r instanceof P&&(r.normalMap=a,r.needsUpdate=!0)})}setColor(e,t=!0,r){let a=new P;a.color=e,this.applyOpacity(a,r),this.materials.push(a)}setShader(e,t){console.warn("MaterialBuilder.setShader: GLSL shaders are not supported on the WebGPU renderer. Author custom shaders as TSL (ZylemTSLShader). Falling back to a default node material."),this.setColor(new F("#ffffff"),!0,t)}setTSLShader(e,t){this.materials.push(se(e,t))}};function se(s,e){let t=new re;return t.colorNode=s.colorNode,s.positionNode&&(t.positionNode=s.positionNode),s.normalNode&&(t.normalNode=s.normalNode),s.blending!==void 0&&(t.blending=s.blending),s.side!==void 0&&(t.side=s.side),s.depthTest!==void 0&&(t.depthTest=s.depthTest),e!==void 0&&(t.opacity=e),t.transparent=!!s.transparent||e!==void 0&&e<1,t.needsUpdate=!0,t}export{G as a,E as b,C as c,O as d,b as e,c as f,A as g,ae as h,N as i,U as j,se as k,vt as l,Ot as m,wt as n,At as o,Ft as p,Pt as q,St as r};
@@ -0,0 +1 @@
1
+ import{RuntimeBoundary2DBehavior as R,RuntimeDynamicCircleBody2DBehavior as t,RuntimeGoalZone2DBehavior as o,RuntimePlayerInput2DBehavior as m,RuntimeRicochet2DBehavior as r,RuntimeTriggerRegion2DBehavior as D,RUNTIME_BOUNDARY_2D_BEHAVIOR_KEY as _,RUNTIME_DYNAMIC_CIRCLE_BODY_2D_BEHAVIOR_KEY as u,RUNTIME_GOAL_ZONE_2D_BEHAVIOR_KEY as E,RUNTIME_PLAYER_INPUT_2D_BEHAVIOR_KEY as a,RUNTIME_RICOCHET_2D_BEHAVIOR_KEY as B,RUNTIME_TRIGGER_REGION_2D_BEHAVIOR_KEY as I,bindRuntimeDynamicCircleBody2DHandle as c,emitRuntimeGoal as O,emitRuntimeRicochet as l,emitRuntimeTriggerRegionEnter as g}from"@zylem/behaviors/runtime-2d";export{R as a,t as b,o as c,m as d,r as e,D as f,_ as g,u as h,E as i,a as j,B as k,I as l,c as m,O as n,l as o,g as p};
@@ -1 +1 @@
1
- import{a as f}from"./chunk-BMRFDDMR.js";import{b as u,r as C,s as V,t as d,v as G,w as U,y as v,z as b}from"./chunk-SAQA4SXW.js";import{e as D}from"./chunk-7NYP4YAG.js";import{c as h,d as y,h as m,i as E,j as x}from"./chunk-7WRQ2UAN.js";import{Color as B,Group as st,Sprite as ot,SpriteMaterial as at,CanvasTexture as H,LinearFilter as w,Vector2 as pt,ClampToEdgeWrapping as W}from"three";var g={position:void 0,text:"",fontFamily:'Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace',fontSize:18,fontColor:"#FFFFFF",backgroundColor:null,padding:4,stickToViewport:!0,screenPosition:new pt(24,24),zDistance:1},O=class extends v{createEntity(t){return new _(t)}},lt=Symbol("Text"),_=class i extends d{static type=lt;_sprite=null;_texture=null;_canvas=null;_ctx=null;_cameraRef=null;_lastCanvasW=0;_lastCanvasH=0;constructor(t){super(),this.options=u(g,t),this.options.screenPosition=E(this.options.screenPosition,g.screenPosition),this.prependSetup(this.textSetup.bind(this)),this.prependUpdate(this.textUpdate.bind(this)),this.onCleanup(this.textDestroy.bind(this))}create(){return this._sprite=null,this._texture=null,this._canvas=null,this._ctx=null,this._lastCanvasW=0,this._lastCanvasH=0,this.group=new st,this.createSprite(),super.create()}createSprite(){this._canvas=document.createElement("canvas"),this._ctx=this._canvas.getContext("2d"),this._texture=new H(this._canvas),this._texture.minFilter=w,this._texture.magFilter=w;let t=new at({map:this._texture,transparent:!0,depthTest:!1,depthWrite:!1,alphaTest:.5});this._sprite=new ot(t),this.group?.add(this._sprite),this.redrawText(this.options.text??"")}measureAndResizeCanvas(t,e,n,s){if(!this._canvas||!this._ctx)return{sizeChanged:!1};this._ctx.font=`${e}px ${n}`;let r=this._ctx.measureText(t),o=Math.ceil(r.width),a=Math.ceil(e*1.4),p=Math.max(2,o+s*2),l=Math.max(2,a+s*2),T=p!==this._lastCanvasW||l!==this._lastCanvasH;return this._canvas.width=p,this._canvas.height=l,this._lastCanvasW=p,this._lastCanvasH=l,{sizeChanged:T}}drawCenteredText(t,e,n){!this._canvas||!this._ctx||(this._ctx.font=`${e}px ${n}`,this._ctx.textAlign="center",this._ctx.textBaseline="middle",this._ctx.clearRect(0,0,this._canvas.width,this._canvas.height),this.options.backgroundColor&&(this._ctx.fillStyle=this.toCssColor(this.options.backgroundColor),this._ctx.fillRect(0,0,this._canvas.width,this._canvas.height)),this._ctx.fillStyle=this.toCssColor(this.options.fontColor??"#FFFFFF"),this._ctx.fillText(t,this._canvas.width/2,this._canvas.height/2))}updateTexture(t){!this._texture||!this._canvas||(t&&(this._texture.dispose(),this._texture=new H(this._canvas),this._texture.minFilter=w,this._texture.magFilter=w,this._texture.wrapS=W,this._texture.wrapT=W),this._texture.image=this._canvas,this._texture.needsUpdate=!0,this._sprite&&this._sprite.material&&(this._sprite.material.map=this._texture,this._sprite.material.needsUpdate=!0))}redrawText(t){if(!this._canvas||!this._ctx)return;let e=this.options.fontSize??18,n=this.options.fontFamily??g.fontFamily,s=this.options.padding??4,{sizeChanged:r}=this.measureAndResizeCanvas(t,e,n,s);this.drawCenteredText(t,e,n),this.updateTexture(!!r),this.options.stickToViewport&&this._cameraRef?this.updateStickyTransform():this.updateWorldSpriteScale()}toCssColor(t){return typeof t=="string"?t:`#${(t instanceof B?t:new B(t)).getHexString()}`}textSetup(t){this._cameraRef=t.camera,this.options.stickToViewport&&this._cameraRef&&(this._cameraRef.camera.add(this.group),this.updateStickyTransform())}textUpdate(t){this._sprite&&this.options.stickToViewport&&this._cameraRef&&this.updateStickyTransform()}getResolution(){return{width:this._cameraRef?.screenResolution.x??1,height:this._cameraRef?.screenResolution.y??1}}getScreenPixels(t,e,n){let s=t.x>=0&&t.x<=1,r=t.y>=0&&t.y<=1;return{px:s?t.x*e:t.x,py:r?t.y*n:t.y}}computeWorldExtents(t,e){let n=1,s=1;if(t.isPerspectiveCamera){let r=t,o=Math.tan(r.fov*Math.PI/180/2)*e;n=o*r.aspect,s=o}else if(t.isOrthographicCamera){let r=t;n=(r.right-r.left)/2,s=(r.top-r.bottom)/2}return{worldHalfW:n,worldHalfH:s}}updateSpriteScale(t,e){if(!this._canvas||!this._sprite)return;let s=t*2/e,r=this._canvas.height,o=Math.max(1e-4,r*s),a=this._canvas.width/this._canvas.height,p=o*a;this._sprite.scale.set(p,o,1)}updateWorldSpriteScale(){if(!this._canvas||!this._sprite)return;let t=this._canvas.width/Math.max(1,this._canvas.height),e=Math.max(1,this.options.fontSize??18),n=Math.max(.25,e/32),s=n*t;this._sprite.scale.set(s,n,1)}updateStickyTransform(){if(!this._sprite||!this._cameraRef)return;let t=this._cameraRef.camera,{width:e,height:n}=this.getResolution(),s=E(this.options.screenPosition,g.screenPosition),{px:r,py:o}=this.getScreenPixels(s,e,n),a=Math.max(.001,this.options.zDistance??1),{worldHalfW:p,worldHalfH:l}=this.computeWorldExtents(t,a),T=r/e*2-1,it=1-o/n*2,nt=T*p,rt=it*l;this.group?.position.set(nt,rt,-a),this.updateSpriteScale(l,n)}updateText(t){this.options.text=t,this.redrawText(t),this.options.stickToViewport&&this._cameraRef&&this.updateStickyTransform()}buildInfo(){return{...new f(this).buildDebugInfo(),type:String(i.type),text:this.options.text??"",sticky:this.options.stickToViewport}}textDestroy(){this._texture?.dispose(),this._sprite?.material&&this._sprite.material.dispose(),this._sprite&&this._sprite.removeFromParent(),this.group?.removeFromParent(),this._sprite=null,this._texture=null,this._canvas=null,this._ctx=null,this._cameraRef=null}};function F(...i){return b({args:i,defaultConfig:{...g},EntityClass:_,BuilderClass:O,entityType:_.type,cloneFactory:t=>F(t??{})})}import{Euler as ct,Group as X,Quaternion as ht,Vector3 as mt}from"three";import{TextureLoader as N,SpriteMaterial as Y,Sprite as $,SRGBColorSpace as j}from"three";import{ClampToEdgeWrapping as Q,LinearFilter as ut,NearestFilter as dt}from"three";var q={...C,size:new mt(1,1,1),images:[],animations:[]},L=class extends U{collider(t){let e=x(t.collisionSize,t.size??y);return{shape:{type:"box",halfExtents:[e.x/2,e.y/2,e.z/2]}}}},I=class extends v{createEntity(t){return new S(t)}},ft=Symbol("Sprite"),S=class i extends d{static type=ft;sprites=[];spriteMap=new Map;currentSpriteIndex=0;animations=new Map;currentAnimation=null;currentAnimationFrame="";currentAnimationIndex=0;currentAnimationTime=0;sheetTexture=null;flippedX=!1;constructor(t){super(),this.options=u(q,t),this.prependSetup(this.spriteSetup.bind(this)),this.prependUpdate(this.spriteUpdate.bind(this)),this.onCleanup(this.spriteDestroy.bind(this))}create(){return this.sprites=[],this.spriteMap.clear(),this.animations.clear(),this.currentAnimation=null,this.currentAnimationFrame="",this.currentAnimationIndex=0,this.currentAnimationTime=0,this.sheetTexture=null,this.group=void 0,this.options?.sheet?this.createSpriteFromSheet(this.options.sheet):this.createSpritesFromImages(this.options?.images||[]),this.createAnimations(this.options?.animations||[]),super.create()}createSpritesFromImages(t){let e=new N,n=x(this.options.size,y);t.forEach((s,r)=>{let o=e.load(s.file);o.colorSpace=j,o.anisotropy=D;let a=new Y({map:o,transparent:!0}),p=new $(a);p.position.normalize(),p.scale.set(n.x,n.y,n.z),p.visible=r===0,this.sprites.push(p),this.spriteMap.set(s.name,r)}),this.group=new X,this.group.add(...this.sprites)}createSpriteFromSheet(t){let e=x(this.options.size,y),n=new N().load(t.file);n.colorSpace=j,n.wrapS=Q,n.wrapT=Q;let s=t.filter==="linear"?ut:dt;n.magFilter=s,n.minFilter=s,n.generateMipmaps=!1,n.repeat.set(1/t.columns,1/t.rows);let r=new Y({map:n,transparent:!0}),o=new $(r);o.position.normalize(),o.scale.set(e.x,e.y,e.z),this.sheetTexture=n,this.sprites.push(o),t.frames.forEach((p,l)=>{p&&this.spriteMap.set(p,l)}),this.group=new X,this.group.add(o);let a=t.frames.find(p=>!!p);a&&this.setSprite(a)}createAnimations(t){t.forEach(e=>{let{name:n,frames:s,loop:r=!1,speed:o=1}=e,a={frames:s.map((p,l)=>({key:p,index:l,duration:typeof o=="number"?o:o[l]})),loop:r};this.animations.set(n,a)})}setSprite(t){let n=this.spriteMap.get(t)??0;if(this.currentSpriteIndex=n,this.sheetTexture){this.applySheetFrame(n);return}this.sprites.forEach((s,r)=>{s.visible=this.currentSpriteIndex===r})}setFlipX(t){if(this.flippedX!==t){if(this.flippedX=t,this.sheetTexture){this.applySheetFrame(this.currentSpriteIndex);return}this.sprites.forEach(e=>{e.material.map?.repeat.setX(t?-1:1),e.material.map?.offset.setX(t?1:0)})}}isFlippedX(){return this.flippedX}applySheetFrame(t){let e=this.options.sheet,n=this.sheetTexture;if(!e||!n)return;let s=t%e.columns,r=Math.floor(t/e.columns),o=1/e.columns,a=1/e.rows;n.repeat.x=this.flippedX?-o:o,n.offset.x=this.flippedX?(s+1)*o:s*o,n.offset.y=1-(r+1)*a}setAnimation(t,e){let n=this.animations.get(t);if(!n)return;let{loop:s,frames:r}=n;if(r.length!==0){for(t!==this.currentAnimation?(this.currentAnimation=t,this.currentAnimationIndex=0,this.currentAnimationTime=0):this.currentAnimationTime+=e;;){let o=r[this.currentAnimationIndex].duration;if(!(o>0)||this.currentAnimationTime<o)break;if(this.currentAnimationTime-=o,this.currentAnimationIndex+1<r.length)this.currentAnimationIndex++;else if(s)this.currentAnimationIndex=0;else{this.currentAnimationTime=0;break}}this.currentAnimationFrame=r[this.currentAnimationIndex].key,this.setSprite(this.currentAnimationFrame)}}getCurrentRotationQuaternion(){return this.transformStore?.dirty.rotation?this.transformStore.rotation:this.body?.rotation?.()??null}syncSpriteMaterials(){let t=this.getCurrentRotationQuaternion();this.sprites.forEach(e=>{if(e.material&&t){let s=new ht(t.x,t.y,t.z,t.w),r=new ct().setFromQuaternion(s,"XYZ");e.material.rotation=r.z}let n=x(this.options.size,y);e.scale.set(n.x,n.y,n.z)})}spriteSetup(t){this.syncSpriteMaterials()}spriteUpdate(t){this.syncSpriteMaterials()}spriteDestroy(t){this.sprites.forEach(e=>{e.removeFromParent()}),this.group?.remove(...this.sprites),this.group?.removeFromParent(),this.sheetTexture?.dispose(),this.sheetTexture=null}buildInfo(){return{...new f(this).buildDebugInfo(),type:String(i.type)}}};function z(...i){return b({args:i,defaultConfig:q,EntityClass:S,BuilderClass:I,CollisionBuilderClass:L,entityType:S.type,cloneFactory:t=>z(t??{})})}import{Color as tt,Group as xt}from"three";import{Line2NodeMaterial as gt}from"three/webgpu";import{Line2 as _t}from"three/addons/lines/webgpu/Line2.js";import{Color as J}from"three";import{LineGeometry as yt}from"three/addons/lines/LineGeometry.js";function R(i){let t=[];for(let e of i){let{x:n,y:s,z:r}=m(e,h);t.push(n,s,r)}return t}function P(i,t,e){if(!i||i.length===0)return;let n=[],s=new J(e);for(let r=0;r<t;r++){let o=i[r]??i[i.length-1]??e,a=new J(o??s);n.push(a.r,a.g,a.b)}return n}function K(i){let t=new yt,e=R(i.points);t.setPositions(e);let n=P(i.colors,i.points.length,"#ffffff");return n&&t.setColors(n),t}var c={...C,points:[{x:0,y:0,z:0},{x:1,y:0,z:0}],linewidth:1,worldUnits:!0,alphaToCoverage:!1,opacity:1,transparent:!1,dashed:!1,dashSize:1,gapSize:1,pickThreshold:0},St=Symbol("Line");function Z(i,t){if(!i||i.length<2)throw new Error(`${t}: at least two points are required`);return i}function et(i){return i instanceof tt?i.clone():new tt(i??"#ffffff")}function Ct(i){let t=!!i.colors?.length,e=new gt({color:et(i.color).getHex(),linewidth:i.linewidth??c.linewidth,worldUnits:i.worldUnits??c.worldUnits,vertexColors:t,dashed:i.dashed??!1,dashSize:i.dashSize??c.dashSize,gapSize:i.gapSize??c.gapSize,transparent:i.transparent??!1,opacity:i.opacity??1});return e.alphaToCoverage=i.alphaToCoverage??!1,e}function vt(i){return!i.point||!i.pointOnLine||i.faceIndex==null?null:{point:i.point.clone(),pointOnLine:i.pointOnLine.clone(),faceIndex:i.faceIndex,distance:i.distance}}function bt(i,t,e={}){let n=t.getLineObject();if(!n)return null;let s=e.threshold??t.options.pickThreshold??0,r=i.params.Line2??{threshold:0};r.threshold=s,i.params.Line2=r;let a=i.intersectObject(n,!1)[0];return a?vt(a):null}var A=class i extends d{static type=St;_line=null;_geometry=null;_material=null;constructor(t){super();let e=u(c,t);e.points=Z(e.points,"ZylemLine").map(n=>m(n,h)),this.options=e}create(){return this.disposeLineResources(),this.group=new xt,this.rebuildLine(),this.applyGroupPosition(),super.create()}setPoints(t,e){if(Z(t,"setPoints"),this.options.points=t.map(s=>m(s,h)),e&&(this.options.colors=e),!this._line||!this._geometry||!this._material)return this;this._geometry.setPositions(R(this.options.points));let n=P(this.options.colors,this.options.points.length,et(this.options.color));return n&&this._geometry.setColors(n),this._material.vertexColors=!!this.options.colors?.length,this.options.dashed&&this._line.computeLineDistances(),this._geometry.computeBoundingBox(),this._geometry.computeBoundingSphere(),this}getLineObject(){return this._line}pickFromRaycaster(t,e={}){return bt(t,this,e)}buildInfo(){return{...new f(this).buildDebugInfo(),type:String(i.type),points:this.options.points.length,linewidth:this.options.linewidth??c.linewidth,worldUnits:this.options.worldUnits??c.worldUnits}}rebuildLine(){this._geometry=K({points:this.options.points,colors:this.options.colors}),this._material=Ct(this.options),this._line=new _t(this._geometry,this._material),this.options.dashed&&this._line.computeLineDistances(),this.group?.add(this._line)}applyGroupPosition(){if(!this.group)return;let t=m(this.options.position,h);this.group.position.set(t.x,t.y,t.z)}_cleanup(t){this.disposeLineResources(),super._cleanup(t)}disposeLineResources(){this._line?.removeFromParent(),this._geometry?.dispose(),this._material?.dispose(),this._line=null,this._geometry=null,this._material=null}};function M(...i){let t=V(i,c);Z(t.points,"createLine");let e=new A(t);return G(e,n=>M(n??{}))}var k={registry:new Map,register(i,t){this.registry.set(i,t)},createFromBlueprint(i){let t=this.registry.get(i.type);if(!t)throw new Error(`Unknown entity type: ${i.type}`);let e={...i.data,position:i.position?{x:i.position[0],y:i.position[1],z:0}:void 0,name:i.id};return t(e)}};k.register("text",i=>F(i));k.register("sprite",i=>z(i));k.register("line",i=>M(i));function ge(i){return{template:i,generate(t){let e=[];for(let n=0;n<t;n++)e.push(i.clone());return e}}}export{lt as a,_ as b,F as c,ft as d,S as e,z as f,St as g,bt as h,A as i,M as j,k,ge as l};
1
+ import{a as f}from"./chunk-X7T7QRYP.js";import{b as u,r as C,s as G,t as d,v as D,w as U,y as v,z as b}from"./chunk-KP6DLLJO.js";import{e as V}from"./chunk-6FGXC4T6.js";import{c as h,d as y,h as m,i as E,j as x}from"./chunk-7WRQ2UAN.js";import{Color as B,Group as st,Sprite as ot,SpriteMaterial as at,CanvasTexture as H,LinearFilter as w,Vector2 as pt,ClampToEdgeWrapping as W}from"three";var g={position:void 0,text:"",fontFamily:'Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace',fontSize:18,fontColor:"#FFFFFF",backgroundColor:null,padding:4,stickToViewport:!0,screenPosition:new pt(24,24),zDistance:1},O=class extends v{createEntity(t){return new _(t)}},lt=Symbol("Text"),_=class i extends d{static type=lt;_sprite=null;_texture=null;_canvas=null;_ctx=null;_cameraRef=null;_lastCanvasW=0;_lastCanvasH=0;constructor(t){super(),this.options=u(g,t),this.options.screenPosition=E(this.options.screenPosition,g.screenPosition),this.prependSetup(this.textSetup.bind(this)),this.prependUpdate(this.textUpdate.bind(this)),this.onCleanup(this.textDestroy.bind(this))}create(){return this._sprite=null,this._texture=null,this._canvas=null,this._ctx=null,this._lastCanvasW=0,this._lastCanvasH=0,this.group=new st,this.createSprite(),super.create()}createSprite(){this._canvas=document.createElement("canvas"),this._ctx=this._canvas.getContext("2d"),this._texture=new H(this._canvas),this._texture.minFilter=w,this._texture.magFilter=w;let t=new at({map:this._texture,transparent:!0,depthTest:!1,depthWrite:!1,alphaTest:.5});this._sprite=new ot(t),this.group?.add(this._sprite),this.redrawText(this.options.text??"")}measureAndResizeCanvas(t,e,n,s){if(!this._canvas||!this._ctx)return{sizeChanged:!1};this._ctx.font=`${e}px ${n}`;let r=this._ctx.measureText(t),o=Math.ceil(r.width),a=Math.ceil(e*1.4),p=Math.max(2,o+s*2),l=Math.max(2,a+s*2),T=p!==this._lastCanvasW||l!==this._lastCanvasH;return this._canvas.width=p,this._canvas.height=l,this._lastCanvasW=p,this._lastCanvasH=l,{sizeChanged:T}}drawCenteredText(t,e,n){!this._canvas||!this._ctx||(this._ctx.font=`${e}px ${n}`,this._ctx.textAlign="center",this._ctx.textBaseline="middle",this._ctx.clearRect(0,0,this._canvas.width,this._canvas.height),this.options.backgroundColor&&(this._ctx.fillStyle=this.toCssColor(this.options.backgroundColor),this._ctx.fillRect(0,0,this._canvas.width,this._canvas.height)),this._ctx.fillStyle=this.toCssColor(this.options.fontColor??"#FFFFFF"),this._ctx.fillText(t,this._canvas.width/2,this._canvas.height/2))}updateTexture(t){!this._texture||!this._canvas||(t&&(this._texture.dispose(),this._texture=new H(this._canvas),this._texture.minFilter=w,this._texture.magFilter=w,this._texture.wrapS=W,this._texture.wrapT=W),this._texture.image=this._canvas,this._texture.needsUpdate=!0,this._sprite&&this._sprite.material&&(this._sprite.material.map=this._texture,this._sprite.material.needsUpdate=!0))}redrawText(t){if(!this._canvas||!this._ctx)return;let e=this.options.fontSize??18,n=this.options.fontFamily??g.fontFamily,s=this.options.padding??4,{sizeChanged:r}=this.measureAndResizeCanvas(t,e,n,s);this.drawCenteredText(t,e,n),this.updateTexture(!!r),this.options.stickToViewport&&this._cameraRef?this.updateStickyTransform():this.updateWorldSpriteScale()}toCssColor(t){return typeof t=="string"?t:`#${(t instanceof B?t:new B(t)).getHexString()}`}textSetup(t){this._cameraRef=t.camera,this.options.stickToViewport&&this._cameraRef&&(this._cameraRef.camera.add(this.group),this.updateStickyTransform())}textUpdate(t){this._sprite&&this.options.stickToViewport&&this._cameraRef&&this.updateStickyTransform()}getResolution(){return{width:this._cameraRef?.screenResolution.x??1,height:this._cameraRef?.screenResolution.y??1}}getScreenPixels(t,e,n){let s=t.x>=0&&t.x<=1,r=t.y>=0&&t.y<=1;return{px:s?t.x*e:t.x,py:r?t.y*n:t.y}}computeWorldExtents(t,e){let n=1,s=1;if(t.isPerspectiveCamera){let r=t,o=Math.tan(r.fov*Math.PI/180/2)*e;n=o*r.aspect,s=o}else if(t.isOrthographicCamera){let r=t;n=(r.right-r.left)/2,s=(r.top-r.bottom)/2}return{worldHalfW:n,worldHalfH:s}}updateSpriteScale(t,e){if(!this._canvas||!this._sprite)return;let s=t*2/e,r=this._canvas.height,o=Math.max(1e-4,r*s),a=this._canvas.width/this._canvas.height,p=o*a;this._sprite.scale.set(p,o,1)}updateWorldSpriteScale(){if(!this._canvas||!this._sprite)return;let t=this._canvas.width/Math.max(1,this._canvas.height),e=Math.max(1,this.options.fontSize??18),n=Math.max(.25,e/32),s=n*t;this._sprite.scale.set(s,n,1)}updateStickyTransform(){if(!this._sprite||!this._cameraRef)return;let t=this._cameraRef.camera,{width:e,height:n}=this.getResolution(),s=E(this.options.screenPosition,g.screenPosition),{px:r,py:o}=this.getScreenPixels(s,e,n),a=Math.max(.001,this.options.zDistance??1),{worldHalfW:p,worldHalfH:l}=this.computeWorldExtents(t,a),T=r/e*2-1,it=1-o/n*2,nt=T*p,rt=it*l;this.group?.position.set(nt,rt,-a),this.updateSpriteScale(l,n)}updateText(t){this.options.text=t,this.redrawText(t),this.options.stickToViewport&&this._cameraRef&&this.updateStickyTransform()}buildInfo(){return{...new f(this).buildDebugInfo(),type:String(i.type),text:this.options.text??"",sticky:this.options.stickToViewport}}textDestroy(){this._texture?.dispose(),this._sprite?.material&&this._sprite.material.dispose(),this._sprite&&this._sprite.removeFromParent(),this.group?.removeFromParent(),this._sprite=null,this._texture=null,this._canvas=null,this._ctx=null,this._cameraRef=null}};function F(...i){return b({args:i,defaultConfig:{...g},EntityClass:_,BuilderClass:O,entityType:_.type,cloneFactory:t=>F(t??{})})}import{Euler as ct,Group as X,Quaternion as ht,Vector3 as mt}from"three";import{TextureLoader as N,SpriteMaterial as Y,Sprite as $,SRGBColorSpace as j}from"three";import{ClampToEdgeWrapping as Q,LinearFilter as ut,NearestFilter as dt}from"three";var q={...C,size:new mt(1,1,1),images:[],animations:[]},L=class extends U{collider(t){let e=x(t.collisionSize,t.size??y);return{shape:{type:"box",halfExtents:[e.x/2,e.y/2,e.z/2]}}}},I=class extends v{createEntity(t){return new S(t)}},ft=Symbol("Sprite"),S=class i extends d{static type=ft;sprites=[];spriteMap=new Map;currentSpriteIndex=0;animations=new Map;currentAnimation=null;currentAnimationFrame="";currentAnimationIndex=0;currentAnimationTime=0;sheetTexture=null;flippedX=!1;constructor(t){super(),this.options=u(q,t),this.prependSetup(this.spriteSetup.bind(this)),this.prependUpdate(this.spriteUpdate.bind(this)),this.onCleanup(this.spriteDestroy.bind(this))}create(){return this.sprites=[],this.spriteMap.clear(),this.animations.clear(),this.currentAnimation=null,this.currentAnimationFrame="",this.currentAnimationIndex=0,this.currentAnimationTime=0,this.sheetTexture=null,this.group=void 0,this.options?.sheet?this.createSpriteFromSheet(this.options.sheet):this.createSpritesFromImages(this.options?.images||[]),this.createAnimations(this.options?.animations||[]),super.create()}createSpritesFromImages(t){let e=new N,n=x(this.options.size,y);t.forEach((s,r)=>{let o=e.load(s.file);o.colorSpace=j,o.anisotropy=V;let a=new Y({map:o,transparent:!0}),p=new $(a);p.position.normalize(),p.scale.set(n.x,n.y,n.z),p.visible=r===0,this.sprites.push(p),this.spriteMap.set(s.name,r)}),this.group=new X,this.group.add(...this.sprites)}createSpriteFromSheet(t){let e=x(this.options.size,y),n=new N().load(t.file);n.colorSpace=j,n.wrapS=Q,n.wrapT=Q;let s=t.filter==="linear"?ut:dt;n.magFilter=s,n.minFilter=s,n.generateMipmaps=!1,n.repeat.set(1/t.columns,1/t.rows);let r=new Y({map:n,transparent:!0}),o=new $(r);o.position.normalize(),o.scale.set(e.x,e.y,e.z),this.sheetTexture=n,this.sprites.push(o),t.frames.forEach((p,l)=>{p&&this.spriteMap.set(p,l)}),this.group=new X,this.group.add(o);let a=t.frames.find(p=>!!p);a&&this.setSprite(a)}createAnimations(t){t.forEach(e=>{let{name:n,frames:s,loop:r=!1,speed:o=1}=e,a={frames:s.map((p,l)=>({key:p,index:l,duration:typeof o=="number"?o:o[l]})),loop:r};this.animations.set(n,a)})}setSprite(t){let n=this.spriteMap.get(t)??0;if(this.currentSpriteIndex=n,this.sheetTexture){this.applySheetFrame(n);return}this.sprites.forEach((s,r)=>{s.visible=this.currentSpriteIndex===r})}setFlipX(t){if(this.flippedX!==t){if(this.flippedX=t,this.sheetTexture){this.applySheetFrame(this.currentSpriteIndex);return}this.sprites.forEach(e=>{e.material.map?.repeat.setX(t?-1:1),e.material.map?.offset.setX(t?1:0)})}}isFlippedX(){return this.flippedX}applySheetFrame(t){let e=this.options.sheet,n=this.sheetTexture;if(!e||!n)return;let s=t%e.columns,r=Math.floor(t/e.columns),o=1/e.columns,a=1/e.rows;n.repeat.x=this.flippedX?-o:o,n.offset.x=this.flippedX?(s+1)*o:s*o,n.offset.y=1-(r+1)*a}setAnimation(t,e){let n=this.animations.get(t);if(!n)return;let{loop:s,frames:r}=n;if(r.length!==0){for(t!==this.currentAnimation?(this.currentAnimation=t,this.currentAnimationIndex=0,this.currentAnimationTime=0):this.currentAnimationTime+=e;;){let o=r[this.currentAnimationIndex].duration;if(!(o>0)||this.currentAnimationTime<o)break;if(this.currentAnimationTime-=o,this.currentAnimationIndex+1<r.length)this.currentAnimationIndex++;else if(s)this.currentAnimationIndex=0;else{this.currentAnimationTime=0;break}}this.currentAnimationFrame=r[this.currentAnimationIndex].key,this.setSprite(this.currentAnimationFrame)}}getCurrentRotationQuaternion(){return this.transformStore?.dirty.rotation?this.transformStore.rotation:this.body?.rotation?.()??null}syncSpriteMaterials(){let t=this.getCurrentRotationQuaternion();this.sprites.forEach(e=>{if(e.material&&t){let s=new ht(t.x,t.y,t.z,t.w),r=new ct().setFromQuaternion(s,"XYZ");e.material.rotation=r.z}let n=x(this.options.size,y);e.scale.set(n.x,n.y,n.z)})}spriteSetup(t){this.syncSpriteMaterials()}spriteUpdate(t){this.syncSpriteMaterials()}spriteDestroy(t){this.sprites.forEach(e=>{e.removeFromParent()}),this.group?.remove(...this.sprites),this.group?.removeFromParent(),this.sheetTexture?.dispose(),this.sheetTexture=null}buildInfo(){return{...new f(this).buildDebugInfo(),type:String(i.type)}}};function z(...i){return b({args:i,defaultConfig:q,EntityClass:S,BuilderClass:I,CollisionBuilderClass:L,entityType:S.type,cloneFactory:t=>z(t??{})})}import{Color as tt,Group as xt}from"three";import{Line2NodeMaterial as gt}from"three/webgpu";import{Line2 as _t}from"three/addons/lines/webgpu/Line2.js";import{Color as J}from"three";import{LineGeometry as yt}from"three/addons/lines/LineGeometry.js";function R(i){let t=[];for(let e of i){let{x:n,y:s,z:r}=m(e,h);t.push(n,s,r)}return t}function P(i,t,e){if(!i||i.length===0)return;let n=[],s=new J(e);for(let r=0;r<t;r++){let o=i[r]??i[i.length-1]??e,a=new J(o??s);n.push(a.r,a.g,a.b)}return n}function K(i){let t=new yt,e=R(i.points);t.setPositions(e);let n=P(i.colors,i.points.length,"#ffffff");return n&&t.setColors(n),t}var c={...C,points:[{x:0,y:0,z:0},{x:1,y:0,z:0}],linewidth:1,worldUnits:!0,alphaToCoverage:!1,opacity:1,transparent:!1,dashed:!1,dashSize:1,gapSize:1,pickThreshold:0},St=Symbol("Line");function Z(i,t){if(!i||i.length<2)throw new Error(`${t}: at least two points are required`);return i}function et(i){return i instanceof tt?i.clone():new tt(i??"#ffffff")}function Ct(i){let t=!!i.colors?.length,e=new gt({color:et(i.color).getHex(),linewidth:i.linewidth??c.linewidth,worldUnits:i.worldUnits??c.worldUnits,vertexColors:t,dashed:i.dashed??!1,dashSize:i.dashSize??c.dashSize,gapSize:i.gapSize??c.gapSize,transparent:i.transparent??!1,opacity:i.opacity??1});return e.alphaToCoverage=i.alphaToCoverage??!1,e}function vt(i){return!i.point||!i.pointOnLine||i.faceIndex==null?null:{point:i.point.clone(),pointOnLine:i.pointOnLine.clone(),faceIndex:i.faceIndex,distance:i.distance}}function bt(i,t,e={}){let n=t.getLineObject();if(!n)return null;let s=e.threshold??t.options.pickThreshold??0,r=i.params.Line2??{threshold:0};r.threshold=s,i.params.Line2=r;let a=i.intersectObject(n,!1)[0];return a?vt(a):null}var A=class i extends d{static type=St;_line=null;_geometry=null;_material=null;constructor(t){super();let e=u(c,t);e.points=Z(e.points,"ZylemLine").map(n=>m(n,h)),this.options=e}create(){return this.disposeLineResources(),this.group=new xt,this.rebuildLine(),this.applyGroupPosition(),super.create()}setPoints(t,e){if(Z(t,"setPoints"),this.options.points=t.map(s=>m(s,h)),e&&(this.options.colors=e),!this._line||!this._geometry||!this._material)return this;this._geometry.setPositions(R(this.options.points));let n=P(this.options.colors,this.options.points.length,et(this.options.color));return n&&this._geometry.setColors(n),this._material.vertexColors=!!this.options.colors?.length,this.options.dashed&&this._line.computeLineDistances(),this._geometry.computeBoundingBox(),this._geometry.computeBoundingSphere(),this}getLineObject(){return this._line}pickFromRaycaster(t,e={}){return bt(t,this,e)}buildInfo(){return{...new f(this).buildDebugInfo(),type:String(i.type),points:this.options.points.length,linewidth:this.options.linewidth??c.linewidth,worldUnits:this.options.worldUnits??c.worldUnits}}rebuildLine(){this._geometry=K({points:this.options.points,colors:this.options.colors}),this._material=Ct(this.options),this._line=new _t(this._geometry,this._material),this.options.dashed&&this._line.computeLineDistances(),this.group?.add(this._line)}applyGroupPosition(){if(!this.group)return;let t=m(this.options.position,h);this.group.position.set(t.x,t.y,t.z)}_cleanup(t){this.disposeLineResources(),super._cleanup(t)}disposeLineResources(){this._line?.removeFromParent(),this._geometry?.dispose(),this._material?.dispose(),this._line=null,this._geometry=null,this._material=null}};function M(...i){let t=G(i,c);Z(t.points,"createLine");let e=new A(t);return D(e,n=>M(n??{}))}var k={registry:new Map,register(i,t){this.registry.set(i,t)},createFromBlueprint(i){let t=this.registry.get(i.type);if(!t)throw new Error(`Unknown entity type: ${i.type}`);let e={...i.data,position:i.position?{x:i.position[0],y:i.position[1],z:0}:void 0,name:i.id};return t(e)}};k.register("text",i=>F(i));k.register("sprite",i=>z(i));k.register("line",i=>M(i));function ge(i){return{template:i,generate(t){let e=[];for(let n=0;n<t;n++)e.push(i.clone());return e}}}export{lt as a,_ as b,F as c,ft as d,S as e,z as f,St as g,bt as h,A as i,M as j,k,ge as l};
@@ -0,0 +1,24 @@
1
+ import{b as ye,d as G,j as Me,u as L,v as E}from"./chunk-BWOZF5YK.js";import{b as Be}from"./chunk-7GYFZKK7.js";import{b as y}from"./chunk-Q2YDBMVY.js";import{b as Re,c as Te}from"./chunk-EYDC2PMO.js";import{c as Ce,e as xe,f as Ge}from"./chunk-2HSR5XDQ.js";import{b as $,c as Se,d as W,e as j,g as we}from"./chunk-G3TBBZUI.js";import{d as g,g as fe,h as K}from"./chunk-EVMLNMGU.js";import{k as Ie}from"./chunk-7JSZEEAE.js";import{a as Q,t as ee}from"./chunk-KP6DLLJO.js";import{j as Ee}from"./chunk-6FGXC4T6.js";import{a as ve,b}from"./chunk-AIQ6IVT5.js";import{c as S}from"./chunk-D2PATZCC.js";import{c as pe,d as C,e as de,h as ce,i as me,j as he,k as J,l as x,m as ge}from"./chunk-4QLJUQSJ.js";import{j as q}from"./chunk-7WRQ2UAN.js";import{g as be}from"./chunk-PCFF4LLO.js";import{l as v}from"./chunk-UG22Z42P.js";function Fe(){return{pressed:!1,released:!1,held:0}}function Xe(){return{value:0,held:0}}function k(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?Fe():a?e?{pressed:a.pressed||e.pressed,released:a.released||e.released,held:a.held+e.held}:{...a}:{...e}}function f(a,e){return!a&&!e?Xe():a?e?{value:a.value+e.value,held:a.held+e.held}:{...a}:{...e}}var w=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=k(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]=f(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 D=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}};import{subscribe as Ye}from"valtio/vanilla";var Ze=.002;function A(a,e,t){return Math.max(e,Math.min(t,a))}function Je(a){if(a instanceof HTMLCanvasElement)return a;let e=a.querySelector("canvas");if(e instanceof HTMLCanvasElement)return e;for(let t of a.querySelectorAll("*")){let n=t.shadowRoot;if(!n)continue;let i=n.querySelector("canvas");if(i instanceof HTMLCanvasElement)return i}return null}var R=class{buttonStates=new Map;analogStates=new Map;compiledMapping;movementX=0;movementY=0;pointerX=.5;pointerY=.5;pointerCenterX=0;pointerCenterY=0;mouseButtonDown=new Set;sensitivity;usePointerLock;lookMode;isLocked=!1;targetElement;debugUnsubscribe=null;updatePointerPosition(e,t){this.pointerX=e/window.innerWidth,this.pointerY=t/window.innerHeight;let n=Je(this.targetElement);if(n){let i=n.getBoundingClientRect();if(i.width>0&&i.height>0){let o=i.left+i.width/2,r=i.top+i.height/2;this.pointerCenterX=A((e-o)/(i.width/2),-1,1),this.pointerCenterY=A((t-r)/(i.height/2),-1,1);return}}this.pointerCenterX=A((this.pointerX-.5)*2,-1,1),this.pointerCenterY=A((this.pointerY-.5)*2,-1,1)}onMouseMove=e=>{this.updatePointerPosition(e.clientX,e.clientY),!(g.enabled||this.lookMode==="screenCenter")&&(this.movementX+=e.movementX,this.movementY+=e.movementY)};onMouseDown=e=>{let t=e.target;t instanceof HTMLCanvasElement&&this.targetElement.contains(t)&&(this.mouseButtonDown.add(e.button),this.usePointerLock&&!this.isLocked&&!g.enabled&&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??Ze,this.lookMode=e?.lookMode??"delta",this.usePointerLock=e?.pointerLock??!1,this.compiledMapping=k(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),this.debugUnsubscribe=Ye(g,()=>{g.enabled&&document.pointerLockElement===this.targetElement&&document.exitPointerLock()}))}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.debugUnsubscribe?.(),this.debugUnsubscribe=null,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]=f(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){g.enabled&&(this.movementX=0,this.movementY=0);let t={value:0,held:0},n=this.lookMode==="delta",i={axes:{Horizontal:t,Vertical:t,SecondaryHorizontal:n?this.handleMovementAxis("x",e):t,SecondaryVertical:n?this.handleMovementAxis("y",e):t},shoulders:{LTrigger:this.handleMouseButton(0,e),RTrigger:this.handleMouseButton(2,e)},pointer:{x:this.pointerX,y:this.pointerY,centerX:this.pointerCenterX,centerY:this.pointerCenterY}};return this.movementX=0,this.movementY=0,this.applyCustomMapping(i,e)}getName(){return"mouse"}isConnected(){return!0}};function T(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 Ke=["A","B","X","Y","Start","Select","L","R","LTrigger","RTrigger","Up","Down","Left","Right"],$e=new Set(["flex","flexGrow","flexShrink","fontWeight","lineHeight","opacity","order","zIndex","zoom"]),We={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"}},je={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}}},M=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:T()}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),B(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 Ke){let i=We[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=je[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",B(n,t.position),B(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??Qe(t.label),n.appendChild(i),n.addEventListener("pointerdown",r=>{if(!Pe(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",B(n,t.position),B(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??et(),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??tt(),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(!Pe(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]=f(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=qe(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 B(a,e){if(e)for(let[t,n]of Object.entries(e)){if(n==null)continue;let i=typeof n=="number"&&!$e.has(t)?`${n}px`:String(n);t.includes("-")?a.style.setProperty(t,i):a.style[t]=i}}function qe(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 Qe(a){let e=nt(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 et(){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 tt(){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 nt(a){return a.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;").replaceAll("'","&#39;")}function Pe(a){return a.pointerType==="touch"}var z=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 D(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 w||l instanceof R||l instanceof M?(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 w(e.key,{includeDefaultBase:i}))}else t&&n.push(new w);return e?.mouse&&n.push(new R(e.mouse,this.mouseTargetElement)),e?.touch&&n.push(new M(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:f(e.axes?.Horizontal,t.axes?.Horizontal),Vertical:f(e.axes?.Vertical,t.axes?.Vertical),SecondaryHorizontal:f(e.axes?.SecondaryHorizontal,t.axes?.SecondaryHorizontal),SecondaryVertical:f(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 V=class{_previousTime;_currentTime;_startTime;_delta;_elapsed;_timescale;_document;_pageVisibilityHandler;constructor(){this._previousTime=0,this._currentTime=0,this._startTime=te(),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=it.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=te()-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:te())-this._startTime,this._delta=(this._currentTime-this._previousTime)*this._timescale,this._elapsed+=this._delta),this}};function te(){return performance.now()}function it(){this._document.hidden===!1&&this.reset()}var I={FourByThree:1.3333333333333333,SixteenByNine:1.7777777777777777,NineBySixteen:.5625,TwentyOneByNine:2.3333333333333335,OneByOne:1},H=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 Le={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 ne(a){return Le[a].displayAspect}function ie(a,e){let t=Le[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 ae(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 oe=null,se=class{constructor(e,t,n,i,o,r,s,l,u,m,p,h,Z){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=h;this.canvas=Z}};function at(a={}){return a.deviceProfile==="mobile"?!0:a.deviceProfile==="desktop"?!1:a.viewportSize?T({viewportSize:a.viewportSize,allowViewportOnly:!0}):T()}function ot(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 st(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:I.SixteenByNine,fullscreen:!0,bodyBackground:"#000000",containerId:e}}var ke=360;function De(a,e){if(!a)return;if(typeof a=="string"){if(a==="native")return oe;let i=ae(a);if(i)return i;if(e){let o=ie(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 rt(a,e,t,n){if(typeof a=="number")return a;if(typeof a=="string")return I[a]??t;if(e)try{return ne(e)||t}catch{return t}return n?n.width/n.height:t}function lt(a){let e=Number.isFinite(a)&&a>0?a:I.SixteenByNine;if(e>=1){let i=ke;return{width:Math.round(i*e),height:i}}let t=ke,n=Math.round(t/e);return{width:t,height:n}}function P(a,e={}){let t=st({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=ot(n,a?.container??null),o=a?.mobile,r=at(e),s=r?o?.preset??a?.preset:a?.preset,l=De(a?.resolution,a?.preset),u=De(o?.resolution,o?.preset??a?.preset),m=(r?Ae(u):void 0)??Ae(l),p=r?o?.aspectRatio??a?.aspectRatio:a?.aspectRatio,h=rt(p,s,t.aspectRatio,m),Z=ut(r,u,l,h),Oe=a?.fullscreen??t.fullscreen,Ue=a?.bodyBackground??t.bodyBackground,Ne=a?.canvas??void 0,_e=pt(a?.input??t.input,o?.controls);return new se(a?.id??t.id,a?.globals??t.globals,a?.stages??t.stages,!!(a?.debug??t.debug),a?.time??t.time,_e,h,Z,Oe,Ue,i,n,Ne)}function Ae(a){if(a)return a}function ut(a,e,t,n){if(a)return e===oe?void 0:e??lt(n);if(t!==oe)return t}function pt(a,e){if(!e)return a;let n=be("p1",{enabled:"auto",...e===!0?{}:e});return v(n,a??{})}function dt(a){return{...a}}var O=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 H({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 ct from"stats.js";import{subscribe as mt}from"valtio/vanilla";var U=class{statsRef=null;unsubscribe=null;constructor(){this.updateDebugUI(),this.unsubscribe=mt(g,()=>{this.updateDebugUI()})}begin(){this.statsRef?.begin()}end(){this.statsRef?.end()}updateDebugUI(){g.enabled&&!this.statsRef?(this.statsRef=new ct,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)):!g.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 N=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}`;b.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=[]}};import{getZylemBridge as ht}from"@zylem/bridge";var _=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 F=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;loadInFlight=!1;hasStarted=!1;debugDelegate=null;loadingDelegate=new N;rendererObserver=new _;eventBusUnsubscribes=[];thumbnailUnsubscribes=[];lastPublishedGameConfig=null;gameBridge=new we;catalogUnsubscribe=null;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 V,this.timer.connect(document),this.sourceOptions={...e},this.displayRuntime={...n};let i=P(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 z(i.input,{targetElement:this.gameCanvas?.getOverlayContainer(),mouseTargetElement:this.gameCanvas?.container}),this.loadDebugOptions(e),this.setGlobals(e),Re(),Te(),this.gameBridge.connect({resolveEntity:o=>this.currentStage()?.wrappedStage?.entityDelegate.childrenMap.get(o)??null,setStageVariable:(o,r)=>{let s=this.currentStage()?.wrappedStage?.state;s&&(s.variables[o]=r)},createEntity:(o,r,s)=>{this.createCatalogEntity(o,r,s)},applySceneOperation:(o,r)=>{this.currentStage()?.wrappedStage?.debugDelegate?.applySceneOperation(o,r)},pickEntity:o=>this.pickEntityAtNdc(o),applySwatches:o=>{let r=this.currentStage()?.wrappedStage?.debugDelegate;return r?r.applySwatches(o):{results:o.uuids.flatMap(s=>o.swatches.map(l=>({uuid:s,kind:l.kind,source:l.source,ok:!1,reason:"entity-not-found"}))),entries:[]}}}),this.publishEntityCatalog(),this.catalogUnsubscribe=Ge(()=>this.publishEntityCatalog())}pickEntityAtNdc(e){let t=this.currentStage()?.wrappedStage,n=t?.debugDelegate?.pickAtNdc(e.x,e.y);if(!t||!n)return null;let i=t.entityDelegate.childrenMap.get(n.uuid);return i?this.buildEntitySummary(i)??{uuid:n.uuid,name:n.name||"Unnamed",type:j(i),position:W(i).position,rotation:W(i).rotation,scale:$(i)}:null}publishEntityCatalog(){this.gameBridge.publishCatalog(xe())}createCatalogEntity(e,t,n){let i=this.currentStage()?.wrappedStage,o=Ce(e);if(!i||!o)return;let r=n?.position??{x:0,y:0,z:0},s=o.create({position:r,props:{...o.defaultProps??{},...t??{}}});s&&Promise.resolve(s).then(l=>l&&i.entityDelegate.spawnEntity(l)).catch(l=>{console.error("entity:create failed",l)})}setDisplayRuntime(e){this.displayRuntime={...e};let t=P(this.sourceOptions,this.displayRuntime);this.resolvedConfig=t,this.rendererObserver.setConfig(t),this.gameCanvas?.setAspectRatio(t.aspectRatio),this.publishGameConfig()}loadGameCanvas(e){this.gameCanvas=new O({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&&(g.enabled=!!e.debug),this.debugDelegate=new U}isLoading(){return this.loadInFlight}async loadStage(e,t=0,n){if(this.loadInFlight){console.warn("loadStage ignored: a stage load is already in progress");return}this.loadInFlight=!0;try{await this.performLoadStage(e,t,n)}finally{this.loadInFlight=!1}}async performLoadStage(e,t=0,n){let i=n?Be(n):null,o=this.currentStage()??null,r=o?.wrappedStage??null,s=r?.scene?.scene??null,l=r?.cameraManagerRef?.primaryCamera?.camera??r?.cameraRef?.camera??null;i&&this.rendererManager?.initialized&&o&&s&&l&&this.rendererManager.beginSnapshotTransition(i,s,l),this.unloadCurrentStage();let m=e.options[0];if(this.loadingDelegate.wireStageLoading(e,t),this.rendererManager||(this.rendererManager=new ye,await this.rendererManager.initRenderer()),y.setRenderer(this.rendererManager.renderer),await e.load(this.id,m?.camera,this.rendererManager),this.stageMap.set(e.wrappedStage.uuid,e),this.currentStageId=e.wrappedStage.uuid,this.defaultCamera=e.wrappedStage.cameraRef,this.wireEntityThumbnails(e),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 p=this.params(),h={...this.stageSetupParams};h.inputs=p.inputs,h.globals=p.globals,h.camera=p.camera,h.stage=p.stage,h.game=p.game,h.me=e.wrappedStage,e.start(h)}this.publishGameConfig(),this.publishStageSnapshot()}applyInputConfig(e){let t=v(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(this.clearEntityThumbnailWiring(),y.clear(),e.onInputConfigChanged=null,e?.wrappedStage){try{e.wrappedStage.nodeDestroy({me:e.wrappedStage,globals:C.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`),de(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=he(),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.currentStage();if(r!==t||!r?.wrappedStage){this.totalTime+=o,C.time=this.totalTime;return}let s=this.stageUpdateParams;s.delta=n.delta,s.inputs=n.inputs,s.globals=n.globals,s.camera=n.camera,s.stage=n.stage,s.game=n.game,s.me=t.wrappedStage,t.wrappedStage?.nodeUpdate(s),this.totalTime+=o,C.time=this.totalTime}loop(e){this.debugDelegate?.begin(),fe()||(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.catalogUnsubscribe?.(),this.catalogUnsubscribe=null,this.gameBridge.disconnect(),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&&(y.setRenderer(null),this.rendererManager.dispose(),this.rendererManager=null),y.clear(),ht().channel.reset(),this.timer.dispose(),this.customDestroy&&this.customDestroy({me:this,globals:C.globals}),x()}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}}buildEntitySummary(e){if(G(e.options))return null;let t=e.position??{x:0,y:0,z:0},n=e.rotation??{x:0,y:0,z:0},i=$(e),o=Se(e),r=y.get(e.uuid);return{uuid:e.uuid,name:e.name||"Unnamed",type:j(e),position:{x:t.x??0,y:t.y??0,z:t.z??0},rotation:{x:n.x??0,y:n.y??0,z:n.z??0},scale:i,quaternion:o,thumbnail:r?.dataUrl??null,bounds:r?.bounds}}buildEntitiesPayload(){let e=this.currentStage();if(!e?.wrappedStage)return[];let t=[];return e.wrappedStage.entityDelegate.childrenMap.forEach(n=>{let i=this.buildEntitySummary(n);i&&t.push(i)}),t}wireEntityThumbnails(e){if(this.clearEntityThumbnailWiring(),!e.wrappedStage)return;let t=r=>{if(!this.gameBridge.wantsThumbnails()||G(r.options))return;let s=r.group??r.mesh??null;s&&y.ensure(r.uuid,s).then(l=>{l&&!this.isDisposed&&this.gameBridge.queueThumbnails([{uuid:r.uuid,url:l.dataUrl,bounds:l.bounds}])})},n=e.wrappedStage.onEntityAdded(r=>{if(this.gameBridge.wantsEntityUpdates()){let s=this.buildEntitySummary(r);s&&this.gameBridge.queueEntityUpsert([s])}t(r)},{replayExisting:!0});this.thumbnailUnsubscribes.push(n);let i=r=>{if(!r.success)return;let s=e.wrappedStage?.entityDelegate.childrenMap.get(r.entityId);s&&(y.invalidate(r.entityId),t(s))};b.on("entity:model:loaded",i),this.thumbnailUnsubscribes.push(()=>{b.off("entity:model:loaded",i)});let o=r=>{y.invalidate(r.entityId),this.gameBridge.wantsEntityUpdates()&&this.gameBridge.queueEntityRemoved([r.entityId])};b.on("entity:destroyed",o),this.thumbnailUnsubscribes.push(()=>{b.off("entity:destroyed",o)}),this.wireEditorBackfill(e)}wireEditorBackfill(e){let t=this.gameBridge.onEditorAttached(()=>{if(!(this.isDisposed||this.currentStage()!==e)){this.lastPublishedGameConfig=null,this.publishGameConfig(),this.publishStageSnapshot();for(let n of e.wrappedStage?.entityDelegate.childrenMap.values()??[]){let i=n;if(G(i.options))continue;let o=i.group??i.mesh??null;o&&y.ensure(i.uuid,o).then(r=>{r&&!this.isDisposed&&this.gameBridge.queueThumbnails([{uuid:i.uuid,url:r.dataUrl,bounds:r.bounds}])})}}});this.thumbnailUnsubscribes.push(t)}clearEntityThumbnailWiring(){this.thumbnailUnsubscribes.forEach(e=>{try{e()}catch{}}),this.thumbnailUnsubscribes=[]}buildGameConfigPayload(){return 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}publishGameConfig(){let e=this.buildGameConfigPayload();if(!e)return;let t=JSON.stringify(e);t!==this.lastPublishedGameConfig&&(this.lastPublishedGameConfig=t,this.gameBridge.publishConfig(e))}publishStageSnapshot(){this.gameBridge.publishStageSnapshot({stage:this.buildStageConfigPayload(),entities:this.buildEntitiesPayload()})}subscribeToEventBus(){this.eventBusUnsubscribes.push(pe.on("game:state:updated",e=>{this.gameBridge.publishVariable({path:e.path,value:e.value,previousValue:e.previousValue})}))}};async function ze(a){let{getGameDefaultConfig:e}=await import("./game-default-6YXFFZ2Q.js"),t={...e()},n=[],i=[],o=[];Object.values(a).forEach(s=>{if(s instanceof L)i.push(s);else if(s instanceof ee)o.push(s);else if(s instanceof Q)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 Ve(a){return!!a.find(t=>t instanceof L)}function re(a){for(let e of a)if(e&&typeof e=="object"&&!(e instanceof L)&&!(e instanceof Q)&&!(e instanceof ee)){let t=e;if(t.globals)return t.globals}}import{proxy as gt}from"valtio/vanilla";import{get as ft,set as yt}from"idb-keyval";import{pack as bt,unpack as vt}from"msgpackr";var c=gt({previous:null,current:null,next:null,isLoading:!1}),X={staticRegistry:new Map,registerStaticStage(a,e){this.staticRegistry.set(a,e)},async loadStageData(a){try{let e=await ft(a);if(e)return vt(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 yt(c.current.id,bt(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 le={async createFromBlueprint(a){let e=E({});if(a.entities)for(let t of a.entities)try{let n=await Ie.createFromBlueprint(t);e.add(n)}catch(n){console.error(`Failed to create entity ${t.id} for stage ${a.id}`,n)}return e}};var Y=class{wrappedGame=null;options;setupCallbacks=[];updateCallbacks=[];destroyCallbacks=[];pendingLoadingCallbacks=[];globalChangeCallbacks=[];globalChangesCallbacks=[];activeGlobalSubscriptions=[];eventDelegate=new ve;pendingInputConfig=null;displayRuntime={};refErrorMessage="lost reference to game";constructor(e){this.options=e,Ve(e)||this.options.push(E());let t=re(e);t&&J(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=v(...e);return this.pendingInputConfig=t,this.wrappedGame&&this.wrappedGame.setGlobalInputConfig(t),this}async start(){x();let e=re(this.options);e&&J(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 ze(this.options),t=P(e,this.displayRuntime);this.pendingInputConfig&&(t.input=v(t.input??{},this.pendingInputConfig));let n=new F({...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=ce(e,i=>{t(i,this.getCurrentStage())});this.activeGlobalSubscriptions.push(n)}for(let{paths:e,callback:t}of this.globalChangesCallbacks){let n=me(e,i=>{t(i,this.getCurrentStage())});this.activeGlobalSubscriptions.push(n)}}getCurrentStage(){return this.wrappedGame?.currentStage()??null}experimental={getRuntime:()=>this.getCurrentStage()?.wrappedStage?.world?.simulation??null};async pause(){K(!0)}async resume(){K(!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(e){if(!this.wrappedGame){console.error(this.refErrorMessage);return}this.wrappedGame.isLoading()||await this.wrappedGame.loadStage(this.wrappedGame.stages[0],0,e?.transition)}previousStage(e){if(!this.wrappedGame){console.error(this.refErrorMessage);return}if(this.wrappedGame.isLoading())return;let t=this.wrappedGame.currentStageId,n=this.wrappedGame.stages.findIndex(o=>o.wrappedStage?.uuid===t),i=this.wrappedGame.stages[n-1];if(!i){console.error("previous stage called on first stage");return}this.wrappedGame.loadStage(i,n-1,e?.transition)}async loadStageFromId(e){if(!this.wrappedGame){console.error(this.refErrorMessage);return}try{let t=await X.loadStageData(e),n=await le.createFromBlueprint(t);await this.wrappedGame.loadStage(n),c.current=t}catch(t){console.error(`Failed to load stage ${e}`,t)}}nextStage(e){if(!this.wrappedGame){console.error(this.refErrorMessage);return}if(this.wrappedGame.isLoading())return;if(c.next){console.log("next stage called");let o=c.next.id;if(X.transitionForward(o),c.current){le.createFromBlueprint(c.current).then(r=>{this.wrappedGame?.loadStage(r,0,e?.transition)});return}}let t=this.wrappedGame.currentStageId,n=this.wrappedGame.stages.findIndex(o=>o.wrappedStage?.uuid===t),i=this.wrappedGame.stages[n+1];if(!i){console.error("next stage called on last stage");return}this.wrappedGame.loadStage(i,n+1,e?.transition)}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),ge(),x(),Ee.clearSharedMaterialCache()}dispatch(e,t){this.eventDelegate.dispatch(e,t),b.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 St(...a){return new Y(a)}import{Euler as wt,Quaternion as Ct,Vector2 as xt}from"three";function Gt(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 xt(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(),h=new Ct(p.x,p.y,p.z,p.w);s=new wt().setFromQuaternion(h,"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 ue="STAGE_STATE_CHANGE";function Rt(){return Et(S,()=>{let a={entities:S.entities,variables:S.variables};window.dispatchEvent(new CustomEvent(ue,{detail:a}))})}function Tt(){let a={entities:S.entities,variables:S.variables};window.dispatchEvent(new CustomEvent(ue,{detail:a}))}import{MathUtils as Bt,Vector3 as Mt}from"three";var He={targetKey:"primary",offset:new Mt(0,0,0),lerpFactor:.1};function It(a){let e={...He,...a,offset:q(a?.offset,He.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=Me(i);if(!t)t=r.clone();else{let l=Bt.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 Pt}from"three";function Lt(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 Pt({map:i});a.mesh.material=o}export{I as a,ne as b,ie as c,ae as d,dt as e,c as f,X as g,Y as h,St as i,Gt as j,ue as k,Rt as l,Tt as m,It as n,Lt as o};