@zylem/game-lib 0.8.6 → 0.8.7

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.
@@ -0,0 +1 @@
1
+ import{b as S,c as v,d as x}from"./chunk-CBUQBP2U.js";import{d as a,h,j as y,o as b,s as f,t as g,u as m}from"./chunk-EVMLNMGU.js";import{subscribe as k}from"valtio/vanilla";import{announceBridgeReady as q,getZylemBridge as l}from"@zylem/bridge";function c(t,e){return[t[0]*e.x,t[1]*e.y,t[2]*e.z]}function E(t,e){let i=new Float32Array(t.length);for(let n=0;n<t.length;n+=3)i[n]=t[n]*e.x,i[n+1]=t[n+1]*e.y,i[n+2]=t[n+2]*e.z;return i}function z(t,e){let{shape:i}=t,n=t.offset?c(t.offset,e):t.offset,o;switch(i.type){case"box":o={type:"box",halfExtents:c(i.halfExtents,e)};break;case"sphere":o={type:"sphere",radius:i.radius*Math.max(e.x,e.y,e.z)};break;case"capsule":case"cylinder":case"cone":o={type:i.type,halfHeight:i.halfHeight*e.y,radius:i.radius*Math.max(e.x,e.z)};break;case"convexHull":o={type:"convexHull",vertices:E(i.vertices,e)};break;case"trimesh":o={type:"trimesh",vertices:E(i.vertices,e),indices:i.indices};break;case"heightfield":o={...i,scale:c(i.scale,e)};break;default:o=i;break}return{...t,shape:o,offset:n}}function V(t){if(!t.colliderBaseline){let e=t.colliderDescs.length?t.colliderDescs:t.colliderDesc?[t.colliderDesc]:[];t.colliderBaseline=e.map(i=>({...i}))}return t.colliderBaseline}function w(t){if(!t.colliderScaleDirty)return!1;t.colliderScaleDirty=!1;let e=V(t);if(!e.length)return!1;let i=t.getScale(),n=e.map(d=>z(d,i));t.colliderDescs=n,t.colliderDesc=n[0];let o=t.physicsWorldRef;if(!o)return!0;let s=t.getPose();return o.destroyEntity(t),s&&t.bodyDesc&&(t.bodyDesc.position=[s.position.x,s.position.y,s.position.z],t.bodyDesc.rotation=[s.rotation.x,s.rotation.y,s.rotation.z,s.rotation.w]),o.addEntity(t),!0}function D(t){return(t?.group??t?.mesh)?.scale}function G(t){let i=(typeof t?.getScale=="function"?t.getScale():void 0)??t?.scale??D(t)??{};return{x:i.x??1,y:i.y??1,z:i.z??1}}function L(t){let e=typeof t?.getPose=="function"?t.getPose():null;if(!e?.rotation)return;let{x:i,y:n,z:o,w:s}=e.rotation;return{x:i,y:n,z:o,w:s}}function u(t){let e=typeof t?.getPose=="function"?t.getPose():null,i=e?.position??{x:0,y:0,z:0},n=e?.rotation??{x:0,y:0,z:0,w:1};return{position:{x:i.x,y:i.y,z:i.z},rotation:x(n),quaternion:{x:n.x,y:n.y,z:n.z,w:n.w},scale:G(t)}}function T(t,e){if(typeof t?.setScale=="function"){t.setScale(e.x,e.y,e.z);return}D(t)?.set?.(e.x,e.y,e.z)}function O(t){!t||typeof t.getScale!="function"||w(t)}function U(t,e){if(!t)return!1;let i=e.quaternion??(e.rotation?v(e.rotation):void 0),n=!1;return(e.position||i)&&typeof t.setPose=="function"&&(n=t.setPose({position:e.position,rotation:i})),e.scale&&(T(t,e.scale),n=!0),n}function K(t){let e=t?.constructor?.type;return e?String(e).replace("Symbol(","").replace(")",""):"Unknown"}function I(t){let e=t;if(!e?.uuid)return;let i=l().channel;if(!i.hasSubscribers("entity:upsert"))return;let n=u(t);i.queue("entity:upsert",[{uuid:e.uuid,name:e.name||"Unnamed",type:K(t),position:n.position,rotation:n.rotation,scale:n.scale,quaternion:n.quaternion}])}function $(t,e){l().channel.send("game:notice",{level:t,message:e})}var P=class{channel;unsubscribes=[];host=null;editorKnown={};applyingSceneOperation=!1;constructor(){this.channel=l().channel}connect(e,i){this.disconnect(),this.host=e,this.unsubscribes.push(this.channel.on("debug:set",({enabled:n})=>{this.editorKnown.debug=n,a.enabled=n}),this.channel.on("tool:set",({tool:n})=>{y(n)}),this.channel.on("playback:set",({paused:n})=>{this.editorKnown.paused=n,h(n)}),this.channel.on("entity:select",({uuid:n})=>{this.editorKnown.selectedUuid=n,b(n)}),this.channel.on("entity:focus",({uuid:n})=>{S(n)}),this.channel.on("entity:transform",({uuid:n,position:o,rotation:s,quaternion:d,scale:p})=>{let r=this.host?.resolveEntity(n);if(!r)return;let C=u(r);if(U(r,{position:o,rotation:s,quaternion:d,scale:p}),p&&O(r),I(r),this.applyingSceneOperation)return;let B=u(r);this.channel.send("scene:operation",{opId:`tx-${n}-${Date.now().toString(36)}`,kind:"transform",label:`Set ${r.name||"entity"} transform`,entries:[{uuid:n,before:C,after:B}]})}),this.channel.on("entity:create",({typeId:n,props:o,pose:s})=>{this.host?.createEntity?.(n,o,s)}),this.channel.on("scene:operation:apply",({op:n,direction:o})=>{this.applyingSceneOperation=!0;try{this.host?.applySceneOperation?.(n,o)}finally{this.applyingSceneOperation=!1}}),this.channel.on("add:type:set",({typeId:n,props:o})=>{m(n,o??null)}),this.channel.on("snap:set",n=>{f(n)}),this.channel.on("grid:set",({visible:n})=>{g(n)}),this.channel.on("stage:variable:set",({key:n,value:o})=>{this.host?.setStageVariable?.(n,o)}),this.channel.on("entity:apply-swatch",n=>{this.host?.applySwatch?.(n)}),k(a,()=>this.publishDebugStateChanges())),this.publishDebugStateChanges(),q(i)}disconnect(){for(let e of this.unsubscribes)e();this.unsubscribes=[],this.host=null,this.editorKnown={}}publishDebugStateChanges(){let e={};a.paused!==this.editorKnown.paused&&(this.editorKnown.paused=a.paused,e.paused=a.paused),a.enabled!==this.editorKnown.debug&&(this.editorKnown.debug=a.enabled,e.debug=a.enabled),(e.paused!==void 0||e.debug!==void 0)&&this.publishStatus(e),(a.selectedEntityId!==this.editorKnown.selectedUuid||a.hoveredEntityId!==this.editorKnown.hoveredUuid)&&(this.editorKnown.selectedUuid=a.selectedEntityId,this.editorKnown.hoveredUuid=a.hoveredEntityId,this.channel.queue("entity:selection",{selectedUuid:a.selectedEntityId,hoveredUuid:a.hoveredEntityId,selectedUuids:[...a.selectedEntityIds]}))}wantsEntityUpdates(){return this.channel.hasSubscribers("entity:upsert")||this.channel.hasSubscribers("stage:snapshot")}wantsThumbnails(){return this.channel.hasSubscribers("entity:thumbnail")}onEditorAttached(e){return this.channel.onSubscriberAdded(i=>{if(i!=="entity:upsert"&&i!=="entity:thumbnail")return;let n=i==="entity:upsert"?"entity:thumbnail":"entity:upsert";this.channel.subscriberCount(n)>0||e()})}publishConfig(e){this.channel.send("game:config",e)}publishLoading(e){this.channel.send("game:loading",e)}publishStatus(e){this.channel.queue("game:status",e)}publishVariable(e){this.channel.send("game:variable",e)}publishNotice(e,i){this.channel.send("game:notice",{level:e,message:i})}publishStageSnapshot(e){this.channel.send("stage:snapshot",e)}queueEntityUpsert(e){e.length&&this.channel.queue("entity:upsert",e)}queueEntityRemoved(e){e.length&&this.channel.queue("entity:removed",{uuids:e})}queueThumbnails(e){e.length&&this.channel.queue("entity:thumbnail",e)}publishCatalog(e){this.channel.send("catalog:snapshot",{entities:e})}publishSceneOperation(e){this.channel.send("scene:operation",e)}wantsSceneOperations(){return this.channel.hasSubscribers("scene:operation")}};function j(t){l().channel.send("scene:operation",t)}export{w as a,G as b,L as c,K as d,$ as e,P as f,j as g};
package/dist/core.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { B as Stage, E as StageStateInterface, C as CameraWrapper } from './game-Cy8f6gJm.js';
2
- export { A as AspectRatio, q as AspectRatioValue, k as CameraManager, j as CameraOptions, D as DeviceProfile, p as FirstPersonOptions, l as FirstPersonPerspective, o as Fixed2DOptions, F as Fixed2DPerspective, G as Game, b as GameConfigLike, d as GameDeviceConfig, a as GameLoadingEvent, P as PerspectiveOptions, y as RenderBundleManager, z as RenderStrategyManager, R as ResolutionInput, e as ResolveGameConfigRuntime, v as RetroPreset, w as RetroPresetKey, x as RetroResolution, S as StageConfigLike, h as StageOptions, n as ThirdPersonOptions, T as ThirdPersonPerspective, i as createCamera, c as createGame, m as createPerspective, f as createStage, g as gameConfig, r as getDisplayAspect, t as getPresetResolution, u as parseResolution, s as stageConfig } from './game-Cy8f6gJm.js';
1
+ import { B as Stage, E as StageStateInterface, C as CameraWrapper } from './game-BPOr7zTB.js';
2
+ export { A as AspectRatio, q as AspectRatioValue, k as CameraManager, j as CameraOptions, D as DeviceProfile, p as FirstPersonOptions, l as FirstPersonPerspective, o as Fixed2DOptions, F as Fixed2DPerspective, G as Game, b as GameConfigLike, d as GameDeviceConfig, a as GameLoadingEvent, P as PerspectiveOptions, y as RenderBundleManager, z as RenderStrategyManager, R as ResolutionInput, e as ResolveGameConfigRuntime, v as RetroPreset, w as RetroPresetKey, x as RetroResolution, S as StageConfigLike, h as StageOptions, n as ThirdPersonOptions, T as ThirdPersonPerspective, i as createCamera, c as createGame, m as createPerspective, f as createStage, g as gameConfig, r as getDisplayAspect, t as getPresetResolution, u as parseResolution, s as stageConfig } from './game-BPOr7zTB.js';
3
3
  export { G as GameInputConfig, a as GameInputPlayerConfig, K as KeyboardMapping, M as MouseConfig, b as MouseMapping, V as VirtualTouchButtonConfig, d as VirtualTouchButtonSlot, c as VirtualTouchButtonsConfig, e as VirtualTouchConfig, f as VirtualTouchJoystickConfig, g as VirtualTouchJoysticksConfig, h as VirtualTouchPosition, i as VirtualTouchStyle, Z as ZylemGameConfig } from './game-interfaces-vF5sRi1n.js';
4
4
  import { Vector2 } from 'three';
5
5
  import { G as GameEntity, a as GameEntityOptions } from './entity-XZNGBeca.js';
package/dist/core.js CHANGED
@@ -1 +1 @@
1
- import{a as b,b as c,c as d,d as e,e as f,f as H,g as I,h as J,i as K,j as L,k as M,l as N,m as O,n as P,o as Q}from"./chunk-LD4KDRYL.js";import{a,c as p,d as q,e as r,f as s,g as t,h as u,i as v,k as w,l as x,m as y,n as z,o as A,p as B,q as C,r as D,s as E,t as F,v as G}from"./chunk-FYQNZCIP.js";import{a as o}from"./chunk-7GYFZKK7.js";import"./chunk-Q2YDBMVY.js";import"./chunk-BCFFS3FP.js";import"./chunk-QDQ4QMAI.js";import"./chunk-AE3CTVHY.js";import"./chunk-DQQA3VJH.js";import"./chunk-VJZMSBKP.js";import"./chunk-DECK4UEC.js";import"./chunk-WBQ5TNRZ.js";import"./chunk-YOVE25NW.js";import"./chunk-MXO4VGDB.js";import"./chunk-BMRFDDMR.js";import"./chunk-SAQA4SXW.js";import"./chunk-7NYP4YAG.js";import"./chunk-AIQ6IVT5.js";import"./chunk-QXVH6POE.js";import"./chunk-EVYHPR3J.js";import"./chunk-D2PATZCC.js";import"./chunk-4QLJUQSJ.js";import{a as g,b as h,c as i,d as j,g as k,h as l,i as m,j as n}from"./chunk-7WRQ2UAN.js";import"./chunk-BH53MBAZ.js";import"./chunk-XRP4JJXL.js";import"./chunk-PCFF4LLO.js";import"./chunk-UG22Z42P.js";export{b as AspectRatio,B as CameraManager,w as CameraPipeline,C as CameraWrapper,z as FirstPersonPerspective,y as Fixed2DPerspective,J as Game,v as Perspectives,s as RenderBundleManager,t as RenderStrategyManager,M as STAGE_STATE_CHANGE,I as StageManager,x as ThirdPersonPerspective,h as VEC2_ONE,g as VEC2_ZERO,j as VEC3_ONE,i as VEC3_ZERO,D as createCamera,P as createFollowTarget,K as createGame,A as createPerspective,G as createStage,o as crossfadeTransitionShader,O as dispatchStageState,L as entitySpawner,f as gameConfig,c as getDisplayAspect,d as getPresetResolution,N as initStageStateDispatcher,r as isManagedRenderEntity,a as isWebGPUSupported,k as normalizeVec2,l as normalizeVec3,e as parseResolution,p as resolveRenderCategory,Q as setCameraFeed,u as setStageFrameProfilerEnabled,E as stageConfig,H as stageState,m as toThreeVector2,n as toThreeVector3,q as usesManagedRenderPath,F as vessel};
1
+ import{a as b,b as c,c as d,d as e,e as f,f as H,g as I,h as J,i as K,j as L,k as M,l as N,m as O,n as P,o as Q}from"./chunk-F5LROYZL.js";import{a,c as p,d as q,e as r,f as s,g as t,h as u,i as v,k as w,l as x,m as y,n as z,o as A,p as B,q as C,r as D,s as E,t as F,v as G}from"./chunk-IBJLPJLE.js";import{a as o}from"./chunk-7GYFZKK7.js";import"./chunk-Q2YDBMVY.js";import"./chunk-BCFFS3FP.js";import"./chunk-QDQ4QMAI.js";import"./chunk-AE3CTVHY.js";import"./chunk-ZTYNZ2N2.js";import"./chunk-CBUQBP2U.js";import"./chunk-EVMLNMGU.js";import"./chunk-WBQ5TNRZ.js";import"./chunk-YOVE25NW.js";import"./chunk-MXO4VGDB.js";import"./chunk-BMRFDDMR.js";import"./chunk-SAQA4SXW.js";import"./chunk-7NYP4YAG.js";import"./chunk-AIQ6IVT5.js";import"./chunk-QXVH6POE.js";import"./chunk-EVYHPR3J.js";import"./chunk-D2PATZCC.js";import"./chunk-4QLJUQSJ.js";import{a as g,b as h,c as i,d as j,g as k,h as l,i as m,j as n}from"./chunk-7WRQ2UAN.js";import"./chunk-BH53MBAZ.js";import"./chunk-XRP4JJXL.js";import"./chunk-PCFF4LLO.js";import"./chunk-UG22Z42P.js";export{b as AspectRatio,B as CameraManager,w as CameraPipeline,C as CameraWrapper,z as FirstPersonPerspective,y as Fixed2DPerspective,J as Game,v as Perspectives,s as RenderBundleManager,t as RenderStrategyManager,M as STAGE_STATE_CHANGE,I as StageManager,x as ThirdPersonPerspective,h as VEC2_ONE,g as VEC2_ZERO,j as VEC3_ONE,i as VEC3_ZERO,D as createCamera,P as createFollowTarget,K as createGame,A as createPerspective,G as createStage,o as crossfadeTransitionShader,O as dispatchStageState,L as entitySpawner,f as gameConfig,c as getDisplayAspect,d as getPresetResolution,N as initStageStateDispatcher,r as isManagedRenderEntity,a as isWebGPUSupported,k as normalizeVec2,l as normalizeVec3,e as parseResolution,p as resolveRenderCategory,Q as setCameraFeed,u as setStageFrameProfilerEnabled,E as stageConfig,H as stageState,m as toThreeVector2,n as toThreeVector3,q as usesManagedRenderPath,F as vessel};
@@ -41,6 +41,11 @@ interface DebugState {
41
41
  addTypeId: string | null;
42
42
  /** Creation options merged over the armed type's defaults. */
43
43
  addTypeProps: Record<string, unknown> | null;
44
+ /**
45
+ * Host-driven hover picking (e.g. Creator swatch drag). Raycasts even when
46
+ * the Select tool is not armed, and keeps the hover highlight painted.
47
+ */
48
+ pickMode: boolean;
44
49
  flags: Set<string>;
45
50
  }
46
51
  declare const debugState: DebugState;
@@ -58,6 +63,9 @@ declare function registerDebugEntityResolver(resolver: DebugEntityResolver): ()
58
63
  declare function resolveDebugEntity(uuid: string | null): GameEntity<any> | null;
59
64
  declare function setPaused(paused: boolean): void;
60
65
  declare function setDebugTool(tool: DebugTools): void;
66
+ /** Hosts arm this while forwarding pointer coords for entity hover (no Select tool). */
67
+ declare function setPickMode(enabled: boolean): void;
68
+ declare function isPickMode(): boolean;
61
69
  declare function getSelectedEntityId(): string | null;
62
70
  declare function setSelectedEntityId(uuid: string | null): void;
63
71
  /** Every selected uuid, in click order. */
@@ -86,4 +94,4 @@ declare function getHoveredEntity(): GameEntity<any> | null;
86
94
  */
87
95
  declare function setSelectedEntity(entity: GameEntity<any> | string | null): void;
88
96
 
89
- export { DEFAULT_SNAP_SETTINGS as D, type SnapSettings as S, TRANSFORM_TOOLS as T, setPaused as a, setSelectedEntity as b, setSelectedEntityId as c, debugState as d, getSelectedEntity as e, setSelectedEntityIds as f, getSelectedEntityId as g, getSelectedEntityIds as h, setHoveredEntityId as i, getHoveredEntityId as j, getHoveredEntity as k, resolveDebugEntity as l, getSnapSettings as m, setSnapSettings as n, setGridVisible as o, setAddType as p, isTransformTool as q, registerDebugEntityResolver as r, setDebugTool as s, type DebugTools as t, type DebugEntityResolver as u, type TransformTool as v };
97
+ export { DEFAULT_SNAP_SETTINGS as D, type SnapSettings as S, TRANSFORM_TOOLS as T, setPaused as a, setSelectedEntity as b, setSelectedEntityId as c, debugState as d, getSelectedEntity as e, setSelectedEntityIds as f, getSelectedEntityId as g, getSelectedEntityIds as h, setHoveredEntityId as i, getHoveredEntityId as j, getHoveredEntity as k, resolveDebugEntity as l, getSnapSettings as m, setSnapSettings as n, setGridVisible as o, setAddType as p, setPickMode as q, registerDebugEntityResolver as r, setDebugTool as s, isPickMode as t, isTransformTool as u, type DebugTools as v, type DebugEntityResolver as w, type TransformTool as x };
package/dist/debug.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- export { D as DEFAULT_SNAP_SETTINGS, u as DebugEntityResolver, t as DebugTools, S as SnapSettings, T as TRANSFORM_TOOLS, v as TransformTool, d as debugState, k as getHoveredEntity, j as getHoveredEntityId, e as getSelectedEntity, g as getSelectedEntityId, h as getSelectedEntityIds, m as getSnapSettings, q as isTransformTool, r as registerDebugEntityResolver, l as resolveDebugEntity, p as setAddType, s as setDebugTool, o as setGridVisible, i as setHoveredEntityId, a as setPaused, b as setSelectedEntity, c as setSelectedEntityId, f as setSelectedEntityIds, n as setSnapSettings } from './debug-state-B5awuDHl.js';
1
+ export { D as DEFAULT_SNAP_SETTINGS, w as DebugEntityResolver, v as DebugTools, S as SnapSettings, T as TRANSFORM_TOOLS, x as TransformTool, d as debugState, k as getHoveredEntity, j as getHoveredEntityId, e as getSelectedEntity, g as getSelectedEntityId, h as getSelectedEntityIds, m as getSnapSettings, t as isPickMode, u as isTransformTool, r as registerDebugEntityResolver, l as resolveDebugEntity, p as setAddType, s as setDebugTool, o as setGridVisible, i as setHoveredEntityId, a as setPaused, q as setPickMode, b as setSelectedEntity, c as setSelectedEntityId, f as setSelectedEntityIds, n as setSnapSettings } from './debug-state-CpnNRUFh.js';
2
2
  import * as three from 'three';
3
3
  import { Group, Scene, Vector3, Camera, Object3D } from 'three';
4
4
  import { c as Vec3 } from './vector-D3eDzvcA.js';
package/dist/debug.js CHANGED
@@ -1 +1 @@
1
- import"./chunk-MSCVL5OK.js";import{a as v,b as w}from"./chunk-Q2YDBMVY.js";import{c as G,d as H,e as I,f as J}from"./chunk-BCFFS3FP.js";import{a as x,b as y,c as z,d as A,e as B,f as C,g as D,h as E,i as F}from"./chunk-VJZMSBKP.js";import{a,b,c,d,e,f,h as g,j as h,l as i,m as j,n as k,o as l,p as m,q as n,r as o,s as p,t as q,u as r,w as s,x as t,y as u}from"./chunk-DECK4UEC.js";export{G as ConstructionGrid,c as DEFAULT_SNAP_SETTINGS,v as EntityThumbnailCache,a as TRANSFORM_TOOLS,J as TransformGizmo,H as closestAxisValue,d as debugState,E as degreesToRadians,w as entityThumbnailCache,z as eulerToQuaternion,y as focusEntity,t as getHoveredEntity,q as getHoveredEntityId,s as getSelectedEntity,i as getSelectedEntityId,k as getSelectedEntityIds,m as getSnapSettings,I as intersectPlane,b as isTransformTool,A as quaternionToEuler,F as radiansToDegrees,e as registerDebugEntityResolver,x as registerEntityFocusContext,f as resolveDebugEntity,p as setAddType,h as setDebugTool,o as setGridVisible,r as setHoveredEntityId,g as setPaused,u as setSelectedEntity,j as setSelectedEntityId,l as setSelectedEntityIds,n as setSnapSettings,D as snapScale,B as snapToIncrement,C as snapVec3};
1
+ import"./chunk-MSCVL5OK.js";import{a as x,b as y}from"./chunk-Q2YDBMVY.js";import{c as I,d as J,e as K,f as L}from"./chunk-BCFFS3FP.js";import{a as z,b as A,c as B,d as C,e as D,f as E,g as F,h as G,i as H}from"./chunk-CBUQBP2U.js";import{A as w,a,b,c,d,e,f,h as g,j as h,l as i,m as j,n as k,o as l,p as m,q as n,r as o,s as p,t as q,u as r,v as s,w as t,y as u,z as v}from"./chunk-EVMLNMGU.js";export{I as ConstructionGrid,c as DEFAULT_SNAP_SETTINGS,x as EntityThumbnailCache,a as TRANSFORM_TOOLS,L as TransformGizmo,J as closestAxisValue,d as debugState,G as degreesToRadians,y as entityThumbnailCache,B as eulerToQuaternion,A as focusEntity,v as getHoveredEntity,s as getHoveredEntityId,u as getSelectedEntity,k as getSelectedEntityId,m as getSelectedEntityIds,o as getSnapSettings,K as intersectPlane,j as isPickMode,b as isTransformTool,C as quaternionToEuler,H as radiansToDegrees,e as registerDebugEntityResolver,z as registerEntityFocusContext,f as resolveDebugEntity,r as setAddType,h as setDebugTool,q as setGridVisible,t as setHoveredEntityId,g as setPaused,i as setPickMode,w as setSelectedEntity,l as setSelectedEntityId,n as setSelectedEntityIds,p as setSnapSettings,F as snapScale,D as snapToIncrement,E as snapVec3};
@@ -949,6 +949,15 @@ declare class StageDebugDelegate {
949
949
  private parkToolVisuals;
950
950
  private disposeToolVisuals;
951
951
  update(): void;
952
+ /**
953
+ * Raycast at NDC coordinates (from a host that cannot send DOM pointer
954
+ * events, e.g. an overlay sitting on a preview iframe). Updates hover so
955
+ * the next `update()` paints the highlight.
956
+ */
957
+ pickAtNdc(ndcX: number, ndcY: number): {
958
+ uuid: string;
959
+ name: string;
960
+ } | null;
952
961
  /** Collider wireframes, straight from the wasm simulation. */
953
962
  private updateColliderWireframes;
954
963
  /**
@@ -1346,6 +1355,11 @@ declare class StageEntityDelegate {
1346
1355
  */
1347
1356
  destroyAll(): void;
1348
1357
  private registerBehaviorLinks;
1358
+ /**
1359
+ * Re-index an entity's behavior refs after a late `entity.use(...)`.
1360
+ * Spawn-time registration only sees refs that existed at attach.
1361
+ */
1362
+ syncBehaviorLinks(entity: any): void;
1349
1363
  private unregisterBehaviorLinks;
1350
1364
  }
1351
1365
 
@@ -1 +1 @@
1
- import{v as e}from"./chunk-FYQNZCIP.js";import"./chunk-BCFFS3FP.js";import"./chunk-AE3CTVHY.js";import"./chunk-DQQA3VJH.js";import"./chunk-VJZMSBKP.js";import"./chunk-DECK4UEC.js";import"./chunk-WBQ5TNRZ.js";import"./chunk-MXO4VGDB.js";import"./chunk-SAQA4SXW.js";import"./chunk-7NYP4YAG.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};
1
+ import{v as e}from"./chunk-IBJLPJLE.js";import"./chunk-BCFFS3FP.js";import"./chunk-AE3CTVHY.js";import"./chunk-ZTYNZ2N2.js";import"./chunk-CBUQBP2U.js";import"./chunk-EVMLNMGU.js";import"./chunk-WBQ5TNRZ.js";import"./chunk-MXO4VGDB.js";import"./chunk-SAQA4SXW.js";import"./chunk-7NYP4YAG.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-Cy8f6gJm.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-BPOr7zTB.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';
@@ -21,10 +21,10 @@ export { EntityEvents, EventEmitterDelegate, GameEvents, GameLoadingPayload, Sta
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 DEFAULT_SNAP_SETTINGS, u as DebugEntityResolver, t as DebugTools, S as SnapSettings, T as TRANSFORM_TOOLS, v as TransformTool, d as debugState, k as getHoveredEntity, j as getHoveredEntityId, e as getSelectedEntity, g as getSelectedEntityId, h as getSelectedEntityIds, m as getSnapSettings, q as isTransformTool, r as registerDebugEntityResolver, l as resolveDebugEntity, p as setAddType, s as setDebugTool, o as setGridVisible, i as setHoveredEntityId, a as setPaused, b as setSelectedEntity, c as setSelectedEntityId, f as setSelectedEntityIds, n as setSnapSettings } from './debug-state-B5awuDHl.js';
24
+ export { D as DEFAULT_SNAP_SETTINGS, w as DebugEntityResolver, v as DebugTools, S as SnapSettings, T as TRANSFORM_TOOLS, x as TransformTool, d as debugState, k as getHoveredEntity, j as getHoveredEntityId, e as getSelectedEntity, g as getSelectedEntityId, h as getSelectedEntityIds, m as getSnapSettings, t as isPickMode, u as isTransformTool, r as registerDebugEntityResolver, l as resolveDebugEntity, p as setAddType, s as setDebugTool, o as setGridVisible, i as setHoveredEntityId, a as setPaused, q as setPickMode, b as setSelectedEntity, c as setSelectedEntityId, f as setSelectedEntityIds, n as setSnapSettings } from './debug-state-CpnNRUFh.js';
25
25
  export { ConstructionGrid, EntityFocusContext, EntityThumbnailCache, EntityThumbnailCacheEntry, EntityThumbnailResult, GizmoAxis, GizmoDelta, GizmoMode, GizmoRay, Quat, TransformGizmo, closestAxisValue, degreesToRadians, entityThumbnailCache, eulerToQuaternion, focusEntity, intersectPlane, quaternionToEuler, radiansToDegrees, registerEntityFocusContext, snapScale, snapToIncrement, snapVec3 } from './debug.js';
26
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';
27
+ export { BRIDGE_READY_EVENT, BridgeChannel, BridgeDebugTool, BridgeHandler, GameLoadingPayload as BridgeLoadingPayload, BridgeMessageType, BridgeMessages, BridgeVec3, EditorToGameMessages, EntityApplySwatchPayload, EntitySummaryPayload, EntityThumbnailPayload, GameConfigPayload, GameToEditorMessages, GameVariablePayload, StageConfigPayload, StageSnapshotPayload, ZylemBridge, announceBridgeReady, getZylemBridge } from '@zylem/bridge';
28
28
  export { ZylemGameElement, ZylemGameState } from './web-components.js';
29
29
  export { a as SimulationBody, S as SimulationStepClock } from './simulation-body-zQw-emOr.js';
30
30
  export { RuntimeBodyOptions, RuntimeColliderOptions, RuntimeCollisionBundle, buildBoxCollider, buildCapsuleCollider, buildConvexHullCollider, buildCylinderCollider, buildHeightfieldCollider, buildRuntimeBody, buildSphereCollider, buildTrimeshCollider, bundleRuntimeCollision } from './runtime.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-MSCVL5OK.js";import{a as Lp,b as vp,c as Zp}from"./chunk-HNCTOJP7.js";import{a as bp}from"./chunk-QVIUZEYA.js";import{a as gp,b as up,c as Tp,d as jp,e as Fp,f as Wp,g as kp,h as wp,i as zp,j as Bp,k as Dp,l as Ep,m as Gp,n as Mp,o as Np,p as Op}from"./chunk-47DG7I7M.js";import{A as cf,B as sf,C as nf,a as Pp,b as Vp,c as qp,d as Ap,e as Cp,f as Hp,g as Ip,h as Jp,i as Kp,j as Qp,k as Rp,l as Up,m as Xp,n as Yp,o as _p,p as $p,q as of,r as rf,s as ef,t as tf,u as mf,v as af,w as pf,x as ff,y as xf,z as df}from"./chunk-JNFFTNMH.js";import{a as jo,b as Fo,c as Wo,d as ko,e as No,f as Xe,g as Ye,h as it,i as dt,j as ct,k as st,l as nt,m as lt,n as St,o as ht}from"./chunk-LD4KDRYL.js";import{a as To,c as Se,d as he,e as ye,f as je,g as Fe,h as Ne,i as Oe,k as Pe,l as Ve,m as qe,n as Ae,o as Ce,p as He,q as Ie,r as Je,s as Ke,t as Re,v as Ue}from"./chunk-FYQNZCIP.js";import{a as le}from"./chunk-7GYFZKK7.js";import{a as io,b as co}from"./chunk-Q2YDBMVY.js";import{c as De,d as Ee,e as Ge,f as Me}from"./chunk-BCFFS3FP.js";import"./chunk-QDQ4QMAI.js";import"./chunk-AE3CTVHY.js";import{f as Ro}from"./chunk-DQQA3VJH.js";import{a as Vo,b as qo,c as Ao,d as Co,e as Ho,f as Io,g as Jo,h as Ko,i as Qo}from"./chunk-VJZMSBKP.js";import{a as C,b as H,c as I,d as J,e as K,f as Q,h as R,j as U,l as X,m as Y,n as _,o as $,p as oo,q as ro,r as eo,s as to,t as mo,u as ao,w as po,x as fo,y as xo}from"./chunk-DECK4UEC.js";import{b as be}from"./chunk-WBQ5TNRZ.js";import{a as yt,b as Lt,c as vt,d as Zt,e as bt}from"./chunk-GHJQ2HKI.js";import{a as _e,b as $e,c as ot,d as rt,e as et,f as tt,g as mt,h as at,i as pt,j as ft,l as xt}from"./chunk-YOVE25NW.js";import{a as Le,b as ve,c as Ze,d as ge,e as ue,f as Te}from"./chunk-MXO4VGDB.js";import{A as oe,B as re,C as ee,D as te,E as me,F as ae,G as pe,H as fe,I as xe,J as ie,K as de,L as ce,M as se,N as ne,b as kr,c as wr,d as zr,e as Br,f as Dr,g as Er,h as Gr,i as Mr,j as Nr,k as Or,l as Pr,m as Vr,n as qr,o as Ar,p as Cr,q as Hr,r as Ir,s as Jr,t as Kr,u as Qr,v as Rr,w as Ur,x as Xr,y as Yr,z as $r}from"./chunk-BMRFDDMR.js";import{c as vr,d as Zr,e as br,f as gr,g as ur,h as Tr,i as jr,j as Fr,u as Wr,z as _r}from"./chunk-SAQA4SXW.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-7NYP4YAG.js";import{a as Oo,b as Po}from"./chunk-AIQ6IVT5.js";import"./chunk-QXVH6POE.js";import{b as Lr}from"./chunk-EVYHPR3J.js";import{$ as bm,$a as ba,A as Rt,Aa as Rm,B as Ut,Ba as Um,C as Xt,Ca as Xm,D as Yt,Da as Ym,E as _t,Ea as _m,F as $t,Fa as $m,G as om,Ga as oa,H as rm,Ha as ra,I as em,Ia as ea,J as tm,Ja as ta,K as mm,Ka as ma,L as am,La as aa,M as pm,Ma as pa,N as fm,Na as fa,O as xm,Oa as xa,P as im,Pa as ia,Q as dm,Qa as da,R as cm,Ra as ca,S as sm,Sa as sa,T as nm,Ta as na,U as lm,Ua as la,V as Sm,Va as Sa,W as hm,Wa as ha,X as ym,Xa as ya,Y as Lm,Ya as La,Z as vm,Za as va,_ as Zm,_a as Za,a as gt,aa as gm,ab as ga,b as ut,ba as um,bb as ua,c as Tt,ca as Tm,cb as Ta,d as jt,da as jm,db as ja,e as Ft,ea as Fm,eb as Fa,f as Wt,fa as Wm,fb as Wa,g as kt,ga as km,gb as ka,h as wt,ha as wm,hb as wa,i as zt,ia as zm,ib as za,j as Bt,ja as Bm,k as Dt,ka as Dm,l as Et,la as Em,m as Gt,ma as Gm,n as Mt,na as Mm,o as Nt,oa as Nm,p as Ot,pa as Om,q as Pt,qa as Pm,r as Vt,ra as Vm,s as qt,sa as qm,t as At,ta as Am,u as Ct,ua as Cm,v as Ht,va as Hm,w as It,wa as Im,x as Jt,xa as Jm,y as Kt,ya as Km,z as Qt,za as Qm}from"./chunk-XK63E4SX.js";import{a as Ba,b as Da,c as Ea}from"./chunk-ZRT3ZQVH.js";import{a as Ga,b as Ma,c as Na,d as Oa}from"./chunk-WQ3WMMZD.js";import{h as We,i as ke,j as we,k as ze,l as Be}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 Uo,b as Xo,c as Yo,d as _o,g as $o,h as or,i as rr,j as er}from"./chunk-7WRQ2UAN.js";import{A as dp,B as cp,C as sp,D as np,E as lp,a as Pa,b as Va,c as qa,d as Aa,e as Ca,f as Ha,g as Ia,h as Ja,i as Ka,j as Qa,k as Ra,l as Ua,m as Xa,n as Ya,o as _a,p as $a,q as op,r as rp,s as ep,t as tp,u as mp,v as ap,w as pp,x as fp,y as xp,z as ip}from"./chunk-IPWUDOV5.js";import{a as Qe}from"./chunk-BH53MBAZ.js";import{a as tr,b as mr,c as ar,d as pr,e as fr,f as xr,g as ir,h as dr,i as cr,j as sr,k as nr,l as lr,m as Sr,n as hr,o as yr}from"./chunk-XRP4JJXL.js";import{a as Sp,b as hp,c as yp}from"./chunk-7QF6YTEZ.js";import"./chunk-ORIDWL3T.js";import{a as wo,b as zo,c as Bo,d as Do,e as Eo,f as Go,g as Mo}from"./chunk-PCFF4LLO.js";import{a as so,b as no,c as lo,d as So,e as ho,f as yo,g as Lo,h as vo,i as Zo,j as bo,k as go,l as uo}from"./chunk-UG22Z42P.js";export{Le as ACTOR_TYPE,jo as AspectRatio,Gr as BOX_TYPE,Zp as BRIDGE_READY_EVENT,gt as BoundaryRicochet3DCoordinator,ut as BoundaryRicochetCoordinator,qr as CONE_TYPE,Kr as CYLINDER_TYPE,He as CameraManager,Pe as CameraPipeline,Ie as CameraWrapper,af as ColorJsonSchema,De as ConstructionGrid,Tt as CooldownBehavior,I as DEFAULT_SNAP_SETTINGS,$r as DISK_TYPE,jt as Destructible3DBehavior,Ft as DestructibleMesh,Jp as EntityJsonSchema,Vp as EntitySchema,io as EntityThumbnailCache,Oo as EventEmitterDelegate,ge as FOG_TYPE,Wt as FirstPersonBehavior,kt as FirstPersonEvent,wt as FirstPersonFSM,Ae as FirstPersonPerspective,Dt as FirstPersonPresentation,zt as FirstPersonShooterCoordinator,Bt as FirstPersonState,qe as Fixed2DPerspective,c as Fn,Et as FractureOptions,it as Game,Ro as GameBridge,nf as GameConfigJsonSchema,sf as GameDeviceConfigJsonSchema,mf as GameInputConfigSchema,tf as GameInputPlayerConfigSchema,Ea as Howl,Gt as Jumper2DBehavior,Mt as Jumper2DEvent,Nt as Jumper2DFSM,Ot as Jumper2DState,Pt as Jumper3DBehavior,Vt as Jumper3DEvent,qt as Jumper3DFSM,At as Jumper3DState,Qp as KeyboardMappingSchema,ce as LIGHT_TYPE,mt as LINE_TYPE,Hp as LineEntityDataSchema,ef as MouseConfigSchema,Rp as MouseMappingSchema,Ct as MultidirectionalSpaceShooterCoordinator,yt as PARTICLE_SYSTEM_TYPE,Ur as PILL_TYPE,ee as PLANE_TYPE,Hr as PYRAMID_TYPE,Ht as ParticleEmitterBehavior,Oe as Perspectives,It as Platformer2DBehavior,Jt as Platformer2DEvent,Kt as Platformer2DFSM,Qt as Platformer2DState,Rt as Platformer3DBehavior,Ut as Platformer3DEvent,Xt as Platformer3DFSM,Yt as Platformer3DState,xe as RECT_TYPE,ba as RUNTIME_BOUNDARY_2D_BEHAVIOR_KEY,ga as RUNTIME_DYNAMIC_CIRCLE_BODY_2D_BEHAVIOR_KEY,ua as RUNTIME_GOAL_ZONE_2D_BEHAVIOR_KEY,Ta as RUNTIME_PLAYER_INPUT_2D_BEHAVIOR_KEY,ja as RUNTIME_RICOCHET_2D_BEHAVIOR_KEY,Fa as RUNTIME_TRIGGER_REGION_2D_BEHAVIOR_KEY,je as RenderBundleManager,Fe as RenderStrategyManager,cf as ResolutionInputSchema,_t as Ricochet2DBehavior,$t as Ricochet2DEvent,om as Ricochet2DFSM,rm as Ricochet2DState,em as Ricochet3DBehavior,tm as Ricochet3DEvent,mm as Ricochet3DFSM,am as Ricochet3DState,Sa as RuntimeBoundary2DBehavior,ha as RuntimeDynamicCircleBody2DBehavior,ya as RuntimeGoalZone2DBehavior,La as RuntimePlayerInput2DBehavior,va as RuntimeRicochet2DBehavior,Za as RuntimeTriggerRegion2DBehavior,Or as SPHERE_TYPE,rt as SPRITE_TYPE,st as STAGE_STATE_CHANGE,pm as ScreenVisibilityBehavior,fm as ScreenVisibilityFSM,xm as ScreenWrapBehavior,im as ScreenWrapEvent,dm as ScreenWrapFSM,cm as ScreenWrapState,sm as Shooter2DBehavior,be as SimulationBody,Ip as SpriteEntityDataSchema,xf as StageAssetLoaderConfigSchema,Bp as StageBodyKind,Dp as StageBoundaryDim,df as StageConfigJsonSchema,Ep as StageEventType,ff as StageGLTFAssetLoaderConfigSchema,Kp as StageJsonSchema,Ye as StageManager,Gp as StageRicochetDim,Mp as StageRicochetReflection,qp as StageSchema,Np as StageTopDownPlane,_e as TEXT_TYPE,C as TRANSFORM_TOOLS,Ap as TextEntityDataSchema,Ve as ThirdPersonPerspective,nm as ThrusterBehavior,lm as ThrusterEvent,Sm as ThrusterFSM,hm as ThrusterState,ym as TopDownMovementBehavior,Lm as TopDownShooterCoordinator,Me as TransformGizmo,Xo as VEC2_ONE,Uo as VEC2_ZERO,_o as VEC3_ONE,Yo as VEC3_ZERO,pf as Vec3ComponentsSchema,Pp as Vector2Schema,Cp as Vector3TupleSchema,Yp as VirtualTouchButtonConfigSchema,$p as VirtualTouchButtonsConfigSchema,rf as VirtualTouchConfigSchema,_p as VirtualTouchJoystickConfigSchema,of as VirtualTouchJoysticksConfigSchema,Xp as VirtualTouchPositionSchema,Up as VirtualTouchStyleSchema,vm as WorldBoundary2DBehavior,Zm as WorldBoundary2DEvent,bm as WorldBoundary2DFSM,gm as WorldBoundary2DState,um as WorldBoundary3DBehavior,Tm as WorldBoundary3DEvent,jm as WorldBoundary3DFSM,Fm as WorldBoundary3DState,ae as ZONE_TYPE,ve as ZylemActor,Mr as ZylemBox,Ar as ZylemCone,Qr as ZylemCylinder,oe as ZylemDisk,ue as ZylemFog,bp as ZylemGameElement,se as ZylemLight,pt as ZylemLine,Lt as ZylemParticleSystem,Xr as ZylemPill,te as ZylemPlane,Ir as ZylemPyramid,ie as ZylemRect,Pr as ZylemSphere,et as ZylemSprite,$e as ZylemText,pe as ZylemZone,u as abs,vp as announceBridgeReady,Qe as applyTransformChanges,g as asin,b as atan,Wa as bindRuntimeDynamicCircleBody2DHandle,vr as boxCollision,kr as boxMesh,up as buildBoxCollider,jp as buildCapsuleCollider,Wp as buildConvexHullCollider,Fp as buildCylinderCollider,wp as buildHeightfieldCollider,gp as buildRuntimeBody,Tp as buildSphereCollider,kp as buildTrimeshCollider,zp as bundleRuntimeCollision,Ha as callFunc,L as clamp,A as clearGlobalSubscriptions,Ee as closestAxisValue,Wm as computeWorldBoundary2DHits,km as computeWorldBoundary3DHits,br as coneCollision,zr as coneMesh,Z as cos,Wr as create,Ze as createActor,s as createBackgroundShader,Nr as createBox,Je as createCamera,Cr as createCone,Zt as createCooldownIcon,Rr as createCylinder,re as createDisk,_r as createEntity,xt as createEntityFactory,wm as createFirstPersonInputComponent,zm as createFirstPersonMovementComponent,Bm as createFirstPersonStateComponent,Te as createFog,St as createFollowTarget,dt as createGame,N as createGlobal,Dm as createJumpConfig2D,Em as createJumpConfig3D,Gm as createJumpInput2D,Mm as createJumpInput3D,Nm as createJumpState2D,Om as createJumpState3D,ne as createLight,ft as createLine,m as createNodeMaterialFromTSL,vt as createParticleSystem,Ce as createPerspective,Pm as createPhysicsBodyComponent,Yr as createPill,me as createPlane,Vm as createPlatformer2DInputComponent,qm as createPlatformer2DMovementComponent,Am as createPlatformer2DStateComponent,Cm as createPlatformer3DInputComponent,Hm as createPlatformer3DMovementComponent,Im as createPlatformer3DStateComponent,Jr as createPyramid,de as createRect,Jm as createShooter2DStateComponent,Op as createSimulation,Vr as createSphere,tt as createSprite,Ue as createStage,ot as createText,Km as createThrusterInputComponent,Qm as createThrusterMovementComponent,Rm as createThrusterStateComponent,Um as createTopDownMovementComponent,Xm as createTopDownMovementInputComponent,Ym as createTopDownMovementStateComponent,_m as createTransformComponent,_a as createTransformStore,ke as createVariable,fe as createZone,le as crossfadeTransitionShader,ur as cylinderCollision,Dr as cylinderMesh,J as debugState,Mo as defaultTouchControls,$m as defineBehavior,Ko as degreesToRadians,Ca as delay,bt as destroy,lt as dispatchStageState,B as dot,ka as emitRuntimeGoal,wa as emitRuntimeRicochet,za as emitRuntimeTriggerRegionEnter,ct as entitySpawner,co as entityThumbnailCache,Ao as eulerToQuaternion,T as exp,Ia as fadeOpacity,oa as fireCooldown,ra as fireShooter2DIfRequested,d as float,w as floor,qo as focusEntity,z as fract,No as gameConfig,ea as getCooldown,ta as getCooldownStore,Fo as getDisplayAspect,ma as getEntityFacingAngle2D,O as getGlobal,q as getGlobals,fo as getHoveredEntity,mo as getHoveredEntityId,fp as getPosition,Wo as getPresetResolution,yr as getRotation,po as getSelectedEntity,X as getSelectedEntityId,_ as getSelectedEntityIds,oo as getSnapSettings,we as getVariable,xp as getVelocity,Lp as getZylemBridge,Ga as globalChange,Ma as globalChanges,aa as hasAnyWorldBoundary2DHit,pa as hasAnyWorldBoundary3DHit,nt as initStageStateDispatcher,Ge as intersectPlane,t as isGLSLShader,ye as isManagedRenderEntity,e as isTSLShader,H as isTransformTool,To as isWebGPUSupported,Do as joystickBaseSvg,Eo as joystickThumbSvg,D as length,W as max,uo as mergeInputConfigs,k as min,h as mix,G as mod,$a as move,Va as moveBy,pp as moveForwardXY,qa as moveTo,op as moveX,tp as moveXY,mp as moveXZ,rp as moveY,ep as moveZ,S as normalize,$o as normalizeVec2,or as normalizeVec3,o as objectVertexShader,P as onGlobalChange,V as onGlobalChanges,Ka as onPress,Qa as onRelease,ze as onVariableChange,Be as onVariableChanges,Lr as packCollisionGroups,Ua as parallel,ko as parseResolution,fa as particleEffect,xa as particlePresets,at as pickZylemLine,Tr as pillCollision,Er as pillMesh,Da as pingPongBeep,jr as planeCollision,l as positionWorld,n as positionWorldDirection,j as pow,gr as pyramidCollision,Br as pyramidMesh,Co as quaternionToEuler,Qo as radiansToDegrees,ia as registerCooldown,K as registerDebugEntityResolver,Vo as registerEntityFocusContext,Xa as repeat,Ya as repeatForever,da as resetCooldown,Pa as resetEntityOpacity,ap as resetVelocity,ca as resolveAim2D,Bo as resolveButtonAccent,Q as resolveDebugEntity,Se as resolveRenderCategory,zo as resolveTouchTheme,Ba as ricochetSound,Aa as rotateBy,ar as rotateEuler,tr as rotateInDirection,fr as rotateX,pr as rotateY,mr as rotateYEuler,xr as rotateZ,yp as screenCenterLookDeltas,hp as screenCenterLookTargets,Ra as sequence,to as setAddType,ht as setCameraFeed,U as setDebugTool,M as setGlobal,eo as setGridVisible,ao as setHoveredEntityId,R as setPaused,ip as setPosition,dp as setPositionX,cp as setPositionY,sp as setPositionZ,Sr as setRotation,hr as setRotationDegrees,sr as setRotationDegreesX,dr as setRotationDegreesY,lr as setRotationDegreesZ,cr as setRotationX,ir as setRotationY,nr as setRotationZ,xo as setSelectedEntity,Y as setSelectedEntityId,$ as setSelectedEntityIds,ro as setSnapSettings,Ne as setStageFrameProfilerEnabled,We as setVariable,Sp as shortestAngleDelta,v as sin,y as smoothstep,Jo as snapScale,Ho as snapToIncrement,Io as snapVec3,Zr as sphereCollision,wr as sphereMesh,Ke as stageConfig,Xe as stageState,r as standardShader,F as step,Ja as throttle,sa as tickCooldowns,f as time,rr as toThreeVector2,er as toThreeVector3,Go as touchButtonSvg,wo as touchThemes,a as uniform,na as updateBoundaryRicochet,so as useArrowsForAxes,lo as useArrowsForDirections,no as useArrowsForSecondaryAxes,la as useBehavior,yo as useIJKLForAxes,Lo as useIJKLForDirections,bo as useMouse,vo as useMouseLook,Zo as useScreenCenterLook,go as useVirtualControls,ho as useWASDForAxes,So as useWASDForDirections,he as usesManagedRenderPath,p as uv,Na as variableChange,Oa as variableChanges,E as vec2,x as vec3,i as vec4,Re as vessel,lp as wrapAround3D,np as wrapAroundXY,Fr as zoneCollision,Po 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-MSCVL5OK.js";import{a as Zp,b as bp,c as gp}from"./chunk-HNCTOJP7.js";import{a as up}from"./chunk-34MYRTRP.js";import{a as Tp,b as jp,c as Fp,d as Wp,e as kp,f as wp,g as zp,h as Bp,i as Dp,j as Ep,k as Gp,l as Mp,m as Np,n as Op,o as Pp,p as Vp}from"./chunk-47DG7I7M.js";import{A as nf,B as lf,C as Sf,a as qp,b as Ap,c as Cp,d as Hp,e as Ip,f as Jp,g as Kp,h as Qp,i as Rp,j as Up,k as Xp,l as Yp,m as _p,n as $p,o as of,p as rf,q as ef,r as tf,s as mf,t as af,u as pf,v as ff,w as xf,x as df,y as cf,z as sf}from"./chunk-JNFFTNMH.js";import{a as Wo,b as ko,c as wo,d as zo,e as Po,f as _e,g as $e,h as ct,i as st,j as nt,k as lt,l as St,m as ht,n as yt,o as Lt}from"./chunk-F5LROYZL.js";import{a as Fo,c as ye,d as Le,e as ve,f as We,g as ke,h as Pe,i as Ve,k as qe,l as Ae,m as Ce,n as He,o as Ie,p as Je,q as Ke,r as Qe,s as Re,t as Xe,v as Ye}from"./chunk-IBJLPJLE.js";import{a as he}from"./chunk-7GYFZKK7.js";import{a as so,b as no}from"./chunk-Q2YDBMVY.js";import{c as Ge,d as Me,e as Ne,f as Oe}from"./chunk-BCFFS3FP.js";import"./chunk-QDQ4QMAI.js";import"./chunk-AE3CTVHY.js";import{f as Xo}from"./chunk-ZTYNZ2N2.js";import{a as Ao,b as Co,c as Ho,d as Io,e as Jo,f as Ko,g as Qo,h as Ro,i as Uo}from"./chunk-CBUQBP2U.js";import{A as co,a as C,b as H,c as I,d as J,e as K,f as Q,h as R,j as U,l as X,m as Y,n as _,o as $,p as oo,q as ro,r as eo,s as to,t as mo,u as ao,v as po,w as fo,y as xo,z as io}from"./chunk-EVMLNMGU.js";import{b as ue}from"./chunk-WBQ5TNRZ.js";import{a as vt,b as Zt,c as bt,d as gt,e as ut}from"./chunk-GHJQ2HKI.js";import{a as ot,b as rt,c as et,d as tt,e as mt,f as at,g as pt,h as ft,i as xt,j as it,l as dt}from"./chunk-YOVE25NW.js";import{a as Ze,b as be,c as ge,d as Te,e as je,f as Fe}from"./chunk-MXO4VGDB.js";import{A as ee,B as te,C as me,D as ae,E as pe,F as fe,G as xe,H as ie,I as de,J as ce,K as se,L as ne,M as le,N as Se,b as zr,c as Br,d as Dr,e as Er,f as Gr,g as Mr,h as Nr,i as Or,j as Pr,k as Vr,l as qr,m as Ar,n as Cr,o as Hr,p as Ir,q as Jr,r as Kr,s as Qr,t as Rr,u as Ur,v as Xr,w as Yr,x as _r,y as $r,z as re}from"./chunk-BMRFDDMR.js";import{c as br,d as gr,e as ur,f as Tr,g as jr,h as Fr,i as Wr,j as kr,u as wr,z as oe}from"./chunk-SAQA4SXW.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-7NYP4YAG.js";import{a as Vo,b as qo}from"./chunk-AIQ6IVT5.js";import"./chunk-QXVH6POE.js";import{b as Zr}from"./chunk-EVYHPR3J.js";import{$ as um,$a as ua,A as Xt,Aa as Xm,B as Yt,Ba as Ym,C as _t,Ca as _m,D as $t,Da as $m,E as om,Ea as oa,F as rm,Fa as ra,G as em,Ga as ea,H as tm,Ha as ta,I as mm,Ia as ma,J as am,Ja as aa,K as pm,Ka as pa,L as fm,La as fa,M as xm,Ma as xa,N as im,Na as ia,O as dm,Oa as da,P as cm,Pa as ca,Q as sm,Qa as sa,R as nm,Ra as na,S as lm,Sa as la,T as Sm,Ta as Sa,U as hm,Ua as ha,V as ym,Va as ya,W as Lm,Wa as La,X as vm,Xa as va,Y as Zm,Ya as Za,Z as bm,Za as ba,_ as gm,_a as ga,a as Tt,aa as Tm,ab as Ta,b as jt,ba as jm,bb as ja,c as Ft,ca as Fm,cb as Fa,d as Wt,da as Wm,db as Wa,e as kt,ea as km,eb as ka,f as wt,fa as wm,fb as wa,g as zt,ga as zm,gb as za,h as Bt,ha as Bm,hb as Ba,i as Dt,ia as Dm,ib as Da,j as Et,ja as Em,k as Gt,ka as Gm,l as Mt,la as Mm,m as Nt,ma as Nm,n as Ot,na as Om,o as Pt,oa as Pm,p as Vt,pa as Vm,q as qt,qa as qm,r as At,ra as Am,s as Ct,sa as Cm,t as Ht,ta as Hm,u as It,ua as Im,v as Jt,va as Jm,w as Kt,wa as Km,x as Qt,xa as Qm,y as Rt,ya as Rm,z as Ut,za as Um}from"./chunk-XK63E4SX.js";import{a as Ea,b as Ga,c as Ma}from"./chunk-ZRT3ZQVH.js";import{a as Na,b as Oa,c as Pa,d as Va}from"./chunk-WQ3WMMZD.js";import{h as we,i as ze,j as Be,k as De,l as Ee}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 Yo,b as _o,c as $o,d as or,g as rr,h as er,i as tr,j as mr}from"./chunk-7WRQ2UAN.js";import{A as sp,B as np,C as lp,D as Sp,E as hp,a as qa,b as Aa,c as Ca,d as Ha,e as Ia,f as Ja,g as Ka,h as Qa,i as Ra,j as Ua,k as Xa,l as Ya,m as _a,n as $a,o as op,p as rp,q as ep,r as tp,s as mp,t as ap,u as pp,v as fp,w as xp,x as ip,y as dp,z as cp}from"./chunk-IPWUDOV5.js";import{a as Ue}from"./chunk-BH53MBAZ.js";import{a as ar,b as pr,c as fr,d as xr,e as ir,f as dr,g as cr,h as sr,i as nr,j as lr,k as Sr,l as hr,m as yr,n as Lr,o as vr}from"./chunk-XRP4JJXL.js";import{a as yp,b as Lp,c as vp}from"./chunk-7QF6YTEZ.js";import"./chunk-ORIDWL3T.js";import{a as Bo,b as Do,c as Eo,d as Go,e as Mo,f as No,g as Oo}from"./chunk-PCFF4LLO.js";import{a as lo,b as So,c as ho,d as yo,e as Lo,f as vo,g as Zo,h as bo,i as go,j as uo,k as To,l as jo}from"./chunk-UG22Z42P.js";export{Ze as ACTOR_TYPE,Wo as AspectRatio,Nr as BOX_TYPE,gp as BRIDGE_READY_EVENT,Tt as BoundaryRicochet3DCoordinator,jt as BoundaryRicochetCoordinator,Cr as CONE_TYPE,Rr as CYLINDER_TYPE,Je as CameraManager,qe as CameraPipeline,Ke as CameraWrapper,ff as ColorJsonSchema,Ge as ConstructionGrid,Ft as CooldownBehavior,I as DEFAULT_SNAP_SETTINGS,re as DISK_TYPE,Wt as Destructible3DBehavior,kt as DestructibleMesh,Qp as EntityJsonSchema,Ap as EntitySchema,so as EntityThumbnailCache,Vo as EventEmitterDelegate,Te as FOG_TYPE,wt as FirstPersonBehavior,zt as FirstPersonEvent,Bt as FirstPersonFSM,He as FirstPersonPerspective,Gt as FirstPersonPresentation,Dt as FirstPersonShooterCoordinator,Et as FirstPersonState,Ce as Fixed2DPerspective,c as Fn,Mt as FractureOptions,ct as Game,Xo as GameBridge,Sf as GameConfigJsonSchema,lf as GameDeviceConfigJsonSchema,pf as GameInputConfigSchema,af as GameInputPlayerConfigSchema,Ma as Howl,Nt as Jumper2DBehavior,Ot as Jumper2DEvent,Pt as Jumper2DFSM,Vt as Jumper2DState,qt as Jumper3DBehavior,At as Jumper3DEvent,Ct as Jumper3DFSM,Ht as Jumper3DState,Up as KeyboardMappingSchema,ne as LIGHT_TYPE,pt as LINE_TYPE,Jp as LineEntityDataSchema,mf as MouseConfigSchema,Xp as MouseMappingSchema,It as MultidirectionalSpaceShooterCoordinator,vt as PARTICLE_SYSTEM_TYPE,Yr as PILL_TYPE,me as PLANE_TYPE,Jr as PYRAMID_TYPE,Jt as ParticleEmitterBehavior,Ve as Perspectives,Kt as Platformer2DBehavior,Qt as Platformer2DEvent,Rt as Platformer2DFSM,Ut as Platformer2DState,Xt as Platformer3DBehavior,Yt as Platformer3DEvent,_t as Platformer3DFSM,$t as Platformer3DState,de as RECT_TYPE,ua as RUNTIME_BOUNDARY_2D_BEHAVIOR_KEY,Ta as RUNTIME_DYNAMIC_CIRCLE_BODY_2D_BEHAVIOR_KEY,ja as RUNTIME_GOAL_ZONE_2D_BEHAVIOR_KEY,Fa as RUNTIME_PLAYER_INPUT_2D_BEHAVIOR_KEY,Wa as RUNTIME_RICOCHET_2D_BEHAVIOR_KEY,ka as RUNTIME_TRIGGER_REGION_2D_BEHAVIOR_KEY,We as RenderBundleManager,ke as RenderStrategyManager,nf as ResolutionInputSchema,om as Ricochet2DBehavior,rm as Ricochet2DEvent,em as Ricochet2DFSM,tm as Ricochet2DState,mm as Ricochet3DBehavior,am as Ricochet3DEvent,pm as Ricochet3DFSM,fm as Ricochet3DState,ya as RuntimeBoundary2DBehavior,La as RuntimeDynamicCircleBody2DBehavior,va as RuntimeGoalZone2DBehavior,Za as RuntimePlayerInput2DBehavior,ba as RuntimeRicochet2DBehavior,ga as RuntimeTriggerRegion2DBehavior,Vr as SPHERE_TYPE,tt as SPRITE_TYPE,lt as STAGE_STATE_CHANGE,xm as ScreenVisibilityBehavior,im as ScreenVisibilityFSM,dm as ScreenWrapBehavior,cm as ScreenWrapEvent,sm as ScreenWrapFSM,nm as ScreenWrapState,lm as Shooter2DBehavior,ue as SimulationBody,Kp as SpriteEntityDataSchema,cf as StageAssetLoaderConfigSchema,Ep as StageBodyKind,Gp as StageBoundaryDim,sf as StageConfigJsonSchema,Mp as StageEventType,df as StageGLTFAssetLoaderConfigSchema,Rp as StageJsonSchema,$e as StageManager,Np as StageRicochetDim,Op as StageRicochetReflection,Cp as StageSchema,Pp as StageTopDownPlane,ot as TEXT_TYPE,C as TRANSFORM_TOOLS,Hp as TextEntityDataSchema,Ae as ThirdPersonPerspective,Sm as ThrusterBehavior,hm as ThrusterEvent,ym as ThrusterFSM,Lm as ThrusterState,vm as TopDownMovementBehavior,Zm as TopDownShooterCoordinator,Oe as TransformGizmo,_o as VEC2_ONE,Yo as VEC2_ZERO,or as VEC3_ONE,$o as VEC3_ZERO,xf as Vec3ComponentsSchema,qp as Vector2Schema,Ip as Vector3TupleSchema,$p as VirtualTouchButtonConfigSchema,rf as VirtualTouchButtonsConfigSchema,tf as VirtualTouchConfigSchema,of as VirtualTouchJoystickConfigSchema,ef as VirtualTouchJoysticksConfigSchema,_p as VirtualTouchPositionSchema,Yp as VirtualTouchStyleSchema,bm as WorldBoundary2DBehavior,gm as WorldBoundary2DEvent,um as WorldBoundary2DFSM,Tm as WorldBoundary2DState,jm as WorldBoundary3DBehavior,Fm as WorldBoundary3DEvent,Wm as WorldBoundary3DFSM,km as WorldBoundary3DState,fe as ZONE_TYPE,be as ZylemActor,Or as ZylemBox,Hr as ZylemCone,Ur as ZylemCylinder,ee as ZylemDisk,je as ZylemFog,up as ZylemGameElement,le as ZylemLight,xt as ZylemLine,Zt as ZylemParticleSystem,_r as ZylemPill,ae as ZylemPlane,Kr as ZylemPyramid,ce as ZylemRect,qr as ZylemSphere,mt as ZylemSprite,rt as ZylemText,xe as ZylemZone,u as abs,bp as announceBridgeReady,Ue as applyTransformChanges,g as asin,b as atan,wa as bindRuntimeDynamicCircleBody2DHandle,br as boxCollision,zr as boxMesh,jp as buildBoxCollider,Wp as buildCapsuleCollider,wp as buildConvexHullCollider,kp as buildCylinderCollider,Bp as buildHeightfieldCollider,Tp as buildRuntimeBody,Fp as buildSphereCollider,zp as buildTrimeshCollider,Dp as bundleRuntimeCollision,Ja as callFunc,L as clamp,A as clearGlobalSubscriptions,Me as closestAxisValue,wm as computeWorldBoundary2DHits,zm as computeWorldBoundary3DHits,ur as coneCollision,Dr as coneMesh,Z as cos,wr as create,ge as createActor,s as createBackgroundShader,Pr as createBox,Qe as createCamera,Ir as createCone,gt as createCooldownIcon,Xr as createCylinder,te as createDisk,oe as createEntity,dt as createEntityFactory,Bm as createFirstPersonInputComponent,Dm as createFirstPersonMovementComponent,Em as createFirstPersonStateComponent,Fe as createFog,yt as createFollowTarget,st as createGame,N as createGlobal,Gm as createJumpConfig2D,Mm as createJumpConfig3D,Nm as createJumpInput2D,Om as createJumpInput3D,Pm as createJumpState2D,Vm as createJumpState3D,Se as createLight,it as createLine,m as createNodeMaterialFromTSL,bt as createParticleSystem,Ie as createPerspective,qm as createPhysicsBodyComponent,$r as createPill,pe as createPlane,Am as createPlatformer2DInputComponent,Cm as createPlatformer2DMovementComponent,Hm as createPlatformer2DStateComponent,Im as createPlatformer3DInputComponent,Jm as createPlatformer3DMovementComponent,Km as createPlatformer3DStateComponent,Qr as createPyramid,se as createRect,Qm as createShooter2DStateComponent,Vp as createSimulation,Ar as createSphere,at as createSprite,Ye as createStage,et as createText,Rm as createThrusterInputComponent,Um as createThrusterMovementComponent,Xm as createThrusterStateComponent,Ym as createTopDownMovementComponent,_m as createTopDownMovementInputComponent,$m as createTopDownMovementStateComponent,oa as createTransformComponent,op as createTransformStore,ze as createVariable,ie as createZone,he as crossfadeTransitionShader,jr as cylinderCollision,Gr as cylinderMesh,J as debugState,Oo as defaultTouchControls,ra as defineBehavior,Ro as degreesToRadians,Ia as delay,ut as destroy,ht as dispatchStageState,B as dot,za as emitRuntimeGoal,Ba as emitRuntimeRicochet,Da as emitRuntimeTriggerRegionEnter,nt as entitySpawner,no as entityThumbnailCache,Ho as eulerToQuaternion,T as exp,Ka as fadeOpacity,ea as fireCooldown,ta as fireShooter2DIfRequested,d as float,w as floor,Co as focusEntity,z as fract,Po as gameConfig,ma as getCooldown,aa as getCooldownStore,ko as getDisplayAspect,pa as getEntityFacingAngle2D,O as getGlobal,q as getGlobals,io as getHoveredEntity,po as getHoveredEntityId,ip as getPosition,wo as getPresetResolution,vr as getRotation,xo as getSelectedEntity,_ as getSelectedEntityId,oo as getSelectedEntityIds,eo as getSnapSettings,Be as getVariable,dp as getVelocity,Zp as getZylemBridge,Na as globalChange,Oa as globalChanges,fa as hasAnyWorldBoundary2DHit,xa as hasAnyWorldBoundary3DHit,St as initStageStateDispatcher,Ne as intersectPlane,t as isGLSLShader,ve as isManagedRenderEntity,Y as isPickMode,e as isTSLShader,H as isTransformTool,Fo as isWebGPUSupported,Go as joystickBaseSvg,Mo as joystickThumbSvg,D as length,W as max,jo as mergeInputConfigs,k as min,h as mix,G as mod,rp as move,Aa as moveBy,xp as moveForwardXY,Ca as moveTo,ep as moveX,ap as moveXY,pp as moveXZ,tp as moveY,mp as moveZ,S as normalize,rr as normalizeVec2,er as normalizeVec3,o as objectVertexShader,P as onGlobalChange,V as onGlobalChanges,Ra as onPress,Ua as onRelease,De as onVariableChange,Ee as onVariableChanges,Zr as packCollisionGroups,Ya as parallel,zo as parseResolution,ia as particleEffect,da as particlePresets,ft as pickZylemLine,Fr as pillCollision,Mr as pillMesh,Ga as pingPongBeep,Wr as planeCollision,l as positionWorld,n as positionWorldDirection,j as pow,Tr as pyramidCollision,Er as pyramidMesh,Io as quaternionToEuler,Uo as radiansToDegrees,ca as registerCooldown,K as registerDebugEntityResolver,Ao as registerEntityFocusContext,_a as repeat,$a as repeatForever,sa as resetCooldown,qa as resetEntityOpacity,fp as resetVelocity,na as resolveAim2D,Eo as resolveButtonAccent,Q as resolveDebugEntity,ye as resolveRenderCategory,Do as resolveTouchTheme,Ea as ricochetSound,Ha as rotateBy,fr as rotateEuler,ar as rotateInDirection,ir as rotateX,xr as rotateY,pr as rotateYEuler,dr as rotateZ,vp as screenCenterLookDeltas,Lp as screenCenterLookTargets,Xa as sequence,ao as setAddType,Lt as setCameraFeed,U as setDebugTool,M as setGlobal,mo as setGridVisible,fo as setHoveredEntityId,R as setPaused,X as setPickMode,cp as setPosition,sp as setPositionX,np as setPositionY,lp as setPositionZ,yr as setRotation,Lr as setRotationDegrees,lr as setRotationDegreesX,sr as setRotationDegreesY,hr as setRotationDegreesZ,nr as setRotationX,cr as setRotationY,Sr as setRotationZ,co as setSelectedEntity,$ as setSelectedEntityId,ro as setSelectedEntityIds,to as setSnapSettings,Pe as setStageFrameProfilerEnabled,we as setVariable,yp as shortestAngleDelta,v as sin,y as smoothstep,Qo as snapScale,Jo as snapToIncrement,Ko as snapVec3,gr as sphereCollision,Br as sphereMesh,Re as stageConfig,_e as stageState,r as standardShader,F as step,Qa as throttle,la as tickCooldowns,f as time,tr as toThreeVector2,mr as toThreeVector3,No as touchButtonSvg,Bo as touchThemes,a as uniform,Sa as updateBoundaryRicochet,lo as useArrowsForAxes,ho as useArrowsForDirections,So as useArrowsForSecondaryAxes,ha as useBehavior,vo as useIJKLForAxes,Zo as useIJKLForDirections,uo as useMouse,bo as useMouseLook,go as useScreenCenterLook,To as useVirtualControls,Lo as useWASDForAxes,yo as useWASDForDirections,Le as usesManagedRenderPath,p as uv,Pa as variableChange,Va as variableChanges,E as vec2,x as vec3,i as vec4,Xe as vessel,hp as wrapAround3D,Sp as wrapAroundXY,kr as zoneCollision,qo as zylemEventBus};
@@ -1,5 +1,5 @@
1
- import { G as Game, D as DeviceProfile } from './game-Cy8f6gJm.js';
2
- import { t as DebugTools } from './debug-state-B5awuDHl.js';
1
+ import { G as Game, D as DeviceProfile } from './game-BPOr7zTB.js';
2
+ import { v as DebugTools } from './debug-state-CpnNRUFh.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-QVIUZEYA.js";import"./chunk-DECK4UEC.js";export{a as ZylemGameElement};
1
+ import{a}from"./chunk-34MYRTRP.js";import"./chunk-EVMLNMGU.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.6",
3
+ "version": "0.8.7",
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",
@@ -105,24 +105,11 @@
105
105
  "files": [
106
106
  "dist"
107
107
  ],
108
- "scripts": {
109
- "build": "tsup && pnpm api:extract && pnpm api:typedoc && pnpm schema:emit",
110
- "dev": "tsup --watch",
111
- "api:extract": "mkdir -p dist/api temp && api-extractor run --local --verbose",
112
- "api:typedoc": "mkdir -p dist/api && typedoc --options typedoc.json",
113
- "schema:emit": "node --experimental-strip-types ./scripts/emit-json-schemas.ts",
114
- "prepublishOnly": "NODE_ENV=production pnpm build",
115
- "lint": "biome check .",
116
- "typecheck": "tsgo --noEmit",
117
- "test": "vitest --reporter=verbose",
118
- "coverage": "vitest run --coverage"
119
- },
120
108
  "dependencies": {
121
109
  "@dgreenheck/three-pinata": "^2.0.1",
122
110
  "@sinclair/typebox": "^0.34.41",
123
111
  "@types/howler": "^2.2.12",
124
112
  "@zylem/behaviors": "^0.5.11",
125
- "@zylem/bridge": "workspace:*",
126
113
  "comlink": "^4.4.2",
127
114
  "howler": "^2.2.4",
128
115
  "idb-keyval": "^6.2.2",
@@ -131,7 +118,8 @@
131
118
  "stats.js": "^0.17.0",
132
119
  "three": "^0.185.0",
133
120
  "typescript-fsm": "^1.6.0",
134
- "valtio": "^2.1.7"
121
+ "valtio": "^2.1.7",
122
+ "@zylem/bridge": "0.1.4"
135
123
  },
136
124
  "peerDependencies": {
137
125
  "howler": "^2.2.4",
@@ -153,5 +141,16 @@
153
141
  "typescript": "6.0.3",
154
142
  "vite-plugin-solid": "^2.11.8",
155
143
  "vitest": "^4.0.9"
144
+ },
145
+ "scripts": {
146
+ "build": "tsup && pnpm api:extract && pnpm api:typedoc && pnpm schema:emit",
147
+ "dev": "tsup --watch",
148
+ "api:extract": "mkdir -p dist/api temp && api-extractor run --local --verbose",
149
+ "api:typedoc": "mkdir -p dist/api && typedoc --options typedoc.json",
150
+ "schema:emit": "node --experimental-strip-types ./scripts/emit-json-schemas.ts",
151
+ "lint": "biome check .",
152
+ "typecheck": "tsgo --noEmit",
153
+ "test": "vitest --reporter=verbose",
154
+ "coverage": "vitest run --coverage"
156
155
  }
157
- }
156
+ }
@@ -1 +0,0 @@
1
- import{proxy as u}from"valtio/vanilla";var a=["translate","rotate","scale"];function f(t){return a.includes(t)}var y={enabled:!0,translate:.25,rotate:Math.PI/12,scale:.1},e=u({enabled:!1,paused:!1,tool:"none",selectedEntityId:null,selectedEntityIds:[],hoveredEntityId:null,snap:{...y},gridVisible:!1,addTypeId:null,addTypeProps:null,flags:new Set}),i=null;function E(t){return i=t,()=>{i===t&&(i=null)}}function d(t){return!t||!i?null:i(t)}function r(t,n){if(t==null)return null;if(typeof t=="string")return t;let l=t.uuid;if(typeof l=="string")return console.warn(`${n}: received a live entity. Pass the UUID instead \u2014 storing entities in debugState makes valtio deep-proxy the scene graph.`),l;throw new TypeError(`${n} expects an entity UUID string or null, received ${typeof t}.`)}function b(){return e.paused}function x(t){e.paused=t}function I(){return e.tool}function S(t){e.tool=t}function v(){return e.enabled||e.tool!=="none"}function T(){return e.selectedEntityId}function c(t){let n=r(t,"setSelectedEntityId");e.selectedEntityId!==n&&(e.selectedEntityId=n,e.selectedEntityIds=n?[n]:[])}function m(){return[...e.selectedEntityIds]}function D(t){let n=t.map((o,s)=>r(o,`setSelectedEntityIds[${s}]`)).filter(o=>o!==null);n.length===e.selectedEntityIds.length&&n.every((o,s)=>e.selectedEntityIds[s]===o)||(e.selectedEntityIds=n,e.selectedEntityId=n[0]??null)}function h(){return{...e.snap}}function R(t){Object.assign(e.snap,t)}function G(t){e.gridVisible=t}function P(t,n){e.addTypeId=t,e.addTypeProps=t?n??null:null}function w(){return e.hoveredEntityId}function p(t){let n=r(t,"setHoveredEntityId");e.hoveredEntityId!==n&&(e.hoveredEntityId=n)}function H(){p(null)}function O(){return d(e.selectedEntityId)}function A(){return d(e.hoveredEntityId)}function k(t){c(r(t,"setSelectedEntity"))}export{a,f as b,y as c,e as d,E as e,d as f,b as g,x as h,I as i,S as j,v as k,T as l,c as m,m as n,D as o,h as p,R as q,G as r,P as s,w as t,p as u,H as v,O as w,A as x,k as y};
@@ -1 +0,0 @@
1
- import{b as S,c as v,d as x}from"./chunk-VJZMSBKP.js";import{d as a,h,j as y,m as b,q as f,r as g,s as m}from"./chunk-DECK4UEC.js";import{subscribe as k}from"valtio/vanilla";import{announceBridgeReady as q,getZylemBridge as l}from"@zylem/bridge";function c(n,e){return[n[0]*e.x,n[1]*e.y,n[2]*e.z]}function E(n,e){let i=new Float32Array(n.length);for(let t=0;t<n.length;t+=3)i[t]=n[t]*e.x,i[t+1]=n[t+1]*e.y,i[t+2]=n[t+2]*e.z;return i}function z(n,e){let{shape:i}=n,t=n.offset?c(n.offset,e):n.offset,o;switch(i.type){case"box":o={type:"box",halfExtents:c(i.halfExtents,e)};break;case"sphere":o={type:"sphere",radius:i.radius*Math.max(e.x,e.y,e.z)};break;case"capsule":case"cylinder":case"cone":o={type:i.type,halfHeight:i.halfHeight*e.y,radius:i.radius*Math.max(e.x,e.z)};break;case"convexHull":o={type:"convexHull",vertices:E(i.vertices,e)};break;case"trimesh":o={type:"trimesh",vertices:E(i.vertices,e),indices:i.indices};break;case"heightfield":o={...i,scale:c(i.scale,e)};break;default:o=i;break}return{...n,shape:o,offset:t}}function V(n){if(!n.colliderBaseline){let e=n.colliderDescs.length?n.colliderDescs:n.colliderDesc?[n.colliderDesc]:[];n.colliderBaseline=e.map(i=>({...i}))}return n.colliderBaseline}function P(n){if(!n.colliderScaleDirty)return!1;n.colliderScaleDirty=!1;let e=V(n);if(!e.length)return!1;let i=n.getScale(),t=e.map(d=>z(d,i));n.colliderDescs=t,n.colliderDesc=t[0];let o=n.physicsWorldRef;if(!o)return!0;let r=n.getPose();return o.destroyEntity(n),r&&n.bodyDesc&&(n.bodyDesc.position=[r.position.x,r.position.y,r.position.z],n.bodyDesc.rotation=[r.rotation.x,r.rotation.y,r.rotation.z,r.rotation.w]),o.addEntity(n),!0}function D(n){return(n?.group??n?.mesh)?.scale}function G(n){let i=(typeof n?.getScale=="function"?n.getScale():void 0)??n?.scale??D(n)??{};return{x:i.x??1,y:i.y??1,z:i.z??1}}function L(n){let e=typeof n?.getPose=="function"?n.getPose():null;if(!e?.rotation)return;let{x:i,y:t,z:o,w:r}=e.rotation;return{x:i,y:t,z:o,w:r}}function u(n){let e=typeof n?.getPose=="function"?n.getPose():null,i=e?.position??{x:0,y:0,z:0},t=e?.rotation??{x:0,y:0,z:0,w:1};return{position:{x:i.x,y:i.y,z:i.z},rotation:x(t),quaternion:{x:t.x,y:t.y,z:t.z,w:t.w},scale:G(n)}}function T(n,e){if(typeof n?.setScale=="function"){n.setScale(e.x,e.y,e.z);return}D(n)?.set?.(e.x,e.y,e.z)}function O(n){!n||typeof n.getScale!="function"||P(n)}function U(n,e){if(!n)return!1;let i=e.quaternion??(e.rotation?v(e.rotation):void 0),t=!1;return(e.position||i)&&typeof n.setPose=="function"&&(t=n.setPose({position:e.position,rotation:i})),e.scale&&(T(n,e.scale),t=!0),t}function K(n){let e=n?.constructor?.type;return e?String(e).replace("Symbol(","").replace(")",""):"Unknown"}function I(n){let e=n;if(!e?.uuid)return;let i=l().channel;if(!i.hasSubscribers("entity:upsert"))return;let t=u(n);i.queue("entity:upsert",[{uuid:e.uuid,name:e.name||"Unnamed",type:K(n),position:t.position,rotation:t.rotation,scale:t.scale,quaternion:t.quaternion}])}function $(n,e){l().channel.send("game:notice",{level:n,message:e})}var w=class{channel;unsubscribes=[];host=null;editorKnown={};applyingSceneOperation=!1;constructor(){this.channel=l().channel}connect(e,i){this.disconnect(),this.host=e,this.unsubscribes.push(this.channel.on("debug:set",({enabled:t})=>{this.editorKnown.debug=t,a.enabled=t}),this.channel.on("tool:set",({tool:t})=>{y(t)}),this.channel.on("playback:set",({paused:t})=>{this.editorKnown.paused=t,h(t)}),this.channel.on("entity:select",({uuid:t})=>{this.editorKnown.selectedUuid=t,b(t)}),this.channel.on("entity:focus",({uuid:t})=>{S(t)}),this.channel.on("entity:transform",({uuid:t,position:o,rotation:r,quaternion:d,scale:p})=>{let s=this.host?.resolveEntity(t);if(!s)return;let C=u(s);if(U(s,{position:o,rotation:r,quaternion:d,scale:p}),p&&O(s),I(s),this.applyingSceneOperation)return;let B=u(s);this.channel.send("scene:operation",{opId:`tx-${t}-${Date.now().toString(36)}`,kind:"transform",label:`Set ${s.name||"entity"} transform`,entries:[{uuid:t,before:C,after:B}]})}),this.channel.on("entity:create",({typeId:t,props:o,pose:r})=>{this.host?.createEntity?.(t,o,r)}),this.channel.on("scene:operation:apply",({op:t,direction:o})=>{this.applyingSceneOperation=!0;try{this.host?.applySceneOperation?.(t,o)}finally{this.applyingSceneOperation=!1}}),this.channel.on("add:type:set",({typeId:t,props:o})=>{m(t,o??null)}),this.channel.on("snap:set",t=>{f(t)}),this.channel.on("grid:set",({visible:t})=>{g(t)}),this.channel.on("stage:variable:set",({key:t,value:o})=>{this.host?.setStageVariable?.(t,o)}),k(a,()=>this.publishDebugStateChanges())),this.publishDebugStateChanges(),q(i)}disconnect(){for(let e of this.unsubscribes)e();this.unsubscribes=[],this.host=null,this.editorKnown={}}publishDebugStateChanges(){let e={};a.paused!==this.editorKnown.paused&&(this.editorKnown.paused=a.paused,e.paused=a.paused),a.enabled!==this.editorKnown.debug&&(this.editorKnown.debug=a.enabled,e.debug=a.enabled),(e.paused!==void 0||e.debug!==void 0)&&this.publishStatus(e),(a.selectedEntityId!==this.editorKnown.selectedUuid||a.hoveredEntityId!==this.editorKnown.hoveredUuid)&&(this.editorKnown.selectedUuid=a.selectedEntityId,this.editorKnown.hoveredUuid=a.hoveredEntityId,this.channel.queue("entity:selection",{selectedUuid:a.selectedEntityId,hoveredUuid:a.hoveredEntityId,selectedUuids:[...a.selectedEntityIds]}))}wantsEntityUpdates(){return this.channel.hasSubscribers("entity:upsert")||this.channel.hasSubscribers("stage:snapshot")}wantsThumbnails(){return this.channel.hasSubscribers("entity:thumbnail")}onEditorAttached(e){return this.channel.onSubscriberAdded(i=>{if(i!=="entity:upsert"&&i!=="entity:thumbnail")return;let t=i==="entity:upsert"?"entity:thumbnail":"entity:upsert";this.channel.subscriberCount(t)>0||e()})}publishConfig(e){this.channel.send("game:config",e)}publishLoading(e){this.channel.send("game:loading",e)}publishStatus(e){this.channel.queue("game:status",e)}publishVariable(e){this.channel.send("game:variable",e)}publishNotice(e,i){this.channel.send("game:notice",{level:e,message:i})}publishStageSnapshot(e){this.channel.send("stage:snapshot",e)}queueEntityUpsert(e){e.length&&this.channel.queue("entity:upsert",e)}queueEntityRemoved(e){e.length&&this.channel.queue("entity:removed",{uuids:e})}queueThumbnails(e){e.length&&this.channel.queue("entity:thumbnail",e)}publishCatalog(e){this.channel.send("catalog:snapshot",{entities:e})}publishSceneOperation(e){this.channel.send("scene:operation",e)}wantsSceneOperations(){return this.channel.hasSubscribers("scene:operation")}};function j(n){l().channel.send("scene:operation",n)}export{P as a,G as b,L as c,K as d,$ as e,w as f,j as g};
@@ -1 +0,0 @@
1
- import{b as yt,c as Zt,f as Gt}from"./chunk-BCFFS3FP.js";import{c as ee}from"./chunk-AE3CTVHY.js";import{a as Ge,e as wt,g as I}from"./chunk-DQQA3VJH.js";import{a as Ct,c as Ve,d as Ze,e as St,f as J,g as Pt}from"./chunk-VJZMSBKP.js";import{b as ze,d as u,e as mt,i as Fe,k as X,m as Ie,p as k,t as ht,u as gt,v as ft}from"./chunk-DECK4UEC.js";import{a as ie,b as Ot}from"./chunk-WBQ5TNRZ.js";import{b as te,d as At}from"./chunk-MXO4VGDB.js";import{a as V,k as xt,l as Tt,m as Dt,n as Mt,o as L,p as _t,q as Z,t as Rt,u as Ue}from"./chunk-SAQA4SXW.js";import{c as Ne,d as kt,g as O,h as Lt}from"./chunk-7NYP4YAG.js";import{a as vt,b as E}from"./chunk-AIQ6IVT5.js";import{a as re,b as Bt,c as ne,d as zt,e as Ft,f as It,g as Vt,m as A}from"./chunk-D2PATZCC.js";import{c as $,d as Be,j as g}from"./chunk-4QLJUQSJ.js";import{c as C,i as Et,j as h}from"./chunk-7WRQ2UAN.js";import{a as Ut}from"./chunk-BH53MBAZ.js";import{l as bt}from"./chunk-UG22Z42P.js";import{Vector2 as Kt,RenderTarget as Zi,HalfFloatType as Gi}from"three";import{WebGPURenderer as Ui,RenderPipeline as Ni}from"three/webgpu";import{pass as Hi,renderOutput as qt,screenCoordinate as Wi,vec2 as He,vec4 as Xt,fract as Qt,sin as Yt,dot as $t,texture as ji,uniform as Ki}from"three/tsl";import{setConsoleFunction as Ii,getConsoleFunction as Vi}from"three";var Nt="THREE.Abstract function.",Ht=!1,Wt=!1;function jt(){if(Ht)return;Ht=!0;let a=Vi();Ii((e,t,...i)=>{if(e==="warn"&&t===Nt){Wt||(Wt=!0,console.warn(`${Nt} (suppressing further per-frame repeats; a WebGPU node is scheduled for updates without an update() implementation)`));return}if(a){a(e,t,...i);return}let r=i[0],n=e==="log"?console.log:e==="error"?console.error:console.warn;r&&r.isStackTrace&&typeof r.getError=="function"?n(r.getError(t)):n(t,...i)})}var Jt={x:0,y:0,width:1,height:1};async function _n(){if(!("gpu"in navigator))return!1;try{return await navigator.gpu.requestAdapter()!==null}catch{return!1}}var ae=class{renderer;postProcessing=null;renderScale=1;screenResolution;_initialized=!1;_sceneRef=null;_lastAnimationTimestamp=null;_postEffects=[];_postSceneRef=null;_postCameraRef=null;_transition=null;constructor(e){this.screenResolution=e||new Kt(window.innerWidth,window.innerHeight)}get initialized(){return this._initialized}get isWebGPU(){return!0}async initRenderer(){this._initialized||(jt(),this.renderer=new Ui({antialias:!0,alpha:!0}),await this.renderer.init(),this.renderer.setSize(this.screenResolution.x,this.screenResolution.y),this.renderer.shadowMap.enabled=!0,this._initialized=!0)}setScene(e){this._sceneRef=e}setupPostProcessing(e,t){this.disposePostProcessing(),this._postSceneRef=e,this._postCameraRef=t;let i=new Ni(this.renderer),r=Hi(e,t);this.renderScale!==1&&r.setResolutionScale(this.renderScale);let n=r;for(let l of this._postEffects)try{n=l(n,{scenePass:r,scene:e,camera:t})}catch(c){console.error("RendererManager: post-processing effect failed, skipping.",c)}i.outputColorTransform=!1;let s=qt(n),o=this._transition;if(o)try{s=Xt(o.resolved.shader({fromNode:o.fromNode,toNode:s,progress:o.progressUniform})),o.composed=!0}catch(l){console.error("RendererManager: stage transition shader failed, skipping.",l)}i.outputNode=s.add(Qi()),this.postProcessing=i}get transitionActive(){return this._transition!==null}beginSnapshotTransition(e,t,i){this.finishTransition();let r=new Kt;this.renderer.getDrawingBufferSize(r);let n=new Zi(Math.max(1,r.x),Math.max(1,r.y),{type:Gi}),s=this.renderer.getRenderTarget();try{this.renderer.setScissorTest(!1),this.renderer.setRenderTarget(n),this.renderer.render(t,i)}catch(o){console.error("RendererManager: failed to capture transition snapshot.",o)}finally{this.renderer.setRenderTarget(s)}this._transition={resolved:e,progressUniform:Ki(0),fromNode:qt(ji(n.texture)),elapsed:0,snapshotTarget:n,composed:!1}}finishTransition(){let e=this._transition;if(e){this._transition=null,e.progressUniform.value=1,this._postSceneRef&&this._postCameraRef&&this.setupPostProcessing(this._postSceneRef,this._postCameraRef);try{e.resolved.onComplete?.()}catch(t){console.error("RendererManager: transition onComplete failed.",t)}this.releaseTransitionResources(e)}}cancelTransition(){let e=this._transition;if(e){this._transition=null;try{e.resolved.onComplete?.()}catch{}this.releaseTransitionResources(e)}}releaseTransitionResources(e){try{e.snapshotTarget?.dispose()}catch{}}advanceTransition(e){let t=this._transition;if(!t||!t.composed)return;t.elapsed+=e;let i=Math.min(t.elapsed/t.resolved.duration,1);t.progressUniform.value=t.resolved.easing(i),i>=1&&this.finishTransition()}setPostProcessingEffects(e){this._postEffects=[...e],this.postProcessing&&this._postSceneRef&&this._postCameraRef&&this.setupPostProcessing(this._postSceneRef,this._postCameraRef)}setRenderScale(e){this.renderScale=Math.max(1,Number.isFinite(e)?e:1)}disposePostProcessing(){try{this.postProcessing?.dispose?.()}catch{}this.postProcessing=null}startRenderLoop(e){this._lastAnimationTimestamp=null,this.renderer.setAnimationLoop(t=>{let i=this._lastAnimationTimestamp===null?0:Math.max(0,(t-this._lastAnimationTimestamp)/1e3);this._lastAnimationTimestamp=t,this.advanceTransition(i),e(i)})}stopRenderLoop(){this._lastAnimationTimestamp=null;try{this.renderer.setAnimationLoop(null)}catch{}}renderCamera(e,t,i=!1){let r=t.viewport,n=this.screenResolution.x,s=this.screenResolution.y,o=Math.floor(r.x*n),l=Math.floor(r.y*s),c=Math.floor(r.width*n),d=Math.floor(r.height*s);this.renderer.setViewport(o,l,c,d),this.renderer.setScissor(o,l,c,d),this.renderer.setScissorTest(!0),i&&this.postProcessing?this.postProcessing.render():this.renderer.render(e,t.camera)}renderCameraToTarget(e,t){if(!t.renderTarget)return;let i=this.renderer.getRenderTarget();this.renderer.setScissorTest(!1),this.renderer.setRenderTarget(t.renderTarget),this.renderer.clear(),this.renderer.render(e,t.camera),this.renderer.setRenderTarget(i)}renderCameras(e,t){if(!e||t.length===0)return;this.renderer.setScissorTest(!1),this.renderer.clear();let i=t.length===1&&qi(t[0].viewport);for(let r of t)this.renderCamera(e,r,i);this.renderer.setScissorTest(!1)}render(e,t){this.postProcessing?this.postProcessing.render():this.renderer.render(e,t)}resize(e,t){this.screenResolution.set(e,t),this.renderer.setSize(e,t,!1)}setPixelRatio(e){let t=Math.max(1,Number.isFinite(e)?e:1);this.renderer.setPixelRatio(t)}getDomElement(){return this.renderer.domElement}dispose(){this.stopRenderLoop(),this.cancelTransition(),this.disposePostProcessing();try{this.renderer.dispose()}catch{}this._sceneRef=null,this._postSceneRef=null,this._postCameraRef=null,this._postEffects=[],this._initialized=!1}};function qi(a){return a.x===0&&a.y===0&&a.width===1&&a.height===1}function Qi(){let a=Wi.xy,e=Qt(Yt($t(a,He(12.9898,78.233))).mul(43758.5453)),t=Qt(Yt($t(a.add(He(13,7)),He(12.9898,78.233))).mul(43758.5453)),i=e.sub(t).mul(1/255);return Xt(i,i,i,0)}function G(a){return a?.category??"none"}function U(a){let e=G(a);return e==="environment"||e==="pack"}function D(a){return a.isInstanced===!0||a.isBundled===!0}import{BundleGroup as Yi}from"three/webgpu";var se=class{bundles=new Map;entityToBundle=new Map;scene=null;setScene(e){this.scene=e}register(e,t,i,r){if(e.isBundled)return!0;let n=e.mesh??e.group;if(!n)return!1;let s=this.getOrCreateBundle(r);return n.matrixAutoUpdate=!0,n.userData.zylemEntityUuid=e.uuid,n.parent&&n.parent.remove(n),s.add(n),s.needsUpdate=!0,e.isBundled=!0,e.bundleKey=r,this.entityToBundle.set(e.uuid,r),!0}unregister(e){let t=this.entityToBundle.get(e.uuid);if(!t)return;let i=this.bundles.get(t),r=e.mesh??e.group;i&&r&&(i.remove(r),i.needsUpdate=!0),e.isBundled=!1,e.bundleKey=null,this.entityToBundle.delete(e.uuid)}getStats(){return{bundleCount:this.bundles.size,entityCount:this.entityToBundle.size}}dispose(){for(let e of this.bundles.values())this.scene&&this.scene.remove(e);this.bundles.clear(),this.entityToBundle.clear()}getOrCreateBundle(e){let t=this.bundles.get(e);return t||(t=new Yi,t.name=`bundle:${e}`,t.static=!0,this.bundles.set(e,t),this.scene&&this.scene.add(t),t)}};import{InstancedMesh as ei,Matrix4 as N,Vector3 as ti,Quaternion as $i}from"three";var H=class a{packs=new Map;entityToPack=new Map;scene=null;static DEFAULT_CAPACITY=128;static GROWTH_FACTOR=2;setScene(e){this.scene=e}static generatePackKey(e){let t={geo:`${e.geometryType}:${Ne(e.dimensions)}`,mat:e.materialPath||"none",shader:e.shaderType||"standard",color:e.colorHex??16777215};return kt(Ne(t))}static generateEntityPackKey(e){let t=e.options;if(t.runtime?.packKeyOverride)return t.runtime.packKeyOverride;let i=e.constructor?.type?.description||"unknown",r=t.size||{x:1,y:1,z:1},n=t.material||{};return a.generatePackKey({geometryType:i,dimensions:{x:r.x,y:r.y,z:r.z},materialPath:n.path||null,shaderType:n.shader?"custom":"standard",colorHex:n.color?.getHex?.()||t.color?.getHex?.()||16777215})}register(e,t,i,r){let n=this.packs.get(r);n||(n=this.createPack(r,t,i));let s;return n.freeIndices.length>0?s=n.freeIndices.pop():(s=n.entities.length,s>=n.capacity&&this.growPack(n),n.entities.push(null)),n.entities[s]=e,n.entityMap.set(e.uuid,s),this.entityToPack.set(e.uuid,r),n.instancedMesh.count=Math.max(n.instancedMesh.count,s+1),n.activeIndices.push(s),n.dirtyIndices.add(s),s}unregister(e){let t=this.entityToPack.get(e.uuid);if(!t)return;let i=this.packs.get(t);if(!i)return;let r=i.entityMap.get(e.uuid);if(r===void 0)return;i.entities[r]=null,i.entityMap.delete(e.uuid),this.entityToPack.delete(e.uuid),i.freeIndices.push(r);let n=i.activeIndices.indexOf(r);if(n!==-1){let o=i.activeIndices.pop();n<i.activeIndices.length&&(i.activeIndices[n]=o)}i.dirtyIndices.delete(r);let s=new N;s.makeScale(0,0,0),i.instancedMesh.setMatrixAt(r,s),i.instancedMesh.instanceMatrix.needsUpdate=!0}markDirty(e){let t=this.entityToPack.get(e.uuid);if(!t)return;let i=this.packs.get(t);if(!i)return;let r=i.entityMap.get(e.uuid);r!==void 0&&i.dirtyIndices.add(r)}update(e=0){let t=new N,i=new ti,r=new $i,n=new ti(1,1,1);for(let s of this.packs.values()){if(s.activeIndices.length===0)continue;let o=!1;for(let l of s.activeIndices){let c=s.entities[l];if(!c)continue;if(xt(c)){t.makeScale(0,0,0),s.instancedMesh.setMatrixAt(l,t),o=!0;continue}let d=s.dirtyIndices.has(l),p=!!c.body;if(!(!d&&!p)){if(!d&&p){let v=c.body;if(typeof v.isRenderSleeping=="function"&&v.isRenderSleeping())continue}this.updateInstanceMatrix(s,l,t,i,r,n,e),o=!0}}s.dirtyIndices.clear(),o&&(s.instancedMesh.instanceMatrix.needsUpdate=!0)}}updateInstanceMatrix(e,t,i,r,n,s,o){let l=e.entities[t];if(l){if(l.body){let c=l.body;if(typeof c.writeRenderPose=="function")c.writeRenderPose(o,r,n);else{let d=ie(l.body,o);r.set(d.position.x,d.position.y,d.position.z),n.set(d.rotation.x,d.rotation.y,d.rotation.z,d.rotation.w)}i.compose(r,n,s)}else l.mesh?(l.mesh.updateMatrix(),i.copy(l.mesh.matrix)):l.group&&(l.group.updateMatrix(),i.copy(l.group.matrix));e.instancedMesh.setMatrixAt(t,i)}}getPackInfo(e){let t=this.entityToPack.get(e.uuid);if(!t)return null;let i=this.packs.get(t);if(!i)return null;let r=i.entityMap.get(e.uuid);return r===void 0?null:{packKey:t,instanceId:r}}getStats(){let e=0,t=[];for(let[i,r]of this.packs){let n=r.entityMap.size;e+=n,t.push({key:i,count:n,capacity:r.capacity})}return{packCount:this.packs.size,totalInstances:e,packs:t}}dispose(){for(let e of this.packs.values())this.scene&&this.scene.remove(e.instancedMesh),e.instancedMesh.dispose(),e.geometry.dispose();this.packs.clear(),this.entityToPack.clear()}createPack(e,t,i){let r=a.DEFAULT_CAPACITY,n=new ei(t,i,r);n.count=0,n.frustumCulled=!1;let s=new N().makeScale(0,0,0);for(let l=0;l<r;l++)n.setMatrixAt(l,s);n.instanceMatrix.needsUpdate=!0;let o={key:e,instancedMesh:n,geometry:t,material:i,entityMap:new Map,entities:[],freeIndices:[],activeIndices:[],dirtyIndices:new Set,capacity:r};return this.packs.set(e,o),this.scene&&this.scene.add(n),o}growPack(e){let t=e.capacity*a.GROWTH_FACTOR,i=new ei(e.geometry,e.material,t);i.count=e.instancedMesh.count,i.frustumCulled=!1;let r=new N;for(let s=0;s<e.capacity;s++)e.instancedMesh.getMatrixAt(s,r),i.setMatrixAt(s,r);let n=new N().makeScale(0,0,0);for(let s=e.capacity;s<t;s++)i.setMatrixAt(s,n);i.instanceMatrix.needsUpdate=!0,this.scene&&(this.scene.remove(e.instancedMesh),this.scene.add(i)),e.instancedMesh.dispose(),e.instancedMesh=i,e.capacity=t}};var oe=class{bundles=new se;instances=new H;setScene(e){this.bundles.setScene(e),this.instances.setScene(e)}register(e){let t=G(e.options);if(t==="none")return!1;if(e.isInstanced||e.isBundled)return!0;if(!e.mesh?.geometry||!e.materials?.length)return!1;let i=e.mesh.geometry,r=e.materials[0],n=H.generateEntityPackKey(e);if(t==="pack"){let s=this.instances.register(e,i,r,n);return s<0?!1:(e.packKey=n,e.instanceId=s,e.isInstanced=!0,e.mesh&&(e.mesh.visible=!1),!0)}return t==="environment"&&this.bundles.register(e,i,r,n)?(e.mesh&&(e.mesh.visible=!0),!0):!1}unregister(e){e.isInstanced&&(this.instances.unregister(e),e.isInstanced=!1,e.instanceId=-1,e.packKey=null),e.isBundled&&this.bundles.unregister(e)}update(e=0){this.instances.update(e)}dispose(){this.bundles.dispose(),this.instances.dispose()}};var le=!1,S={},ii=0,ri=0,W=null;function ni(){return typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()}function We(){return le?!0:(typeof globalThis<"u"&&globalThis.__ZYLEM_PROFILE_STAGE__===!0&&(le=!0),le)}function jn(a){le=a,typeof globalThis<"u"&&(globalThis.__ZYLEM_PROFILE_STAGE__=a)}function je(a){We()&&(W=a,ri=ni())}function Ke(){if(!We()||W===null)return;let a=ni()-ri;S[W]=(S[W]??0)+a,W=null}function ai(){if(!We()||(ii++,ii%60!==0))return;let a=Object.values(S).reduce((t,i)=>t+(i??0),0),e=Object.keys(S).sort((t,i)=>(S[i]??0)-(S[t]??0)).map(t=>{let i=S[t]??0,r=a>0?(i/a*100).toFixed(1):"0.0";return`${t}=${i.toFixed(2)}ms (${r}%)`});console.info(`[ZylemStage profile] avg over 60 frames (${a.toFixed(2)}ms/frame): ${e.join(", ")}`);for(let t of Object.keys(S))S[t]=0}function P(a,e){je(a);try{return e()}finally{Ke()}}var m={FirstPerson:"first-person",ThirdPerson:"third-person",Isometric:"isometric",Flat2D:"flat-2d",Fixed2D:"fixed-2d",TopDown:"top-down"};import{Vector3 as Xi,Quaternion as Ji,MathUtils as qe}from"three";function ce(){return{position:new Xi(0,0,10),rotation:new Ji,fov:75,zoom:1,near:.1,far:1e3}}function M(a){return{position:a.position.clone(),rotation:a.rotation.clone(),fov:a.fov,zoom:a.zoom,near:a.near,far:a.far,lookAt:a.lookAt?.clone()}}function si(a,e){let t=M(a);return e.position&&t.position.add(e.position),e.rotation&&t.rotation.multiply(e.rotation),e.fov!=null&&t.fov!=null&&(t.fov+=e.fov),e.zoom!=null&&t.zoom!=null&&(t.zoom+=e.zoom),t}function oi(a,e,t,i){let r=1-Math.pow(1-qe.clamp(t,0,1),i*60),n=M(a);return n.position.lerp(e.position,r),n.rotation.slerp(e.rotation,r),e.fov!=null&&n.fov!=null&&(n.fov=qe.lerp(n.fov,e.fov,r)),e.zoom!=null&&n.zoom!=null&&(n.zoom=qe.lerp(n.zoom,e.zoom,r)),e.near!=null&&(n.near=e.near),e.far!=null&&(n.far=e.far),e.lookAt?n.lookAt?n.lookAt.lerp(e.lookAt,r):n.lookAt=e.lookAt.clone():n.lookAt=void 0,n}var de=class{perspective=null;behaviors=new Map;actions=[];_desiredPose=ce();_finalPose=ce();_initialized=!1;damping=.15;constructor(e){e&&(this.perspective=e,e.defaults?.damping!=null&&(this.damping=e.defaults.damping))}run(e){let t=this.perspective?this.perspective.getBasePose(e):ce(),i=this.getSortedBehaviors();for(let r of i)r.enabled!==!1&&(t=r.update(e,t));this._desiredPose=M(t);for(let r=this.actions.length-1;r>=0;r--){let n=this.actions[r],s=n.update(e);t=si(t,s),n.isDone(e)&&this.actions.splice(r,1)}return this._initialized?this._finalPose=oi(this._finalPose,t,this.damping,e.dt):(this._finalPose=M(t),this._initialized=!0),this._finalPose}addBehavior(e,t,i){let r=this.behaviors.get(e);r?.onDetach&&i&&r.onDetach(i),this.behaviors.set(e,t),t.onAttach&&i&&t.onAttach(i)}removeBehavior(e,t){let i=this.behaviors.get(e);return i?(i.onDetach&&t&&i.onDetach(t),this.behaviors.delete(e)):!1}hasBehavior(e){return this.behaviors.has(e)}addAction(e){this.actions.push(e)}getState(){return{perspectiveId:this.perspective?.id??null,desiredPose:this._desiredPose?M(this._desiredPose):null,finalPose:this._finalPose?M(this._finalPose):null,activeBehaviors:Array.from(this.behaviors.keys()),activeActionCount:this.actions.length}}setPerspective(e){this.perspective=e,this._initialized=!1,e.defaults?.damping!=null&&(this.damping=e.defaults.damping)}getSortedBehaviors(){return Array.from(this.behaviors.values()).sort((e,t)=>(e.priority??0)-(t.priority??0))}};import{Vector3 as x,Quaternion as ue}from"three";var er={distance:8,height:5,shoulderOffset:0,targetKey:"primary",fov:75,paddingFactor:1.5,minDistance:5,trailDelay:.1,trailBufferSize:120},_=class{id="third-person";defaults={damping:.12};opts;initialPosition;initialLookAt;_trailBuffers=new Map;constructor(e){let{initialPosition:t,initialLookAt:i,...r}=e??{};this.opts={...er,...r},this.initialPosition=t?h(t,C):void 0,this.initialLookAt=i?h(i,C):void 0}getBasePose(e){let t=Object.keys(e.targets),i=e.targets[this.opts.targetKey];return t.length===0||!i?this.staticPose():t.length===1?this.singleTargetPose(i.position,e,this.opts.targetKey):this.multiTargetPose(e)}staticPose(){return this.initialPosition?{position:this.initialPosition.clone(),rotation:new ue,fov:this.opts.fov,zoom:1,near:.1,far:1e3,lookAt:this.initialLookAt?.clone()??new x(0,0,0)}:{position:new x(this.opts.shoulderOffset,this.opts.height,this.opts.distance),rotation:new ue,fov:this.opts.fov,zoom:1,near:.1,far:1e3,lookAt:new x(0,0,0)}}singleTargetPose(e,t,i){let r=this.getTrailedPosition(i,e,t.time);return{position:new x(r.x+this.opts.shoulderOffset,r.y+this.opts.height,r.z+this.opts.distance),rotation:new ue,fov:this.opts.fov,zoom:1,near:.1,far:1e3,lookAt:r.clone()}}multiTargetPose(e){let i=Object.entries(e.targets).map(([p,v])=>this.getTrailedPosition(p,v.position,e.time)),r=new x;for(let p of i)r.add(p);r.divideScalar(i.length);let n=0;for(let p of i){let v=r.distanceTo(p);v>n&&(n=v)}let s=Math.max(n*this.opts.paddingFactor,this.opts.minDistance),o=new x(this.opts.shoulderOffset,this.opts.height,this.opts.distance),l=o.length(),c=l>0?o.clone().normalize():new x(0,.5,1).normalize(),d=r.clone().add(c.multiplyScalar(s));if(l>0){let p=this.opts.height/l;d.y=r.y+s*p}return{position:d,rotation:new ue,fov:this.opts.fov,zoom:1,near:.1,far:1e3,lookAt:r.clone()}}getTrailedPosition(e,t,i){let r=this.opts.trailDelay;if(r<=0)return t;let n=this._trailBuffers.get(e);n||(n=[],this._trailBuffers.set(e,n)),n.push({time:i,pos:t.clone()});let s=i-r-.05;for(;n.length>1&&n[0].time<s;)n.shift();n.length>this.opts.trailBufferSize&&n.splice(0,n.length-this.opts.trailBufferSize);let o=i-r;if(n[0].time>=o)return n[0].pos.clone();for(let l=1;l<n.length;l++){let c=n[l-1],d=n[l];if(c.time<=o&&o<=d.time){let p=d.time-c.time,v=p>1e-6?(o-c.time)/p:0;return new x().lerpVectors(c.pos,d.pos,v)}}return n[n.length-1].pos.clone()}};import{Vector3 as li,Quaternion as tr}from"three";var ci={position:{x:0,y:0,z:10},zoom:10},B=class{id="fixed-2d";defaults={damping:1};opts;constructor(e){this.opts={...ci,...e,position:h(e?.position,ci.position)}}getBasePose(e){return{position:new li(this.opts.position.x,this.opts.position.y,this.opts.position.z),rotation:new tr,zoom:this.opts.zoom,near:1,far:1e3,lookAt:new li(this.opts.position.x,this.opts.position.y,0)}}};import{Vector3 as Qe,Quaternion as Ye,Euler as pi,MathUtils as f}from"three";var ir={eyeHeight:1.7,defaultFov:75,pitchLimit:Math.PI/2-.01,lookAtLerpSpeed:5,fovLerpSpeed:8,targetKey:"primary",verticalSmoothing:1},j=class{id="first-person";defaults={damping:1};opts;initialPosition;initialLookAt;_yaw=0;_pitch=0;_currentFov;_targetFov;_lookAtTarget=null;_lookAtLerpSpeed;_currentRotation=new Ye;_rotationInitialized=!1;_smoothedY=null;constructor(e){let{initialPosition:t,initialLookAt:i,...r}=e??{};this.opts={...ir,...r},this.initialPosition=t?h(t,C):void 0,this.initialLookAt=i?h(i,C):void 0,this._currentFov=this.opts.defaultFov,this._targetFov=this.opts.defaultFov,this._lookAtLerpSpeed=this.opts.lookAtLerpSpeed,this.initialPosition&&this.initialLookAt&&this.deriveYawPitchFromLookAt(this.initialPosition,this.initialLookAt)}look(e,t){this._yaw+=e,this._pitch=f.clamp(this._pitch+t,-this.opts.pitchLimit,this.opts.pitchLimit)}setLook(e,t){this._yaw=e,this._pitch=f.clamp(t,-this.opts.pitchLimit,this.opts.pitchLimit)}setEyeHeight(e){this.opts.eyeHeight=e}get yaw(){return this._yaw}get pitch(){return this._pitch}zoom(e){this._targetFov=e}resetZoom(){this._targetFov=this.opts.defaultFov}get currentFov(){return this._currentFov}lookAt(e,t){this._lookAtTarget=e,t!=null&&(this._lookAtLerpSpeed=t)}clearLookAt(){this._lookAtTarget&&this.deriveYawPitchFromQuaternion(this._currentRotation),this._lookAtTarget=null}getBasePose(e){let t=this.computePosition(e),i=this.computeRotation(t,e.dt);return this._currentFov=this.lerpFov(e.dt),{position:t,rotation:i,fov:this._currentFov,near:.1,far:1e3}}computePosition(e){let t=e.targets[this.opts.targetKey];if(t){let i=t.position.y+this.opts.eyeHeight,r=this.smoothVertical(i,e.dt);return new Qe(t.position.x,r,t.position.z)}return this.initialPosition?this.initialPosition.clone():new Qe(0,this.opts.eyeHeight,0)}smoothVertical(e,t){if(this.opts.verticalSmoothing>=1)return this._smoothedY=e,e;if(this._smoothedY==null)return this._smoothedY=e,e;let i=f.clamp(this.opts.verticalSmoothing,0,1),r=1-Math.pow(1-i,t*60);return this._smoothedY=f.lerp(this._smoothedY,e,r),this._smoothedY}computeRotation(e,t){let i=new Ye().setFromEuler(new pi(this._pitch,this._yaw,0,"YXZ"));if(this._rotationInitialized||(this._currentRotation.copy(i),this._rotationInitialized=!0),this._lookAtTarget){let r=di.copy(this._lookAtTarget).sub(e);if(r.lengthSq()>1e-4){r.normalize();let n=Math.atan2(-r.x,-r.z),s=Math.asin(f.clamp(r.y,-1,1)),o=rr.setFromEuler(ui.set(s,n,0,"YXZ")),l=1-Math.pow(1-Math.min(this._lookAtLerpSpeed*t,1),1);return this._currentRotation.slerp(o,f.clamp(l,0,1)),this._currentRotation.clone()}}return this._currentRotation.copy(i),i}lerpFov(e){if(Math.abs(this._currentFov-this._targetFov)<.01)return this._targetFov;let t=1-Math.pow(1-Math.min(this.opts.fovLerpSpeed*e,1),1);return f.lerp(this._currentFov,this._targetFov,f.clamp(t,0,1))}deriveYawPitchFromLookAt(e,t){let i=di.copy(t).sub(e).normalize();this._yaw=Math.atan2(-i.x,-i.z),this._pitch=Math.asin(f.clamp(i.y,-1,1))}deriveYawPitchFromQuaternion(e){let t=ui.setFromQuaternion(e,"YXZ");this._yaw=t.y,this._pitch=f.clamp(t.x,-this.opts.pitchLimit,this.opts.pitchLimit)}},di=new Qe,rr=new Ye,ui=new pi;function z(a,e){switch(a){case"third-person":return new _(e);case"first-person":return new j(e);case"isometric":return new _({distance:10,height:10,...e});case"flat-2d":return new B(e);case"fixed-2d":return new B(e);default:return new _(e)}}import{Vector2 as or,Object3D as lr,Vector3 as he}from"three";import{PerspectiveCamera as K,Vector3 as ar,OrthographicCamera as me,RenderTarget as sr,LinearFilter as mi}from"three";import{Vector3 as $e}from"three";import{OrbitControls as nr}from"three/addons/controls/OrbitControls.js";var pe=class{camera;domElement;cameraRig=null;sceneRef=null;orbitControls=null;orbitTarget=null;orbitTargetWorldPos=new $e;debugDelegate=null;debugUnsubscribe=null;debugStateSnapshot={enabled:!1,selected:[]};savedCameraPosition=null;savedCameraQuaternion=null;savedCameraZoom=null;savedCameraLocalPosition=null;savedDebugCameraPosition=null;savedDebugCameraQuaternion=null;savedDebugCameraZoom=null;savedDebugOrbitTarget=null;_userOrbitEnabled=!1;_isDebugViewCamera=!1;_defaultOrbitTarget=null;_debugPoseSeeded=!1;_interactionEnabled=!0;_followSelection=!0;constructor(e,t,i){this.camera=e,this.domElement=t,this.cameraRig=i??null}setScene(e){this.sceneRef=e}setDebugViewCamera(e){this._isDebugViewCamera=e}setDefaultOrbitTarget(e){this._defaultOrbitTarget=e,e&&!this.orbitTarget&&this.debugStateSnapshot.enabled&&this._followSelection&&(this.orbitTarget=e)}seedOrbitPose(e,t){this.camera.position.copy(e),this.camera.lookAt(t),this.orbitControls&&(this.orbitControls.target.copy(t),this.orbitControls.update()),this._debugPoseSeeded=!0}get isDebugViewCamera(){return this._isDebugViewCamera}get isDebugOrbitPoseSeeded(){return this._debugPoseSeeded}get isActive(){return this.debugStateSnapshot.enabled}get isOrbitActive(){return this.debugStateSnapshot.enabled||this._userOrbitEnabled}update(){this._followSelection&&this.orbitControls&&this.orbitTarget&&(this.orbitTarget.getWorldPosition(this.orbitTargetWorldPos),this.orbitControls.target.copy(this.orbitTargetWorldPos)),this.orbitControls?.update()}enableUserOrbitControls(){this._userOrbitEnabled=!0,this.orbitControls||this.enableOrbitControls()}disableUserOrbitControls(){this._userOrbitEnabled=!1,this.debugStateSnapshot.enabled||this.disableOrbitControls()}setDebugDelegate(e){if(this.debugDelegate===e)return;if(this.detachDebugDelegate(),this.debugDelegate=e,!e){this.applyDebugState({enabled:!1,selected:[]});return}let t=e.subscribe(i=>{this.applyDebugState(i)});this.debugUnsubscribe=()=>{t?.()}}dispose(){this.disableOrbitControls(),this.detachDebugDelegate()}get debugState(){return this.debugStateSnapshot}frameTarget(e){!this.orbitControls&&(this.debugStateSnapshot.enabled||this._userOrbitEnabled)&&this.enableOrbitControls(),this.orbitControls||this.enableOrbitControls(),this.orbitTarget=e;let t=new $e().subVectors(this.camera.position,this.orbitControls.target).normalize();t.lengthSq()<1e-8&&t.set(1,1,1).normalize();let i=yt(e,this.camera,t);this.orbitControls.target.copy(i.center),this.orbitControls.update()}applyDebugState(e){let t=this.debugStateSnapshot.enabled;if(this.debugStateSnapshot={enabled:e.enabled,selected:[...e.selected]},this._isDebugViewCamera){e.enabled&&!t?(this.enableOrbitControls(),this._debugPoseSeeded&&this.restoreDebugCameraState(),this.updateOrbitTargetFromSelection(e.selected)):!e.enabled&&t?(this.saveDebugCameraState(),this._userOrbitEnabled||this.disableOrbitControls()):e.enabled&&this.updateOrbitTargetFromSelection(e.selected);return}e.enabled&&!t?(this.saveCameraState(),this.detachCameraFromRig(),this.enableOrbitControls(),this.restoreDebugCameraState(),this.updateOrbitTargetFromSelection(e.selected)):!e.enabled&&t?(this.saveDebugCameraState(),this.orbitTarget=null,this._userOrbitEnabled||this.disableOrbitControls(),this.reattachCameraToRig(),this.restoreCameraState()):e.enabled&&this.updateOrbitTargetFromSelection(e.selected)}enableOrbitControls(){this.orbitControls||(this.orbitControls=new nr(this.camera,this.domElement),this.orbitControls.enableDamping=!0,this.orbitControls.dampingFactor=.05,this.orbitControls.screenSpacePanning=!1,this.orbitControls.minDistance=1,this.orbitControls.maxDistance=500,this.orbitControls.maxPolarAngle=Math.PI/2,this.orbitControls.enabled=this._interactionEnabled,this.orbitControls.target.set(0,0,0))}setInteractionEnabled(e){this._interactionEnabled=e,this.orbitControls&&(this.orbitControls.enabled=e)}setFollowSelectionEnabled(e){if(this._followSelection!==e){if(this._followSelection=e,!e){this.orbitTarget=null;return}this.updateOrbitTargetFromSelection(this.debugStateSnapshot.selected)}}get isFollowingSelection(){return this._followSelection}disableOrbitControls(){this.orbitControls&&(this.orbitControls.dispose(),this.orbitControls=null)}updateOrbitTargetFromSelection(e){if(this._followSelection){if(!this.debugDelegate||e.length===0){this.orbitTarget=this._defaultOrbitTarget,this.orbitControls&&(this.orbitTarget?(this.orbitTarget.getWorldPosition(this.orbitTargetWorldPos),this.orbitControls.target.copy(this.orbitTargetWorldPos)):this.orbitControls.target.set(0,0,0));return}for(let t=e.length-1;t>=0;t-=1){let i=e[t],r=this.debugDelegate.resolveTarget(i);if(r){this.orbitTarget=r,this.orbitControls&&(r.getWorldPosition(this.orbitTargetWorldPos),this.orbitControls.target.copy(this.orbitTargetWorldPos));return}}this.orbitTarget=this._defaultOrbitTarget,this.orbitControls&&(this.orbitTarget?(this.orbitTarget.getWorldPosition(this.orbitTargetWorldPos),this.orbitControls.target.copy(this.orbitTargetWorldPos)):this.orbitControls.target.set(0,0,0))}}detachDebugDelegate(){if(this.debugUnsubscribe)try{this.debugUnsubscribe()}catch{}this.debugUnsubscribe=null,this.debugDelegate=null}saveCameraState(){this.savedCameraPosition=this.camera.position.clone(),this.savedCameraQuaternion=this.camera.quaternion.clone(),"zoom"in this.camera&&(this.savedCameraZoom=this.camera.zoom)}restoreCameraState(){this.savedCameraPosition&&(this.camera.position.copy(this.savedCameraPosition),this.savedCameraPosition=null),this.savedCameraQuaternion&&(this.camera.quaternion.copy(this.savedCameraQuaternion),this.savedCameraQuaternion=null),this.savedCameraZoom!==null&&"zoom"in this.camera&&(this.camera.zoom=this.savedCameraZoom,this.camera.updateProjectionMatrix?.(),this.savedCameraZoom=null)}saveDebugCameraState(){this.savedDebugCameraPosition=this.camera.position.clone(),this.savedDebugCameraQuaternion=this.camera.quaternion.clone(),"zoom"in this.camera&&(this.savedDebugCameraZoom=this.camera.zoom),this.orbitControls&&(this.savedDebugOrbitTarget=this.orbitControls.target.clone())}restoreDebugCameraState(){this.savedDebugCameraPosition&&this.camera.position.copy(this.savedDebugCameraPosition),this.savedDebugCameraQuaternion&&this.camera.quaternion.copy(this.savedDebugCameraQuaternion),this.savedDebugCameraZoom!==null&&"zoom"in this.camera&&(this.camera.zoom=this.savedDebugCameraZoom,this.camera.updateProjectionMatrix?.()),this.savedDebugOrbitTarget&&this.orbitControls&&this.orbitControls.target.copy(this.savedDebugOrbitTarget)}detachCameraFromRig(){if(!this.cameraRig||this.camera.parent!==this.cameraRig)return;this.savedCameraLocalPosition=this.camera.position.clone();let e=new $e;this.camera.getWorldPosition(e),this.cameraRig.remove(this.camera),this.sceneRef&&this.sceneRef.add(this.camera),this.camera.position.copy(e)}reattachCameraToRig(){!this.cameraRig||this.camera.parent===this.cameraRig||(this.sceneRef&&this.camera.parent===this.sceneRef&&this.sceneRef.remove(this.camera),this.cameraRig.add(this.camera),this.savedCameraLocalPosition&&(this.camera.position.copy(this.savedCameraLocalPosition),this.savedCameraLocalPosition=null))}};var w=class{cameraRig=null;camera;screenResolution;_perspective;frustumSize=10;sceneRef=null;name="";viewport={...Jt};targets=[];pipeline;renderTarget=null;get target(){return this.targets.length>0?this.targets[0]:null}set target(e){e?this.targets.length===0?this.targets.push(e):this.targets[0]=e:this.targets=[]}orbitController=null;_useOrbitalControls=!1;_skipDebugOrbit=!1;isDebugViewCamera=!1;_rendererManager=null;_elapsedTime=0;constructor(e,t,i=10){this._perspective=e,this.screenResolution=t,this.frustumSize=i;let r=t.x/t.y;this.camera=this.createCameraForPerspective(r),this.camera.position.set(0,0,10),this.camera.lookAt(new ar(0,0,0));let n=z(e);this.pipeline=new de(n)}async setup(e,t){this.sceneRef=e,t&&(this._rendererManager=t),this._rendererManager&&!this._rendererManager.initialized&&await this._rendererManager.initRenderer(),this._rendererManager&&(this.orbitController=new pe(this.camera,this._rendererManager.renderer.domElement,null),this.orbitController.setScene(e),this.isDebugViewCamera&&this.orbitController.setDebugViewCamera(!0),this._useOrbitalControls&&this.orbitController.enableUserOrbitControls())}async setupLegacy(e){this._rendererManager||(this._rendererManager=new ae(this.screenResolution),await this._rendererManager.initRenderer(),this._rendererManager.setupPostProcessing(e,this.camera),this._rendererManager.startRenderLoop(()=>{this._rendererManager&&this.sceneRef&&(this.isOrbitActive&&this.updateOrbitControls(),this._rendererManager.render(this.sceneRef,this.camera))})),await this.setup(e,this._rendererManager)}update(e){if(this.isDebugModeActive()||this._useOrbitalControls)return;this._elapsedTime+=e;let t=this.buildContext(e),i=this.pipeline.run(t);this.commitPose(i)}isDebugModeActive(){return this.orbitController?.isActive??!1}get isOrbitActive(){return this.orbitController?.isOrbitActive??!1}updateOrbitControls(){this.orbitController?.update()}enableOrbitalControls(){this._useOrbitalControls=!0,this.orbitController?.enableUserOrbitControls()}disableOrbitalControls(){this._useOrbitalControls=!1,this.orbitController?.disableUserOrbitControls()}get useOrbitalControls(){return this._useOrbitalControls}addTarget(e){this.targets.includes(e)||this.targets.push(e)}removeTarget(e){let t=this.targets.indexOf(e);t!==-1&&this.targets.splice(t,1)}clearTargets(){this.targets=[]}setViewport(e,t,i,r){this.viewport={x:e,y:t,width:i,height:r}}resize(e,t){if(this.screenResolution.set(e,t),this.camera instanceof K&&(this.camera.aspect=e/t,this.camera.updateProjectionMatrix()),this.camera instanceof me){let i=e/t;this.camera.left=this.frustumSize*i/-2,this.camera.right=this.frustumSize*i/2,this.camera.top=this.frustumSize/2,this.camera.bottom=this.frustumSize/-2,this.camera.updateProjectionMatrix()}}createRenderTarget(e=512,t=512){return this.renderTarget&&this.renderTarget.dispose(),this.renderTarget=new sr(e,t,{minFilter:mi,magFilter:mi}),this.renderTarget}getRenderTexture(){return this.renderTarget?.texture??null}destroy(){try{this.orbitController?.dispose()}catch{}try{this.renderTarget?.dispose()}catch{}this.renderTarget=null,this.sceneRef=null,this.targets=[],this._rendererManager=null}setDefaultOrbitTarget(e){this.orbitController?.setDefaultOrbitTarget(e)}seedDebugOrbitPose(e,t){this.isDebugViewCamera&&this.isDebugOrbitPoseSeeded()||this.orbitController?.seedOrbitPose(e,t)}isDebugOrbitPoseSeeded(){return this.orbitController?.isDebugOrbitPoseSeeded??!1}setDebugDelegate(e){this._skipDebugOrbit||this.orbitController?.setDebugDelegate(e)}frameObject(e){this.orbitController?.frameTarget(e)}setOrbitInteractionEnabled(e){this.orbitController?.setInteractionEnabled(e)}setOrbitFollowEnabled(e){this.orbitController?.setFollowSelectionEnabled(e)}move(e){(this._perspective===m.Flat2D||this._perspective===m.Fixed2D)&&(this.frustumSize=e.z),this.camera.position.set(e.x,e.y,e.z)}rotate(e,t,i){this.camera.rotateX(e),this.camera.rotateY(t),this.camera.rotateZ(i)}getDomElement(){if(this._rendererManager)return this._rendererManager.getDomElement();throw new Error("ZylemCamera: No renderer manager available. Call setup() first.")}getRendererManager(){return this._rendererManager}setRendererManager(e){this._rendererManager=e}get renderer(){return this._rendererManager?.renderer}get composer(){return this._rendererManager?.postProcessing}setPixelRatio(e){this._rendererManager?.setPixelRatio(e)}buildContext(e){let t={};for(let i=0;i<this.targets.length;i++){let r=this.targets[i],n=i===0?"primary":`target_${i}`;r.group&&(t[n]={position:r.group.position,rotation:r.group.quaternion})}return{dt:e,time:this._elapsedTime,viewport:{width:this.screenResolution.x,height:this.screenResolution.y,aspect:this.screenResolution.x/this.screenResolution.y},targets:t}}commitPose(e){if(this.camera.position.copy(e.position),e.lookAt?this.camera.lookAt(e.lookAt):this.camera.quaternion.copy(e.rotation),this.camera instanceof K&&(e.fov!=null&&(this.camera.fov=e.fov),e.near!=null&&(this.camera.near=e.near),e.far!=null&&(this.camera.far=e.far),this.camera.updateProjectionMatrix()),this.camera instanceof me){if(e.zoom!=null){let t=this.screenResolution.x/this.screenResolution.y,i=e.zoom;this.camera.left=-i*t/2,this.camera.right=i*t/2,this.camera.top=i/2,this.camera.bottom=-i/2}e.near!=null&&(this.camera.near=e.near),e.far!=null&&(this.camera.far=e.far),this.camera.updateProjectionMatrix()}}createCameraForPerspective(e){switch(this._perspective){case m.ThirdPerson:return new K(75,e,.1,1e3);case m.FirstPerson:return new K(75,e,.1,1e3);case m.Isometric:return new me(this.frustumSize*e/-2,this.frustumSize*e/2,this.frustumSize/2,this.frustumSize/-2,1,1e3);case m.Flat2D:case m.Fixed2D:return new me(this.frustumSize*e/-2,this.frustumSize*e/2,this.frustumSize/2,this.frustumSize/-2,1,1e3);default:return new K(75,e,.1,1e3)}}};var ge=class{cameras=new Map;_activeCameras=[];_debugCamera=null;_preDebugPrimary=null;_debugOrbitTargetAnchor=null;_rendererManager=null;_sceneRef=null;_autoNameCounter=0;constructor(){}get activeCameras(){return this._activeCameras}get primaryCamera(){return this._activeCameras.length>0?this._activeCameras[0]:null}get debugCamera(){return this._debugCamera}get preDebugPrimary(){return this._preDebugPrimary}get allCameras(){return Array.from(this.cameras.values())}addCamera(e,t){let i=t||e.name||`camera_${this._autoNameCounter++}`;return e.name=i,this.cameras.set(i,e),this._activeCameras.length===0&&this._activeCameras.push(e),i}removeCamera(e){let t;if(typeof e=="string")t=e;else for(let[n,s]of this.cameras.entries())if(s===e){t=n;break}if(!t)return!1;let i=this.cameras.get(t);if(!i)return!1;if(i===this._debugCamera)return console.warn("CameraManager: Cannot remove the debug camera"),!1;this.cameras.delete(t);let r=this._activeCameras.indexOf(i);return r!==-1&&this._activeCameras.splice(r,1),!0}setActiveCamera(e){let t=this.resolveCamera(e);if(!t)return console.warn(`CameraManager: Camera not found: ${e}`),!1;let i=this._activeCameras.filter(r=>r!==this._activeCameras[0]&&r.viewport.width<1);return this._activeCameras=[t,...i],!0}addActiveCamera(e){let t=this.resolveCamera(e);return t?(this._activeCameras.includes(t)||this._activeCameras.push(t),!0):!1}deactivateCamera(e){let t=this.resolveCamera(e);if(!t)return!1;let i=this._activeCameras.indexOf(t);return i!==-1?(this._activeCameras.splice(i,1),!0):!1}getCamera(e){return this.cameras.get(e)??null}async setup(e,t){this._sceneRef=e,this._rendererManager=t,this.createDebugCamera(t.screenResolution),this._debugOrbitTargetAnchor=new lr,this._debugOrbitTargetAnchor.name="__debug_orbit_target__",e.add(this._debugOrbitTargetAnchor);for(let i of this.cameras.values())i.setRendererManager(t),await i.setup(e,t);this._debugCamera&&this._debugOrbitTargetAnchor&&this._debugCamera.setDefaultOrbitTarget(this._debugOrbitTargetAnchor)}activateDebugCamera(){if(!this._debugCamera)return!1;let e=this.primaryCamera;if(e===this._debugCamera)return!0;this._preDebugPrimary=e;let t=this.setActiveCamera(this._debugCamera);return t&&this.seedDebugCameraPose(e),t}deactivateDebugCamera(){if(!this._debugCamera)return!1;let e=this._preDebugPrimary;if(this._preDebugPrimary=null,e&&e!==this._debugCamera)return this.setActiveCamera(e);for(let t of this.cameras.values())if(t!==this._debugCamera)return this.setActiveCamera(t);return!1}update(e){for(let t of this._activeCameras)t.update(e)}render(e){if(!this._rendererManager||this._activeCameras.length===0)return;this.updateOrbitingCamerasForRender();let t=[],i=[];for(let r of this._activeCameras)r.renderTarget?t.push(r):i.push(r);for(let r of t)this._rendererManager.renderCameraToTarget(e,r);i.length>0&&this._rendererManager.renderCameras(e,i)}updateOrbitingCamerasForRender(){for(let e of this._activeCameras)e.isOrbitActive&&e.updateOrbitControls()}ensureDefaultCamera(){if(this.cameras.size===0||this._activeCameras.length===0){let e=this._rendererManager?.screenResolution||new or(window.innerWidth,window.innerHeight),t=new w(m.ThirdPerson,e);return this.addCamera(t,"default"),t}return this._activeCameras[0]}dispose(){for(let e of this.cameras.values())e.destroy();this._debugCamera&&!this.cameras.has("__debug__")&&this._debugCamera.destroy(),this.cameras.clear(),this._activeCameras=[],this._debugCamera=null,this._preDebugPrimary=null,this._debugOrbitTargetAnchor&&this._sceneRef&&this._sceneRef.remove(this._debugOrbitTargetAnchor),this._debugOrbitTargetAnchor=null,this._rendererManager=null,this._sceneRef=null}createDebugCamera(e){this._debugCamera=new w(m.ThirdPerson,e),this._debugCamera.name="__debug__",this._debugCamera.isDebugViewCamera=!0,this._debugCamera.enableOrbitalControls(),this.cameras.set("__debug__",this._debugCamera)}seedDebugCameraPose(e){if(!this._debugCamera||this._debugCamera.isDebugOrbitPoseSeeded())return;let t=new he(0,0,0),i=new he(0,6,12);if(e&&e!==this._debugCamera){let r=e.camera.position,n=new he().subVectors(r,t);n.lengthSq()>1&&i.copy(n.normalize().multiplyScalar(12).add(new he(0,4,0)))}this._debugCamera.seedDebugOrbitPose(i,t)}resolveCamera(e){if(typeof e=="string")return this.cameras.get(e)??null;if(e===this._debugCamera)return this._debugCamera;for(let t of this.cameras.values())if(t===e)return t;return null}};var y=class{cameraRef;constructor(e){this.cameraRef=e}addTarget(e){this.cameraRef.addTarget(e)}removeTarget(e){this.cameraRef.removeTarget(e)}clearTargets(){this.cameraRef.clearTargets()}enableOrbitalControls(){this.cameraRef.enableOrbitalControls()}disableOrbitalControls(){this.cameraRef.disableOrbitalControls()}setViewport(e,t,i,r){this.cameraRef.setViewport(e,t,i,r)}addBehavior(e,t){this.cameraRef.pipeline.addBehavior(e,t)}removeBehavior(e){return this.cameraRef.pipeline.removeBehavior(e)}addAction(e){this.cameraRef.pipeline.addAction(e)}setPerspective(e,t){this.cameraRef.pipeline.setPerspective(z(e,t))}getPerspective(){return this.cameraRef.pipeline.perspective}getState(){return this.cameraRef.pipeline.getState()}getRenderTexture(){return this.cameraRef.getRenderTexture()}};function $a(a){let e=Et(a.screenResolution,{x:window.innerWidth,y:window.innerHeight}),t=10;a.perspective==="fixed-2d"&&(t=a.zoom||10);let i=new w(a.perspective||"third-person",e,t);a.name&&(i.name=a.name);let r=h(a.position,C),n=h(a.target,C);i.move(r),i.camera.lookAt(n);let s=a.perspective||"third-person";if(s==="fixed-2d"||s==="flat-2d"?i.pipeline.setPerspective(z(s,{zoom:t})):i.pipeline.setPerspective(z(s,{initialPosition:r.clone(),initialLookAt:n.clone()})),a.viewport&&(i.viewport={...a.viewport}),a.useOrbitalControls&&(i._useOrbitalControls=!0),a.skipDebugOrbit&&(i._skipDebugOrbit=!0),a.damping!=null&&(i.pipeline.damping=a.damping),a.behaviors)for(let[o,l]of Object.entries(a.behaviors))i.pipeline.addBehavior(o,l);if(a.renderToTexture){let{width:o=512,height:l=512}=a.renderToTexture;i.createRenderTarget(o,l)}return new y(i)}import{Vector3 as cr}from"three";function T(a){return!!a&&typeof a=="object"&&typeof a.create=="function"}function q(a){return!!a&&typeof a.then=="function"}function Xe(a){return!!a&&typeof a=="object"&&a instanceof y}function hi(a){return!a||typeof a!="object"||T(a)||Xe(a)||q(a)||typeof a.then=="function"?!1:a.constructor===Object||a.constructor?.name==="Object"}function gi(a){return a?!!(T(a)||typeof a=="function"||q(a)):!1}var dr="/three/basis/";function ye(a){return{...a,ktx2TranscoderPath:a?.ktx2TranscoderPath??dr}}var fe=class{constructor(e,t,i,r,n,s,o=60,l={},c=!0,d=[]){this.inputs=e;this.backgroundColor=t;this.backgroundImage=i;this.backgroundShader=r;this.gravity=n;this.variables=s;this.physicsRate=o;this.assetLoaders=l;this.defaultLighting=c;this.postProcessingEffects=d}};function ur(){return new fe({p1:["gamepad-1","keyboard-1"],p2:["gamepad-2","keyboard-2"]},re,null,null,new cr(0,0,0),{},60,{},!0)}function fi(a=[]){let e=ur(),t={},i=[],r=[],n=[];for(let l of a)Xe(l)?n.push(l):T(l)?i.push(l):gi(l)&&!T(l)?r.push(l):hi(l)&&(t={...t,...l});let s=new fe(t.inputs??e.inputs,t.backgroundColor??e.backgroundColor,t.backgroundImage??e.backgroundImage,t.backgroundShader??e.backgroundShader,t.gravity??e.gravity,t.variables??e.variables,t.physicsRate??e.physicsRate,t.assetLoaders??e.assetLoaders,t.defaultLighting??e.defaultLighting,t.postProcessingEffects??e.postProcessingEffects),o=n.length>0?n[0]:void 0;return{config:s,entities:i,asyncEntities:r,camera:o,cameras:n}}function as(a){return{...a}}var pr=Symbol("vessel"),Q=class extends V{static type=pr;_setup(e){}async _loaded(e){}_update(e){}_destroy(e){}_cleanup(e){}create(){return this}clone(){let e=mr();return this.replayUserLifecycleRegistrationsTo(e),this.cloneChildrenInto(e),e}add(...e){for(let t of e)super.add(t);return this}};function mr(...a){let e=new Q;return a.forEach(t=>e.add(t)),e.enableUserLifecycleTracking(),e}import{Color as Bi,Vector3 as zi}from"three";import{createSimulation as hr}from"@zylem/behaviors/core";function Je(a){return typeof a?.handlePostCollision=="function"&&typeof a?.handleIntersectionEvent=="function"}function gr(a,e){return a<e?`${a}|${e}`:`${e}|${a}`}var be=class a{type="World";simulation;collisionMap=new Map;collisionBehaviorMap=new Map;_removalMap=new Map;activeCollisionPairs=new Map;livePairs=new Map;handleIdToUuid=new Map;currentCollisionTimeMs=0;zeroGravity;fixedTimestep;interpolationAlpha=0;stepClock={steps:0};static async create(e,t=60){let i={x:e?.x??0,y:e?.y??0,z:e?.z??0},r=await hr({gravity:[i.x,i.y,i.z],fixedTimestep:1/t,initialCapacity:4096});return new a(r,t,i.x===0&&i.y===0&&i.z===0)}constructor(e,t=60,i=!1){this.simulation=e,this.fixedTimestep=1/t,this.zeroGravity=i,this.simulation?.setEventsEnabled?.(!1)}addEntity(e){let t={...e.bodyDesc??{}},i=e.colliderDescs?.length?e.colliderDescs:e.colliderDesc?[e.colliderDesc]:[];this.zeroGravity&&(t.lockTranslation=t.lockTranslation??[!0,!0,!0],t.lockRotation=t.lockRotation??[!0,!0,!0]),(e.controlledRotation||e instanceof te)&&e.bodyDesc?.lockRotation===void 0&&(t.lockRotation=[!0,!0,!0]);let r=this.simulation.spawn({body:t,colliders:i});if(!r){console.warn(`ZylemWorld: failed to spawn entity ${e.uuid} into simulation`);return}e.body=new Ot(this.simulation,r,this.stepClock),e.physicsAttached=!0,e.physicsWorldRef=this,e.simulationHandle=r,e.runtimeHandle=r.slot,e.runtimeAttached=!0,e.wasmStageRef=this.simulation.adapter,this.handleIdToUuid.set(r.id,e.uuid),this.collisionMap.set(e.uuid,e)}setForRemoval(e){e.physicsAttached&&this._removalMap.set(e.uuid,e)}destroyEntity(e){if(!(e.physicsWorldRef===this)){this.removeEntityFromTracking(e.uuid);return}let i=e.simulationHandle;if(i){try{this.simulation.despawn(i)}catch{}this.handleIdToUuid.delete(i.id)}this.removeEntityFromTracking(e.uuid),this.clearEntityPhysicsState(e)}setup(){}update(e){let{delta:t}=e;this.currentCollisionTimeMs+=t*1e3,this.processPendingRemovals();let i=this.hasCollisionPhaseListeners();i&&!this.simulation.areEventsEnabled&&this.simulation.setEventsEnabled?.(!0);let r=this.simulation.update(t);this.stepClock.steps+=r.stepsTaken,this.interpolationAlpha=r.alpha,i&&(this.applyCollisionEvents(r.events),this.processCollisionPairs(t,this.currentCollisionTimeMs))}hasCollisionPhaseListeners(){for(let e of this.collisionMap.values())if(e?.collisionDelegate?.collision?.length)return!0;return!1}applyCollisionEvents(e){for(let t of e){if(t.type!=="collisionStarted"&&t.type!=="collisionStopped")continue;let i=t.a?this.handleIdToUuid.get(t.a.id):void 0,r=t.b?this.handleIdToUuid.get(t.b.id):void 0;if(!i||!r||i===r)continue;let n=gr(i,r),s=this.livePairs.get(n);s||(s={uuidA:i<r?i:r,uuidB:i<r?r:i,contactCount:0,intersectionCount:0},this.livePairs.set(n,s));let o=t.type==="collisionStarted"?1:-1;t.sensor?s.intersectionCount=Math.max(0,s.intersectionCount+o):s.contactCount=Math.max(0,s.contactCount+o),s.contactCount===0&&s.intersectionCount===0&&this.livePairs.delete(n)}}snapshotLivePairs(){let e=new Map;for(let[t,i]of this.livePairs)e.set(t,{uuidA:i.uuidA,uuidB:i.uuidB,hasContact:i.contactCount>0,hasIntersection:i.intersectionCount>0});return e}updatePostCollisionBehaviors(e){let t=this.collisionBehaviorMap;for(let[i,r]of t){let n=r;if(!Je(n))continue;n.handlePostCollision({entity:n,delta:e})||this.collisionBehaviorMap.delete(i)}}processPendingRemovals(){if(this._removalMap.size!==0){for(let[,e]of this._removalMap)this.destroyEntity(e);this._removalMap.clear()}}removeEntityFromTracking(e){this.collisionMap.delete(e),this._removalMap.delete(e),this.pruneActiveCollisionPairs(e)}pruneActiveCollisionPairs(e){for(let[t,i]of this.activeCollisionPairs)(i.uuidA===e||i.uuidB===e)&&this.activeCollisionPairs.delete(t);for(let[t,i]of this.livePairs)(i.uuidA===e||i.uuidB===e)&&this.livePairs.delete(t)}entityHasCollisionPhaseListener(e,t){let i=e?.collisionDelegate.collision;if(!i?.length)return!1;for(let r of i)if(r.options.phase===t)return!0;return!1}processCollisionPairs(e,t=this.currentCollisionTimeMs){let i=this.snapshotLivePairs();for(let[r,n]of i){let s=this.collisionMap.get(n.uuidA),o=this.collisionMap.get(n.uuidB);this.activeCollisionPairs.has(r)||this.dispatchCollisionPhase(n,"enter",t),(this.entityHasCollisionPhaseListener(s,"stay")||this.entityHasCollisionPhaseListener(o,"stay"))&&this.dispatchCollisionPhase(n,"stay",t),n.hasIntersection&&this.dispatchIntersectionDelegates(n,e)}this.updatePostCollisionBehaviors(e),this.activeCollisionPairs=i}dispatchCollisionPhase(e,t,i){let r={phase:t,nowMs:i},n=this.collisionMap.get(e.uuidA),s=this.collisionMap.get(e.uuidB);n&&s&&n._collision(s,Be.globals,r);let o=this.collisionMap.get(e.uuidA),l=this.collisionMap.get(e.uuidB);o&&l&&l._collision(o,Be.globals,r)}dispatchIntersectionDelegates(e,t){let i=this.collisionMap.get(e.uuidA),r=this.collisionMap.get(e.uuidB);i&&r&&Je(i)&&(i.handleIntersectionEvent({entity:i,other:r,delta:t}),this.collisionBehaviorMap.set(i.uuid,i));let n=this.collisionMap.get(e.uuidA),s=this.collisionMap.get(e.uuidB);n&&s&&Je(s)&&(s.handleIntersectionEvent({entity:s,other:n,delta:t}),this.collisionBehaviorMap.set(s.uuid,s))}raycast(e,t,i){let r=this.simulation.castRay([e.x,e.y,e.z],[t.x,t.y,t.z],i,!0);return r?{uuid:r.entity?this.handleIdToUuid.get(r.entity.id)??null:null,distance:r.distance,normal:r.normal}:null}destroy(){try{for(let[,e]of this.collisionMap)try{this.clearEntityPhysicsState(e)}catch{}try{this.simulation.dispose()}catch{}this.collisionMap.clear(),this.collisionBehaviorMap.clear(),this._removalMap.clear(),this.activeCollisionPairs.clear(),this.livePairs.clear(),this.handleIdToUuid.clear()}catch{}}clearEntityPhysicsState(e){e.physicsAttached=!1,e.body=null,e.runtimeHandle=-1,e.runtimeAttached=!1,e.wasmStageRef=null,e.simulationHandle=void 0,e.physicsWorldRef===this&&(e.physicsWorldRef=null)}};import{Scene as fr,Color as yi,AmbientLight as yr,DirectionalLight as br,Vector3 as ve,GridHelper as vr,Texture as Cr,SRGBColorSpace as Sr}from"three";var Ce=class{type="Scene";_setup;scene;zylemCamera;cameraManager=null;containerElement=null;update=()=>{};_collision;_destroy;name;tag;constructor(e,t,i){let r=new fr,s=i.backgroundColor instanceof yi?i.backgroundColor:new yi(i.backgroundColor);r.background=s,i.backgroundShader?this.setupBackgroundShader(r,i.backgroundShader):i.backgroundImage&&O.loadTexture(i.backgroundImage,{colorSpace:Sr}).then(o=>{r.background=o}),this.scene=r,this.zylemCamera=t,i.defaultLighting!==!1&&this.setupLighting(r),u.enabled&&this.debugScene()}setupBackgroundShader(e,t){if(!Lt(t)){console.warn("ZylemScene: GLSL background shaders are not supported on the WebGPU renderer. Provide a TSL shader (ZylemTSLShader) as backgroundShader. Keeping solid background.");return}e.background=null,e.backgroundNode=t.colorNode}setup(){this._setup&&this._setup({me:this,camera:this.zylemCamera,globals:g()})}destroy(){this.cameraManager?(this.cameraManager.dispose(),this.cameraManager=null):this.zylemCamera&&this.zylemCamera.destroy&&this.zylemCamera.destroy(),this.scene&&(this.scene.backgroundNode=null,this.scene.background instanceof Cr&&(this.scene.background.dispose(),this.scene.background=null),this.scene.traverse(e=>{if(e.geometry&&e.geometry.dispose?.(),e.material){let t=Array.isArray(e.material)?e.material:[e.material];for(let i of t)i.map&&i.map.dispose?.(),i.normalMap&&i.normalMap.dispose?.(),i.aoMap&&i.aoMap.dispose?.(),i.emissiveMap&&i.emissiveMap.dispose?.(),i.roughnessMap&&i.roughnessMap.dispose?.(),i.metalnessMap&&i.metalnessMap.dispose?.(),i.envMap&&i.envMap.dispose?.(),i.lightMap&&i.lightMap.dispose?.(),i.bumpMap&&i.bumpMap.dispose?.(),i.displacementMap&&i.displacementMap.dispose?.(),i.alphaMap&&i.alphaMap.dispose?.(),i.dispose?.()}e.isLight&&e.shadow?.map&&e.shadow.map.dispose()}),this.scene.clear())}async setupCamera(e,t,i){this.addCameraToScene(e,t),i?await t.setup(e,i):await t.setupLegacy(e)}async setupCameraManager(e,t,i){this.cameraManager=t;for(let r of t.activeCameras)this.addCameraToScene(e,r);await t.setup(e,i)}addCameraToScene(e,t){t.cameraRig?e.add(t.cameraRig):e.add(t.camera)}setupLighting(e){let t=new yr(16777215,1);e.add(t);let i=new br(16777215,2);i.name="Light",i.position.set(0,100,0),i.castShadow=!0,i.shadow.camera.near=.1,i.shadow.camera.far=2e3,i.shadow.camera.left=-100,i.shadow.camera.right=100,i.shadow.camera.top=100,i.shadow.camera.bottom=-100,i.shadow.mapSize.width=2048,i.shadow.mapSize.height=2048,e.add(i)}updateRenderer(e,t){if(this.cameraManager)for(let i of this.cameraManager.allCameras)i.resize(e,t);else this.zylemCamera.resize(e,t)}add(e,t=new ve(0,0,0)){e.position.set(t.x,t.y,t.z),this.scene.add(e)}addEntity(e){let t=e.group??e.mesh;!t||this.isAttachedOutsideScene(t)||this.add(t,e.options.position)}addEntityGroup(e){if(D(e))return;let t=e.group??e.mesh;if(!t||this.isAttachedOutsideScene(t))return;let i=Pr(e);i&&i.attachToScene(this.scene);let r=e.options.position??new ve(0,0,0);if(e.physicsAttached&&e.body)try{let n=e.body.translation();r=new ve(n.x,n.y,n.z)}catch{r=e.options.position??new ve(0,0,0)}this.add(t,r),Z(e)}isAttachedOutsideScene(e){return e.parent!=null&&e.parent!==this.scene}debugScene(){let i=new vr(1e3,100);this.scene.add(i)}};function Pr(a){return a.constructor.type===At?a:null}var Se=class{update=()=>{};setup=()=>{};destroy=()=>{};nodeSetup(e){typeof this._setup=="function"&&this._setup(e),this.setup&&this.setup(e)}nodeUpdate(e){typeof this._update=="function"&&this._update(e),this.update&&this.update(e)}nodeDestroy(e){this.destroy&&this.destroy(e),typeof this._destroy=="function"&&this._destroy(e)}};import{Quaternion as wr}from"three";var bi=new wr;function vi(a){let e=a._childrenMap,t=a._world;for(let[,i]of e){if(!i?.body||i.markedForRemoval||i.isInstanced||i.isBundled||i.skipRenderPoseSync)continue;let r=i.body,n=i.group??i.mesh,s=n?ie(r,t?.interpolationAlpha??0):null;n&&s&&n.position.set(s.position.x,s.position.y,s.position.z),!i.controlledRotation&&n&&s&&(bi.set(s.rotation.x,s.rotation.y,s.rotation.z,s.rotation.w),n.setRotationFromQuaternion(bi))}}import{nanoid as gn}from"nanoid";import{Box3 as nn,BufferAttribute as ki,BufferGeometry as an,LineBasicMaterial as sn,LineSegments as on,Raycaster as ln,Vector2 as cn,Vector3 as ut}from"three";import{subscribe as dn}from"valtio/vanilla";import{nanoid as Li}from"nanoid";import{subscribe as Er}from"valtio/vanilla";var Pe=class{stage;constructor(e){this.stage=e}subscribe(e){let t=()=>e(this.snapshot());return t(),Er(u,t)}resolveTarget(e){let t=this.stage.entityDelegate.debugMap.get(e)||this.stage.entityDelegate.childrenMap.get(e)||this.stage.world?.collisionMap.get(e)||null;return t?.group??t?.mesh??null??null}snapshot(){return{enabled:u.enabled,selected:u.selectedEntityId?[u.selectedEntityId]:[]}}};import{Box3 as xr,BoxGeometry as Ci,Color as Tr,EdgesGeometry as Si,Group as Dr,LineBasicMaterial as Mr,LineSegments as _r,Mesh as Rr,MeshBasicMaterial as kr,Vector3 as Pi}from"three";var we=class{scene;container;fillMesh;edgeLines;currentColor=new Tr(65280);bbox=new xr;size=new Pi;center=new Pi;constructor(e){this.scene=e;let t=new Ci(1,1,1);this.fillMesh=new Rr(t,new kr({color:this.currentColor,transparent:!0,opacity:.12,depthWrite:!1}));let i=new Si(t);this.edgeLines=new _r(i,new Mr({color:this.currentColor,linewidth:1})),this.container=new Dr,this.container.name="DebugEntityCursor",this.container.add(this.fillMesh),this.container.add(this.edgeLines),this.container.visible=!1,this.scene.add(this.container)}setColor(e){this.currentColor.set(e),this.fillMesh.material.color.set(this.currentColor),this.edgeLines.material.color.set(this.currentColor)}updateFromObject(e){if(!e){this.hide();return}if(this.bbox.setFromObject(e),!isFinite(this.bbox.min.x)||!isFinite(this.bbox.max.x)){this.hide();return}this.bbox.getSize(this.size),this.bbox.getCenter(this.center);let t=new Ci(Math.max(this.size.x,1e-6),Math.max(this.size.y,1e-6),Math.max(this.size.z,1e-6));this.fillMesh.geometry.dispose(),this.fillMesh.geometry=t;let i=new Si(t);this.edgeLines.geometry.dispose(),this.edgeLines.geometry=i,this.container.position.copy(this.center),this.container.visible=!0}hide(){this.container.visible=!1}dispose(){this.scene.remove(this.container),this.fillMesh.geometry.dispose(),this.fillMesh.material.dispose(),this.edgeLines.geometry.dispose(),this.edgeLines.material.dispose()}};import{Box3 as Lr,BoxGeometry as Or,Group as Ar,Mesh as Br,MeshBasicMaterial as zr,Vector3 as wi}from"three";var Fr={x:0,y:0,z:0},Ir=7128319,Vr=.35;function Zr(){return new zr({color:Ir,transparent:!0,opacity:Vr,depthWrite:!1})}function Gr(a){let e=a.size;return new wi(e?.x??1,e?.y??1,e?.z??1)}function Ur(a,e){try{let t=a.create({position:Fr,props:e});if(!t||typeof t.then=="function")return null;let i=t,r=i.group??i.mesh??null;return r?r.clone():null}catch(t){return console.warn(`[zylem] placement ghost: the "${a.id}" factory failed, falling back to a box`,t),null}}function Nr(a,e){a.traverse(t=>{let i=t;i.isMesh&&(i.material=e,i.castShadow=!1,i.receiveShadow=!1)})}var Ee=class{scene;container;builtFor=null;builtProps=null;material=null;extent=null;bounds=new Lr;constructor(e){this.scene=e,this.container=new Ar,this.container.name="PlacementGhost",this.container.visible=!1,this.scene.add(this.container)}setType(e,t){let i=t??null;if(e===this.builtFor&&i===this.builtProps)return;if(this.builtFor=e,this.builtProps=i,this.clearSilhouette(),!e){this.hide();return}let r=ee(e),n={...r?.defaultProps??{},...t??{}},o=(r?Ur(r,n):null)??new Br(new Or(...Gr(n).toArray()));o.position.set(0,0,0),this.material=Zr(),Nr(o,this.material),this.container.add(o),this.bounds.setFromObject(o),this.extent=this.bounds.isEmpty()?null:this.bounds.getSize(new wi)}measure(){return this.extent}showAt(e){if(this.container.children.length===0){this.hide();return}this.container.position.copy(e),this.container.visible=!0}hide(){this.container.visible=!1}dispose(){this.clearSilhouette(),this.scene.remove(this.container),this.builtFor=null,this.builtProps=null}clearSilhouette(){for(let e of[...this.container.children])this.container.remove(e),e.traverse(t=>{let i=t;i.isMesh&&i.geometry?.dispose()});this.material?.dispose(),this.material=null,this.extent=null}};import{Vector3 as et}from"three";var Hr=0;function Wr(a,e){if(e)return{position:a.origin.clone().add(a.direction.clone().multiplyScalar(e.distance)),normal:new et(e.normal[0],e.normal[1],e.normal[2])};if(Math.abs(a.direction.y)<1e-6)return null;let t=(Hr-a.origin.y)/a.direction.y;return t<0?null:{position:a.origin.clone().add(a.direction.clone().multiplyScalar(t)),normal:new et(0,1,0)}}function jr(a,e){if(e.lengthSq()<1e-8)return 0;let t=e.clone().normalize();return(Math.abs(t.x)*a.x+Math.abs(t.y)*a.y+Math.abs(t.z)*a.z)/2}function tt(a,e,t){let i=jr(e,t);return i<=0?a.clone():a.clone().add(t.clone().normalize().multiplyScalar(i))}function it(a,e,t,i){let r=Wr(a,e);if(!r)return null;let{normal:n}=r,s=t.enabled?J(r.position,t.translate):r.position,o=new et(s.x,s.y,s.z);return{position:i?tt(o,i,n):o,normal:n}}import{Box3 as Yr,Quaternion as Me,Vector3 as b}from"three";import{nanoid as $r}from"nanoid";import{Vector3 as F}from"three";var nt=.95,Kr=16,Y=new F,qr=new F,Ei=new F,rt=new F;function xi(a){return a?a.isPerspectiveCamera===!0||a.isOrthographicCamera===!0:!1}function xe(a,e,t=nt){return Y.copy(a).project(e),Math.abs(Y.x)<=t&&Math.abs(Y.y)<=t&&Y.z>=-1&&Y.z<=1}function Ti(a){let e=0,t=1;for(let i=0;i<Kr;i+=1){let r=(e+t)/2;a(r)?e=r:t=r}return e}function Di(a,e,t,i=nt){if(!xi(t))return e.clone();let r=t;if(xe(e,r,i)||!xe(a,r,i))return e.clone();let n=Ti(s=>xe(qr.copy(a).lerp(e,s),r,i));return a.clone().lerp(e,n)}function Mi(a,e,t,i,r=nt){if(!xi(i)||t.x<=1&&t.y<=1&&t.z<=1||a.isEmpty())return t.clone();let n=i;Ei.copy(e);let s=new F(1,1,1),o=c=>(s.set(1+(t.x-1)*c,1+(t.y-1)*c,1+(t.z-1)*c),Qr(a,Ei,s,n,r));if(o(1))return t.clone();let l=Ti(o);return new F(1+(t.x-1)*l,1+(t.y-1)*l,1+(t.z-1)*l)}function Qr(a,e,t,i,r){for(let n=0;n<8;n+=1)if(rt.set(n&1?a.max.x:a.min.x,n&2?a.max.y:a.min.y,n&4?a.max.z:a.min.z),rt.sub(e).multiply(t).add(e),!xe(rt,i,r))return!1;return!0}var Xr={translate:"Move",rotate:"Rotate",scale:"Scale"};function at(a){let e=typeof a?.getPose=="function"?a.getPose():null,t=a?.group??a?.mesh,i=e?.position??(t?{x:t.position.x,y:t.position.y,z:t.position.z}:null)??{x:0,y:0,z:0},r=e?.rotation??{x:0,y:0,z:0,w:1},n=typeof a?.getScale=="function"?a.getScale():{x:1,y:1,z:1};return{position:new b(i.x,i.y,i.z),quaternion:new Me(r.x,r.y,r.z,r.w),scale:new b(n.x,n.y,n.z)}}function _i(a){let e=Ze(a.quaternion);return{position:{x:a.position.x,y:a.position.y,z:a.position.z},rotation:e,quaternion:{x:a.quaternion.x,y:a.quaternion.y,z:a.quaternion.z,w:a.quaternion.w},scale:{x:a.scale.x,y:a.scale.y,z:a.scale.z}}}function Jr(a,e){return a.position.distanceToSquared(e.position)>1e-5*1e-5||Math.abs(a.quaternion.dot(e.quaternion))<1-1e-5||a.scale.distanceToSquared(e.scale)>1e-5*1e-5}function Te(a,e){(e.position||e.quaternion)&&a.setPose?.({position:e.position?{x:e.position.x,y:e.position.y,z:e.position.z}:void 0,rotation:e.quaternion?{x:e.quaternion.x,y:e.quaternion.y,z:e.quaternion.z,w:e.quaternion.w}:void 0}),e.scale&&a.setScale?.(e.scale.x,e.scale.y,e.scale.z)}function en(a){let e=a?.group??a?.mesh;if(!e?.isObject3D)return null;let t=new Yr().setFromObject(e);return t.isEmpty()?null:t}var st=.02,ot=50;function tn(a){return new b(lt(a.x,st,ot),lt(a.y,st,ot),lt(a.z,st,ot))}function lt(a,e,t){return Math.min(Math.max(a,e),t)}var ct=new Me,rn=new b,De=class{gizmo=new Gt;context;mode=null;session=null;pausedBeforeEntry=null;constructor(e){this.context=e}setMode(e){if(this.mode!==e){if(e&&this.pausedBeforeEntry===null?(this.pausedBeforeEntry=u.paused,u.paused=!0):!e&&this.pausedBeforeEntry!==null&&(u.paused=this.pausedBeforeEntry,this.pausedBeforeEntry=null),this.mode=e,this.cancelDrag(),!e){this.gizmo.hide();return}this.gizmo.setMode(e)}}getMode(){return this.mode}get isDragging(){return this.session!==null}update(){let e=this.context.getScene();if(e&&this.gizmo.addTo(e),!this.mode){this.gizmo.hide();return}if(!this.session){let i=this.selectionPivot();if(!i){this.gizmo.hide();return}this.gizmo.show(i)}let t=this.context.getCamera();t&&this.gizmo.update(t)}hover(e){if(!this.mode||this.session)return null;let t=this.gizmo.pick(e);return this.gizmo.setHighlight(t),t}pointerDown(e){if(!this.mode)return!1;let t=this.context.getCamera();if(!t)return!1;let i=this.gizmo.pick(e);if(!i||!this.gizmo.beginDrag(i,e,t))return!1;let r=[];for(let n of u.selectedEntityIds){let s=this.context.resolveEntity(n);s&&r.push({uuid:n,entity:s,start:at(s),startBounds:this.mode==="scale"?en(s):null})}return r.length?(this.session={mode:this.mode,axis:i,entries:r,pivotStart:this.gizmo.pivot.clone(),changed:!1},!0):(this.gizmo.endDrag(),!1)}pointerMove(e,t){let i=this.session;if(!i)return;let r=this.context.getCamera();if(!r)return;let n=this.gizmo.updateDrag(e,r);if(!n)return;let s=k(),o=s.enabled&&!t;switch(n.kind){case"translate":this.applyTranslate(i,n.offset,o?s.translate:0,r);break;case"rotate":this.applyRotate(i,n.axis,n.angle,o?s.rotate:0);break;case"scale":this.applyScale(i,n.factor,o?s.scale:0,r);break}i.changed=!0}pointerUp(){let e=this.session;if(this.session=null,this.gizmo.endDrag(),!e)return;let t=[];for(let i of e.entries){let r=at(i.entity);Jr(i.start,r)&&(e.mode==="scale"&&Ge(i.entity),t.push({uuid:i.uuid,before:_i(i.start),after:_i(r)}))}t.length&&I({opId:$r(10),kind:"transform",label:this.describeOperation(e),entries:t})}cancelDrag(){this.session=null,this.gizmo.endDrag()}dispose(){this.cancelDrag(),this.pausedBeforeEntry!==null&&(u.paused=this.pausedBeforeEntry,this.pausedBeforeEntry=null),this.gizmo.dispose()}applyTranslate(e,t,i,r){let n=rn.copy(e.pivotStart).add(t),s=Di(e.pivotStart,n,r),o=i>0?J(s,i):s,l=new b(o.x-e.pivotStart.x,o.y-e.pivotStart.y,o.z-e.pivotStart.z);for(let c of e.entries)Te(c.entity,{position:c.start.position.clone().add(l)})}applyRotate(e,t,i,r){let n=e.axis;for(let s of e.entries){ct.setFromAxisAngle(t,i);let o=ct.clone().multiply(s.start.quaternion),l=o;if(r>0&&(n==="x"||n==="y"||n==="z")){let d=Ze(o);d[n]=St(d[n],r);let p=Ve(d);l=new Me(p.x,p.y,p.z,p.w)}let c=s.start.position.clone().sub(e.pivotStart).applyQuaternion(ct).add(e.pivotStart);Te(s.entity,{position:c,quaternion:l})}}applyScale(e,t,i,r){for(let n of e.entries){let s=n.startBounds?Mi(n.startBounds,n.start.position,t,r):t,o=tn(s),l=new b(n.start.scale.x*o.x,n.start.scale.y*o.y,n.start.scale.z*o.z),c=i>0?Pt(l,i):l;Te(n.entity,{scale:new b(c.x,c.y,c.z)})}}describeOperation(e){let t=Xr[e.mode];if(e.entries.length>1)return`${t} ${e.entries.length} entities`;let i=e.entries[0]?.entity,r=i?.name||String(i?.constructor?.type??"").replace("Symbol(","").replace(")","")||"Entity";return`${t} ${r}`}selectionPivot(){let e=u.selectedEntityIds;if(!e.length)return null;let t=new b,i=0;for(let r of e){let n=this.context.resolveEntity(r);n&&(t.add(at(n).position),i++)}return i?t.divideScalar(i):null}};function Ri(a,e,t){for(let i of a.entries){let r=e==="undo"?i.before:i.after;if(!r)continue;let n=t(i.uuid);if(!n)continue;let s=r.quaternion??(r.rotation?Ve(r.rotation):void 0);Te(n,{position:r.position?new b(r.position.x,r.position.y,r.position.z):void 0,quaternion:s?new Me(s.x,s.y,s.z,s.w):void 0,scale:r.scale?new b(r.scale.x,r.scale.y,r.scale.z):void 0}),r.scale&&Ge(n)}}var un=2293538,pn=16724787,dt=new nn,Oi=new ut,_e=class{stage;options;mouseNdc=new cn(-2,-2);raycaster=new ln;domDisposeFns=[];domListenersAttached=!1;debugCursor=null;placementGhost=null;debugLines=null;cameraDebugDelegate=null;debugStateUnsubscribe=null;focusContextUnregister=null;entityResolverUnregister=null;lastDebugEnabled=null;warnedMissingAddFactory=!1;transformTool;grid=new Zt;lastTool=null;capturedPointer=null;constructor(e,t){this.stage=e,this.options={maxRayDistance:t?.maxRayDistance??5e3,addEntityFactory:t?.addEntityFactory??null},this.transformTool=new De({getScene:()=>this.stage.scene?.scene??null,getCamera:()=>this.getDebugViewCamera()?.camera??null,resolveEntity:i=>this.resolveEntity(i)}),this.syncWithDebugState(),this.debugStateUnsubscribe=dn(u,()=>{this.syncWithDebugState()}),this.entityResolverUnregister=mt(i=>this.resolveEntity(i)),this.focusContextUnregister=Ct({resolveEntity:i=>this.resolveEntity(i),frameObject:i=>{this.ensureCameraDebugDelegate(),this.getDebugViewCamera()?.frameObject(i)},ensureDebugReady:()=>{u.enabled||(u.enabled=!0),this.lastDebugEnabled=!0,this.activate()}})}setAddEntityFactory(e){this.options.addEntityFactory=e,this.warnedMissingAddFactory=!1}getDebugViewCamera(){return this.stage.cameraManagerRef?.primaryCamera??this.stage.cameraManagerRef?.debugCamera??this.stage.cameraRef??null}resolveEntity(e){let t=this.stage.entityDelegate.debugMap.get(e);if(t)return t;let i=this.stage.entityDelegate.childrenMap.get(e);return i||(this.stage.world?.collisionMap.get(e)??null)}populateDebugMap(){this.stage.entityDelegate.childrenMap.forEach((e,t)=>{this.stage.entityDelegate.debugMap.set(t,e)})}ensureCameraDebugDelegate(){let e=this.stage.cameraManagerRef?.debugCamera??null;e&&(this.cameraDebugDelegate||(this.cameraDebugDelegate=new Pe(this.stage)),e.setDebugDelegate(this.cameraDebugDelegate))}syncWithDebugState(){this.syncToolMode(),this.syncGrid();let e=u.enabled;e!==this.lastDebugEnabled&&(this.lastDebugEnabled=e,e?this.activate():this.deactivate())}syncToolMode(){let e=u.tool;if(e===this.lastTool)return;this.lastTool=e,e!=="none"&&(this.ensureInteraction(),this.populateDebugMap()),this.parkToolVisuals(e);let t=ze(e);this.getDebugViewCamera()?.setOrbitFollowEnabled(!t),this.transformTool.setMode(t?e:null)}syncGrid(){let e=this.stage.scene?.scene;e&&(this.grid.addTo(e),this.grid.setIncrement(k().translate),this.grid.setVisible(u.gridVisible))}activate(){this.domListenersAttached||(this.domListenersAttached=this.attachDomListeners()),this.populateDebugMap(),this.stage.cameraManagerRef?.activateDebugCamera();let e=this.stage.cameraManagerRef?.debugCamera??null;this.rebindPostProcessing(e),this.ensureCameraDebugDelegate(),document.pointerLockElement&&document.exitPointerLock()}deactivate(){this.disposeDebugVisuals(),this.transformTool.cancelDrag(),this.grid.setVisible(!1);let e=this.stage.cameraManagerRef?.debugCamera;e&&e.setDebugDelegate(null),this.stage.cameraRef&&this.stage.cameraRef!==e&&this.stage.cameraRef.setDebugDelegate(null),this.cameraDebugDelegate=null,this.stage.cameraManagerRef?.deactivateDebugCamera();let t=this.stage.cameraManagerRef?.primaryCamera??this.stage.cameraRef??null;this.rebindPostProcessing(t)}rebindPostProcessing(e){let t=this.stage.scene?.scene,i=this.stage.rendererManager;t&&i&&e&&i.setupPostProcessing(t,e.camera)}initDebugVisuals(){this.debugLines||!this.stage.scene||(this.debugLines=new on(new an,new sn({vertexColors:!0})),this.stage.scene.scene.add(this.debugLines),this.debugLines.visible=!0)}disposeDebugVisuals(){this.debugLines&&this.stage.scene&&(this.stage.scene.scene.remove(this.debugLines),this.debugLines.geometry.dispose(),this.debugLines.material.dispose(),this.debugLines=null)}ensureToolVisuals(){let e=this.stage.scene?.scene;e&&(this.debugCursor??=new we(e),this.placementGhost??=new Ee(e))}parkToolVisuals(e){e!=="add"&&this.placementGhost?.hide(),e!=="select"&&e!=="delete"&&this.debugCursor?.hide()}disposeToolVisuals(){this.debugCursor?.dispose(),this.debugCursor=null,this.placementGhost?.dispose(),this.placementGhost=null}update(){let e=this.getDebugViewCamera();if(!this.stage.scene||!this.stage.world||!e)return;let{world:t}=this.stage,i=Fe();if(this.ensureInteraction(),this.ensureToolVisuals(),u.enabled?(this.initDebugVisuals(),this.updateColliderWireframes(t)):this.disposeDebugVisuals(),this.updatePlacementGhost(i,t),ze(i)){this.debugCursor?.hide(),this.transformTool.update(),this.transformTool.isDragging||this.transformTool.hover(this.currentRay());return}if(this.transformTool.update(),!(i==="select"||i==="delete")){this.debugCursor?.hide();return}let n=this.currentRay(),s=t.raycast(n.origin,n.direction,this.options.maxRayDistance);s?gt(s.uuid??null):ft();let o=ht();if(!o){this.debugCursor?.hide();return}let l=this.resolveEntity(o),c=l?.group??l?.mesh??null;if(!c){this.debugCursor?.hide();return}switch(i){case"select":this.debugCursor?.setColor(un);break;case"delete":this.debugCursor?.setColor(pn);break;default:this.debugCursor?.setColor(16777215);break}this.debugCursor?.updateFromObject(c)}updateColliderWireframes(e){if(!this.debugLines)return;let t=e.simulation.getDebugRender();t&&t.vertices.length>0?(this.debugLines.geometry.setAttribute("position",new ki(new Float32Array(t.vertices),3)),this.debugLines.geometry.setAttribute("color",new ki(new Float32Array(t.colors),4)),this.debugLines.geometry.attributes.position.needsUpdate=!0,this.debugLines.geometry.attributes.color.needsUpdate=!0,this.debugLines.visible=!0):this.debugLines.visible=!1}ensureInteraction(){this.domListenersAttached||!X()||(this.domListenersAttached=this.attachDomListeners())}updatePlacementGhost(e,t){let i=this.placementGhost;if(!i)return;let r=u.addTypeId;if(e!=="add"||!r){i.hide();return}i.setType(r,u.addTypeProps??null);let n=this.currentRay(),s=t.raycast(n.origin,n.direction,this.options.maxRayDistance)??null,o=it(n,s,k(),i.measure());if(!o){i.hide();return}i.showAt(o.position)}dispose(){this.focusContextUnregister?.(),this.focusContextUnregister=null,this.entityResolverUnregister?.(),this.entityResolverUnregister=null,this.debugStateUnsubscribe?.(),this.debugStateUnsubscribe=null,this.endPointerCapture(),this.transformTool.dispose(),this.grid.dispose(),this.deactivate(),this.disposeToolVisuals(),this.domDisposeFns.forEach(e=>e()),this.domDisposeFns=[],this.domListenersAttached=!1}applySceneOperation(e,t){let i=t==="undo";switch(e.kind){case"transform":Ri(e,t,r=>this.resolveEntity(r));break;case"create":for(let r of e.entries)i?this.stage.entityDelegate.detachEntity(r.uuid):this.stage.entityDelegate.restoreEntity(r.uuid);break;case"delete":for(let r of e.entries)i?this.stage.entityDelegate.restoreEntity(r.uuid):this.stage.entityDelegate.detachEntity(r.uuid);break}}currentRay(){let e=this.getDebugViewCamera();return e?(this.raycaster.setFromCamera(this.mouseNdc,e.camera),{origin:this.raycaster.ray.origin.clone(),direction:this.raycaster.ray.direction.clone().normalize()}):{origin:new ut,direction:new ut(0,0,-1)}}handleAction(e){let t=Fe();if(t!=="select"&&t!=="delete"&&t!=="add")return;let r=this.stage.world?.raycast(e.origin,e.direction,this.options.maxRayDistance)??null;switch(t){case"select":{let n=r?.uuid??null;n&&this.resolveEntity(n)?Ie(n):Ie(null);break}case"delete":{let n=r?.uuid??null;if(!n)break;this.stage.entityDelegate.detachEntity(n)&&I({opId:Li(10),kind:"delete",label:"Delete entity",entries:[{uuid:n}]});break}case"add":this.placeEntity(e,r);break}}placeEntity(e,t){let i=it(e,t,k());if(!i)return;let{position:r,normal:n}=i,s=u.addTypeId?ee(u.addTypeId):null;if(!s&&!this.options.addEntityFactory){this.warnMissingAddSource();return}let o=s?s.create({position:{x:r.x,y:r.y,z:r.z},normal:{x:n.x,y:n.y,z:n.z},props:{...s.defaultProps??{},...u.addTypeProps??{}}}):this.options.addEntityFactory({position:r,normal:n});o&&Promise.resolve(o).then(async l=>{l&&(await this.stage.entityDelegate.spawnEntity(l),this.restOnSurface(l,r,n),I({opId:Li(10),kind:"create",label:`Add ${s?.label??"entity"}`,entries:[{uuid:l.uuid}]}))}).catch(l=>{console.error("Add tool: failed to spawn entity",l)})}restOnSurface(e,t,i){let r=e?.group??e?.mesh;if(!r||typeof e.setPose!="function"||(dt.setFromObject(r),dt.isEmpty()))return;dt.getSize(Oi);let n=tt(t,Oi,i);n.equals(t)||e.setPose({position:{x:n.x,y:n.y,z:n.z}})}warnMissingAddSource(){if(this.warnedMissingAddFactory)return;this.warnedMissingAddFactory=!0;let e="Add tool: no entity type is armed and no `addEntityFactory` is configured, so there is nothing to spawn.";console.warn(e),wt("warn",e)}attachDomListeners(){let e=this.stage.rendererManager?.getDomElement();if(!e)return!1;let t=s=>{let o=e.getBoundingClientRect(),l=(s.clientX-o.left)/o.width*2-1,c=-((s.clientY-o.top)/o.height*2-1);this.mouseNdc.set(l,c)},i=s=>{t(s),this.transformTool.isDragging&&this.transformTool.pointerMove(this.currentRay(),s.altKey)},r=s=>{if(s.button!==0)return;t(s);let o=this.currentRay();if(this.transformTool.pointerDown(o)){this.beginPointerCapture(e,s.pointerId);return}this.handleAction(o)},n=()=>{this.transformTool.isDragging&&(this.transformTool.pointerUp(),this.endPointerCapture())};return e.addEventListener("pointermove",i),e.addEventListener("pointerdown",r),e.addEventListener("pointerup",n),e.addEventListener("pointercancel",n),this.domDisposeFns.push(()=>e.removeEventListener("pointermove",i),()=>e.removeEventListener("pointerdown",r),()=>e.removeEventListener("pointerup",n),()=>e.removeEventListener("pointercancel",n)),!0}beginPointerCapture(e,t){this.getDebugViewCamera()?.setOrbitInteractionEnabled(!1);try{e.setPointerCapture(t),this.capturedPointer={element:e,pointerId:t}}catch{this.capturedPointer=null}}endPointerCapture(){if(this.getDebugViewCamera()?.setOrbitInteractionEnabled(!0),!!this.capturedPointer){try{this.capturedPointer.element.releasePointerCapture(this.capturedPointer.pointerId)}catch{}this.capturedPointer=null}}};import{Vector2 as mn}from"three";var Re=class{stage;constructor(e){this.stage=e}createDefaultCamera(){let e=window.innerWidth,t=window.innerHeight,i=new mn(e,t);return new w(m.ThirdPerson,i)}resolveCamera(e,t){return e||(t?t.cameraRef:this.createDefaultCamera())}buildCameraManager(e,...t){let i=new ge;if(e)return i.addCamera(e,e.name||"main"),i;let r=t.filter(n=>n!==void 0);if(r.length>0){for(let n of r){let s=n.cameraRef;i.addCamera(s,s.name||void 0)}for(let n=1;n<r.length;n++)i.addActiveCamera(r[n].cameraRef)}else{let n=this.createDefaultCamera();i.addCamera(n,"default")}return i}};var ke=class{loadingHandlers=[];stageName;stageIndex;setStageContext(e,t){this.stageName=e,this.stageIndex=t}onLoading(e){return this.loadingHandlers.push(e),()=>{this.loadingHandlers=this.loadingHandlers.filter(t=>t!==e)}}emit(e){for(let i of this.loadingHandlers)try{i(e)}catch(r){console.error("Loading handler failed",r)}let t={...e,stageName:this.stageName,stageIndex:this.stageIndex};e.type==="start"?$.emit("stage:loading:start",t):e.type==="progress"?$.emit("stage:loading:progress",t):e.type==="complete"&&$.emit("stage:loading:complete",t)}emitStart(e="Loading stage..."){this.emit({type:"start",message:e,progress:0})}emitProgress(e,t,i){let r=i>0?t/i:0;this.emit({type:"progress",message:e,progress:r,current:t,total:i})}emitComplete(e="Stage loaded"){this.emit({type:"complete",message:e,progress:1})}dispose(){this.loadingHandlers=[]}};var Le=class{scene=null;onEntityReady=null;pendingEntities=new Map;modelLoadedHandler=null;attach(e,t){this.scene=e,this.onEntityReady=t??null,this.modelLoadedHandler=i=>{this.handleModelLoaded(i.entityId,i.success)},E.on("entity:model:loaded",this.modelLoadedHandler)}observe(e){if(e.group||e.mesh){U(e.options)||(this.scene?.addEntityGroup(e),Z(e),L(e),this.onEntityReady?.(e));return}this.pendingEntities.set(e.uuid,e)}unobserve(e){this.pendingEntities.delete(e)}handleModelLoaded(e,t){let i=this.pendingEntities.get(e);if(!i||!t){this.pendingEntities.delete(e);return}this.scene?.addEntityGroup(i),Z(i),L(i),U(i.options)||this.onEntityReady?.(i),this.pendingEntities.delete(e)}dispose(){this.modelLoadedHandler&&(E.off("entity:model:loaded",this.modelLoadedHandler),this.modelLoadedHandler=null),this.pendingEntities.clear(),this.onEntityReady=null,this.scene=null}};import{StageBodyKind as Ai}from"@zylem/behaviors/core";var hn=200,Oe=class a{static EMPTY_BEHAVIOR_LINKS=[];children=[];childrenMap=new Map;debugMap=new Map;detachedMap=new Map;pendingEntities=[];pendingPromises=[];_isLoaded=!1;entityAddedHandlers=[];behaviorSystems=[];behaviorSystemByKey=new Map;registeredSystemKeys=new Set;behaviorEntityIndex=new Map;behaviorLinksByUuid=new Map;scene=null;world=null;renderStrategy=null;camera=null;wasmStage=null;loadingDelegate;entityModelDelegate;constructor(e,t){this.loadingDelegate=e,this.entityModelDelegate=t}get isLoaded(){return this._isLoaded}set isLoaded(e){this._isLoaded=e}attach(e){this.scene=e.scene,this.world=e.world,this.renderStrategy=e.renderStrategy,this.camera=e.camera,this.wasmStage=e.world.simulation.adapter}async spawnEntity(e){if(!this.scene||!this.world)return;if(e instanceof Q){e.create();for(let i of e.getChildren())i instanceof V&&await this.spawnEntity(i);e.nodeSetup({me:e,globals:g(),camera:this.camera}),this.addEntityToStage(e);return}let t=e.create();Dt(t),this.registerBehaviorLinks(t),this.ensureEnvironmentStatic(t),this.maybeAttachEntityPhysics(t);for(let i of e.getChildren())i instanceof V&&await this.spawnEntity(i);e.nodeSetup({me:e,globals:g(),camera:this.camera}),this.tryRegisterRenderStrategy(t),D(t)||this.scene.addEntityGroup(t),L(t),this.addEntityToStage(t),this.entityModelDelegate.observe(t),Mt(t)}handleLateModelReady(e){!this.world||!this.scene||!this.childrenMap.has(e.uuid)||(this.ensureEnvironmentStatic(e),this.maybeAttachEntityPhysics(e),this.tryRegisterRenderStrategy(e),D(e)||this.scene.addEntityGroup(e),L(e))}tryRegisterRenderStrategy(e){this.renderStrategy&&this.renderStrategy.register(e)}ensureEnvironmentStatic(e){if(G(e.options)!=="environment")return;let t=e.options.collision??{};t.static!==!0&&(console.warn(`category 'environment' forces static collision for entity '${e.name||e.uuid}'`),e.options.collision={...t,static:!0}),e.bodyDesc&&e.bodyDesc.kind!==Ai.Static&&(e.bodyDesc.kind=Ai.Static)}maybeAttachEntityPhysics(e){if(!(!this.world||e.physicsAttached||!e.colliderDesc)){if(e instanceof te){if(e.needsDeferredModelCollision())return;e.synchronizeRuntimeCollider()}this.world.addEntity(e)}}addEntityToStage(e){this.childrenMap.set(e.uuid,e),u.enabled&&this.debugMap.set(e.uuid,e);for(let t of this.entityAddedHandlers)try{t(e)}catch(i){console.error("onEntityAdded handler failed",i)}}removeEntityByUuid(e){return this.detachEntity(e)}detachEntity(e){if(!this.scene||!this.world)return!1;let t=this.world.collisionMap.get(e),i=this.childrenMap.get(e),r=t??i??this.debugMap.get(e);if(!r)return!1;let n=typeof r.getPose=="function"?r.getPose():null;return this.unregisterBehaviorLinks(r),this.entityModelDelegate.unobserve(e),D(r)&&this.renderStrategy?.unregister(r),this.world.destroyEntity(r),r.group?this.scene.scene.remove(r.group):r.mesh&&this.scene.scene.remove(r.mesh),this.childrenMap.delete(e),this.debugMap.delete(e),this.detachedMap.set(e,{entity:r,position:n?.position??null,rotation:n?.rotation??null}),this.evictOldestDetached(),E.emit("entity:destroyed",{entityId:e}),!0}restoreEntity(e){if(!this.scene||!this.world)return!1;let t=this.detachedMap.get(e);if(!t)return!1;this.detachedMap.delete(e);let{entity:i,position:r,rotation:n}=t;return i.bodyDesc&&(r&&(i.bodyDesc.position=[r.x,r.y,r.z]),n&&(i.bodyDesc.rotation=[n.x,n.y,n.z,n.w])),this.registerBehaviorLinks(i),this.maybeAttachEntityPhysics(i),this.tryRegisterRenderStrategy(i),D(i)||this.scene.addEntityGroup(i),Tt(i),_t(i),this.addEntityToStage(i),this.entityModelDelegate.observe(i),!0}isDetached(e){return this.detachedMap.has(e)}evictOldestDetached(){for(;this.detachedMap.size>hn;){let e=this.detachedMap.keys().next();if(e.done)return;let t=this.detachedMap.get(e.value);if(this.detachedMap.delete(e.value),!!t){try{t.entity.nodeDestroy?.({me:t.entity,globals:g()})}catch{}A(t.entity)}}}getEntityByName(e){for(let t of this.childrenMap.values())if(t.name===e)return t;return console.warn(`Entity ${e} not found`),null}buildEntityState(e){return e instanceof Rt?{...e.buildInfo()}:{uuid:e.uuid,name:e.name}}onEntityAdded(e,t){return this.entityAddedHandlers.push(e),t?.replayExisting&&this._isLoaded&&this.childrenMap.forEach(i=>{try{e(i)}catch(r){console.error("onEntityAdded replay failed",r)}}),()=>{this.entityAddedHandlers=this.entityAddedHandlers.filter(i=>i!==e)}}enqueue(...e){for(let t of e)if(t){if(T(t)){this.handleEntityImmediatelyOrQueue(t);continue}if(typeof t=="function"){try{let i=t();T(i)?this.handleEntityImmediatelyOrQueue(i):q(i)&&this.handlePromiseWithSpawnOnResolve(i)}catch(i){console.error("Error executing entity factory",i)}continue}q(t)&&this.handlePromiseWithSpawnOnResolve(t)}}handleEntityImmediatelyOrQueue(e){this._isLoaded?this.spawnEntity(e):this.children.push(e)}handlePromiseWithSpawnOnResolve(e){this._isLoaded?e.then(t=>this.spawnEntity(t)).catch(t=>console.error("Failed to build async entity",t)):this.pendingPromises.push(e)}yieldToEventLoop(){return new Promise(e=>{let t=new MessageChannel;t.port1.onmessage=()=>e(),t.port2.postMessage(void 0)})}async runEntityLoadGenerator(){let t=0;if(this.pendingEntities.length){let n=[...this.pendingEntities];this.pendingEntities=[],this.enqueue(...n)}let i=[...this.pendingPromises];this.pendingPromises=[];let r=this.children.length+i.length;for(let n of this.children)await this.spawnEntity(n),t++,this.loadingDelegate.emitProgress(`Loaded ${n.name||"unknown"}`,t,r),t%5===0&&await this.yieldToEventLoop();for(let n of i){try{let s=await n;s&&await this.spawnEntity(s)}catch(s){console.error("Failed to resolve pending stage entity",s)}t++,this.loadingDelegate.emitProgress("Loaded async entity",t,r),t%5===0&&await this.yieldToEventLoop()}t%5!==0&&await this.yieldToEventLoop()}registerSystem(e){if(!this.world||!this.scene)return;let t;typeof e=="function"?t=e({world:this.world,scene:this.scene,getBehaviorLinks:i=>this.behaviorEntityIndex.get(i)??a.EMPTY_BEHAVIOR_LINKS,createEntity:Ue,getGlobals:g}):t=e,this.behaviorSystems.push(t)}destroyAll(){for(let t of this.behaviorSystems)t.destroy?.();this.behaviorSystems.length=0,this.behaviorSystemByKey.clear(),this.registeredSystemKeys.clear(),this.behaviorEntityIndex.clear(),this.behaviorLinksByUuid.clear();let e=[];this.childrenMap.forEach(t=>{try{t.nodeDestroy({me:t,globals:g()})}catch{}A(t),e.push(t.uuid)}),this.detachedMap.forEach(({entity:t})=>{try{t.nodeDestroy?.({me:t,globals:g()})}catch{}A(t)}),this.detachedMap.clear(),this.childrenMap.clear(),this.debugMap.clear(),this.entityAddedHandlers=[];for(let t of e)E.emit("entity:destroyed",{entityId:t});this._isLoaded=!1,this.scene=null,this.world=null,this.renderStrategy=null,this.camera=null,this.wasmStage=null}registerBehaviorLinks(e){if(!this.world||!this.scene||typeof e?.getBehaviorRefs!="function")return;let t=e.getBehaviorRefs();if(!Array.isArray(t)||t.length===0)return;let i=[];for(let r of t){let n=r.descriptor.key,s={entity:e,ref:r};i.push(s);let o=this.behaviorEntityIndex.get(n);o||(o=new Set,this.behaviorEntityIndex.set(n,o)),o.add(s);let l=this.behaviorSystemByKey.get(n);if(!l&&!this.registeredSystemKeys.has(n)){let c=r.descriptor.systemFactory({world:this.world,scene:this.scene,wasmStage:this.wasmStage,getBehaviorLinks:d=>this.behaviorEntityIndex.get(d)??a.EMPTY_BEHAVIOR_LINKS,createEntity:Ue,getGlobals:g});l=c,this.behaviorSystems.push(c),this.behaviorSystemByKey.set(n,c),this.registeredSystemKeys.add(n)}l?.attach?.(s)}this.behaviorLinksByUuid.set(e.uuid,i)}unregisterBehaviorLinks(e){let t=this.behaviorLinksByUuid.get(e?.uuid);if(t){for(let i of t){let r=i.ref?.descriptor?.key;if(!r)continue;let n=this.behaviorEntityIndex.get(r);n&&(this.behaviorSystemByKey.get(r)?.detach?.(i),n.delete(i),n.size===0&&this.behaviorEntityIndex.delete(r))}this.behaviorLinksByUuid.delete(e.uuid)}}};var fn="Stage",Ae=class extends Se{type=fn;state={...Bt};gravity;world;scene;renderStrategy=null;debugDelegate=null;uuid;wrapperRef=null;camera;cameras=[];cameraRef=null;cameraManagerRef=null;rendererManager=null;cameraDelegate;loadingDelegate;entityModelDelegate;childUpdateParams={};entityDelegate;constructor(e=[]){super(),this.world=null,this.scene=null,this.uuid=gn(),this.cameraDelegate=new Re(this),this.loadingDelegate=new ke,this.entityModelDelegate=new Le,this.entityDelegate=new Oe(this.loadingDelegate,this.entityModelDelegate);let t=fi(e);this.camera=t.camera,this.cameras=t.cameras,this.entityDelegate.children=t.entities,t.asyncEntities.length&&this.entityDelegate.enqueue(...t.asyncEntities),this.state={...this.state,inputs:t.config.inputs,backgroundColor:t.config.backgroundColor,backgroundImage:t.config.backgroundImage,backgroundShader:t.config.backgroundShader,gravity:t.config.gravity,variables:t.config.variables,physicsRate:t.config.physicsRate,assetLoaders:t.config.assetLoaders,defaultLighting:t.config.defaultLighting,postProcessingEffects:t.config.postProcessingEffects,entities:[]},this.gravity=t.config.gravity??new zi(0,0,0)}setState(){let{backgroundColor:e,backgroundImage:t}=this.state,i=e instanceof Bi?e:new Bi(e);zt(i),Ft(t),It(this.state.variables??{})}resolveRenderer(e){return this.rendererManager?.renderer?this.rendererManager.renderer:e.renderer?e.renderer:null}async load(e,t,i){this.setState(),i&&(this.rendererManager=i),this.rendererManager&&(this.cameraManagerRef=this.cameraDelegate.buildCameraManager(t,...this.cameras));let r=this.cameraManagerRef?.primaryCamera??this.cameraDelegate.resolveCamera(t,this.camera);this.cameraRef=r,this.scene=new Ce(e,r,this.state);let n=this.gravity??new zi(0,0,0);if(this.world=await be.create(n,this.state.physicsRate),this.scene.setup(),this.cameraManagerRef&&this.rendererManager){await this.scene.setupCameraManager(this.scene.scene,this.cameraManagerRef,this.rendererManager);let o=this.cameraManagerRef.primaryCamera;o&&(this.rendererManager.setPostProcessingEffects(this.state.postProcessingEffects??[]),this.rendererManager.setupPostProcessing(this.scene.scene,o.camera)),this.rendererManager.startRenderLoop(()=>{this.cameraManagerRef?.render(this.scene.scene)})}else await this.scene.setupCamera(this.scene.scene,r);let s=this.resolveRenderer(r);await O.configureGLTFRuntime({renderer:s,...ye(this.state.assetLoaders?.gltf)}),this.entityModelDelegate.attach(this.scene,o=>this.entityDelegate.handleLateModelReady(o)),this.renderStrategy=new oe,this.renderStrategy.setScene(this.scene.scene),this.entityDelegate.attach({scene:this.scene,world:this.world,renderStrategy:this.renderStrategy,camera:r}),this.loadingDelegate.emitStart(),await this.entityDelegate.runEntityLoadGenerator(),this.entityDelegate.isLoaded=!0,this.loadingDelegate.emitComplete()}hasSetup=!1;_setup(e){if(!this.hasSetup){if(!this.scene||!this.world){this.logMissingEntities();return}this.debugDelegate=new _e(this),this.hasSetup=!0}}_update(e){let{delta:t}=e;if(!this.scene||!this.world){this.logMissingEntities();return}let i=this.world,r=this.scene;P("behaviorSystems",()=>{for(let n of this.entityDelegate.behaviorSystems)n.update(void 0,t)}),P("entityLoop",()=>{for(let n of this.entityDelegate.childrenMap.values()){let s=this.childUpdateParams;s.delta=e.delta,s.inputs=e.inputs,s.globals=e.globals,s.camera=e.camera,s.stage=e.stage,s.game=e.game,s.me=n,n.nodeUpdate(s);let o=n;o.transformStore&&Ut(o,o.transformStore),n.markedForRemoval&&this.entityDelegate.removeEntityByUuid(n.uuid)}}),P("worldUpdate",()=>{i.update(e)}),P("behaviorPostUpdate",()=>{for(let n of this.entityDelegate.behaviorSystems)n.postUpdate?.(void 0,t)}),P("syncRenderPoses",()=>{vi({_childrenMap:this.entityDelegate.childrenMap,_world:i})}),P("renderStrategy",()=>{this.renderStrategy?.update(i.interpolationAlpha)}),P("camera",()=>{this.cameraManagerRef?this.cameraManagerRef.update(t):this.cameraRef?.update(t)}),P("scene",()=>{r.update({delta:t})}),ai()}outOfLoop(){this.debugUpdate()}debugUpdate(){X()&&(je("debugUpdate"),this.debugDelegate?.update(),Ke())}_destroy(e){this.entityDelegate.destroyAll(),this.world?.destroy(),this.scene?.destroy(),this.debugDelegate?.dispose(),this.debugDelegate=null,this.entityModelDelegate.dispose(),this.renderStrategy?.dispose(),this.renderStrategy=null,this.rendererManager&&this.rendererManager.stopRenderLoop(),this.world=null,this.scene=null,this.cameraRef=null,this.cameraManagerRef=null,Vt(),A(this)}async spawnEntity(e){return this.entityDelegate.spawnEntity(e)}buildEntityState(e){return this.entityDelegate.buildEntityState(e)}onEntityAdded(e,t){return this.entityDelegate.onEntityAdded(e,t)}onLoading(e){return this.loadingDelegate.onLoading(e)}registerSystem(e){return this.entityDelegate.registerSystem(e),this}removeEntityByUuid(e){return this.entityDelegate.removeEntityByUuid(e)}getEntityByName(e){return this.entityDelegate.getEntityByName(e)}enqueue(...e){this.entityDelegate.enqueue(...e)}logMissingEntities(){console.warn("Zylem world or scene is null")}addCamera(e,t){return this.cameraManagerRef?this.cameraManagerRef.addCamera(e,t):(console.warn("ZylemStage: CameraManager not available. Ensure stage is loaded with a RendererManager."),null)}removeCamera(e){return this.cameraManagerRef?.removeCamera(e)??!1}setActiveCamera(e){return this.cameraManagerRef?.setActiveCamera(e)??!1}getCamera(e){return this.cameraManagerRef?.getCamera(e)??null}resize(e,t){this.scene&&this.scene.updateRenderer(e,t)}};import{proxy as yn}from"valtio/vanilla";import{Vector3 as bn}from"three";var vn={backgroundColor:re,backgroundImage:null,inputs:{p1:["gamepad-1","keyboard"],p2:["gamepad-2","keyboard"]},gravity:new bn(0,0,0),variables:{}},R=yn({...vn});function Fi(a){let e=Cn(),t={};return typeof a[0]=="object"&&(t=a.shift()??{}),[{...e,...t},...a]}function Cn(){return{backgroundColor:R.backgroundColor,backgroundImage:R.backgroundImage??null,inputs:R.inputs?{...R.inputs}:void 0,gravity:R.gravity,variables:R.variables?{...R.variables}:void 0}}var pt=class{wrappedStage;options=[];_pendingEntities=[];setupCallbacks=[];updateCallbacks=[];destroyCallbacks=[];pendingLoadingCallbacks=[];eventDelegate=new vt;inputConfig=null;onInputConfigChanged=null;constructor(e){this.options=e,this.wrappedStage=null;let t=this.options[0];O.prepareGLTFRuntime(ye(t?.assetLoaders?.gltf))}setInputConfiguration(...e){return this.inputConfig=bt(...e),this.onInputConfigChanged&&this.onInputConfigChanged(),this}async load(e,t,i){ne.entities=[];let r=[...this.options,...this._pendingEntities];this._pendingEntities=[],this.wrappedStage=new Ae(r),this.wrappedStage.wrapperRef=this,this.pendingLoadingCallbacks.forEach(c=>{this.wrappedStage.onLoading(c)}),this.pendingLoadingCallbacks=[];let n=t instanceof y?t.cameraRef:t;await this.wrappedStage.load(e,n,i);let s=null,o=!1,l=()=>{if(o=!1,!s?.length){s=null;return}let c=s;s=null,ne.entities=[...ne.entities,...c]};this.wrappedStage.onEntityAdded(c=>{if(U(c.options))return;let d=this.wrappedStage.buildEntityState(c);s||(s=[]),s.push(d),o||(o=!0,queueMicrotask(l))},{replayExisting:!0}),this.applyLifecycleCallbacks()}applyLifecycleCallbacks(){this.wrappedStage&&(this.setupCallbacks.length>0&&(this.wrappedStage.setup=e=>{let t={...e,stage:this};this.setupCallbacks.forEach(i=>i(t))}),this.updateCallbacks.length>0&&(this.wrappedStage.update=e=>{let t={...e,stage:this};this.updateCallbacks.forEach(i=>i(t))}),this.destroyCallbacks.length>0&&(this.wrappedStage.destroy=e=>{let t={...e,stage:this};this.destroyCallbacks.forEach(i=>i(t))}))}async addEntities(e){this._pendingEntities.push(...e),this.wrappedStage&&this.wrappedStage.enqueue(...e)}add(...e){this.addToBlueprints(...e),this.addToStage(...e)}addToBlueprints(...e){this.wrappedStage||this.options.push(...e)}addToStage(...e){this.wrappedStage&&this.wrappedStage.enqueue(...e)}start(e){!this.wrappedStage||this.wrappedStage.hasSetup||this.wrappedStage.nodeSetup(e)}onUpdate(...e){return this.updateCallbacks.push(...e),this.wrappedStage&&(this.wrappedStage.update=t=>{let i={...t,stage:this};this.updateCallbacks.forEach(r=>r(i))}),this}onSetup(...e){return this.setupCallbacks.push(...e),this.wrappedStage&&(this.wrappedStage.setup=t=>{let i={...t,stage:this};this.setupCallbacks.forEach(r=>r(i))}),this}onDestroy(...e){return this.destroyCallbacks.push(...e),this.wrappedStage&&(this.wrappedStage.destroy=t=>{let i={...t,stage:this};this.destroyCallbacks.forEach(r=>r(i))}),this}onLoading(e){return this.wrappedStage?this.wrappedStage.onLoading(e):(this.pendingLoadingCallbacks.push(e),()=>{this.pendingLoadingCallbacks=this.pendingLoadingCallbacks.filter(t=>t!==e)})}getEntityByName(e,t){return this.wrappedStage?.getEntityByName(e)}addCamera(e,t){let i=e instanceof y?e.cameraRef:e;return this.wrappedStage?.addCamera(i,t)??null}removeCamera(e){return e instanceof y?this.wrappedStage?.removeCamera(e.cameraRef)??!1:this.wrappedStage?.removeCamera(e)??!1}setActiveCamera(e){return e instanceof y?this.wrappedStage?.setActiveCamera(e.cameraRef)??!1:this.wrappedStage?.setActiveCamera(e)??!1}getCamera(e){return this.wrappedStage?.getCamera(e)??null}dispatch(e,t){this.eventDelegate.dispatch(e,t),E.emit(e,t)}listen(e,t){return this.eventDelegate.listen(e,t)}dispose(){this.eventDelegate.dispose()}};function Ol(...a){let e=Fi(a);return new pt([...e])}export{_n as a,ae as b,G as c,U as d,D as e,se as f,oe as g,jn as h,m as i,M as j,de as k,_ as l,B as m,j as n,z as o,ge as p,y as q,$a as r,as as s,mr as t,pt as u,Ol as v};