@zylem/game-lib 0.9.6 → 0.9.8
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.
- package/dist/actions.d.ts +3 -3
- package/dist/api/game-lib.api.json +99183 -42019
- package/dist/api/game-lib.api.md +3822 -706
- package/dist/api/game-lib.d.ts +8703 -784
- package/dist/api/game-lib.typedoc.json +336362 -193038
- package/dist/audio.js +1 -1
- package/dist/behavior/action/fighting.d.ts +1 -0
- package/dist/behavior/action/fighting.js +1 -0
- package/dist/behavior/action/pinball.d.ts +1 -0
- package/dist/behavior/action/pinball.js +1 -0
- package/dist/behavior/action/platform.d.ts +1 -0
- package/dist/behavior/action/platform.js +1 -0
- package/dist/behavior/action/rhythm.d.ts +1 -0
- package/dist/behavior/action/rhythm.js +1 -0
- package/dist/behavior/action/shooter/first-person.d.ts +1 -0
- package/dist/behavior/action/shooter/first-person.js +1 -0
- package/dist/behavior/action/shooter/shoot-em-up.d.ts +1 -0
- package/dist/behavior/action/shooter/shoot-em-up.js +1 -0
- package/dist/behavior/action/shooter.d.ts +1 -0
- package/dist/behavior/action/shooter.js +1 -0
- package/dist/behavior/action/stealth.d.ts +1 -0
- package/dist/behavior/action/stealth.js +1 -0
- package/dist/behavior/action/survival.d.ts +1 -0
- package/dist/behavior/action/survival.js +1 -0
- package/dist/behavior/action-adventure.d.ts +1 -0
- package/dist/behavior/action-adventure.js +1 -0
- package/dist/behavior/action.d.ts +1 -0
- package/dist/behavior/action.js +1 -0
- package/dist/behavior/genre-map.d.ts +1 -0
- package/dist/behavior/genre-map.js +1 -0
- package/dist/behavior/mechanics.d.ts +1 -0
- package/dist/behavior/mechanics.js +1 -0
- package/dist/behavior/puzzle/physics.d.ts +1 -0
- package/dist/behavior/puzzle/physics.js +1 -0
- package/dist/behavior/puzzle/tile-matching.d.ts +1 -0
- package/dist/behavior/puzzle/tile-matching.js +1 -0
- package/dist/behavior/puzzle.d.ts +1 -0
- package/dist/behavior/puzzle.js +1 -0
- package/dist/behavior/role-playing/action-rpg.d.ts +1 -0
- package/dist/behavior/role-playing/action-rpg.js +1 -0
- package/dist/behavior/role-playing/monster-taming.d.ts +1 -0
- package/dist/behavior/role-playing/monster-taming.js +1 -0
- package/dist/behavior/role-playing/tactical-rpg.d.ts +1 -0
- package/dist/behavior/role-playing/tactical-rpg.js +1 -0
- package/dist/behavior/role-playing/turn-based.d.ts +1 -0
- package/dist/behavior/role-playing/turn-based.js +1 -0
- package/dist/behavior/role-playing.d.ts +1 -0
- package/dist/behavior/role-playing.js +1 -0
- package/dist/behavior/simulation/life.d.ts +1 -0
- package/dist/behavior/simulation/life.js +1 -0
- package/dist/behavior/simulation/vehicle/racing.d.ts +1 -0
- package/dist/behavior/simulation/vehicle/racing.js +1 -0
- package/dist/behavior/simulation/vehicle.d.ts +1 -0
- package/dist/behavior/simulation/vehicle.js +1 -0
- package/dist/behavior/simulation.d.ts +1 -0
- package/dist/behavior/simulation.js +1 -0
- package/dist/behavior/sports/golf.d.ts +1 -0
- package/dist/behavior/sports/golf.js +1 -0
- package/dist/behavior/sports/racing.d.ts +1 -0
- package/dist/behavior/sports/racing.js +1 -0
- package/dist/behavior/sports/racket.d.ts +1 -0
- package/dist/behavior/sports/racket.js +1 -0
- package/dist/behavior/sports/skate.d.ts +1 -0
- package/dist/behavior/sports/skate.js +1 -0
- package/dist/behavior/sports.d.ts +1 -0
- package/dist/behavior/sports.js +1 -0
- package/dist/behavior/strategy/real-time-tactics.d.ts +1 -0
- package/dist/behavior/strategy/real-time-tactics.js +1 -0
- package/dist/behavior/strategy/tower-defense.d.ts +1 -0
- package/dist/behavior/strategy/tower-defense.js +1 -0
- package/dist/behavior/strategy/turn-based-tactics.d.ts +1 -0
- package/dist/behavior/strategy/turn-based-tactics.js +1 -0
- package/dist/behavior/strategy.d.ts +1 -0
- package/dist/behavior/strategy.js +1 -0
- package/dist/behavior.d.ts +34 -0
- package/dist/bridge.d.ts +16 -4
- package/dist/bridge.js +1 -1
- package/dist/catalog.d.ts +1 -1
- package/dist/catalog.js +1 -1
- package/dist/chunk-26EJFYDX.js +1 -0
- package/dist/chunk-2NO4YCLR.js +1 -0
- package/dist/chunk-3LXDHDJB.js +1 -0
- package/dist/chunk-4DAITCJS.js +1 -0
- package/dist/{chunk-Y23IJJPD.js → chunk-5NQGXW75.js} +1 -1
- package/dist/chunk-5WRFDAZN.js +1 -0
- package/dist/{chunk-OCQ7A5IK.js → chunk-B6GDESCB.js} +1 -1
- package/dist/chunk-BIZOIGCZ.js +1 -0
- package/dist/chunk-BJYXY2FB.js +1 -0
- package/dist/chunk-CI7A5N6G.js +1 -0
- package/dist/chunk-GQXYD2JG.js +1 -0
- package/dist/{chunk-KIFB427K.js → chunk-ICJ2E2OV.js} +1 -1
- package/dist/chunk-NPA6GUGE.js +24 -0
- package/dist/chunk-SIRFF4DY.js +1 -0
- package/dist/chunk-T6O2SGH5.js +1 -0
- package/dist/chunk-UNCP6V7I.js +1 -0
- package/dist/chunk-Y5IU6IA5.js +1 -0
- package/dist/chunk-YFXNZ2RS.js +1 -0
- package/dist/chunk-YW2GTHCV.js +19 -0
- package/dist/chunk-YWH5HQDT.js +1 -0
- package/dist/cinematics.d.ts +7 -6
- package/dist/core.d.ts +20 -17
- package/dist/core.js +1 -1
- package/dist/{debug-state-DhVkY2aM.d.ts → debug-state-JRneI6c2.d.ts} +2 -2
- package/dist/debug.d.ts +28 -126
- package/dist/debug.js +1 -1
- package/dist/{entity-DC0P747T.d.ts → entity-CY75JJSw.d.ts} +78 -4
- package/dist/{entity-type-map-B0S5cfv7.d.ts → entity-type-map-BMaPY8cd.d.ts} +2 -2
- package/dist/entity.d.ts +5 -5
- package/dist/entity.js +1 -1
- package/dist/fbx-loader-SDI6QYTS.js +1 -0
- package/dist/game-default-AF5QFXSD.js +1 -0
- package/dist/{game-mu6OSCrq.d.ts → game-uQd7k6-m.d.ts} +3 -3
- package/dist/gaussian-splat-loader-ACFJKCCL.js +1 -0
- package/dist/geometry-mesh-loader-XDJV77TU.js +1 -0
- package/dist/graphics.d.ts +3 -3
- package/dist/graphics.js +1 -1
- package/dist/{material-CxxAyJYp.d.ts → material-D1IVeQc5.d.ts} +48 -2
- package/dist/obj-loader-SI5RVY24.js +1 -0
- package/dist/placement-session-BNQoL7Jb.d.ts +82 -0
- package/dist/placement.d.ts +52 -0
- package/dist/placement.js +1 -0
- package/dist/public.d.ts +12 -10
- package/dist/public.js +1 -1
- package/dist/sog-loader-BZFMQ3ZB.js +1 -0
- package/dist/{stage-B_KdSEK6.d.ts → stage-Dez16Gxm.d.ts} +186 -16
- package/dist/transform-gizmo-DappLQ9w.d.ts +123 -0
- package/dist/usd-loader-PCBATNPM.js +1 -0
- package/dist/web-components.d.ts +9 -8
- package/dist/{zylem-camera-CWhIGXlW.d.ts → zylem-camera-BA3VPFlS.d.ts} +9 -0
- package/package.json +150 -7
- package/dist/chunk-47HAZZWF.js +0 -1
- package/dist/chunk-5V52N34T.js +0 -1
- package/dist/chunk-6FGXC4T6.js +0 -19
- package/dist/chunk-FUZDTRCU.js +0 -1
- package/dist/chunk-P6IOYQHU.js +0 -1
- package/dist/chunk-QB3NL7VQ.js +0 -1
- package/dist/chunk-RPMV7GDX.js +0 -24
- package/dist/chunk-VKWJHFUR.js +0 -1
- package/dist/chunk-VXE3CV3K.js +0 -1
- package/dist/chunk-YRHRMVHS.js +0 -1
- package/dist/game-default-VUMUMTXA.js +0 -1
- package/dist/level-types-D10LiOcn.d.ts +0 -91
package/dist/chunk-P6IOYQHU.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{b as di,c as Ai,f as Oi}from"./chunk-47HAZZWF.js";import{c as Z,j as we}from"./chunk-2HSR5XDQ.js";import{a as pi,b as C,c as be,d as mi,f as Ct,m as St,o as X}from"./chunk-VKWJHFUR.js";import{a as fi,c as vt,d as bt,e as gi,f as Ce,g as yi}from"./chunk-273CUPEO.js";import{A as ve,b as ft,d as u,e as si,i as L,k as ye,o as gt,q as oi,s as ai,t as li,u as T,y as ci,z as yt}from"./chunk-UM5VNQPY.js";import{a as xe,b as Di}from"./chunk-WBQ5TNRZ.js";import{b as Pe,d as Ti}from"./chunk-FUZDTRCU.js";import{C as ki,a as J,k as Si,l as wi,m as Pi,n as xi,o as N,p as Ei,q as ee,t as Mi,u as Pt}from"./chunk-VXE3CV3K.js";import{a as wt,b as bi,g as H,h as Se,i as Ci}from"./chunk-6FGXC4T6.js";import{a as hi,b as R}from"./chunk-AIQ6IVT5.js";import{g as te}from"./chunk-UUOPT2N4.js";import{a as Ee,b as Ri,c as Me,d as _i,e as Bi,f as zi,g as Li,m as U}from"./chunk-D2PATZCC.js";import{c as ge,d as mt,j as b}from"./chunk-4QLJUQSJ.js";import{c as x,i as vi,j as p}from"./chunk-7WRQ2UAN.js";import{a as Vi}from"./chunk-BH53MBAZ.js";import{l as ui}from"./chunk-UG22Z42P.js";import{Vector2 as Hi,RenderTarget as mn,HalfFloatType as fn}from"three";import{WebGPURenderer as gn,RenderPipeline as yn}from"three/webgpu";import{pass as vn,renderOutput as Ni,screenCoordinate as bn,vec2 as xt,vec4 as qi,fract as Ui,sin as ji,dot as Wi,texture as Cn,uniform as Sn}from"three/tsl";import{setConsoleFunction as hn,getConsoleFunction as pn}from"three";var Ii="THREE.Abstract function.",Fi=!1,Gi=!1;function Zi(){if(Fi)return;Fi=!0;let s=pn();hn((e,t,...i)=>{if(e==="warn"&&t===Ii){Gi||(Gi=!0,console.warn(`${Ii} (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 Ki={x:0,y:0,width:1,height:1},wn=1/20;async function Wo(){if(!("gpu"in navigator))return!1;try{return await navigator.gpu.requestAdapter()!==null}catch{return!1}}var ke=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 Hi(window.innerWidth,window.innerHeight)}get initialized(){return this._initialized}get isWebGPU(){return!0}async initRenderer(){this._initialized||(Zi(),this.renderer=new gn({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 yn(this.renderer),r=vn(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=Ni(n),a=this._transition;if(a)try{o=qi(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(xn()),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 Hi;this.renderer.getDrawingBufferSize(r);let n=new mn(Math.max(1,r.x),Math.max(1,r.y),{type:fn}),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:Sn(0),fromNode:Ni(Cn(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,wn);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&&Pn(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 Pn(s){return s.x===0&&s.y===0&&s.width===1&&s.height===1}function xn(){let s=bn.xy,e=Ui(ji(Wi(s,xt(12.9898,78.233))).mul(43758.5453)),t=Ui(ji(Wi(s.add(xt(13,7)),xt(12.9898,78.233))).mul(43758.5453)),i=e.sub(t).mul(1/255);return qi(i,i,i,0)}function ie(s){return s?.category??"none"}function re(s){let e=ie(s);return e==="environment"||e==="pack"}function A(s){return s.isInstanced===!0||s.isBundled===!0}import{BundleGroup as En}from"three/webgpu";var De=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 En,t.name=`bundle:${e}`,t.static=!0,this.bundles.set(e,t),this.scene&&this.scene.add(t),t)}};import{InstancedMesh as Qi,Matrix4 as ne,Vector3 as $i,Quaternion as Mn}from"three";var se=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}:${wt(e.dimensions)}`,mat:e.materialPath||"none",shader:e.shaderType||"standard",color:e.colorHex??16777215};return bi(wt(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 ne;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 ne,i=new $i,r=new Mn,n=new $i(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(Si(c)){t.makeScale(0,0,0),o.instancedMesh.setMatrixAt(l,t),a=!0;continue}let d=o.dirtyIndices.has(l),h=!!c.body;if(!(!d&&!h)){if(!d&&h){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=xe(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 Qi(t,i,r);n.count=0,n.frustumCulled=!1;let o=new ne().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 Qi(e.geometry,e.material,t);i.count=e.instancedMesh.count,i.frustumCulled=!1;let r=new ne;for(let o=0;o<e.capacity;o++)e.instancedMesh.getMatrixAt(o,r),i.setMatrixAt(o,r);let n=new ne().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 Te=class{bundles=new De;instances=new se;setScene(e){this.bundles.setScene(e),this.instances.setScene(e)}register(e){let t=ie(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=se.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()}};import{BoxGeometry as _t,BufferGeometry as or,DoubleSide as ar,EdgesGeometry as Vn,Float32BufferAttribute as lr,Group as Bt,Line as In,LineBasicMaterial as cr,LineSegments as Fn,Mesh as W,MeshBasicMaterial as er,MeshStandardMaterial as Be,OctahedronGeometry as Gn,Raycaster as Zn,SphereGeometry as tr}from"three";function oe(s,e){return s.x*e.x+s.y*e.y+s.z*e.z}function O(s,e){return{x:s.y*e.z-s.z*e.y,y:s.z*e.x-s.x*e.z,z:s.x*e.y-s.y*e.x}}function kn(s,e){return{x:s.x-e.x,y:s.y-e.y,z:s.z-e.z}}function Dn(s,e){return{x:s.x*e,y:s.y*e,z:s.z*e}}function Yi(s){return Math.hypot(s.x,s.y,s.z)}function Tn(s){let e=Yi(s);return e<1e-5?null:Dn(s,1/e)}function Rn(s,e){return Math.abs(s.x-e.x)<=1e-5&&Math.abs(s.y-e.y)<=1e-5&&Math.abs(s.z-e.z)<=1e-5}function _n(s,e,t){let i=s.normal,r=e.normal,n=t.normal,o=oe(i,O(r,n));if(Math.abs(o)<1e-8)return null;let a=O(r,n),l=O(n,i),c=O(i,r);return{x:(s.distance*a.x+e.distance*l.x+t.distance*c.x)/o,y:(s.distance*a.y+e.distance*l.y+t.distance*c.y)/o,z:(s.distance*a.z+e.distance*l.z+t.distance*c.z)/o}}function Bn(s,e){for(let t of e)if(oe(t.normal,s)-t.distance>1e-5)return!1;return!0}function zn(s,e,t){let i=s[e[0]],r=O(t,{x:1,y:0,z:0});Yi(r)<1e-8&&(r=O(t,{x:0,y:1,z:0}));let n=Tn(r);if(!n)return[...e];let o=O(t,n),a=e.map(l=>{let c=kn(s[l],i);return{index:l,angle:Math.atan2(oe(c,o),oe(c,n))}});return a.sort((l,c)=>l.angle-c.angle),a.map(l=>l.index)}function j(s){if(s.length<4)return null;let e=[];for(let i=0;i<s.length;i+=1)for(let r=i+1;r<s.length;r+=1)for(let n=r+1;n<s.length;n+=1){let o=_n(s[i],s[r],s[n]);!o||!Bn(o,s)||e.some(a=>Rn(a,o))||e.push(o)}if(e.length<4)return null;let t=[];for(let i=0;i<s.length;i+=1){let r=s[i],n=[];for(let a=0;a<e.length;a+=1)Math.abs(oe(r.normal,e[a])-r.distance)<=1e-5&&n.push(a);if(n.length<3)continue;let o=zn(e,n,r.normal);o.length<3||t.push({planeIndex:i,indices:o})}return t.length<4?null:{vertices:e,faces:t}}import{Vector3 as Et}from"three";var Ln=0;function An(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=(Ln-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 On(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 Mt(s,e,t){let i=On(e,t);return i<=0?s.clone():s.clone().add(t.clone().normalize().multiplyScalar(i))}function ae(s,e,t,i){let r=An(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?Mt(a,i,n):a,normal:n}}function Xi(s){let e=[];for(let t of s){let i=j(t.planes);if(!i)continue;let r=new Float32Array(i.vertices.length*3);i.vertices.forEach((n,o)=>{r[o*3]=n.x,r[o*3+1]=n.y,r[o*3+2]=n.z}),e.push(r)}return e}function kt(s){return s===C.top?"top":s===C.side?"side":null}function Re(s,e,t){let i=s.origin[e],r=s.direction[e];if(Math.abs(r)<1e-8)return null;let n=(t-i)/r;return n<0?null:{x:s.origin.x+s.direction.x*n,y:s.origin.y+s.direction.y*n,z:s.origin.z+s.direction.z*n}}function V(s,e){return Math.round(s/e)*e}function Dt(s,e,t,i){let r=Math.max(i,1e-4),n=(h,m)=>{let v=V(Math.min(h,m),r),Y=V(Math.max(h,m),r);return Y-v<r*.5&&(Y=v+r),[v,Y]};if(s==="top"){let[h,m]=n(e.x,t.x),[v,Y]=n(e.z,t.z),ni=V(e.y,r);return{min:{x:h,y:ni,z:v},max:{x:m,y:ni+r,z:Y}}}let[o,a]=n(e.y,t.y),[l,c]=n(e.z,t.z),d=V(e.x,r);return{min:{x:d,y:o,z:l},max:{x:d+r,y:a,z:c}}}function Ji(s,e,t){if(s==="top"){let a=t.x-e.x,l=t.z-e.z,c=Math.hypot(a,l);if(c<1e-6)return null;let d={x:-l/c,y:0,z:a/c};return{normal:d,distance:d.x*e.x+d.z*e.z}}let i=t.y-e.y,r=t.z-e.z,n=Math.hypot(i,r);if(n<1e-6)return null;let o={x:0,y:-r/n,z:i/n};return{normal:o,distance:o.y*e.y+o.z*e.z}}function _e(s,e){return e<=0?{x:s.x,y:s.y,z:s.z}:{x:V(s.x,e),y:V(s.y,e),z:V(s.z,e)}}var Hn="Draw, clip, and vertex edit need the Top or Side view.",dr=13157044,Nn=14998992,ir=250,Un=[{color:16724787,axis:"x"},{color:3394662,axis:"y"},{color:3377407,axis:"z"}],ur=null;function Ea(){return ur}function Tt(s){ur=s}function Rt(s){return{origin:{x:s.origin.x,y:s.origin.y,z:s.origin.z},direction:{x:s.direction.x,y:s.direction.y,z:s.direction.z}}}function zt(s,e){let t=s.size;return{x:t?.x??e.x,y:t?.y??e.y,z:t?.z??e.z}}function jn(s,e){return s.solids.some(t=>t.id===e)?"solid":s.doodads.some(t=>t.id===e)?"doodad":s.entities.some(t=>t.id===e)?"entity":null}function Wn(s){Array.isArray(s)?s.forEach(e=>e.dispose()):s.dispose()}function rr(s){s.traverse(e=>{let t=e;t.geometry?.dispose(),t.material&&Wn(t.material)})}function qn(s){let e=s.clone(!0);return e.traverse(t=>{let i=t;if(i.geometry&&(i.geometry=i.geometry.clone()),!i.material)return;let n=(Array.isArray(i.material)?i.material:[i.material]).map(o=>o.clone());i.material=Array.isArray(i.material)?n:n[0]}),e}function Kn(s,e){let t=Z(s);if(t)try{let r=t.create({position:{x:0,y:0,z:0},props:e});if(r&&typeof r.then!="function"){let n=r.group??r.mesh;if(n)return qn(n)}}catch{}let i=zt(e,{x:1,y:1,z:1});return new W(new _t(i.x,i.y,i.z),new Be({color:13157044}))}function nr(s,e){let t=e.position??{x:0,y:0,z:0};s.position.set(t.x,t.y,t.z),e.quaternion?s.quaternion.set(e.quaternion.x,e.quaternion.y,e.quaternion.z,e.quaternion.w):e.rotation&&s.rotation.set(e.rotation.x,e.rotation.y,e.rotation.z),e.scale&&s.scale.set(e.scale.x,e.scale.y,e.scale.z)}function Qn(s){return new Be({color:s?Nn:dr,side:ar})}function sr(s){let e=new Bt;for(let t of Un){let i={x:s.x,y:s.y,z:s.z},r={x:s.x,y:s.y,z:s.z};i[t.axis]-=ir,r[t.axis]+=ir;let n=new or;n.setAttribute("position",new lr([i.x,i.y,i.z,r.x,r.y,r.z],3));let o=new In(n,new cr({color:t.color,depthTest:!1}));o.frustumCulled=!1,o.renderOrder=20,e.add(o)}return e}function $n(s){let e=s.vertices.reduce((i,r)=>({x:i.x+r.x,y:i.y+r.y,z:i.z+r.z}),{x:0,y:0,z:0}),t=s.vertices.length;return{x:e.x/t,y:e.y/t,z:e.z/t}}function Yn(s){let e=[],t=[];for(let r of s.faces){let n=e.length/3;for(let o of r.indices){let a=s.vertices[o];e.push(a.x,a.y,a.z)}for(let o=1;o<r.indices.length-1;o+=1)t.push(n,n+o,n+o+1)}let i=new or;return i.setAttribute("position",new lr(e,3)),i.setIndex(t),i.computeVertexNormals(),i}var ze=class{constructor(e){this.host=e;this.root.name="level-preview"}root=new Bt;raycaster=new Zn;mounted=!1;generation=0;mode="edit";payload=null;drag=null;clipAnchor=null;ghost=null;bodyHandle=null;zoneIds=[];get isActive(){return this.payload!==null}get isEditing(){return this.payload!==null&&this.mode==="edit"}tick(){!this.payload||this.mounted||!this.host.getScene()||this.rebuild()}sync(e){this.mode="edit",this.payload=e,Tt(e.document),this.rebuild()}play(e){this.mode="play",this.payload={document:e,hiddenLayers:[],selectedIds:this.payload?.selectedIds??[],activeLayer:this.payload?.activeLayer??"solid",placement:null},Tt(e),this.rebuild()}close(){this.generation+=1,this.payload=null,this.drag=null,this.clipAnchor=null,Tt(null),this.teardownOwned(),this.unmount()}dispose(){this.close()}pointerDown(e){if(!this.payload)return!1;let t=L();if(t==="select")return this.host.publishSelect(this.pickId(e)),!0;if(t==="delete"){let i=this.pickId(e);return i&&this.host.publishGesture({kind:"delete",id:i}),!0}return t==="add"?(this.placeArmed(e),!0):t==="brush"||t==="clip"||t==="vertex"?(this.beginSolidGesture(t,e),!0):t==="translate"?this.beginTranslate(e):!1}pointerMove(e){if(!this.drag||this.drag.kind!=="brush")return;let t=this.viewPoint(this.drag.view,e);t&&this.showBrushGhost(Dt(this.drag.view,this.drag.start,t,this.gridStep()))}pointerUp(e){let t=this.drag;if(this.drag=null,this.clearGhost(),!t)return;if(t.kind==="brush"){let o=this.viewPoint(t.view,e)??t.start,a=Dt(t.view,t.start,o,this.gridStep());this.host.publishGesture({kind:"brush",min:a.min,max:a.max});return}if(t.kind==="vertex"){let o=this.viewPoint(t.view,e,t.plane);if(!o)return;this.host.publishGesture({kind:"vertex",brushId:t.brushId,vertexIndex:t.vertexIndex,position:_e(o,this.gridStep())});return}let i=this.translatePoint(t,e);if(!i)return;let r=_e(i,this.gridStep()),n={x:r.x-t.start.x,y:r.y-t.start.y,z:r.z-t.start.z};(t.view==="top"||t.view==="xz")&&(n.y=0),t.view==="side"&&(n.x=0),!(n.x===0&&n.y===0&&n.z===0)&&this.host.publishGesture({kind:"translate",id:t.id,layer:t.layer,delta:n})}rebuild(){let e=++this.generation;this.teardownOwned();let t=this.payload;if(!t||!this.ensureRoot()||(this.buildVisuals(),this.mode!=="play"))return;let i=Xi(t.document.solids);this.bodyHandle=i.length>0?this.host.spawnHulls(i):null,this.spawnZones(t.document,e).catch(r=>{console.error("Level triggers failed to spawn",r)})}buildVisuals(){let e=this.payload;if(!e)return;let t=new Set(this.mode==="play"?[]:e.hiddenLayers),i=new Set(e.selectedIds);if(this.mode==="edit"&&!t.has("solid"))for(let n of e.document.solids){let o=j(n.planes);if(!o)continue;let a=i.has(n.id),l=new W(Yn(o),Qn(a));l.userData.levelId=n.id,this.root.add(l),a&&this.root.add(sr($n(o))),i.has(n.id)&&L()==="vertex"&&this.addVertexHandles(n.id,o)}if(!t.has("doodad"))for(let n of e.document.doodads){let o=Kn(n.typeId,n.props);nr(o,n.pose),o.userData.levelId=n.id,this.root.add(o)}if(!t.has("entity"))for(let n of e.document.entities){let o=n.typeId==="zone"?this.triggerOutline(n.props):new W(new Gn(.3),new Be({color:14904020}));nr(o,n.pose),o.userData.levelId=n.id,this.root.add(o)}}addVertexHandles(e,t){let i=Math.max(this.gridStep()*.28,.08);t.vertices.forEach((r,n)=>{let o=new W(new tr(i,8,6),new er({color:16772744,depthTest:!1}));o.position.set(r.x,r.y,r.z),o.userData.levelId=e,o.userData.vertexIndex=n,o.renderOrder=10,this.root.add(o)})}triggerOutline(e){let t=zt(e,{x:2,y:2,z:2});return new Fn(new Vn(new _t(t.x,t.y,t.z)),new cr({color:4054167}))}async spawnZones(e,t){for(let i of e.entities){if(i.typeId!=="zone")continue;if(t!==this.generation)return;let r=await this.host.spawnZone({name:i.name,position:i.pose.position??{x:0,y:0,z:0},size:zt(i.props,{x:2,y:2,z:2})});if(t!==this.generation){r&&this.host.detach(r);return}r&&this.zoneIds.push(r)}}beginSolidGesture(e,t){let i=kt(this.host.cameraId());if(!i){this.host.publishNotice(Hn);return}let r=this.viewPoint(i,t);if(!r)return;if(e==="brush"){this.drag={kind:"brush",view:i,start:r};return}if(e==="clip"){if(!this.clipAnchor){this.clipAnchor=r,this.showClipMarker(r);return}let o=Ji(i,this.clipAnchor,r);this.clipAnchor=null,this.clearGhost();let a=this.selectedSolidId();o&&a&&this.host.publishGesture({kind:"clip",brushId:a,plane:o});return}let n=this.pick(t);if(n&&typeof n.vertexIndex=="number"){let o=this.vertexAt(n.id,n.vertexIndex);this.drag={kind:"vertex",brushId:n.id,vertexIndex:n.vertexIndex,view:i,plane:i==="top"?o?.y??0:o?.x??0};return}this.host.publishSelect(n?.id??null)}vertexAt(e,t){let i=this.payload?.document.solids.find(r=>r.id===e);return i?j(i.planes)?.vertices[t]??null:null}beginTranslate(e){let t=this.payload,i=t?.selectedIds[0];if(!t||!i)return!1;let r=jn(t.document,i);if(!r)return!1;let n=kt(this.host.cameraId())??"xz",o=this.translatePoint({kind:"translate",id:i,layer:r,view:n,start:{x:0,y:0,z:0}},e);return o&&(this.drag={kind:"translate",id:i,layer:r,view:n,start:_e(o,this.gridStep())}),!0}placeArmed(e){let t=this.payload?.placement;if(!t)return;let i=ae(e,this.host.physicsHit(e),{enabled:!0,translate:this.gridStep()});if(!i)return;let r={position:{x:i.position.x,y:i.position.y,z:i.position.z}};if(t.kind==="doodad"){this.host.publishGesture({kind:"doodad",typeId:t.typeId,pose:r,...t.props?{props:t.props}:{}});return}if(t.kind==="spawn"){this.host.publishGesture({kind:"spawn",pose:r});return}this.host.publishGesture({kind:"trigger",pose:r,size:t.size})}viewPoint(e,t,i=0){return Re(Rt(t),e==="top"?"y":"x",i)}translatePoint(e,t){let i=this.anchorOf(e.id);return e.view==="side"?Re(Rt(t),"x",i.x):Re(Rt(t),"y",(e.view==="top",i.y))}anchorOf(e){let t=this.payload?.document,i=t?.solids.find(o=>o.id===e);if(i){let o=j(i.planes);if(o&&o.vertices.length>0){let a=o.vertices.reduce((c,d)=>({x:c.x+d.x,y:c.y+d.y,z:c.z+d.z}),{x:0,y:0,z:0}),l=o.vertices.length;return{x:a.x/l,y:a.y/l,z:a.z/l}}}let r=t?.doodads.find(o=>o.id===e);return r?.pose.position?r.pose.position:t?.entities.find(o=>o.id===e)?.pose.position??{x:0,y:0,z:0}}selectedSolidId(){let e=this.payload;return e?e.selectedIds.find(t=>e.document.solids.some(i=>i.id===t))??null:null}pickId(e){return this.pick(e)?.id??null}pick(e){if(!this.mounted)return null;this.raycaster.set(e.origin,e.direction);let t=this.raycaster.intersectObjects(this.root.children,!0);for(let i of t){let r=i.object;for(;r;){let n=r.userData.vertexIndex,o=r.userData.levelId;if(typeof o=="string")return typeof n=="number"?{id:o,vertexIndex:n}:{id:o};r=r.parent}}return null}showBrushGhost(e){this.clearGhost();let t={x:e.max.x-e.min.x,y:e.max.y-e.min.y,z:e.max.z-e.min.z},i={x:(e.min.x+e.max.x)/2,y:(e.min.y+e.max.y)/2,z:(e.min.z+e.max.z)/2},r=new W(new _t(t.x,t.y,t.z),new Be({color:dr,transparent:!0,opacity:.35,depthWrite:!1,side:ar}));r.position.set(i.x,i.y,i.z);let n=new Bt;n.add(r),n.add(sr(i)),this.ghost=n,this.root.add(n)}showClipMarker(e){this.clearGhost();let t=new W(new tr(Math.max(this.gridStep()*.2,.06),8,6),new er({color:16772744,depthTest:!1}));t.position.set(e.x,e.y,e.z),this.ghost=t,this.root.add(t)}clearGhost(){this.ghost&&(this.root.remove(this.ghost),rr(this.ghost),this.ghost=null)}gridStep(){let e=T().translate;return e>0?e:1}ensureRoot(){let e=this.host.getScene();return e?(this.mounted||(e.add(this.root),this.mounted=!0),!0):!1}teardownOwned(){for(let e of this.zoneIds)this.host.detach(e);this.zoneIds=[],this.bodyHandle!==null&&(this.host.despawnHulls(this.bodyHandle),this.bodyHandle=null),this.clearGhost();for(let e of[...this.root.children])this.root.remove(e),rr(e)}unmount(){this.mounted&&(this.host.getScene()?.remove(this.root),this.mounted=!1)}};var Le=!1,E={},hr=0,pr=0,le=null;function mr(){return typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()}function Lt(){return Le?!0:(typeof globalThis<"u"&&globalThis.__ZYLEM_PROFILE_STAGE__===!0&&(Le=!0),Le)}function ka(s){Le=s,typeof globalThis<"u"&&(globalThis.__ZYLEM_PROFILE_STAGE__=s)}function At(s){Lt()&&(le=s,pr=mr())}function Ot(){if(!Lt()||le===null)return;let s=mr()-pr;E[le]=(E[le]??0)+s,le=null}function fr(){if(!Lt()||(hr++,hr%60!==0))return;let s=Object.values(E).reduce((t,i)=>t+(i??0),0),e=Object.keys(E).sort((t,i)=>(E[i]??0)-(E[t]??0)).map(t=>{let i=E[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(E))E[t]=0}function M(s,e){At(s);try{return e()}finally{Ot()}}var f={FirstPerson:"first-person",ThirdPerson:"third-person",SecondPerson:"second-person",Isometric:"isometric",Flat2D:"flat-2d",Fixed2D:"fixed-2d",TopDown:"top-down"};function Vt(s){switch(s){case f.Isometric:case f.TopDown:case f.Flat2D:case f.Fixed2D:return"orthographic";default:return"perspective"}}import{Vector3 as Xn,Quaternion as Jn,MathUtils as It}from"three";function Ae(){return{position:new Xn(0,0,10),rotation:new Jn,fov:75,zoom:1,near:.1,far:1e3}}function I(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 gr(s,e){let t=I(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 yr(s,e,t,i){let r=1-Math.pow(1-It.clamp(t,0,1),i*60),n=I(s);return n.position.lerp(e.position,r),n.rotation.slerp(e.rotation,r),e.fov!=null&&n.fov!=null&&(n.fov=It.lerp(n.fov,e.fov,r)),e.zoom!=null&&n.zoom!=null&&(n.zoom=It.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 Oe=class{perspective=null;behaviors=new Map;actions=[];_desiredPose=Ae();_finalPose=Ae();_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):Ae(),i=this.getSortedBehaviors();for(let r of i)r.enabled!==!1&&(t=r.update(e,t));this._desiredPose=I(t);for(let r=this.actions.length-1;r>=0;r--){let n=this.actions[r],o=n.update(e);t=gr(t,o),n.isDone(e)&&this.actions.splice(r,1)}return this._initialized?this._finalPose=yr(this._finalPose,t,this.damping,e.dt):(this._finalPose=I(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?I(this._desiredPose):null,finalPose:this._finalPose?I(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 _,Quaternion as Ve}from"three";var es={distance:8,height:5,shoulderOffset:0,targetKey:"primary",fov:75,paddingFactor:1.5,minDistance:5,trailDelay:.1,trailBufferSize:120},q=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={...es,...r},this.initialPosition=t?p(t,x):void 0,this.initialLookAt=i?p(i,x):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 Ve,fov:this.opts.fov,zoom:1,near:.1,far:1e3,lookAt:this.initialLookAt?.clone()??new _(0,0,0)}:{position:new _(this.opts.shoulderOffset,this.opts.height,this.opts.distance),rotation:new Ve,fov:this.opts.fov,zoom:1,near:.1,far:1e3,lookAt:new _(0,0,0)}}singleTargetPose(e,t,i){let r=this.getTrailedPosition(i,e,t.time);return{position:new _(r.x+this.opts.shoulderOffset,r.y+this.opts.height,r.z+this.opts.distance),rotation:new Ve,fov:this.opts.fov,zoom:1,near:.1,far:1e3,lookAt:r.clone()}}multiTargetPose(e){let i=Object.entries(e.targets).map(([h,m])=>this.getTrailedPosition(h,m.position,e.time)),r=new _;for(let h of i)r.add(h);r.divideScalar(i.length);let n=0;for(let h of i){let m=r.distanceTo(h);m>n&&(n=m)}let o=Math.max(n*this.opts.paddingFactor,this.opts.minDistance),a=new _(this.opts.shoulderOffset,this.opts.height,this.opts.distance),l=a.length(),c=l>0?a.clone().normalize():new _(0,.5,1).normalize(),d=r.clone().add(c.multiplyScalar(o));if(l>0){let h=this.opts.height/l;d.y=r.y+o*h}return{position:d,rotation:new Ve,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 h=d.time-c.time,m=h>1e-6?(a-c.time)/h:0;return new _().lerpVectors(c.pos,d.pos,m)}}return n[n.length-1].pos.clone()}};import{Vector3 as vr,Quaternion as ts}from"three";var br={position:{x:0,y:0,z:10},zoom:10},K=class{id="fixed-2d";projection="orthographic";defaults={damping:1};opts;constructor(e){this.opts={...br,...e,position:p(e?.position,br.position)}}getBasePose(e){return{position:new vr(this.opts.position.x,this.opts.position.y,this.opts.position.z),rotation:new ts,zoom:this.opts.zoom,near:1,far:1e3,lookAt:new vr(this.opts.position.x,this.opts.position.y,0)}}};import{Vector3 as Ft,Quaternion as Gt,Euler as wr,MathUtils as S}from"three";var is={eyeHeight:1.7,defaultFov:75,pitchLimit:Math.PI/2-.01,lookAtLerpSpeed:5,fovLerpSpeed:8,targetKey:"primary",verticalSmoothing:1},ce=class{id="first-person";projection="perspective";defaults={damping:1};opts;initialPosition;initialLookAt;_yaw=0;_pitch=0;_currentFov;_targetFov;_lookAtTarget=null;_lookAtLerpSpeed;_currentRotation=new Gt;_rotationInitialized=!1;_smoothedY=null;constructor(e){let{initialPosition:t,initialLookAt:i,...r}=e??{};this.opts={...is,...r},this.initialPosition=t?p(t,x):void 0,this.initialLookAt=i?p(i,x):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=S.clamp(this._pitch+t,-this.opts.pitchLimit,this.opts.pitchLimit)}setLook(e,t){this._yaw=e,this._pitch=S.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 Ft(t.position.x,r,t.position.z)}return this.initialPosition?this.initialPosition.clone():new Ft(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=S.clamp(this.opts.verticalSmoothing,0,1),r=1-Math.pow(1-i,t*60);return this._smoothedY=S.lerp(this._smoothedY,e,r),this._smoothedY}computeRotation(e,t){let i=new Gt().setFromEuler(new wr(this._pitch,this._yaw,0,"YXZ"));if(this._rotationInitialized||(this._currentRotation.copy(i),this._rotationInitialized=!0),this._lookAtTarget){let r=Cr.copy(this._lookAtTarget).sub(e);if(r.lengthSq()>1e-4){r.normalize();let n=Math.atan2(-r.x,-r.z),o=Math.asin(S.clamp(r.y,-1,1)),a=rs.setFromEuler(Sr.set(o,n,0,"YXZ")),l=1-Math.pow(1-Math.min(this._lookAtLerpSpeed*t,1),1);return this._currentRotation.slerp(a,S.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 S.lerp(this._currentFov,this._targetFov,S.clamp(t,0,1))}deriveYawPitchFromLookAt(e,t){let i=Cr.copy(t).sub(e).normalize();this._yaw=Math.atan2(-i.x,-i.z),this._pitch=Math.asin(S.clamp(i.y,-1,1))}deriveYawPitchFromQuaternion(e){let t=Sr.setFromQuaternion(e,"YXZ");this._yaw=t.y,this._pitch=S.clamp(t.x,-this.opts.pitchLimit,this.opts.pitchLimit)}},Cr=new Ft,rs=new Gt,Sr=new wr;import{Quaternion as ns,Vector3 as Zt}from"three";var ss={distance:10,zoom:10,targetKey:"primary"},Pr=new Zt(1,1,1).normalize(),de=class{id="isometric";projection="orthographic";defaults={damping:1};opts;initialPosition;initialLookAt;constructor(e){let{initialPosition:t,initialLookAt:i,...r}=e??{};this.opts={...ss,...r},this.initialPosition=t?p(t):void 0,this.initialLookAt=i?p(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(Pr,this.opts.distance);return this.pose(r,i)}staticPose(){return this.initialPosition?this.pose(this.initialPosition.clone(),this.initialLookAt?.clone()??new Zt(0,0,0)):this.pose(Pr.clone().multiplyScalar(this.opts.distance),new Zt(0,0,0))}pose(e,t){return{position:e,rotation:new ns,zoom:this.opts.zoom,near:1,far:1e3,lookAt:t}}};import{Quaternion as os,Vector3 as Ie}from"three";var as={height:10,zoom:10,targetKey:"primary"},ue=class{id="top-down";projection="orthographic";defaults={damping:1};opts;initialPosition;initialLookAt;constructor(e){let{initialPosition:t,initialLookAt:i,...r}=e??{};this.opts={...as,...r},this.initialPosition=t?p(t):void 0,this.initialLookAt=i?p(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 Ie(i.x,i.y+this.opts.height,i.z),i)}staticPose(){if(this.initialPosition){let e=this.initialLookAt?.clone()??new Ie(this.initialPosition.x,this.initialPosition.y-this.opts.height,this.initialPosition.z);return this.pose(this.initialPosition.clone(),e)}return this.pose(new Ie(0,this.opts.height,0),new Ie(0,0,0))}pose(e,t){return{position:e,rotation:new os,zoom:this.opts.zoom,near:1,far:1e3,lookAt:t}}};import{Quaternion as xr,Vector3 as Fe}from"three";var ls={anchorKey:"anchor",subjectKey:"primary",eyeHeight:1.7,fov:75},Ht=new Fe,he=class{id="second-person";projection="perspective";defaults={damping:1};opts;initialPosition;initialLookAt;constructor(e){let{initialPosition:t,initialLookAt:i,...r}=e??{};this.opts={...ls,...r},this.initialPosition=t?p(t):void 0,this.initialLookAt=i?p(i):void 0}getBasePose(e){let t=e.targets[this.opts.anchorKey];if(!t)return this.staticPose();let i=new Fe(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 xr,fov:this.opts.fov,near:.1,far:1e3,lookAt:n}}staticPose(){let e=this.initialPosition?.clone()??new Fe(0,this.opts.eyeHeight,0),t=this.initialLookAt?.clone()??e.clone().add(new Fe(0,0,-1));return{position:e,rotation:new xr,fov:this.opts.fov,near:.1,far:1e3,lookAt:t}}anchorForward(e){return Ht.set(0,0,-1),e&&Ht.applyQuaternion(e),Ht.clone()}};function F(s,e){switch(s){case"third-person":return new q(e);case"first-person":return new ce(e);case"second-person":return new he(e);case"isometric":return new de(e);case"top-down":return new ue(e);case"flat-2d":return new K(e);case"fixed-2d":return new K(e);default:return new q(e)}}import{Vector2 as hs,Vector3 as D,OrthographicCamera as ps,PerspectiveCamera as ms}from"three";import{PerspectiveCamera as Nt,Vector3 as ds,OrthographicCamera as He,RenderTarget as us,LinearFilter as Er}from"three";import{Vector3 as Ge}from"three";import{OrbitControls as cs}from"three/addons/controls/OrbitControls.js";var Ze=class{camera;domElement;cameraRig=null;sceneRef=null;orbitControls=null;orbitTarget=null;orbitTargetWorldPos=new Ge;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;_rotationLocked=!1;_screenSpacePanning=!1;_seededLookAt=null;constructor(e,t,i){this.camera=e,this.domElement=t,this.cameraRig=i??null}setScene(e){this.sceneRef=e}setDebugViewCamera(e){this._isDebugViewCamera=e}setDefaultOrbitTarget(e){this._defaultOrbitTarget=e,e&&!this.orbitTarget&&this.debugStateSnapshot.enabled&&this._followSelection&&(this.orbitTarget=e)}seedOrbitPose(e,t){this._seededLookAt=t.clone(),this.camera.position.copy(e),this.camera.lookAt(t),this.orbitControls&&(this.orbitControls.target.copy(t),this.orbitControls.update(),this._rotationLocked&&this.applyRotationLock()),this._debugPoseSeeded=!0}get isDebugViewCamera(){return this._isDebugViewCamera}get isDebugOrbitPoseSeeded(){return this._debugPoseSeeded}get isActive(){return this.debugStateSnapshot.enabled}get isOrbitActive(){return this.debugStateSnapshot.enabled||this._userOrbitEnabled}update(){this._followSelection&&this.orbitControls&&this.orbitTarget&&(this.orbitTarget.getWorldPosition(this.orbitTargetWorldPos),this.orbitControls.target.copy(this.orbitTargetWorldPos)),this.orbitControls?.update()}enableUserOrbitControls(){this._userOrbitEnabled=!0,this.orbitControls||this.enableOrbitControls()}disableUserOrbitControls(){this._userOrbitEnabled=!1,this.debugStateSnapshot.enabled||this.disableOrbitControls()}setDebugDelegate(e){if(this.debugDelegate===e)return;if(this.detachDebugDelegate(),this.debugDelegate=e,!e){this.applyDebugState({enabled:!1,selected:[]});return}let t=e.subscribe(i=>{this.applyDebugState(i)});this.debugUnsubscribe=()=>{t?.()}}dispose(){this.disableOrbitControls(),this.detachDebugDelegate()}setRotationLocked(e){this._rotationLocked=e,e?this.applyRotationLock():this.releaseRotationLock()}setScreenSpacePanning(e){this._screenSpacePanning=e,this.orbitControls&&(this.orbitControls.screenSpacePanning=e)}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 Ge().subVectors(this.camera.position,this.orbitControls.target).normalize();t.lengthSq()<1e-8&&t.set(1,1,1).normalize();let i=di(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._rotationLocked&&this.applyRotationLock()):!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._rotationLocked&&this.applyRotationLock()):!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 cs(this.camera,this.domElement),this.orbitControls.enableDamping=!0,this.orbitControls.dampingFactor=.05,this.orbitControls.screenSpacePanning=this._screenSpacePanning,this.orbitControls.minDistance=1,this.orbitControls.maxDistance=500,this.orbitControls.maxPolarAngle=Math.PI/2,this.orbitControls.enabled=this._interactionEnabled,this.orbitControls.target.copy(this._seededLookAt??new Ge),this._rotationLocked&&this.applyRotationLock())}applyRotationLock(){let e=this.orbitControls;if(!e)return;e.update();let t=e.getPolarAngle(),i=e.getAzimuthalAngle();e.minPolarAngle=t,e.maxPolarAngle=t,e.minAzimuthAngle=i,e.maxAzimuthAngle=i,e.enableRotate=!1,e.update()}releaseRotationLock(){let e=this.orbitControls;e&&(e.minPolarAngle=0,e.maxPolarAngle=Math.PI/2,e.minAzimuthAngle=-1/0,e.maxAzimuthAngle=1/0,e.enableRotate=!0,e.update())}rebindCamera(e){this.camera=e,this.orbitControls&&(this.orbitControls.object=e,this._rotationLocked&&this.applyRotationLock())}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 Ge;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 k=class{cameraRig=null;camera;screenResolution;_perspective;frustumSize=10;sceneRef=null;name="";viewport={...Ki};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 ds(0,0,0));let n=F(e);this.pipeline=new Oe(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 Ze(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 ke(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()}armEditorOrbit(e,t=!1){this._skipDebugOrbit=!0,this.orbitController?.setScreenSpacePanning(t),this.orbitController?.setRotationLocked(e),this.enableOrbitalControls(),this.setOrbitInteractionEnabled(!0)}disarmEditorOrbit(){this.setOrbitInteractionEnabled(!1)}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 Nt&&(this.camera.aspect=e/t,this.camera.updateProjectionMatrix()),this.camera instanceof He){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 us(e,t,{minFilter:Er,magFilter:Er}),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===f.Flat2D||this._perspective===f.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 Nt&&(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 He){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??Vt(e))}ensureProjection(e){if((this.camera instanceof He?"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 Vt(this._perspective)==="orthographic"?this.createOrthographicCamera(e):this.createPerspectiveCamera(e)}createPerspectiveCamera(e){return new Nt(75,e,.1,1e3)}createOrthographicCamera(e){return new He(this.frustumSize*e/-2,this.frustumSize*e/2,this.frustumSize/2,this.frustumSize/-2,1,1e3)}};var Mr=1e4,fs=[{id:C.side,perspective:f.Fixed2D,lockRotation:!0,screenSpacePan:!0,position:(s,e)=>new D(s.x+e,s.y,s.z),up:()=>new D(0,1,0)},{id:C.top,perspective:f.TopDown,lockRotation:!0,screenSpacePan:!0,position:(s,e)=>new D(s.x,s.y+e,s.z),up:()=>new D(0,0,-1)},{id:C.isometric,perspective:f.Isometric,lockRotation:!0,screenSpacePan:!0,near:-Mr,far:Mr,position:(s,e)=>s.clone().add(new D(1,1,1).normalize().multiplyScalar(e)),up:()=>new D(0,1,0)},{id:C.free,perspective:f.ThirdPerson,lockRotation:!1,screenSpacePan:!1,position:(s,e,t)=>t.distanceTo(s)>.5?t.clone():s.clone().add(new D(0,e*.5,e)),up:s=>s.clone()}];function gs(s){let e=new D;s.getWorldDirection(e);let i=new D().sub(s.position).dot(e),r=i>1?i:12;return{lookAt:s.position.clone().add(e.multiplyScalar(r)),distance:r}}var Ne=class{cameras=new Map;_activeCameras=[];_editorCameras=new Map;_lockedEditorIds=new Set;_screenSpacePanIds=new Set;_rememberedGameCamera=null;_editorViewLocked=!1;_suspendedOrbits=new Set;_editorCamerasPromise=null;_rendererManager=null;_sceneRef=null;_autoNameCounter=0;_unregisterEditorHost=null;get activeCameras(){return this._activeCameras}get primaryCamera(){return this._activeCameras.length>0?this._activeCameras[0]:null}isEditorViewActive(){return this._editorViewLocked}activeEditorCameraId(){let e=this.primaryCamera;if(!e||!this._editorViewLocked)return null;for(let[t,i]of this._editorCameras)if(i===e)return t;return null}hasEditorCameras(){return this._editorCameras.size>0}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;this.cameras.delete(t);let r=this._activeCameras.indexOf(i);return r!==-1&&this._activeCameras.splice(r,1),this._rememberedGameCamera===i&&(this._rememberedGameCamera=null),this._suspendedOrbits.delete(i),!0}setActiveCamera(e){let t=this.resolveCamera(e);return t?this._editorViewLocked&&!this.isEditorCamera(t)?(this._rememberedGameCamera=t,!0):(this.isEditorCamera(t)||(this._rememberedGameCamera=t,this.restoreOrbitFor(t)),this.commitActive(t)):(console.warn(`CameraManager: Camera not found: ${e}`),!1)}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;for(let i of this.cameras.values())i.setRendererManager(t),await i.setup(e,t);this._unregisterEditorHost=mi(this),be()&&await this.ensureEditorCameras()}ensureEditorCameras(){return this._editorCameras.size>0?Promise.resolve():this._editorCamerasPromise?this._editorCamerasPromise:(this._editorCamerasPromise=this.createEditorCameras().finally(()=>{this._editorCamerasPromise=null}),this._editorCamerasPromise)}destroyEditorCameras(){let e=this.primaryCamera!==null&&this.isEditorCamera(this.primaryCamera);if(this._editorViewLocked=!1,e){let t=this.gameCameraToRestore();t&&(this.restoreOrbitFor(t),this.commitActive(t))}for(let t of this._editorCameras.values())this.removeCamera(t),t.destroy();this._editorCameras.clear(),this._lockedEditorIds.clear(),this._screenSpacePanIds.clear()}activateCameraById(e){if(e===pi){let r=this.gameCameraToRestore();return r?this.showGameCamera(r):!1}let t=this._editorCameras.get(e);if(t)return this.showEditorCamera(e,t);let i=this.getCamera(e);return!i||this.isEditorCamera(i)?!1:(this._rememberedGameCamera=i,this.showGameCamera(i))}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 hs(window.innerWidth,window.innerHeight),t=new k(f.ThirdPerson,e);return this.addCamera(t,"default"),t}return this._activeCameras[0]}dispose(){this._unregisterEditorHost?.(),this._unregisterEditorHost=null,this._editorViewLocked=!1;for(let e of this.cameras.values())e.destroy();this.cameras.clear(),this._activeCameras=[],this._editorCameras.clear(),this._lockedEditorIds.clear(),this._screenSpacePanIds.clear(),this._rememberedGameCamera=null,this._suspendedOrbits.clear(),this._rendererManager=null,this._sceneRef=null}async createEditorCameras(){if(this._editorCameras.size>0||!this._sceneRef||!this._rendererManager)return;let e=this.primaryCamera??this.ensureDefaultCamera();e.sceneRef||(e.setRendererManager(this._rendererManager),await e.setup(this._sceneRef,this._rendererManager));let t=gs(e.camera),i=this._rendererManager.screenResolution.clone(),r=Math.max(t.distance,4);this.isEditorCamera(e)||(this._rememberedGameCamera=e);for(let n of fs){let o=new k(n.perspective,i,r);o._skipDebugOrbit=!0;let a=n.position(t.lookAt,t.distance,e.camera.position),l=n.up(e.camera.up);o.camera.up.copy(l),o.camera.position.copy(a),o.camera.lookAt(t.lookAt),(o.camera instanceof ps||o.camera instanceof ms)&&(o.camera.near=n.near??.1,o.camera.far=n.far??2e3,o.camera.updateProjectionMatrix()),this.addCamera(o,n.id),this._editorCameras.set(n.id,o),n.lockRotation&&this._lockedEditorIds.add(n.id),n.screenSpacePan&&this._screenSpacePanIds.add(n.id),o.setRendererManager(this._rendererManager),await o.setup(this._sceneRef,this._rendererManager),o.seedDebugOrbitPose(a,t.lookAt)}}showEditorCamera(e,t){if(!this._editorViewLocked){let i=this.primaryCamera;i&&!this.isEditorCamera(i)&&(this._rememberedGameCamera=i)}return this._editorViewLocked=!0,this.suspendOtherOrbits(t),this.syncEditorOrbit(e),this.commitActive(t)}showGameCamera(e){return this._editorViewLocked=!1,this.syncEditorOrbit(null),this.restoreOrbitFor(e),this.commitActive(e)}syncEditorOrbit(e){for(let[t,i]of this._editorCameras)t===e?i.armEditorOrbit(this._lockedEditorIds.has(t),this._screenSpacePanIds.has(t)):i.disarmEditorOrbit()}suspendOtherOrbits(e){for(let t of this.cameras.values())t===e||this.isEditorCamera(t)||t.isOrbitActive&&(t.setOrbitInteractionEnabled(!1),this._suspendedOrbits.add(t))}restoreOrbitFor(e){this._suspendedOrbits.has(e)&&(e.setOrbitInteractionEnabled(!0),this._suspendedOrbits.delete(e))}gameCameraToRestore(){if(this._rememberedGameCamera&&this.cameraIsRegistered(this._rememberedGameCamera))return this._rememberedGameCamera;for(let e of this.cameras.values())if(!this.isEditorCamera(e))return e;return null}cameraIsRegistered(e){for(let t of this.cameras.values())if(t===e)return!0;return!1}isEditorCamera(e){for(let t of this._editorCameras.values())if(t===e)return!0;return!1}commitActive(e){let t=this.primaryCamera,i=this._activeCameras.filter(r=>r!==this._activeCameras[0]&&r.viewport.width<1);return this._activeCameras=[e,...i],t!==e&&this._rendererManager?.rebindPostProcessingCamera(e.camera),!0}resolveCamera(e){if(typeof e=="string")return this.cameras.get(e)??null;for(let t of this.cameras.values())if(t===e)return t;return null}};var w=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,F(e,t))}getPerspective(){return this.cameraRef.pipeline.perspective}getState(){return this.cameraRef.pipeline.getState()}getRenderTexture(){return this.cameraRef.getRenderTexture()}};function Yl(s){let e=vi(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 k(s.perspective||"third-person",e,t);s.name&&(i.name=s.name);let r=p(s.position,x),n=p(s.target,x);i.move(r),i.camera.lookAt(n);let o=s.perspective||"third-person";if(o==="fixed-2d"||o==="flat-2d"?i.applyPerspective(o,F(o,{zoom:t})):o==="isometric"||o==="top-down"?i.applyPerspective(o,F(o,{zoom:t,initialPosition:r.clone(),initialLookAt:n.clone()})):i.applyPerspective(o,F(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 w(i)}import{Vector3 as ys}from"three";function B(s){return!!s&&typeof s=="object"&&typeof s.create=="function"}function pe(s){return!!s&&typeof s.then=="function"}function Ut(s){return!!s&&typeof s=="object"&&s instanceof w}function kr(s){return!s||typeof s!="object"||B(s)||Ut(s)||pe(s)||typeof s.then=="function"?!1:s.constructor===Object||s.constructor?.name==="Object"}function Dr(s){return s?!!(B(s)||typeof s=="function"||pe(s)):!1}var vs="/three/basis/";function je(s){return{...s,ktx2TranscoderPath:s?.ktx2TranscoderPath??vs}}var Ue=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 bs(){return new Ue({p1:["gamepad-1","keyboard-1"],p2:["gamepad-2","keyboard-2"]},Ee,null,null,new ys(0,0,0),{},60,{},!0)}function Tr(s=[]){let e=bs(),t={},i=[],r=[],n=[];for(let l of s)Ut(l)?n.push(l):B(l)?i.push(l):Dr(l)&&!B(l)?r.push(l):kr(l)&&(t={...t,...l});let o=new Ue(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 sc(s){return{...s}}var Cs=Symbol("vessel"),me=class extends J{static type=Cs;_setup(e){}async _loaded(e){}_update(e){}_destroy(e){}_cleanup(e){}create(){return this}clone(){let e=Ss();return this.replayUserLifecycleRegistrationsTo(e),this.cloneChildrenInto(e),e}add(...e){for(let t of e)super.add(t);return this}};function Ss(...s){let e=new me;return s.forEach(t=>e.add(t)),e.enableUserLifecycleTracking(),e}import{Color as cn,Vector3 as dn}from"three";import{createSimulation as ws}from"@zylem/behaviors/core";function jt(s){return typeof s?.handlePostCollision=="function"&&typeof s?.handleIntersectionEvent=="function"}function Ps(s,e){return s<e?`${s}|${e}`:`${e}|${s}`}var We=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 ws({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 Pe)&&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 Di(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=Ps(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(!jt(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,mt.globals,r);let a=this.collisionMap.get(e.uuidA),l=this.collisionMap.get(e.uuidB);a&&l&&l._collision(a,mt.globals,r)}dispatchIntersectionDelegates(e,t){let i=this.collisionMap.get(e.uuidA),r=this.collisionMap.get(e.uuidB);i&&r&&jt(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&&jt(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 xs,Color as Rr,AmbientLight as Es,DirectionalLight as Ms,Vector3 as qe,GridHelper as ks,Texture as Ds,SRGBColorSpace as Ts}from"three";var Ke=class{type="Scene";_setup;scene;zylemCamera;cameraManager=null;containerElement=null;update=()=>{};_collision;_destroy;name;tag;constructor(e,t,i){let r=new xs,o=i.backgroundColor instanceof Rr?i.backgroundColor:new Rr(i.backgroundColor);r.background=o,i.backgroundShader?this.setupBackgroundShader(r,i.backgroundShader):i.backgroundImage&&H.loadTexture(i.backgroundImage,{colorSpace:Ts}).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(!Se(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:b()})}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 Ds&&(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 Es(16777215,1);e.add(t);let i=new Ms(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 qe(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(A(e))return;let t=e.group??e.mesh;if(!t||this.isAttachedOutsideScene(t))return;let i=Rs(e);i&&i.attachToScene(this.scene);let r=e.options.position??new qe(0,0,0);if(e.physicsAttached&&e.body)try{let n=e.body.translation();r=new qe(n.x,n.y,n.z)}catch{r=e.options.position??new qe(0,0,0)}this.add(t,r),ee(e)}isAttachedOutsideScene(e){return e.parent!=null&&e.parent!==this.scene}debugScene(){let i=new ks(1e3,100);this.scene.add(i)}};function Rs(s){return s.constructor.type===Ti?s:null}var Qe=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 _s}from"three";var _r=new _s;function Br(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?xe(r,t?.interpolationAlpha??0):null;n&&o&&n.position.set(o.position.x,o.position.y,o.position.z),!i.controlledRotation&&n&&o&&(_r.set(o.rotation.x,o.rotation.y,o.rotation.z,o.rotation.w),n.setRotationFromQuaternion(_r))}}import{nanoid as Bo}from"nanoid";import{Box3 as ti,BufferAttribute as tn,BufferGeometry as wo,LineBasicMaterial as Po,LineSegments as xo,Raycaster as Eo,Vector2 as Mo,Vector3 as ii}from"three";import{subscribe as ko}from"valtio/vanilla";import{nanoid as rn}from"nanoid";import{getZylemBridge as nn}from"@zylem/bridge";import{StageBodyKind as Do}from"@zylem/behaviors/core";import{Box3 as Bs,BoxGeometry as zr,Color as zs,EdgesGeometry as Lr,Group as Ls,LineBasicMaterial as As,LineSegments as Os,Mesh as Vs,MeshBasicMaterial as Is,Vector3 as Ar}from"three";var $e=class{scene;container;fillMesh;edgeLines;currentColor=new zs(65280);bbox=new Bs;size=new Ar;center=new Ar;constructor(e){this.scene=e;let t=new zr(1,1,1);this.fillMesh=new Vs(t,new Is({color:this.currentColor,transparent:!0,opacity:.12,depthWrite:!1}));let i=new Lr(t);this.edgeLines=new Os(i,new As({color:this.currentColor,linewidth:1})),this.container=new Ls,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 zr(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 Lr(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 Fs,BoxGeometry as Gs,Group as Zs,Mesh as Hs,MeshBasicMaterial as Ns,Vector3 as Or}from"three";var Us={x:0,y:0,z:0},js=7128319,Ws=.35;function qs(){return new Ns({color:js,transparent:!0,opacity:Ws,depthWrite:!1})}function Ks(s){let e=s.size;return new Or(e?.x??1,e?.y??1,e?.z??1)}function Qs(s,e){try{let t=s.create({position:Us,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 $s(s,e){s.traverse(t=>{let i=t;i.isMesh&&(i.material=e,i.castShadow=!1,i.receiveShadow=!1)})}var Ye=class{scene;container;builtFor=null;builtProps=null;material=null;extent=null;bounds=new Fs;constructor(e){this.scene=e,this.container=new Zs,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=Z(e),n={...r?.defaultProps??{},...t??{}},a=(r?Qs(r,n):null)??new Hs(new Gs(...Ks(n).toArray()));a.position.set(0,0,0),this.material=qs(),$s(a,this.material),this.container.add(a),this.bounds.setFromObject(a),this.extent=this.bounds.isEmpty()?null:this.bounds.getSize(new Or)}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{Box3 as eo,Quaternion as tt,Vector3 as P}from"three";import{nanoid as to}from"nanoid";import{Vector3 as Q}from"three";var qt=.95,Ys=16,fe=new Q,Xs=new Q,Vr=new Q,Wt=new Q;function Ir(s){return s?s.isPerspectiveCamera===!0||s.isOrthographicCamera===!0:!1}function Xe(s,e,t=qt){return fe.copy(s).project(e),Math.abs(fe.x)<=t&&Math.abs(fe.y)<=t&&fe.z>=-1&&fe.z<=1}function Fr(s){let e=0,t=1;for(let i=0;i<Ys;i+=1){let r=(e+t)/2;s(r)?e=r:t=r}return e}function Gr(s,e,t,i=qt){if(!Ir(t))return e.clone();let r=t;if(Xe(e,r,i)||!Xe(s,r,i))return e.clone();let n=Fr(o=>Xe(Xs.copy(s).lerp(e,o),r,i));return s.clone().lerp(e,n)}function Zr(s,e,t,i,r=qt){if(!Ir(i)||t.x<=1&&t.y<=1&&t.z<=1||s.isEmpty())return t.clone();let n=i;Vr.copy(e);let o=new Q(1,1,1),a=c=>(o.set(1+(t.x-1)*c,1+(t.y-1)*c,1+(t.z-1)*c),Js(s,Vr,o,n,r));if(a(1))return t.clone();let l=Fr(a);return new Q(1+(t.x-1)*l,1+(t.y-1)*l,1+(t.z-1)*l)}function Js(s,e,t,i,r){for(let n=0;n<8;n+=1)if(Wt.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),Wt.sub(e).multiply(t).add(e),!Xe(Wt,i,r))return!1;return!0}var io={translate:"Move",rotate:"Rotate",scale:"Scale"};function Kt(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 P(i.x,i.y,i.z),quaternion:new tt(r.x,r.y,r.z,r.w),scale:new P(n.x,n.y,n.z)}}function Hr(s){let e=bt(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 ro(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 Je(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 no(s){let e=s?.group??s?.mesh;if(!e?.isObject3D)return null;let t=new eo().setFromObject(e);return t.isEmpty()?null:t}var Qt=.02,$t=50;function so(s){return new P(Yt(s.x,Qt,$t),Yt(s.y,Qt,$t),Yt(s.z,Qt,$t))}function Yt(s,e,t){return Math.min(Math.max(s,e),t)}var Xt=new tt,oo=new P,et=class{gizmo=new Oi;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:Kt(o),startBounds:this.mode==="scale"?no(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=T(),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=Kt(i.entity);ro(i.start,r)&&(e.mode==="scale"&&Ct(i.entity),t.push({uuid:i.uuid,before:Hr(i.start),after:Hr(r)}))}t.length&&X({opId:to(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=oo.copy(e.pivotStart).add(t),o=Gr(e.pivotStart,n,r),a=i>0?Ce(o,i):o,l=new P(a.x-e.pivotStart.x,a.y-e.pivotStart.y,a.z-e.pivotStart.z);for(let c of e.entries)Je(c.entity,{position:c.start.position.clone().add(l)})}applyRotate(e,t,i,r){let n=e.axis;for(let o of e.entries){Xt.setFromAxisAngle(t,i);let a=Xt.clone().multiply(o.start.quaternion),l=a;if(r>0&&(n==="x"||n==="y"||n==="z")){let d=bt(a);d[n]=gi(d[n],r);let h=vt(d);l=new tt(h.x,h.y,h.z,h.w)}let c=o.start.position.clone().sub(e.pivotStart).applyQuaternion(Xt).add(e.pivotStart);Je(o.entity,{position:c,quaternion:l})}}applyScale(e,t,i,r){for(let n of e.entries){let o=n.startBounds?Zr(n.startBounds,n.start.position,t,r):t,a=so(o),l=new P(n.start.scale.x*a.x,n.start.scale.y*a.y,n.start.scale.z*a.z),c=i>0?yi(l,i):l;Je(n.entity,{scale:new P(c.x,c.y,c.z)})}}describeOperation(e){let t=io[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 P,i=0;for(let r of e){let n=this.context.resolveEntity(r);n&&(t.add(Kt(n).position),i++)}return i?t.divideScalar(i):null}};function Nr(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?vt(r.rotation):void 0);Je(n,{position:r.position?new P(r.position.x,r.position.y,r.position.z):void 0,quaternion:o?new tt(o.x,o.y,o.z,o.w):void 0,scale:r.scale?new P(r.scale.x,r.scale.y,r.scale.z):void 0}),r.scale&&Ct(n)}}var ao=200;function Ur(s){return typeof s=="object"&&s!==null&&!Array.isArray(s)}function lo(s){return Ur(s)&&(Se(s)||Ci(s))}var it=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(!Ur(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=we("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(!lo(n))return{ok:!1,reason:"invalid-props"};let o=e.setMaterial({shader:n},{disposePrevious:!1});return o?(i.previousMaterials?Jt(o,i.previousMaterials):i.previousMaterials=o,{ok:!0,replaced:!1}):{ok:!1,reason:"no-material"}}applyBehavior(e,t,i){let r=we("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(h){console.warn(`[zylem] swatch behavior "${t.source}" failed to attach`,h)}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=we("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>ao;){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()??[];Jt(r.previousMaterials??[],n),Jt(r.redoMaterials??[],n)}}};function Jt(s,e){for(let t of s)e.includes(t)||t.dispose()}import{Box3 as po,Frustum as mo,Vector2 as nt}from"three";import{Frustum as co,Vector2 as jr,Vector3 as uo}from"three";var Wr=Array.from({length:8},()=>new uo),g=new jr,y=new jr;function qr(s,e,t,i=new co){g.set(Math.min(e.x,t.x),Math.min(e.y,t.y)),y.set(Math.max(e.x,t.x),Math.max(e.y,t.y));let r=1e-5;y.x-g.x<r&&(y.x=g.x+r),y.y-g.y<r&&(y.y=g.y+r),z(0,g.x,g.y,-1,s),z(1,y.x,g.y,-1,s),z(2,y.x,y.y,-1,s),z(3,g.x,y.y,-1,s),z(4,g.x,g.y,1,s),z(5,y.x,g.y,1,s),z(6,y.x,y.y,1,s),z(7,g.x,y.y,1,s);let[n,o,a,l,c,d,h,m]=Wr,v=i.planes;return $(v[0],n,c,m),$(v[1],o,h,d),$(v[2],l,m,h),$(v[3],n,d,c),$(v[4],n,l,a),$(v[5],c,h,m),i}function z(s,e,t,i,r){Wr[s].set(e,t,i).unproject(r)}function $(s,e,t,i){s.setFromCoplanarPoints(e,t,i)}function Kr(s,e){return e.isEmpty()||!Number.isFinite(e.min.x)||!Number.isFinite(e.max.x)?!1:s.intersectsBox(e)}function Qr(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 $r(s){return s.altKey?"subtract":s.shiftKey?"add":"replace"}var ho="[data-zylem-overlay-root]";function Yr(s){let e=s.parentElement;return e?e.querySelector(ho)??e:null}var rt=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 fo=4,go=new po,Xr=new mo,st=class{context;overlay=new rt;armed=!1;dragging=!1;mode="replace";baseSelection=[];startNdc=new nt;currentNdc=new nt;startClient=new nt;currentClient=new nt;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=$r(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=Yr(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)<fo)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;qr(e,this.startNdc,this.currentNdc,Xr);let t=[];this.context.forEachEntity((i,r)=>{let n=te(r,go);n&&Kr(Xr,n)&&t.push(i)}),oi(Qr(this.baseSelection,t,this.mode))}};import{BoxGeometry as yo,EdgesGeometry as vo,Group as bo,LineBasicMaterial as Co,LineSegments as So,Vector3 as en}from"three";var ot=new en,Jr=new en,at=class{scene;container=new bo;edges;material;pool=[];constructor(e,t=16765503){this.scene=e;let i=new yo(1,1,1);this.edges=new vo(i),i.dispose(),this.material=new Co({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(ot),i.getCenter(Jr);let r=this.acquire(t);t+=1,r.position.copy(Jr),r.scale.set(Math.max(ot.x,1e-6),Math.max(ot.y,1e-6),Math.max(ot.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 So(this.edges,this.material);return i.frustumCulled=!1,this.container.add(i),this.pool.push(i),i}};var sn=2293538,To=16724787,ei=new ti,on=new ii,lt=class{stage;options;mouseNdc=new Mo(-2,-2);raycaster=new Eo;domDisposeFns=[];domListenersAttached=!1;debugCursor=null;placementGhost=null;debugLines=null;debugStateUnsubscribe=null;focusContextUnregister=null;entityResolverUnregister=null;lastDebugEnabled=null;warnedMissingAddFactory=!1;transformTool;swatchApplier;marquee;selectionHighlight=null;selectionBoundsPool=[];hoverBounds=new ti;grid=new Ai;levelSession;levelPointer=!1;lastTool=null;capturedPointer=null;constructor(e,t){this.stage=e,this.options={maxRayDistance:t?.maxRayDistance??5e3,addEntityFactory:t?.addEntityFactory??null},this.transformTool=new et({getScene:()=>this.stage.scene?.scene??null,getCamera:()=>this.getDebugViewCamera()?.camera??null,resolveEntity:i=>this.resolveEntity(i)}),this.swatchApplier=new it({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 st({getCamera:()=>this.getDebugViewCamera()?.camera??null,forEachEntity:i=>this.forEachSelectableEntity(i)}),this.levelSession=new ze(this.levelSessionHost()),this.syncWithDebugState(),this.debugStateUnsubscribe=ko(u,()=>{this.syncWithDebugState()}),this.entityResolverUnregister=si(i=>this.resolveEntity(i)),this.focusContextUnregister=fi({resolveEntity:i=>this.resolveEntity(i),frameObject:i=>{let r=this.stage.cameraManagerRef,n=()=>{r&&!r.isEditorViewActive()&&r.hasEditorCameras()&&r.activateCameraById(C.free),this.getDebugViewCamera()?.frameObject(i)};if(r&&be()&&!r.hasEditorCameras()){r.ensureEditorCameras().then(n);return}n()},ensureDebugReady:()=>{u.enabled||(u.enabled=!0),this.lastDebugEnabled=!0,this.activate()}})}setAddEntityFactory(e){this.options.addEntityFactory=e,this.warnedMissingAddFactory=!1}syncLevel(e){this.levelSession.sync(e),this.syncGrid()}playLevel(e){this.levelSession.play(e),this.syncGrid()}closeLevel(){this.levelSession.close(),this.syncGrid()}levelSessionHost(){return{getScene:()=>this.stage.scene?.scene??null,cameraId:()=>this.stage.cameraManagerRef?.activeEditorCameraId()??null,physicsHit:e=>{let t=this.stage.world?.raycast(e.origin,e.direction,this.options.maxRayDistance);return t?{distance:t.distance,normal:t.normal}:null},spawnZone:async e=>{let t=ki({name:e.name,position:e.position,size:e.size,editorOwned:!0});return await this.stage.spawnEntity(t),t.uuid??null},detach:e=>{this.stage.entityDelegate.detachEntity(e)},spawnHulls:e=>{let t=this.stage.world?.simulation;return!t||e.length===0?null:t.spawn({body:{kind:Do.Static,position:[0,0,0],rotation:[0,0,0,1],canSleep:!0,ccdEnabled:!1},colliders:e.map(i=>({shape:{type:"convexHull",vertices:i},friction:.5,restitution:0,sensor:!1}))})},despawnHulls:e=>{if(e)try{this.stage.world?.simulation.despawn(e)}catch{}},publishGesture:e=>{an("level:gesture",{gesture:e})},publishSelect:e=>{an("level:select",{id:e})},publishNotice:e=>{St("info",e)}}}getDebugViewCamera(){return this.stage.cameraManagerRef?.primaryCamera??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)})}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=ft(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(T().translate),this.grid.setVisible(u.gridVisible||this.levelSession.isEditing))}activate(){this.domListenersAttached||(this.domListenersAttached=this.attachDomListeners()),this.populateDebugMap(),this.rebindPostProcessing(this.getDebugViewCamera()),document.pointerLockElement&&document.exitPointerLock()}deactivate(){this.disposeDebugVisuals(),this.transformTool.cancelDrag(),this.grid.setVisible(!1),this.rebindPostProcessing(this.getDebugViewCamera())}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 xo(new wo,new Po({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 $e(e),this.placementGhost??=new Ye(e),this.selectionHighlight??=new at(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 ti,a=te(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=L();if(this.ensureInteraction(),this.ensureToolVisuals(),this.levelSession.tick(),this.syncGrid(),u.enabled?(this.initDebugVisuals(),this.updateColliderWireframes(t)):this.disposeDebugVisuals(),this.updatePlacementGhost(i,t),this.updateSelectionHighlight(),ft(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?yt(o.uuid??null):ve();let a=ci();if(!a){this.debugCursor?.hide();return}let l=te(this.resolveEntity(a),this.hoverBounds);if(!l){this.debugCursor?.hide();return}switch(i){case"select":this.debugCursor?.setColor(sn);break;case"delete":this.debugCursor?.setColor(To);break;default:this.debugCursor?.setColor(u.pickMode?sn: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&&ve(),null;let o=this.currentRay(),l=n.raycast(o.origin,o.direction,this.options.maxRayDistance)?.uuid??null;if(!l)return r&&ve(),null;r&&yt(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 tn(new Float32Array(t.vertices),3)),this.debugLines.geometry.setAttribute("color",new tn(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||!ye()||(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=ae(n,o,T(),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.levelSession.dispose(),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":Nr(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 ii,direction:new ii(0,0,-1)}}handleAction(e,t={shiftKey:!1,altKey:!1}){let i=L();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&&ai([a]):t.shiftKey?a&&li(a):a?gt(a):gt(null);break}case"delete":{let o=n?.uuid??null;if(!o)break;this.stage.entityDelegate.detachEntity(o)&&X({opId:rn(10),kind:"delete",label:"Delete entity",entries:[{uuid:o}]});break}case"add":this.placeEntity(e,n);break}}placeEntity(e,t){let i=ae(e,t,T());if(!i)return;let{position:r,normal:n}=i,o=u.addTypeId?Z(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),X({opId:rn(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"||(ei.setFromObject(r),ei.isEmpty()))return;ei.getSize(on);let n=Mt(t,on,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),St("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.levelPointer){this.levelSession.pointerMove(this.currentRay());return}if(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.levelSession.pointerDown(l)){this.levelPointer=!0,this.beginPointerCapture(e,a.pointerId);return}if(this.transformTool.pointerDown(l)){this.beginPointerCapture(e,a.pointerId);return}if(L()==="select"){this.marquee.pointerDown(this.mouseNdc,a,e),this.beginPointerCapture(e,a.pointerId);return}this.handleAction(l,a)},n=a=>{if(this.levelPointer){this.levelSession.pointerUp(this.currentRay()),this.levelPointer=!1,this.endPointerCapture();return}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.levelPointer){this.levelPointer=!1,this.levelSession.pointerUp(this.currentRay()),this.endPointerCapture();return}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}}};function an(s,e){nn().channel.send.bind(nn().channel)(s,e)}import{Vector2 as Ro}from"three";var ct=class{stage;constructor(e){this.stage=e}createDefaultCamera(){let e=window.innerWidth,t=window.innerHeight,i=new Ro(e,t);return new k(f.ThirdPerson,i)}resolveCamera(e,t){return e||(t?t.cameraRef:this.createDefaultCamera())}buildCameraManager(e,...t){let i=new Ne;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 dt=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"?ge.emit("stage:loading:start",t):e.type==="progress"?ge.emit("stage:loading:progress",t):e.type==="complete"&&ge.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 ut=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)},R.on("entity:model:loaded",this.modelLoadedHandler)}observe(e){if(e.group||e.mesh){re(e.options)||(this.scene?.addEntityGroup(e),ee(e),N(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),ee(i),N(i),re(i.options)||this.onEntityReady?.(i),this.pendingEntities.delete(e)}dispose(){this.modelLoadedHandler&&(R.off("entity:model:loaded",this.modelLoadedHandler),this.modelLoadedHandler=null),this.pendingEntities.clear(),this.onEntityReady=null,this.scene=null}};import{StageBodyKind as ln}from"@zylem/behaviors/core";var _o=200,ht=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 me){e.create();for(let i of e.getChildren())i instanceof J&&await this.spawnEntity(i);e.nodeSetup({me:e,globals:b(),camera:this.camera}),this.addEntityToStage(e);return}let t=e.create();Pi(t),this.registerBehaviorLinks(t),this.ensureEnvironmentStatic(t),this.maybeAttachEntityPhysics(t);for(let i of e.getChildren())i instanceof J&&await this.spawnEntity(i);e.nodeSetup({me:e,globals:b(),camera:this.camera}),this.tryRegisterRenderStrategy(t),A(t)||this.scene.addEntityGroup(t),N(t),this.addEntityToStage(t),this.entityModelDelegate.observe(t),xi(t)}handleLateModelReady(e){!this.world||!this.scene||!this.childrenMap.has(e.uuid)||(this.ensureEnvironmentStatic(e),this.maybeAttachEntityPhysics(e),this.tryRegisterRenderStrategy(e),A(e)||this.scene.addEntityGroup(e),N(e))}tryRegisterRenderStrategy(e){this.renderStrategy&&this.renderStrategy.register(e)}ensureEnvironmentStatic(e){if(ie(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!==ln.Static&&(e.bodyDesc.kind=ln.Static)}maybeAttachEntityPhysics(e){if(!(!this.world||e.physicsAttached||!e.colliderDesc)){if(e instanceof Pe){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),A(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(),R.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),A(i)||this.scene.addEntityGroup(i),wi(i),Ei(i),this.addEntityToStage(i),this.entityModelDelegate.observe(i),!0}isDetached(e){return this.detachedMap.has(e)}evictOldestDetached(){for(;this.detachedMap.size>_o;){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:b()})}catch{}U(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 Mi?{...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(B(t)){this.handleEntityImmediatelyOrQueue(t);continue}if(typeof t=="function"){try{let i=t();B(i)?this.handleEntityImmediatelyOrQueue(i):pe(i)&&this.handlePromiseWithSpawnOnResolve(i)}catch(i){console.error("Error executing entity factory",i)}continue}pe(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:Pt,getGlobals:b}):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:b()})}catch{}U(t),e.push(t.uuid)}),this.detachedMap.forEach(({entity:t})=>{try{t.nodeDestroy?.({me:t,globals:b()})}catch{}U(t)}),this.detachedMap.clear(),this.childrenMap.clear(),this.debugMap.clear(),this.entityAddedHandlers=[];for(let t of e)R.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:Pt,getGlobals:b});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 zo="Stage",pt=class extends Qe{type=zo;state={...Ri};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=Bo(),this.cameraDelegate=new ct(this),this.loadingDelegate=new dt,this.entityModelDelegate=new ut,this.entityDelegate=new ht(this.loadingDelegate,this.entityModelDelegate);let t=Tr(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 dn(0,0,0)}setState(){let{backgroundColor:e,backgroundImage:t}=this.state,i=e instanceof cn?e:new cn(e);_i(i),Bi(t),zi(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 Ke(e,r,this.state);let n=this.gravity??new dn(0,0,0);if(this.world=await We.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 H.configureGLTFRuntime({renderer:o,...je(this.state.assetLoaders?.gltf)}),this.entityModelDelegate.attach(this.scene,a=>this.entityDelegate.handleLateModelReady(a)),this.renderStrategy=new Te,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 lt(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;M("behaviorSystems",()=>{for(let n of this.entityDelegate.behaviorSystems)n.update(void 0,t)}),M("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&&Vi(a,a.transformStore),n.markedForRemoval&&this.entityDelegate.removeEntityByUuid(n.uuid)}}),M("worldUpdate",()=>{i.update(e)}),M("behaviorPostUpdate",()=>{for(let n of this.entityDelegate.behaviorSystems)n.postUpdate?.(void 0,t)}),M("syncRenderPoses",()=>{Br({_childrenMap:this.entityDelegate.childrenMap,_world:i})}),M("renderStrategy",()=>{this.renderStrategy?.update(i.interpolationAlpha)}),M("camera",()=>{this.cameraManagerRef?this.cameraManagerRef.update(t):this.cameraRef?.update(t)}),M("scene",()=>{r.update({delta:t})}),fr()}outOfLoop(){this.debugUpdate()}debugUpdate(){ye()&&(At("debugUpdate"),this.debugDelegate?.update(),Ot())}_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,Li(),U(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 Lo}from"valtio/vanilla";import{Vector3 as Ao}from"three";var Oo={backgroundColor:Ee,backgroundImage:null,inputs:{p1:["gamepad-1","keyboard"],p2:["gamepad-2","keyboard"]},gravity:new Ao(0,0,0),variables:{}},G=Lo({...Oo});function un(s){let e=Vo(),t={};return typeof s[0]=="object"&&(t=s.shift()??{}),[{...e,...t},...s]}function Vo(){return{backgroundColor:G.backgroundColor,backgroundImage:G.backgroundImage??null,inputs:G.inputs?{...G.inputs}:void 0,gravity:G.gravity,variables:G.variables?{...G.variables}:void 0}}var ri=class{wrappedStage;options=[];_pendingEntities=[];setupCallbacks=[];updateCallbacks=[];destroyCallbacks=[];pendingLoadingCallbacks=[];eventDelegate=new hi;inputConfig=null;onInputConfigChanged=null;constructor(e){this.options=e,this.wrappedStage=null;let t=this.options[0];H.prepareGLTFRuntime(je(t?.assetLoaders?.gltf))}setInputConfiguration(...e){return this.inputConfig=ui(...e),this.onInputConfigChanged&&this.onInputConfigChanged(),this}async load(e,t,i){Me.entities=[];let r=[...this.options,...this._pendingEntities];this._pendingEntities=[],this.wrappedStage=new pt(r),this.wrappedStage.wrapperRef=this,this.pendingLoadingCallbacks.forEach(c=>{this.wrappedStage.onLoading(c)}),this.pendingLoadingCallbacks=[];let n=t instanceof w?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,Me.entities=[...Me.entities,...c]};this.wrappedStage.onEntityAdded(c=>{if(re(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 w?e.cameraRef:e;return this.wrappedStage?.addCamera(i,t)??null}removeCamera(e){return e instanceof w?this.wrappedStage?.removeCamera(e.cameraRef)??!1:this.wrappedStage?.removeCamera(e)??!1}setActiveCamera(e){return e instanceof w?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),R.emit(e,t)}listen(e,t){return this.eventDelegate.listen(e,t)}dispose(){this.eventDelegate.dispose()}};function Yu(...s){let e=un(s);return new ri([...e])}export{Wo as a,ke as b,ie as c,re as d,A as e,De as f,Te as g,Ea as h,ka as i,f as j,I as k,Oe as l,q as m,K as n,ce as o,de as p,ue as q,he as r,F as s,Ne as t,w as u,Yl as v,sc as w,Ss as x,ri as y,Yu as z};
|
package/dist/chunk-QB3NL7VQ.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{positionWorldDirection as v,positionWorld as j,normalize as k,mix as B,smoothstep as E,clamp as F,sin as W,cos as w,atan as z,asin as C,abs as D,exp as G,pow as M,step as N,max as O,min as P,floor as V,fract as q,dot as A,length as H,vec2 as I,mod as J}from"three/tsl";function o(e,r=!1){return{colorNode:e,transparent:r}}export{o as a,v as b,j as c,k as d,B as e,E as f,F as g,W as h,w as i,z as j,C as k,D as l,G as m,M as n,N as o,O as p,P as q,V as r,q as s,A as t,H as u,I as v,J as w};
|
package/dist/chunk-RPMV7GDX.js
DELETED
|
@@ -1,24 +0,0 @@
|
|
|
1
|
-
import{b as Fe,d as H,k as D,y as J,z as F}from"./chunk-P6IOYQHU.js";import{g as Ue}from"./chunk-PCFF4LLO.js";import{b as x}from"./chunk-OCQ7A5IK.js";import{b as We,c as je}from"./chunk-KIFB427K.js";import{c as K,e as Ke,f as Je}from"./chunk-2HSR5XDQ.js";import{e as ce,g as me,h as Ne,i as he,j as Xe,k as Ye,l as ge,n as Ze}from"./chunk-VKWJHFUR.js";import{d as v,g as He,h as de}from"./chunk-UM5VNQPY.js";import{k as et}from"./chunk-YRHRMVHS.js";import{a as ye,t as be}from"./chunk-VXE3CV3K.js";import{j as $e}from"./chunk-6FGXC4T6.js";import{a as _e,b as E}from"./chunk-AIQ6IVT5.js";import{t as Qe}from"./chunk-2XMG3NJS.js";import{b as qe}from"./chunk-7GYFZKK7.js";import{c as k}from"./chunk-D2PATZCC.js";import{c as ke,d as V,e as De,h as Ae,i as ze,j as Ve,k as pe,l as O,m as Oe}from"./chunk-4QLJUQSJ.js";import{j as fe}from"./chunk-7WRQ2UAN.js";import{l as L}from"./chunk-UG22Z42P.js";function yt(){return{pressed:!1,released:!1,held:0}}function bt(){return{value:0,held:0}}function $(a){let e=new Map;if(!a)return e;for(let[t,n]of Object.entries(a)){if(!n||n.length===0)continue;let i=[];for(let o of n){let[s,r]=(o||"").split(".");if(!s||!r)continue;let l=s.toLowerCase(),p=r.toLowerCase();if(l==="buttons"){let u={a:"A",b:"B",x:"X",y:"Y",start:"Start",select:"Select",l:"L",r:"R"}[p];u&&i.push({category:"buttons",property:u})}else if(l==="directions"){let u={up:"Up",down:"Down",left:"Left",right:"Right"}[p];u&&i.push({category:"directions",property:u})}else if(l==="shoulders"){let u={ltrigger:"LTrigger",rtrigger:"RTrigger"}[p];u&&i.push({category:"shoulders",property:u})}else if(l==="axes"){let u={left:{property:"Horizontal",direction:-1},right:{property:"Horizontal",direction:1},up:{property:"Vertical",direction:-1},down:{property:"Vertical",direction:1},secondaryleft:{property:"SecondaryHorizontal",direction:-1},secondaryright:{property:"SecondaryHorizontal",direction:1},secondaryup:{property:"SecondaryVertical",direction:-1},secondarydown:{property:"SecondaryVertical",direction:1}}[p];u&&i.push({category:"axes",property:u.property,axisDirection:u.direction})}}i.length>0&&e.set(t,i)}return e}function m(a,e){return!a&&!e?yt():a?e?{pressed:a.pressed||e.pressed,released:a.released||e.released,held:a.held+e.held}:{...a}:{...e}}function w(a,e){return!a&&!e?bt():a?e?{value:a.value+e.value,held:a.held+e.held}:{...a}:{...e}}var A=class{keyStates=new Map;keyButtonStates=new Map;analogStates=new Map;compiledMapping;includeDefaultBase=!0;onKeyDown=({key:e})=>this.keyStates.set(e,!0);onKeyUp=({key:e})=>this.keyStates.set(e,!1);constructor(e,t){this.includeDefaultBase=t?.includeDefaultBase??!0,this.compiledMapping=$(e??null),window.addEventListener("keydown",this.onKeyDown),window.addEventListener("keyup",this.onKeyUp)}dispose(){window.removeEventListener("keydown",this.onKeyDown),window.removeEventListener("keyup",this.onKeyUp),this.keyStates.clear(),this.keyButtonStates.clear(),this.analogStates.clear()}isKeyPressed(e){return this.keyStates.get(e)||!1}handleButtonState(e,t){let n=this.keyButtonStates.get(e);n||(n={pressed:!1,released:!1,held:0},this.keyButtonStates.set(e,n));let i=this.isKeyPressed(e);return n.pressed=i&&n.held===0,n.released=!i&&n.held>0,n.held=i?n.held+t:0,n}handleAnalogState(e,t,n){let i=`${e}:${t}`,o=this.analogStates.get(i);return o||(o={value:0,held:0},this.analogStates.set(i,o)),o.value=this.getAxisValue(e,t),o.held=o.value!==0?o.held+n:0,o}applyCustomMapping(e,t){if(this.compiledMapping.size===0)return e;let n=new Map;for(let[i,o]of this.compiledMapping.entries()){let s=null;for(let r of o)if(r.category==="axes")n.has(r.property)||n.set(r.property,0),this.isKeyPressed(i)&&n.set(r.property,n.get(r.property)+r.axisDirection);else{s||(s=this.handleButtonState(i,t));let l=e[r.category]??={};l[r.property]=m(l[r.property],s)}}if(n.size>0){e.axes||(e.axes={});for(let[i,o]of n.entries()){let s=`custom:${i}`,r=this.analogStates.get(s);r||(r={value:0,held:0},this.analogStates.set(s,r)),r.value=o,r.held=o!==0?r.held+t:0,e.axes[i]=w(e.axes[i],r)}}return e}getInput(e){let t={};return this.includeDefaultBase&&(t.buttons={A:this.handleButtonState("z",e),B:this.handleButtonState("x",e),X:this.handleButtonState("a",e),Y:this.handleButtonState("s",e),Start:this.handleButtonState(" ",e),Select:this.handleButtonState("Enter",e),L:this.handleButtonState("q",e),R:this.handleButtonState("e",e)},t.directions={Up:this.handleButtonState("ArrowUp",e),Down:this.handleButtonState("ArrowDown",e),Left:this.handleButtonState("ArrowLeft",e),Right:this.handleButtonState("ArrowRight",e)},t.shoulders={LTrigger:this.handleButtonState("Q",e),RTrigger:this.handleButtonState("E",e)}),this.applyCustomMapping(t,e)}getName(){return"keyboard"}getAxisValue(e,t){return(this.isKeyPressed(t)?1:0)-(this.isKeyPressed(e)?1:0)}isConnected(){return!0}};var W=class{gamepadIndex;connected=!1;buttonStates={};analogStates={};onConnected=e=>{e.gamepad.index===this.gamepadIndex&&(this.connected=!0)};onDisconnected=e=>{e.gamepad.index===this.gamepadIndex&&(this.connected=!1)};constructor(e){this.gamepadIndex=e,window.addEventListener("gamepadconnected",this.onConnected),window.addEventListener("gamepaddisconnected",this.onDisconnected)}dispose(){window.removeEventListener("gamepadconnected",this.onConnected),window.removeEventListener("gamepaddisconnected",this.onDisconnected),this.buttonStates={},this.analogStates={}}handleButtonState(e,t,n){let i=this.buttonStates[e];i||(i={pressed:!1,released:!1,held:0},this.buttonStates[e]=i);let o=t.buttons[e].pressed;return i.pressed=o&&i.held===0,i.released=!o&&i.held>0,i.held=o?i.held+n:0,i}handleAnalogState(e,t,n){let i=this.analogStates[e];return i||(i={value:0,held:0},this.analogStates[e]=i),i.value=t.axes[e],i.held=i.value!==0?i.held+n:0,i}getInput(e){let t=navigator.getGamepads()[this.gamepadIndex];return t?{buttons:{A:this.handleButtonState(0,t,e),B:this.handleButtonState(1,t,e),X:this.handleButtonState(2,t,e),Y:this.handleButtonState(3,t,e),Start:this.handleButtonState(9,t,e),Select:this.handleButtonState(8,t,e),L:this.handleButtonState(4,t,e),R:this.handleButtonState(5,t,e)},directions:{Up:this.handleButtonState(12,t,e),Down:this.handleButtonState(13,t,e),Left:this.handleButtonState(14,t,e),Right:this.handleButtonState(15,t,e)},axes:{Horizontal:this.handleAnalogState(0,t,e),Vertical:this.handleAnalogState(1,t,e),SecondaryHorizontal:this.handleAnalogState(2,t,e),SecondaryVertical:this.handleAnalogState(3,t,e)},shoulders:{LTrigger:this.handleButtonState(6,t,e),RTrigger:this.handleButtonState(7,t,e)}}:{}}getName(){return`gamepad-${this.gamepadIndex+1}`}isConnected(){return this.connected}};import{subscribe as vt}from"valtio/vanilla";var St=.002;function j(a,e,t){return Math.max(e,Math.min(t,a))}function wt(a){if(a instanceof HTMLCanvasElement)return a;let e=a.querySelector("canvas");if(e instanceof HTMLCanvasElement)return e;for(let t of a.querySelectorAll("*")){let n=t.shadowRoot;if(!n)continue;let i=n.querySelector("canvas");if(i instanceof HTMLCanvasElement)return i}return null}var U=class{buttonStates=new Map;analogStates=new Map;compiledMapping;movementX=0;movementY=0;pointerX=.5;pointerY=.5;pointerCenterX=0;pointerCenterY=0;mouseButtonDown=new Set;sensitivity;usePointerLock;lookMode;isLocked=!1;targetElement;debugUnsubscribe=null;updatePointerPosition(e,t){this.pointerX=e/window.innerWidth,this.pointerY=t/window.innerHeight;let n=wt(this.targetElement);if(n){let i=n.getBoundingClientRect();if(i.width>0&&i.height>0){let o=i.left+i.width/2,s=i.top+i.height/2;this.pointerCenterX=j((e-o)/(i.width/2),-1,1),this.pointerCenterY=j((t-s)/(i.height/2),-1,1);return}}this.pointerCenterX=j((this.pointerX-.5)*2,-1,1),this.pointerCenterY=j((this.pointerY-.5)*2,-1,1)}onMouseMove=e=>{this.updatePointerPosition(e.clientX,e.clientY),!(v.enabled||this.lookMode==="screenCenter")&&(this.movementX+=e.movementX,this.movementY+=e.movementY)};onMouseDown=e=>{let t=e.target;t instanceof HTMLCanvasElement&&this.targetElement.contains(t)&&(this.mouseButtonDown.add(e.button),this.usePointerLock&&!this.isLocked&&!v.enabled&&this.targetElement.requestPointerLock())};onMouseUp=e=>{this.mouseButtonDown.delete(e.button)};onContextMenu=e=>{e.preventDefault()};onPointerLockChange=()=>{this.isLocked=document.pointerLockElement===this.targetElement};constructor(e,t){this.sensitivity=e?.sensitivity??St,this.lookMode=e?.lookMode??"delta",this.usePointerLock=e?.pointerLock??!1,this.compiledMapping=$(e?.mapping??null),this.targetElement=t??document.body,window.addEventListener("mousemove",this.onMouseMove),this.targetElement.addEventListener("mousedown",this.onMouseDown),this.targetElement.addEventListener("mouseup",this.onMouseUp),this.targetElement.addEventListener("contextmenu",this.onContextMenu),this.usePointerLock&&(document.addEventListener("pointerlockchange",this.onPointerLockChange),this.debugUnsubscribe=vt(v,()=>{v.enabled&&document.pointerLockElement===this.targetElement&&document.exitPointerLock()}))}dispose(){window.removeEventListener("mousemove",this.onMouseMove),this.targetElement.removeEventListener("mousedown",this.onMouseDown),this.targetElement.removeEventListener("mouseup",this.onMouseUp),this.targetElement.removeEventListener("contextmenu",this.onContextMenu),document.removeEventListener("pointerlockchange",this.onPointerLockChange),this.debugUnsubscribe?.(),this.debugUnsubscribe=null,this.isLocked&&document.exitPointerLock(),this.buttonStates.clear(),this.analogStates.clear(),this.mouseButtonDown.clear(),this.movementX=0,this.movementY=0}handleMouseButton(e,t){let n=this.buttonStates.get(e);n||(n={pressed:!1,released:!1,held:0},this.buttonStates.set(e,n));let i=this.mouseButtonDown.has(e);return n.pressed=i&&n.held===0,n.released=!i&&n.held>0,n.held=i?n.held+t:0,n}handleMovementAxis(e,t){let n=this.analogStates.get(e);n||(n={value:0,held:0},this.analogStates.set(e,n));let i=e==="x"?this.movementX:this.movementY;return n.value=Math.max(-1,Math.min(1,i*this.sensitivity)),n.held=n.value!==0?n.held+t:0,n}applyCustomMapping(e,t){if(this.compiledMapping.size===0)return e;let n=new Map,i={leftbutton:()=>this.handleMouseButton(0,t),rightbutton:()=>this.handleMouseButton(2,t),middlebutton:()=>this.handleMouseButton(1,t)};for(let[o,s]of this.compiledMapping.entries()){let r=o.toLowerCase();for(let l of s)if(l.category==="axes")n.has(l.property)||n.set(l.property,0),r==="movex"?n.set(l.property,n.get(l.property)+Math.max(-1,Math.min(1,this.movementX*this.sensitivity))*l.axisDirection):r==="movey"?n.set(l.property,n.get(l.property)+Math.max(-1,Math.min(1,this.movementY*this.sensitivity))*l.axisDirection):r in i&&this.mouseButtonDown.has(this.buttonIndexForAction(r))&&n.set(l.property,n.get(l.property)+l.axisDirection);else{let p=i[r];if(p){let g=p();if(g){let u=e[l.category]??={};u[l.property]=m(u[l.property],g)}}}}if(n.size>0){e.axes||(e.axes={});for(let[o,s]of n.entries()){let r=`custom:${o}`,l=this.analogStates.get(r);l||(l={value:0,held:0},this.analogStates.set(r,l)),l.value=Math.max(-1,Math.min(1,s)),l.held=s!==0?l.held+t:0,e.axes[o]=w(e.axes[o],l)}}return e}buttonIndexForAction(e){switch(e){case"leftbutton":return 0;case"middlebutton":return 1;case"rightbutton":return 2;default:return-1}}getInput(e){v.enabled&&(this.movementX=0,this.movementY=0);let t={value:0,held:0},n=this.lookMode==="delta",i={axes:{Horizontal:t,Vertical:t,SecondaryHorizontal:n?this.handleMovementAxis("x",e):t,SecondaryVertical:n?this.handleMovementAxis("y",e):t},shoulders:{LTrigger:this.handleMouseButton(0,e),RTrigger:this.handleMouseButton(2,e)},pointer:{x:this.pointerX,y:this.pointerY,centerX:this.pointerCenterX,centerY:this.pointerCenterY}};return this.movementX=0,this.movementY=0,this.applyCustomMapping(i,e)}getName(){return"mouse"}isConnected(){return!0}};function _(a={}){if(typeof window>"u"||typeof navigator>"u")return!1;let e=navigator.userAgent,t=/android/i.test(e)||/iPad|iPhone|iPod/.test(e),n="ontouchstart"in window||navigator.maxTouchPoints>0,i=typeof window.matchMedia=="function"?window.matchMedia("(pointer: coarse)").matches:!1,o=a.viewportSize?.width??window.innerWidth??0,s=a.viewportSize?.height??window.innerHeight??0,r=Math.max(o,s),l=r===0||r<=1024;return a.allowViewportOnly&&a.viewportSize?l:t||(n||i)&&l}var Ct=["A","B","X","Y","Start","Select","L","R","LTrigger","RTrigger","Up","Down","Left","Right"],xt=new Set(["flex","flexGrow","flexShrink","fontWeight","lineHeight","opacity","order","zIndex","zoom"]),Et={A:{size:72,label:"A",position:{right:98,bottom:44}},B:{size:72,label:"B",position:{right:24,bottom:108}},X:{size:72,label:"X",position:{right:172,bottom:108}},Y:{size:72,label:"Y",position:{right:98,bottom:172}},Start:{size:64,label:"Start",position:{left:"50%",top:24,transform:"translateX(28px)"}},Select:{size:64,label:"Select",position:{left:"50%",top:24,transform:"translateX(-108px)"}},L:{size:62,label:"L",position:{left:28,bottom:184}},R:{size:62,label:"R",position:{right:236,bottom:184}},LTrigger:{size:76,label:"LT",position:{left:24,top:24}},RTrigger:{size:76,label:"RT",position:{right:24,top:24}},Up:{enabled:!1,size:64,label:"Up"},Down:{enabled:!1,size:64,label:"Down"},Left:{enabled:!1,size:64,label:"Left"},Right:{enabled:!1,size:64,label:"Right"}},Gt={left:{size:140,thumbSize:58,maxDistance:44,deadzone:.12,directionThreshold:.34,horizontalAxis:"Horizontal",verticalAxis:"Vertical",emitDirections:!0,position:{left:24,bottom:24}},right:{size:140,thumbSize:58,maxDistance:44,deadzone:.12,directionThreshold:.34,horizontalAxis:"SecondaryHorizontal",verticalAxis:"SecondaryVertical",emitDirections:!1,position:{right:24,bottom:236}}},X=class{config;targetElement;buttonStates=new Map;analogStates=new Map;buttons=new Map;joysticks=new Map;rootElement=null;enabled=!1;onPointerMove=e=>{for(let t of this.joysticks.values())t.pointerId===e.pointerId&&(this.consumeEvent(e),this.updateJoystickFromPoint(t,e.clientX,e.clientY))};onPointerUp=e=>{for(let t of this.buttons.values())t.pointerId===e.pointerId&&(this.consumeEvent(e),this.releaseButton(t));for(let t of this.joysticks.values())t.pointerId===e.pointerId&&(this.consumeEvent(e),this.releaseJoystick(t))};onWindowBlur=()=>{for(let e of this.buttons.values())this.releaseButton(e);for(let e of this.joysticks.values())this.releaseJoystick(e)};constructor(e,t){this.config=e??{},this.targetElement=t??document.body,this.enabled=this.resolveEnabledState(),this.enabled&&(this.mountControls(),window.addEventListener("pointermove",this.onPointerMove),window.addEventListener("pointerup",this.onPointerUp),window.addEventListener("pointercancel",this.onPointerUp),window.addEventListener("blur",this.onWindowBlur))}getInput(e){if(!this.enabled)return{};let t={};for(let n of this.buttons.values()){let i=this.handleButtonState(`button:${n.slot}`,n.pointerId!==null,e);this.assignButtonState(t,this.resolveButtonTarget(n.slot),i)}for(let n of this.joysticks.values()){let i=this.handleAnalogState(`joystick:${n.id}:x`,n.valueX,e),o=this.handleAnalogState(`joystick:${n.id}:y`,n.valueY,e);this.assignAxisState(t,n.config.horizontalAxis,i),this.assignAxisState(t,n.config.verticalAxis,o),n.config.emitDirections&&(this.assignButtonState(t,this.resolveButtonTarget("Left"),this.handleButtonState(`joystick:${n.id}:left`,n.valueX<=-n.config.directionThreshold,e)),this.assignButtonState(t,this.resolveButtonTarget("Right"),this.handleButtonState(`joystick:${n.id}:right`,n.valueX>=n.config.directionThreshold,e)),this.assignButtonState(t,this.resolveButtonTarget("Up"),this.handleButtonState(`joystick:${n.id}:up`,n.valueY<=-n.config.directionThreshold,e)),this.assignButtonState(t,this.resolveButtonTarget("Down"),this.handleButtonState(`joystick:${n.id}:down`,n.valueY>=n.config.directionThreshold,e)))}return t}getName(){return"virtual-touch"}isConnected(){return this.enabled}dispose(){window.removeEventListener("pointermove",this.onPointerMove),window.removeEventListener("pointerup",this.onPointerUp),window.removeEventListener("pointercancel",this.onPointerUp),window.removeEventListener("blur",this.onWindowBlur),this.rootElement?.remove(),this.rootElement=null,this.buttons.clear(),this.joysticks.clear(),this.buttonStates.clear(),this.analogStates.clear()}resolveEnabledState(){return typeof window>"u"||typeof document>"u"?!1:this.config.enabled===!0?!0:this.config.enabled===!1?!1:_()}mountControls(){this.rootElement=document.createElement("div"),this.rootElement.className="zylem-virtual-touch",this.rootElement.dataset.zylemTouchRoot="true",this.rootElement.style.position="absolute",this.rootElement.style.inset="0",this.rootElement.style.pointerEvents="none",this.rootElement.style.touchAction="none",this.rootElement.style.userSelect="none",this.rootElement.style.WebkitUserSelect="none",this.rootElement.style.WebkitTouchCallout="none",this.rootElement.style.color="rgba(245, 247, 255, 0.96)",this.rootElement.style.zIndex="20",this.appendClassName(this.rootElement,this.config.className),N(this.rootElement,this.config.style),this.rootElement.addEventListener("contextmenu",e=>e.preventDefault());for(let[e,t]of this.resolveButtons())this.rootElement.appendChild(this.createButton(e,t));for(let[e,t]of this.resolveJoysticks())this.rootElement.appendChild(this.createJoystick(e,t));this.targetElement.appendChild(this.rootElement)}resolveButtons(){if(this.config.buttons===!1)return[];let e=this.config.buttons,t=[];for(let n of Ct){let i=Et[n],o=e?.[n];if(o===!1)continue;let s={...i,...o??{},style:{...i.style,...o?.style},position:{...i.position,...o?.position},label:o?.label??i.label??n,size:o?.size??i.size??72};s.enabled!==!1&&t.push([n,s])}return t}resolveJoysticks(){if(this.config.joysticks===!1)return[];let e=this.config.joysticks,t=[];for(let n of["left","right"]){let i=Gt[n],o=e?.[n];if(o===!1)continue;let s={...i,...o??{},style:{...i.style,...o?.style},position:{...i.position,...o?.position},svg:{...i.svg,...o?.svg},size:o?.size??i.size??140,thumbSize:o?.thumbSize??i.thumbSize??58,maxDistance:o?.maxDistance??i.maxDistance??44,deadzone:o?.deadzone??i.deadzone??.12,directionThreshold:o?.directionThreshold??i.directionThreshold??.34,horizontalAxis:o?.horizontalAxis??i.horizontalAxis??"Horizontal",verticalAxis:o?.verticalAxis??i.verticalAxis??"Vertical",emitDirections:o?.emitDirections??i.emitDirections??!1};s.enabled!==!1&&t.push([n,s])}return t}createButton(e,t){let n=document.createElement("button"),i=document.createElement("div");n.type="button",n.ariaLabel=t.label,n.className=`zylem-virtual-touch__button zylem-virtual-touch__button--${e}`,n.dataset.zylemTouchButton=e,n.dataset.active="false",n.style.position="absolute",n.style.width=`${t.size}px`,n.style.height=`${t.size}px`,n.style.padding="0",n.style.margin="0",n.style.border="0",n.style.background="transparent",n.style.pointerEvents="auto",n.style.touchAction="none",n.style.cursor="pointer",n.style.appearance="none",n.style.outline="none",n.style.userSelect="none",n.style.WebkitTapHighlightColor="transparent",N(n,t.position),N(n,t.style),this.appendClassName(n,t.className),i.className="zylem-virtual-touch__button-content",i.style.width="100%",i.style.height="100%",i.style.pointerEvents="none",i.style.transform="scale(1)",i.style.transformOrigin="center",i.style.transition="transform 120ms ease, opacity 120ms ease",i.style.opacity="0.92",i.innerHTML=t.svg??Rt(t.label),n.appendChild(i),n.addEventListener("pointerdown",s=>{if(!tt(s))return;let r=this.buttons.get(e);!r||r.pointerId!==null||(this.consumeEvent(s),r.pointerId=s.pointerId,this.updateButtonVisual(r,!0))});let o={slot:e,config:t,element:n,content:i,pointerId:null};return this.buttons.set(e,o),n}createJoystick(e,t){let n=document.createElement("div"),i=document.createElement("div"),o=document.createElement("div");n.className=`zylem-virtual-touch__joystick zylem-virtual-touch__joystick--${e}`,n.dataset.zylemTouchJoystick=e,n.dataset.active="false",n.style.position="absolute",n.style.width=`${t.size}px`,n.style.height=`${t.size}px`,n.style.pointerEvents="auto",n.style.touchAction="none",n.style.userSelect="none",N(n,t.position),N(n,t.style),this.appendClassName(n,t.className),i.className="zylem-virtual-touch__joystick-base",i.style.position="absolute",i.style.inset="0",i.style.pointerEvents="none",i.style.opacity="0.88",i.style.transition="opacity 120ms ease",i.innerHTML=t.svg?.base??Pt(),o.className="zylem-virtual-touch__joystick-thumb",o.style.position="absolute",o.style.left="50%",o.style.top="50%",o.style.width=`${t.thumbSize}px`,o.style.height=`${t.thumbSize}px`,o.style.pointerEvents="none",o.style.transform="translate(-50%, -50%) translate(0px, 0px)",o.style.transition="transform 60ms linear, opacity 120ms ease",o.style.opacity="0.94",o.innerHTML=t.svg?.thumb??Bt(),n.append(i,o);let s={id:e,config:t,element:n,base:i,thumb:o,pointerId:null,centerX:0,centerY:0,rawX:0,rawY:0,valueX:0,valueY:0};return this.joysticks.set(e,s),n.addEventListener("pointerdown",r=>{if(!tt(r))return;let l=this.joysticks.get(e);if(!l||l.pointerId!==null)return;this.consumeEvent(r);let p=l.element.getBoundingClientRect();l.pointerId=r.pointerId,l.centerX=p.left+p.width/2,l.centerY=p.top+p.height/2,this.updateJoystickVisual(l,!0),this.updateJoystickFromPoint(l,r.clientX,r.clientY)}),n}handleButtonState(e,t,n){let i=this.buttonStates.get(e);return i||(i={pressed:!1,released:!1,held:0},this.buttonStates.set(e,i)),i.pressed=t&&i.held===0,i.released=!t&&i.held>0,i.held=t?i.held+n:0,i}handleAnalogState(e,t,n){let i=this.analogStates.get(e);return i||(i={value:0,held:0},this.analogStates.set(e,i)),i.value=t,i.held=t!==0?i.held+n:0,i}assignAxisState(e,t,n){e.axes||(e.axes={}),e.axes[t]=w(e.axes[t],n)}assignButtonState(e,t,n){if(t.category==="buttons"){e.buttons??={},e.buttons[t.property]=m(e.buttons[t.property],n);return}if(t.category==="directions"){e.directions??={},e.directions[t.property]=m(e.directions[t.property],n);return}e.shoulders??={},e.shoulders[t.property]=m(e.shoulders[t.property],n)}resolveButtonTarget(e){switch(e){case"LTrigger":case"RTrigger":return{category:"shoulders",property:e};case"Up":case"Down":case"Left":case"Right":return{category:"directions",property:e};default:return{category:"buttons",property:e}}}updateJoystickFromPoint(e,t,n){let i=t-e.centerX,o=n-e.centerY,s=Math.hypot(i,o),r=e.config.maxDistance,l=s>r&&s>0?r/s:1;e.rawX=i*l,e.rawY=o*l;let p=Tt(e.rawX/r,e.rawY/r,e.config.deadzone);e.valueX=p.x,e.valueY=p.y,e.thumb.style.transform=`translate(-50%, -50%) translate(${e.rawX}px, ${e.rawY}px)`}releaseButton(e){e.pointerId=null,this.updateButtonVisual(e,!1)}releaseJoystick(e){e.pointerId=null,e.rawX=0,e.rawY=0,e.valueX=0,e.valueY=0,e.thumb.style.transform="translate(-50%, -50%) translate(0px, 0px)",this.updateJoystickVisual(e,!1)}updateButtonVisual(e,t){e.element.dataset.active=String(t),e.content.style.transform=t?"scale(0.94)":"scale(1)",e.content.style.opacity=t?"1":"0.92"}updateJoystickVisual(e,t){e.element.dataset.active=String(t),e.base.style.opacity=t?"1":"0.88",e.thumb.style.opacity=t?"1":"0.94"}consumeEvent(e){e.cancelable&&e.preventDefault(),e.stopPropagation()}appendClassName(e,t){t&&(e.className=`${e.className} ${t}`.trim())}};function N(a,e){if(e)for(let[t,n]of Object.entries(e)){if(n==null)continue;let i=typeof n=="number"&&!xt.has(t)?`${n}px`:String(n);t.includes("-")?a.style.setProperty(t,i):a.style[t]=i}}function Tt(a,e,t){let n=Math.hypot(a,e);if(n===0||n<=t)return{x:0,y:0};let o=Math.min(1,(n-t)/Math.max(1-t,1e-4))/n;return{x:a*o,y:e*o}}function Rt(a){let e=Mt(a);return`
|
|
2
|
-
<svg viewBox="0 0 100 100" width="100%" height="100%" aria-hidden="true">
|
|
3
|
-
<circle cx="50" cy="50" r="45" fill="rgba(12,18,24,0.72)" stroke="currentColor" stroke-width="4" />
|
|
4
|
-
<circle cx="50" cy="50" r="34" fill="rgba(255,255,255,0.06)" stroke="rgba(255,255,255,0.12)" stroke-width="1.5" />
|
|
5
|
-
<text
|
|
6
|
-
x="50"
|
|
7
|
-
y="56"
|
|
8
|
-
text-anchor="middle"
|
|
9
|
-
font-family="ui-sans-serif, system-ui, sans-serif"
|
|
10
|
-
font-size="${e.length>2?24:34}"
|
|
11
|
-
font-weight="700"
|
|
12
|
-
fill="currentColor"
|
|
13
|
-
>${e}</text>
|
|
14
|
-
</svg>
|
|
15
|
-
`}function Pt(){return`
|
|
16
|
-
<svg viewBox="0 0 140 140" width="100%" height="100%" aria-hidden="true">
|
|
17
|
-
<circle cx="70" cy="70" r="62" fill="rgba(10,16,20,0.64)" stroke="currentColor" stroke-width="4" />
|
|
18
|
-
<circle cx="70" cy="70" r="40" fill="rgba(255,255,255,0.04)" stroke="rgba(255,255,255,0.12)" stroke-width="1.5" />
|
|
19
|
-
</svg>
|
|
20
|
-
`}function Bt(){return`
|
|
21
|
-
<svg viewBox="0 0 64 64" width="100%" height="100%" aria-hidden="true">
|
|
22
|
-
<circle cx="32" cy="32" r="28" fill="rgba(22,30,38,0.9)" stroke="currentColor" stroke-width="3.5" />
|
|
23
|
-
</svg>
|
|
24
|
-
`}function Mt(a){return a.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""").replaceAll("'","'")}function tt(a){return a.pointerType==="touch"}var q=class{inputMap=new Map;currentInputs={};previousInputs={};targetElement;mouseTargetElement;constructor(e,t){this.targetElement=t?.targetElement,this.mouseTargetElement=t?.mouseTargetElement??t?.targetElement;let n=this.buildPlayerEntries(e);for(let{player:i,config:o,gamepadIndex:s,isP1:r}of n)this.addConfigurableProviders(i,o,r),this.addInputProvider(i,new W(s))}configure(e){let t=this.buildPlayerEntries(e);for(let{player:n,config:i,isP1:o}of t){let r=(this.inputMap.get(n)??[]).filter(l=>l instanceof A||l instanceof U||l instanceof X?(l.dispose(),!1):!0);this.inputMap.set(n,[...this.createConfigurableProviders(i,o),...r])}}addInputProvider(e,t){this.inputMap.has(e)||this.inputMap.set(e,[]),this.inputMap.get(e)?.push(t)}dispose(){for(let e of this.inputMap.values())for(let t of e)t.dispose?.();this.inputMap.clear(),this.currentInputs={},this.previousInputs={}}getInputs(e){let t={};return this.inputMap.forEach((n,i)=>{let o=`p${i}`,s=n.reduce((r,l)=>{let p=l.getInput(e);return this.mergeInputs(r,p)},{});t[o]={playerNumber:i,...s}}),t}buildPlayerEntries(e){return[{player:1,config:e?.p1,gamepadIndex:0,isP1:!0},{player:2,config:e?.p2,gamepadIndex:1,isP1:!1},{player:3,config:e?.p3,gamepadIndex:2,isP1:!1},{player:4,config:e?.p4,gamepadIndex:3,isP1:!1},{player:5,config:e?.p5,gamepadIndex:4,isP1:!1},{player:6,config:e?.p6,gamepadIndex:5,isP1:!1},{player:7,config:e?.p7,gamepadIndex:6,isP1:!1},{player:8,config:e?.p8,gamepadIndex:7,isP1:!1}]}addConfigurableProviders(e,t,n){for(let i of this.createConfigurableProviders(t,n))this.addInputProvider(e,i)}createConfigurableProviders(e,t){let n=[];if(e?.key){let i=e.includeDefaults??t;n.push(new A(e.key,{includeDefaultBase:i}))}else t&&n.push(new A);return e?.mouse&&n.push(new U(e.mouse,this.mouseTargetElement)),e?.touch&&n.push(new X(e.touch,this.targetElement)),n}mergeInputs(e,t){return{buttons:{A:m(e.buttons?.A,t.buttons?.A),B:m(e.buttons?.B,t.buttons?.B),X:m(e.buttons?.X,t.buttons?.X),Y:m(e.buttons?.Y,t.buttons?.Y),Start:m(e.buttons?.Start,t.buttons?.Start),Select:m(e.buttons?.Select,t.buttons?.Select),L:m(e.buttons?.L,t.buttons?.L),R:m(e.buttons?.R,t.buttons?.R)},directions:{Up:m(e.directions?.Up,t.directions?.Up),Down:m(e.directions?.Down,t.directions?.Down),Left:m(e.directions?.Left,t.directions?.Left),Right:m(e.directions?.Right,t.directions?.Right)},axes:{Horizontal:w(e.axes?.Horizontal,t.axes?.Horizontal),Vertical:w(e.axes?.Vertical,t.axes?.Vertical),SecondaryHorizontal:w(e.axes?.SecondaryHorizontal,t.axes?.SecondaryHorizontal),SecondaryVertical:w(e.axes?.SecondaryVertical,t.axes?.SecondaryVertical)},shoulders:{LTrigger:m(e.shoulders?.LTrigger,t.shoulders?.LTrigger),RTrigger:m(e.shoulders?.RTrigger,t.shoulders?.RTrigger)},pointer:t.pointer??e.pointer}}};var Q=class{_previousTime;_currentTime;_startTime;_delta;_elapsed;_timescale;_document;_pageVisibilityHandler;constructor(){this._previousTime=0,this._currentTime=0,this._startTime=ve(),this._delta=0,this._elapsed=0,this._timescale=1,this._document=null,this._pageVisibilityHandler=null}connect(e){this._document=e,e.hidden!==void 0&&(this._pageVisibilityHandler=It.bind(this),e.addEventListener("visibilitychange",this._pageVisibilityHandler,!1))}disconnect(){this._pageVisibilityHandler!==null&&(this._document.removeEventListener("visibilitychange",this._pageVisibilityHandler),this._pageVisibilityHandler=null),this._document=null}getDelta(){return this._delta/1e3}getElapsed(){return this._elapsed/1e3}getTimescale(){return this._timescale}setTimescale(e){return this._timescale=e,this}reset(){return this._currentTime=ve()-this._startTime,this}dispose(){this.disconnect()}update(e){return this._pageVisibilityHandler!==null&&this._document.hidden===!0?this._delta=0:(this._previousTime=this._currentTime,this._currentTime=(e!==void 0?e:ve())-this._startTime,this._delta=(this._currentTime-this._previousTime)*this._timescale,this._elapsed+=this._delta),this}};function ve(){return performance.now()}function It(){this._document.hidden===!1&&this.reset()}var Y={FourByThree:1.3333333333333333,SixteenByNine:1.7777777777777777,NineBySixteen:.5625,TwentyOneByNine:2.3333333333333335,OneByOne:1},ee=class{container;canvas;aspectRatio;onResize;handleResizeBound;resizeObserver=null;constructor(e){this.container=e.container,this.canvas=e.canvas,this.aspectRatio=(typeof e.aspectRatio=="number",e.aspectRatio),this.onResize=e.onResize,this.handleResizeBound=this.apply.bind(this)}attach(){window.addEventListener("resize",this.handleResizeBound),typeof ResizeObserver<"u"&&(this.resizeObserver=new ResizeObserver(this.handleResizeBound),this.resizeObserver.observe(this.container)),this.apply()}detach(){window.removeEventListener("resize",this.handleResizeBound),this.resizeObserver?.disconnect(),this.resizeObserver=null}measure(){let e=this.container.getBoundingClientRect(),t=Math.round(e.width||this.container.clientWidth||0),n=Math.round(e.height||this.container.clientHeight||0);if(t>0&&n>0){if(t/n>this.aspectRatio){let p=n;return{width:Math.round(p*this.aspectRatio),height:p}}let r=t,l=Math.round(r/this.aspectRatio);return{width:r,height:l}}if(t>0){let s=t,r=Math.round(s/this.aspectRatio);return{width:s,height:r}}if(n>0){let s=n;return{width:Math.round(s*this.aspectRatio),height:s}}let i=window.innerWidth,o=Math.round(i/this.aspectRatio);return{width:i,height:o}}apply(){let{width:e,height:t}=this.measure();this.canvas.style.width=`${e}px`,this.canvas.style.height=`${t}px`,this.onResize?.(e,t)}};var nt={NES:{displayAspect:1.3333333333333333,resolutions:[{key:"256x240",width:256,height:240,notes:"Standard NTSC; effective 240p."}]},SNES:{displayAspect:1.3333333333333333,resolutions:[{key:"256x224",width:256,height:224,notes:"Common 240p-equivalent mode."},{key:"512x448",width:512,height:448,notes:"Hi-res interlaced (480i)."}]},N64:{displayAspect:1.3333333333333333,resolutions:[{key:"320x240",width:320,height:240,notes:"Common 240p mode."},{key:"640x480",width:640,height:480,notes:"Higher resolution (480i)."}]},PS1:{displayAspect:1.3333333333333333,resolutions:[{key:"320x240",width:320,height:240,notes:"Progressive 240p common."},{key:"640x480",width:640,height:480,notes:"Interlaced 480i for higher detail."}]},PS2:{displayAspect:1.3333333333333333,resolutions:[{key:"640x480",width:640,height:480,notes:"480i/480p baseline."},{key:"720x480",width:720,height:480,notes:"480p (widescreen capable in some titles)."},{key:"1280x720",width:1280,height:720,notes:"720p (select titles)."}]},PS5:{displayAspect:1.7777777777777777,resolutions:[{key:"720x480",width:720,height:480,notes:"Legacy compatibility."},{key:"1280x720",width:1280,height:720,notes:"720p."},{key:"1920x1080",width:1920,height:1080,notes:"1080p."},{key:"2560x1440",width:2560,height:1440,notes:"1440p."},{key:"3840x2160",width:3840,height:2160,notes:"4K (up to 120Hz)."},{key:"7680x4320",width:7680,height:4320,notes:"8K (limited)."}]},XboxOne:{displayAspect:1.7777777777777777,resolutions:[{key:"1280x720",width:1280,height:720,notes:"720p (original)."},{key:"1920x1080",width:1920,height:1080,notes:"1080p (original)."},{key:"3840x2160",width:3840,height:2160,notes:"4K UHD (S/X models)."}]},MobilePortrait:{displayAspect:.5625,resolutions:[{key:"360x640",width:360,height:640,notes:"Low-density phone portrait baseline."},{key:"720x1280",width:720,height:1280,notes:"HD phone portrait."},{key:"1080x1920",width:1080,height:1920,notes:"Full HD phone portrait."}]}};function Se(a){return nt[a].displayAspect}function we(a,e){let t=nt[a]?.resolutions||[];if(!e)return t[0];let n=e.toLowerCase().replace(/\s+/g,"").replace("\xD7","x");return t.find(i=>i.key.toLowerCase()===n)}function Ce(a){if(!a)return null;let t=String(a).toLowerCase().trim().replace(/\s+/g,"").replace("\xD7","x").match(/^(\d+)x(\d+)$/);if(!t)return null;let n=parseInt(t[1],10),i=parseInt(t[2],10);return!Number.isFinite(n)||!Number.isFinite(i)?null:{width:n,height:i}}var xe=null,Ee=class{constructor(e,t,n,i,o,s,r,l,p,g,u,d,S){this.id=e;this.globals=t;this.stages=n;this.debug=i;this.time=o;this.input=s;this.aspectRatio=r;this.internalResolution=l;this.fullscreen=p;this.bodyBackground=g;this.container=u;this.containerId=d;this.canvas=S}};function Lt(a={}){return a.deviceProfile==="mobile"?!0:a.deviceProfile==="desktop"?!1:a.viewportSize?_({viewportSize:a.viewportSize,allowViewportOnly:!0}):_()}function kt(a,e){if(e)return e;if(a){let i=document.getElementById(a);if(i)return i}let t=a||"zylem-root",n=document.createElement("main");return n.setAttribute("id",t),n.style.position="relative",n.style.width="100%",n.style.height="100%",document.body.appendChild(n),n}function Dt(a){let e=a?.id??"zylem";return{id:e,globals:a?.globals??{},stages:a?.stages??[],debug:!!a?.debug,time:a?.time??0,input:a?.input,aspectRatio:Y.SixteenByNine,fullscreen:!0,bodyBackground:"#000000",containerId:e}}var it=360;function at(a,e){if(!a)return;if(typeof a=="string"){if(a==="native")return xe;let i=Ce(a);if(i)return i;if(e){let o=we(e,a);if(o)return{width:o.width,height:o.height}}return}let t=a.width,n=a.height;if(Number.isFinite(t)&&Number.isFinite(n))return{width:t,height:n}}function At(a,e,t,n){if(typeof a=="number")return a;if(typeof a=="string")return Y[a]??t;if(e)try{return Se(e)||t}catch{return t}return n?n.width/n.height:t}function zt(a){let e=Number.isFinite(a)&&a>0?a:Y.SixteenByNine;if(e>=1){let i=it;return{width:Math.round(i*e),height:i}}let t=it,n=Math.round(t/e);return{width:t,height:n}}function Z(a,e={}){let t=Dt({id:a?.id??"zylem",debug:!!a?.debug,time:a?.time??0,input:a?.input,stages:a?.stages??[],globals:a?.globals??{}}),n=a?.containerId??t.containerId,i=kt(n,a?.container??null),o=a?.mobile,s=Lt(e),r=s?o?.preset??a?.preset:a?.preset,l=at(a?.resolution,a?.preset),p=at(o?.resolution,o?.preset??a?.preset),g=(s?ot(p):void 0)??ot(l),u=s?o?.aspectRatio??a?.aspectRatio:a?.aspectRatio,d=At(u,r,t.aspectRatio,g),S=Vt(s,p,l,d),f=a?.fullscreen??t.fullscreen,G=a?.bodyBackground??t.bodyBackground,P=a?.canvas??void 0,B=Ot(a?.input??t.input,o?.controls);return new Ee(a?.id??t.id,a?.globals??t.globals,a?.stages??t.stages,!!(a?.debug??t.debug),a?.time??t.time,B,d,S,f,G,i,n,P)}function ot(a){if(a)return a}function Vt(a,e,t,n){if(a)return e===xe?void 0:e??zt(n);if(t!==xe)return t}function Ot(a,e){if(!e)return a;let n=Ue("p1",{enabled:"auto",...e===!0?{}:e});return L(n,a??{})}function Ht(a){return{...a}}var te=class{id;container;canvas;bodyBackground;fullscreen;aspectRatio;ratioDelegate=null;overlayContainer=null;constructor(e){this.id=e.id,this.container=this.ensureContainer(e.containerId??e.id,e.container),this.canvas=e.canvas??document.createElement("canvas"),this.bodyBackground=e.bodyBackground,this.fullscreen=!!e.fullscreen,this.aspectRatio=(typeof e.aspectRatio=="number",e.aspectRatio)}applyBodyBackground(){this.bodyBackground&&(document.body.style.background=this.bodyBackground)}mountCanvas(){this.mountChildren(this.canvas)}mountRenderer(e,t){this.mountChildren(e),this.canvas=e,this.attachAspectRatio(t)}getOverlayContainer(){return this.ensureOverlayContainer()}centerIfFullscreen(){if(!this.fullscreen)return;let e=this.container.style;e.display="flex",e.alignItems="center",e.justifyContent="center",e.position="relative",e.inset="0"}attachAspectRatio(e){this.ratioDelegate?(this.ratioDelegate.canvas=this.canvas,this.ratioDelegate.onResize=e,this.ratioDelegate.aspectRatio=this.aspectRatio,this.ratioDelegate.apply()):(this.ratioDelegate=new ee({container:this.container,canvas:this.canvas,aspectRatio:this.aspectRatio,onResize:e}),this.ratioDelegate.attach())}setAspectRatio(e){this.aspectRatio=e,this.ratioDelegate&&(this.ratioDelegate.aspectRatio=e,this.ratioDelegate.apply())}reapplyLayout(){this.ratioDelegate?.apply()}destroy(){this.ratioDelegate?.detach(),this.ratioDelegate=null}mountChildren(e){for(;this.container.firstChild;)this.container.removeChild(this.container.firstChild);this.container.appendChild(e),this.container.appendChild(this.ensureOverlayContainer())}ensureOverlayContainer(){if(this.overlayContainer)return this.overlayContainer;let e=document.createElement("div");return e.dataset.zylemOverlayRoot="true",e.style.position="absolute",e.style.inset="0",e.style.pointerEvents="none",e.style.touchAction="none",e.style.zIndex="10",this.overlayContainer=e,e}ensureContainer(e,t){if(t)return t;if(e){let o=document.getElementById(e);if(o)return o}let n=e||this.id||"zylem-root",i=document.createElement("main");return i.setAttribute("id",n),i.style.position="relative",i.style.width="100%",i.style.height="100%",document.body.appendChild(i),i}};import Ft from"stats.js";import{subscribe as Ut}from"valtio/vanilla";var rt="zylem-fps-host",ne=class{statsRef=null;unsubscribe=null;host=null;onFpsHost=e=>{let t=e.detail;this.host=t?.element??null,this.attachStats()};constructor(){typeof window<"u"&&window.addEventListener(rt,this.onFpsHost),this.updateDebugUI(),this.unsubscribe=Ut(v,()=>{this.updateDebugUI()})}begin(){this.statsRef?.begin()}end(){this.statsRef?.end()}styleForPanel(e){e.style.position="relative",e.style.top="auto",e.style.right="auto",e.style.bottom="auto",e.style.left="auto",e.style.zIndex="auto"}detachStats(){let e=this.statsRef?.dom;e?.parentNode&&e.parentNode.removeChild(e)}attachStats(){if(this.statsRef){if(!this.host){this.detachStats();return}this.styleForPanel(this.statsRef.dom),this.statsRef.dom.parentNode!==this.host&&this.host.appendChild(this.statsRef.dom)}}updateDebugUI(){v.enabled&&!this.statsRef?(this.statsRef=new Ft,this.statsRef.showPanel(0),this.attachStats()):!v.enabled&&this.statsRef&&(this.detachStats(),this.statsRef=null)}dispose(){typeof window<"u"&&window.removeEventListener(rt,this.onFpsHost),this.unsubscribe&&(this.unsubscribe(),this.unsubscribe=null),this.detachStats(),this.statsRef=null,this.host=null}};var ie=class{loadingHandlers=[];stageLoadingUnsubscribes=[];onLoading(e){return this.loadingHandlers.push(e),()=>{this.loadingHandlers=this.loadingHandlers.filter(t=>t!==e)}}emit(e){for(let n of this.loadingHandlers)try{n(e)}catch(i){console.error("Game loading handler failed",i)}let t=`loading:${e.type}`;E.emit(t,e)}wireStageLoading(e,t){let n=e.onLoading(i=>{this.emit({type:i.type,message:i.message??"",progress:i.progress??0,current:i.current,total:i.total,stageName:e.uuid??`Stage ${t}`,stageIndex:t})});typeof n=="function"&&this.stageLoadingUnsubscribes.push(n)}unwireAllStages(){for(let e of this.stageLoadingUnsubscribes)try{e()}catch{}this.stageLoadingUnsubscribes=[]}dispose(){this.unwireAllStages(),this.loadingHandlers=[]}};import{getZylemBridge as _t}from"@zylem/bridge";var ae=class{container=null;camera=null;rendererManager=null;gameCanvas=null;config=null;stage=null;mounted=!1;setGameCanvas(e){this.gameCanvas=e,this.tryMount()}setConfig(e){this.config=e,this.tryMount()}setContainer(e){this.container=e,this.tryMount()}setStage(e){this.stage=e,this.mounted&&this.gameCanvas?.reapplyLayout()}setCamera(e){this.camera=e,this.tryMount()}setRendererManager(e){this.rendererManager=e,this.tryMount()}tryMount(){this.mounted||!this.container||!this.gameCanvas||(this.rendererManager?this.mountWithRendererManager():this.camera&&this.mountWithCamera())}mountWithRendererManager(){if(!this.rendererManager||!this.gameCanvas)return;let e=this.rendererManager.getDomElement();this.gameCanvas.mountRenderer(e,(t,n)=>{if(!this.rendererManager)return;let i=this.config?.internalResolution;if(i)this.rendererManager.setPixelRatio(1),this.rendererManager.resize(i.width,i.height),this.stage?.resize(i.width,i.height);else{let o=window.devicePixelRatio||1;this.rendererManager.setPixelRatio(o),this.rendererManager.resize(t,n),this.stage?.resize(t,n)}}),this.mounted=!0}mountWithCamera(){if(!this.camera||!this.gameCanvas)return;let e=this.camera.getDomElement();this.gameCanvas.mountRenderer(e,(t,n)=>{if(!this.camera)return;let i=this.config?.internalResolution;if(i)this.camera.setPixelRatio(1),this.camera.resize(i.width,i.height);else{let o=window.devicePixelRatio||1;this.camera.setPixelRatio(o),this.camera.resize(t,n)}}),this.mounted=!0}reset(){this.camera=null,this.stage=null,this.mounted=!1}dispose(){this.container=null,this.camera=null,this.rendererManager=null,this.gameCanvas=null,this.config=null,this.stage=null,this.mounted=!1}};var oe=class a{id;initialGlobals={};customSetup=null;customUpdate=null;customDestroy=null;stages=[];stageMap=new Map;currentStageId="";previousTimeStamp=0;totalTime=0;timer;inputManager;wrapperRef;globalInputConfig;defaultCamera=null;rendererManager=null;container=null;canvas=null;aspectRatioDelegate=null;resolvedConfig=null;gameCanvas=null;animationFrameId=null;isDisposed=!1;loadInFlight=!1;hasStarted=!1;debugDelegate=null;loadingDelegate=new ie;rendererObserver=new ae;eventBusUnsubscribes=[];thumbnailUnsubscribes=[];lastPublishedGameConfig=null;gameBridge=new Ze;cutscenePreview=new Qe(()=>this.currentStage()?.wrappedStage??null,e=>this.gameBridge.publishCutsceneStatus(e),{},e=>this.gameBridge.publishCutsceneView(e));catalogUnsubscribe=null;gameUpdateParams={};stageSetupParams={};stageUpdateParams={};frameCallback=e=>this.loop(e);sourceOptions;displayRuntime;static FRAME_LIMIT=120;static FRAME_DURATION=1e3/a.FRAME_LIMIT;static MAX_DELTA_SECONDS=1/30;constructor(e,t,n={}){this.wrapperRef=t,this.timer=new Q,this.timer.connect(document),this.sourceOptions={...e},this.displayRuntime={...n};let i=Z(e,this.displayRuntime);this.globalInputConfig=i.input,this.id=i.id,this.stages=i.stages||[],this.container=i.container,this.canvas=i.canvas??null,this.resolvedConfig=i,this.loadGameCanvas(i),this.container=this.gameCanvas?.container??this.container,this.inputManager=new q(i.input,{targetElement:this.gameCanvas?.getOverlayContainer(),mouseTargetElement:this.gameCanvas?.container}),this.loadDebugOptions(e),this.setGlobals(e),We(),je(),this.gameBridge.connect({resolveEntity:o=>this.currentStage()?.wrappedStage?.entityDelegate.childrenMap.get(o)??null,setStageVariable:(o,s)=>{let r=this.currentStage()?.wrappedStage?.state;r&&(r.variables[o]=s)},createEntity:(o,s,r)=>{this.createCatalogEntity(o,s,r)},applySceneOperation:(o,s)=>{this.currentStage()?.wrappedStage?.debugDelegate?.applySceneOperation(o,s)},pickEntity:o=>this.pickEntityAtNdc(o),cutscene:this.cutscenePreview,cameraPose:()=>this.cutscenePreview.cameraPose(),levelSync:o=>{this.currentStage()?.wrappedStage?.debugDelegate?.syncLevel(o)},levelPlay:o=>{this.currentStage()?.wrappedStage?.debugDelegate?.playLevel(o)},levelClose:()=>{this.currentStage()?.wrappedStage?.debugDelegate?.closeLevel()},applySwatches:o=>{let s=this.currentStage()?.wrappedStage?.debugDelegate;return s?s.applySwatches(o):{results:o.uuids.flatMap(r=>o.swatches.map(l=>({uuid:r,kind:l.kind,source:l.source,ok:!1,reason:"entity-not-found"}))),entries:[]}}}),this.publishEntityCatalog(),this.catalogUnsubscribe=Je(()=>this.publishEntityCatalog())}pickEntityAtNdc(e){let t=this.currentStage()?.wrappedStage,n=t?.debugDelegate?.pickAtNdc(e.x,e.y);if(!t||!n)return null;let i=t.entityDelegate.childrenMap.get(n.uuid);return i?this.buildEntitySummary(i)??{uuid:n.uuid,name:n.name||"Unnamed",type:ge(i),position:he(i).position,rotation:he(i).rotation,scale:me(i)}:null}publishEntityCatalog(){this.gameBridge.publishCatalog(Ke())}createCatalogEntity(e,t,n){let i=this.currentStage()?.wrappedStage,o=K(e);if(!i||!o)return;let s=n?.position??{x:0,y:0,z:0},r=o.create({position:s,props:{...o.defaultProps??{},...t??{}}});r&&Promise.resolve(r).then(l=>l&&i.entityDelegate.spawnEntity(l)).catch(l=>{console.error("entity:create failed",l)})}setDisplayRuntime(e){this.displayRuntime={...e};let t=Z(this.sourceOptions,this.displayRuntime);this.resolvedConfig=t,this.rendererObserver.setConfig(t),this.gameCanvas?.setAspectRatio(t.aspectRatio),this.publishGameConfig()}loadGameCanvas(e){this.gameCanvas=new te({id:e.id,container:e.container,containerId:e.containerId,canvas:this.canvas??void 0,bodyBackground:e.bodyBackground,fullscreen:e.fullscreen,aspectRatio:e.aspectRatio}),this.gameCanvas.applyBodyBackground(),this.gameCanvas.mountCanvas(),this.gameCanvas.centerIfFullscreen(),this.rendererObserver.setGameCanvas(this.gameCanvas),this.resolvedConfig&&this.rendererObserver.setConfig(this.resolvedConfig),this.container&&this.rendererObserver.setContainer(this.container),this.subscribeToEventBus()}loadDebugOptions(e){e.debug!==void 0&&(v.enabled=!!e.debug),this.debugDelegate=new ne}isLoading(){return this.loadInFlight}async loadStage(e,t=0,n){if(this.loadInFlight){console.warn("loadStage ignored: a stage load is already in progress");return}this.loadInFlight=!0;try{await this.performLoadStage(e,t,n)}finally{this.loadInFlight=!1}}async performLoadStage(e,t=0,n){let i=n?qe(n):null;this.cutscenePreview.releaseStage();let o=this.currentStage()??null,s=o?.wrappedStage??null,r=s?.scene?.scene??null,l=s?.cameraManagerRef?.primaryCamera?.camera??s?.cameraRef?.camera??null;i&&this.rendererManager?.initialized&&o&&r&&l&&this.rendererManager.beginSnapshotTransition(i,r,l),this.unloadCurrentStage();let g=e.options[0];if(this.loadingDelegate.wireStageLoading(e,t),this.rendererManager||(this.rendererManager=new Fe,await this.rendererManager.initRenderer()),x.setRenderer(this.rendererManager.renderer),await e.load(this.id,g?.camera,this.rendererManager),this.stageMap.set(e.wrappedStage.uuid,e),this.currentStageId=e.wrappedStage.uuid,this.defaultCamera=e.wrappedStage.cameraRef,this.wireEntityThumbnails(e),this.rendererObserver.setStage(e.wrappedStage??null),this.rendererManager&&this.rendererObserver.setRendererManager(this.rendererManager),this.applyInputConfig(e),e.onInputConfigChanged=()=>this.applyInputConfig(e),this.hasStarted&&e.wrappedStage&&!e.wrappedStage.hasSetup){let u=this.params(),d={...this.stageSetupParams};d.inputs=u.inputs,d.globals=u.globals,d.camera=u.camera,d.stage=u.stage,d.game=u.game,d.me=e.wrappedStage,e.start(d)}this.publishGameConfig(),this.publishStageSnapshot(),this.cutscenePreview.stageReady()}applyInputConfig(e){let t=L(this.globalInputConfig??{},e.inputConfig??{});this.inputManager.configure(t)}setGlobalInputConfig(e){this.globalInputConfig=e;let t=this.currentStage();t&&this.applyInputConfig(t)}unloadCurrentStage(){if(!this.currentStageId)return;let e=this.getStage(this.currentStageId);if(e){if(this.clearEntityThumbnailWiring(),x.clear(),e.onInputConfigChanged=null,e?.wrappedStage){try{e.wrappedStage.nodeDestroy({me:e.wrappedStage,globals:V.globals})}catch(t){console.error("Failed to destroy previous stage",t)}e.wrappedStage=null}e.dispose(),this.stageMap.delete(this.currentStageId),this.currentStageId="",this.defaultCamera=null,this.rendererObserver.reset()}}setGlobals(e){this.initialGlobals={...e.globals};for(let t in this.initialGlobals){let n=this.initialGlobals[t];n===void 0&&console.error(`global ${t} is undefined`),De(t,n)}}params(){let e=this.currentStage(),t=this.timer.getDelta(),n=this.inputManager.getInputs(t),i=e?.wrappedStage?.cameraRef||this.defaultCamera,o=this.gameUpdateParams;return o.delta=t,o.inputs=n,o.globals=Ve(),o.me=this,o.camera=i,o.stage=e,o.game=this.wrapperRef,o}start(){let e=this.currentStage(),t=this.params(),n=this.stageSetupParams;n.inputs=t.inputs,n.globals=t.globals,n.camera=t.camera,n.stage=t.stage,n.game=t.game,n.me=e.wrappedStage,e.start(n),this.customSetup&&this.customSetup(t),this.hasStarted=!0,this.loop(0)}step(e){let t=this.currentStage();if(!t||!t.wrappedStage)return;let n=this.params(),i=e!==void 0?e:n.delta,o=Math.min(Math.max(i,0),a.MAX_DELTA_SECONDS);n.delta=o,this.customUpdate&&this.customUpdate(n);let s=this.currentStage();if(s!==t||!s?.wrappedStage){this.totalTime+=o,V.time=this.totalTime;return}let r=this.stageUpdateParams;r.delta=n.delta,r.inputs=n.inputs,r.globals=n.globals,r.camera=n.camera,r.stage=n.stage,r.game=n.game,r.me=t.wrappedStage,t.wrappedStage?.nodeUpdate(r),this.totalTime+=o,V.time=this.totalTime}loop(e){this.debugDelegate?.begin(),He()||(this.timer.update(e),this.step(),this.previousTimeStamp=e),this.debugDelegate?.end(),this.outOfLoop(),this.cutscenePreview.frame(),this.isDisposed||(this.animationFrameId=requestAnimationFrame(this.frameCallback))}dispose(){this.isDisposed=!0,this.cutscenePreview.unload(),this.catalogUnsubscribe?.(),this.catalogUnsubscribe=null,this.gameBridge.disconnect(),this.animationFrameId!==null&&(cancelAnimationFrame(this.animationFrameId),this.animationFrameId=null),this.unloadCurrentStage(),this.debugDelegate&&(this.debugDelegate.dispose(),this.debugDelegate=null),this.eventBusUnsubscribes.forEach(e=>e()),this.eventBusUnsubscribes=[],this.rendererObserver.dispose(),this.inputManager.dispose(),this.rendererManager&&(x.setRenderer(null),this.rendererManager.dispose(),this.rendererManager=null),x.clear(),_t().channel.reset(),this.timer.dispose(),this.customDestroy&&this.customDestroy({me:this,globals:V.globals}),O()}outOfLoop(){let e=this.currentStage();e&&e.wrappedStage.outOfLoop()}getStage(e){return this.stageMap.get(e)}currentStage(){return this.getStage(this.currentStageId)}onLoading(e){return this.loadingDelegate.onLoading(e)}buildStageConfigPayload(){let e=this.currentStage();if(!e?.wrappedStage)return null;let t=e.wrappedStage.state,n=t.backgroundColor,i=typeof n=="string"?n:`#${n.getHexString()}`;return{id:e.wrappedStage.uuid,backgroundColor:i,backgroundImage:t.backgroundImage,gravity:{x:t.gravity.x,y:t.gravity.y,z:t.gravity.z},inputs:t.inputs,variables:t.variables}}buildEntitySummary(e){if(e.options?.editorOwned||H(e.options))return null;let t=e.position??{x:0,y:0,z:0},n=e.rotation??{x:0,y:0,z:0},i=me(e),o=Ne(e),s=x.get(e.uuid);return{uuid:e.uuid,name:e.name||"Unnamed",type:ge(e),position:{x:t.x??0,y:t.y??0,z:t.z??0},rotation:{x:n.x??0,y:n.y??0,z:n.z??0},scale:i,quaternion:o,thumbnail:s?.dataUrl??null,bounds:s?.bounds}}buildEntitiesPayload(){let e=this.currentStage();if(!e?.wrappedStage)return[];let t=[];return e.wrappedStage.entityDelegate.childrenMap.forEach(n=>{let i=this.buildEntitySummary(n);i&&t.push(i)}),t}wireEntityThumbnails(e){if(this.clearEntityThumbnailWiring(),!e.wrappedStage)return;let t=s=>{if(s.options?.editorOwned||!this.gameBridge.wantsThumbnails()||H(s.options))return;let r=s.group??s.mesh??null;r&&x.ensure(s.uuid,r).then(l=>{l&&!this.isDisposed&&this.gameBridge.queueThumbnails([{uuid:s.uuid,url:l.dataUrl,bounds:l.bounds}])})},n=e.wrappedStage.onEntityAdded(s=>{if(this.gameBridge.wantsEntityUpdates()){let r=this.buildEntitySummary(s);r&&this.gameBridge.queueEntityUpsert([r])}t(s)},{replayExisting:!0});this.thumbnailUnsubscribes.push(n);let i=s=>{if(!s.success)return;let r=e.wrappedStage?.entityDelegate.childrenMap.get(s.entityId);r&&(x.invalidate(s.entityId),t(r))};E.on("entity:model:loaded",i),this.thumbnailUnsubscribes.push(()=>{E.off("entity:model:loaded",i)});let o=s=>{x.invalidate(s.entityId),this.gameBridge.wantsEntityUpdates()&&this.gameBridge.queueEntityRemoved([s.entityId])};E.on("entity:destroyed",o),this.thumbnailUnsubscribes.push(()=>{E.off("entity:destroyed",o)}),this.wireEditorBackfill(e)}wireEditorBackfill(e){let t=this.gameBridge.onEditorAttached(()=>{if(!(this.isDisposed||this.currentStage()!==e)){this.lastPublishedGameConfig=null,this.publishGameConfig(),this.publishStageSnapshot();for(let n of e.wrappedStage?.entityDelegate.childrenMap.values()??[]){let i=n;if(i.options?.editorOwned||H(i.options))continue;let o=i.group??i.mesh??null;o&&x.ensure(i.uuid,o).then(s=>{s&&!this.isDisposed&&this.gameBridge.queueThumbnails([{uuid:i.uuid,url:s.dataUrl,bounds:s.bounds}])})}}});this.thumbnailUnsubscribes.push(t)}clearEntityThumbnailWiring(){this.thumbnailUnsubscribes.forEach(e=>{try{e()}catch{}}),this.thumbnailUnsubscribes=[]}buildGameConfigPayload(){return this.resolvedConfig?{id:this.resolvedConfig.id,aspectRatio:this.resolvedConfig.aspectRatio,fullscreen:this.resolvedConfig.fullscreen,bodyBackground:this.resolvedConfig.bodyBackground,internalResolution:this.resolvedConfig.internalResolution,debug:this.resolvedConfig.debug}:null}publishGameConfig(){let e=this.buildGameConfigPayload();if(!e)return;let t=JSON.stringify(e);t!==this.lastPublishedGameConfig&&(this.lastPublishedGameConfig=t,this.gameBridge.publishConfig(e))}publishStageSnapshot(){this.gameBridge.publishStageSnapshot({stage:this.buildStageConfigPayload(),entities:this.buildEntitiesPayload()})}subscribeToEventBus(){this.eventBusUnsubscribes.push(ke.on("game:state:updated",e=>{this.gameBridge.publishVariable({path:e.path,value:e.value,previousValue:e.previousValue})}))}};async function st(a){let{getGameDefaultConfig:e}=await import("./game-default-VUMUMTXA.js"),t={...e()},n=[],i=[],o=[];Object.values(a).forEach(r=>{if(r instanceof J)i.push(r);else if(r instanceof be)o.push(r);else if(r instanceof ye)o.push(r);else if(r?.constructor?.name==="Object"&&typeof r=="object"){let l=Object.assign({...e()},{...r});n.push(l)}}),n.forEach(r=>{t=Object.assign(t,{...r})});let s=t;return s.input=n[0].input,i.forEach(r=>{r.addEntities(o)}),i.length?s.stages=i:s.stages[0].addEntities(o),s}function lt(a){return!!a.find(t=>t instanceof J)}function Ge(a){for(let e of a)if(e&&typeof e=="object"&&!(e instanceof J)&&!(e instanceof ye)&&!(e instanceof be)){let t=e;if(t.globals)return t.globals}}import{proxy as Nt}from"valtio/vanilla";import{get as Xt,set as Yt}from"idb-keyval";import{pack as Zt,unpack as Kt}from"msgpackr";var h=Nt({previous:null,current:null,next:null,isLoading:!1}),re={staticRegistry:new Map,registerStaticStage(a,e){this.staticRegistry.set(a,e)},async loadStageData(a){try{let e=await Xt(a);if(e)return Kt(e)}catch(e){console.warn(`Failed to load stage ${a} from storage`,e)}if(this.staticRegistry.has(a))return this.staticRegistry.get(a);throw new Error(`Stage ${a} not found in storage and static loading not fully implemented.`)},async transitionForward(a,e){if(!h.isLoading){h.isLoading=!0;try{h.current&&await Yt(h.current.id,Zt(h.current)),h.previous=h.current,h.current=h.next,h.current?.id!==a&&(e?h.current=await e(a):h.current=await this.loadStageData(a)),h.next=null}catch(t){console.error("Failed to transition stage:",t)}finally{h.isLoading=!1}}},async preloadNext(a,e){e?h.next=await e(a):h.next=await this.loadStageData(a)}};var Te={async createFromBlueprint(a){let e=F({});if(a.entities)for(let t of a.entities)try{let n=await et.createFromBlueprint(t);e.add(n)}catch(n){console.error(`Failed to create entity ${t.id} for stage ${a.id}`,n)}return e}};var se=class{wrappedGame=null;options;setupCallbacks=[];updateCallbacks=[];destroyCallbacks=[];pendingLoadingCallbacks=[];globalChangeCallbacks=[];globalChangesCallbacks=[];activeGlobalSubscriptions=[];eventDelegate=new _e;pendingInputConfig=null;displayRuntime={};refErrorMessage="lost reference to game";constructor(e){this.options=e,lt(e)||this.options.push(F());let t=Ge(e);t&&pe(t)}onSetup(...e){return this.setupCallbacks.push(...e),this}onUpdate(...e){return this.updateCallbacks.push(...e),this}onDestroy(...e){return this.destroyCallbacks.push(...e),this}setInputConfiguration(...e){let t=L(...e);return this.pendingInputConfig=t,this.wrappedGame&&this.wrappedGame.setGlobalInputConfig(t),this}async start(){O();let e=Ge(this.options);e&&pe(e);let t=await this.load();return this.wrappedGame=t,this.setOverrides(),this.registerGlobalSubscriptions(),t.start(),this}setDisplayRuntime(e){return this.displayRuntime={...this.displayRuntime,...e},this.wrappedGame&&this.wrappedGame.setDisplayRuntime(this.displayRuntime),this}setDeviceProfile(e){return this.setDisplayRuntime({deviceProfile:e})}setViewportSize(e,t){return this.setDisplayRuntime({viewportSize:{width:e,height:t}})}async load(){let e=await st(this.options),t=Z(e,this.displayRuntime);this.pendingInputConfig&&(t.input=L(t.input??{},this.pendingInputConfig));let n=new oe({...e,...t},this,this.displayRuntime);for(let i of this.pendingLoadingCallbacks)n.onLoading(i);return await n.loadStage(e.stages[0]),n}setOverrides(){if(!this.wrappedGame){console.error(this.refErrorMessage);return}this.wrappedGame.customSetup=e=>{this.setupCallbacks.forEach(t=>t(e))},this.wrappedGame.customUpdate=e=>{this.updateCallbacks.forEach(t=>t(e))},this.wrappedGame.customDestroy=e=>{this.destroyCallbacks.forEach(t=>t(e))}}onGlobalChange(e,t){return this.globalChangeCallbacks.push({path:e,callback:t}),this}onGlobalChanges(e,t){return this.globalChangesCallbacks.push({paths:e,callback:t}),this}registerGlobalSubscriptions(){for(let{path:e,callback:t}of this.globalChangeCallbacks){let n=Ae(e,i=>{t(i,this.getCurrentStage())});this.activeGlobalSubscriptions.push(n)}for(let{paths:e,callback:t}of this.globalChangesCallbacks){let n=ze(e,i=>{t(i,this.getCurrentStage())});this.activeGlobalSubscriptions.push(n)}}getCurrentStage(){return this.wrappedGame?.currentStage()??null}experimental={getRuntime:()=>this.getCurrentStage()?.wrappedStage?.world?.simulation??null};async pause(){de(!0)}async resume(){de(!1),this.wrappedGame&&(this.wrappedGame.previousTimeStamp=0,this.wrappedGame.timer.reset())}step(e=1/60){if(!this.wrappedGame){console.error(this.refErrorMessage);return}this.wrappedGame.step(e)}async reset(e){if(!this.wrappedGame){console.error(this.refErrorMessage);return}this.wrappedGame.isLoading()||await this.wrappedGame.loadStage(this.wrappedGame.stages[0],0,e?.transition)}previousStage(e){if(!this.wrappedGame){console.error(this.refErrorMessage);return}if(this.wrappedGame.isLoading())return;let t=this.wrappedGame.currentStageId,n=this.wrappedGame.stages.findIndex(o=>o.wrappedStage?.uuid===t),i=this.wrappedGame.stages[n-1];if(!i){console.error("previous stage called on first stage");return}this.wrappedGame.loadStage(i,n-1,e?.transition)}async loadStageFromId(e){if(!this.wrappedGame){console.error(this.refErrorMessage);return}try{let t=await re.loadStageData(e),n=await Te.createFromBlueprint(t);await this.wrappedGame.loadStage(n),h.current=t}catch(t){console.error(`Failed to load stage ${e}`,t)}}nextStage(e){if(!this.wrappedGame){console.error(this.refErrorMessage);return}if(this.wrappedGame.isLoading())return;if(h.next){console.log("next stage called");let o=h.next.id;if(re.transitionForward(o),h.current){Te.createFromBlueprint(h.current).then(s=>{this.wrappedGame?.loadStage(s,0,e?.transition)});return}}let t=this.wrappedGame.currentStageId,n=this.wrappedGame.stages.findIndex(o=>o.wrappedStage?.uuid===t),i=this.wrappedGame.stages[n+1];if(!i){console.error("next stage called on last stage");return}this.wrappedGame.loadStage(i,n+1,e?.transition)}async goToStage(){}async end(){}dispose(){this.eventDelegate.dispose();for(let e of this.activeGlobalSubscriptions)e();this.activeGlobalSubscriptions=[],this.wrappedGame&&(this.wrappedGame.dispose(),this.wrappedGame=null),Oe(),O(),$e.clearSharedMaterialCache()}dispatch(e,t){this.eventDelegate.dispatch(e,t),E.emit(e,t)}listen(e,t){return this.eventDelegate.listen(e,t)}onLoading(e){return this.wrappedGame?this.wrappedGame.onLoading(e):(this.pendingLoadingCallbacks.push(e),()=>{this.pendingLoadingCallbacks=this.pendingLoadingCallbacks.filter(t=>t!==e),this.wrappedGame})}};function Jt(...a){return new se(a)}function $t(a,e,t){return ce(e,n=>Wt(a,n),t)}async function Wt(a,e){let t=K(e.typeId);if(!t)return;let n=e.pose.position??{x:0,y:0,z:0},i=await t.create({position:n,props:{...t.defaultProps??{}}});i&&(await a.spawnEntity(i),Ye(i,e.pose),e.pose.scale&&Xe(i))}import{Euler as jt,Quaternion as qt,Vector2 as Qt}from"three";function en(a){return{spawn:async(e,t,n)=>{let i=await Promise.resolve(a(t,n));return e.add(i),i},spawnRelative:async(e,t,n=new Qt(0,1))=>{if(!e.body){console.warn("body missing for entity during spawnRelative");return}let{x:i,y:o,z:s}=e.body.translation(),r=e._rotation2DAngle??0;try{let u=e.body.rotation(),d=new qt(u.x,u.y,u.z,u.w);r=new jt().setFromQuaternion(d,"XYZ").z}catch{}let l=Math.sin(-r)*(n.x??0),p=Math.cos(-r)*(n.y??0),g=await Promise.resolve(a(i+l,o+p));return t.add(g),g}}}import{subscribe as tn}from"valtio/vanilla";var Re="STAGE_STATE_CHANGE";function nn(){return tn(k,()=>{let a={entities:k.entities,variables:k.variables};window.dispatchEvent(new CustomEvent(Re,{detail:a}))})}function an(){let a={entities:k.entities,variables:k.variables};window.dispatchEvent(new CustomEvent(Re,{detail:a}))}import{MathUtils as on,Vector3 as rn}from"three";var ut={targetKey:"primary",offset:new rn(0,0,0),lerpFactor:.1};function sn(a){let e={...ut,...a,offset:fe(a?.offset,ut.offset)},t=null;return{priority:0,enabled:!0,onAttach(){t=null},update(n,i){let o=n.targets[e.targetKey];if(!o)return i;let s=o.position.clone().add(e.offset),r=D(i);if(!t)t=s.clone();else{let l=on.clamp(e.lerpFactor,0,1),p=1-Math.pow(1-l,n.dt*60);t.lerp(s,p)}return r.position.copy(t),r.lookAt=o.position.clone(),r},onDetach(){t=null}}}import{MathUtils as Pe,Vector3 as pt}from"three";var ln={x:"delay",y:"settle",z:"delay"},dt=["x","y","z"];function un(a){let e={...ln,...a?.axes},t=a?.targetKey??"primary",n=a?.lerpFactor??.1,i=a?.window??0,o=a?.settleSpeed??.75,s=a?.settleTime??.15,r=a?.settleLerp??.08,l=a?.lookahead??0,p=null,g=null,u=null,d={x:0,y:0,z:0},S=new pt,f=new pt,G=()=>{p=null,g=null,u=null,d.x=d.y=d.z=0,S.set(0,0,0)};return{priority:0,enabled:!0,onAttach:G,onDetach:G,update(P,B){let M=P.targets[t];if(!M)return B;let b=M.position,y=p??b.clone(),C=g??b.clone(),I=u??b.clone();p=y,g=C,u=I;let T=P.dt,z=T>1e-8?1/T:0,ht=ct(n,T),gt=ct(r,T);if(l>0){f.set(0,0,0);for(let c of dt)e[c]==="delay"&&(f[c]=(b[c]-I[c])*z);f.lengthSq()>1e-8&&S.copy(f).normalize()}for(let c of dt){let Le=e[c];if(Le==="off"){y[c]=b[c];continue}let ft=Math.abs((b[c]-I[c])*z);if(Le==="settle"){ft<=o?(d[c]+=T,d[c]>=s&&(C[c]=b[c])):d[c]=0,y[c]=Pe.lerp(y[c],C[c],gt);continue}let ue=b[c];l>0&&(ue+=S[c]*l),!(Math.abs(ue-y[c])<=i)&&(y[c]=Pe.lerp(y[c],ue,ht))}I.copy(b);let R=D(B),Be=y.x-b.x,Me=y.y-b.y,Ie=y.z-b.z;return R.position.x+=Be,R.position.y+=Me,R.position.z+=Ie,R.lookAt&&(R.lookAt.x+=Be,R.lookAt.y+=Me,R.lookAt.z+=Ie),R}}}function ct(a,e){let t=Pe.clamp(a,0,1);return 1-Math.pow(1-t,e*60)}import{MathUtils as le}from"three";function pn(a){let e=a?.sampleInput??(()=>({})),t=le.clamp(a?.edgeMargin??.08,0,.5),n=a?.edgeSpeed??12,i=a?.panSpeed??16,o=a?.followLerp??.12,s=a?.breakFollowOnPan??!0,r=a?.followKey??null,l=!1,p=null,g=()=>{p=null,l=!1};return{priority:0,enabled:!0,onAttach:g,onDetach:g,setFollowKey(u){r=u,l=!1},update(u,d){let S=d.lookAt??d.position,f=p??S.clone();p=f;let G=e()??{},P=G.pan?.x??0,B=G.pan?.y??0,M=dn(G.pointer,t);(Math.abs(P)>.01||Math.abs(B)>.01||M.x!==0||M.y!==0)&&s&&(l=!0);let y=!l&&r?u.targets[r]:void 0;if(y){let z=cn(o,u.dt);f.x=le.lerp(f.x,y.position.x,z),f.z=le.lerp(f.z,y.position.z,z)}else f.x+=(P*i+M.x*n)*u.dt,f.z+=(-B*i+M.y*n)*u.dt;let C=D(d),I=f.x-S.x,T=f.z-S.z;return C.position.x+=I,C.position.z+=T,C.lookAt&&(C.lookAt.x+=I,C.lookAt.z+=T),C}}}function dn(a,e){if(!a||e<=0)return{x:0,y:0};let t=a.centered?(a.x+1)/2:a.x,n=a.centered?(a.y+1)/2:a.y;return{x:mt(t,e),y:mt(n,e)}}function mt(a,e){return a<e?-((e-a)/e):a>1-e?(a-(1-e))/e:0}function cn(a,e){let t=le.clamp(a,0,1);return 1-Math.pow(1-t,e*60)}import{MeshBasicMaterial as mn}from"three";function hn(a,e,t){let n=e.cameraRef;if(!n.renderTarget){let s=t?.width??512,r=t?.height??512;n.createRenderTarget(s,r)}let i=n.getRenderTexture();if(!i){console.warn("setCameraFeed: Failed to obtain render texture from camera.");return}if(!a.mesh){console.warn("setCameraFeed: Entity has no mesh to apply the camera feed to.");return}let o=new mn({map:i});a.mesh.material=o}export{Y as a,Se as b,we as c,Ce as d,Ht as e,h as f,re as g,se as h,Jt as i,$t as j,en as k,Re as l,nn as m,an as n,sn as o,un as p,pn as q,hn as r};
|
package/dist/chunk-VKWJHFUR.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{b as k,c as B,d as I}from"./chunk-273CUPEO.js";import{d as s,h as v,j as g,l as S,o as E,q as p,r as C,s as w,t as P,v as x,w as D,x as A}from"./chunk-UM5VNQPY.js";function L(){return new Promise(t=>{let e=new MessageChannel;e.port1.onmessage=()=>t(),e.port2.postMessage(void 0)})}async function O(t,e,i={}){let n=Math.max(1,i.batchSize??5),o=0;for(let a of t.entries)await e(a),o+=1,o%n===0&&await L();return o%n!==0&&await L(),{spawned:o}}import{subscribe as H}from"valtio/vanilla";import{announceBridgeReady as M,getZylemBridge as h}from"@zylem/bridge";var te="game",ne={side:"editor:side",top:"editor:top",isometric:"editor:isometric",free:"editor:free"},d=!1,c=new Set;function ie(){return d}function oe(t){return c.add(t),d&&t.ensureEditorCameras(),()=>{c.delete(t)}}function u(t){if(!t&&!d)return Promise.resolve();if(d=t,!t){for(let e of c)e.destroyEditorCameras();return Promise.resolve()}return Promise.all([...c].map(e=>e.ensureEditorCameras())).then(()=>{})}function z(t){let e=!1;for(let i of c)i.activateCameraById(t)&&(e=!0);return e}function y(t,e){return[t[0]*e.x,t[1]*e.y,t[2]*e.z]}function V(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?y(t.offset,e):t.offset,o;switch(i.type){case"box":o={type:"box",halfExtents:y(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:V(i.vertices,e)};break;case"trimesh":o={type:"trimesh",vertices:V(i.vertices,e),indices:i.indices};break;case"heightfield":o={...i,scale:y(i.scale,e)};break;default:o=i;break}return{...t,shape:o,offset:n}}function F(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 T(t){if(!t.colliderScaleDirty)return!1;t.colliderScaleDirty=!1;let e=F(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 a=t.getPose();return o.destroyEntity(t),a&&t.bodyDesc&&(t.bodyDesc.position=[a.position.x,a.position.y,a.position.z],t.bodyDesc.rotation=[a.rotation.x,a.rotation.y,a.rotation.z,a.rotation.w]),o.addEntity(t),!0}function R(t){return(t?.group??t?.mesh)?.scale}function N(t){let i=(typeof t?.getScale=="function"?t.getScale():void 0)??t?.scale??R(t)??{};return{x:i.x??1,y:i.y??1,z:i.z??1}}function me(t){let e=typeof t?.getPose=="function"?t.getPose():null;if(!e?.rotation)return;let{x:i,y:n,z:o,w:a}=e.rotation;return{x:i,y:n,z:o,w:a}}function f(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:I(n),quaternion:{x:n.x,y:n.y,z:n.z,w:n.w},scale:N(t)}}function $(t,e){if(typeof t?.setScale=="function"){t.setScale(e.x,e.y,e.z);return}R(t)?.set?.(e.x,e.y,e.z)}function W(t){!t||typeof t.getScale!="function"||T(t)}function _(t,e){if(!t)return!1;let i=e.quaternion??(e.rotation?B(e.rotation):void 0),n=!1;return(e.position||i)&&typeof t.setPose=="function"&&(n=t.setPose({position:e.position,rotation:i})),e.scale&&($(t,e.scale),n=!0),n}function Q(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=h().channel;if(!i.hasSubscribers("entity:upsert"))return;let n=f(t);i.queue("entity:upsert",[{uuid:e.uuid,name:e.name||"Unnamed",type:Q(t),position:n.position,rotation:n.rotation,scale:n.scale,quaternion:n.quaternion}])}function fe(t,e){h().channel.send("game:notice",{level:t,message:e})}function Z(t,e,i){let n=[...new Set(t.swatches.map(r=>r.source))],o=[...new Set(e.map(r=>r.uuid))],a=o.length===1?i(o[0])||"entity":`${o.length} entities`;return`Apply ${n.join(", ")} to ${a}`}function J(t,e){return!e||t.length!==e.length?!1:t.every((i,n)=>i===e[n])}function X(t,e){switch(e){case"add":C(t);break;case"subtract":w(t);break;case"toggle":for(let i of t)P(i);break;default:p(t);break}}function m(t,e,i){return t.on.bind(t)(e,i)}function Y(t,e){return t.on.bind(t)("camera:activate",({id:n})=>e(n))}var q=class{channel;unsubscribes=[];host=null;editorKnown={};applyingSceneOperation=!1;editorCameraFrame=0;constructor(){this.channel=h().channel}connect(e,i){this.disconnect(),this.host=e,this.unsubscribes.push(this.channel.on("debug:set",({enabled:n})=>{this.editorKnown.debug=n,s.enabled=n}),this.channel.on("tool:set",({tool:n})=>{g(n)}),this.channel.on("playback:set",({paused:n})=>{this.editorKnown.paused=n,v(n)}),this.channel.on("entity:select",({uuid:n,uuids:o,mode:a})=>{o?X(o,a??"replace"):E(n),this.editorKnown.selectedUuid=s.selectedEntityId,this.editorKnown.selectedUuids=[...s.selectedEntityIds]}),this.channel.on("entity:focus",({uuid:n})=>{k(n)}),this.channel.on("entity:transform",({uuid:n,position:o,rotation:a,quaternion:r,scale:b})=>{let l=this.host?.resolveEntity(n);if(!l)return;let U=f(l);if(_(l,{position:o,rotation:a,quaternion:r,scale:b}),b&&W(l),j(l),this.applyingSceneOperation)return;let G=f(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:U,after:G}]})}),this.channel.on("entity:create",({typeId:n,props:o,pose:a})=>{this.host?.createEntity?.(n,o,a)}),this.channel.on("level:load",({buffer:n})=>{this.loadLevel(n)}),m(this.channel,"level:sync",n=>{this.host?.levelSync?.(n)}),m(this.channel,"level:play",({document:n})=>{this.host?.levelPlay?.(n)}),m(this.channel,"level:close",()=>{this.host?.levelClose?.()}),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})=>{A(n,o??null)}),this.channel.on("snap:set",n=>{x(n)}),this.channel.on("grid:set",({visible:n})=>{D(n)}),this.channel.on("stage:variable:set",({key:n,value:o})=>{this.host?.setStageVariable?.(n,o)}),this.channel.on("pick:mode:set",({enabled:n})=>{S(n)}),this.channel.on("entity:pick",({requestId:n,ndc:o})=>{let a=this.host?.pickEntity?.(o)??null;this.channel.send("entity:pick:result",{requestId:n,hit:a})}),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})}),Y(this.channel,z),this.onEditorAttached(()=>{this.attachEditorCameras()}),this.onEditorDetached(()=>{this.detachEditorCameras()}),H(s,()=>this.publishDebugStateChanges())),this.publishDebugStateChanges(),this.editorIsAttached()&&this.attachEditorCameras(),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={},this.detachEditorCameras()}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(a=>e.swatches.map(r=>({uuid:a,kind:r.kind,source:r.source,ok:!1,reason:"entity-not-found"}))),entries:[]},o=[...new Set(n.entries.map(a=>a.uuid))];e.select&&o.length>0&&p(o),n.entries.length>0&&!this.applyingSceneOperation&&this.channel.send("scene:operation",{opId:i,kind:"swatch",label:Z(e,n.entries,a=>this.host?.resolveEntity(a)?.name),entries:n.entries}),this.channel.send("entity:swatch-applied",{opId:i,results:n.results})}publishDebugStateChanges(){let e={};s.paused!==this.editorKnown.paused&&(this.editorKnown.paused=s.paused,e.paused=s.paused),s.enabled!==this.editorKnown.debug&&(this.editorKnown.debug=s.enabled,e.debug=s.enabled),(e.paused!==void 0||e.debug!==void 0)&&this.publishStatus(e),(s.selectedEntityId!==this.editorKnown.selectedUuid||s.hoveredEntityId!==this.editorKnown.hoveredUuid||!J(s.selectedEntityIds,this.editorKnown.selectedUuids))&&(this.editorKnown.selectedUuid=s.selectedEntityId,this.editorKnown.selectedUuids=[...s.selectedEntityIds],this.editorKnown.hoveredUuid=s.hoveredEntityId,this.channel.queue("entity:selection",{selectedUuid:s.selectedEntityId,hoveredUuid:s.hoveredEntityId,selectedUuids:[...s.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()})}onEditorDetached(e){let i=this.channel;return typeof i.onSubscriberRemoved!="function"?()=>{}:i.onSubscriberRemoved(n=>{if(n!=="entity:upsert"&&n!=="entity:thumbnail")return;let o=n==="entity:upsert"?"entity:thumbnail":"entity:upsert";this.channel.subscriberCount(o)>0||e()})}editorIsAttached(){return this.channel.hasSubscribers("entity:upsert")||this.channel.hasSubscribers("entity:thumbnail")}attachEditorCameras(){u(!0),this.watchEditorDetached()}detachEditorCameras(){this.stopWatchingEditorDetached(),u(!1)}watchEditorDetached(){if(typeof this.channel.onSubscriberRemoved=="function"||this.editorCameraFrame)return;let i=()=>{if(!this.editorIsAttached()){this.editorCameraFrame=0,u(!1);return}this.editorCameraFrame=requestAnimationFrame(i)};this.editorCameraFrame=requestAnimationFrame(i)}stopWatchingEditorDetached(){this.editorCameraFrame&&(cancelAnimationFrame(this.editorCameraFrame),this.editorCameraFrame=0)}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 O(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 be(t){h().channel.send("scene:operation",t)}export{te as a,ne as b,ie as c,oe as d,O as e,T as f,N as g,me as h,f as i,W as j,_ as k,Q as l,fe as m,q as n,be as o};
|