@zylem/game-lib 0.8.2 → 0.8.3

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 (43) hide show
  1. package/dist/api/game-lib.api.json +1310 -704
  2. package/dist/api/game-lib.api.md +125 -88
  3. package/dist/api/game-lib.d.ts +255 -92
  4. package/dist/api/game-lib.typedoc.json +127368 -201231
  5. package/dist/bridge.d.ts +97 -0
  6. package/dist/bridge.js +1 -0
  7. package/dist/chunk-2VSVOPQN.js +19 -0
  8. package/dist/{chunk-KVSJE4XD.js → chunk-3I537JFL.js} +1 -1
  9. package/dist/chunk-AIQ6IVT5.js +1 -0
  10. package/dist/chunk-C5NEGC3S.js +1 -0
  11. package/dist/{chunk-CD7ZOZ35.js → chunk-CV75NSES.js} +1 -1
  12. package/dist/chunk-GKHAJ3MW.js +1 -0
  13. package/dist/chunk-HNCTOJP7.js +1 -0
  14. package/dist/{chunk-MZZCDXFB.js → chunk-LGS5N5M4.js} +1 -1
  15. package/dist/chunk-LKFF6XJC.js +1 -0
  16. package/dist/chunk-Q27ULMXY.js +24 -0
  17. package/dist/chunk-TV3AZKT4.js +9 -0
  18. package/dist/chunk-W5SXED5T.js +1 -0
  19. package/dist/chunk-WVSYUWTT.js +1 -0
  20. package/dist/core.d.ts +2 -2
  21. package/dist/core.js +1 -1
  22. package/dist/debug-state-Dp9CQQZ4.d.ts +49 -0
  23. package/dist/debug.d.ts +22 -3
  24. package/dist/debug.js +1 -1
  25. package/dist/entity.js +1 -1
  26. package/dist/events.d.ts +1 -64
  27. package/dist/events.js +1 -1
  28. package/dist/{game-DbqBQiFC.d.ts → game-NHkubIfI.d.ts} +49 -21
  29. package/dist/game-default-5TB3T5N7.js +1 -0
  30. package/dist/public.d.ts +5 -3
  31. package/dist/public.js +1 -1
  32. package/dist/web-components.d.ts +2 -2
  33. package/dist/web-components.js +1 -1
  34. package/package.json +8 -3
  35. package/dist/chunk-3PRBSSTS.js +0 -24
  36. package/dist/chunk-CFVRRRZZ.js +0 -1
  37. package/dist/chunk-COM6HJ2L.js +0 -1
  38. package/dist/chunk-JQKS42G4.js +0 -1
  39. package/dist/chunk-TAUWDQZF.js +0 -9
  40. package/dist/chunk-VS2D4B3W.js +0 -1
  41. package/dist/chunk-YHEWKN7N.js +0 -1
  42. package/dist/debug-state-DRoeasG2.d.ts +0 -17
  43. package/dist/game-default-6AZZCNST.js +0 -1
package/dist/events.js CHANGED
@@ -1 +1 @@
1
- import"./chunk-BIGH6D34.js";import{a,b}from"./chunk-YHEWKN7N.js";import"./chunk-QXVH6POE.js";export{a as EventEmitterDelegate,b as zylemEventBus};
1
+ import"./chunk-BIGH6D34.js";import{a,b}from"./chunk-AIQ6IVT5.js";import"./chunk-QXVH6POE.js";export{a as EventEmitterDelegate,b as zylemEventBus};
@@ -883,13 +883,27 @@ declare class StageDebugDelegate {
883
883
  private cameraDebugDelegate;
884
884
  private debugStateUnsubscribe;
885
885
  private focusContextUnregister;
886
+ private entityResolverUnregister;
887
+ private lastDebugEnabled;
888
+ private warnedMissingAddFactory;
886
889
  constructor(stage: ZylemStage, options?: StageDebugDelegateOptions);
890
+ /**
891
+ * Supply the factory the `add` tool uses to spawn entities at the clicked
892
+ * point. Without one the tool warns instead of silently doing nothing.
893
+ */
894
+ setAddEntityFactory(factory: AddEntityFactory | null): void;
887
895
  /** Camera used for debug orbit / raycasts (active primary, usually `__debug__`). */
888
896
  private getDebugViewCamera;
889
897
  private resolveEntity;
890
898
  /** Copy all stage children into debugMap so raycast/select tools work after enabling debug mid-session. */
891
899
  private populateDebugMap;
892
900
  private ensureCameraDebugDelegate;
901
+ /**
902
+ * Activate/deactivate only when `debugState.enabled` actually flips.
903
+ * Hover and selection write to `debugState` every frame, and `activate()`
904
+ * rebuilds post-processing, so reacting to every notification would
905
+ * rebuild the render pipeline once per frame.
906
+ */
893
907
  private syncWithDebugState;
894
908
  /** Initialize DOM listeners and switch rendering to the debug orbit camera. */
895
909
  private activate;
@@ -1694,16 +1708,10 @@ declare class ZylemGame<TGlobals extends BaseGlobals> {
1694
1708
  private rendererObserver;
1695
1709
  private eventBusUnsubscribes;
1696
1710
  private thumbnailUnsubscribes;
1697
- /**
1698
- * Trailing-debounce timer for entity-driven state dispatches. Building a
1699
- * `state:dispatch` payload is O(entities) (and downstream editor stores
1700
- * re-proxy/reconcile every entity), so bursts of thumbnail/destroy events
1701
- * must coalesce into a single dispatch instead of one per entity.
1702
- */
1703
- private entityDispatchTimer;
1704
- private pendingEntityDispatchPath;
1705
- /** Debounce window (ms) for coalescing entity-driven state dispatches. */
1706
- private static readonly ENTITY_DISPATCH_DEBOUNCE_MS;
1711
+ /** Serialized last-published game config, for dirty-checking resize churn. */
1712
+ private lastPublishedGameConfig;
1713
+ /** Editor ↔ game bridge adapter (RAF-coalesced publishes, command intake). */
1714
+ private gameBridge;
1707
1715
  private readonly gameUpdateParams;
1708
1716
  private readonly stageSetupParams;
1709
1717
  private readonly stageUpdateParams;
@@ -1757,27 +1765,47 @@ declare class ZylemGame<TGlobals extends BaseGlobals> {
1757
1765
  */
1758
1766
  private buildStageConfigPayload;
1759
1767
  /**
1760
- * Build the entities payload for the current stage.
1768
+ * Build a bridge entity summary for one entity, or null for entities on
1769
+ * the managed render path (instanced packs/bundles), which can number in
1770
+ * the thousands and are not useful in the editor panel.
1771
+ */
1772
+ private buildEntitySummary;
1773
+ /**
1774
+ * Build the full entities payload for the current stage.
1761
1775
  */
1762
1776
  private buildEntitiesPayload;
1763
1777
  /**
1764
- * Generate entity thumbnails as entities become available, then refresh editor state.
1778
+ * Generate entity thumbnails as entities become available, streaming
1779
+ * upserts/thumbnails/removals to the editor through the bridge
1780
+ * (RAF-coalesced, merged by uuid).
1781
+ *
1782
+ * All of this work exists only to feed the editor, and thumbnails in
1783
+ * particular cost an offscreen render plus a pixel readback on the shared
1784
+ * renderer. Each publisher therefore checks the bridge for a live listener
1785
+ * first, and a late-connecting editor is backfilled from
1786
+ * {@link wireEditorBackfill}.
1765
1787
  */
1766
1788
  private wireEntityThumbnails;
1767
- private clearEntityThumbnailWiring;
1768
1789
  /**
1769
- * Coalesce entity-driven state dispatches (thumbnail resolutions, entity
1770
- * destruction) into one trailing `emitStateDispatch` per burst.
1790
+ * Republish the current stage when an editor subscribes after the game
1791
+ * started. Without this, entities added while nothing was listening would
1792
+ * never appear, since the per-entity publishers were skipped.
1771
1793
  */
1772
- private queueEntityStateDispatch;
1794
+ private wireEditorBackfill;
1795
+ private clearEntityThumbnailWiring;
1796
+ private buildGameConfigPayload;
1797
+ /** Publish the resolved display config over the bridge. */
1773
1798
  /**
1774
- * Emit a state:dispatch event to the zylemEventBus.
1775
- * Called after stage load and on global state changes.
1799
+ * Publish the display config, skipping unchanged payloads. The
1800
+ * `ResizeObserver` on `<zylem-game>` funnels into `setDisplayRuntime`, which
1801
+ * fires on every layout tick even when nothing about the config moved.
1776
1802
  */
1777
- private emitStateDispatch;
1803
+ private publishGameConfig;
1804
+ /** Publish a full stage snapshot (config + entity list) over the bridge. */
1805
+ private publishStageSnapshot;
1778
1806
  /**
1779
- * Subscribe to the game event bus for stage loading and state events.
1780
- * Emits events to zylemEventBus for cross-package communication.
1807
+ * Subscribe to the game event bus for stage loading and state events,
1808
+ * mirroring global-variable updates to the editor over the bridge.
1781
1809
  */
1782
1810
  private subscribeToEventBus;
1783
1811
  }
@@ -0,0 +1 @@
1
+ import{v as e}from"./chunk-WVSYUWTT.js";import"./chunk-C5NEGC3S.js";import"./chunk-GKHAJ3MW.js";import"./chunk-LKFF6XJC.js";import"./chunk-W5SXED5T.js";import"./chunk-YAOXFYOD.js";import"./chunk-3I537JFL.js";import"./chunk-CM5YRNBJ.js";import"./chunk-AIQ6IVT5.js";import"./chunk-QXVH6POE.js";import"./chunk-EVYHPR3J.js";import"./chunk-D2PATZCC.js";import"./chunk-4QLJUQSJ.js";import"./chunk-7WRQ2UAN.js";import"./chunk-BH53MBAZ.js";import"./chunk-XRP4JJXL.js";import"./chunk-UG22Z42P.js";import{proxy as t}from"valtio/vanilla";var s=()=>({id:"zylem",globals:{},stages:[e()],debug:!1,time:0,input:void 0}),a=t({...s()});function o(){return{id:a.id??"zylem",globals:a.globals??{},stages:a.stages??[e()],debug:a.debug,time:a.time,input:a.input}}export{o as getGameDefaultConfig};
package/dist/public.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- export { A as AspectRatio, q as AspectRatioValue, k as CameraManager, j as CameraOptions, C as CameraWrapper, D as DeviceProfile, p as FirstPersonOptions, l as FirstPersonPerspective, o as Fixed2DOptions, F as Fixed2DPerspective, G as Game, b as GameConfigLike, d as GameDeviceConfig, a as GameLoadingEvent, P as PerspectiveOptions, y as RenderBundleManager, z as RenderStrategyManager, R as ResolutionInput, e as ResolveGameConfigRuntime, v as RetroPreset, w as RetroPresetKey, x as RetroResolution, S as StageConfigLike, h as StageOptions, n as ThirdPersonOptions, T as ThirdPersonPerspective, i as createCamera, c as createGame, m as createPerspective, f as createStage, g as gameConfig, r as getDisplayAspect, t as getPresetResolution, u as parseResolution, s as stageConfig } from './game-DbqBQiFC.js';
1
+ export { A as AspectRatio, q as AspectRatioValue, k as CameraManager, j as CameraOptions, C as CameraWrapper, D as DeviceProfile, p as FirstPersonOptions, l as FirstPersonPerspective, o as Fixed2DOptions, F as Fixed2DPerspective, G as Game, b as GameConfigLike, d as GameDeviceConfig, a as GameLoadingEvent, P as PerspectiveOptions, y as RenderBundleManager, z as RenderStrategyManager, R as ResolutionInput, e as ResolveGameConfigRuntime, v as RetroPreset, w as RetroPresetKey, x as RetroResolution, S as StageConfigLike, h as StageOptions, n as ThirdPersonOptions, T as ThirdPersonPerspective, i as createCamera, c as createGame, m as createPerspective, f as createStage, g as gameConfig, r as getDisplayAspect, t as getPresetResolution, u as parseResolution, s as stageConfig } from './game-NHkubIfI.js';
2
2
  export { G as GameInputConfig, a as GameInputPlayerConfig, K as KeyboardMapping, M as MouseConfig, b as MouseMapping, V as VirtualTouchButtonConfig, d as VirtualTouchButtonSlot, c as VirtualTouchButtonsConfig, e as VirtualTouchConfig, f as VirtualTouchJoystickConfig, g as VirtualTouchJoysticksConfig, h as VirtualTouchPosition, i as VirtualTouchStyle, Z as ZylemGameConfig } from './game-interfaces-vF5sRi1n.js';
3
3
  export { CameraFeedOptions, FollowTargetOptions, RenderCategory, STAGE_STATE_CHANGE, StageManager, StageStateChangeEvent, Vect3, createFollowTarget, dispatchStageState, entitySpawner, initStageStateDispatcher, isManagedRenderEntity, resolveRenderCategory, setCameraFeed, setStageFrameProfilerEnabled, stageState, usesManagedRenderPath, vessel } from './core.js';
4
4
  export { f as EntityBlueprint, j as EntityJson, d as EntityJsonSchema, E as EntitySchema, i as LineEntityData, L as LineEntityDataSchema, h as SpriteEntityData, b as SpriteEntityDataSchema, S as StageBlueprint, k as StageJson, e as StageJsonSchema, c as StageSchema, g as TextEntityData, T as TextEntityDataSchema, V as Vector2Schema, a as Vector3TupleSchema } from './blueprints-TbGY-h53.js';
@@ -17,12 +17,14 @@ export { BehaviorRuntime, EntityDefinition, EntityHandle, Simulation, Simulation
17
17
  export { ScreenCenterLookOptions, ScreenCenterLookTargets, mergeInputConfigs, screenCenterLookDeltas, screenCenterLookTargets, shortestAngleDelta, useArrowsForAxes, useArrowsForDirections, useArrowsForSecondaryAxes, useIJKLForAxes, useIJKLForDirections, useMouse, useMouseLook, useScreenCenterLook, useVirtualControls, useWASDForAxes, useWASDForDirections } from './input.js';
18
18
  export { D as DefaultTouchControlsOptions, J as JoystickSelection, T as TouchTheme, b as TouchThemeName, d as defaultTouchControls, a as resolveButtonAccent, r as resolveTouchTheme, t as touchThemes } from './default-controls-CAKJ5zlo.js';
19
19
  export { TouchButtonSvgOptions, TouchThemeInput, joystickBaseSvg, joystickThumbSvg, touchButtonSvg } from './input-ui.js';
20
- export { EntityConfigPayload, EntityEvents, EventEmitterDelegate, GameEvents, GameLoadingPayload, StageConfigPayload, StageEvents, StateDispatchPayload, ZylemEvents, zylemEventBus } from './events.js';
20
+ export { EntityEvents, EventEmitterDelegate, GameEvents, GameLoadingPayload, StageEvents, ZylemEvents, zylemEventBus } from './events.js';
21
21
  export { clearGlobalSubscriptions, createGlobal, createVariable, getGlobal, getGlobals, getVariable, globalChange, globalChanges, onGlobalChange, onGlobalChanges, onVariableChange, onVariableChanges, setGlobal, setVariable, variableChange, variableChanges } from './globals.js';
22
22
  export { pingPongBeep, ricochetSound } from './audio.js';
23
23
  export { Howl } from 'howler';
24
- export { D as DebugTools, d as debugState, s as setDebugTool, a as setPaused, b as setSelectedEntity } from './debug-state-DRoeasG2.js';
24
+ export { k as DebugEntityResolver, D as DebugTools, d as debugState, i as getHoveredEntity, h as getHoveredEntityId, e as getSelectedEntity, g as getSelectedEntityId, r as registerDebugEntityResolver, j as resolveDebugEntity, s as setDebugTool, f as setHoveredEntityId, a as setPaused, b as setSelectedEntity, c as setSelectedEntityId } from './debug-state-Dp9CQQZ4.js';
25
25
  export { EntityFocusContext, EntityThumbnailCache, EntityThumbnailCacheEntry, EntityThumbnailResult, entityThumbnailCache, focusEntity, registerEntityFocusContext } from './debug.js';
26
+ export { GameBridge, GameBridgeHost } from './bridge.js';
27
+ export { BRIDGE_READY_EVENT, BridgeChannel, BridgeDebugTool, BridgeHandler, GameLoadingPayload as BridgeLoadingPayload, BridgeMessageType, BridgeMessages, BridgeVec3, EditorToGameMessages, EntitySummaryPayload, EntityThumbnailPayload, GameConfigPayload, GameToEditorMessages, GameVariablePayload, StageConfigPayload, StageSnapshotPayload, ZylemBridge, announceBridgeReady, getZylemBridge } from '@zylem/bridge';
26
28
  export { ZylemGameElement, ZylemGameState } from './web-components.js';
27
29
  export { RuntimeBodyOptions, RuntimeColliderOptions, RuntimeCollisionBundle, buildBoxCollider, buildCapsuleCollider, buildConvexHullCollider, buildCylinderCollider, buildHeightfieldCollider, buildRuntimeBody, buildSphereCollider, buildTrimeshCollider, bundleRuntimeCollision } from './runtime.js';
28
30
  export { ColorJsonSchema, GameConfigJson, GameConfigJsonSchema, GameDeviceConfigJson, GameDeviceConfigJsonSchema, GameInputConfigJson, GameInputConfigSchema, GameInputPlayerConfigSchema, KeyboardMappingSchema, MouseConfigSchema, MouseMappingSchema, ResolutionInputSchema, StageAssetLoaderConfigSchema, StageConfigJson, StageConfigJsonSchema, StageGLTFAssetLoaderConfigSchema, Vec3ComponentsSchema, VirtualTouchButtonConfigSchema, VirtualTouchButtonsConfigSchema, VirtualTouchConfigSchema, VirtualTouchJoystickConfigSchema, VirtualTouchJoysticksConfigSchema, VirtualTouchPositionSchema, VirtualTouchStyleSchema } from './schema.js';
package/dist/public.js CHANGED
@@ -1 +1 @@
1
- import{a as s,b as n,c as l,d as S,e as h,f as y,g as L,h as v,i as Z,j as b,k as g,l as u,m as T,n as j,o as F,p as W,q as k,r as w,s as z,t as B,u as D,v as E,w as G}from"./chunk-QB3NL7VQ.js";import"./chunk-BIGH6D34.js";import"./chunk-DFLI7ICU.js";import{a as Ha}from"./chunk-TAUWDQZF.js";import{a as Ia,b as Ja,c as Ka,d as Qa,e as Ra,f as Ua,g as Xa,h as Ya,i as _a,j as $a,k as op,l as rp,m as ep,n as tp,o as mp,p as ap}from"./chunk-47DG7I7M.js";import{A as Dp,B as Ep,C as Gp,a as pp,b as fp,c as xp,d as ip,e as dp,f as cp,g as sp,h as np,i as lp,j as Sp,k as hp,l as yp,m as Lp,n as vp,o as Zp,p as bp,q as gp,r as up,s as Tp,t as jp,u as Fp,v as Wp,w as kp,x as wp,y as zp,z as Bp}from"./chunk-JNFFTNMH.js";import{a as fo,b as xo,c as io,d as co,e as vo,f as Nr,g as Or,h as Ur,i as Xr,j as Yr,k as _r,l as $r,m as oe,n as re,o as ee}from"./chunk-3PRBSSTS.js";import{a as go}from"./chunk-7GYFZKK7.js";import{a as K,b as Q}from"./chunk-COM6HJ2L.js";import{a as po,c as uo,d as To,e as jo,f as nr,g as lr,h as gr,i as ur,k as Tr,l as jr,m as Fr,n as Wr,o as kr,p as wr,q as zr,r as Br,s as Dr,t as Gr,v as Mr}from"./chunk-CFVRRRZZ.js";import{c as Zr,d as br}from"./chunk-VS2D4B3W.js";import{a as C,c as H,e as I,f as J}from"./chunk-JQKS42G4.js";import{b as ir}from"./chunk-YAOXFYOD.js";import{A as we,B as ze,C as Be,D as De,E as Ee,F as Ge,G as Me,H as Ne,I as Oe,J as Pe,K as Ve,L as qe,M as Ae,N as Ce,O as He,P as Ie,Q as Je,R as Ke,a as te,b as me,c as ae,d as pe,e as fe,f as xe,g as ie,h as de,i as ce,j as se,k as ne,l as le,m as Se,n as he,o as ye,p as Le,q as ve,r as Ze,s as be,t as ge,u as ue,v as Te,w as je,x as Fe,y as We,z as ke}from"./chunk-CD7ZOZ35.js";import{b as Pr,c as Vr,d as qr,e as Ar,f as Cr,g as Hr,h as Ir,i as Jr,j as Kr,k as Qr,m as Rr}from"./chunk-MZZCDXFB.js";import{A as xr,B as dr,C as cr,D as sr,c as Xo,d as Yo,e as _o,f as $o,g as or,h as rr,i as er,j as tr,s as mr,u as ar,y as pr,z as fr}from"./chunk-KVSJE4XD.js";import{a as o,b as r,h as e,i as t,k as m,l as a,m as p,n as f,o as x,p as i,q as d,r as c}from"./chunk-CM5YRNBJ.js";import{a as Zo,b as bo}from"./chunk-YHEWKN7N.js";import"./chunk-QXVH6POE.js";import{b as Uo}from"./chunk-EVYHPR3J.js";import{$ as Kt,$a as Km,A as vt,Aa as vm,B as Zt,Ba as Zm,C as bt,Ca as bm,D as gt,Da as gm,E as ut,Ea as um,F as Tt,Fa as Tm,G as jt,Ga as jm,H as Ft,Ha as Fm,I as Wt,Ia as Wm,J as kt,Ja as km,K as wt,Ka as wm,L as zt,La as zm,M as Bt,Ma as Bm,N as Dt,Na as Dm,O as Et,Oa as Em,P as Gt,Pa as Gm,Q as Mt,Qa as Mm,R as Nt,Ra as Nm,S as Ot,Sa as Om,T as Pt,Ta as Pm,U as Vt,Ua as Vm,V as qt,Va as qm,W as At,Wa as Am,X as Ct,Xa as Cm,Y as Ht,Ya as Hm,Z as It,Za as Im,_ as Jt,_a as Jm,a as Qe,aa as Qt,ab as Qm,b as Re,ba as Rt,bb as Rm,c as Ue,ca as Ut,cb as Um,d as Xe,da as Xt,db as Xm,e as Ye,ea as Yt,eb as Ym,f as _e,fa as _t,fb as _m,g as $e,ga as $t,gb as $m,h as ot,ha as om,hb as oa,i as rt,ia as rm,ib as ra,j as et,ja as em,k as tt,ka as tm,l as mt,la as mm,m as at,ma as am,n as pt,na as pm,o as ft,oa as fm,p as xt,pa as xm,q as it,qa as im,r as dt,ra as dm,s as ct,sa as cm,t as st,ta as sm,u as nt,ua as nm,v as lt,va as lm,w as St,wa as Sm,x as ht,xa as hm,y as yt,ya as ym,z as Lt,za as Lm}from"./chunk-XK63E4SX.js";import{a as ea,b as ta,c as ma}from"./chunk-ZRT3ZQVH.js";import{a as aa,b as pa,c as fa,d as xa}from"./chunk-WQ3WMMZD.js";import{h as Sr,i as hr,j as yr,k as Lr,l as vr}from"./chunk-D2PATZCC.js";import{e as M,f as N,g as O,h as P,i as V,j as q,m as A}from"./chunk-4QLJUQSJ.js";import{a as Fo,b as Wo,c as ko,d as wo,g as zo,h as Bo,i as Do,j as Eo}from"./chunk-7WRQ2UAN.js";import{A as Ma,B as Na,C as Oa,D as Pa,E as Va,a as ia,b as da,c as ca,d as sa,e as na,f as la,g as Sa,h as ha,i as ya,j as La,k as va,l as Za,m as ba,n as ga,o as ua,p as Ta,q as ja,r as Fa,s as Wa,t as ka,u as wa,v as za,w as Ba,x as Da,y as Ea,z as Ga}from"./chunk-IPWUDOV5.js";import{a as Er}from"./chunk-BH53MBAZ.js";import{a as Go,b as Mo,c as No,d as Oo,e as Po,f as Vo,g as qo,h as Ao,i as Co,j as Ho,k as Io,l as Jo,m as Ko,n as Qo,o as Ro}from"./chunk-XRP4JJXL.js";import{a as qa,b as Aa,c as Ca}from"./chunk-7QF6YTEZ.js";import"./chunk-ORIDWL3T.js";import{a as so,b as no,c as lo,d as So,e as ho,f as yo,g as Lo}from"./chunk-PCFF4LLO.js";import{a as R,b as U,c as X,d as Y,e as _,f as $,g as oo,h as ro,i as eo,j as to,k as mo,l as ao}from"./chunk-UG22Z42P.js";export{pr as ACTOR_TYPE,fo as AspectRatio,ie as BOX_TYPE,Qe as BoundaryRicochet3DCoordinator,Re as BoundaryRicochetCoordinator,We as CONE_TYPE,Ee as CYLINDER_TYPE,wr as CameraManager,Tr as CameraPipeline,zr as CameraWrapper,Wp as ColorJsonSchema,Ue as CooldownBehavior,Te as DISK_TYPE,Xe as Destructible3DBehavior,Ye as DestructibleMesh,np as EntityJsonSchema,fp as EntitySchema,K as EntityThumbnailCache,Zo as EventEmitterDelegate,dr as FOG_TYPE,_e as FirstPersonBehavior,$e as FirstPersonEvent,ot as FirstPersonFSM,Wr as FirstPersonPerspective,tt as FirstPersonPresentation,rt as FirstPersonShooterCoordinator,et as FirstPersonState,Fr as Fixed2DPerspective,c as Fn,mt as FractureOptions,Ur as Game,Gp as GameConfigJsonSchema,Ep as GameDeviceConfigJsonSchema,Fp as GameInputConfigSchema,jp as GameInputPlayerConfigSchema,ma as Howl,at as Jumper2DBehavior,pt as Jumper2DEvent,ft as Jumper2DFSM,xt as Jumper2DState,it as Jumper3DBehavior,dt as Jumper3DEvent,ct as Jumper3DFSM,st as Jumper3DState,Sp as KeyboardMappingSchema,Ce as LIGHT_TYPE,Ir as LINE_TYPE,cp as LineEntityDataSchema,Tp as MouseConfigSchema,hp as MouseMappingSchema,nt as MultidirectionalSpaceShooterCoordinator,Ve as PARTICLE_SYSTEM_TYPE,Ne as PILL_TYPE,Se as PLANE_TYPE,ze as PYRAMID_TYPE,lt as ParticleEmitterBehavior,ur as Perspectives,St as Platformer2DBehavior,ht as Platformer2DEvent,yt as Platformer2DFSM,Lt as Platformer2DState,vt as Platformer3DBehavior,Zt as Platformer3DEvent,bt as Platformer3DFSM,gt as Platformer3DState,be as RECT_TYPE,Km as RUNTIME_BOUNDARY_2D_BEHAVIOR_KEY,Qm as RUNTIME_DYNAMIC_CIRCLE_BODY_2D_BEHAVIOR_KEY,Rm as RUNTIME_GOAL_ZONE_2D_BEHAVIOR_KEY,Um as RUNTIME_PLAYER_INPUT_2D_BEHAVIOR_KEY,Xm as RUNTIME_RICOCHET_2D_BEHAVIOR_KEY,Ym as RUNTIME_TRIGGER_REGION_2D_BEHAVIOR_KEY,nr as RenderBundleManager,lr as RenderStrategyManager,Dp as ResolutionInputSchema,ut as Ricochet2DBehavior,Tt as Ricochet2DEvent,jt as Ricochet2DFSM,Ft as Ricochet2DState,Wt as Ricochet3DBehavior,kt as Ricochet3DEvent,wt as Ricochet3DFSM,zt as Ricochet3DState,qm as RuntimeBoundary2DBehavior,Am as RuntimeDynamicCircleBody2DBehavior,Cm as RuntimeGoalZone2DBehavior,Hm as RuntimePlayerInput2DBehavior,Im as RuntimeRicochet2DBehavior,Jm as RuntimeTriggerRegion2DBehavior,se as SPHERE_TYPE,Ar as SPRITE_TYPE,_r as STAGE_STATE_CHANGE,Bt as ScreenVisibilityBehavior,Dt as ScreenVisibilityFSM,Et as ScreenWrapBehavior,Gt as ScreenWrapEvent,Mt as ScreenWrapFSM,Nt as ScreenWrapState,Ot as Shooter2DBehavior,ir as SimulationBody,sp as SpriteEntityDataSchema,zp as StageAssetLoaderConfigSchema,$a as StageBodyKind,op as StageBoundaryDim,Bp as StageConfigJsonSchema,rp as StageEventType,wp as StageGLTFAssetLoaderConfigSchema,lp as StageJsonSchema,Or as StageManager,ep as StageRicochetDim,tp as StageRicochetReflection,xp as StageSchema,mp as StageTopDownPlane,Pr as TEXT_TYPE,ip as TextEntityDataSchema,jr as ThirdPersonPerspective,Pt as ThrusterBehavior,Vt as ThrusterEvent,qt as ThrusterFSM,At as ThrusterState,Ct as TopDownMovementBehavior,Ht as TopDownShooterCoordinator,Wo as VEC2_ONE,Fo as VEC2_ZERO,wo as VEC3_ONE,ko as VEC3_ZERO,kp as Vec3ComponentsSchema,pp as Vector2Schema,dp as Vector3TupleSchema,vp as VirtualTouchButtonConfigSchema,bp as VirtualTouchButtonsConfigSchema,up as VirtualTouchConfigSchema,Zp as VirtualTouchJoystickConfigSchema,gp as VirtualTouchJoysticksConfigSchema,Lp as VirtualTouchPositionSchema,yp as VirtualTouchStyleSchema,It as WorldBoundary2DBehavior,Jt as WorldBoundary2DEvent,Kt as WorldBoundary2DFSM,Qt as WorldBoundary2DState,Rt as WorldBoundary3DBehavior,Ut as WorldBoundary3DEvent,Xt as WorldBoundary3DFSM,Yt as WorldBoundary3DState,Le as ZONE_TYPE,fr as ZylemActor,de as ZylemBox,ke as ZylemCone,Ge as ZylemCylinder,je as ZylemDisk,cr as ZylemFog,Ha as ZylemGameElement,He as ZylemLight,Kr as ZylemLine,qe as ZylemParticleSystem,Oe as ZylemPill,he as ZylemPlane,Be as ZylemPyramid,ge as ZylemRect,ne as ZylemSphere,Cr as ZylemSprite,Vr as ZylemText,ve as ZylemZone,u as abs,Er as applyTransformChanges,g as asin,b as atan,_m as bindRuntimeDynamicCircleBody2DHandle,Xo as boxCollision,te as boxMesh,Ja as buildBoxCollider,Qa as buildCapsuleCollider,Ua as buildConvexHullCollider,Ra as buildCylinderCollider,Ya as buildHeightfieldCollider,Ia as buildRuntimeBody,Ka as buildSphereCollider,Xa as buildTrimeshCollider,_a as bundleRuntimeCollision,la as callFunc,L as clamp,A as clearGlobalSubscriptions,_t as computeWorldBoundary2DHits,$t as computeWorldBoundary3DHits,_o as coneCollision,ae as coneMesh,Z as cos,mr as create,xr as createActor,s as createBackgroundShader,ce as createBox,Br as createCamera,we as createCone,Je as createCooldownIcon,Me as createCylinder,Fe as createDisk,ar as createEntity,Rr as createEntityFactory,om as createFirstPersonInputComponent,rm as createFirstPersonMovementComponent,em as createFirstPersonStateComponent,sr as createFog,re as createFollowTarget,Xr as createGame,N as createGlobal,tm as createJumpConfig2D,mm as createJumpConfig3D,am as createJumpInput2D,pm as createJumpInput3D,fm as createJumpState2D,xm as createJumpState3D,Ie as createLight,Qr as createLine,m as createNodeMaterialFromTSL,Ae as createParticleSystem,kr as createPerspective,im as createPhysicsBodyComponent,Pe as createPill,ye as createPlane,dm as createPlatformer2DInputComponent,cm as createPlatformer2DMovementComponent,sm as createPlatformer2DStateComponent,nm as createPlatformer3DInputComponent,lm as createPlatformer3DMovementComponent,Sm as createPlatformer3DStateComponent,De as createPyramid,ue as createRect,hm as createShooter2DStateComponent,ap as createSimulation,le as createSphere,Hr as createSprite,Mr as createStage,qr as createText,ym as createThrusterInputComponent,Lm as createThrusterMovementComponent,vm as createThrusterStateComponent,Zm as createTopDownMovementComponent,bm as createTopDownMovementInputComponent,gm as createTopDownMovementStateComponent,um as createTransformComponent,ua as createTransformStore,hr as createVariable,Ze as createZone,go as crossfadeTransitionShader,or as cylinderCollision,fe as cylinderMesh,C as debugState,Lo as defaultTouchControls,Tm as defineBehavior,na as delay,Ke as destroy,oe as dispatchStageState,B as dot,$m as emitRuntimeGoal,oa as emitRuntimeRicochet,ra as emitRuntimeTriggerRegionEnter,Yr as entitySpawner,Q as entityThumbnailCache,T as exp,Sa as fadeOpacity,jm as fireCooldown,Fm as fireShooter2DIfRequested,d as float,w as floor,br as focusEntity,z as fract,vo as gameConfig,Wm as getCooldown,km as getCooldownStore,xo as getDisplayAspect,wm as getEntityFacingAngle2D,O as getGlobal,q as getGlobals,Da as getPosition,io as getPresetResolution,Ro as getRotation,yr as getVariable,Ea as getVelocity,aa as globalChange,pa as globalChanges,zm as hasAnyWorldBoundary2DHit,Bm as hasAnyWorldBoundary3DHit,$r as initStageStateDispatcher,t as isGLSLShader,jo as isManagedRenderEntity,e as isTSLShader,po as isWebGPUSupported,So as joystickBaseSvg,ho as joystickThumbSvg,D as length,W as max,ao as mergeInputConfigs,k as min,h as mix,G as mod,Ta as move,da as moveBy,Ba as moveForwardXY,ca as moveTo,ja as moveX,ka as moveXY,wa as moveXZ,Fa as moveY,Wa as moveZ,S as normalize,zo as normalizeVec2,Bo as normalizeVec3,o as objectVertexShader,P as onGlobalChange,V as onGlobalChanges,ya as onPress,La as onRelease,Lr as onVariableChange,vr as onVariableChanges,Uo as packCollisionGroups,Za as parallel,co as parseResolution,Dm as particleEffect,Em as particlePresets,Jr as pickZylemLine,rr as pillCollision,xe as pillMesh,ta as pingPongBeep,er as planeCollision,l as positionWorld,n as positionWorldDirection,j as pow,$o as pyramidCollision,pe as pyramidMesh,Gm as registerCooldown,Zr as registerEntityFocusContext,ba as repeat,ga as repeatForever,Mm as resetCooldown,ia as resetEntityOpacity,za as resetVelocity,Nm as resolveAim2D,lo as resolveButtonAccent,uo as resolveRenderCategory,no as resolveTouchTheme,ea as ricochetSound,sa as rotateBy,No as rotateEuler,Go as rotateInDirection,Po as rotateX,Oo as rotateY,Mo as rotateYEuler,Vo as rotateZ,Ca as screenCenterLookDeltas,Aa as screenCenterLookTargets,va as sequence,ee as setCameraFeed,I as setDebugTool,M as setGlobal,H as setPaused,Ga as setPosition,Ma as setPositionX,Na as setPositionY,Oa as setPositionZ,Ko as setRotation,Qo as setRotationDegrees,Ho as setRotationDegreesX,Ao as setRotationDegreesY,Jo as setRotationDegreesZ,Co as setRotationX,qo as setRotationY,Io as setRotationZ,J as setSelectedEntity,gr as setStageFrameProfilerEnabled,Sr as setVariable,qa as shortestAngleDelta,v as sin,y as smoothstep,Yo as sphereCollision,me as sphereMesh,Dr as stageConfig,Nr as stageState,r as standardShader,F as step,ha as throttle,Om as tickCooldowns,f as time,Do as toThreeVector2,Eo as toThreeVector3,yo as touchButtonSvg,so as touchThemes,a as uniform,Pm as updateBoundaryRicochet,R as useArrowsForAxes,X as useArrowsForDirections,U as useArrowsForSecondaryAxes,Vm as useBehavior,$ as useIJKLForAxes,oo as useIJKLForDirections,to as useMouse,ro as useMouseLook,eo as useScreenCenterLook,mo as useVirtualControls,_ as useWASDForAxes,Y as useWASDForDirections,To as usesManagedRenderPath,p as uv,fa as variableChange,xa as variableChanges,E as vec2,x as vec3,i as vec4,Gr as vessel,Va as wrapAround3D,Pa as wrapAroundXY,tr as zoneCollision,bo as zylemEventBus};
1
+ import{a as s,b as n,c as l,d as S,e as h,f as y,g as L,h as v,i as Z,j as b,k as g,l as u,m as T,n as j,o as F,p as W,q as k,r as w,s as z,t as B,u as D,v as E,w as G}from"./chunk-QB3NL7VQ.js";import"./chunk-BIGH6D34.js";import"./chunk-DFLI7ICU.js";import{a as _a,b as $a,c as op}from"./chunk-HNCTOJP7.js";import{a as rp}from"./chunk-TV3AZKT4.js";import{a as ep,b as tp,c as mp,d as ap,e as pp,f as fp,g as xp,h as ip,i as dp,j as cp,k as sp,l as np,m as lp,n as Sp,o as hp,p as yp}from"./chunk-47DG7I7M.js";import{A as Ip,B as Jp,C as Kp,a as Lp,b as vp,c as Zp,d as bp,e as gp,f as up,g as Tp,h as jp,i as Fp,j as Wp,k as kp,l as wp,m as zp,n as Bp,o as Dp,p as Ep,q as Gp,r as Mp,s as Np,t as Op,u as Pp,v as Vp,w as qp,x as Ap,y as Cp,z as Hp}from"./chunk-JNFFTNMH.js";import{a as ho,b as yo,c as Lo,d as vo,e as Wo,f as Jr,g as Kr,h as me,i as ae,j as pe,k as fe,l as xe,m as ie,n as de,o as ce}from"./chunk-Q27ULMXY.js";import{a as So,c as Go,d as Mo,e as No,f as Tr,g as jr,h as Br,i as Dr,k as Er,l as Gr,m as Mr,n as Nr,o as Or,p as Pr,q as Vr,r as qr,s as Ar,t as Hr,v as Ir}from"./chunk-WVSYUWTT.js";import{a as Eo}from"./chunk-7GYFZKK7.js";import{a as oo,b as ro}from"./chunk-2VSVOPQN.js";import"./chunk-C5NEGC3S.js";import{c as Do}from"./chunk-GKHAJ3MW.js";import{a as zo,b as Bo}from"./chunk-LKFF6XJC.js";import{a as C,b as H,c as I,e as J,g as K,h as Q,i as R,j as U,k as X,m as Y,n as _,o as $}from"./chunk-W5SXED5T.js";import{b as Zr}from"./chunk-YAOXFYOD.js";import{A as Pe,B as Ve,C as qe,D as Ae,E as Ce,F as He,G as Ie,H as Je,I as Ke,J as Qe,K as Re,L as Ue,M as Xe,N as Ye,O as _e,P as $e,Q as ot,R as rt,a as se,b as ne,c as le,d as Se,e as he,f as ye,g as Le,h as ve,i as Ze,j as be,k as ge,l as ue,m as Te,n as je,o as Fe,p as We,q as ke,r as we,s as ze,t as Be,u as De,v as Ee,w as Ge,x as Me,y as Ne,z as Oe}from"./chunk-CV75NSES.js";import{b as Qr,c as Rr,d as Ur,e as Xr,f as Yr,g as _r,h as $r,i as oe,j as re,k as ee,m as te}from"./chunk-LGS5N5M4.js";import{A as vr,B as br,C as gr,D as ur,c as fr,d as xr,e as ir,f as dr,g as cr,h as sr,i as nr,j as lr,s as Sr,u as hr,y as yr,z as Lr}from"./chunk-3I537JFL.js";import{a as o,b as r,h as e,i as t,k as m,l as a,m as p,n as f,o as x,p as i,q as d,r as c}from"./chunk-CM5YRNBJ.js";import{a as ko,b as wo}from"./chunk-AIQ6IVT5.js";import"./chunk-QXVH6POE.js";import{b as pr}from"./chunk-EVYHPR3J.js";import{$ as rm,$a as ra,A as kt,Aa as km,B as wt,Ba as wm,C as zt,Ca as zm,D as Bt,Da as Bm,E as Dt,Ea as Dm,F as Et,Fa as Em,G as Gt,Ga as Gm,H as Mt,Ha as Mm,I as Nt,Ia as Nm,J as Ot,Ja as Om,K as Pt,Ka as Pm,L as Vt,La as Vm,M as qt,Ma as qm,N as At,Na as Am,O as Ct,Oa as Cm,P as Ht,Pa as Hm,Q as It,Qa as Im,R as Jt,Ra as Jm,S as Kt,Sa as Km,T as Qt,Ta as Qm,U as Rt,Ua as Rm,V as Ut,Va as Um,W as Xt,Wa as Xm,X as Yt,Xa as Ym,Y as _t,Ya as _m,Z as $t,Za as $m,_ as om,_a as oa,a as et,aa as em,ab as ea,b as tt,ba as tm,bb as ta,c as mt,ca as mm,cb as ma,d as at,da as am,db as aa,e as pt,ea as pm,eb as pa,f as ft,fa as fm,fb as fa,g as xt,ga as xm,gb as xa,h as it,ha as im,hb as ia,i as dt,ia as dm,ib as da,j as ct,ja as cm,k as st,ka as sm,l as nt,la as nm,m as lt,ma as lm,n as St,na as Sm,o as ht,oa as hm,p as yt,pa as ym,q as Lt,qa as Lm,r as vt,ra as vm,s as Zt,sa as Zm,t as bt,ta as bm,u as gt,ua as gm,v as ut,va as um,w as Tt,wa as Tm,x as jt,xa as jm,y as Ft,ya as Fm,z as Wt,za as Wm}from"./chunk-XK63E4SX.js";import{a as ca,b as sa,c as na}from"./chunk-ZRT3ZQVH.js";import{a as la,b as Sa,c as ha,d as ya}from"./chunk-WQ3WMMZD.js";import{h as Fr,i as Wr,j as kr,k as wr,l as zr}from"./chunk-D2PATZCC.js";import{e as M,f as N,g as O,h as P,i as V,j as q,m as A}from"./chunk-4QLJUQSJ.js";import{a as Oo,b as Po,c as Vo,d as qo,g as Ao,h as Co,i as Ho,j as Io}from"./chunk-7WRQ2UAN.js";import{A as Ia,B as Ja,C as Ka,D as Qa,E as Ra,a as La,b as va,c as Za,d as ba,e as ga,f as ua,g as Ta,h as ja,i as Fa,j as Wa,k as ka,l as wa,m as za,n as Ba,o as Da,p as Ea,q as Ga,r as Ma,s as Na,t as Oa,u as Pa,v as Va,w as qa,x as Aa,y as Ca,z as Ha}from"./chunk-IPWUDOV5.js";import{a as Cr}from"./chunk-BH53MBAZ.js";import{a as Jo,b as Ko,c as Qo,d as Ro,e as Uo,f as Xo,g as Yo,h as _o,i as $o,j as or,k as rr,l as er,m as tr,n as mr,o as ar}from"./chunk-XRP4JJXL.js";import{a as Ua,b as Xa,c as Ya}from"./chunk-7QF6YTEZ.js";import"./chunk-ORIDWL3T.js";import{a as Zo,b as bo,c as go,d as uo,e as To,f as jo,g as Fo}from"./chunk-PCFF4LLO.js";import{a as eo,b as to,c as mo,d as ao,e as po,f as fo,g as xo,h as io,i as co,j as so,k as no,l as lo}from"./chunk-UG22Z42P.js";export{yr as ACTOR_TYPE,ho as AspectRatio,Le as BOX_TYPE,op as BRIDGE_READY_EVENT,et as BoundaryRicochet3DCoordinator,tt as BoundaryRicochetCoordinator,Ne as CONE_TYPE,Ce as CYLINDER_TYPE,Pr as CameraManager,Er as CameraPipeline,Vr as CameraWrapper,Vp as ColorJsonSchema,mt as CooldownBehavior,Ee as DISK_TYPE,at as Destructible3DBehavior,pt as DestructibleMesh,jp as EntityJsonSchema,vp as EntitySchema,oo as EntityThumbnailCache,ko as EventEmitterDelegate,br as FOG_TYPE,ft as FirstPersonBehavior,xt as FirstPersonEvent,it as FirstPersonFSM,Nr as FirstPersonPerspective,st as FirstPersonPresentation,dt as FirstPersonShooterCoordinator,ct as FirstPersonState,Mr as Fixed2DPerspective,c as Fn,nt as FractureOptions,me as Game,Do as GameBridge,Kp as GameConfigJsonSchema,Jp as GameDeviceConfigJsonSchema,Pp as GameInputConfigSchema,Op as GameInputPlayerConfigSchema,na as Howl,lt as Jumper2DBehavior,St as Jumper2DEvent,ht as Jumper2DFSM,yt as Jumper2DState,Lt as Jumper3DBehavior,vt as Jumper3DEvent,Zt as Jumper3DFSM,bt as Jumper3DState,Wp as KeyboardMappingSchema,Ye as LIGHT_TYPE,$r as LINE_TYPE,up as LineEntityDataSchema,Np as MouseConfigSchema,kp as MouseMappingSchema,gt as MultidirectionalSpaceShooterCoordinator,Re as PARTICLE_SYSTEM_TYPE,Je as PILL_TYPE,Te as PLANE_TYPE,Ve as PYRAMID_TYPE,ut as ParticleEmitterBehavior,Dr as Perspectives,Tt as Platformer2DBehavior,jt as Platformer2DEvent,Ft as Platformer2DFSM,Wt as Platformer2DState,kt as Platformer3DBehavior,wt as Platformer3DEvent,zt as Platformer3DFSM,Bt as Platformer3DState,ze as RECT_TYPE,ra as RUNTIME_BOUNDARY_2D_BEHAVIOR_KEY,ea as RUNTIME_DYNAMIC_CIRCLE_BODY_2D_BEHAVIOR_KEY,ta as RUNTIME_GOAL_ZONE_2D_BEHAVIOR_KEY,ma as RUNTIME_PLAYER_INPUT_2D_BEHAVIOR_KEY,aa as RUNTIME_RICOCHET_2D_BEHAVIOR_KEY,pa as RUNTIME_TRIGGER_REGION_2D_BEHAVIOR_KEY,Tr as RenderBundleManager,jr as RenderStrategyManager,Ip as ResolutionInputSchema,Dt as Ricochet2DBehavior,Et as Ricochet2DEvent,Gt as Ricochet2DFSM,Mt as Ricochet2DState,Nt as Ricochet3DBehavior,Ot as Ricochet3DEvent,Pt as Ricochet3DFSM,Vt as Ricochet3DState,Um as RuntimeBoundary2DBehavior,Xm as RuntimeDynamicCircleBody2DBehavior,Ym as RuntimeGoalZone2DBehavior,_m as RuntimePlayerInput2DBehavior,$m as RuntimeRicochet2DBehavior,oa as RuntimeTriggerRegion2DBehavior,be as SPHERE_TYPE,Xr as SPRITE_TYPE,fe as STAGE_STATE_CHANGE,qt as ScreenVisibilityBehavior,At as ScreenVisibilityFSM,Ct as ScreenWrapBehavior,Ht as ScreenWrapEvent,It as ScreenWrapFSM,Jt as ScreenWrapState,Kt as Shooter2DBehavior,Zr as SimulationBody,Tp as SpriteEntityDataSchema,Cp as StageAssetLoaderConfigSchema,cp as StageBodyKind,sp as StageBoundaryDim,Hp as StageConfigJsonSchema,np as StageEventType,Ap as StageGLTFAssetLoaderConfigSchema,Fp as StageJsonSchema,Kr as StageManager,lp as StageRicochetDim,Sp as StageRicochetReflection,Zp as StageSchema,hp as StageTopDownPlane,Qr as TEXT_TYPE,bp as TextEntityDataSchema,Gr as ThirdPersonPerspective,Qt as ThrusterBehavior,Rt as ThrusterEvent,Ut as ThrusterFSM,Xt as ThrusterState,Yt as TopDownMovementBehavior,_t as TopDownShooterCoordinator,Po as VEC2_ONE,Oo as VEC2_ZERO,qo as VEC3_ONE,Vo as VEC3_ZERO,qp as Vec3ComponentsSchema,Lp as Vector2Schema,gp as Vector3TupleSchema,Bp as VirtualTouchButtonConfigSchema,Ep as VirtualTouchButtonsConfigSchema,Mp as VirtualTouchConfigSchema,Dp as VirtualTouchJoystickConfigSchema,Gp as VirtualTouchJoysticksConfigSchema,zp as VirtualTouchPositionSchema,wp as VirtualTouchStyleSchema,$t as WorldBoundary2DBehavior,om as WorldBoundary2DEvent,rm as WorldBoundary2DFSM,em as WorldBoundary2DState,tm as WorldBoundary3DBehavior,mm as WorldBoundary3DEvent,am as WorldBoundary3DFSM,pm as WorldBoundary3DState,We as ZONE_TYPE,Lr as ZylemActor,ve as ZylemBox,Oe as ZylemCone,He as ZylemCylinder,Ge as ZylemDisk,gr as ZylemFog,rp as ZylemGameElement,_e as ZylemLight,re as ZylemLine,Ue as ZylemParticleSystem,Ke as ZylemPill,je as ZylemPlane,qe as ZylemPyramid,Be as ZylemRect,ge as ZylemSphere,Yr as ZylemSprite,Rr as ZylemText,ke as ZylemZone,u as abs,$a as announceBridgeReady,Cr as applyTransformChanges,g as asin,b as atan,fa as bindRuntimeDynamicCircleBody2DHandle,fr as boxCollision,se as boxMesh,tp as buildBoxCollider,ap as buildCapsuleCollider,fp as buildConvexHullCollider,pp as buildCylinderCollider,ip as buildHeightfieldCollider,ep as buildRuntimeBody,mp as buildSphereCollider,xp as buildTrimeshCollider,dp as bundleRuntimeCollision,ua as callFunc,L as clamp,A as clearGlobalSubscriptions,fm as computeWorldBoundary2DHits,xm as computeWorldBoundary3DHits,ir as coneCollision,le as coneMesh,Z as cos,Sr as create,vr as createActor,s as createBackgroundShader,Ze as createBox,qr as createCamera,Pe as createCone,ot as createCooldownIcon,Ie as createCylinder,Me as createDisk,hr as createEntity,te as createEntityFactory,im as createFirstPersonInputComponent,dm as createFirstPersonMovementComponent,cm as createFirstPersonStateComponent,ur as createFog,de as createFollowTarget,ae as createGame,N as createGlobal,sm as createJumpConfig2D,nm as createJumpConfig3D,lm as createJumpInput2D,Sm as createJumpInput3D,hm as createJumpState2D,ym as createJumpState3D,$e as createLight,ee as createLine,m as createNodeMaterialFromTSL,Xe as createParticleSystem,Or as createPerspective,Lm as createPhysicsBodyComponent,Qe as createPill,Fe as createPlane,vm as createPlatformer2DInputComponent,Zm as createPlatformer2DMovementComponent,bm as createPlatformer2DStateComponent,gm as createPlatformer3DInputComponent,um as createPlatformer3DMovementComponent,Tm as createPlatformer3DStateComponent,Ae as createPyramid,De as createRect,jm as createShooter2DStateComponent,yp as createSimulation,ue as createSphere,_r as createSprite,Ir as createStage,Ur as createText,Fm as createThrusterInputComponent,Wm as createThrusterMovementComponent,km as createThrusterStateComponent,wm as createTopDownMovementComponent,zm as createTopDownMovementInputComponent,Bm as createTopDownMovementStateComponent,Dm as createTransformComponent,Da as createTransformStore,Wr as createVariable,we as createZone,Eo as crossfadeTransitionShader,cr as cylinderCollision,he as cylinderMesh,C as debugState,Fo as defaultTouchControls,Em as defineBehavior,ga as delay,rt as destroy,ie as dispatchStageState,B as dot,xa as emitRuntimeGoal,ia as emitRuntimeRicochet,da as emitRuntimeTriggerRegionEnter,pe as entitySpawner,ro as entityThumbnailCache,T as exp,Ta as fadeOpacity,Gm as fireCooldown,Mm as fireShooter2DIfRequested,d as float,w as floor,Bo as focusEntity,z as fract,Wo as gameConfig,Nm as getCooldown,Om as getCooldownStore,yo as getDisplayAspect,Pm as getEntityFacingAngle2D,O as getGlobal,q as getGlobals,_ as getHoveredEntity,U as getHoveredEntityId,Aa as getPosition,Lo as getPresetResolution,ar as getRotation,Y as getSelectedEntity,Q as getSelectedEntityId,kr as getVariable,Ca as getVelocity,_a as getZylemBridge,la as globalChange,Sa as globalChanges,Vm as hasAnyWorldBoundary2DHit,qm as hasAnyWorldBoundary3DHit,xe as initStageStateDispatcher,t as isGLSLShader,No as isManagedRenderEntity,e as isTSLShader,So as isWebGPUSupported,uo as joystickBaseSvg,To as joystickThumbSvg,D as length,W as max,lo as mergeInputConfigs,k as min,h as mix,G as mod,Ea as move,va as moveBy,qa as moveForwardXY,Za as moveTo,Ga as moveX,Oa as moveXY,Pa as moveXZ,Ma as moveY,Na as moveZ,S as normalize,Ao as normalizeVec2,Co as normalizeVec3,o as objectVertexShader,P as onGlobalChange,V as onGlobalChanges,Fa as onPress,Wa as onRelease,wr as onVariableChange,zr as onVariableChanges,pr as packCollisionGroups,wa as parallel,vo as parseResolution,Am as particleEffect,Cm as particlePresets,oe as pickZylemLine,sr as pillCollision,ye as pillMesh,sa as pingPongBeep,nr as planeCollision,l as positionWorld,n as positionWorldDirection,j as pow,dr as pyramidCollision,Se as pyramidMesh,Hm as registerCooldown,H as registerDebugEntityResolver,zo as registerEntityFocusContext,za as repeat,Ba as repeatForever,Im as resetCooldown,La as resetEntityOpacity,Va as resetVelocity,Jm as resolveAim2D,go as resolveButtonAccent,I as resolveDebugEntity,Go as resolveRenderCategory,bo as resolveTouchTheme,ca as ricochetSound,ba as rotateBy,Qo as rotateEuler,Jo as rotateInDirection,Uo as rotateX,Ro as rotateY,Ko as rotateYEuler,Xo as rotateZ,Ya as screenCenterLookDeltas,Xa as screenCenterLookTargets,ka as sequence,ce as setCameraFeed,K as setDebugTool,M as setGlobal,X as setHoveredEntityId,J as setPaused,Ha as setPosition,Ia as setPositionX,Ja as setPositionY,Ka as setPositionZ,tr as setRotation,mr as setRotationDegrees,or as setRotationDegreesX,_o as setRotationDegreesY,er as setRotationDegreesZ,$o as setRotationX,Yo as setRotationY,rr as setRotationZ,$ as setSelectedEntity,R as setSelectedEntityId,Br as setStageFrameProfilerEnabled,Fr as setVariable,Ua as shortestAngleDelta,v as sin,y as smoothstep,xr as sphereCollision,ne as sphereMesh,Ar as stageConfig,Jr as stageState,r as standardShader,F as step,ja as throttle,Km as tickCooldowns,f as time,Ho as toThreeVector2,Io as toThreeVector3,jo as touchButtonSvg,Zo as touchThemes,a as uniform,Qm as updateBoundaryRicochet,eo as useArrowsForAxes,mo as useArrowsForDirections,to as useArrowsForSecondaryAxes,Rm as useBehavior,fo as useIJKLForAxes,xo as useIJKLForDirections,so as useMouse,io as useMouseLook,co as useScreenCenterLook,no as useVirtualControls,po as useWASDForAxes,ao as useWASDForDirections,Mo as usesManagedRenderPath,p as uv,ha as variableChange,ya as variableChanges,E as vec2,x as vec3,i as vec4,Hr as vessel,Ra as wrapAround3D,Qa as wrapAroundXY,lr as zoneCollision,wo as zylemEventBus};
@@ -1,5 +1,5 @@
1
- import { G as Game, D as DeviceProfile } from './game-DbqBQiFC.js';
2
- import { D as DebugTools } from './debug-state-DRoeasG2.js';
1
+ import { G as Game, D as DeviceProfile } from './game-NHkubIfI.js';
2
+ import { D as DebugTools } from './debug-state-Dp9CQQZ4.js';
3
3
  import './base-node-life-cycle-BK9xebT9.js';
4
4
  import 'three';
5
5
  import './stage-transition-CmGpV4tc.js';
@@ -1 +1 @@
1
- import{a}from"./chunk-TAUWDQZF.js";import"./chunk-JQKS42G4.js";export{a as ZylemGameElement};
1
+ import{a}from"./chunk-TV3AZKT4.js";import"./chunk-W5SXED5T.js";export{a as ZylemGameElement};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zylem/game-lib",
3
- "version": "0.8.2",
3
+ "version": "0.8.3",
4
4
  "type": "module",
5
5
  "description": "A powerful and easy-to-use framework for creating simple 3D digital interactive applications using TypeScript.",
6
6
  "license": "MIT",
@@ -61,6 +61,10 @@
61
61
  "types": "./dist/debug.d.ts",
62
62
  "import": "./dist/debug.js"
63
63
  },
64
+ "./bridge": {
65
+ "types": "./dist/bridge.d.ts",
66
+ "import": "./dist/bridge.js"
67
+ },
64
68
  "./web-components": {
65
69
  "types": "./dist/web-components.d.ts",
66
70
  "import": "./dist/web-components.js"
@@ -101,7 +105,7 @@
101
105
  "@dgreenheck/three-pinata": "^2.0.1",
102
106
  "@sinclair/typebox": "^0.34.41",
103
107
  "@types/howler": "^2.2.12",
104
- "@zylem/behaviors": "link:../../../behaviors",
108
+ "@zylem/behaviors": "^0.5.8",
105
109
  "comlink": "^4.4.2",
106
110
  "howler": "^2.2.4",
107
111
  "idb-keyval": "^6.2.2",
@@ -110,7 +114,8 @@
110
114
  "stats.js": "^0.17.0",
111
115
  "three": "^0.185.0",
112
116
  "typescript-fsm": "^1.6.0",
113
- "valtio": "^2.1.7"
117
+ "valtio": "^2.1.7",
118
+ "@zylem/bridge": "0.1.1"
114
119
  },
115
120
  "peerDependencies": {
116
121
  "howler": "^2.2.4",
@@ -1,24 +0,0 @@
1
- import{b as ye}from"./chunk-7GYFZKK7.js";import{b}from"./chunk-COM6HJ2L.js";import{b as he,d as P,j as ve,u as L,v as G}from"./chunk-CFVRRRZZ.js";import{a as g,b as me,c as K}from"./chunk-JQKS42G4.js";import{l as Se}from"./chunk-MZZCDXFB.js";import{a as $,r as j}from"./chunk-KVSJE4XD.js";import{j as be}from"./chunk-CM5YRNBJ.js";import{a as fe,b as y}from"./chunk-YHEWKN7N.js";import{c as S}from"./chunk-D2PATZCC.js";import{c as re,d as C,e as le,h as ue,i as pe,j as de,k as J,l as x,m as ce}from"./chunk-4QLJUQSJ.js";import{j as W}from"./chunk-7WRQ2UAN.js";import{g as ge}from"./chunk-PCFF4LLO.js";import{l as v}from"./chunk-UG22Z42P.js";function De(){return{pressed:!1,released:!1,held:0}}function ke(){return{value:0,held:0}}function D(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?De():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?ke():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=D(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 k=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 ze}from"valtio/vanilla";var Ae=.002;function z(a,e,t){return Math.max(e,Math.min(t,a))}function Ve(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 T=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=Ve(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=z((e-o)/(i.width/2),-1,1),this.pointerCenterY=z((t-r)/(i.height/2),-1,1);return}}this.pointerCenterX=z((this.pointerX-.5)*2,-1,1),this.pointerCenterY=z((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??Ae,this.lookMode=e?.lookMode??"delta",this.usePointerLock=e?.pointerLock??!1,this.compiledMapping=D(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=ze(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 R(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 He=["A","B","X","Y","Start","Select","L","R","LTrigger","RTrigger","Up","Down","Left","Right"],Oe=new Set(["flex","flexGrow","flexShrink","fontWeight","lineHeight","opacity","order","zIndex","zoom"]),_e={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"}},Ne={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:R()}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),E(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 He){let i=_e[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=Ne[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",E(n,t.position),E(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??Fe(t.label),n.appendChild(i),n.addEventListener("pointerdown",r=>{if(!we(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",E(n,t.position),E(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??Xe(),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??Ye(),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(!we(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=Ue(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 E(a,e){if(e)for(let[t,n]of Object.entries(e)){if(n==null)continue;let i=typeof n=="number"&&!Oe.has(t)?`${n}px`:String(n);t.includes("-")?a.style.setProperty(t,i):a.style[t]=i}}function Ue(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 Fe(a){let e=Ze(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 Xe(){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 Ye(){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 Ze(a){return a.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;").replaceAll("'","&#39;")}function we(a){return a.pointerType==="touch"}var A=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 k(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 T||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 T(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=q(),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=Je.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=q()-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:q())-this._startTime,this._delta=(this._currentTime-this._previousTime)*this._timescale,this._elapsed+=this._delta),this}};function q(){return performance.now()}function Je(){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 Ce={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 Q(a){return Ce[a].displayAspect}function ee(a,e){let t=Ce[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 te(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 ne=null,ie=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 Ke(a={}){return a.deviceProfile==="mobile"?!0:a.deviceProfile==="desktop"?!1:a.viewportSize?R({viewportSize:a.viewportSize,allowViewportOnly:!0}):R()}function $e(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 We(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 xe=360;function Ge(a,e){if(!a)return;if(typeof a=="string"){if(a==="native")return ne;let i=te(a);if(i)return i;if(e){let o=ee(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 je(a,e,t,n){if(typeof a=="number")return a;if(typeof a=="string")return I[a]??t;if(e)try{return Q(e)||t}catch{return t}return n?n.width/n.height:t}function qe(a){let e=Number.isFinite(a)&&a>0?a:I.SixteenByNine;if(e>=1){let i=xe;return{width:Math.round(i*e),height:i}}let t=xe,n=Math.round(t/e);return{width:t,height:n}}function B(a,e={}){let t=We({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=$e(n,a?.container??null),o=a?.mobile,r=Ke(e),s=r?o?.preset??a?.preset:a?.preset,l=Ge(a?.resolution,a?.preset),u=Ge(o?.resolution,o?.preset??a?.preset),m=(r?Te(u):void 0)??Te(l),p=r?o?.aspectRatio??a?.aspectRatio:a?.aspectRatio,h=je(p,s,t.aspectRatio,m),Z=Qe(r,u,l,h),Ie=a?.fullscreen??t.fullscreen,Be=a?.bodyBackground??t.bodyBackground,Pe=a?.canvas??void 0,Le=et(a?.input??t.input,o?.controls);return new ie(a?.id??t.id,a?.globals??t.globals,a?.stages??t.stages,!!(a?.debug??t.debug),a?.time??t.time,Le,h,Z,Ie,Be,i,n,Pe)}function Te(a){if(a)return a}function Qe(a,e,t,n){if(a)return e===ne?void 0:e??qe(n);if(t!==ne)return t}function et(a,e){if(!e)return a;let n=ge("p1",{enabled:"auto",...e===!0?{}:e});return v(n,a??{})}function tt(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 nt from"stats.js";import{subscribe as it}from"valtio/vanilla";var _=class{statsRef=null;unsubscribe=null;constructor(){this.updateDebugUI(),this.unsubscribe=it(g,()=>{this.updateDebugUI()})}begin(){this.statsRef?.begin()}end(){this.statsRef?.end()}updateDebugUI(){g.enabled&&!this.statsRef?(this.statsRef=new nt,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}`;y.emit(t,e)}wireStageLoading(e,t){let n=e.onLoading(i=>{this.emit({type:i.type,message:i.message??"",progress:i.progress??0,current:i.current,total:i.total,stageName:e.uuid??`Stage ${t}`,stageIndex:t})});typeof n=="function"&&this.stageLoadingUnsubscribes.push(n)}unwireAllStages(){for(let e of this.stageLoadingUnsubscribes)try{e()}catch{}this.stageLoadingUnsubscribes=[]}dispose(){this.unwireAllStages(),this.loadingHandlers=[]}};var U=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 U;eventBusUnsubscribes=[];thumbnailUnsubscribes=[];entityDispatchTimer=null;pendingEntityDispatchPath=null;static ENTITY_DISPATCH_DEBOUNCE_MS=150;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=B(e,this.displayRuntime);this.globalInputConfig=i.input,this.id=i.id,this.stages=i.stages||[],this.container=i.container,this.canvas=i.canvas??null,this.resolvedConfig=i,this.loadGameCanvas(i),this.container=this.gameCanvas?.container??this.container,this.inputManager=new A(i.input,{targetElement:this.gameCanvas?.getOverlayContainer(),mouseTargetElement:this.gameCanvas?.container}),this.loadDebugOptions(e),this.setGlobals(e)}setDisplayRuntime(e){this.displayRuntime={...e};let t=B(this.sourceOptions,this.displayRuntime);this.resolvedConfig=t,this.rendererObserver.setConfig(t),this.gameCanvas?.setAspectRatio(t.aspectRatio),this.emitStateDispatch("@game:display-config")}loadGameCanvas(e){this.gameCanvas=new 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 _}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?ye(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 he,await this.rendererManager.initRenderer()),b.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.emitStateDispatch("@stage:loaded")}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(),b.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`),le(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=de(),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(),me()||(this.timer.update(e),this.step(),this.previousTimeStamp=e),this.debugDelegate?.end(),this.outOfLoop(),this.isDisposed||(this.animationFrameId=requestAnimationFrame(this.frameCallback))}dispose(){this.isDisposed=!0,this.animationFrameId!==null&&(cancelAnimationFrame(this.animationFrameId),this.animationFrameId=null),this.unloadCurrentStage(),this.debugDelegate&&(this.debugDelegate.dispose(),this.debugDelegate=null),this.eventBusUnsubscribes.forEach(e=>e()),this.eventBusUnsubscribes=[],this.rendererObserver.dispose(),this.inputManager.dispose(),this.rendererManager&&(b.setRenderer(null),this.rendererManager.dispose(),this.rendererManager=null),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}}buildEntitiesPayload(){let e=this.currentStage();if(!e?.wrappedStage)return null;let t=[];return e.wrappedStage.entityDelegate.childrenMap.forEach(n=>{if(P(n.options))return;let i=n.constructor.type,o=i?String(i).replace("Symbol(","").replace(")",""):"Unknown",r=n.position??{x:0,y:0,z:0},s=n.rotation??{x:0,y:0,z:0},l=n.scale??{x:1,y:1,z:1},u=b.get(n.uuid);t.push({uuid:n.uuid,name:n.name||"Unnamed",type:o,position:{x:r.x??0,y:r.y??0,z:r.z??0},rotation:{x:s.x??0,y:s.y??0,z:s.z??0},scale:{x:l.x??1,y:l.y??1,z:l.z??1},thumbnail:u?.dataUrl??null,bounds:u?.bounds})}),t}wireEntityThumbnails(e){if(this.clearEntityThumbnailWiring(),!e.wrappedStage)return;let t=r=>{if(P(r.options))return;let s=r.group??r.mesh??null;s&&b.ensure(r.uuid,s).then(l=>{l&&this.queueEntityStateDispatch("@entity:thumbnail")})},n=e.wrappedStage.onEntityAdded(r=>{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&&(b.invalidate(r.entityId),t(s))};y.on("entity:model:loaded",i),this.thumbnailUnsubscribes.push(()=>{y.off("entity:model:loaded",i)});let o=r=>{b.invalidate(r.entityId),this.queueEntityStateDispatch("@entity:destroyed")};y.on("entity:destroyed",o),this.thumbnailUnsubscribes.push(()=>{y.off("entity:destroyed",o)})}clearEntityThumbnailWiring(){this.thumbnailUnsubscribes.forEach(e=>{try{e()}catch{}}),this.thumbnailUnsubscribes=[],this.entityDispatchTimer!==null&&(clearTimeout(this.entityDispatchTimer),this.entityDispatchTimer=null),this.pendingEntityDispatchPath=null}queueEntityStateDispatch(e){this.pendingEntityDispatchPath=e,this.entityDispatchTimer===null&&(this.entityDispatchTimer=setTimeout(()=>{this.entityDispatchTimer=null;let t=this.pendingEntityDispatchPath;this.pendingEntityDispatchPath=null,t&&!this.isDisposed&&this.emitStateDispatch(t)},a.ENTITY_DISPATCH_DEBOUNCE_MS))}emitStateDispatch(e,t,n){let i={scope:"game",path:e,value:t,previousValue:n,config:this.resolvedConfig?{id:this.resolvedConfig.id,aspectRatio:this.resolvedConfig.aspectRatio,fullscreen:this.resolvedConfig.fullscreen,bodyBackground:this.resolvedConfig.bodyBackground,internalResolution:this.resolvedConfig.internalResolution,debug:this.resolvedConfig.debug}:null,stageConfig:this.buildStageConfigPayload(),entities:this.buildEntitiesPayload()};y.emit("state:dispatch",i)}subscribeToEventBus(){this.eventBusUnsubscribes.push(re.on("game:state:updated",e=>{this.emitStateDispatch(e.path,e.value,e.previousValue)}))}};async function Re(a){let{getGameDefaultConfig:e}=await import("./game-default-6AZZCNST.js"),t={...e()},n=[],i=[],o=[];Object.values(a).forEach(s=>{if(s instanceof L)i.push(s);else if(s instanceof j)o.push(s);else if(s instanceof $)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 Ee(a){return!!a.find(t=>t instanceof L)}function ae(a){for(let e of a)if(e&&typeof e=="object"&&!(e instanceof L)&&!(e instanceof $)&&!(e instanceof j)){let t=e;if(t.globals)return t.globals}}import{proxy as at}from"valtio/vanilla";import{get as ot,set as st}from"idb-keyval";import{pack as rt,unpack as lt}from"msgpackr";var c=at({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 ot(a);if(e)return lt(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 st(c.current.id,rt(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 oe={async createFromBlueprint(a){let e=G({});if(a.entities)for(let t of a.entities)try{let n=await Se.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 fe;pendingInputConfig=null;displayRuntime={};refErrorMessage="lost reference to game";constructor(e){this.options=e,Ee(e)||this.options.push(G());let t=ae(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=ae(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 Re(this.options),t=B(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=ue(e,i=>{t(i,this.getCurrentStage())});this.activeGlobalSubscriptions.push(n)}for(let{paths:e,callback:t}of this.globalChangesCallbacks){let n=pe(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 oe.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){oe.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),ce(),x(),be.clearSharedMaterialCache()}dispatch(e,t){this.eventDelegate.dispatch(e,t),y.emit(e,t)}listen(e,t){return this.eventDelegate.listen(e,t)}onLoading(e){return this.wrappedGame?this.wrappedGame.onLoading(e):(this.pendingLoadingCallbacks.push(e),()=>{this.pendingLoadingCallbacks=this.pendingLoadingCallbacks.filter(t=>t!==e),this.wrappedGame})}};function ut(...a){return new Y(a)}import{Euler as pt,Quaternion as dt,Vector2 as ct}from"three";function mt(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 ct(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 dt(p.x,p.y,p.z,p.w);s=new pt().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 ht}from"valtio/vanilla";var se="STAGE_STATE_CHANGE";function gt(){return ht(S,()=>{let a={entities:S.entities,variables:S.variables};window.dispatchEvent(new CustomEvent(se,{detail:a}))})}function ft(){let a={entities:S.entities,variables:S.variables};window.dispatchEvent(new CustomEvent(se,{detail:a}))}import{MathUtils as yt,Vector3 as bt}from"three";var Me={targetKey:"primary",offset:new bt(0,0,0),lerpFactor:.1};function vt(a){let e={...Me,...a,offset:W(a?.offset,Me.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=ve(i);if(!t)t=r.clone();else{let l=yt.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 St}from"three";function wt(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 St({map:i});a.mesh.material=o}export{I as a,Q as b,ee as c,te as d,tt as e,c as f,X as g,Y as h,ut as i,mt as j,se as k,gt as l,ft as m,vt as n,wt as o};