@zylem/game-lib 0.9.2 → 0.9.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -4,7 +4,7 @@ import { Scene, Color, Object3D, Vector3, BufferGeometry, Material, Group, Textu
4
4
  import { al as ZylemWorld, aj as EntityTypeMap } from './entity-type-map-CrsrKT8c.js';
5
5
  import { E as Entity, L as LifecycleFunction, S as StageEntity } from './entity-BIf_a4dl.js';
6
6
  import { G as GameEntity, a as GameEntityOptions } from './entity-XqvuWgPm.js';
7
- import { l as ZylemCamera, R as RendererManager, e as CameraPerspective, d as CameraContext, C as CameraPose, P as PerspectiveType, f as CameraBehavior, g as CameraAction, h as CameraPipelineState, V as Viewport, Z as ZylemPostEffect } from './zylem-camera-CYDtrVgi.js';
7
+ import { l as ZylemCamera, R as RendererManager, e as CameraPerspective, d as CameraContext, C as CameraPose, P as PerspectiveType, f as CameraBehavior, g as CameraAction, h as CameraPipelineState, V as Viewport, Z as ZylemPostEffect } from './zylem-camera-CO713zFl.js';
8
8
  import { d as ZylemShader } from './material-CxxAyJYp.js';
9
9
  import { a as SimulationBody } from './simulation-body-zQw-emOr.js';
10
10
  import { e as Vec3Input, b as Vec2Input, d as Vec3Components } from './vector-D3eDzvcA.js';
@@ -13,34 +13,57 @@ import { G as GameInputConfig } from './game-interfaces-vF5sRi1n.js';
13
13
  import { SwatchApplyResult, SceneOperationEntry, EntityApplySwatchPayload, SceneOperationPayload } from '@zylem/bridge';
14
14
  import { BehaviorSystem, BehaviorEntityLink, BehaviorRuntime, BehaviorSystemFactory, BehaviorRef } from '@zylem/behaviors/core';
15
15
 
16
+ /**
17
+ * Editor-view cameras exist only while an editor is attached.
18
+ *
19
+ * `GameBridge.connect()` runs for every game, so it is not the signal. The
20
+ * bridge marks the session attached when an editor subscribes, and every live
21
+ * camera manager creates or destroys its four view cameras from that flag.
22
+ */
23
+ interface EditorCameraHost {
24
+ ensureEditorCameras(): Promise<void>;
25
+ destroyEditorCameras(): void;
26
+ activateCameraById(id: string): boolean;
27
+ }
28
+
16
29
  /**
17
30
  * CameraManager orchestrates multiple cameras per stage.
18
31
  *
19
32
  * Responsibilities:
20
33
  * - Named camera registry (add/remove/get by name or reference)
21
34
  * - Active camera list management (determines which cameras render)
22
- * - Always-available debug camera with orbit controls
35
+ * - Editor view cameras (side, top, isometric, free), created only while an editor is attached
23
36
  * - Per-frame update of all active cameras' perspective controllers
24
37
  * - Coordinating rendering via RendererManager for all active viewports
25
38
  */
26
- declare class CameraManager {
39
+ declare class CameraManager implements EditorCameraHost {
27
40
  /** Named camera registry */
28
41
  private cameras;
29
42
  /** Currently active cameras, ordered by render layer (first = bottom) */
30
43
  private _activeCameras;
31
- /** Auto-created debug camera with orbit controls */
32
- private _debugCamera;
33
- /** Gameplay primary camera saved while the debug camera is active. */
34
- private _preDebugPrimary;
35
- /** Scene anchor at world origin for debug orbit when nothing is selected. */
36
- private _debugOrbitTargetAnchor;
44
+ /** Editor view cameras, keyed by `editor:*` id. */
45
+ private _editorCameras;
46
+ /** Which editor views freeze rotation. */
47
+ private _lockedEditorIds;
48
+ /** Game camera to restore when the editor releases the main view. */
49
+ private _rememberedGameCamera;
50
+ /**
51
+ * True while an editor view is the main camera. Game calls to
52
+ * {@link setActiveCamera} update {@link _rememberedGameCamera} and leave
53
+ * the view on screen.
54
+ */
55
+ private _editorViewLocked;
56
+ /** Game cameras whose orbit input was suspended for an editor view. */
57
+ private _suspendedOrbits;
58
+ /** In-flight creation, so a second attach does not build a second set. */
59
+ private _editorCamerasPromise;
37
60
  /** Reference to the shared renderer manager */
38
61
  private _rendererManager;
39
62
  /** Scene reference */
40
63
  private _sceneRef;
41
64
  /** Counter for auto-generated camera names */
42
65
  private _autoNameCounter;
43
- constructor();
66
+ private _unregisterEditorHost;
44
67
  /**
45
68
  * Get the list of currently active cameras.
46
69
  */
@@ -49,14 +72,10 @@ declare class CameraManager {
49
72
  * Get the primary active camera (first in the active list).
50
73
  */
51
74
  get primaryCamera(): ZylemCamera | null;
52
- /**
53
- * Get the debug camera.
54
- */
55
- get debugCamera(): ZylemCamera | null;
56
- /**
57
- * Gameplay primary camera that was active before debug mode was enabled.
58
- */
59
- get preDebugPrimary(): ZylemCamera | null;
75
+ /** True while side, top, isometric, or free is the main view. */
76
+ isEditorViewActive(): boolean;
77
+ /** True after the four editor views have been created. */
78
+ hasEditorCameras(): boolean;
60
79
  /**
61
80
  * Get all registered cameras.
62
81
  */
@@ -73,13 +92,15 @@ declare class CameraManager {
73
92
  addCamera(camera: ZylemCamera, name?: string): string;
74
93
  /**
75
94
  * Remove a camera by name or reference.
76
- * Cannot remove the debug camera via this method.
77
95
  */
78
96
  removeCamera(nameOrRef: string | ZylemCamera): boolean;
79
97
  /**
80
98
  * Set a camera as the primary active camera (replaces all active cameras
81
99
  * except additional viewport cameras).
82
100
  *
101
+ * While an editor view owns the main view, a game camera is remembered
102
+ * and the rendered camera does not change.
103
+ *
83
104
  * @param nameOrRef Camera name or reference to activate
84
105
  */
85
106
  setActiveCamera(nameOrRef: string | ZylemCamera): boolean;
@@ -97,19 +118,27 @@ declare class CameraManager {
97
118
  getCamera(name: string): ZylemCamera | null;
98
119
  /**
99
120
  * Setup all cameras with the given scene and renderer manager.
100
- * Also creates the debug camera.
121
+ * Editor view cameras are created here only when an editor is already attached.
101
122
  */
102
123
  setup(scene: Scene, rendererManager: RendererManager): Promise<void>;
103
124
  /**
104
- * Switch the primary viewport to the debug orbit camera, remembering the
105
- * previous primary so gameplay cameras (e.g. first-person) can be restored.
125
+ * Create side, top, isometric, and free cameras seeded from the current
126
+ * game camera. Does not change which camera is rendering.
127
+ */
128
+ ensureEditorCameras(): Promise<void>;
129
+ /**
130
+ * Restore the game camera when an editor view is showing, then destroy
131
+ * the four editor cameras.
106
132
  */
107
- activateDebugCamera(): boolean;
133
+ destroyEditorCameras(): void;
108
134
  /**
109
- * Restore the gameplay primary camera that was active before
110
- * {@link activateDebugCamera}.
135
+ * Switch the main view.
136
+ *
137
+ * `game` releases to the remembered game camera. Editor view ids show
138
+ * that view. Any other id activates a game-registered camera and clears
139
+ * the editor override.
111
140
  */
112
- deactivateDebugCamera(): boolean;
141
+ activateCameraById(id: string): boolean;
113
142
  /**
114
143
  * Update all active cameras' controllers.
115
144
  */
@@ -129,16 +158,19 @@ declare class CameraManager {
129
158
  * Dispose all cameras and cleanup.
130
159
  */
131
160
  dispose(): void;
132
- /**
133
- * Create the always-available debug camera with orbit controls.
134
- * Registered for lookup/activation, but not added to the active list.
135
- */
136
- private createDebugCamera;
137
- /**
138
- * Seed the debug camera orbit pose on first activation, framing the origin
139
- * or offsetting from the saved gameplay primary.
140
- */
141
- private seedDebugCameraPose;
161
+ private createEditorCameras;
162
+ private showEditorCamera;
163
+ private showGameCamera;
164
+ /** Enable orbit on the active editor view only. Inactive views keep their pose. */
165
+ private syncEditorOrbit;
166
+ /** Stop game-camera orbit controls from sharing the canvas with an editor view. */
167
+ private suspendOtherOrbits;
168
+ private restoreOrbitFor;
169
+ private gameCameraToRestore;
170
+ private cameraIsRegistered;
171
+ private isEditorCamera;
172
+ /** Replace the primary camera and keep picture-in-picture viewports. */
173
+ private commitActive;
142
174
  /**
143
175
  * Resolve a camera from a name or reference.
144
176
  */
@@ -879,8 +911,9 @@ interface SwatchApplyOutcome {
879
911
  * hover/select/delete/spawn, the `DebugEntityCursor` highlight and the
880
912
  * `PlacementGhost` — is live whenever a tool is armed, so the toolbar's buttons
881
913
  * work on their own. The debug layer — the wasm simulation's collider
882
- * wireframes and the orbit camera — is the part `debugState.enabled` gates, and
883
- * is torn down when it goes off while the delegate stays alive to re-activate.
914
+ * wireframes — is the part `debugState.enabled` gates, and is torn down when
915
+ * it goes off while the delegate stays alive to re-activate. Debug mode does
916
+ * not switch cameras; picking and gizmos use whichever camera is rendering.
884
917
  *
885
918
  * Centralizes all of this so `ZylemStage` doesn't have to know about
886
919
  * raycasting, DOM input, or debug rendering.
@@ -911,7 +944,6 @@ declare class StageDebugDelegate {
911
944
  private debugCursor;
912
945
  private placementGhost;
913
946
  private debugLines;
914
- private cameraDebugDelegate;
915
947
  private debugStateUnsubscribe;
916
948
  private focusContextUnregister;
917
949
  private entityResolverUnregister;
@@ -933,7 +965,7 @@ declare class StageDebugDelegate {
933
965
  * point. Without one the tool warns instead of silently doing nothing.
934
966
  */
935
967
  setAddEntityFactory(factory: AddEntityFactory | null): void;
936
- /** Camera used for debug orbit / raycasts (active primary, usually `__debug__`). */
968
+ /** Camera used for raycasts and gizmos: whichever one is rendering. */
937
969
  private getDebugViewCamera;
938
970
  private resolveEntity;
939
971
  /**
@@ -945,7 +977,6 @@ declare class StageDebugDelegate {
945
977
  private forEachSelectableEntity;
946
978
  /** Copy all stage children into debugMap so raycast/select tools work after enabling debug mid-session. */
947
979
  private populateDebugMap;
948
- private ensureCameraDebugDelegate;
949
980
  /**
950
981
  * Activate/deactivate only when `debugState.enabled` actually flips.
951
982
  * Hover and selection write to `debugState` every frame, and `activate()`
@@ -956,9 +987,9 @@ declare class StageDebugDelegate {
956
987
  /** Hand the transform tool its mode whenever the active tool changes. */
957
988
  private syncToolMode;
958
989
  private syncGrid;
959
- /** Initialize DOM listeners and switch rendering to the debug orbit camera. */
990
+ /** Initialize DOM listeners. The rendering camera stays whatever the editor selected. */
960
991
  private activate;
961
- /** Tear down visuals and restore the gameplay primary camera. */
992
+ /** Tear down visuals without changing which camera is rendering. */
962
993
  private deactivate;
963
994
  private rebindPostProcessing;
964
995
  /**
@@ -1,11 +1,11 @@
1
- import { G as Game, D as DeviceProfile } from './game-D8KTP3fD.js';
1
+ import { G as Game, D as DeviceProfile } from './game-DBNxY6mb.js';
2
2
  import { v as DebugTools } from './debug-state-Cg3f5FB6.js';
3
3
  import './base-node-life-cycle-BK9xebT9.js';
4
4
  import 'three';
5
5
  import './stage-transition-CmGpV4tc.js';
6
6
  import './game-interfaces-vF5sRi1n.js';
7
7
  import './base-node-idopiSw5.js';
8
- import './stage-CAPlk_cN.js';
8
+ import './stage-bVLyYnOQ.js';
9
9
  import './entity-type-map-CrsrKT8c.js';
10
10
  import './entity-XqvuWgPm.js';
11
11
  import '@zylem/behaviors/core';
@@ -20,7 +20,7 @@ import './selection-bounds-BKmSo9aG.js';
20
20
  import './entity-BIf_a4dl.js';
21
21
  import '@zylem/behaviors/particle-emitter';
22
22
  import 'three/addons/lines/webgpu/Line2.js';
23
- import './zylem-camera-CYDtrVgi.js';
23
+ import './zylem-camera-CO713zFl.js';
24
24
  import '@zylem/bridge';
25
25
  import './default-controls-CAKJ5zlo.js';
26
26
 
@@ -504,6 +504,17 @@ declare class ZylemCamera {
504
504
  * Disable user-configured orbital controls.
505
505
  */
506
506
  disableOrbitalControls(): void;
507
+ /**
508
+ * Turn on orbit for an editor view camera.
509
+ *
510
+ * Locked views keep pan and zoom and freeze the seeded angle. The free
511
+ * view can rotate. Controls stay allocated after this so a later visit
512
+ * keeps the panned pose; use {@link setOrbitInteractionEnabled} to ignore
513
+ * pointer input while another camera is showing.
514
+ */
515
+ armEditorOrbit(lockRotation: boolean): void;
516
+ /** Ignore pointer input without disposing orbit controls or their pose. */
517
+ disarmEditorOrbit(): void;
507
518
  /**
508
519
  * Whether user orbital controls are enabled.
509
520
  */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zylem/game-lib",
3
- "version": "0.9.2",
3
+ "version": "0.9.3",
4
4
  "type": "module",
5
5
  "description": "A powerful and easy-to-use framework for creating simple 3D digital interactive applications using TypeScript.",
6
6
  "license": "MIT",
@@ -116,7 +116,7 @@
116
116
  "@sinclair/typebox": "^0.34.52",
117
117
  "@types/howler": "^2.2.13",
118
118
  "@zylem/behaviors": "^0.8.8",
119
- "@zylem/bridge": "^0.9.3",
119
+ "@zylem/bridge": "^0.9.4",
120
120
  "comlink": "^4.4.2",
121
121
  "howler": "^2.2.4",
122
122
  "idb-keyval": "^6.2.6",
@@ -1 +0,0 @@
1
- import{GridHelper as O,Group as X}from"three";var R=3094855,V=4871528,q=20,_=class{group=new X;scene=null;fine=null;coarse=null;increment=0;constructor(){this.group.name="__zylem_construction_grid__",this.group.renderOrder=-1,this.group.visible=!1}addTo(t){this.scene!==t&&(this.scene=t,t.add(this.group))}setIncrement(t){t<=0||t===this.increment||(this.increment=t,this.rebuild())}setVisible(t){this.group.visible=t}get visible(){return this.group.visible}dispose(){this.clearHelpers(),this.scene?.remove(this.group),this.scene=null}rebuild(){this.clearHelpers();let t=q*2,i=Math.round(t/this.increment);i>0&&i<=400&&(this.fine=new O(t,i,R,R),this.fine.material.transparent=!0,this.fine.material.opacity=.35,this.fine.material.depthWrite=!1,this.group.add(this.fine)),this.coarse=new O(t,t,V,V),this.coarse.material.transparent=!0,this.coarse.material.opacity=.6,this.coarse.material.depthWrite=!1,this.group.add(this.coarse)}clearHelpers(){for(let t of[this.fine,this.coarse])t&&(this.group.remove(t),t.geometry.dispose(),t.material.dispose());this.fine=null,this.coarse=null}};import{BoxGeometry as y,ConeGeometry as W,CylinderGeometry as f,Group as d,Mesh as m,MeshBasicMaterial as D,PlaneGeometry as C,Quaternion as Q,Raycaster as Z,TorusGeometry as S,Vector3 as l}from"three";var H={x:16726867,y:5036364,z:3900150,xy:3900150,yz:16726867,xz:5036364,xyz:14540253},J=16765499,I=.16,h={x:new l(1,0,0),y:new l(0,1,0),z:new l(0,0,1)},z={xy:new l(0,0,1),yz:new l(1,0,0),xz:new l(0,1,0)},A=12,K=Math.sqrt(1-1/A),w=1/A;function U(n,t){return Math.abs(n.dot(t))>K}function M(n,t,i){let e=k.copy(n.origin).sub(t),s=n.direction.dot(i),o=1-s*s;return o<1/A?null:(e.dot(i)-s*e.dot(n.direction))/o}function x(n,t,i,e){let s=i.dot(n.direction);if(Math.abs(s)<w)return null;let o=k.copy(t).sub(n.origin).dot(i)/s;return o<0?null:e.copy(n.direction).multiplyScalar(o).add(n.origin)}var k=new l,G=new l,Y=new l,j=new l,T=new Q,B=class{root=new d;scene=null;modeGroups={translate:new d,rotate:new d,scale:new d};handles={translate:[],rotate:[],scale:[]};materials=[];geometries=[];mode="translate";highlighted=null;drag=null;raycaster=new Z;constructor(){this.root.name="__zylem_transform_gizmo__",this.root.renderOrder=1e3,this.root.visible=!1,this.buildTranslate(),this.buildRotate(),this.buildScale();for(let t of Object.keys(this.modeGroups))this.root.add(this.modeGroups[t]);this.applyModeVisibility()}addTo(t){this.scene!==t&&(this.scene=t,t.add(this.root))}removeFromScene(){this.scene&&(this.scene.remove(this.root),this.scene=null)}dispose(){this.removeFromScene();for(let t of this.geometries)t.dispose();for(let t of this.materials)t.dispose();this.geometries=[],this.materials=[]}setMode(t){this.mode!==t&&(this.mode=t,this.applyModeVisibility())}getMode(){return this.mode}show(t){this.root.position.copy(t),this.root.visible=!0}hide(){this.root.visible=!1,this.setHighlight(null)}get visible(){return this.root.visible}get pivot(){return this.root.position}update(t){if(!this.root.visible)return;let i;if(t.isPerspectiveCamera){let e=t;j.setFromMatrixPosition(e.matrixWorld),i=2*j.distanceTo(this.root.position)*Math.tan(e.fov*Math.PI/360)*I}else if(t.isOrthographicCamera){let e=t;i=(e.top-e.bottom)/(e.zoom||1)*I}else i=1;this.root.scale.setScalar(Math.max(i,1e-4))}pick(t){if(!this.root.visible)return null;this.raycaster.set(t.origin,t.direction);let i=this.handles[this.mode].filter(s=>this.isHandleDraggable(s.axis,t)).map(s=>s.picker),e=this.raycaster.intersectObjects(i,!1);return e.length?e[0].object.userData.gizmoAxis??null:null}isHandleDraggable(t,i){if(t==="xyz")return!0;if(this.isPlaneAxis(t))return Math.abs(i.direction.dot(z[t]))>=w;let e=h[t];return this.mode==="rotate"?Math.abs(i.direction.dot(e))>=w:!U(i.direction,e)}setHighlight(t){if(this.highlighted!==t){this.highlighted=t;for(let i of Object.keys(this.handles))for(let e of this.handles[i]){let s=e.axis===t?J:H[e.axis];for(let o of e.visuals)o.material.color.setHex(s)}}}beginDrag(t,i,e){let s=this.root.position.clone(),o={axis:t,mode:this.mode,pivot:s,startAxisValue:0,startPoint:new l,startAngle:0,startRadius:0};if(t==="xyz"){let r=this.cameraPlaneRadius(i,s,e);if(r===null||r<1e-4)return!1;o.startRadius=r}else if(this.isPlaneAxis(t)){let r=z[t];if(!x(i,s,r,o.startPoint))return!1}else if(this.mode==="rotate"){let r=h[t],a=this.angleOnPlane(i,s,r);if(a===null)return!1;o.startAngle=a}else{let r=M(i,s,h[t]);if(r===null||(o.startAxisValue=r,this.mode==="scale"&&Math.abs(r)<1e-4))return!1}return this.drag=o,this.setHighlight(t),!0}updateDrag(t,i){let e=this.drag;if(!e)return null;if(e.mode==="rotate"){let r=h[e.axis]??h.y,a=this.angleOnPlane(t,e.pivot,r);return a===null?null:{kind:"rotate",axis:r.clone(),angle:a-e.startAngle}}if(e.mode==="scale"){if(e.axis==="xyz"){let u=this.cameraPlaneRadius(t,e.pivot,i);if(u===null)return null;let p=u/e.startRadius;return{kind:"scale",factor:new l(p,p,p)}}let r=M(t,e.pivot,h[e.axis]);if(r===null)return null;let a=r/e.startAxisValue,c=new l(1,1,1);return c[e.axis]=a,{kind:"scale",factor:c}}if(this.isPlaneAxis(e.axis)){let r=z[e.axis],a=x(t,e.pivot,r,G);return a?{kind:"translate",offset:a.clone().sub(e.startPoint)}:null}let s=h[e.axis],o=M(t,e.pivot,s);return o===null?null:{kind:"translate",offset:s.clone().multiplyScalar(o-e.startAxisValue)}}endDrag(){this.drag=null,this.setHighlight(null)}get isDragging(){return this.drag!==null}get draggingAxis(){return this.drag?.axis??null}isPlaneAxis(t){return t==="xy"||t==="yz"||t==="xz"}angleOnPlane(t,i,e){let s=x(t,i,e,G);if(!s)return null;let o=Y.copy(s).sub(i);if(o.lengthSq()<1e-8)return null;let r=Math.abs(e.y)>.9?h.x:h.y,a=k.copy(r).cross(e).normalize(),c=new l().copy(e).cross(a);return Math.atan2(o.dot(c),o.dot(a))}cameraPlaneRadius(t,i,e){T.setFromRotationMatrix(e.matrixWorld);let s=new l(0,0,1).applyQuaternion(T),o=x(t,i,s,G);return o?o.distanceTo(i):null}applyModeVisibility(){for(let t of Object.keys(this.modeGroups))this.modeGroups[t].visible=t===this.mode}makeMaterial(t,i){let e=new D({color:H[t],transparent:!0,opacity:i,depthTest:!1,depthWrite:!1,toneMapped:!1});return this.materials.push(e),e}track(t){return this.geometries.push(t),t}makePicker(t,i,e){let s=new D({visible:!1});this.materials.push(s);let o=new m(this.track(i),s);return o.visible=!1,o.userData.gizmoAxis=t,e(o),o}orientAlongAxis(t,i){i==="x"&&(t.rotation.z=-Math.PI/2),i==="z"&&(t.rotation.x=Math.PI/2)}buildTranslate(){let t=this.modeGroups.translate;for(let i of["x","y","z"]){let e=this.makeMaterial(i,1),s=new m(this.track(new f(.012,.012,.7,8)),e);s.position.y=.35;let o=new m(this.track(new W(.045,.16,12)),e);o.position.y=.78;let r=new d;r.add(s,o),this.orientAlongAxis(r,i);let a=this.makePicker(i,new f(.1,.1,.9,6),u=>{u.position.y=.45}),c=new d;c.add(a),this.orientAlongAxis(c,i),t.add(r,c),this.handles.translate.push({axis:i,visuals:[s,o],picker:a})}for(let i of["xy","yz","xz"]){let e=this.makeMaterial(i,.35),s=new m(this.track(new C(.22,.22)),e);this.positionPlaneHandle(s,i);let o=this.makePicker(i,new C(.22,.22),r=>{this.positionPlaneHandle(r,i)});t.add(s,o),this.handles.translate.push({axis:i,visuals:[s],picker:o})}}positionPlaneHandle(t,i){i==="xy"?t.position.set(.28,.28,0):i==="yz"?(t.position.set(0,.28,.28),t.rotation.y=Math.PI/2):(t.position.set(.28,0,.28),t.rotation.x=-Math.PI/2)}buildRotate(){let t=this.modeGroups.rotate;for(let i of["x","y","z"]){let e=this.makeMaterial(i,1),s=new m(this.track(new S(.68,.01,6,64)),e);this.orientRing(s,i);let o=this.makePicker(i,new S(.68,.08,4,24),r=>this.orientRing(r,i));t.add(s,o),this.handles.rotate.push({axis:i,visuals:[s],picker:o})}}orientRing(t,i){i==="x"&&(t.rotation.y=Math.PI/2),i==="y"&&(t.rotation.x=Math.PI/2)}buildScale(){let t=this.modeGroups.scale;for(let o of["x","y","z"]){let r=this.makeMaterial(o,1),a=new m(this.track(new f(.012,.012,.7,8)),r);a.position.y=.35;let c=new m(this.track(new y(.09,.09,.09)),r);c.position.y=.74;let u=new d;u.add(a,c),this.orientAlongAxis(u,o);let p=this.makePicker(o,new f(.1,.1,.85,6),F=>{F.position.y=.43}),b=new d;b.add(p),this.orientAlongAxis(b,o),t.add(u,b),this.handles.scale.push({axis:o,visuals:[a,c],picker:p})}let i=this.makeMaterial("xyz",.9),e=new m(this.track(new y(.13,.13,.13)),i),s=this.makePicker("xyz",new y(.22,.22,.22),()=>{});t.add(e,s),this.handles.scale.push({axis:"xyz",visuals:[e],picker:s})}};import{Box3 as $,PerspectiveCamera as tt,Vector3 as v}from"three";var P=new $,g=new v,E=new v,et=new v;function N(n){P.setFromObject(n),P.getSize(g),P.getCenter(E);let t=Math.max(g.x,1e-4),i=Math.max(g.y,1e-4),e=Math.max(g.z,1e-4),s=Math.max(t,i,e);return{width:t,height:i,depth:e,center:E.clone(),maxDim:s}}function L(n,t,i=1.35){let e=t.fov*(Math.PI/180),s=n/(2*Math.tan(e/2))*i;return Math.max(s,.5)}function ct(n,t,i=1.35){let e=N(n),s=L(e.maxDim,t,i);return t.position.copy(e.center).add(new v(s,s,s)),t.lookAt(e.center),t.near=Math.max(s/100,.01),t.far=Math.max(s*20,100),t.updateProjectionMatrix(),e}function ht(n,t,i,e=1.5){let s=N(n),o=et.copy(i);o.lengthSq()<1e-8&&o.set(1,1,1),o.normalize();let r=s.maxDim*e;return t instanceof tt&&(r=L(s.maxDim,t,e),t.near=Math.max(r/100,.01),t.far=Math.max(r*20,100),t.updateProjectionMatrix()),t.position.copy(s.center).addScaledVector(o,r),t.lookAt(s.center),s}export{ct as a,ht as b,_ as c,M as d,x as e,B as f};
@@ -1 +0,0 @@
1
- import{b as Ht,c as mi,f as gi}from"./chunk-BCFFS3FP.js";import{c as de,j as pe}from"./chunk-2HSR5XDQ.js";import{a as qt,c as lt,j as $t,l as U}from"./chunk-G5IJBJ4E.js";import{a as Kt,c as ot,d as at,e as Qt,f as ce,g as Yt}from"./chunk-BQRMYLYD.js";import{A as le,b as rt,d as u,e as Ft,i as oe,k as ae,o as nt,q as Gt,s as Zt,t as Nt,u as B,y as Ut,z as st}from"./chunk-GPCSX3M6.js";import{a as me,b as ai}from"./chunk-WBQ5TNRZ.js";import{b as he,d as li}from"./chunk-YQS7CGXE.js";import{a as H,k as ti,l as ii,m as ri,n as ni,o as V,p as si,q as j,t as oi,u as dt}from"./chunk-KP6DLLJO.js";import{a as ct,b as Jt,g as z,h as ue,i as ei}from"./chunk-6FGXC4T6.js";import{a as Wt,b as M}from"./chunk-AIQ6IVT5.js";import{g as W}from"./chunk-UUOPT2N4.js";import{a as ge,b as ci,c as fe,d as di,e as ui,f as pi,g as hi,m as I}from"./chunk-D2PATZCC.js";import{c as se,d as it,j as v}from"./chunk-4QLJUQSJ.js";import{c as P,i as Xt,j as h}from"./chunk-7WRQ2UAN.js";import{a as fi}from"./chunk-BH53MBAZ.js";import{l as jt}from"./chunk-UG22Z42P.js";import{Vector2 as Si,RenderTarget as Rr,HalfFloatType as _r}from"three";import{WebGPURenderer as kr,RenderPipeline as Lr}from"three/webgpu";import{pass as Ar,renderOutput as Pi,screenCoordinate as Or,vec2 as ut,vec4 as Mi,fract as wi,sin as Ei,dot as xi,texture as Br,uniform as zr}from"three/tsl";import{setConsoleFunction as Tr,getConsoleFunction as Dr}from"three";var yi="THREE.Abstract function.",vi=!1,bi=!1;function Ci(){if(vi)return;vi=!0;let s=Dr();Tr((e,t,...i)=>{if(e==="warn"&&t===yi){bi||(bi=!0,console.warn(`${yi} (suppressing further per-frame repeats; a WebGPU node is scheduled for updates without an update() implementation)`));return}if(s){s(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 Ti={x:0,y:0,width:1,height:1},Vr=1/20;async function Is(){if(!("gpu"in navigator))return!1;try{return await navigator.gpu.requestAdapter()!==null}catch{return!1}}var ye=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 Si(window.innerWidth,window.innerHeight)}get initialized(){return this._initialized}get isWebGPU(){return!0}async initRenderer(){this._initialized||(Ci(),this.renderer=new kr({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 Lr(this.renderer),r=Ar(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 o=Pi(n),a=this._transition;if(a)try{o=Mi(a.resolved.shader({fromNode:a.fromNode,toNode:o,progress:a.progressUniform})),a.composed=!0}catch(l){console.error("RendererManager: stage transition shader failed, skipping.",l)}i.outputNode=o.add(Fr()),this.postProcessing=i}rebindPostProcessingCamera(e){!this.postProcessing||!this._postSceneRef||this.setupPostProcessing(this._postSceneRef,e)}get transitionActive(){return this._transition!==null}beginSnapshotTransition(e,t,i){this.finishTransition();let r=new Si;this.renderer.getDrawingBufferSize(r);let n=new Rr(Math.max(1,r.x),Math.max(1,r.y),{type:_r}),o=this.renderer.getRenderTarget();try{this.renderer.setScissorTest(!1),this.renderer.setRenderTarget(n),this.renderer.render(t,i)}catch(a){console.error("RendererManager: failed to capture transition snapshot.",a)}finally{this.renderer.setRenderTarget(o)}this._transition={resolved:e,progressUniform:zr(0),fromNode:Pi(Br(n.texture)),elapsed:0,snapshotTarget:n,composed:!1}}beginInStageTransition(e,t,i){this._initialized&&(this.beginSnapshotTransition(e,t,i),this.setupPostProcessing(t,i))}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+=Math.min(e,Vr);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,o=this.screenResolution.y,a=Math.floor(r.x*n),l=Math.floor(r.y*o),c=Math.floor(r.width*n),d=Math.floor(r.height*o);this.renderer.setViewport(a,l,c,d),this.renderer.setScissor(a,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&&Ir(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 Ir(s){return s.x===0&&s.y===0&&s.width===1&&s.height===1}function Fr(){let s=Or.xy,e=wi(Ei(xi(s,ut(12.9898,78.233))).mul(43758.5453)),t=wi(Ei(xi(s.add(ut(13,7)),ut(12.9898,78.233))).mul(43758.5453)),i=e.sub(t).mul(1/255);return Mi(i,i,i,0)}function q(s){return s?.category??"none"}function K(s){let e=q(s);return e==="environment"||e==="pack"}function _(s){return s.isInstanced===!0||s.isBundled===!0}import{BundleGroup as Gr}from"three/webgpu";var ve=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 o=this.getOrCreateBundle(r);return n.matrixAutoUpdate=!0,n.userData.zylemEntityUuid=e.uuid,n.parent&&n.parent.remove(n),o.add(n),o.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 Gr,t.name=`bundle:${e}`,t.static=!0,this.bundles.set(e,t),this.scene&&this.scene.add(t),t)}};import{InstancedMesh as Di,Matrix4 as Q,Vector3 as Ri,Quaternion as Zr}from"three";var Y=class s{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}:${ct(e.dimensions)}`,mat:e.materialPath||"none",shader:e.shaderType||"standard",color:e.colorHex??16777215};return Jt(ct(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 s.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 o;return n.freeIndices.length>0?o=n.freeIndices.pop():(o=n.entities.length,o>=n.capacity&&this.growPack(n),n.entities.push(null)),n.entities[o]=e,n.entityMap.set(e.uuid,o),this.entityToPack.set(e.uuid,r),n.instancedMesh.count=Math.max(n.instancedMesh.count,o+1),n.activeIndices.push(o),n.dirtyIndices.add(o),o}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 a=i.activeIndices.pop();n<i.activeIndices.length&&(i.activeIndices[n]=a)}i.dirtyIndices.delete(r);let o=new Q;o.makeScale(0,0,0),i.instancedMesh.setMatrixAt(r,o),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 Q,i=new Ri,r=new Zr,n=new Ri(1,1,1);for(let o of this.packs.values()){if(o.activeIndices.length===0)continue;let a=!1;for(let l of o.activeIndices){let c=o.entities[l];if(!c)continue;if(ti(c)){t.makeScale(0,0,0),o.instancedMesh.setMatrixAt(l,t),a=!0;continue}let d=o.dirtyIndices.has(l),p=!!c.body;if(!(!d&&!p)){if(!d&&p){let m=c.body;if(typeof m.isRenderSleeping=="function"&&m.isRenderSleeping())continue}this.updateInstanceMatrix(o,l,t,i,r,n,e),a=!0}}o.dirtyIndices.clear(),a&&(o.instancedMesh.instanceMatrix.needsUpdate=!0)}}updateInstanceMatrix(e,t,i,r,n,o,a){let l=e.entities[t];if(l){if(l.body){let c=l.body;if(typeof c.writeRenderPose=="function")c.writeRenderPose(a,r,n);else{let d=me(l.body,a);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,o)}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=s.DEFAULT_CAPACITY,n=new Di(t,i,r);n.count=0,n.frustumCulled=!1;let o=new Q().makeScale(0,0,0);for(let l=0;l<r;l++)n.setMatrixAt(l,o);n.instanceMatrix.needsUpdate=!0;let a={key:e,instancedMesh:n,geometry:t,material:i,entityMap:new Map,entities:[],freeIndices:[],activeIndices:[],dirtyIndices:new Set,capacity:r};return this.packs.set(e,a),this.scene&&this.scene.add(n),a}growPack(e){let t=e.capacity*s.GROWTH_FACTOR,i=new Di(e.geometry,e.material,t);i.count=e.instancedMesh.count,i.frustumCulled=!1;let r=new Q;for(let o=0;o<e.capacity;o++)e.instancedMesh.getMatrixAt(o,r),i.setMatrixAt(o,r);let n=new Q().makeScale(0,0,0);for(let o=e.capacity;o<t;o++)i.setMatrixAt(o,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 be=class{bundles=new ve;instances=new Y;setScene(e){this.bundles.setScene(e),this.instances.setScene(e)}register(e){let t=q(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=Y.generateEntityPackKey(e);if(t==="pack"){let o=this.instances.register(e,i,r,n);return o<0?!1:(e.packKey=n,e.instanceId=o,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 Ce=!1,w={},_i=0,ki=0,$=null;function Li(){return typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()}function pt(){return Ce?!0:(typeof globalThis<"u"&&globalThis.__ZYLEM_PROFILE_STAGE__===!0&&(Ce=!0),Ce)}function to(s){Ce=s,typeof globalThis<"u"&&(globalThis.__ZYLEM_PROFILE_STAGE__=s)}function ht(s){pt()&&($=s,ki=Li())}function mt(){if(!pt()||$===null)return;let s=Li()-ki;w[$]=(w[$]??0)+s,$=null}function Ai(){if(!pt()||(_i++,_i%60!==0))return;let s=Object.values(w).reduce((t,i)=>t+(i??0),0),e=Object.keys(w).sort((t,i)=>(w[i]??0)-(w[t]??0)).map(t=>{let i=w[t]??0,r=s>0?(i/s*100).toFixed(1):"0.0";return`${t}=${i.toFixed(2)}ms (${r}%)`});console.info(`[ZylemStage profile] avg over 60 frames (${s.toFixed(2)}ms/frame): ${e.join(", ")}`);for(let t of Object.keys(w))w[t]=0}function E(s,e){ht(s);try{return e()}finally{mt()}}var y={FirstPerson:"first-person",ThirdPerson:"third-person",SecondPerson:"second-person",Isometric:"isometric",Flat2D:"flat-2d",Fixed2D:"fixed-2d",TopDown:"top-down"};function gt(s){switch(s){case y.Isometric:case y.TopDown:case y.Flat2D:case y.Fixed2D:return"orthographic";default:return"perspective"}}import{Vector3 as Nr,Quaternion as Ur,MathUtils as ft}from"three";function Se(){return{position:new Nr(0,0,10),rotation:new Ur,fov:75,zoom:1,near:.1,far:1e3}}function k(s){return{position:s.position.clone(),rotation:s.rotation.clone(),fov:s.fov,zoom:s.zoom,near:s.near,far:s.far,lookAt:s.lookAt?.clone()}}function Oi(s,e){let t=k(s);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 Bi(s,e,t,i){let r=1-Math.pow(1-ft.clamp(t,0,1),i*60),n=k(s);return n.position.lerp(e.position,r),n.rotation.slerp(e.rotation,r),e.fov!=null&&n.fov!=null&&(n.fov=ft.lerp(n.fov,e.fov,r)),e.zoom!=null&&n.zoom!=null&&(n.zoom=ft.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 Pe=class{perspective=null;behaviors=new Map;actions=[];_desiredPose=Se();_finalPose=Se();_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):Se(),i=this.getSortedBehaviors();for(let r of i)r.enabled!==!1&&(t=r.update(e,t));this._desiredPose=k(t);for(let r=this.actions.length-1;r>=0;r--){let n=this.actions[r],o=n.update(e);t=Oi(t,o),n.isDone(e)&&this.actions.splice(r,1)}return this._initialized?this._finalPose=Bi(this._finalPose,t,this.damping,e.dt):(this._finalPose=k(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?k(this._desiredPose):null,finalPose:this._finalPose?k(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 T,Quaternion as we}from"three";var Hr={distance:8,height:5,shoulderOffset:0,targetKey:"primary",fov:75,paddingFactor:1.5,minDistance:5,trailDelay:.1,trailBufferSize:120},F=class{id="third-person";projection="perspective";defaults={damping:.12};opts;initialPosition;initialLookAt;_trailBuffers=new Map;constructor(e){let{initialPosition:t,initialLookAt:i,...r}=e??{};this.opts={...Hr,...r},this.initialPosition=t?h(t,P):void 0,this.initialLookAt=i?h(i,P):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 we,fov:this.opts.fov,zoom:1,near:.1,far:1e3,lookAt:this.initialLookAt?.clone()??new T(0,0,0)}:{position:new T(this.opts.shoulderOffset,this.opts.height,this.opts.distance),rotation:new we,fov:this.opts.fov,zoom:1,near:.1,far:1e3,lookAt:new T(0,0,0)}}singleTargetPose(e,t,i){let r=this.getTrailedPosition(i,e,t.time);return{position:new T(r.x+this.opts.shoulderOffset,r.y+this.opts.height,r.z+this.opts.distance),rotation:new we,fov:this.opts.fov,zoom:1,near:.1,far:1e3,lookAt:r.clone()}}multiTargetPose(e){let i=Object.entries(e.targets).map(([p,m])=>this.getTrailedPosition(p,m.position,e.time)),r=new T;for(let p of i)r.add(p);r.divideScalar(i.length);let n=0;for(let p of i){let m=r.distanceTo(p);m>n&&(n=m)}let o=Math.max(n*this.opts.paddingFactor,this.opts.minDistance),a=new T(this.opts.shoulderOffset,this.opts.height,this.opts.distance),l=a.length(),c=l>0?a.clone().normalize():new T(0,.5,1).normalize(),d=r.clone().add(c.multiplyScalar(o));if(l>0){let p=this.opts.height/l;d.y=r.y+o*p}return{position:d,rotation:new we,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 o=i-r-.05;for(;n.length>1&&n[0].time<o;)n.shift();n.length>this.opts.trailBufferSize&&n.splice(0,n.length-this.opts.trailBufferSize);let a=i-r;if(n[0].time>=a)return n[0].pos.clone();for(let l=1;l<n.length;l++){let c=n[l-1],d=n[l];if(c.time<=a&&a<=d.time){let p=d.time-c.time,m=p>1e-6?(a-c.time)/p:0;return new T().lerpVectors(c.pos,d.pos,m)}}return n[n.length-1].pos.clone()}};import{Vector3 as zi,Quaternion as jr}from"three";var Vi={position:{x:0,y:0,z:10},zoom:10},G=class{id="fixed-2d";projection="orthographic";defaults={damping:1};opts;constructor(e){this.opts={...Vi,...e,position:h(e?.position,Vi.position)}}getBasePose(e){return{position:new zi(this.opts.position.x,this.opts.position.y,this.opts.position.z),rotation:new jr,zoom:this.opts.zoom,near:1,far:1e3,lookAt:new zi(this.opts.position.x,this.opts.position.y,0)}}};import{Vector3 as yt,Quaternion as vt,Euler as Gi,MathUtils as b}from"three";var Wr={eyeHeight:1.7,defaultFov:75,pitchLimit:Math.PI/2-.01,lookAtLerpSpeed:5,fovLerpSpeed:8,targetKey:"primary",verticalSmoothing:1},X=class{id="first-person";projection="perspective";defaults={damping:1};opts;initialPosition;initialLookAt;_yaw=0;_pitch=0;_currentFov;_targetFov;_lookAtTarget=null;_lookAtLerpSpeed;_currentRotation=new vt;_rotationInitialized=!1;_smoothedY=null;constructor(e){let{initialPosition:t,initialLookAt:i,...r}=e??{};this.opts={...Wr,...r},this.initialPosition=t?h(t,P):void 0,this.initialLookAt=i?h(i,P):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=b.clamp(this._pitch+t,-this.opts.pitchLimit,this.opts.pitchLimit)}setLook(e,t){this._yaw=e,this._pitch=b.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 yt(t.position.x,r,t.position.z)}return this.initialPosition?this.initialPosition.clone():new yt(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=b.clamp(this.opts.verticalSmoothing,0,1),r=1-Math.pow(1-i,t*60);return this._smoothedY=b.lerp(this._smoothedY,e,r),this._smoothedY}computeRotation(e,t){let i=new vt().setFromEuler(new Gi(this._pitch,this._yaw,0,"YXZ"));if(this._rotationInitialized||(this._currentRotation.copy(i),this._rotationInitialized=!0),this._lookAtTarget){let r=Ii.copy(this._lookAtTarget).sub(e);if(r.lengthSq()>1e-4){r.normalize();let n=Math.atan2(-r.x,-r.z),o=Math.asin(b.clamp(r.y,-1,1)),a=qr.setFromEuler(Fi.set(o,n,0,"YXZ")),l=1-Math.pow(1-Math.min(this._lookAtLerpSpeed*t,1),1);return this._currentRotation.slerp(a,b.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 b.lerp(this._currentFov,this._targetFov,b.clamp(t,0,1))}deriveYawPitchFromLookAt(e,t){let i=Ii.copy(t).sub(e).normalize();this._yaw=Math.atan2(-i.x,-i.z),this._pitch=Math.asin(b.clamp(i.y,-1,1))}deriveYawPitchFromQuaternion(e){let t=Fi.setFromQuaternion(e,"YXZ");this._yaw=t.y,this._pitch=b.clamp(t.x,-this.opts.pitchLimit,this.opts.pitchLimit)}},Ii=new yt,qr=new vt,Fi=new Gi;import{Quaternion as Kr,Vector3 as bt}from"three";var Qr={distance:10,zoom:10,targetKey:"primary"},Zi=new bt(1,1,1).normalize(),J=class{id="isometric";projection="orthographic";defaults={damping:1};opts;initialPosition;initialLookAt;constructor(e){let{initialPosition:t,initialLookAt:i,...r}=e??{};this.opts={...Qr,...r},this.initialPosition=t?h(t):void 0,this.initialLookAt=i?h(i):void 0}getBasePose(e){let t=e.targets[this.opts.targetKey];if(!t)return this.staticPose();let i=t.position.clone(),r=i.clone().addScaledVector(Zi,this.opts.distance);return this.pose(r,i)}staticPose(){return this.initialPosition?this.pose(this.initialPosition.clone(),this.initialLookAt?.clone()??new bt(0,0,0)):this.pose(Zi.clone().multiplyScalar(this.opts.distance),new bt(0,0,0))}pose(e,t){return{position:e,rotation:new Kr,zoom:this.opts.zoom,near:1,far:1e3,lookAt:t}}};import{Quaternion as Yr,Vector3 as Ee}from"three";var $r={height:10,zoom:10,targetKey:"primary"},ee=class{id="top-down";projection="orthographic";defaults={damping:1};opts;initialPosition;initialLookAt;constructor(e){let{initialPosition:t,initialLookAt:i,...r}=e??{};this.opts={...$r,...r},this.initialPosition=t?h(t):void 0,this.initialLookAt=i?h(i):void 0}getBasePose(e){let t=e.targets[this.opts.targetKey];if(!t)return this.staticPose();let i=t.position.clone();return this.pose(new Ee(i.x,i.y+this.opts.height,i.z),i)}staticPose(){if(this.initialPosition){let e=this.initialLookAt?.clone()??new Ee(this.initialPosition.x,this.initialPosition.y-this.opts.height,this.initialPosition.z);return this.pose(this.initialPosition.clone(),e)}return this.pose(new Ee(0,this.opts.height,0),new Ee(0,0,0))}pose(e,t){return{position:e,rotation:new Yr,zoom:this.opts.zoom,near:1,far:1e3,lookAt:t}}};import{Quaternion as Ni,Vector3 as xe}from"three";var Xr={anchorKey:"anchor",subjectKey:"primary",eyeHeight:1.7,fov:75},Ct=new xe,te=class{id="second-person";projection="perspective";defaults={damping:1};opts;initialPosition;initialLookAt;constructor(e){let{initialPosition:t,initialLookAt:i,...r}=e??{};this.opts={...Xr,...r},this.initialPosition=t?h(t):void 0,this.initialLookAt=i?h(i):void 0}getBasePose(e){let t=e.targets[this.opts.anchorKey];if(!t)return this.staticPose();let i=new xe(t.position.x,t.position.y+this.opts.eyeHeight,t.position.z),r=e.targets[this.opts.subjectKey],n=r?r.position.clone():i.clone().add(this.anchorForward(t.rotation));return{position:i,rotation:new Ni,fov:this.opts.fov,near:.1,far:1e3,lookAt:n}}staticPose(){let e=this.initialPosition?.clone()??new xe(0,this.opts.eyeHeight,0),t=this.initialLookAt?.clone()??e.clone().add(new xe(0,0,-1));return{position:e,rotation:new Ni,fov:this.opts.fov,near:.1,far:1e3,lookAt:t}}anchorForward(e){return Ct.set(0,0,-1),e&&Ct.applyQuaternion(e),Ct.clone()}};function L(s,e){switch(s){case"third-person":return new F(e);case"first-person":return new X(e);case"second-person":return new te(e);case"isometric":return new J(e);case"top-down":return new ee(e);case"flat-2d":return new G(e);case"fixed-2d":return new G(e);default:return new F(e)}}import{Vector2 as sn,Object3D as on,Vector3 as Re}from"three";import{PerspectiveCamera as St,Vector3 as rn,OrthographicCamera as De,RenderTarget as nn,LinearFilter as Hi}from"three";import{Vector3 as Me}from"three";import{OrbitControls as Jr}from"three/addons/controls/OrbitControls.js";var en=Math.atan(Math.SQRT2),tn={top:{phi:0,theta:0},side:{phi:Math.PI/2,theta:Math.PI/2},isometric:{phi:en,theta:Math.PI/4}},Ui=new Me,Te=class{camera;domElement;cameraRig=null;sceneRef=null;orbitControls=null;orbitTarget=null;orbitTargetWorldPos=new Me;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;_viewPreset="custom";_unsubscribeCameraView=null;constructor(e,t,i){this.camera=e,this.domElement=t,this.cameraRig=i??null,this._unsubscribeCameraView=qt(r=>{this.setViewLock(r)})}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._unsubscribeCameraView?.(),this._unsubscribeCameraView=null,this.disableOrbitControls(),this.detachDebugDelegate()}setViewLock(e){this._viewPreset=e,this.applyViewLock()}get viewPreset(){return this._viewPreset}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 Me().subVectors(this.camera.position,this.orbitControls.target).normalize();t.lengthSq()<1e-8&&t.set(1,1,1).normalize();let i=Ht(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),this.applyViewLock()):!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),this.applyViewLock()):!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 Jr(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),this.applyViewLock())}applyViewLock(){let e=this.orbitControls;if(!e)return;if(this._viewPreset==="custom"){e.minPolarAngle=0,e.maxPolarAngle=Math.PI/2,e.minAzimuthAngle=-1/0,e.maxAzimuthAngle=1/0,e.enableRotate=!0,e.update();return}let{phi:t,theta:i}=tn[this._viewPreset];Ui.copy(this.camera.position).sub(e.target);let r=Math.max(Ui.length(),e.minDistance),n=Math.sin(t);this.camera.position.set(e.target.x+r*n*Math.sin(i),e.target.y+r*Math.cos(t),e.target.z+r*n*Math.cos(i)),e.minPolarAngle=t,e.maxPolarAngle=t,e.minAzimuthAngle=i,e.maxAzimuthAngle=i,e.enableRotate=!1,e.update()}rebindCamera(e){this.camera=e,this.orbitControls&&(this.orbitControls.object=e,this.applyViewLock())}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 Me;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 x=class{cameraRig=null;camera;screenResolution;_perspective;frustumSize=10;sceneRef=null;name="";viewport={...Ti};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 rn(0,0,0));let n=L(e);this.pipeline=new Pe(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 Te(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 ye(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 St&&(this.camera.aspect=e/t,this.camera.updateProjectionMatrix()),this.camera instanceof De){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 nn(e,t,{minFilter:Hi,magFilter:Hi}),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===y.Flat2D||this._perspective===y.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){let t=e.lookAt.x-e.position.x,i=e.lookAt.y-e.position.y,r=e.lookAt.z-e.position.z,n=Math.hypot(t,i,r);n>1e-8&&Math.abs(i)/n>.999?this.camera.up.set(0,0,-1):this.camera.up.set(0,1,0),this.camera.lookAt(e.lookAt)}else this.camera.quaternion.copy(e.rotation);if(this.camera instanceof St&&(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 De){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()}}applyPerspective(e,t){this._perspective=e,this.pipeline.setPerspective(t),this.ensureProjection(t.projection??gt(e))}ensureProjection(e){if((this.camera instanceof De?"orthographic":"perspective")===e)return;let i=this.screenResolution.x/Math.max(this.screenResolution.y,1),r=e==="orthographic"?this.createOrthographicCamera(i):this.createPerspectiveCamera(i);if(r.position.copy(this.camera.position),r.quaternion.copy(this.camera.quaternion),r.up.copy(this.camera.up),r.layers.mask=this.camera.layers.mask,r.name=this.camera.name,"near"in this.camera&&"near"in r){let o=this.camera,a=r;a.near=o.near,a.far=o.far,a.zoom=o.zoom,a.updateProjectionMatrix()}let n=this.camera.parent;n&&(n.add(r),n.remove(this.camera)),this.camera=r,this.orbitController?.rebindCamera(r),this._rendererManager?.rebindPostProcessingCamera(r)}createCameraForPerspective(e){return gt(this._perspective)==="orthographic"?this.createOrthographicCamera(e):this.createPerspectiveCamera(e)}createPerspectiveCamera(e){return new St(75,e,.1,1e3)}createOrthographicCamera(e){return new De(this.frustumSize*e/-2,this.frustumSize*e/2,this.frustumSize/2,this.frustumSize/-2,1,1e3)}};var _e=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,o]of this.cameras.entries())if(o===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 on,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 sn(window.innerWidth,window.innerHeight),t=new x(y.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 x(y.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 Re(0,0,0),i=new Re(0,6,12);if(e&&e!==this._debugCamera){let r=e.camera.position,n=new Re().subVectors(r,t);n.lengthSq()>1&&i.copy(n.normalize().multiplyScalar(12).add(new Re(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 C=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.applyPerspective(e,L(e,t))}getPerspective(){return this.cameraRef.pipeline.perspective}getState(){return this.cameraRef.pipeline.getState()}getRenderTexture(){return this.cameraRef.getRenderTexture()}};function Ma(s){let e=Xt(s.screenResolution,{x:window.innerWidth,y:window.innerHeight}),t=10;(s.perspective==="fixed-2d"||s.perspective==="isometric"||s.perspective==="top-down")&&(t=s.zoom||10);let i=new x(s.perspective||"third-person",e,t);s.name&&(i.name=s.name);let r=h(s.position,P),n=h(s.target,P);i.move(r),i.camera.lookAt(n);let o=s.perspective||"third-person";if(o==="fixed-2d"||o==="flat-2d"?i.applyPerspective(o,L(o,{zoom:t})):o==="isometric"||o==="top-down"?i.applyPerspective(o,L(o,{zoom:t,initialPosition:r.clone(),initialLookAt:n.clone()})):i.applyPerspective(o,L(o,{initialPosition:r.clone(),initialLookAt:n.clone()})),s.viewport&&(i.viewport={...s.viewport}),s.useOrbitalControls&&(i._useOrbitalControls=!0),s.skipDebugOrbit&&(i._skipDebugOrbit=!0),s.damping!=null&&(i.pipeline.damping=s.damping),s.behaviors)for(let[a,l]of Object.entries(s.behaviors))i.pipeline.addBehavior(a,l);if(s.renderToTexture){let{width:a=512,height:l=512}=s.renderToTexture;i.createRenderTarget(a,l)}return new C(i)}import{Vector3 as an}from"three";function D(s){return!!s&&typeof s=="object"&&typeof s.create=="function"}function ie(s){return!!s&&typeof s.then=="function"}function Pt(s){return!!s&&typeof s=="object"&&s instanceof C}function ji(s){return!s||typeof s!="object"||D(s)||Pt(s)||ie(s)||typeof s.then=="function"?!1:s.constructor===Object||s.constructor?.name==="Object"}function Wi(s){return s?!!(D(s)||typeof s=="function"||ie(s)):!1}var ln="/three/basis/";function Le(s){return{...s,ktx2TranscoderPath:s?.ktx2TranscoderPath??ln}}var ke=class{constructor(e,t,i,r,n,o,a=60,l={},c=!0,d=[]){this.inputs=e;this.backgroundColor=t;this.backgroundImage=i;this.backgroundShader=r;this.gravity=n;this.variables=o;this.physicsRate=a;this.assetLoaders=l;this.defaultLighting=c;this.postProcessingEffects=d}};function cn(){return new ke({p1:["gamepad-1","keyboard-1"],p2:["gamepad-2","keyboard-2"]},ge,null,null,new an(0,0,0),{},60,{},!0)}function qi(s=[]){let e=cn(),t={},i=[],r=[],n=[];for(let l of s)Pt(l)?n.push(l):D(l)?i.push(l):Wi(l)&&!D(l)?r.push(l):ji(l)&&(t={...t,...l});let o=new ke(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),a=n.length>0?n[0]:void 0;return{config:o,entities:i,asyncEntities:r,camera:a,cameras:n}}function Oa(s){return{...s}}var dn=Symbol("vessel"),re=class extends H{static type=dn;_setup(e){}async _loaded(e){}_update(e){}_destroy(e){}_cleanup(e){}create(){return this}clone(){let e=un();return this.replayUserLifecycleRegistrationsTo(e),this.cloneChildrenInto(e),e}add(...e){for(let t of e)super.add(t);return this}};function un(...s){let e=new re;return s.forEach(t=>e.add(t)),e.enableUserLifecycleTracking(),e}import{Color as Er,Vector3 as xr}from"three";import{createSimulation as pn}from"@zylem/behaviors/core";function wt(s){return typeof s?.handlePostCollision=="function"&&typeof s?.handleIntersectionEvent=="function"}function hn(s,e){return s<e?`${s}|${e}`:`${e}|${s}`}var Ae=class s{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 pn({gravity:[i.x,i.y,i.z],fixedTimestep:1/t,initialCapacity:4096});return new s(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 he)&&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 ai(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=hn(i,r),o=this.livePairs.get(n);o||(o={uuidA:i<r?i:r,uuidB:i<r?r:i,contactCount:0,intersectionCount:0},this.livePairs.set(n,o));let a=t.type==="collisionStarted"?1:-1;t.sensor?o.intersectionCount=Math.max(0,o.intersectionCount+a):o.contactCount=Math.max(0,o.contactCount+a),o.contactCount===0&&o.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(!wt(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 o=this.collisionMap.get(n.uuidA),a=this.collisionMap.get(n.uuidB);this.activeCollisionPairs.has(r)||this.dispatchCollisionPhase(n,"enter",t),(this.entityHasCollisionPhaseListener(o,"stay")||this.entityHasCollisionPhaseListener(a,"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),o=this.collisionMap.get(e.uuidB);n&&o&&n._collision(o,it.globals,r);let a=this.collisionMap.get(e.uuidA),l=this.collisionMap.get(e.uuidB);a&&l&&l._collision(a,it.globals,r)}dispatchIntersectionDelegates(e,t){let i=this.collisionMap.get(e.uuidA),r=this.collisionMap.get(e.uuidB);i&&r&&wt(i)&&(i.handleIntersectionEvent({entity:i,other:r,delta:t}),this.collisionBehaviorMap.set(i.uuid,i));let n=this.collisionMap.get(e.uuidA),o=this.collisionMap.get(e.uuidB);n&&o&&wt(o)&&(o.handleIntersectionEvent({entity:o,other:n,delta:t}),this.collisionBehaviorMap.set(o.uuid,o))}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 mn,Color as Ki,AmbientLight as gn,DirectionalLight as fn,Vector3 as Oe,GridHelper as yn,Texture as vn,SRGBColorSpace as bn}from"three";var Be=class{type="Scene";_setup;scene;zylemCamera;cameraManager=null;containerElement=null;update=()=>{};_collision;_destroy;name;tag;constructor(e,t,i){let r=new mn,o=i.backgroundColor instanceof Ki?i.backgroundColor:new Ki(i.backgroundColor);r.background=o,i.backgroundShader?this.setupBackgroundShader(r,i.backgroundShader):i.backgroundImage&&z.loadTexture(i.backgroundImage,{colorSpace:bn}).then(a=>{r.background=a}),this.scene=r,this.zylemCamera=t,i.defaultLighting!==!1&&this.setupLighting(r),u.enabled&&this.debugScene()}setupBackgroundShader(e,t){if(!ue(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:v()})}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 vn&&(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 gn(16777215,1);e.add(t);let i=new fn(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 Oe(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(_(e))return;let t=e.group??e.mesh;if(!t||this.isAttachedOutsideScene(t))return;let i=Cn(e);i&&i.attachToScene(this.scene);let r=e.options.position??new Oe(0,0,0);if(e.physicsAttached&&e.body)try{let n=e.body.translation();r=new Oe(n.x,n.y,n.z)}catch{r=e.options.position??new Oe(0,0,0)}this.add(t,r),j(e)}isAttachedOutsideScene(e){return e.parent!=null&&e.parent!==this.scene}debugScene(){let i=new yn(1e3,100);this.scene.add(i)}};function Cn(s){return s.constructor.type===li?s:null}var ze=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 Sn}from"three";var Qi=new Sn;function Yi(s){let e=s._childrenMap,t=s._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,o=n?me(r,t?.interpolationAlpha??0):null;n&&o&&n.position.set(o.position.x,o.position.y,o.position.z),!i.controlledRotation&&n&&o&&(Qi.set(o.rotation.x,o.rotation.y,o.rotation.z,o.rotation.w),n.setRotationFromQuaternion(Qi))}}import{nanoid as Es}from"nanoid";import{Box3 as zt,BufferAttribute as br,BufferGeometry as gs,LineBasicMaterial as fs,LineSegments as ys,Raycaster as vs,Vector2 as bs,Vector3 as Vt}from"three";import{subscribe as Cs}from"valtio/vanilla";import{nanoid as Cr}from"nanoid";import{subscribe as Pn}from"valtio/vanilla";var Ve=class{stage;constructor(e){this.stage=e}subscribe(e){let t=()=>e(this.snapshot());return t(),Pn(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.selectedEntityIds]}}};import{Box3 as wn,BoxGeometry as $i,Color as En,EdgesGeometry as Xi,Group as xn,LineBasicMaterial as Mn,LineSegments as Tn,Mesh as Dn,MeshBasicMaterial as Rn,Vector3 as Ji}from"three";var Ie=class{scene;container;fillMesh;edgeLines;currentColor=new En(65280);bbox=new wn;size=new Ji;center=new Ji;constructor(e){this.scene=e;let t=new $i(1,1,1);this.fillMesh=new Dn(t,new Rn({color:this.currentColor,transparent:!0,opacity:.12,depthWrite:!1}));let i=new Xi(t);this.edgeLines=new Tn(i,new Mn({color:this.currentColor,linewidth:1})),this.container=new xn,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}this.bbox.setFromObject(e),this.updateFromBounds(this.bbox)}updateFromBounds(e){if(!e||e.isEmpty()){this.hide();return}if(e!==this.bbox&&this.bbox.copy(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 $i(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 Xi(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 _n,BoxGeometry as kn,Group as Ln,Mesh as An,MeshBasicMaterial as On,Vector3 as er}from"three";var Bn={x:0,y:0,z:0},zn=7128319,Vn=.35;function In(){return new On({color:zn,transparent:!0,opacity:Vn,depthWrite:!1})}function Fn(s){let e=s.size;return new er(e?.x??1,e?.y??1,e?.z??1)}function Gn(s,e){try{let t=s.create({position:Bn,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 "${s.id}" factory failed, falling back to a box`,t),null}}function Zn(s,e){s.traverse(t=>{let i=t;i.isMesh&&(i.material=e,i.castShadow=!1,i.receiveShadow=!1)})}var Fe=class{scene;container;builtFor=null;builtProps=null;material=null;extent=null;bounds=new _n;constructor(e){this.scene=e,this.container=new Ln,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=de(e),n={...r?.defaultProps??{},...t??{}},a=(r?Gn(r,n):null)??new An(new kn(...Fn(n).toArray()));a.position.set(0,0,0),this.material=In(),Zn(a,this.material),this.container.add(a),this.bounds.setFromObject(a),this.extent=this.bounds.isEmpty()?null:this.bounds.getSize(new er)}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 Nn=0;function Un(s,e){if(e)return{position:s.origin.clone().add(s.direction.clone().multiplyScalar(e.distance)),normal:new Et(e.normal[0],e.normal[1],e.normal[2])};if(Math.abs(s.direction.y)<1e-6)return null;let t=(Nn-s.origin.y)/s.direction.y;return t<0?null:{position:s.origin.clone().add(s.direction.clone().multiplyScalar(t)),normal:new Et(0,1,0)}}function Hn(s,e){if(e.lengthSq()<1e-8)return 0;let t=e.clone().normalize();return(Math.abs(t.x)*s.x+Math.abs(t.y)*s.y+Math.abs(t.z)*s.z)/2}function xt(s,e,t){let i=Hn(e,t);return i<=0?s.clone():s.clone().add(t.clone().normalize().multiplyScalar(i))}function Mt(s,e,t,i){let r=Un(s,e);if(!r)return null;let{normal:n}=r,o=t.enabled?ce(r.position,t.translate):r.position,a=new Et(o.x,o.y,o.z);return{position:i?xt(a,i,n):a,normal:n}}import{Box3 as Kn,Quaternion as Ue,Vector3 as S}from"three";import{nanoid as Qn}from"nanoid";import{Vector3 as Z}from"three";var Dt=.95,jn=16,ne=new Z,Wn=new Z,tr=new Z,Tt=new Z;function ir(s){return s?s.isPerspectiveCamera===!0||s.isOrthographicCamera===!0:!1}function Ge(s,e,t=Dt){return ne.copy(s).project(e),Math.abs(ne.x)<=t&&Math.abs(ne.y)<=t&&ne.z>=-1&&ne.z<=1}function rr(s){let e=0,t=1;for(let i=0;i<jn;i+=1){let r=(e+t)/2;s(r)?e=r:t=r}return e}function nr(s,e,t,i=Dt){if(!ir(t))return e.clone();let r=t;if(Ge(e,r,i)||!Ge(s,r,i))return e.clone();let n=rr(o=>Ge(Wn.copy(s).lerp(e,o),r,i));return s.clone().lerp(e,n)}function sr(s,e,t,i,r=Dt){if(!ir(i)||t.x<=1&&t.y<=1&&t.z<=1||s.isEmpty())return t.clone();let n=i;tr.copy(e);let o=new Z(1,1,1),a=c=>(o.set(1+(t.x-1)*c,1+(t.y-1)*c,1+(t.z-1)*c),qn(s,tr,o,n,r));if(a(1))return t.clone();let l=rr(a);return new Z(1+(t.x-1)*l,1+(t.y-1)*l,1+(t.z-1)*l)}function qn(s,e,t,i,r){for(let n=0;n<8;n+=1)if(Tt.set(n&1?s.max.x:s.min.x,n&2?s.max.y:s.min.y,n&4?s.max.z:s.min.z),Tt.sub(e).multiply(t).add(e),!Ge(Tt,i,r))return!1;return!0}var Yn={translate:"Move",rotate:"Rotate",scale:"Scale"};function Rt(s){let e=typeof s?.getPose=="function"?s.getPose():null,t=s?.group??s?.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 s?.getScale=="function"?s.getScale():{x:1,y:1,z:1};return{position:new S(i.x,i.y,i.z),quaternion:new Ue(r.x,r.y,r.z,r.w),scale:new S(n.x,n.y,n.z)}}function or(s){let e=at(s.quaternion);return{position:{x:s.position.x,y:s.position.y,z:s.position.z},rotation:e,quaternion:{x:s.quaternion.x,y:s.quaternion.y,z:s.quaternion.z,w:s.quaternion.w},scale:{x:s.scale.x,y:s.scale.y,z:s.scale.z}}}function $n(s,e){return s.position.distanceToSquared(e.position)>1e-5*1e-5||Math.abs(s.quaternion.dot(e.quaternion))<1-1e-5||s.scale.distanceToSquared(e.scale)>1e-5*1e-5}function Ze(s,e){(e.position||e.quaternion)&&s.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&&s.setScale?.(e.scale.x,e.scale.y,e.scale.z)}function Xn(s){let e=s?.group??s?.mesh;if(!e?.isObject3D)return null;let t=new Kn().setFromObject(e);return t.isEmpty()?null:t}var _t=.02,kt=50;function Jn(s){return new S(Lt(s.x,_t,kt),Lt(s.y,_t,kt),Lt(s.z,_t,kt))}function Lt(s,e,t){return Math.min(Math.max(s,e),t)}var At=new Ue,es=new S,Ne=class{gizmo=new gi;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 o=this.context.resolveEntity(n);o&&r.push({uuid:n,entity:o,start:Rt(o),startBounds:this.mode==="scale"?Xn(o):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 o=B(),a=o.enabled&&!t;switch(n.kind){case"translate":this.applyTranslate(i,n.offset,a?o.translate:0,r);break;case"rotate":this.applyRotate(i,n.axis,n.angle,a?o.rotate:0);break;case"scale":this.applyScale(i,n.factor,a?o.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=Rt(i.entity);$n(i.start,r)&&(e.mode==="scale"&&lt(i.entity),t.push({uuid:i.uuid,before:or(i.start),after:or(r)}))}t.length&&U({opId:Qn(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=es.copy(e.pivotStart).add(t),o=nr(e.pivotStart,n,r),a=i>0?ce(o,i):o,l=new S(a.x-e.pivotStart.x,a.y-e.pivotStart.y,a.z-e.pivotStart.z);for(let c of e.entries)Ze(c.entity,{position:c.start.position.clone().add(l)})}applyRotate(e,t,i,r){let n=e.axis;for(let o of e.entries){At.setFromAxisAngle(t,i);let a=At.clone().multiply(o.start.quaternion),l=a;if(r>0&&(n==="x"||n==="y"||n==="z")){let d=at(a);d[n]=Qt(d[n],r);let p=ot(d);l=new Ue(p.x,p.y,p.z,p.w)}let c=o.start.position.clone().sub(e.pivotStart).applyQuaternion(At).add(e.pivotStart);Ze(o.entity,{position:c,quaternion:l})}}applyScale(e,t,i,r){for(let n of e.entries){let o=n.startBounds?sr(n.startBounds,n.start.position,t,r):t,a=Jn(o),l=new S(n.start.scale.x*a.x,n.start.scale.y*a.y,n.start.scale.z*a.z),c=i>0?Yt(l,i):l;Ze(n.entity,{scale:new S(c.x,c.y,c.z)})}}describeOperation(e){let t=Yn[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 S,i=0;for(let r of e){let n=this.context.resolveEntity(r);n&&(t.add(Rt(n).position),i++)}return i?t.divideScalar(i):null}};function ar(s,e,t){for(let i of s.entries){let r=e==="undo"?i.before:i.after;if(!r)continue;let n=t(i.uuid);if(!n)continue;let o=r.quaternion??(r.rotation?ot(r.rotation):void 0);Ze(n,{position:r.position?new S(r.position.x,r.position.y,r.position.z):void 0,quaternion:o?new Ue(o.x,o.y,o.z,o.w):void 0,scale:r.scale?new S(r.scale.x,r.scale.y,r.scale.z):void 0}),r.scale&&lt(n)}}var ts=200;function lr(s){return typeof s=="object"&&s!==null&&!Array.isArray(s)}function is(s){return lr(s)&&(ue(s)||ei(s))}var He=class{stage;snapshots=new Map;constructor(e){this.stage=e}applySwatches(e){let t=new Map,i=[],r=[];for(let n of e.uuids)for(let o of e.swatches){let{result:a,entry:l}=this.applyPair(n,o,t);i.push(a),l&&r.push(l)}return t.size>0&&this.remember(e.opId,t),{results:i,entries:r}}applySceneOperation(e,t){if(e.kind!=="swatch")return;let i=this.snapshots.get(e.opId);if(i){t==="undo"?this.undoFromSnapshot(i):this.redoFromSnapshot(i);return}if(t==="redo"){let r=new Map;for(let n of e.entries)n.swatch&&this.applyPair(n.uuid,n.swatch,r);r.size>0&&this.remember(e.opId,r);return}this.undoWithoutSnapshot(e)}hasSnapshot(e){return this.snapshots.has(e)}dispose(){for(let[e]of this.snapshots)this.forget(e)}applyPair(e,t,i){let r={uuid:e,kind:t.kind,source:t.source},n=this.stage.resolveEntity(e);if(!n)return{result:{...r,ok:!1,reason:"entity-not-found"}};if(!lr(t.props))return{result:{...r,ok:!1,reason:"invalid-props"}};let o=i.get(e)??{previousRefs:new Map,appliedRefs:new Map},a=t.kind==="shader"?this.applyShader(n,t,o):this.applyBehavior(n,t,o);return a.ok?(i.set(e,o),{result:{...r,ok:!0,replaced:a.replaced},entry:{uuid:e,swatch:t,...a.replacedSpec?{replaced:a.replacedSpec}:{}}}):{result:{...r,ok:!1,reason:a.reason}}}applyShader(e,t,i){let r=pe("shader",t.source);if(!r)return{ok:!1,reason:"unknown-source"};if(!e.hasMaterial())return{ok:!1,reason:"no-material"};let n;try{n=r.create(t.props)}catch(a){return console.warn(`[zylem] swatch shader "${t.source}" threw`,a),{ok:!1,reason:"invalid-props"}}if(!is(n))return{ok:!1,reason:"invalid-props"};let o=e.setMaterial({shader:n},{disposePrevious:!1});return o?(i.previousMaterials?Ot(o,i.previousMaterials):i.previousMaterials=o,{ok:!0,replaced:!1}):{ok:!1,reason:"no-material"}}applyBehavior(e,t,i){let r=pe("behavior",t.source);if(!r)return{ok:!1,reason:"unknown-source"};let{descriptor:n}=r,o=n.key,a=!1,l,c=e.getBehaviorRef(n);c&&(e.removeBehavior(c),this.stage.detachBehaviorLink(e,c),i.appliedRefs.get(o)===c||(a=!0,l={source:t.source,props:{...c.options}},i.previousRefs.has(o)||i.previousRefs.set(o,c)));let d;try{e.use(n,t.props),d=e.getBehaviorRefs().at(-1)}catch(p){console.warn(`[zylem] swatch behavior "${t.source}" failed to attach`,p)}return!d||d.descriptor.key!==o?(c&&(e.restoreBehaviorRef(c),this.stage.attachBehaviorLink(e,c),i.previousRefs.get(o)===c&&i.previousRefs.delete(o)),{ok:!1,reason:"invalid-props"}):(this.stage.attachBehaviorLink(e,d),i.appliedRefs.set(o,d),{ok:!0,replaced:a,replacedSpec:l})}undoFromSnapshot(e){for(let[t,i]of[...e].reverse()){let r=this.stage.resolveEntity(t);if(r){if(i.previousMaterials){let n=r.replaceMaterials(i.previousMaterials,{disposePrevious:!1});n&&(i.redoMaterials=n)}for(let n of i.appliedRefs.values())r.removeBehavior(n)&&this.stage.detachBehaviorLink(r,n);for(let n of i.previousRefs.values())r.restoreBehaviorRef(n),this.stage.attachBehaviorLink(r,n)}}}redoFromSnapshot(e){for(let[t,i]of e){let r=this.stage.resolveEntity(t);if(r){i.redoMaterials&&r.replaceMaterials(i.redoMaterials,{disposePrevious:!1});for(let n of i.previousRefs.values())r.removeBehavior(n)&&this.stage.detachBehaviorLink(r,n);for(let n of i.appliedRefs.values())r.restoreBehaviorRef(n),this.stage.attachBehaviorLink(r,n)}}}undoWithoutSnapshot(e){for(let t of[...e.entries].reverse()){let i=this.stage.resolveEntity(t.uuid);if(!(!i||!t.swatch)){if(t.swatch.kind==="behavior"){let r=pe("behavior",t.swatch.source);if(!r)continue;let n=i.removeBehavior(r.descriptor);if(n&&this.stage.detachBehaviorLink(i,n),t.replaced){i.use(r.descriptor,t.replaced.props);let o=i.getBehaviorRefs().at(-1);o&&this.stage.attachBehaviorLink(i,o)}continue}i.setMaterial({})}}}remember(e,t){for(this.snapshots.has(e)&&this.forget(e),this.snapshots.set(e,t);this.snapshots.size>ts;){let i=this.snapshots.keys().next().value;if(i===void 0)break;this.forget(i)}}forget(e){let t=this.snapshots.get(e);if(this.snapshots.delete(e),!!t)for(let[i,r]of t){let n=this.stage.resolveEntity(i)?.getMaterials()??[];Ot(r.previousMaterials??[],n),Ot(r.redoMaterials??[],n)}}};function Ot(s,e){for(let t of s)e.includes(t)||t.dispose()}import{Box3 as os,Frustum as as,Vector2 as We}from"three";import{Frustum as rs,Vector2 as cr,Vector3 as ns}from"three";var dr=Array.from({length:8},()=>new ns),g=new cr,f=new cr;function ur(s,e,t,i=new rs){g.set(Math.min(e.x,t.x),Math.min(e.y,t.y)),f.set(Math.max(e.x,t.x),Math.max(e.y,t.y));let r=1e-5;f.x-g.x<r&&(f.x=g.x+r),f.y-g.y<r&&(f.y=g.y+r),R(0,g.x,g.y,-1,s),R(1,f.x,g.y,-1,s),R(2,f.x,f.y,-1,s),R(3,g.x,f.y,-1,s),R(4,g.x,g.y,1,s),R(5,f.x,g.y,1,s),R(6,f.x,f.y,1,s),R(7,g.x,f.y,1,s);let[n,o,a,l,c,d,p,m]=dr,O=i.planes;return N(O[0],n,c,m),N(O[1],o,p,d),N(O[2],l,m,p),N(O[3],n,d,c),N(O[4],n,l,a),N(O[5],c,p,m),i}function R(s,e,t,i,r){dr[s].set(e,t,i).unproject(r)}function N(s,e,t,i){s.setFromCoplanarPoints(e,t,i)}function pr(s,e){return e.isEmpty()||!Number.isFinite(e.min.x)||!Number.isFinite(e.max.x)?!1:s.intersectsBox(e)}function hr(s,e,t){switch(t){case"add":{let i=new Set(s),r=[...s];for(let n of e)i.has(n)||(i.add(n),r.push(n));return r}case"subtract":{let i=new Set(e);return s.filter(r=>!i.has(r))}default:return[...new Set(e)]}}function mr(s){return s.altKey?"subtract":s.shiftKey?"add":"replace"}var ss="[data-zylem-overlay-root]";function gr(s){let e=s.parentElement;return e?e.querySelector(ss)??e:null}var je=class{element=null;host=null;show(e,t){let i=this.ensureElement(e);i.style.left=`${t.left}px`,i.style.top=`${t.top}px`,i.style.width=`${t.width}px`,i.style.height=`${t.height}px`,i.style.display="block"}hide(){this.element&&(this.element.style.display="none")}dispose(){this.element?.remove(),this.element=null,this.host=null}ensureElement(e){if(this.element&&this.host===e)return this.element;this.element?.remove();let t=document.createElement("div");t.dataset.zylemMarquee="true";let i=t.style;return i.position="absolute",i.pointerEvents="none",i.boxSizing="border-box",i.border="1px solid rgba(34, 255, 34, 0.9)",i.background="rgba(34, 255, 34, 0.12)",i.display="none",i.zIndex="20",e.appendChild(t),this.element=t,this.host=e,t}};var ls=4,cs=new os,fr=new as,qe=class{context;overlay=new je;armed=!1;dragging=!1;mode="replace";baseSelection=[];startNdc=new We;currentNdc=new We;startClient=new We;currentClient=new We;host=null;constructor(e){this.context=e}get isArmed(){return this.armed}get isDragging(){return this.dragging}pointerDown(e,t,i){this.armed=!0,this.dragging=!1,this.mode=mr(t),this.baseSelection=[...u.selectedEntityIds],this.startNdc.copy(e),this.currentNdc.copy(e),this.startClient.set(t.clientX,t.clientY),this.currentClient.copy(this.startClient),this.host=gr(i)}pointerMove(e,t){if(!this.armed)return!1;this.currentNdc.copy(e),this.currentClient.set(t.clientX,t.clientY);let i=!1;if(!this.dragging){if(this.currentClient.distanceTo(this.startClient)<ls)return!1;this.dragging=!0,i=!0}return this.drawOverlay(),i}pointerUp(e){if(!this.armed)return"idle";let t=this.dragging;return this.currentNdc.copy(e),this.reset(),t?(this.commit(),"marquee"):"click"}cancel(){this.reset()}dispose(){this.reset(),this.overlay.dispose()}reset(){this.armed=!1,this.dragging=!1,this.overlay.hide()}drawOverlay(){if(!this.host)return;let e=this.host.getBoundingClientRect(),t=Math.min(this.startClient.x,this.currentClient.x)-e.left,i=Math.min(this.startClient.y,this.currentClient.y)-e.top;this.overlay.show(this.host,{left:t,top:i,width:Math.abs(this.currentClient.x-this.startClient.x),height:Math.abs(this.currentClient.y-this.startClient.y)})}commit(){let e=this.context.getCamera();if(!e)return;ur(e,this.startNdc,this.currentNdc,fr);let t=[];this.context.forEachEntity((i,r)=>{let n=W(r,cs);n&&pr(fr,n)&&t.push(i)}),Gt(hr(this.baseSelection,t,this.mode))}};import{BoxGeometry as ds,EdgesGeometry as us,Group as ps,LineBasicMaterial as hs,LineSegments as ms,Vector3 as vr}from"three";var Ke=new vr,yr=new vr,Qe=class{scene;container=new ps;edges;material;pool=[];constructor(e,t=16765503){this.scene=e;let i=new ds(1,1,1);this.edges=new us(i),i.dispose(),this.material=new hs({color:t,depthTest:!1,transparent:!0,opacity:.9}),this.container.name="SelectionHighlight",this.container.renderOrder=999,this.scene.add(this.container)}setColor(e){this.material.color.set(e)}update(e){let t=0;for(let i of e){if(i.isEmpty()||!Number.isFinite(i.min.x)||!Number.isFinite(i.max.x))continue;i.getSize(Ke),i.getCenter(yr);let r=this.acquire(t);t+=1,r.position.copy(yr),r.scale.set(Math.max(Ke.x,1e-6),Math.max(Ke.y,1e-6),Math.max(Ke.z,1e-6)),r.visible=!0}for(let i=t;i<this.pool.length;i+=1)this.pool[i].visible=!1}hide(){for(let e of this.pool)e.visible=!1}dispose(){this.scene.remove(this.container),this.edges.dispose(),this.material.dispose(),this.pool.length=0}acquire(e){let t=this.pool[e];if(t)return t;let i=new ms(this.edges,this.material);return i.frustumCulled=!1,this.container.add(i),this.pool.push(i),i}};var Sr=2293538,Ss=16724787,Bt=new zt,Pr=new Vt,Ye=class{stage;options;mouseNdc=new bs(-2,-2);raycaster=new vs;domDisposeFns=[];domListenersAttached=!1;debugCursor=null;placementGhost=null;debugLines=null;cameraDebugDelegate=null;debugStateUnsubscribe=null;focusContextUnregister=null;entityResolverUnregister=null;lastDebugEnabled=null;warnedMissingAddFactory=!1;transformTool;swatchApplier;marquee;selectionHighlight=null;selectionBoundsPool=[];hoverBounds=new zt;grid=new mi;lastTool=null;capturedPointer=null;constructor(e,t){this.stage=e,this.options={maxRayDistance:t?.maxRayDistance??5e3,addEntityFactory:t?.addEntityFactory??null},this.transformTool=new Ne({getScene:()=>this.stage.scene?.scene??null,getCamera:()=>this.getDebugViewCamera()?.camera??null,resolveEntity:i=>this.resolveEntity(i)}),this.swatchApplier=new He({resolveEntity:i=>this.resolveEntity(i),attachBehaviorLink:(i,r)=>this.stage.entityDelegate.attachBehaviorLink(i,r),detachBehaviorLink:(i,r)=>this.stage.entityDelegate.detachBehaviorLink(i,r)}),this.marquee=new qe({getCamera:()=>this.getDebugViewCamera()?.camera??null,forEachEntity:i=>this.forEachSelectableEntity(i)}),this.syncWithDebugState(),this.debugStateUnsubscribe=Cs(u,()=>{this.syncWithDebugState()}),this.entityResolverUnregister=Ft(i=>this.resolveEntity(i)),this.focusContextUnregister=Kt({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)}forEachSelectableEntity(e){let t=new Set,i=(r,n)=>{t.has(n)||(t.add(n),e(n,r))};this.stage.entityDelegate.childrenMap.forEach(i),this.stage.entityDelegate.debugMap.forEach(i)}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 Ve(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,this.marquee.isArmed&&(this.marquee.cancel(),this.endPointerCapture()),e!=="none"&&(this.ensureInteraction(),this.populateDebugMap()),this.parkToolVisuals(e);let t=rt(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(B().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 ys(new gs,new fs({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 Ie(e),this.placementGhost??=new Fe(e),this.selectionHighlight??=new Qe(e))}updateSelectionHighlight(){let e=this.selectionHighlight;if(!e)return;let t=u.selectedEntityIds;if(t.length===0){e.hide();return}let i=[];for(let r of t){let n=this.resolveEntity(r),o=this.selectionBoundsPool[i.length]??=new zt,a=W(n,o);a&&i.push(a)}e.update(i)}parkToolVisuals(e){e!=="add"&&this.placementGhost?.hide(),e!=="select"&&e!=="delete"&&!u.pickMode&&this.debugCursor?.hide(),e==="none"&&!u.enabled&&this.selectionHighlight?.hide()}disposeToolVisuals(){this.debugCursor?.dispose(),this.debugCursor=null,this.placementGhost?.dispose(),this.placementGhost=null,this.selectionHighlight?.dispose(),this.selectionHighlight=null}update(){let e=this.getDebugViewCamera();if(!this.stage.scene||!this.stage.world||!e)return;let{world:t}=this.stage,i=oe();if(this.ensureInteraction(),this.ensureToolVisuals(),u.enabled?(this.initDebugVisuals(),this.updateColliderWireframes(t)):this.disposeDebugVisuals(),this.updatePlacementGhost(i,t),this.updateSelectionHighlight(),rt(i)){this.debugCursor?.hide(),this.transformTool.update(),this.transformTool.isDragging||this.transformTool.hover(this.currentRay());return}if(this.transformTool.update(),!(i==="select"||i==="delete"||u.pickMode)){this.debugCursor?.hide();return}let n=this.currentRay(),o=t.raycast(n.origin,n.direction,this.options.maxRayDistance);o?st(o.uuid??null):le();let a=Ut();if(!a){this.debugCursor?.hide();return}let l=W(this.resolveEntity(a),this.hoverBounds);if(!l){this.debugCursor?.hide();return}switch(i){case"select":this.debugCursor?.setColor(Sr);break;case"delete":this.debugCursor?.setColor(Ss);break;default:this.debugCursor?.setColor(u.pickMode?Sr:16777215);break}this.debugCursor?.updateFromBounds(l)}pickAtNdc(e,t,i={}){let r=i.updateHover??u.pickMode;this.mouseNdc.set(e,t);let n=this.stage.world;if(!n||!this.getDebugViewCamera())return r&&le(),null;let o=this.currentRay(),l=n.raycast(o.origin,o.direction,this.options.maxRayDistance)?.uuid??null;if(!l)return r&&le(),null;r&&st(l);let c=this.resolveEntity(l);return{uuid:l,name:c?.name??""}}applySwatches(e){return this.swatchApplier.applySwatches(e)}updateColliderWireframes(e){if(!this.debugLines)return;let t=e.simulation.getDebugRender();t&&t.vertices.length>0?(this.debugLines.geometry.setAttribute("position",new br(new Float32Array(t.vertices),3)),this.debugLines.geometry.setAttribute("color",new br(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||!ae()||(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(),o=t.raycast(n.origin,n.direction,this.options.maxRayDistance)??null,a=Mt(n,o,B(),i.measure());if(!a){i.hide();return}i.showAt(a.position)}dispose(){this.focusContextUnregister?.(),this.focusContextUnregister=null,this.entityResolverUnregister?.(),this.entityResolverUnregister=null,this.debugStateUnsubscribe?.(),this.debugStateUnsubscribe=null,this.endPointerCapture(),this.marquee.dispose(),this.transformTool.dispose(),this.swatchApplier.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":ar(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;case"swatch":this.swatchApplier.applySceneOperation(e,t);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 Vt,direction:new Vt(0,0,-1)}}handleAction(e,t={shiftKey:!1,altKey:!1}){let i=oe();if(i!=="select"&&i!=="delete"&&i!=="add")return;let n=this.stage.world?.raycast(e.origin,e.direction,this.options.maxRayDistance)??null;switch(i){case"select":{let o=n?.uuid??null,a=o&&this.resolveEntity(o)?o:null;t.altKey?a&&Zt([a]):t.shiftKey?a&&Nt(a):a?nt(a):nt(null);break}case"delete":{let o=n?.uuid??null;if(!o)break;this.stage.entityDelegate.detachEntity(o)&&U({opId:Cr(10),kind:"delete",label:"Delete entity",entries:[{uuid:o}]});break}case"add":this.placeEntity(e,n);break}}placeEntity(e,t){let i=Mt(e,t,B());if(!i)return;let{position:r,normal:n}=i,o=u.addTypeId?de(u.addTypeId):null;if(!o&&!this.options.addEntityFactory){this.warnMissingAddSource();return}let a=o?o.create({position:{x:r.x,y:r.y,z:r.z},normal:{x:n.x,y:n.y,z:n.z},props:{...o.defaultProps??{},...u.addTypeProps??{}}}):this.options.addEntityFactory({position:r,normal:n});a&&Promise.resolve(a).then(async l=>{l&&(await this.stage.entityDelegate.spawnEntity(l),this.restOnSurface(l,r,n),U({opId:Cr(10),kind:"create",label:`Add ${o?.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"||(Bt.setFromObject(r),Bt.isEmpty()))return;Bt.getSize(Pr);let n=xt(t,Pr,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),$t("warn",e)}attachDomListeners(){let e=this.stage.rendererManager?.getDomElement();if(!e)return!1;let t=a=>{let l=e.getBoundingClientRect(),c=(a.clientX-l.left)/l.width*2-1,d=-((a.clientY-l.top)/l.height*2-1);this.mouseNdc.set(c,d)},i=a=>{if(t(a),this.marquee.isArmed){this.marquee.pointerMove(this.mouseNdc,a);return}this.transformTool.isDragging&&this.transformTool.pointerMove(this.currentRay(),a.altKey)},r=a=>{if(a.button!==0)return;t(a);let l=this.currentRay();if(this.transformTool.pointerDown(l)){this.beginPointerCapture(e,a.pointerId);return}if(oe()==="select"){this.marquee.pointerDown(this.mouseNdc,a,e),this.beginPointerCapture(e,a.pointerId);return}this.handleAction(l,a)},n=a=>{if(this.marquee.isArmed){let l=this.marquee.pointerUp(this.mouseNdc);this.endPointerCapture(),l==="click"&&this.handleAction(this.currentRay(),a);return}this.transformTool.isDragging&&(this.transformTool.pointerUp(),this.endPointerCapture())},o=a=>{if(this.marquee.isArmed){this.marquee.cancel(),this.endPointerCapture();return}n(a)};return e.addEventListener("pointermove",i),e.addEventListener("pointerdown",r),e.addEventListener("pointerup",n),e.addEventListener("pointercancel",o),this.domDisposeFns.push(()=>e.removeEventListener("pointermove",i),()=>e.removeEventListener("pointerdown",r),()=>e.removeEventListener("pointerup",n),()=>e.removeEventListener("pointercancel",o)),!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 Ps}from"three";var $e=class{stage;constructor(e){this.stage=e}createDefaultCamera(){let e=window.innerWidth,t=window.innerHeight,i=new Ps(e,t);return new x(y.ThirdPerson,i)}resolveCamera(e,t){return e||(t?t.cameraRef:this.createDefaultCamera())}buildCameraManager(e,...t){let i=new _e;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 o=n.cameraRef;i.addCamera(o,o.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 Xe=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"?se.emit("stage:loading:start",t):e.type==="progress"?se.emit("stage:loading:progress",t):e.type==="complete"&&se.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 Je=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)},M.on("entity:model:loaded",this.modelLoadedHandler)}observe(e){if(e.group||e.mesh){K(e.options)||(this.scene?.addEntityGroup(e),j(e),V(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),j(i),V(i),K(i.options)||this.onEntityReady?.(i),this.pendingEntities.delete(e)}dispose(){this.modelLoadedHandler&&(M.off("entity:model:loaded",this.modelLoadedHandler),this.modelLoadedHandler=null),this.pendingEntities.clear(),this.onEntityReady=null,this.scene=null}};import{StageBodyKind as wr}from"@zylem/behaviors/core";var ws=200,et=class s{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 re){e.create();for(let i of e.getChildren())i instanceof H&&await this.spawnEntity(i);e.nodeSetup({me:e,globals:v(),camera:this.camera}),this.addEntityToStage(e);return}let t=e.create();ri(t),this.registerBehaviorLinks(t),this.ensureEnvironmentStatic(t),this.maybeAttachEntityPhysics(t);for(let i of e.getChildren())i instanceof H&&await this.spawnEntity(i);e.nodeSetup({me:e,globals:v(),camera:this.camera}),this.tryRegisterRenderStrategy(t),_(t)||this.scene.addEntityGroup(t),V(t),this.addEntityToStage(t),this.entityModelDelegate.observe(t),ni(t)}handleLateModelReady(e){!this.world||!this.scene||!this.childrenMap.has(e.uuid)||(this.ensureEnvironmentStatic(e),this.maybeAttachEntityPhysics(e),this.tryRegisterRenderStrategy(e),_(e)||this.scene.addEntityGroup(e),V(e))}tryRegisterRenderStrategy(e){this.renderStrategy&&this.renderStrategy.register(e)}ensureEnvironmentStatic(e){if(q(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!==wr.Static&&(e.bodyDesc.kind=wr.Static)}maybeAttachEntityPhysics(e){if(!(!this.world||e.physicsAttached||!e.colliderDesc)){if(e instanceof he){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),_(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(),M.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),_(i)||this.scene.addEntityGroup(i),ii(i),si(i),this.addEntityToStage(i),this.entityModelDelegate.observe(i),!0}isDetached(e){return this.detachedMap.has(e)}evictOldestDetached(){for(;this.detachedMap.size>ws;){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:v()})}catch{}I(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 oi?{...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(D(t)){this.handleEntityImmediatelyOrQueue(t);continue}if(typeof t=="function"){try{let i=t();D(i)?this.handleEntityImmediatelyOrQueue(i):ie(i)&&this.handlePromiseWithSpawnOnResolve(i)}catch(i){console.error("Error executing entity factory",i)}continue}ie(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 o=await n;o&&await this.spawnEntity(o)}catch(o){console.error("Failed to resolve pending stage entity",o)}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)??s.EMPTY_BEHAVIOR_LINKS,createEntity:dt,getGlobals:v}):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:v()})}catch{}I(t),e.push(t.uuid)}),this.detachedMap.forEach(({entity:t})=>{try{t.nodeDestroy?.({me:t,globals:v()})}catch{}I(t)}),this.detachedMap.clear(),this.childrenMap.clear(),this.debugMap.clear(),this.entityAddedHandlers=[];for(let t of e)M.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)i.push(this.linkBehaviorRef(e,r));this.behaviorLinksByUuid.set(e.uuid,i)}linkBehaviorRef(e,t){let i=t.descriptor.key,r={entity:e,ref:t},n=this.behaviorEntityIndex.get(i);n||(n=new Set,this.behaviorEntityIndex.set(i,n)),n.add(r);let o=this.behaviorSystemByKey.get(i);if(!o&&!this.registeredSystemKeys.has(i)){let a=t.descriptor.systemFactory({world:this.world,scene:this.scene,wasmStage:this.wasmStage,getBehaviorLinks:l=>this.behaviorEntityIndex.get(l)??s.EMPTY_BEHAVIOR_LINKS,createEntity:dt,getGlobals:v});o=a,this.behaviorSystems.push(a),this.behaviorSystemByKey.set(i,a),this.registeredSystemKeys.add(i)}return o?.attach?.(r),r}unlinkBehaviorLink(e){let t=e.ref?.descriptor?.key;if(!t)return;this.behaviorSystemByKey.get(t)?.detach?.(e);let i=this.behaviorEntityIndex.get(t);i&&(i.delete(e),i.size===0&&this.behaviorEntityIndex.delete(t))}syncBehaviorLinks(e){this.unregisterBehaviorLinks(e),this.registerBehaviorLinks(e)}attachBehaviorLink(e,t){if(!this.world||!this.scene||!e?.uuid)return!1;let i=this.behaviorLinksByUuid.get(e.uuid)??[];return i.some(r=>r.ref===t)?!1:(i.push(this.linkBehaviorRef(e,t)),this.behaviorLinksByUuid.set(e.uuid,i),!0)}detachBehaviorLink(e,t){let i=this.behaviorLinksByUuid.get(e?.uuid);if(!i)return!1;let r=i.findIndex(o=>o.ref===t);if(r===-1)return!1;let[n]=i.splice(r,1);return n&&this.unlinkBehaviorLink(n),i.length===0&&this.behaviorLinksByUuid.delete(e.uuid),!0}unregisterBehaviorLinks(e){let t=this.behaviorLinksByUuid.get(e?.uuid);if(t){for(let i of t)this.unlinkBehaviorLink(i);this.behaviorLinksByUuid.delete(e.uuid)}}};var xs="Stage",tt=class extends ze{type=xs;state={...ci};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=Es(),this.cameraDelegate=new $e(this),this.loadingDelegate=new Xe,this.entityModelDelegate=new Je,this.entityDelegate=new et(this.loadingDelegate,this.entityModelDelegate);let t=qi(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 xr(0,0,0)}setState(){let{backgroundColor:e,backgroundImage:t}=this.state,i=e instanceof Er?e:new Er(e);di(i),ui(t),pi(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 Be(e,r,this.state);let n=this.gravity??new xr(0,0,0);if(this.world=await Ae.create(n,this.state.physicsRate),this.scene.setup(),this.cameraManagerRef&&this.rendererManager){await this.scene.setupCameraManager(this.scene.scene,this.cameraManagerRef,this.rendererManager);let a=this.cameraManagerRef.primaryCamera;a&&(this.rendererManager.setPostProcessingEffects(this.state.postProcessingEffects??[]),this.rendererManager.setupPostProcessing(this.scene.scene,a.camera)),this.rendererManager.startRenderLoop(()=>{this.cameraManagerRef?.render(this.scene.scene)})}else await this.scene.setupCamera(this.scene.scene,r);let o=this.resolveRenderer(r);await z.configureGLTFRuntime({renderer:o,...Le(this.state.assetLoaders?.gltf)}),this.entityModelDelegate.attach(this.scene,a=>this.entityDelegate.handleLateModelReady(a)),this.renderStrategy=new be,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 Ye(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;E("behaviorSystems",()=>{for(let n of this.entityDelegate.behaviorSystems)n.update(void 0,t)}),E("entityLoop",()=>{for(let n of this.entityDelegate.childrenMap.values()){let o=this.childUpdateParams;o.delta=e.delta,o.inputs=e.inputs,o.globals=e.globals,o.camera=e.camera,o.stage=e.stage,o.game=e.game,o.me=n,n.nodeUpdate(o);let a=n;a.transformStore&&fi(a,a.transformStore),n.markedForRemoval&&this.entityDelegate.removeEntityByUuid(n.uuid)}}),E("worldUpdate",()=>{i.update(e)}),E("behaviorPostUpdate",()=>{for(let n of this.entityDelegate.behaviorSystems)n.postUpdate?.(void 0,t)}),E("syncRenderPoses",()=>{Yi({_childrenMap:this.entityDelegate.childrenMap,_world:i})}),E("renderStrategy",()=>{this.renderStrategy?.update(i.interpolationAlpha)}),E("camera",()=>{this.cameraManagerRef?this.cameraManagerRef.update(t):this.cameraRef?.update(t)}),E("scene",()=>{r.update({delta:t})}),Ai()}outOfLoop(){this.debugUpdate()}debugUpdate(){ae()&&(ht("debugUpdate"),this.debugDelegate?.update(),mt())}_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,hi(),I(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 Ms}from"valtio/vanilla";import{Vector3 as Ts}from"three";var Ds={backgroundColor:ge,backgroundImage:null,inputs:{p1:["gamepad-1","keyboard"],p2:["gamepad-2","keyboard"]},gravity:new Ts(0,0,0),variables:{}},A=Ms({...Ds});function Mr(s){let e=Rs(),t={};return typeof s[0]=="object"&&(t=s.shift()??{}),[{...e,...t},...s]}function Rs(){return{backgroundColor:A.backgroundColor,backgroundImage:A.backgroundImage??null,inputs:A.inputs?{...A.inputs}:void 0,gravity:A.gravity,variables:A.variables?{...A.variables}:void 0}}var It=class{wrappedStage;options=[];_pendingEntities=[];setupCallbacks=[];updateCallbacks=[];destroyCallbacks=[];pendingLoadingCallbacks=[];eventDelegate=new Wt;inputConfig=null;onInputConfigChanged=null;constructor(e){this.options=e,this.wrappedStage=null;let t=this.options[0];z.prepareGLTFRuntime(Le(t?.assetLoaders?.gltf))}setInputConfiguration(...e){return this.inputConfig=jt(...e),this.onInputConfigChanged&&this.onInputConfigChanged(),this}async load(e,t,i){fe.entities=[];let r=[...this.options,...this._pendingEntities];this._pendingEntities=[],this.wrappedStage=new tt(r),this.wrappedStage.wrapperRef=this,this.pendingLoadingCallbacks.forEach(c=>{this.wrappedStage.onLoading(c)}),this.pendingLoadingCallbacks=[];let n=t instanceof C?t.cameraRef:t;await this.wrappedStage.load(e,n,i);let o=null,a=!1,l=()=>{if(a=!1,!o?.length){o=null;return}let c=o;o=null,fe.entities=[...fe.entities,...c]};this.wrappedStage.onEntityAdded(c=>{if(K(c.options))return;let d=this.wrappedStage.buildEntityState(c);o||(o=[]),o.push(d),a||(a=!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 C?e.cameraRef:e;return this.wrappedStage?.addCamera(i,t)??null}removeCamera(e){return e instanceof C?this.wrappedStage?.removeCamera(e.cameraRef)??!1:this.wrappedStage?.removeCamera(e)??!1}setActiveCamera(e){return e instanceof C?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),M.emit(e,t)}listen(e,t){return this.eventDelegate.listen(e,t)}dispose(){this.eventDelegate.dispose()}};function Dd(...s){let e=Mr(s);return new It([...e])}export{Is as a,ye as b,q as c,K as d,_ as e,ve as f,be as g,to as h,y as i,k as j,Pe as k,F as l,G as m,X as n,J as o,ee as p,te as q,L as r,_e as s,C as t,Ma as u,Oa as v,un as w,It as x,Dd as y};
@@ -1 +0,0 @@
1
- import{b as V,c as k,d as D}from"./chunk-BQRMYLYD.js";import{d as a,h as f,j as b,l as g,o as S,q as u,r as v,s as w,t as P,v as E,w as x,x as C}from"./chunk-GPCSX3M6.js";function B(){return new Promise(t=>{let e=new MessageChannel;e.port1.onmessage=()=>t(),e.port2.postMessage(void 0)})}async function I(t,e,i={}){let n=Math.max(1,i.batchSize??5),o=0;for(let s of t.entries)await e(s),o+=1,o%n===0&&await B();return o%n!==0&&await B(),{spawned:o}}import{subscribe as R}from"valtio/vanilla";import{announceBridgeReady as M,getZylemBridge as d}from"@zylem/bridge";var c="custom",p=new Set;function O(t){if(t!==c){c=t;for(let e of p)e(c)}}function Y(t){return p.add(t),t(c),()=>{p.delete(t)}}function h(t,e){return[t[0]*e.x,t[1]*e.y,t[2]*e.z]}function z(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 K(t,e){let{shape:i}=t,n=t.offset?h(t.offset,e):t.offset,o;switch(i.type){case"box":o={type:"box",halfExtents:h(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:z(i.vertices,e)};break;case"trimesh":o={type:"trimesh",vertices:z(i.vertices,e),indices:i.indices};break;case"heightfield":o={...i,scale:h(i.scale,e)};break;default:o=i;break}return{...t,shape:o,offset:n}}function G(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 L(t){if(!t.colliderScaleDirty)return!1;t.colliderScaleDirty=!1;let e=G(t);if(!e.length)return!1;let i=t.getScale(),n=e.map(r=>K(r,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 U(t){return(t?.group??t?.mesh)?.scale}function H(t){let i=(typeof t?.getScale=="function"?t.getScale():void 0)??t?.scale??U(t)??{};return{x:i.x??1,y:i.y??1,z:i.z??1}}function de(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 y(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:D(n),quaternion:{x:n.x,y:n.y,z:n.z,w:n.w},scale:H(t)}}function N(t,e){if(typeof t?.setScale=="function"){t.setScale(e.x,e.y,e.z);return}U(t)?.set?.(e.x,e.y,e.z)}function $(t){!t||typeof t.getScale!="function"||L(t)}function Q(t,e){if(!t)return!1;let i=e.quaternion??(e.rotation?k(e.rotation):void 0),n=!1;return(e.position||i)&&typeof t.setPose=="function"&&(n=t.setPose({position:e.position,rotation:i})),e.scale&&(N(t,e.scale),n=!0),n}function W(t){let e=t?.constructor?.type;return e?String(e).replace("Symbol(","").replace(")",""):"Unknown"}function j(t){let e=t;if(!e?.uuid)return;let i=d().channel;if(!i.hasSubscribers("entity:upsert"))return;let n=y(t);i.queue("entity:upsert",[{uuid:e.uuid,name:e.name||"Unnamed",type:W(t),position:n.position,rotation:n.rotation,scale:n.scale,quaternion:n.quaternion}])}function ue(t,e){d().channel.send("game:notice",{level:t,message:e})}function F(t,e,i){let n=[...new Set(t.swatches.map(r=>r.source))],o=[...new Set(e.map(r=>r.uuid))],s=o.length===1?i(o[0])||"entity":`${o.length} entities`;return`Apply ${n.join(", ")} to ${s}`}function Z(t,e){return!e||t.length!==e.length?!1:t.every((i,n)=>i===e[n])}function _(t,e){switch(e){case"add":v(t);break;case"subtract":w(t);break;case"toggle":for(let i of t)P(i);break;default:u(t);break}}function J(t,e){return t.on.bind(t)("camera:view:set",({preset:n})=>e(n))}var A=class{channel;unsubscribes=[];host=null;editorKnown={};applyingSceneOperation=!1;constructor(){this.channel=d().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})=>{b(n)}),this.channel.on("playback:set",({paused:n})=>{this.editorKnown.paused=n,f(n)}),this.channel.on("entity:select",({uuid:n,uuids:o,mode:s})=>{o?_(o,s??"replace"):S(n),this.editorKnown.selectedUuid=a.selectedEntityId,this.editorKnown.selectedUuids=[...a.selectedEntityIds]}),this.channel.on("entity:focus",({uuid:n})=>{V(n)}),this.channel.on("entity:transform",({uuid:n,position:o,rotation:s,quaternion:r,scale:m})=>{let l=this.host?.resolveEntity(n);if(!l)return;let q=y(l);if(Q(l,{position:o,rotation:s,quaternion:r,scale:m}),m&&$(l),j(l),this.applyingSceneOperation)return;let T=y(l);this.channel.send("scene:operation",{opId:`tx-${n}-${Date.now().toString(36)}`,kind:"transform",label:`Set ${l.name||"entity"} transform`,entries:[{uuid:n,before:q,after:T}]})}),this.channel.on("entity:create",({typeId:n,props:o,pose:s})=>{this.host?.createEntity?.(n,o,s)}),this.channel.on("level:load",({buffer:n})=>{this.loadLevel(n)}),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})=>{C(n,o??null)}),this.channel.on("snap:set",n=>{E(n)}),this.channel.on("grid:set",({visible:n})=>{x(n)}),this.channel.on("stage:variable:set",({key:n,value:o})=>{this.host?.setStageVariable?.(n,o)}),this.channel.on("pick:mode:set",({enabled:n})=>{g(n)}),this.channel.on("entity:pick",({requestId:n,ndc:o})=>{let s=this.host?.pickEntity?.(o)??null;this.channel.send("entity:pick:result",{requestId:n,hit:s})}),this.channel.on("entity:apply-swatch",n=>{this.handleApplySwatch(n)}),this.channel.on("cutscene:load",n=>this.host?.cutscene?.load(n)),this.channel.on("cutscene:play",({from:n})=>this.host?.cutscene?.play(n)),this.channel.on("cutscene:pause",()=>this.host?.cutscene?.pause()),this.channel.on("cutscene:stop",()=>this.host?.cutscene?.stop()),this.channel.on("cutscene:seek",({time:n})=>this.host?.cutscene?.seek(n)),this.channel.on("cutscene:unload",()=>this.host?.cutscene?.unload()),this.channel.on("camera:pose:get",({requestId:n})=>{let o=this.host?.cameraPose?.();o&&this.channel.send("camera:pose",{requestId:n,...o})}),J(this.channel,O),R(a,()=>this.publishDebugStateChanges())),this.publishDebugStateChanges(),M(i)}publishCutsceneStatus(e){this.channel.queue("cutscene:status",e)}publishCutsceneView(e){this.channel.queue("cutscene:view",e)}disconnect(){for(let e of this.unsubscribes)e();this.unsubscribes=[],this.host=null,this.editorKnown={}}handleApplySwatch(e){let i=e.opId??`swatch-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`,n=this.host?.applySwatches?this.host.applySwatches({...e,opId:i}):{results:e.uuids.flatMap(s=>e.swatches.map(r=>({uuid:s,kind:r.kind,source:r.source,ok:!1,reason:"entity-not-found"}))),entries:[]},o=[...new Set(n.entries.map(s=>s.uuid))];e.select&&o.length>0&&u(o),n.entries.length>0&&!this.applyingSceneOperation&&this.channel.send("scene:operation",{opId:i,kind:"swatch",label:F(e,n.entries,s=>this.host?.resolveEntity(s)?.name),entries:n.entries}),this.channel.send("entity:swatch-applied",{opId:i,results:n.results})}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||!Z(a.selectedEntityIds,this.editorKnown.selectedUuids))&&(this.editorKnown.selectedUuid=a.selectedEntityId,this.editorKnown.selectedUuids=[...a.selectedEntityIds],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)}async loadLevel(e){let{spawned:i}=await I(e,n=>{this.host?.createEntity?.(n.typeId,void 0,n.pose)});this.publishNotice("info",`Streamed ${i} level entries`)}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 pe(t){d().channel.send("scene:operation",t)}export{Y as a,I as b,L as c,H as d,de as e,y as f,$ as g,Q as h,W as i,ue as j,A as k,pe as l};