@zylem/game-lib 0.8.2 → 0.8.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (58) hide show
  1. package/dist/actions.d.ts +5 -5
  2. package/dist/api/game-lib.api.json +2079 -1214
  3. package/dist/api/game-lib.api.md +150 -97
  4. package/dist/api/game-lib.d.ts +321 -95
  5. package/dist/api/game-lib.typedoc.json +141279 -214520
  6. package/dist/bridge.d.ts +111 -0
  7. package/dist/bridge.js +1 -0
  8. package/dist/{chunk-KVSJE4XD.js → chunk-3I537JFL.js} +1 -1
  9. package/dist/chunk-4CHZUWLF.js +1 -0
  10. package/dist/chunk-6B5JP7T5.js +24 -0
  11. package/dist/chunk-AIQ6IVT5.js +1 -0
  12. package/dist/chunk-C5NEGC3S.js +1 -0
  13. package/dist/chunk-D3JO4HW2.js +1 -0
  14. package/dist/chunk-HNCTOJP7.js +1 -0
  15. package/dist/chunk-LKFF6XJC.js +1 -0
  16. package/dist/{chunk-CD7ZOZ35.js → chunk-OAWK2UUY.js} +1 -1
  17. package/dist/chunk-PNLNC3FA.js +1 -0
  18. package/dist/chunk-TV3AZKT4.js +9 -0
  19. package/dist/chunk-VIPINV7V.js +19 -0
  20. package/dist/chunk-W5SXED5T.js +1 -0
  21. package/dist/{chunk-YAOXFYOD.js → chunk-WBQ5TNRZ.js} +1 -1
  22. package/dist/{collision-builder-B_tm8OVy.d.ts → collision-builder-4TVDzXsp.d.ts} +1 -1
  23. package/dist/core.d.ts +11 -11
  24. package/dist/core.js +1 -1
  25. package/dist/debug-state-s0s-qndj.d.ts +49 -0
  26. package/dist/debug.d.ts +32 -7
  27. package/dist/debug.js +1 -1
  28. package/dist/{entity-BGEq1yfC.d.ts → entity-BI7cSlK8.d.ts} +3 -3
  29. package/dist/{entity-B9yZeBm4.d.ts → entity-DDks47JB.d.ts} +1 -1
  30. package/dist/{entity-type-map-CW6RHQkx.d.ts → entity-type-map-COHu4fkW.d.ts} +41 -7
  31. package/dist/entity.d.ts +7 -7
  32. package/dist/entity.js +1 -1
  33. package/dist/events.d.ts +1 -64
  34. package/dist/events.js +1 -1
  35. package/dist/{game-DbqBQiFC.d.ts → game-4fsy55uN.d.ts} +55 -27
  36. package/dist/game-default-4PPYYGAR.js +1 -0
  37. package/dist/graphics.d.ts +5 -5
  38. package/dist/{material-DbSuZBbP.d.ts → material-BKPYeBC6.d.ts} +1 -1
  39. package/dist/public.d.ts +12 -10
  40. package/dist/public.js +1 -1
  41. package/dist/runtime.d.ts +3 -3
  42. package/dist/runtime.js +1 -1
  43. package/dist/{vector-DN6zlPoE.d.ts → vector-DPbwlzgG.d.ts} +10 -2
  44. package/dist/web-components.d.ts +9 -9
  45. package/dist/web-components.js +1 -1
  46. package/dist/{zylem-camera-Du2UPW9O.d.ts → zylem-camera-B73ZNcgs.d.ts} +1 -1
  47. package/package.json +20 -14
  48. package/LICENSE +0 -21
  49. package/dist/chunk-3PRBSSTS.js +0 -24
  50. package/dist/chunk-CFVRRRZZ.js +0 -1
  51. package/dist/chunk-COM6HJ2L.js +0 -1
  52. package/dist/chunk-JQKS42G4.js +0 -1
  53. package/dist/chunk-MZZCDXFB.js +0 -1
  54. package/dist/chunk-TAUWDQZF.js +0 -9
  55. package/dist/chunk-VS2D4B3W.js +0 -1
  56. package/dist/chunk-YHEWKN7N.js +0 -1
  57. package/dist/debug-state-DRoeasG2.d.ts +0 -17
  58. package/dist/game-default-6AZZCNST.js +0 -1
@@ -0,0 +1,24 @@
1
+ import{b as he,d as G,j as we,u as L,v as R}from"./chunk-4CHZUWLF.js";import{b as ve}from"./chunk-7GYFZKK7.js";import{b as y}from"./chunk-VIPINV7V.js";import{a as ye,c as be}from"./chunk-D3JO4HW2.js";import{a as g,d as me,e as K}from"./chunk-W5SXED5T.js";import{l as Ce}from"./chunk-PNLNC3FA.js";import{a as $,r as j}from"./chunk-3I537JFL.js";import{j as Se}from"./chunk-CM5YRNBJ.js";import{a as fe,b}from"./chunk-AIQ6IVT5.js";import{c as S}from"./chunk-D2PATZCC.js";import{c as re,d as C,e as le,h as ue,i as pe,j as de,k as J,l as x,m as ce}from"./chunk-4QLJUQSJ.js";import{j as W}from"./chunk-7WRQ2UAN.js";import{g as ge}from"./chunk-PCFF4LLO.js";import{l as v}from"./chunk-UG22Z42P.js";function ze(){return{pressed:!1,released:!1,held:0}}function Ae(){return{value:0,held:0}}function k(a){let e=new Map;if(!a)return e;for(let[t,n]of Object.entries(a)){if(!n||n.length===0)continue;let i=[];for(let o of n){let[r,s]=(o||"").split(".");if(!r||!s)continue;let l=r.toLowerCase(),u=s.toLowerCase();if(l==="buttons"){let p={a:"A",b:"B",x:"X",y:"Y",start:"Start",select:"Select",l:"L",r:"R"}[u];p&&i.push({category:"buttons",property:p})}else if(l==="directions"){let p={up:"Up",down:"Down",left:"Left",right:"Right"}[u];p&&i.push({category:"directions",property:p})}else if(l==="shoulders"){let p={ltrigger:"LTrigger",rtrigger:"RTrigger"}[u];p&&i.push({category:"shoulders",property:p})}else if(l==="axes"){let p={left:{property:"Horizontal",direction:-1},right:{property:"Horizontal",direction:1},up:{property:"Vertical",direction:-1},down:{property:"Vertical",direction:1},secondaryleft:{property:"SecondaryHorizontal",direction:-1},secondaryright:{property:"SecondaryHorizontal",direction:1},secondaryup:{property:"SecondaryVertical",direction:-1},secondarydown:{property:"SecondaryVertical",direction:1}}[u];p&&i.push({category:"axes",property:p.property,axisDirection:p.direction})}}i.length>0&&e.set(t,i)}return e}function d(a,e){return!a&&!e?ze():a?e?{pressed:a.pressed||e.pressed,released:a.released||e.released,held:a.held+e.held}:{...a}:{...e}}function f(a,e){return!a&&!e?Ae():a?e?{value:a.value+e.value,held:a.held+e.held}:{...a}:{...e}}var w=class{keyStates=new Map;keyButtonStates=new Map;analogStates=new Map;compiledMapping;includeDefaultBase=!0;onKeyDown=({key:e})=>this.keyStates.set(e,!0);onKeyUp=({key:e})=>this.keyStates.set(e,!1);constructor(e,t){this.includeDefaultBase=t?.includeDefaultBase??!0,this.compiledMapping=k(e??null),window.addEventListener("keydown",this.onKeyDown),window.addEventListener("keyup",this.onKeyUp)}dispose(){window.removeEventListener("keydown",this.onKeyDown),window.removeEventListener("keyup",this.onKeyUp),this.keyStates.clear(),this.keyButtonStates.clear(),this.analogStates.clear()}isKeyPressed(e){return this.keyStates.get(e)||!1}handleButtonState(e,t){let n=this.keyButtonStates.get(e);n||(n={pressed:!1,released:!1,held:0},this.keyButtonStates.set(e,n));let i=this.isKeyPressed(e);return n.pressed=i&&n.held===0,n.released=!i&&n.held>0,n.held=i?n.held+t:0,n}handleAnalogState(e,t,n){let i=`${e}:${t}`,o=this.analogStates.get(i);return o||(o={value:0,held:0},this.analogStates.set(i,o)),o.value=this.getAxisValue(e,t),o.held=o.value!==0?o.held+n:0,o}applyCustomMapping(e,t){if(this.compiledMapping.size===0)return e;let n=new Map;for(let[i,o]of this.compiledMapping.entries()){let r=null;for(let s of o)if(s.category==="axes")n.has(s.property)||n.set(s.property,0),this.isKeyPressed(i)&&n.set(s.property,n.get(s.property)+s.axisDirection);else{r||(r=this.handleButtonState(i,t));let l=e[s.category]??={};l[s.property]=d(l[s.property],r)}}if(n.size>0){e.axes||(e.axes={});for(let[i,o]of n.entries()){let r=`custom:${i}`,s=this.analogStates.get(r);s||(s={value:0,held:0},this.analogStates.set(r,s)),s.value=o,s.held=o!==0?s.held+t:0,e.axes[i]=f(e.axes[i],s)}}return e}getInput(e){let t={};return this.includeDefaultBase&&(t.buttons={A:this.handleButtonState("z",e),B:this.handleButtonState("x",e),X:this.handleButtonState("a",e),Y:this.handleButtonState("s",e),Start:this.handleButtonState(" ",e),Select:this.handleButtonState("Enter",e),L:this.handleButtonState("q",e),R:this.handleButtonState("e",e)},t.directions={Up:this.handleButtonState("ArrowUp",e),Down:this.handleButtonState("ArrowDown",e),Left:this.handleButtonState("ArrowLeft",e),Right:this.handleButtonState("ArrowRight",e)},t.shoulders={LTrigger:this.handleButtonState("Q",e),RTrigger:this.handleButtonState("E",e)}),this.applyCustomMapping(t,e)}getName(){return"keyboard"}getAxisValue(e,t){return(this.isKeyPressed(t)?1:0)-(this.isKeyPressed(e)?1:0)}isConnected(){return!0}};var D=class{gamepadIndex;connected=!1;buttonStates={};analogStates={};onConnected=e=>{e.gamepad.index===this.gamepadIndex&&(this.connected=!0)};onDisconnected=e=>{e.gamepad.index===this.gamepadIndex&&(this.connected=!1)};constructor(e){this.gamepadIndex=e,window.addEventListener("gamepadconnected",this.onConnected),window.addEventListener("gamepaddisconnected",this.onDisconnected)}dispose(){window.removeEventListener("gamepadconnected",this.onConnected),window.removeEventListener("gamepaddisconnected",this.onDisconnected),this.buttonStates={},this.analogStates={}}handleButtonState(e,t,n){let i=this.buttonStates[e];i||(i={pressed:!1,released:!1,held:0},this.buttonStates[e]=i);let o=t.buttons[e].pressed;return i.pressed=o&&i.held===0,i.released=!o&&i.held>0,i.held=o?i.held+n:0,i}handleAnalogState(e,t,n){let i=this.analogStates[e];return i||(i={value:0,held:0},this.analogStates[e]=i),i.value=t.axes[e],i.held=i.value!==0?i.held+n:0,i}getInput(e){let t=navigator.getGamepads()[this.gamepadIndex];return t?{buttons:{A:this.handleButtonState(0,t,e),B:this.handleButtonState(1,t,e),X:this.handleButtonState(2,t,e),Y:this.handleButtonState(3,t,e),Start:this.handleButtonState(9,t,e),Select:this.handleButtonState(8,t,e),L:this.handleButtonState(4,t,e),R:this.handleButtonState(5,t,e)},directions:{Up:this.handleButtonState(12,t,e),Down:this.handleButtonState(13,t,e),Left:this.handleButtonState(14,t,e),Right:this.handleButtonState(15,t,e)},axes:{Horizontal:this.handleAnalogState(0,t,e),Vertical:this.handleAnalogState(1,t,e),SecondaryHorizontal:this.handleAnalogState(2,t,e),SecondaryVertical:this.handleAnalogState(3,t,e)},shoulders:{LTrigger:this.handleButtonState(6,t,e),RTrigger:this.handleButtonState(7,t,e)}}:{}}getName(){return`gamepad-${this.gamepadIndex+1}`}isConnected(){return this.connected}};import{subscribe as Ve}from"valtio/vanilla";var He=.002;function z(a,e,t){return Math.max(e,Math.min(t,a))}function Oe(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 E=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=Oe(this.targetElement);if(n){let i=n.getBoundingClientRect();if(i.width>0&&i.height>0){let o=i.left+i.width/2,r=i.top+i.height/2;this.pointerCenterX=z((e-o)/(i.width/2),-1,1),this.pointerCenterY=z((t-r)/(i.height/2),-1,1);return}}this.pointerCenterX=z((this.pointerX-.5)*2,-1,1),this.pointerCenterY=z((this.pointerY-.5)*2,-1,1)}onMouseMove=e=>{this.updatePointerPosition(e.clientX,e.clientY),!(g.enabled||this.lookMode==="screenCenter")&&(this.movementX+=e.movementX,this.movementY+=e.movementY)};onMouseDown=e=>{let t=e.target;t instanceof HTMLCanvasElement&&this.targetElement.contains(t)&&(this.mouseButtonDown.add(e.button),this.usePointerLock&&!this.isLocked&&!g.enabled&&this.targetElement.requestPointerLock())};onMouseUp=e=>{this.mouseButtonDown.delete(e.button)};onContextMenu=e=>{e.preventDefault()};onPointerLockChange=()=>{this.isLocked=document.pointerLockElement===this.targetElement};constructor(e,t){this.sensitivity=e?.sensitivity??He,this.lookMode=e?.lookMode??"delta",this.usePointerLock=e?.pointerLock??!1,this.compiledMapping=k(e?.mapping??null),this.targetElement=t??document.body,window.addEventListener("mousemove",this.onMouseMove),this.targetElement.addEventListener("mousedown",this.onMouseDown),this.targetElement.addEventListener("mouseup",this.onMouseUp),this.targetElement.addEventListener("contextmenu",this.onContextMenu),this.usePointerLock&&(document.addEventListener("pointerlockchange",this.onPointerLockChange),this.debugUnsubscribe=Ve(g,()=>{g.enabled&&document.pointerLockElement===this.targetElement&&document.exitPointerLock()}))}dispose(){window.removeEventListener("mousemove",this.onMouseMove),this.targetElement.removeEventListener("mousedown",this.onMouseDown),this.targetElement.removeEventListener("mouseup",this.onMouseUp),this.targetElement.removeEventListener("contextmenu",this.onContextMenu),document.removeEventListener("pointerlockchange",this.onPointerLockChange),this.debugUnsubscribe?.(),this.debugUnsubscribe=null,this.isLocked&&document.exitPointerLock(),this.buttonStates.clear(),this.analogStates.clear(),this.mouseButtonDown.clear(),this.movementX=0,this.movementY=0}handleMouseButton(e,t){let n=this.buttonStates.get(e);n||(n={pressed:!1,released:!1,held:0},this.buttonStates.set(e,n));let i=this.mouseButtonDown.has(e);return n.pressed=i&&n.held===0,n.released=!i&&n.held>0,n.held=i?n.held+t:0,n}handleMovementAxis(e,t){let n=this.analogStates.get(e);n||(n={value:0,held:0},this.analogStates.set(e,n));let i=e==="x"?this.movementX:this.movementY;return n.value=Math.max(-1,Math.min(1,i*this.sensitivity)),n.held=n.value!==0?n.held+t:0,n}applyCustomMapping(e,t){if(this.compiledMapping.size===0)return e;let n=new Map,i={leftbutton:()=>this.handleMouseButton(0,t),rightbutton:()=>this.handleMouseButton(2,t),middlebutton:()=>this.handleMouseButton(1,t)};for(let[o,r]of this.compiledMapping.entries()){let s=o.toLowerCase();for(let l of r)if(l.category==="axes")n.has(l.property)||n.set(l.property,0),s==="movex"?n.set(l.property,n.get(l.property)+Math.max(-1,Math.min(1,this.movementX*this.sensitivity))*l.axisDirection):s==="movey"?n.set(l.property,n.get(l.property)+Math.max(-1,Math.min(1,this.movementY*this.sensitivity))*l.axisDirection):s in i&&this.mouseButtonDown.has(this.buttonIndexForAction(s))&&n.set(l.property,n.get(l.property)+l.axisDirection);else{let u=i[s];if(u){let m=u();if(m){let p=e[l.category]??={};p[l.property]=d(p[l.property],m)}}}}if(n.size>0){e.axes||(e.axes={});for(let[o,r]of n.entries()){let s=`custom:${o}`,l=this.analogStates.get(s);l||(l={value:0,held:0},this.analogStates.set(s,l)),l.value=Math.max(-1,Math.min(1,r)),l.held=r!==0?l.held+t:0,e.axes[o]=f(e.axes[o],l)}}return e}buttonIndexForAction(e){switch(e){case"leftbutton":return 0;case"middlebutton":return 1;case"rightbutton":return 2;default:return-1}}getInput(e){g.enabled&&(this.movementX=0,this.movementY=0);let t={value:0,held:0},n=this.lookMode==="delta",i={axes:{Horizontal:t,Vertical:t,SecondaryHorizontal:n?this.handleMovementAxis("x",e):t,SecondaryVertical:n?this.handleMovementAxis("y",e):t},shoulders:{LTrigger:this.handleMouseButton(0,e),RTrigger:this.handleMouseButton(2,e)},pointer:{x:this.pointerX,y:this.pointerY,centerX:this.pointerCenterX,centerY:this.pointerCenterY}};return this.movementX=0,this.movementY=0,this.applyCustomMapping(i,e)}getName(){return"mouse"}isConnected(){return!0}};function T(a={}){if(typeof window>"u"||typeof navigator>"u")return!1;let e=navigator.userAgent,t=/android/i.test(e)||/iPad|iPhone|iPod/.test(e),n="ontouchstart"in window||navigator.maxTouchPoints>0,i=typeof window.matchMedia=="function"?window.matchMedia("(pointer: coarse)").matches:!1,o=a.viewportSize?.width??window.innerWidth??0,r=a.viewportSize?.height??window.innerHeight??0,s=Math.max(o,r),l=s===0||s<=1024;return a.allowViewportOnly&&a.viewportSize?l:t||(n||i)&&l}var Ue=["A","B","X","Y","Start","Select","L","R","LTrigger","RTrigger","Up","Down","Left","Right"],_e=new Set(["flex","flexGrow","flexShrink","fontWeight","lineHeight","opacity","order","zIndex","zoom"]),Ne={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"}},Fe={left:{size:140,thumbSize:58,maxDistance:44,deadzone:.12,directionThreshold:.34,horizontalAxis:"Horizontal",verticalAxis:"Vertical",emitDirections:!0,position:{left:24,bottom:24}},right:{size:140,thumbSize:58,maxDistance:44,deadzone:.12,directionThreshold:.34,horizontalAxis:"SecondaryHorizontal",verticalAxis:"SecondaryVertical",emitDirections:!1,position:{right:24,bottom:236}}},M=class{config;targetElement;buttonStates=new Map;analogStates=new Map;buttons=new Map;joysticks=new Map;rootElement=null;enabled=!1;onPointerMove=e=>{for(let t of this.joysticks.values())t.pointerId===e.pointerId&&(this.consumeEvent(e),this.updateJoystickFromPoint(t,e.clientX,e.clientY))};onPointerUp=e=>{for(let t of this.buttons.values())t.pointerId===e.pointerId&&(this.consumeEvent(e),this.releaseButton(t));for(let t of this.joysticks.values())t.pointerId===e.pointerId&&(this.consumeEvent(e),this.releaseJoystick(t))};onWindowBlur=()=>{for(let e of this.buttons.values())this.releaseButton(e);for(let e of this.joysticks.values())this.releaseJoystick(e)};constructor(e,t){this.config=e??{},this.targetElement=t??document.body,this.enabled=this.resolveEnabledState(),this.enabled&&(this.mountControls(),window.addEventListener("pointermove",this.onPointerMove),window.addEventListener("pointerup",this.onPointerUp),window.addEventListener("pointercancel",this.onPointerUp),window.addEventListener("blur",this.onWindowBlur))}getInput(e){if(!this.enabled)return{};let t={};for(let n of this.buttons.values()){let i=this.handleButtonState(`button:${n.slot}`,n.pointerId!==null,e);this.assignButtonState(t,this.resolveButtonTarget(n.slot),i)}for(let n of this.joysticks.values()){let i=this.handleAnalogState(`joystick:${n.id}:x`,n.valueX,e),o=this.handleAnalogState(`joystick:${n.id}:y`,n.valueY,e);this.assignAxisState(t,n.config.horizontalAxis,i),this.assignAxisState(t,n.config.verticalAxis,o),n.config.emitDirections&&(this.assignButtonState(t,this.resolveButtonTarget("Left"),this.handleButtonState(`joystick:${n.id}:left`,n.valueX<=-n.config.directionThreshold,e)),this.assignButtonState(t,this.resolveButtonTarget("Right"),this.handleButtonState(`joystick:${n.id}:right`,n.valueX>=n.config.directionThreshold,e)),this.assignButtonState(t,this.resolveButtonTarget("Up"),this.handleButtonState(`joystick:${n.id}:up`,n.valueY<=-n.config.directionThreshold,e)),this.assignButtonState(t,this.resolveButtonTarget("Down"),this.handleButtonState(`joystick:${n.id}:down`,n.valueY>=n.config.directionThreshold,e)))}return t}getName(){return"virtual-touch"}isConnected(){return this.enabled}dispose(){window.removeEventListener("pointermove",this.onPointerMove),window.removeEventListener("pointerup",this.onPointerUp),window.removeEventListener("pointercancel",this.onPointerUp),window.removeEventListener("blur",this.onWindowBlur),this.rootElement?.remove(),this.rootElement=null,this.buttons.clear(),this.joysticks.clear(),this.buttonStates.clear(),this.analogStates.clear()}resolveEnabledState(){return typeof window>"u"||typeof document>"u"?!1:this.config.enabled===!0?!0:this.config.enabled===!1?!1:T()}mountControls(){this.rootElement=document.createElement("div"),this.rootElement.className="zylem-virtual-touch",this.rootElement.dataset.zylemTouchRoot="true",this.rootElement.style.position="absolute",this.rootElement.style.inset="0",this.rootElement.style.pointerEvents="none",this.rootElement.style.touchAction="none",this.rootElement.style.userSelect="none",this.rootElement.style.WebkitUserSelect="none",this.rootElement.style.WebkitTouchCallout="none",this.rootElement.style.color="rgba(245, 247, 255, 0.96)",this.rootElement.style.zIndex="20",this.appendClassName(this.rootElement,this.config.className),B(this.rootElement,this.config.style),this.rootElement.addEventListener("contextmenu",e=>e.preventDefault());for(let[e,t]of this.resolveButtons())this.rootElement.appendChild(this.createButton(e,t));for(let[e,t]of this.resolveJoysticks())this.rootElement.appendChild(this.createJoystick(e,t));this.targetElement.appendChild(this.rootElement)}resolveButtons(){if(this.config.buttons===!1)return[];let e=this.config.buttons,t=[];for(let n of Ue){let i=Ne[n],o=e?.[n];if(o===!1)continue;let r={...i,...o??{},style:{...i.style,...o?.style},position:{...i.position,...o?.position},label:o?.label??i.label??n,size:o?.size??i.size??72};r.enabled!==!1&&t.push([n,r])}return t}resolveJoysticks(){if(this.config.joysticks===!1)return[];let e=this.config.joysticks,t=[];for(let n of["left","right"]){let i=Fe[n],o=e?.[n];if(o===!1)continue;let r={...i,...o??{},style:{...i.style,...o?.style},position:{...i.position,...o?.position},svg:{...i.svg,...o?.svg},size:o?.size??i.size??140,thumbSize:o?.thumbSize??i.thumbSize??58,maxDistance:o?.maxDistance??i.maxDistance??44,deadzone:o?.deadzone??i.deadzone??.12,directionThreshold:o?.directionThreshold??i.directionThreshold??.34,horizontalAxis:o?.horizontalAxis??i.horizontalAxis??"Horizontal",verticalAxis:o?.verticalAxis??i.verticalAxis??"Vertical",emitDirections:o?.emitDirections??i.emitDirections??!1};r.enabled!==!1&&t.push([n,r])}return t}createButton(e,t){let n=document.createElement("button"),i=document.createElement("div");n.type="button",n.ariaLabel=t.label,n.className=`zylem-virtual-touch__button zylem-virtual-touch__button--${e}`,n.dataset.zylemTouchButton=e,n.dataset.active="false",n.style.position="absolute",n.style.width=`${t.size}px`,n.style.height=`${t.size}px`,n.style.padding="0",n.style.margin="0",n.style.border="0",n.style.background="transparent",n.style.pointerEvents="auto",n.style.touchAction="none",n.style.cursor="pointer",n.style.appearance="none",n.style.outline="none",n.style.userSelect="none",n.style.WebkitTapHighlightColor="transparent",B(n,t.position),B(n,t.style),this.appendClassName(n,t.className),i.className="zylem-virtual-touch__button-content",i.style.width="100%",i.style.height="100%",i.style.pointerEvents="none",i.style.transform="scale(1)",i.style.transformOrigin="center",i.style.transition="transform 120ms ease, opacity 120ms ease",i.style.opacity="0.92",i.innerHTML=t.svg??Ye(t.label),n.appendChild(i),n.addEventListener("pointerdown",r=>{if(!xe(r))return;let s=this.buttons.get(e);!s||s.pointerId!==null||(this.consumeEvent(r),s.pointerId=r.pointerId,this.updateButtonVisual(s,!0))});let o={slot:e,config:t,element:n,content:i,pointerId:null};return this.buttons.set(e,o),n}createJoystick(e,t){let n=document.createElement("div"),i=document.createElement("div"),o=document.createElement("div");n.className=`zylem-virtual-touch__joystick zylem-virtual-touch__joystick--${e}`,n.dataset.zylemTouchJoystick=e,n.dataset.active="false",n.style.position="absolute",n.style.width=`${t.size}px`,n.style.height=`${t.size}px`,n.style.pointerEvents="auto",n.style.touchAction="none",n.style.userSelect="none",B(n,t.position),B(n,t.style),this.appendClassName(n,t.className),i.className="zylem-virtual-touch__joystick-base",i.style.position="absolute",i.style.inset="0",i.style.pointerEvents="none",i.style.opacity="0.88",i.style.transition="opacity 120ms ease",i.innerHTML=t.svg?.base??Ze(),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??Je(),n.append(i,o);let r={id:e,config:t,element:n,base:i,thumb:o,pointerId:null,centerX:0,centerY:0,rawX:0,rawY:0,valueX:0,valueY:0};return this.joysticks.set(e,r),n.addEventListener("pointerdown",s=>{if(!xe(s))return;let l=this.joysticks.get(e);if(!l||l.pointerId!==null)return;this.consumeEvent(s);let u=l.element.getBoundingClientRect();l.pointerId=s.pointerId,l.centerX=u.left+u.width/2,l.centerY=u.top+u.height/2,this.updateJoystickVisual(l,!0),this.updateJoystickFromPoint(l,s.clientX,s.clientY)}),n}handleButtonState(e,t,n){let i=this.buttonStates.get(e);return i||(i={pressed:!1,released:!1,held:0},this.buttonStates.set(e,i)),i.pressed=t&&i.held===0,i.released=!t&&i.held>0,i.held=t?i.held+n:0,i}handleAnalogState(e,t,n){let i=this.analogStates.get(e);return i||(i={value:0,held:0},this.analogStates.set(e,i)),i.value=t,i.held=t!==0?i.held+n:0,i}assignAxisState(e,t,n){e.axes||(e.axes={}),e.axes[t]=f(e.axes[t],n)}assignButtonState(e,t,n){if(t.category==="buttons"){e.buttons??={},e.buttons[t.property]=d(e.buttons[t.property],n);return}if(t.category==="directions"){e.directions??={},e.directions[t.property]=d(e.directions[t.property],n);return}e.shoulders??={},e.shoulders[t.property]=d(e.shoulders[t.property],n)}resolveButtonTarget(e){switch(e){case"LTrigger":case"RTrigger":return{category:"shoulders",property:e};case"Up":case"Down":case"Left":case"Right":return{category:"directions",property:e};default:return{category:"buttons",property:e}}}updateJoystickFromPoint(e,t,n){let i=t-e.centerX,o=n-e.centerY,r=Math.hypot(i,o),s=e.config.maxDistance,l=r>s&&r>0?s/r:1;e.rawX=i*l,e.rawY=o*l;let u=Xe(e.rawX/s,e.rawY/s,e.config.deadzone);e.valueX=u.x,e.valueY=u.y,e.thumb.style.transform=`translate(-50%, -50%) translate(${e.rawX}px, ${e.rawY}px)`}releaseButton(e){e.pointerId=null,this.updateButtonVisual(e,!1)}releaseJoystick(e){e.pointerId=null,e.rawX=0,e.rawY=0,e.valueX=0,e.valueY=0,e.thumb.style.transform="translate(-50%, -50%) translate(0px, 0px)",this.updateJoystickVisual(e,!1)}updateButtonVisual(e,t){e.element.dataset.active=String(t),e.content.style.transform=t?"scale(0.94)":"scale(1)",e.content.style.opacity=t?"1":"0.92"}updateJoystickVisual(e,t){e.element.dataset.active=String(t),e.base.style.opacity=t?"1":"0.88",e.thumb.style.opacity=t?"1":"0.94"}consumeEvent(e){e.cancelable&&e.preventDefault(),e.stopPropagation()}appendClassName(e,t){t&&(e.className=`${e.className} ${t}`.trim())}};function B(a,e){if(e)for(let[t,n]of Object.entries(e)){if(n==null)continue;let i=typeof n=="number"&&!_e.has(t)?`${n}px`:String(n);t.includes("-")?a.style.setProperty(t,i):a.style[t]=i}}function Xe(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 Ye(a){let e=Ke(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 Ze(){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 Je(){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 Ke(a){return a.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;").replaceAll("'","&#39;")}function xe(a){return a.pointerType==="touch"}var A=class{inputMap=new Map;currentInputs={};previousInputs={};targetElement;mouseTargetElement;constructor(e,t){this.targetElement=t?.targetElement,this.mouseTargetElement=t?.mouseTargetElement??t?.targetElement;let n=this.buildPlayerEntries(e);for(let{player:i,config:o,gamepadIndex:r,isP1:s}of n)this.addConfigurableProviders(i,o,s),this.addInputProvider(i,new D(r))}configure(e){let t=this.buildPlayerEntries(e);for(let{player:n,config:i,isP1:o}of t){let s=(this.inputMap.get(n)??[]).filter(l=>l instanceof w||l instanceof E||l instanceof M?(l.dispose(),!1):!0);this.inputMap.set(n,[...this.createConfigurableProviders(i,o),...s])}}addInputProvider(e,t){this.inputMap.has(e)||this.inputMap.set(e,[]),this.inputMap.get(e)?.push(t)}dispose(){for(let e of this.inputMap.values())for(let t of e)t.dispose?.();this.inputMap.clear(),this.currentInputs={},this.previousInputs={}}getInputs(e){let t={};return this.inputMap.forEach((n,i)=>{let o=`p${i}`,r=n.reduce((s,l)=>{let u=l.getInput(e);return this.mergeInputs(s,u)},{});t[o]={playerNumber:i,...r}}),t}buildPlayerEntries(e){return[{player:1,config:e?.p1,gamepadIndex:0,isP1:!0},{player:2,config:e?.p2,gamepadIndex:1,isP1:!1},{player:3,config:e?.p3,gamepadIndex:2,isP1:!1},{player:4,config:e?.p4,gamepadIndex:3,isP1:!1},{player:5,config:e?.p5,gamepadIndex:4,isP1:!1},{player:6,config:e?.p6,gamepadIndex:5,isP1:!1},{player:7,config:e?.p7,gamepadIndex:6,isP1:!1},{player:8,config:e?.p8,gamepadIndex:7,isP1:!1}]}addConfigurableProviders(e,t,n){for(let i of this.createConfigurableProviders(t,n))this.addInputProvider(e,i)}createConfigurableProviders(e,t){let n=[];if(e?.key){let i=e.includeDefaults??t;n.push(new w(e.key,{includeDefaultBase:i}))}else t&&n.push(new w);return e?.mouse&&n.push(new E(e.mouse,this.mouseTargetElement)),e?.touch&&n.push(new M(e.touch,this.targetElement)),n}mergeInputs(e,t){return{buttons:{A:d(e.buttons?.A,t.buttons?.A),B:d(e.buttons?.B,t.buttons?.B),X:d(e.buttons?.X,t.buttons?.X),Y:d(e.buttons?.Y,t.buttons?.Y),Start:d(e.buttons?.Start,t.buttons?.Start),Select:d(e.buttons?.Select,t.buttons?.Select),L:d(e.buttons?.L,t.buttons?.L),R:d(e.buttons?.R,t.buttons?.R)},directions:{Up:d(e.directions?.Up,t.directions?.Up),Down:d(e.directions?.Down,t.directions?.Down),Left:d(e.directions?.Left,t.directions?.Left),Right:d(e.directions?.Right,t.directions?.Right)},axes:{Horizontal:f(e.axes?.Horizontal,t.axes?.Horizontal),Vertical:f(e.axes?.Vertical,t.axes?.Vertical),SecondaryHorizontal:f(e.axes?.SecondaryHorizontal,t.axes?.SecondaryHorizontal),SecondaryVertical:f(e.axes?.SecondaryVertical,t.axes?.SecondaryVertical)},shoulders:{LTrigger:d(e.shoulders?.LTrigger,t.shoulders?.LTrigger),RTrigger:d(e.shoulders?.RTrigger,t.shoulders?.RTrigger)},pointer:t.pointer??e.pointer}}};var V=class{_previousTime;_currentTime;_startTime;_delta;_elapsed;_timescale;_document;_pageVisibilityHandler;constructor(){this._previousTime=0,this._currentTime=0,this._startTime=q(),this._delta=0,this._elapsed=0,this._timescale=1,this._document=null,this._pageVisibilityHandler=null}connect(e){this._document=e,e.hidden!==void 0&&(this._pageVisibilityHandler=$e.bind(this),e.addEventListener("visibilitychange",this._pageVisibilityHandler,!1))}disconnect(){this._pageVisibilityHandler!==null&&(this._document.removeEventListener("visibilitychange",this._pageVisibilityHandler),this._pageVisibilityHandler=null),this._document=null}getDelta(){return this._delta/1e3}getElapsed(){return this._elapsed/1e3}getTimescale(){return this._timescale}setTimescale(e){return this._timescale=e,this}reset(){return this._currentTime=q()-this._startTime,this}dispose(){this.disconnect()}update(e){return this._pageVisibilityHandler!==null&&this._document.hidden===!0?this._delta=0:(this._previousTime=this._currentTime,this._currentTime=(e!==void 0?e:q())-this._startTime,this._delta=(this._currentTime-this._previousTime)*this._timescale,this._elapsed+=this._delta),this}};function q(){return performance.now()}function $e(){this._document.hidden===!1&&this.reset()}var I={FourByThree:1.3333333333333333,SixteenByNine:1.7777777777777777,NineBySixteen:.5625,TwentyOneByNine:2.3333333333333335,OneByOne:1},H=class{container;canvas;aspectRatio;onResize;handleResizeBound;resizeObserver=null;constructor(e){this.container=e.container,this.canvas=e.canvas,this.aspectRatio=(typeof e.aspectRatio=="number",e.aspectRatio),this.onResize=e.onResize,this.handleResizeBound=this.apply.bind(this)}attach(){window.addEventListener("resize",this.handleResizeBound),typeof ResizeObserver<"u"&&(this.resizeObserver=new ResizeObserver(this.handleResizeBound),this.resizeObserver.observe(this.container)),this.apply()}detach(){window.removeEventListener("resize",this.handleResizeBound),this.resizeObserver?.disconnect(),this.resizeObserver=null}measure(){let e=this.container.getBoundingClientRect(),t=Math.round(e.width||this.container.clientWidth||0),n=Math.round(e.height||this.container.clientHeight||0);if(t>0&&n>0){if(t/n>this.aspectRatio){let u=n;return{width:Math.round(u*this.aspectRatio),height:u}}let s=t,l=Math.round(s/this.aspectRatio);return{width:s,height:l}}if(t>0){let r=t,s=Math.round(r/this.aspectRatio);return{width:r,height:s}}if(n>0){let r=n;return{width:Math.round(r*this.aspectRatio),height:r}}let i=window.innerWidth,o=Math.round(i/this.aspectRatio);return{width:i,height:o}}apply(){let{width:e,height:t}=this.measure();this.canvas.style.width=`${e}px`,this.canvas.style.height=`${t}px`,this.onResize?.(e,t)}};var Ge={NES:{displayAspect:1.3333333333333333,resolutions:[{key:"256x240",width:256,height:240,notes:"Standard NTSC; effective 240p."}]},SNES:{displayAspect:1.3333333333333333,resolutions:[{key:"256x224",width:256,height:224,notes:"Common 240p-equivalent mode."},{key:"512x448",width:512,height:448,notes:"Hi-res interlaced (480i)."}]},N64:{displayAspect:1.3333333333333333,resolutions:[{key:"320x240",width:320,height:240,notes:"Common 240p mode."},{key:"640x480",width:640,height:480,notes:"Higher resolution (480i)."}]},PS1:{displayAspect:1.3333333333333333,resolutions:[{key:"320x240",width:320,height:240,notes:"Progressive 240p common."},{key:"640x480",width:640,height:480,notes:"Interlaced 480i for higher detail."}]},PS2:{displayAspect:1.3333333333333333,resolutions:[{key:"640x480",width:640,height:480,notes:"480i/480p baseline."},{key:"720x480",width:720,height:480,notes:"480p (widescreen capable in some titles)."},{key:"1280x720",width:1280,height:720,notes:"720p (select titles)."}]},PS5:{displayAspect:1.7777777777777777,resolutions:[{key:"720x480",width:720,height:480,notes:"Legacy compatibility."},{key:"1280x720",width:1280,height:720,notes:"720p."},{key:"1920x1080",width:1920,height:1080,notes:"1080p."},{key:"2560x1440",width:2560,height:1440,notes:"1440p."},{key:"3840x2160",width:3840,height:2160,notes:"4K (up to 120Hz)."},{key:"7680x4320",width:7680,height:4320,notes:"8K (limited)."}]},XboxOne:{displayAspect:1.7777777777777777,resolutions:[{key:"1280x720",width:1280,height:720,notes:"720p (original)."},{key:"1920x1080",width:1920,height:1080,notes:"1080p (original)."},{key:"3840x2160",width:3840,height:2160,notes:"4K UHD (S/X models)."}]},MobilePortrait:{displayAspect:.5625,resolutions:[{key:"360x640",width:360,height:640,notes:"Low-density phone portrait baseline."},{key:"720x1280",width:720,height:1280,notes:"HD phone portrait."},{key:"1080x1920",width:1080,height:1920,notes:"Full HD phone portrait."}]}};function Q(a){return Ge[a].displayAspect}function ee(a,e){let t=Ge[a]?.resolutions||[];if(!e)return t[0];let n=e.toLowerCase().replace(/\s+/g,"").replace("\xD7","x");return t.find(i=>i.key.toLowerCase()===n)}function te(a){if(!a)return null;let t=String(a).toLowerCase().trim().replace(/\s+/g,"").replace("\xD7","x").match(/^(\d+)x(\d+)$/);if(!t)return null;let n=parseInt(t[1],10),i=parseInt(t[2],10);return!Number.isFinite(n)||!Number.isFinite(i)?null:{width:n,height:i}}var ne=null,ie=class{constructor(e,t,n,i,o,r,s,l,u,m,p,h,Z){this.id=e;this.globals=t;this.stages=n;this.debug=i;this.time=o;this.input=r;this.aspectRatio=s;this.internalResolution=l;this.fullscreen=u;this.bodyBackground=m;this.container=p;this.containerId=h;this.canvas=Z}};function We(a={}){return a.deviceProfile==="mobile"?!0:a.deviceProfile==="desktop"?!1:a.viewportSize?T({viewportSize:a.viewportSize,allowViewportOnly:!0}):T()}function je(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 qe(a){let e=a?.id??"zylem";return{id:e,globals:a?.globals??{},stages:a?.stages??[],debug:!!a?.debug,time:a?.time??0,input:a?.input,aspectRatio:I.SixteenByNine,fullscreen:!0,bodyBackground:"#000000",containerId:e}}var Re=360;function Ee(a,e){if(!a)return;if(typeof a=="string"){if(a==="native")return ne;let i=te(a);if(i)return i;if(e){let o=ee(e,a);if(o)return{width:o.width,height:o.height}}return}let t=a.width,n=a.height;if(Number.isFinite(t)&&Number.isFinite(n))return{width:t,height:n}}function Qe(a,e,t,n){if(typeof a=="number")return a;if(typeof a=="string")return I[a]??t;if(e)try{return Q(e)||t}catch{return t}return n?n.width/n.height:t}function et(a){let e=Number.isFinite(a)&&a>0?a:I.SixteenByNine;if(e>=1){let i=Re;return{width:Math.round(i*e),height:i}}let t=Re,n=Math.round(t/e);return{width:t,height:n}}function P(a,e={}){let t=qe({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=je(n,a?.container??null),o=a?.mobile,r=We(e),s=r?o?.preset??a?.preset:a?.preset,l=Ee(a?.resolution,a?.preset),u=Ee(o?.resolution,o?.preset??a?.preset),m=(r?Te(u):void 0)??Te(l),p=r?o?.aspectRatio??a?.aspectRatio:a?.aspectRatio,h=Qe(p,s,t.aspectRatio,m),Z=tt(r,u,l,h),Pe=a?.fullscreen??t.fullscreen,Le=a?.bodyBackground??t.bodyBackground,ke=a?.canvas??void 0,De=nt(a?.input??t.input,o?.controls);return new ie(a?.id??t.id,a?.globals??t.globals,a?.stages??t.stages,!!(a?.debug??t.debug),a?.time??t.time,De,h,Z,Pe,Le,i,n,ke)}function Te(a){if(a)return a}function tt(a,e,t,n){if(a)return e===ne?void 0:e??et(n);if(t!==ne)return t}function nt(a,e){if(!e)return a;let n=ge("p1",{enabled:"auto",...e===!0?{}:e});return v(n,a??{})}function it(a){return{...a}}var O=class{id;container;canvas;bodyBackground;fullscreen;aspectRatio;ratioDelegate=null;overlayContainer=null;constructor(e){this.id=e.id,this.container=this.ensureContainer(e.containerId??e.id,e.container),this.canvas=e.canvas??document.createElement("canvas"),this.bodyBackground=e.bodyBackground,this.fullscreen=!!e.fullscreen,this.aspectRatio=(typeof e.aspectRatio=="number",e.aspectRatio)}applyBodyBackground(){this.bodyBackground&&(document.body.style.background=this.bodyBackground)}mountCanvas(){this.mountChildren(this.canvas)}mountRenderer(e,t){this.mountChildren(e),this.canvas=e,this.attachAspectRatio(t)}getOverlayContainer(){return this.ensureOverlayContainer()}centerIfFullscreen(){if(!this.fullscreen)return;let e=this.container.style;e.display="flex",e.alignItems="center",e.justifyContent="center",e.position="relative",e.inset="0"}attachAspectRatio(e){this.ratioDelegate?(this.ratioDelegate.canvas=this.canvas,this.ratioDelegate.onResize=e,this.ratioDelegate.aspectRatio=this.aspectRatio,this.ratioDelegate.apply()):(this.ratioDelegate=new H({container:this.container,canvas:this.canvas,aspectRatio:this.aspectRatio,onResize:e}),this.ratioDelegate.attach())}setAspectRatio(e){this.aspectRatio=e,this.ratioDelegate&&(this.ratioDelegate.aspectRatio=e,this.ratioDelegate.apply())}reapplyLayout(){this.ratioDelegate?.apply()}destroy(){this.ratioDelegate?.detach(),this.ratioDelegate=null}mountChildren(e){for(;this.container.firstChild;)this.container.removeChild(this.container.firstChild);this.container.appendChild(e),this.container.appendChild(this.ensureOverlayContainer())}ensureOverlayContainer(){if(this.overlayContainer)return this.overlayContainer;let e=document.createElement("div");return e.dataset.zylemOverlayRoot="true",e.style.position="absolute",e.style.inset="0",e.style.pointerEvents="none",e.style.touchAction="none",e.style.zIndex="10",this.overlayContainer=e,e}ensureContainer(e,t){if(t)return t;if(e){let o=document.getElementById(e);if(o)return o}let n=e||this.id||"zylem-root",i=document.createElement("main");return i.setAttribute("id",n),i.style.position="relative",i.style.width="100%",i.style.height="100%",document.body.appendChild(i),i}};import at from"stats.js";import{subscribe as ot}from"valtio/vanilla";var U=class{statsRef=null;unsubscribe=null;constructor(){this.updateDebugUI(),this.unsubscribe=ot(g,()=>{this.updateDebugUI()})}begin(){this.statsRef?.begin()}end(){this.statsRef?.end()}updateDebugUI(){g.enabled&&!this.statsRef?(this.statsRef=new at,this.statsRef.showPanel(0),this.statsRef.dom.style.position="absolute",this.statsRef.dom.style.bottom="0",this.statsRef.dom.style.right="0",this.statsRef.dom.style.top="auto",this.statsRef.dom.style.left="auto",document.body.appendChild(this.statsRef.dom)):!g.enabled&&this.statsRef&&(this.statsRef.dom.parentNode&&this.statsRef.dom.parentNode.removeChild(this.statsRef.dom),this.statsRef=null)}dispose(){this.unsubscribe&&(this.unsubscribe(),this.unsubscribe=null),this.statsRef?.dom?.parentNode&&this.statsRef.dom.parentNode.removeChild(this.statsRef.dom),this.statsRef=null}};var _=class{loadingHandlers=[];stageLoadingUnsubscribes=[];onLoading(e){return this.loadingHandlers.push(e),()=>{this.loadingHandlers=this.loadingHandlers.filter(t=>t!==e)}}emit(e){for(let n of this.loadingHandlers)try{n(e)}catch(i){console.error("Game loading handler failed",i)}let t=`loading:${e.type}`;b.emit(t,e)}wireStageLoading(e,t){let n=e.onLoading(i=>{this.emit({type:i.type,message:i.message??"",progress:i.progress??0,current:i.current,total:i.total,stageName:e.uuid??`Stage ${t}`,stageIndex:t})});typeof n=="function"&&this.stageLoadingUnsubscribes.push(n)}unwireAllStages(){for(let e of this.stageLoadingUnsubscribes)try{e()}catch{}this.stageLoadingUnsubscribes=[]}dispose(){this.unwireAllStages(),this.loadingHandlers=[]}};import{getZylemBridge as st}from"@zylem/bridge";var N=class{container=null;camera=null;rendererManager=null;gameCanvas=null;config=null;stage=null;mounted=!1;setGameCanvas(e){this.gameCanvas=e,this.tryMount()}setConfig(e){this.config=e,this.tryMount()}setContainer(e){this.container=e,this.tryMount()}setStage(e){this.stage=e,this.mounted&&this.gameCanvas?.reapplyLayout()}setCamera(e){this.camera=e,this.tryMount()}setRendererManager(e){this.rendererManager=e,this.tryMount()}tryMount(){this.mounted||!this.container||!this.gameCanvas||(this.rendererManager?this.mountWithRendererManager():this.camera&&this.mountWithCamera())}mountWithRendererManager(){if(!this.rendererManager||!this.gameCanvas)return;let e=this.rendererManager.getDomElement();this.gameCanvas.mountRenderer(e,(t,n)=>{if(!this.rendererManager)return;let i=this.config?.internalResolution;if(i)this.rendererManager.setPixelRatio(1),this.rendererManager.resize(i.width,i.height),this.stage?.resize(i.width,i.height);else{let o=window.devicePixelRatio||1;this.rendererManager.setPixelRatio(o),this.rendererManager.resize(t,n),this.stage?.resize(t,n)}}),this.mounted=!0}mountWithCamera(){if(!this.camera||!this.gameCanvas)return;let e=this.camera.getDomElement();this.gameCanvas.mountRenderer(e,(t,n)=>{if(!this.camera)return;let i=this.config?.internalResolution;if(i)this.camera.setPixelRatio(1),this.camera.resize(i.width,i.height);else{let o=window.devicePixelRatio||1;this.camera.setPixelRatio(o),this.camera.resize(t,n)}}),this.mounted=!0}reset(){this.camera=null,this.stage=null,this.mounted=!1}dispose(){this.container=null,this.camera=null,this.rendererManager=null,this.gameCanvas=null,this.config=null,this.stage=null,this.mounted=!1}};var F=class a{id;initialGlobals={};customSetup=null;customUpdate=null;customDestroy=null;stages=[];stageMap=new Map;currentStageId="";previousTimeStamp=0;totalTime=0;timer;inputManager;wrapperRef;globalInputConfig;defaultCamera=null;rendererManager=null;container=null;canvas=null;aspectRatioDelegate=null;resolvedConfig=null;gameCanvas=null;animationFrameId=null;isDisposed=!1;loadInFlight=!1;hasStarted=!1;debugDelegate=null;loadingDelegate=new _;rendererObserver=new N;eventBusUnsubscribes=[];thumbnailUnsubscribes=[];lastPublishedGameConfig=null;gameBridge=new be;gameUpdateParams={};stageSetupParams={};stageUpdateParams={};frameCallback=e=>this.loop(e);sourceOptions;displayRuntime;static FRAME_LIMIT=120;static FRAME_DURATION=1e3/a.FRAME_LIMIT;static MAX_DELTA_SECONDS=1/30;constructor(e,t,n={}){this.wrapperRef=t,this.timer=new V,this.timer.connect(document),this.sourceOptions={...e},this.displayRuntime={...n};let i=P(e,this.displayRuntime);this.globalInputConfig=i.input,this.id=i.id,this.stages=i.stages||[],this.container=i.container,this.canvas=i.canvas??null,this.resolvedConfig=i,this.loadGameCanvas(i),this.container=this.gameCanvas?.container??this.container,this.inputManager=new A(i.input,{targetElement:this.gameCanvas?.getOverlayContainer(),mouseTargetElement:this.gameCanvas?.container}),this.loadDebugOptions(e),this.setGlobals(e),this.gameBridge.connect({resolveEntity:o=>this.currentStage()?.wrappedStage?.entityDelegate.childrenMap.get(o)??null,setStageVariable:(o,r)=>{let s=this.currentStage()?.wrappedStage?.state;s&&(s.variables[o]=r)}})}setDisplayRuntime(e){this.displayRuntime={...e};let t=P(this.sourceOptions,this.displayRuntime);this.resolvedConfig=t,this.rendererObserver.setConfig(t),this.gameCanvas?.setAspectRatio(t.aspectRatio),this.publishGameConfig()}loadGameCanvas(e){this.gameCanvas=new O({id:e.id,container:e.container,containerId:e.containerId,canvas:this.canvas??void 0,bodyBackground:e.bodyBackground,fullscreen:e.fullscreen,aspectRatio:e.aspectRatio}),this.gameCanvas.applyBodyBackground(),this.gameCanvas.mountCanvas(),this.gameCanvas.centerIfFullscreen(),this.rendererObserver.setGameCanvas(this.gameCanvas),this.resolvedConfig&&this.rendererObserver.setConfig(this.resolvedConfig),this.container&&this.rendererObserver.setContainer(this.container),this.subscribeToEventBus()}loadDebugOptions(e){e.debug!==void 0&&(g.enabled=!!e.debug),this.debugDelegate=new U}isLoading(){return this.loadInFlight}async loadStage(e,t=0,n){if(this.loadInFlight){console.warn("loadStage ignored: a stage load is already in progress");return}this.loadInFlight=!0;try{await this.performLoadStage(e,t,n)}finally{this.loadInFlight=!1}}async performLoadStage(e,t=0,n){let i=n?ve(n):null,o=this.currentStage()??null,r=o?.wrappedStage??null,s=r?.scene?.scene??null,l=r?.cameraManagerRef?.primaryCamera?.camera??r?.cameraRef?.camera??null;i&&this.rendererManager?.initialized&&o&&s&&l&&this.rendererManager.beginSnapshotTransition(i,s,l),this.unloadCurrentStage();let m=e.options[0];if(this.loadingDelegate.wireStageLoading(e,t),this.rendererManager||(this.rendererManager=new he,await this.rendererManager.initRenderer()),y.setRenderer(this.rendererManager.renderer),await e.load(this.id,m?.camera,this.rendererManager),this.stageMap.set(e.wrappedStage.uuid,e),this.currentStageId=e.wrappedStage.uuid,this.defaultCamera=e.wrappedStage.cameraRef,this.wireEntityThumbnails(e),this.rendererObserver.setStage(e.wrappedStage??null),this.rendererManager&&this.rendererObserver.setRendererManager(this.rendererManager),this.applyInputConfig(e),e.onInputConfigChanged=()=>this.applyInputConfig(e),this.hasStarted&&e.wrappedStage&&!e.wrappedStage.hasSetup){let p=this.params(),h={...this.stageSetupParams};h.inputs=p.inputs,h.globals=p.globals,h.camera=p.camera,h.stage=p.stage,h.game=p.game,h.me=e.wrappedStage,e.start(h)}this.publishGameConfig(),this.publishStageSnapshot()}applyInputConfig(e){let t=v(this.globalInputConfig??{},e.inputConfig??{});this.inputManager.configure(t)}setGlobalInputConfig(e){this.globalInputConfig=e;let t=this.currentStage();t&&this.applyInputConfig(t)}unloadCurrentStage(){if(!this.currentStageId)return;let e=this.getStage(this.currentStageId);if(e){if(this.clearEntityThumbnailWiring(),y.clear(),e.onInputConfigChanged=null,e?.wrappedStage){try{e.wrappedStage.nodeDestroy({me:e.wrappedStage,globals:C.globals})}catch(t){console.error("Failed to destroy previous stage",t)}e.wrappedStage=null}e.dispose(),this.stageMap.delete(this.currentStageId),this.currentStageId="",this.defaultCamera=null,this.rendererObserver.reset()}}setGlobals(e){this.initialGlobals={...e.globals};for(let t in this.initialGlobals){let n=this.initialGlobals[t];n===void 0&&console.error(`global ${t} is undefined`),le(t,n)}}params(){let e=this.currentStage(),t=this.timer.getDelta(),n=this.inputManager.getInputs(t),i=e?.wrappedStage?.cameraRef||this.defaultCamera,o=this.gameUpdateParams;return o.delta=t,o.inputs=n,o.globals=de(),o.me=this,o.camera=i,o.stage=e,o.game=this.wrapperRef,o}start(){let e=this.currentStage(),t=this.params(),n=this.stageSetupParams;n.inputs=t.inputs,n.globals=t.globals,n.camera=t.camera,n.stage=t.stage,n.game=t.game,n.me=e.wrappedStage,e.start(n),this.customSetup&&this.customSetup(t),this.hasStarted=!0,this.loop(0)}step(e){let t=this.currentStage();if(!t||!t.wrappedStage)return;let n=this.params(),i=e!==void 0?e:n.delta,o=Math.min(Math.max(i,0),a.MAX_DELTA_SECONDS);n.delta=o,this.customUpdate&&this.customUpdate(n);let r=this.currentStage();if(r!==t||!r?.wrappedStage){this.totalTime+=o,C.time=this.totalTime;return}let s=this.stageUpdateParams;s.delta=n.delta,s.inputs=n.inputs,s.globals=n.globals,s.camera=n.camera,s.stage=n.stage,s.game=n.game,s.me=t.wrappedStage,t.wrappedStage?.nodeUpdate(s),this.totalTime+=o,C.time=this.totalTime}loop(e){this.debugDelegate?.begin(),me()||(this.timer.update(e),this.step(),this.previousTimeStamp=e),this.debugDelegate?.end(),this.outOfLoop(),this.isDisposed||(this.animationFrameId=requestAnimationFrame(this.frameCallback))}dispose(){this.isDisposed=!0,this.gameBridge.disconnect(),this.animationFrameId!==null&&(cancelAnimationFrame(this.animationFrameId),this.animationFrameId=null),this.unloadCurrentStage(),this.debugDelegate&&(this.debugDelegate.dispose(),this.debugDelegate=null),this.eventBusUnsubscribes.forEach(e=>e()),this.eventBusUnsubscribes=[],this.rendererObserver.dispose(),this.inputManager.dispose(),this.rendererManager&&(y.setRenderer(null),this.rendererManager.dispose(),this.rendererManager=null),y.clear(),st().channel.reset(),this.timer.dispose(),this.customDestroy&&this.customDestroy({me:this,globals:C.globals}),x()}outOfLoop(){let e=this.currentStage();e&&e.wrappedStage.outOfLoop()}getStage(e){return this.stageMap.get(e)}currentStage(){return this.getStage(this.currentStageId)}onLoading(e){return this.loadingDelegate.onLoading(e)}buildStageConfigPayload(){let e=this.currentStage();if(!e?.wrappedStage)return null;let t=e.wrappedStage.state,n=t.backgroundColor,i=typeof n=="string"?n:`#${n.getHexString()}`;return{id:e.wrappedStage.uuid,backgroundColor:i,backgroundImage:t.backgroundImage,gravity:{x:t.gravity.x,y:t.gravity.y,z:t.gravity.z},inputs:t.inputs,variables:t.variables}}buildEntitySummary(e){if(G(e.options))return null;let t=e.constructor.type,n=t?String(t).replace("Symbol(","").replace(")",""):"Unknown",i=e.position??{x:0,y:0,z:0},o=e.rotation??{x:0,y:0,z:0},r=ye(e),s=y.get(e.uuid);return{uuid:e.uuid,name:e.name||"Unnamed",type:n,position:{x:i.x??0,y:i.y??0,z:i.z??0},rotation:{x:o.x??0,y:o.y??0,z:o.z??0},scale:r,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=r=>{if(!this.gameBridge.wantsThumbnails()||G(r.options))return;let s=r.group??r.mesh??null;s&&y.ensure(r.uuid,s).then(l=>{l&&!this.isDisposed&&this.gameBridge.queueThumbnails([{uuid:r.uuid,url:l.dataUrl,bounds:l.bounds}])})},n=e.wrappedStage.onEntityAdded(r=>{if(this.gameBridge.wantsEntityUpdates()){let s=this.buildEntitySummary(r);s&&this.gameBridge.queueEntityUpsert([s])}t(r)},{replayExisting:!0});this.thumbnailUnsubscribes.push(n);let i=r=>{if(!r.success)return;let s=e.wrappedStage?.entityDelegate.childrenMap.get(r.entityId);s&&(y.invalidate(r.entityId),t(s))};b.on("entity:model:loaded",i),this.thumbnailUnsubscribes.push(()=>{b.off("entity:model:loaded",i)});let o=r=>{y.invalidate(r.entityId),this.gameBridge.wantsEntityUpdates()&&this.gameBridge.queueEntityRemoved([r.entityId])};b.on("entity:destroyed",o),this.thumbnailUnsubscribes.push(()=>{b.off("entity:destroyed",o)}),this.wireEditorBackfill(e)}wireEditorBackfill(e){let t=this.gameBridge.onEditorAttached(()=>{if(!(this.isDisposed||this.currentStage()!==e)){this.lastPublishedGameConfig=null,this.publishGameConfig(),this.publishStageSnapshot();for(let n of e.wrappedStage?.entityDelegate.childrenMap.values()??[]){let i=n;if(G(i.options))continue;let o=i.group??i.mesh??null;o&&y.ensure(i.uuid,o).then(r=>{r&&!this.isDisposed&&this.gameBridge.queueThumbnails([{uuid:i.uuid,url:r.dataUrl,bounds:r.bounds}])})}}});this.thumbnailUnsubscribes.push(t)}clearEntityThumbnailWiring(){this.thumbnailUnsubscribes.forEach(e=>{try{e()}catch{}}),this.thumbnailUnsubscribes=[]}buildGameConfigPayload(){return this.resolvedConfig?{id:this.resolvedConfig.id,aspectRatio:this.resolvedConfig.aspectRatio,fullscreen:this.resolvedConfig.fullscreen,bodyBackground:this.resolvedConfig.bodyBackground,internalResolution:this.resolvedConfig.internalResolution,debug:this.resolvedConfig.debug}:null}publishGameConfig(){let e=this.buildGameConfigPayload();if(!e)return;let t=JSON.stringify(e);t!==this.lastPublishedGameConfig&&(this.lastPublishedGameConfig=t,this.gameBridge.publishConfig(e))}publishStageSnapshot(){this.gameBridge.publishStageSnapshot({stage:this.buildStageConfigPayload(),entities:this.buildEntitiesPayload()})}subscribeToEventBus(){this.eventBusUnsubscribes.push(re.on("game:state:updated",e=>{this.gameBridge.publishVariable({path:e.path,value:e.value,previousValue:e.previousValue})}))}};async function Be(a){let{getGameDefaultConfig:e}=await import("./game-default-4PPYYGAR.js"),t={...e()},n=[],i=[],o=[];Object.values(a).forEach(s=>{if(s instanceof L)i.push(s);else if(s instanceof j)o.push(s);else if(s instanceof $)o.push(s);else if(s?.constructor?.name==="Object"&&typeof s=="object"){let l=Object.assign({...e()},{...s});n.push(l)}}),n.forEach(s=>{t=Object.assign(t,{...s})});let r=t;return r.input=n[0].input,i.forEach(s=>{s.addEntities(o)}),i.length?r.stages=i:r.stages[0].addEntities(o),r}function Me(a){return!!a.find(t=>t instanceof L)}function ae(a){for(let e of a)if(e&&typeof e=="object"&&!(e instanceof L)&&!(e instanceof $)&&!(e instanceof j)){let t=e;if(t.globals)return t.globals}}import{proxy as rt}from"valtio/vanilla";import{get as lt,set as ut}from"idb-keyval";import{pack as pt,unpack as dt}from"msgpackr";var c=rt({previous:null,current:null,next:null,isLoading:!1}),X={staticRegistry:new Map,registerStaticStage(a,e){this.staticRegistry.set(a,e)},async loadStageData(a){try{let e=await lt(a);if(e)return dt(e)}catch(e){console.warn(`Failed to load stage ${a} from storage`,e)}if(this.staticRegistry.has(a))return this.staticRegistry.get(a);throw new Error(`Stage ${a} not found in storage and static loading not fully implemented.`)},async transitionForward(a,e){if(!c.isLoading){c.isLoading=!0;try{c.current&&await ut(c.current.id,pt(c.current)),c.previous=c.current,c.current=c.next,c.current?.id!==a&&(e?c.current=await e(a):c.current=await this.loadStageData(a)),c.next=null}catch(t){console.error("Failed to transition stage:",t)}finally{c.isLoading=!1}}},async preloadNext(a,e){e?c.next=await e(a):c.next=await this.loadStageData(a)}};var oe={async createFromBlueprint(a){let e=R({});if(a.entities)for(let t of a.entities)try{let n=await Ce.createFromBlueprint(t);e.add(n)}catch(n){console.error(`Failed to create entity ${t.id} for stage ${a.id}`,n)}return e}};var Y=class{wrappedGame=null;options;setupCallbacks=[];updateCallbacks=[];destroyCallbacks=[];pendingLoadingCallbacks=[];globalChangeCallbacks=[];globalChangesCallbacks=[];activeGlobalSubscriptions=[];eventDelegate=new fe;pendingInputConfig=null;displayRuntime={};refErrorMessage="lost reference to game";constructor(e){this.options=e,Me(e)||this.options.push(R());let t=ae(e);t&&J(t)}onSetup(...e){return this.setupCallbacks.push(...e),this}onUpdate(...e){return this.updateCallbacks.push(...e),this}onDestroy(...e){return this.destroyCallbacks.push(...e),this}setInputConfiguration(...e){let t=v(...e);return this.pendingInputConfig=t,this.wrappedGame&&this.wrappedGame.setGlobalInputConfig(t),this}async start(){x();let e=ae(this.options);e&&J(e);let t=await this.load();return this.wrappedGame=t,this.setOverrides(),this.registerGlobalSubscriptions(),t.start(),this}setDisplayRuntime(e){return this.displayRuntime={...this.displayRuntime,...e},this.wrappedGame&&this.wrappedGame.setDisplayRuntime(this.displayRuntime),this}setDeviceProfile(e){return this.setDisplayRuntime({deviceProfile:e})}setViewportSize(e,t){return this.setDisplayRuntime({viewportSize:{width:e,height:t}})}async load(){let e=await Be(this.options),t=P(e,this.displayRuntime);this.pendingInputConfig&&(t.input=v(t.input??{},this.pendingInputConfig));let n=new F({...e,...t},this,this.displayRuntime);for(let i of this.pendingLoadingCallbacks)n.onLoading(i);return await n.loadStage(e.stages[0]),n}setOverrides(){if(!this.wrappedGame){console.error(this.refErrorMessage);return}this.wrappedGame.customSetup=e=>{this.setupCallbacks.forEach(t=>t(e))},this.wrappedGame.customUpdate=e=>{this.updateCallbacks.forEach(t=>t(e))},this.wrappedGame.customDestroy=e=>{this.destroyCallbacks.forEach(t=>t(e))}}onGlobalChange(e,t){return this.globalChangeCallbacks.push({path:e,callback:t}),this}onGlobalChanges(e,t){return this.globalChangesCallbacks.push({paths:e,callback:t}),this}registerGlobalSubscriptions(){for(let{path:e,callback:t}of this.globalChangeCallbacks){let n=ue(e,i=>{t(i,this.getCurrentStage())});this.activeGlobalSubscriptions.push(n)}for(let{paths:e,callback:t}of this.globalChangesCallbacks){let n=pe(e,i=>{t(i,this.getCurrentStage())});this.activeGlobalSubscriptions.push(n)}}getCurrentStage(){return this.wrappedGame?.currentStage()??null}experimental={getRuntime:()=>this.getCurrentStage()?.wrappedStage?.world?.simulation??null};async pause(){K(!0)}async resume(){K(!1),this.wrappedGame&&(this.wrappedGame.previousTimeStamp=0,this.wrappedGame.timer.reset())}step(e=1/60){if(!this.wrappedGame){console.error(this.refErrorMessage);return}this.wrappedGame.step(e)}async reset(e){if(!this.wrappedGame){console.error(this.refErrorMessage);return}this.wrappedGame.isLoading()||await this.wrappedGame.loadStage(this.wrappedGame.stages[0],0,e?.transition)}previousStage(e){if(!this.wrappedGame){console.error(this.refErrorMessage);return}if(this.wrappedGame.isLoading())return;let t=this.wrappedGame.currentStageId,n=this.wrappedGame.stages.findIndex(o=>o.wrappedStage?.uuid===t),i=this.wrappedGame.stages[n-1];if(!i){console.error("previous stage called on first stage");return}this.wrappedGame.loadStage(i,n-1,e?.transition)}async loadStageFromId(e){if(!this.wrappedGame){console.error(this.refErrorMessage);return}try{let t=await X.loadStageData(e),n=await oe.createFromBlueprint(t);await this.wrappedGame.loadStage(n),c.current=t}catch(t){console.error(`Failed to load stage ${e}`,t)}}nextStage(e){if(!this.wrappedGame){console.error(this.refErrorMessage);return}if(this.wrappedGame.isLoading())return;if(c.next){console.log("next stage called");let o=c.next.id;if(X.transitionForward(o),c.current){oe.createFromBlueprint(c.current).then(r=>{this.wrappedGame?.loadStage(r,0,e?.transition)});return}}let t=this.wrappedGame.currentStageId,n=this.wrappedGame.stages.findIndex(o=>o.wrappedStage?.uuid===t),i=this.wrappedGame.stages[n+1];if(!i){console.error("next stage called on last stage");return}this.wrappedGame.loadStage(i,n+1,e?.transition)}async goToStage(){}async end(){}dispose(){this.eventDelegate.dispose();for(let e of this.activeGlobalSubscriptions)e();this.activeGlobalSubscriptions=[],this.wrappedGame&&(this.wrappedGame.dispose(),this.wrappedGame=null),ce(),x(),Se.clearSharedMaterialCache()}dispatch(e,t){this.eventDelegate.dispatch(e,t),b.emit(e,t)}listen(e,t){return this.eventDelegate.listen(e,t)}onLoading(e){return this.wrappedGame?this.wrappedGame.onLoading(e):(this.pendingLoadingCallbacks.push(e),()=>{this.pendingLoadingCallbacks=this.pendingLoadingCallbacks.filter(t=>t!==e),this.wrappedGame})}};function ct(...a){return new Y(a)}import{Euler as mt,Quaternion as ht,Vector2 as gt}from"three";function ft(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 gt(0,1))=>{if(!e.body){console.warn("body missing for entity during spawnRelative");return}let{x:i,y:o,z:r}=e.body.translation(),s=e._rotation2DAngle??0;try{let p=e.body.rotation(),h=new ht(p.x,p.y,p.z,p.w);s=new mt().setFromQuaternion(h,"XYZ").z}catch{}let l=Math.sin(-s)*(n.x??0),u=Math.cos(-s)*(n.y??0),m=await Promise.resolve(a(i+l,o+u));return t.add(m),m}}}import{subscribe as yt}from"valtio/vanilla";var se="STAGE_STATE_CHANGE";function bt(){return yt(S,()=>{let a={entities:S.entities,variables:S.variables};window.dispatchEvent(new CustomEvent(se,{detail:a}))})}function vt(){let a={entities:S.entities,variables:S.variables};window.dispatchEvent(new CustomEvent(se,{detail:a}))}import{MathUtils as St,Vector3 as wt}from"three";var Ie={targetKey:"primary",offset:new wt(0,0,0),lerpFactor:.1};function Ct(a){let e={...Ie,...a,offset:W(a?.offset,Ie.offset)},t=null;return{priority:0,enabled:!0,onAttach(){t=null},update(n,i){let o=n.targets[e.targetKey];if(!o)return i;let r=o.position.clone().add(e.offset),s=we(i);if(!t)t=r.clone();else{let l=St.clamp(e.lerpFactor,0,1),u=1-Math.pow(1-l,n.dt*60);t.lerp(r,u)}return s.position.copy(t),s.lookAt=o.position.clone(),s},onDetach(){t=null}}}import{MeshBasicMaterial as xt}from"three";function Gt(a,e,t){let n=e.cameraRef;if(!n.renderTarget){let r=t?.width??512,s=t?.height??512;n.createRenderTarget(r,s)}let i=n.getRenderTexture();if(!i){console.warn("setCameraFeed: Failed to obtain render texture from camera.");return}if(!a.mesh){console.warn("setCameraFeed: Entity has no mesh to apply the camera feed to.");return}let o=new xt({map:i});a.mesh.material=o}export{I as a,Q as b,ee as c,te as d,it as e,c as f,X as g,Y as h,ct as i,ft as j,se as k,bt as l,vt as m,Ct as n,Gt as o};
@@ -0,0 +1 @@
1
+ import{a as n}from"./chunk-QXVH6POE.js";var s=class{emitter;unsubscribes=[];constructor(){this.emitter=n()}dispatch(e,t){this.emitter.emit(e,t)}listen(e,t){this.emitter.on(e,t);let i=()=>this.emitter.off(e,t);return this.unsubscribes.push(i),i}listenAll(e){this.emitter.on("*",e);let t=()=>this.emitter.off("*",e);return this.unsubscribes.push(t),t}dispose(){this.unsubscribes.forEach(e=>e()),this.unsubscribes=[],this.emitter.all.clear()}};var o=n();export{s as a,o as b};
@@ -0,0 +1 @@
1
+ import{Box3 as d,PerspectiveCamera as h,Vector3 as a}from"three";var m=new d,s=new a,x=new a,p=new a;function u(c){m.setFromObject(c),m.getSize(s),m.getCenter(x);let t=Math.max(s.x,1e-4),o=Math.max(s.y,1e-4),n=Math.max(s.z,1e-4),e=Math.max(t,o,n);return{width:t,height:o,depth:n,center:x.clone(),maxDim:e}}function b(c,t,o=1.35){let n=t.fov*(Math.PI/180),e=c/(2*Math.tan(n/2))*o;return Math.max(e,.5)}function j(c,t,o=1.35){let n=u(c),e=b(n.maxDim,t,o);return t.position.copy(n.center).add(new a(e,e,e)),t.lookAt(n.center),t.near=Math.max(e/100,.01),t.far=Math.max(e*20,100),t.updateProjectionMatrix(),n}function M(c,t,o,n=1.5){let e=u(c),r=p.copy(o);r.lengthSq()<1e-8&&r.set(1,1,1),r.normalize();let i=e.maxDim*n;return t instanceof h&&(i=b(e.maxDim,t,n),t.near=Math.max(i/100,.01),t.far=Math.max(i*20,100),t.updateProjectionMatrix()),t.position.copy(e.center).addScaledVector(r,i),t.lookAt(e.center),e}export{j as a,M as b};
@@ -0,0 +1 @@
1
+ import{b as c}from"./chunk-LKFF6XJC.js";import{a as n,e as u,g as l,i as h}from"./chunk-W5SXED5T.js";import{subscribe as p}from"valtio/vanilla";import{announceBridgeReady as m,getZylemBridge as y}from"@zylem/bridge";function g(i){return(i?.group??i?.mesh)?.scale}function w(i){let e=i?.scale??g(i)??{};return{x:e.x??1,y:e.y??1,z:e.z??1}}function f(i,e){if(typeof i?.setScale=="function"){i.setScale(e.x,e.y,e.z);return}g(i)?.set?.(e.x,e.y,e.z)}function G(i,e){y().channel.send("game:notice",{level:i,message:e})}var b=class{channel;unsubscribes=[];host=null;editorKnown={};constructor(){this.channel=y().channel}connect(e,s){this.disconnect(),this.host=e,this.unsubscribes.push(this.channel.on("debug:set",({enabled:t})=>{this.editorKnown.debug=t,n.enabled=t}),this.channel.on("tool:set",({tool:t})=>{l(t)}),this.channel.on("playback:set",({paused:t})=>{this.editorKnown.paused=t,u(t)}),this.channel.on("entity:select",({uuid:t})=>{this.editorKnown.selectedUuid=t,h(t)}),this.channel.on("entity:focus",({uuid:t})=>{c(t)}),this.channel.on("entity:transform",({uuid:t,position:o,rotation:d,scale:r})=>{let a=this.host?.resolveEntity(t);a&&(o&&typeof a.setPosition=="function"&&a.setPosition(o.x,o.y,o.z),d&&(a.setRotationX?.(d.x),a.setRotationY?.(d.y),a.setRotationZ?.(d.z)),r&&f(a,r))}),this.channel.on("stage:variable:set",({key:t,value:o})=>{this.host?.setStageVariable?.(t,o)}),p(n,()=>this.publishDebugStateChanges())),this.publishDebugStateChanges(),m(s)}disconnect(){for(let e of this.unsubscribes)e();this.unsubscribes=[],this.host=null,this.editorKnown={}}publishDebugStateChanges(){let e={};n.paused!==this.editorKnown.paused&&(this.editorKnown.paused=n.paused,e.paused=n.paused),n.enabled!==this.editorKnown.debug&&(this.editorKnown.debug=n.enabled,e.debug=n.enabled),(e.paused!==void 0||e.debug!==void 0)&&this.publishStatus(e),(n.selectedEntityId!==this.editorKnown.selectedUuid||n.hoveredEntityId!==this.editorKnown.hoveredUuid)&&(this.editorKnown.selectedUuid=n.selectedEntityId,this.editorKnown.hoveredUuid=n.hoveredEntityId,this.channel.queue("entity:selection",{selectedUuid:n.selectedEntityId,hoveredUuid:n.hoveredEntityId}))}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(s=>{if(s!=="entity:upsert"&&s!=="entity:thumbnail")return;let t=s==="entity:upsert"?"entity:thumbnail":"entity:upsert";this.channel.subscriberCount(t)>0||e()})}publishConfig(e){this.channel.send("game:config",e)}publishLoading(e){this.channel.send("game:loading",e)}publishStatus(e){this.channel.queue("game:status",e)}publishVariable(e){this.channel.send("game:variable",e)}publishNotice(e,s){this.channel.send("game:notice",{level:e,message:s})}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)}};export{w as a,G as b,b as c};
@@ -0,0 +1 @@
1
+ import{getZylemBridge as d,announceBridgeReady as o,BRIDGE_READY_EVENT as g}from"@zylem/bridge";export{d as a,o as b,g as c};
@@ -0,0 +1 @@
1
+ import{a as o,i}from"./chunk-W5SXED5T.js";var e=null;function a(t){return e=t,()=>{e===t&&(e=null)}}function u(t){if(!e)return console.warn("focusEntity: no active stage focus context"),!1;let n=e.resolveEntity(t);if(!n)return console.warn(`focusEntity: entity ${t} not found`),!1;let r=n.group??n.mesh??null;return r?(o.enabled||(o.enabled=!0),e.ensureDebugReady?.(),i(t),e.frameObject(r),!0):(console.warn(`focusEntity: entity ${t} has no group/mesh`),!1)}export{a,u as b};
@@ -1 +1 @@
1
- import{a as P}from"./chunk-MZZCDXFB.js";import{a as Dt,b as Z,c as Y,d as N,e as W,f as X,g as U,h as j,j as q,p as m,q as w,r as c,t as x,u as R,v as $,w as K,x as D}from"./chunk-KVSJE4XD.js";import{j as kt}from"./chunk-CM5YRNBJ.js";import{d as V,j as Rt}from"./chunk-4QLJUQSJ.js";import{a as It,b as gt,c as zt,d as Lt,g as Bt,h as xt,i as E,j as Ht}from"./chunk-7WRQ2UAN.js";import{Vector3 as Fe}from"three";import{BoxGeometry as ze,CapsuleGeometry as Le,ConeGeometry as Ft,CylinderGeometry as Be,Mesh as I,MeshStandardMaterial as He,SphereGeometry as ke}from"three";function z(i,t=Symbol("mesh")){if(i.material||i.color){let e=new kt;if(e.build({...i.material,color:i.color??i.material?.color},t),e.materials.length>0)return e.materials}return[new He]}function L(i,t){if(t.position){let e=xt(t.position,zt);i.position.set(e.x,e.y,e.z)}return i.castShadow=!0,i.receiveShadow=!0,i}function Q(i={}){let t=xt(i.size,Lt),e=new ze(t.x,t.y,t.z),o=z(i);return L(new I(e,o.at(-1)),i)}function J(i={}){let t=new ke(i.radius??1),e=z(i);return L(new I(t,e.at(-1)),i)}function tt(i={}){let t=new Ft(i.radius??1,i.height??2,i.radialSegments??32),e=z(i);return L(new I(t,e.at(-1)),i)}function et(i={}){let t=new Ft(i.radius??1,i.height??2,4),e=z(i);return L(new I(t,e.at(-1)),i)}function it(i={}){let t=new Be(i.radiusTop??1,i.radiusBottom??1,i.height??2,i.radialSegments??32),e=z(i);return L(new I(t,e.at(-1)),i)}function ot(i={}){let t=new Le(i.radius??.5,i.length??1,i.capSegments??10,i.radialSegments??20),e=z(i);return L(new I(t,e.at(-1)),i)}var Gt={...m,size:new Fe(1,1,1)},At=Symbol("Box"),nt=class i extends c{static type=At;constructor(t){super(),this.options={...Gt,...t}}buildInfo(){let e=new P(this).buildDebugInfo(),{x:o,y:n,z:s}=this.options.size??{x:1,y:1,z:1};return{...e,type:String(i.type),size:`${o}, ${n}, ${s}`}}};function Vt(...i){let t=w(i,Gt),e=new nt(t);return e.add(Q({size:t.size,material:t.material,color:t.color}),Y({size:t.size,static:t.collision?.static,sensor:t.collision?.sensor,canSleep:t.collision?.canSleep,ccdEnabled:t.collision?.ccdEnabled,gravityScale:t.collision?.gravityScale,lockRotations:t.collision?.lockRotations,lockTranslations:t.collision?.lockTranslations,collisionType:t.collisionType,collisionFilter:t.collisionFilter})),x(e,o=>Vt(o??{}))}var Yt={...m,radius:1},Nt=Symbol("Sphere"),st=class i extends c{static type=Nt;constructor(t){super(),this.options={...Yt,...t}}buildInfo(){let e=new P(this).buildDebugInfo(),o=this.options.radius??1;return{...e,type:String(i.type),radius:o.toFixed(2)}}};function Wt(...i){let t=w(i,Yt),e=new st(t);return e.add(J({radius:t.radius,material:t.material,color:t.color}),N({radius:t.radius,static:t.collision?.static,sensor:t.collision?.sensor,gravityScale:t.collision?.gravityScale,lockRotations:t.collision?.lockRotations,lockTranslations:t.collision?.lockTranslations,collisionType:t.collisionType,collisionFilter:t.collisionFilter})),x(e,o=>Wt(o??{}))}import{PlaneGeometry as Ae,Vector2 as Xt,Vector3 as Ut}from"three";import{BufferGeometry as Ge,Float32BufferAttribute as bt}from"three";var rt=class i extends Ge{constructor(t=1,e=1,o=1,n=1){super(),this.type="XZPlaneGeometry",this.parameters={width:t,height:e,widthSegments:o,heightSegments:n};let s=t/2,a=e/2,r=Math.floor(o),l=Math.floor(n),p=r+1,O=l+1,u=t/r,d=e/l,b=[],f=[],y=[],_=[];for(let g=0;g<O;g++){let h=g*d-a;for(let C=0;C<p;C++){let T=C*u-s;f.push(T,0,h),y.push(0,1,0),_.push(C/r),_.push(1-g/l)}}for(let g=0;g<l;g++)for(let h=0;h<r;h++){let C=h+p*g,T=h+p*(g+1),S=h+1+p*(g+1),v=h+1+p*g;b.push(C,T,v),b.push(T,S,v)}this.setIndex(b),this.setAttribute("position",new bt(f,3)),this.setAttribute("normal",new bt(y,3)),this.setAttribute("uv",new bt(_,2))}copy(t){return super.copy(t),this.parameters=Object.assign({},t.parameters),this}static fromJSON(t){return new i(t.width,t.height,t.widthSegments,t.heightSegments)}};var at=4,jt={...m,tile:new Xt(10,10),repeat:new Xt(1,1),collision:{static:!0},subdivisions:at,randomizeHeight:!1,heightScale:1};function qt(i){let t=i.subdivisions??at,e=i.heightMap2D,o=i.heightMap,n=i.subdivisionsX??t,s=i.subdivisionsZ??t;return e&&e.length>0&&e[0]?.length>0?(s=e.length-1,n=e[0].length-1):o&&o.length>0&&(n=o.length-1),{subdivisionsX:n,subdivisionsZ:s}}var Ot=class extends ${collider(t){let e=E(t.tile,gt),{subdivisionsX:o,subdivisionsZ:n}=qt(t),s=new Ut(e.x,1,e.y),a=t._builders?.meshBuilder?.heightData??new Float32Array((o+1)*(n+1));return{shape:{type:"heightfield",rows:o,cols:n,heights:a,scale:[s.x,1,s.z]}}}},Pt=class extends K{heightData=new Float32Array;columnsRows=new Map;subdivisionsX=at;subdivisionsZ=at;build(t){let e=E(t.tile,gt),{subdivisionsX:o,subdivisionsZ:n}=qt(t);this.subdivisionsX=o,this.subdivisionsZ=n;let s=new Ut(e.x,1,e.y),a=t.heightScale??1,r=new rt(s.x,s.z,o,n),l=new Ae(s.x,s.z,o,n),p=o>0?s.x/o:1,O=n>0?s.z/n:1,u=r.attributes.position.array,d=l.attributes.position.array,b=new Map,f=t.heightMap2D,y=t.heightMap,_=t.randomizeHeight??!1,g=(h,C)=>h<0?0:h>C?C:h;for(let h=0;h<d.length;h+=3){let C=d[h],T=d[h+1],S=g(Math.round((C+s.x/2)/p),o),v=g(Math.round((s.z/2-T)/O),n),M=0;if(f){let Mt=f[v];Mt&&(M=Mt[S]??0)}else y&&y.length>0?M=y[S]??0:_&&(M=Math.random()*4);let G=M*a;d[h+2]=G,u[h+1]=G,b.get(v)||b.set(v,new Map),b.get(v).set(S,G)}return this.columnsRows=b,r}postBuild(){let t=[];for(let e=0;e<=this.subdivisionsX;++e)for(let o=0;o<=this.subdivisionsZ;++o){let n=this.columnsRows.get(o);t.push(n?.get(e)??0)}this.heightData=new Float32Array(t)}},St=class extends D{createEntity(t){return new B(t)}},$t=Symbol("Plane"),B=class extends c{static type=$t;constructor(t){super(),this.options=Z(jt,t)}};function Kt(...i){return R({args:i,defaultConfig:jt,EntityClass:B,BuilderClass:St,MeshBuilderClass:Pt,CollisionBuilderClass:Ot,entityType:B.type,cloneFactory:t=>Kt(t??{})})}import{Vector3 as Ve}from"three";var Qt={...m,size:new Ve(1,1,1),collision:{static:!0}},Jt=Symbol("Zone"),lt=class extends c{static type=Jt;_enteredZone=new Map;_exitedZone=new Map;_zoneEntities=new Map;constructor(t){super(),this.options=Z(Qt,t)}handlePostCollision({delta:t}){return this._enteredZone.forEach((e,o)=>{this.exited(t,o)}),this._enteredZone.size>0}handleIntersectionEvent({other:t,delta:e}){this._enteredZone.get(t.uuid)?this.held(e,t):(this.entered(t),this._zoneEntities.set(t.uuid,t))}onEnter(t){return this.options.onEnter=t,this}onHeld(t){return this.options.onHeld=t,this}onExit(t){return this.options.onExit=t,this}entered(t){this._enteredZone.set(t.uuid,1),this.options.onEnter&&this.options.onEnter({self:this,visitor:t,globals:V.globals})}exited(t,e){let o=this._exitedZone.get(e);if(o&&o>1+t){this._exitedZone.delete(e),this._enteredZone.delete(e);let n=this._zoneEntities.get(e);this.options.onExit&&this.options.onExit({self:this,visitor:n,globals:V.globals});return}this._exitedZone.set(e,1+t)}held(t,e){let o=this._enteredZone.get(e.uuid)??0;this._enteredZone.set(e.uuid,o+t),this._exitedZone.set(e.uuid,1),this.options.onHeld&&this.options.onHeld({delta:t,self:this,visitor:e,globals:V.globals,heldTime:o})}};function te(...i){let t=w(i,Qt),e=new lt(t);return e.add(q({size:t.size,static:t.collision?.static??!0,collisionType:t.collisionType,collisionFilter:t.collisionFilter})),x(e,o=>te(o??{}))}import{Color as ee,Group as Ye,Sprite as Ne,SpriteMaterial as We,CanvasTexture as ie,LinearFilter as ct,Vector2 as pt,ClampToEdgeWrapping as oe,ShaderMaterial as ne,Mesh as Xe,PlaneGeometry as Ue,Vector3 as se}from"three";var H={position:void 0,width:120,height:48,fillColor:"#FFFFFF",strokeColor:null,strokeWidth:0,radius:0,padding:0,stickToViewport:!0,screenPosition:new pt(24,24),zDistance:1,anchor:new pt(0,0)},wt=class extends D{createEntity(t){return new k(t)}},re=Symbol("Rect"),k=class i extends c{static type=re;_sprite=null;_mesh=null;_texture=null;_canvas=null;_ctx=null;_cameraRef=null;_lastCanvasW=0;_lastCanvasH=0;constructor(t){super(),this.options=Z(H,t),this.options.screenPosition=E(this.options.screenPosition,H.screenPosition),this.options.anchor=E(this.options.anchor,H.anchor),this.group=new Ye,this.createSprite(),this.prependSetup(this.rectSetup.bind(this)),this.prependUpdate(this.rectUpdate.bind(this))}createSprite(){this._canvas=document.createElement("canvas"),this._ctx=this._canvas.getContext("2d"),this._texture=new ie(this._canvas),this._texture.minFilter=ct,this._texture.magFilter=ct;let t=new We({map:this._texture,transparent:!0,depthTest:!1,depthWrite:!1,alphaTest:.5});this._sprite=new Ne(t),this.group?.add(this._sprite),this.redrawRect()}redrawRect(){if(!this._canvas||!this._ctx)return;let t=Math.max(2,Math.floor(this.options.width??120)),e=Math.max(2,Math.floor(this.options.height??48)),o=this.options.padding??0,n=this.options.strokeWidth??0,s=t+o*2+n,a=e+o*2+n,r=Math.max(2,s),l=Math.max(2,a),p=r!==this._lastCanvasW||l!==this._lastCanvasH;this._canvas.width=r,this._canvas.height=l,this._lastCanvasW=r,this._lastCanvasH=l,this._ctx.clearRect(0,0,this._canvas.width,this._canvas.height);let O=Math.max(0,this.options.radius??0),u=Math.floor(o+n/2),d=Math.floor(o+n/2),b=Math.floor(t),f=Math.floor(e);if(this._ctx.beginPath(),O>0?this.roundedRectPath(this._ctx,u,d,b,f,O):this._ctx.rect(u,d,b,f),this.options.fillColor&&(this._ctx.fillStyle=this.toCssColor(this.options.fillColor),this._ctx.fill()),this.options.strokeColor&&n>0&&(this._ctx.lineWidth=n,this._ctx.strokeStyle=this.toCssColor(this.options.strokeColor),this._ctx.stroke()),this._texture){if(p&&(this._texture.dispose(),this._texture=new ie(this._canvas),this._texture.minFilter=ct,this._texture.magFilter=ct,this._texture.wrapS=oe,this._texture.wrapT=oe,this._sprite&&this._sprite.material instanceof ne)){let y=this._sprite.material;y.uniforms?.tDiffuse&&(y.uniforms.tDiffuse.value=this._texture),y.uniforms?.iResolution&&y.uniforms.iResolution.value.set(this._canvas.width,this._canvas.height,1)}this._texture.image=this._canvas,this._texture.needsUpdate=!0,this._sprite&&this._sprite.material&&(this._sprite.material.map=this._texture,this._sprite.material.needsUpdate=!0)}}getWidth(){return this.options.width??0}getHeight(){return this.options.height??0}roundedRectPath(t,e,o,n,s,a){let r=Math.min(a,Math.floor(Math.min(n,s)/2));t.moveTo(e+r,o),t.lineTo(e+n-r,o),t.quadraticCurveTo(e+n,o,e+n,o+r),t.lineTo(e+n,o+s-r),t.quadraticCurveTo(e+n,o+s,e+n-r,o+s),t.lineTo(e+r,o+s),t.quadraticCurveTo(e,o+s,e,o+s-r),t.lineTo(e,o+r),t.quadraticCurveTo(e,o,e+r,o)}toCssColor(t){return typeof t=="string"?t:`#${(t instanceof ee?t:new ee(t)).getHexString()}`}getResolution(){try{let t=this._cameraRef?.renderer?.domElement;if(t)return{width:t.clientWidth||1,height:t.clientHeight||1}}catch{}return{width:this._cameraRef?.screenResolution?.x??1,height:this._cameraRef?.screenResolution?.y??1}}rectSetup(t){if(this._cameraRef=t.camera,this.options.stickToViewport&&this._cameraRef&&this._cameraRef.camera.add(this.group),this.materials?.length&&this._sprite){let e=this.materials[0];e instanceof ne&&(e.transparent=!0,e.depthTest=!1,e.depthWrite=!1,this._texture&&(e.uniforms?.tDiffuse&&(e.uniforms.tDiffuse.value=this._texture),e.uniforms?.iResolution&&this._canvas&&e.uniforms.iResolution.value.set(this._canvas.width,this._canvas.height,1)),this._mesh=new Xe(new Ue(1,1),e),this.group?.add(this._mesh),this._sprite.visible=!1)}}rectUpdate(t){if(this._sprite){if(this._cameraRef&&this.options.bounds){let e=this.computeScreenBoundsFromOptions(this.options.bounds);if(e){let{x:o,y:n,width:s,height:a}=e,r=Math.max(2,Math.floor(s)),l=Math.max(2,Math.floor(a)),p=r!==(this.options.width??0)||l!==(this.options.height??0);this.options.screenPosition=new pt(Math.floor(o),Math.floor(n)),this.options.width=r,this.options.height=l,this.options.anchor=new pt(0,0),p&&this.redrawRect()}}this.options.stickToViewport&&this._cameraRef&&this.updateStickyTransform()}}updateStickyTransform(){if(!this._sprite||!this._cameraRef)return;let t=this._cameraRef.camera,{width:e,height:o}=this.getResolution(),n=E(this.options.screenPosition,H.screenPosition),s=n.x,a=n.y,r=Math.max(.001,this.options.zDistance??1),l=1,p=1;if(t.isPerspectiveCamera){let S=t,v=Math.tan(S.fov*Math.PI/180/2)*r;l=v*S.aspect,p=v}else if(t.isOrthographicCamera){let S=t;l=(S.right-S.left)/2,p=(S.top-S.bottom)/2}let O=s/e*2-1,u=1-a/o*2,d=O*l,b=u*p,f=1,y=1;if(this._canvas){let v=p*2/o,M=this._canvas.height;y=Math.max(1e-4,M*v);let G=this._canvas.width/this._canvas.height;f=y*G,this._sprite.scale.set(f,y,1),this._mesh&&this._mesh.scale.set(f,y,1)}let _=E(this.options.anchor,H.anchor),g=Math.min(100,Math.max(0,_.x))/100,h=Math.min(100,Math.max(0,_.y))/100,C=(.5-g)*f,T=(h-.5)*y;this.group?.position.set(d+C,b+T,-r)}worldToScreen(t){if(!this._cameraRef)return{x:0,y:0};let e=this._cameraRef.camera,{width:o,height:n}=this.getResolution(),s=t.clone().project(e),a=(s.x+1)/2*o,r=(1-s.y)/2*n;return{x:a,y:r}}computeScreenBoundsFromOptions(t){if(!this._cameraRef)return null;if(t.screen)return{...t.screen};if(t.world){let{left:e,right:o,top:n,bottom:s,z:a=0}=t.world,r=this.worldToScreen(new se(e,n,a)),l=this.worldToScreen(new se(o,s,a)),p=Math.min(r.x,l.x),O=Math.min(r.y,l.y),u=Math.abs(l.x-r.x),d=Math.abs(l.y-r.y);return{x:p,y:O,width:u,height:d}}return null}updateRect(t){this.options={...this.options,...t},this.redrawRect(),this.options.stickToViewport&&this._cameraRef&&this.updateStickyTransform()}buildInfo(){return{...new P(this).buildDebugInfo(),type:String(i.type),width:this.options.width??0,height:this.options.height??0,sticky:this.options.stickToViewport}}};function ae(...i){return R({args:i,defaultConfig:{...H},EntityClass:k,BuilderClass:wt,entityType:k.type,cloneFactory:t=>ae(t??{})})}import{Group as je,RingGeometry as qe}from"three";var le={...m,innerRadius:0,outerRadius:1,thetaSegments:32},Ct=class extends ${collider(t){let e=t.outerRadius??1;return{shape:{type:"cylinder",halfHeight:.1/2,radius:e}}}},vt=class extends K{build(t){let e=t.innerRadius??0,o=t.outerRadius??1,n=t.thetaSegments??32,s=new qe(e,o,n);return s.rotateX(-Math.PI/2),s}},_t=class extends D{createEntity(t){return new F(t)}build(){let t=super.build();return t.mesh&&!t.group&&(t.group=new je,t.group.add(t.mesh)),t}},ce=Symbol("Disk"),F=class i extends c{static type=ce;constructor(t){super(),this.options={...le,...t}}buildInfo(){let e=new P(this).buildDebugInfo(),o=this.options.innerRadius??0,n=this.options.outerRadius??1;return{...e,type:String(i.type),innerRadius:o.toFixed(2),outerRadius:n.toFixed(2)}}};function pe(...i){return R({args:i,defaultConfig:le,EntityClass:F,BuilderClass:_t,MeshBuilderClass:vt,CollisionBuilderClass:Ct,entityType:F.type,cloneFactory:t=>pe(t??{})})}var he={...m,radius:1,height:2,radialSegments:32},me=Symbol("Cone"),ht=class i extends c{static type=me;constructor(t){super(),this.options={...he,...t}}buildInfo(){let e=new P(this).buildDebugInfo(),o=this.options.radius??1,n=this.options.height??2;return{...e,type:String(i.type),radius:o.toFixed(2),height:n.toFixed(2)}}};function ue(...i){let t=w(i,he),e=new ht(t);return e.add(tt({radius:t.radius,height:t.height,radialSegments:t.radialSegments,material:t.material,color:t.color}),W({radius:t.radius,height:t.height,static:t.collision?.static,sensor:t.collision?.sensor,gravityScale:t.collision?.gravityScale,lockRotations:t.collision?.lockRotations,lockTranslations:t.collision?.lockTranslations,collisionType:t.collisionType,collisionFilter:t.collisionFilter})),x(e,o=>ue(o??{}))}var de={...m,radius:1,height:2},ye=Symbol("Pyramid"),mt=class i extends c{static type=ye;constructor(t){super(),this.options={...de,...t}}buildInfo(){let e=new P(this).buildDebugInfo(),o=this.options.radius??1,n=this.options.height??2;return{...e,type:String(i.type),radius:o.toFixed(2),height:n.toFixed(2)}}};function fe(...i){let t=w(i,de),e=new mt(t);return e.add(et({radius:t.radius,height:t.height,material:t.material,color:t.color}),X({radius:t.radius,height:t.height,static:t.collision?.static,sensor:t.collision?.sensor,gravityScale:t.collision?.gravityScale,lockRotations:t.collision?.lockRotations,lockTranslations:t.collision?.lockTranslations,collisionType:t.collisionType,collisionFilter:t.collisionFilter})),x(e,o=>fe(o??{}))}var ge={...m,radiusTop:1,radiusBottom:1,height:2,radialSegments:32},xe=Symbol("Cylinder"),ut=class i extends c{static type=xe;constructor(t){super(),this.options={...ge,...t}}buildInfo(){let e=new P(this).buildDebugInfo(),o=this.options.radiusTop??1,n=this.options.radiusBottom??1,s=this.options.height??2;return{...e,type:String(i.type),radiusTop:o.toFixed(2),radiusBottom:n.toFixed(2),height:s.toFixed(2)}}};function be(...i){let t=w(i,ge),e=new ut(t);return e.add(it({radiusTop:t.radiusTop,radiusBottom:t.radiusBottom,height:t.height,radialSegments:t.radialSegments,material:t.material,color:t.color}),U({radiusTop:t.radiusTop,radiusBottom:t.radiusBottom,height:t.height,static:t.collision?.static,sensor:t.collision?.sensor,gravityScale:t.collision?.gravityScale,lockRotations:t.collision?.lockRotations,lockTranslations:t.collision?.lockTranslations,collisionType:t.collisionType,collisionFilter:t.collisionFilter})),x(e,o=>be(o??{}))}var Oe={...m,radius:.5,length:1,capSegments:10,radialSegments:20},Pe=Symbol("Pill"),dt=class i extends c{static type=Pe;constructor(t){super(),this.options={...Oe,...t}}buildInfo(){let e=new P(this).buildDebugInfo(),o=this.options.radius??.5,n=this.options.length??1;return{...e,type:String(i.type),radius:o.toFixed(2),length:n.toFixed(2)}}};function Se(...i){let t=w(i,Oe),e=new dt(t);return e.add(ot({radius:t.radius,length:t.length,capSegments:t.capSegments,radialSegments:t.radialSegments,material:t.material,color:t.color}),j({radius:t.radius,length:t.length,static:t.collision?.static,sensor:t.collision?.sensor,gravityScale:t.collision?.gravityScale,lockRotations:t.collision?.lockRotations,lockTranslations:t.collision?.lockTranslations,collisionType:t.collisionType,collisionFilter:t.collisionFilter})),x(e,o=>Se(o??{}))}import{Group as $e,Quaternion as Ke,Vector3 as Qe}from"three";import{ParticleEmitterBehavior as Et}from"@zylem/behaviors/particle-emitter";var Je={...m,effect:{create(){throw new Error("createParticleSystem(...) requires an effect or preset definition.")}},preset:void 0,autoplay:!0,localOffset:void 0,followPosition:!0,followRotation:!0,autoDestroy:!1},we=Symbol("ParticleSystem");function ti(i){return{effect:i.preset??i.effect,autoplay:i.autoplay,localOffset:i.localOffset,followPosition:i.followPosition,followRotation:i.followRotation,autoDestroy:i.autoDestroy}}var yt=class i extends c{static type=we;particleHandle=null;constructor(t,e=!0){super(),this.options=Z(Je,t),this.group=new $e;let o=this.options.position;o&&this.group.position.copy(Ht(o)),this.__zylemParticleSystemEntity=!0,this.bindStandaloneTransforms(),e&&(this.particleHandle=this.use(Et,ti(this.options)))}bindStandaloneTransforms(){let t=()=>{this.options.position=new Qe(this.group?.position.x??0,this.group?.position.y??0,this.group?.position.z??0)},e=()=>{this.group&&(this._rotation2DAngle=this.group.rotation.z)};this.setPosition=(o,n,s)=>{this.group?.position.set(o,n,s),t()},this.setPositionX=o=>{this.group&&(this.group.position.x=o,t())},this.setPositionY=o=>{this.group&&(this.group.position.y=o,t())},this.setPositionZ=o=>{this.group&&(this.group.position.z=o,t())},this.getPosition=()=>this.group?{x:this.group.position.x,y:this.group.position.y,z:this.group.position.z}:null,this.setRotation=(o,n,s)=>{this.group?.rotation.set(o,n,s),e()},this.setRotationX=o=>{this.group&&(this.group.rotation.x=o,e())},this.setRotationY=o=>{this.group&&(this.group.rotation.y=o,e())},this.setRotationZ=o=>{this.group&&(this.group.rotation.z=o,e())},this.setRotationDegrees=(o,n,s)=>{this.group?.rotation.set(o*Math.PI/180,n*Math.PI/180,s*Math.PI/180),e()},this.setRotationDegreesX=o=>{this.group&&(this.group.rotation.x=o*Math.PI/180,e())},this.setRotationDegreesY=o=>{this.group&&(this.group.rotation.y=o*Math.PI/180,e())},this.setRotationDegreesZ=o=>{this.group&&(this.group.rotation.z=o*Math.PI/180,e())},this.rotateX=o=>{this.group?.rotateX(o),e()},this.rotateY=o=>{this.group?.rotateY(o),e()},this.rotateZ=o=>{this.group?.rotateZ(o),e()},this.getRotation=()=>{if(!this.group)return null;let o=new Ke;return this.group.getWorldQuaternion(o),o}}resolveParticleHandle(){if(this.particleHandle)return this.particleHandle;let t=this.getBehaviorRefs().find(n=>n.descriptor.key===Et.key);if(!t)return null;let e={getFSM:()=>t.fsm??null,getOptions:()=>t.options,ref:t},o=Et.createHandle?.(t)??{};return this.particleHandle={...e,...o},this.particleHandle}play(){this.resolveParticleHandle()?.play()}stop(){this.resolveParticleHandle()?.stop()}pause(){this.resolveParticleHandle()?.pause()}restart(){this.resolveParticleHandle()?.restart()}burst(){this.resolveParticleHandle()?.burst()}isPlaying(){return this.resolveParticleHandle()?.isPlaying()??!1}getSystem(){return this.resolveParticleHandle()?.getSystem()}buildInfo(){return{...super.buildInfo(),type:String(i.type)}}};function Ce(i,t=!0){let e=new yt(i,t);return x(e,o=>Ce(o,!1))}function ei(i){return Ce(i,!0)}import{AmbientLight as ii,DirectionalLight as oi,Group as ni,HemisphereLight as si,Object3D as ri,PointLight as ai,SpotLight as li}from"three";var ve=Symbol("Light"),ci={x:0,y:0,z:0},A=16777215,pi={mapSize:2048,near:.1,far:500,bias:0,radius:1,left:-100,right:100,top:100,bottom:-100},hi={mapSize:1024,near:.1,far:500,bias:0,radius:1},ft=class extends c{static type=ve;light=null;lightTarget=null;constructor(t){super(),this.options={...t}}create(){super.create();let t=new ni,{light:e,target:o}=mi(this.options);return t.add(e),o&&t.add(o),this.group=t,this.light=e,this.lightTarget=o,this}_cleanup(t){this.light?.shadow?.map?.dispose?.(),this.light=null,this.lightTarget=null,super._cleanup(t)}};function mi(i){switch(i.type){case"ambient":return{light:ui(i),target:null};case"hemisphere":return{light:di(i),target:null};case"directional":return yi(i);case"point":return{light:fi(i),target:null};case"spot":return gi(i)}}function ui(i){let t=new ii(i.color??A,i.intensity??1);return i.name&&(t.name=i.name),t}function di(i){let t=i.skyColor??i.color??A,e=i.groundColor??0,o=new si(t,e,i.intensity??1);return i.name&&(o.name=i.name),o}function yi(i){let t=new oi(i.color??A,i.intensity??1);i.name&&(t.name=i.name),xi(t,i.castShadow??!1,i.shadow);let e=_e(i.position,i.target);return e&&(t.target=e),{light:t,target:e}}function fi(i){let t=new ai(i.color??A,i.intensity??1,i.distance,i.decay);return i.name&&(t.name=i.name),Ee(t,i.castShadow??!1,i.shadow),t}function gi(i){let t=new li(i.color??A,i.intensity??1,i.distance,i.angle,i.penumbra,i.decay);i.name&&(t.name=i.name),Ee(t,i.castShadow??!1,i.shadow);let e=_e(i.position,i.target);return e&&(t.target=e),{light:t,target:e}}function _e(i,t){if(!t)return null;let e=i??ci,o=new ri;return o.position.set(t.x-e.x,t.y-e.y,t.z-e.z),o}function xi(i,t,e){if(!t){i.castShadow=!1;return}i.castShadow=!0;let o={...pi,...e??{}};i.shadow.mapSize.set(o.mapSize,o.mapSize),i.shadow.camera.near=o.near,i.shadow.camera.far=o.far,i.shadow.camera.left=o.left,i.shadow.camera.right=o.right,i.shadow.camera.top=o.top,i.shadow.camera.bottom=o.bottom,i.shadow.bias=o.bias,i.shadow.radius=o.radius,i.shadow.camera.updateProjectionMatrix()}function Ee(i,t,e){if(!t){i.castShadow=!1;return}i.castShadow=!0;let o={...hi,...e??{}};i.shadow.mapSize.set(o.mapSize,o.mapSize),i.shadow.camera.near=o.near,i.shadow.camera.far=o.far,i.shadow.bias=o.bias,i.shadow.radius=o.radius,i.shadow.camera.updateProjectionMatrix()}function bi(i){return new ft(i)}import{Group as Oi,Sprite as Pi,SpriteMaterial as Si,CanvasTexture as wi,LinearFilter as Ze,Color as Te,ClampToEdgeWrapping as Me}from"three";import{getCooldown as Re}from"@zylem/behaviors/cooldown";var Ci={"top-left":{fx:0,fy:0},"top-center":{fx:.5,fy:0},"top-right":{fx:1,fy:0},"center-left":{fx:0,fy:.5},center:{fx:.5,fy:.5},"center-right":{fx:1,fy:.5},"bottom-left":{fx:0,fy:1},"bottom-center":{fx:.5,fy:1},"bottom-right":{fx:1,fy:1}},De=192,vi={xs:8,sm:16,md:32,lg:48,xl:64},Zt={position:void 0,cooldown:"",iconSize:"md",fillColor:"#333333",showTimer:!0,stickToViewport:!0,screenAnchor:"top-left",screenPosition:{x:0,y:0},zDistance:1,overlayColor:"rgba(0, 0, 0, 0.65)"},_i=Symbol("CooldownIcon"),Tt=class extends c{static type=_i;_sprite=null;_texture=null;_canvas=null;_ctx=null;_cameraRef=null;_iconTexture=null;_iconImage=null;_lastRenderedProgress=-1;constructor(t){super(),this.options=Z(Zt,t),this.options.screenPosition=E(this.options.screenPosition,Zt.screenPosition),this.group=new Oi,this.createSprite(),this.prependSetup(this.iconSetup.bind(this)),this.prependUpdate(this.iconUpdate.bind(this)),this.onCleanup(this.iconDestroy.bind(this))}createSprite(){this._canvas=document.createElement("canvas"),this._canvas.width=256,this._canvas.height=256,this._ctx=this._canvas.getContext("2d"),this._texture=new wi(this._canvas),this._texture.minFilter=Ze,this._texture.magFilter=Ze,this._texture.wrapS=Me,this._texture.wrapT=Me;let e=new Si({map:this._texture,transparent:!0,depthTest:!1,depthWrite:!1});if(this._sprite=new Pi(e),this.group?.add(this._sprite),this.options.icon){let o=new Image;o.crossOrigin="anonymous",o.onload=()=>{this._iconImage=o,this.redraw(this._lastRenderedProgress>=0?this._lastRenderedProgress:1)},o.src=this.options.icon}this.redraw(1)}redraw(t){if(!this._canvas||!this._ctx)return;let e=this._ctx,o=this._canvas.width,n=this._canvas.height,s=o/2,a=n/2,r=Math.min(s,a);if(e.clearRect(0,0,o,n),this._iconImage?e.drawImage(this._iconImage,0,0,o,n):(e.fillStyle=this.toCssColor(this.options.fillColor??"#333333"),e.fillRect(0,0,o,n)),t<1){let l=(1-t)*Math.PI*2,p=-Math.PI/2,O=p+l;if(e.save(),e.fillStyle=this.options.overlayColor??"rgba(0, 0, 0, 0.65)",e.beginPath(),e.moveTo(s,a),e.arc(s,a,r+1,p,O,!1),e.closePath(),e.fill(),e.restore(),this.options.showTimer){let u=Re(this.options.cooldown);if(u){let d=Math.max(0,u.duration-u.elapsed),b=d>=10?Math.ceil(d).toString():d.toFixed(1),f=Math.floor(o*.3);e.font=`bold ${f}px sans-serif`,e.textAlign="center",e.textBaseline="middle",e.fillStyle="#FFFFFF",e.strokeStyle="#000000",e.lineWidth=2,e.strokeText(b,s,a),e.fillText(b,s,a)}}}this._texture&&(this._texture.needsUpdate=!0),this._lastRenderedProgress=t}toCssColor(t){return typeof t=="string"?t:`#${(t instanceof Te?t:new Te(t)).getHexString()}`}getResolution(){try{let t=this._cameraRef?.renderer?.domElement;if(t)return{width:t.clientWidth||1,height:t.clientHeight||1}}catch{}return{width:this._cameraRef?.screenResolution?.x??1,height:this._cameraRef?.screenResolution?.y??1}}iconSetup(t){this._sprite||this.createSprite(),this._cameraRef=t.camera,this.options.stickToViewport&&this._cameraRef&&(this._cameraRef.camera.add(this.group),this.updateStickyTransform())}iconUpdate(t){let o=Re(this.options.cooldown)?.progress??1;(Math.abs(o-this._lastRenderedProgress)>.02||o===1&&this._lastRenderedProgress!==1)&&this.redraw(o),this.options.stickToViewport&&this._cameraRef&&this.updateStickyTransform()}resolveScreenPosition(t,e){let o=this.options.screenAnchor??"top-left",n=Bt(this.options.screenPosition,It),s=n.x,a=n.y,{fx:r,fy:l}=Ci[o],p=r*t,O=l*e,u=e/De;return{px:p+s*u,py:O+a*u}}resolveIconSize(t){let e=this.options.iconSize??"md",o,n;typeof e=="string"?o=n=vi[e]:typeof e=="number"?o=n=e:(o=e.width,n=e.height);let s=t/De;return{widthPx:o*s,heightPx:n*s}}computeWorldExtents(t,e){let o=1,n=1;if(t.isPerspectiveCamera){let s=t,a=Math.tan(s.fov*Math.PI/180/2)*e;o=a*s.aspect,n=a}else if(t.isOrthographicCamera){let s=t;o=(s.right-s.left)/2,n=(s.top-s.bottom)/2}return{worldHalfW:o,worldHalfH:n}}updateStickyTransform(){if(!this._sprite||!this._cameraRef)return;let t=this._cameraRef.camera,{width:e,height:o}=this.getResolution(),{px:n,py:s}=this.resolveScreenPosition(e,o),a=Math.max(.001,this.options.zDistance??1),{worldHalfW:r,worldHalfH:l}=this.computeWorldExtents(t,a),p=n/e*2-1,O=1-s/o*2,u=p*r,d=O*l;{let f=l*2/o,{widthPx:y,heightPx:_}=this.resolveIconSize(o),g=Math.max(1e-4,y*f),h=Math.max(1e-4,_*f);this._sprite.scale.set(g,h,1)}this.group?.position.set(u,d,-a)}iconDestroy(){this._texture?.dispose(),this._sprite?.material&&this._sprite.material.dispose(),this._sprite&&this._sprite.removeFromParent(),this.group?.removeFromParent(),this._iconTexture?.dispose(),this._sprite=null,this._texture=null,this._canvas=null,this._ctx=null,this._cameraRef=null,this._iconTexture=null,this._iconImage=null}};function Ie(...i){let t=i.filter(o=>!(o instanceof Dt)),e={...Zt};for(let o of t)e={...e,...o};return x(new Tt(e),o=>Ie(o??{}))}function Ei(i,t,e){e({me:i,globals:t})}function Zi(i,t){let e=t??Rt();Ei(i,e,i.nodeDestroy.bind(i))}export{Q as a,J as b,tt as c,et as d,it as e,ot as f,At as g,nt as h,Vt as i,Nt as j,st as k,Wt as l,$t as m,B as n,Kt as o,Jt as p,lt as q,te as r,re as s,k as t,ae as u,ce as v,F as w,pe as x,me as y,ht as z,ue as A,ye as B,mt as C,fe as D,xe as E,ut as F,be as G,Pe as H,dt as I,Se as J,we as K,yt as L,ei as M,ve as N,ft as O,bi as P,Ie as Q,Zi as R};
1
+ import{a as P}from"./chunk-PNLNC3FA.js";import{a as Dt,b as Z,c as Y,d as N,e as W,f as X,g as U,h as j,j as q,p as m,q as w,r as c,t as x,u as R,v as $,w as K,x as D}from"./chunk-3I537JFL.js";import{j as kt}from"./chunk-CM5YRNBJ.js";import{d as V,j as Rt}from"./chunk-4QLJUQSJ.js";import{a as It,b as gt,c as zt,d as Lt,g as Bt,h as xt,i as E,j as Ht}from"./chunk-7WRQ2UAN.js";import{Vector3 as Fe}from"three";import{BoxGeometry as ze,CapsuleGeometry as Le,ConeGeometry as Ft,CylinderGeometry as Be,Mesh as I,MeshStandardMaterial as He,SphereGeometry as ke}from"three";function z(i,t=Symbol("mesh")){if(i.material||i.color){let e=new kt;if(e.build({...i.material,color:i.color??i.material?.color},t),e.materials.length>0)return e.materials}return[new He]}function L(i,t){if(t.position){let e=xt(t.position,zt);i.position.set(e.x,e.y,e.z)}return i.castShadow=!0,i.receiveShadow=!0,i}function Q(i={}){let t=xt(i.size,Lt),e=new ze(t.x,t.y,t.z),o=z(i);return L(new I(e,o.at(-1)),i)}function J(i={}){let t=new ke(i.radius??1),e=z(i);return L(new I(t,e.at(-1)),i)}function tt(i={}){let t=new Ft(i.radius??1,i.height??2,i.radialSegments??32),e=z(i);return L(new I(t,e.at(-1)),i)}function et(i={}){let t=new Ft(i.radius??1,i.height??2,4),e=z(i);return L(new I(t,e.at(-1)),i)}function it(i={}){let t=new Be(i.radiusTop??1,i.radiusBottom??1,i.height??2,i.radialSegments??32),e=z(i);return L(new I(t,e.at(-1)),i)}function ot(i={}){let t=new Le(i.radius??.5,i.length??1,i.capSegments??10,i.radialSegments??20),e=z(i);return L(new I(t,e.at(-1)),i)}var Gt={...m,size:new Fe(1,1,1)},At=Symbol("Box"),nt=class i extends c{static type=At;constructor(t){super(),this.options={...Gt,...t}}buildInfo(){let e=new P(this).buildDebugInfo(),{x:o,y:n,z:s}=this.options.size??{x:1,y:1,z:1};return{...e,type:String(i.type),size:`${o}, ${n}, ${s}`}}};function Vt(...i){let t=w(i,Gt),e=new nt(t);return e.add(Q({size:t.size,material:t.material,color:t.color}),Y({size:t.size,static:t.collision?.static,sensor:t.collision?.sensor,canSleep:t.collision?.canSleep,ccdEnabled:t.collision?.ccdEnabled,gravityScale:t.collision?.gravityScale,lockRotations:t.collision?.lockRotations,lockTranslations:t.collision?.lockTranslations,collisionType:t.collisionType,collisionFilter:t.collisionFilter})),x(e,o=>Vt(o??{}))}var Yt={...m,radius:1},Nt=Symbol("Sphere"),st=class i extends c{static type=Nt;constructor(t){super(),this.options={...Yt,...t}}buildInfo(){let e=new P(this).buildDebugInfo(),o=this.options.radius??1;return{...e,type:String(i.type),radius:o.toFixed(2)}}};function Wt(...i){let t=w(i,Yt),e=new st(t);return e.add(J({radius:t.radius,material:t.material,color:t.color}),N({radius:t.radius,static:t.collision?.static,sensor:t.collision?.sensor,gravityScale:t.collision?.gravityScale,lockRotations:t.collision?.lockRotations,lockTranslations:t.collision?.lockTranslations,collisionType:t.collisionType,collisionFilter:t.collisionFilter})),x(e,o=>Wt(o??{}))}import{PlaneGeometry as Ae,Vector2 as Xt,Vector3 as Ut}from"three";import{BufferGeometry as Ge,Float32BufferAttribute as bt}from"three";var rt=class i extends Ge{constructor(t=1,e=1,o=1,n=1){super(),this.type="XZPlaneGeometry",this.parameters={width:t,height:e,widthSegments:o,heightSegments:n};let s=t/2,a=e/2,r=Math.floor(o),l=Math.floor(n),p=r+1,O=l+1,u=t/r,d=e/l,b=[],f=[],y=[],_=[];for(let g=0;g<O;g++){let h=g*d-a;for(let C=0;C<p;C++){let T=C*u-s;f.push(T,0,h),y.push(0,1,0),_.push(C/r),_.push(1-g/l)}}for(let g=0;g<l;g++)for(let h=0;h<r;h++){let C=h+p*g,T=h+p*(g+1),S=h+1+p*(g+1),v=h+1+p*g;b.push(C,T,v),b.push(T,S,v)}this.setIndex(b),this.setAttribute("position",new bt(f,3)),this.setAttribute("normal",new bt(y,3)),this.setAttribute("uv",new bt(_,2))}copy(t){return super.copy(t),this.parameters=Object.assign({},t.parameters),this}static fromJSON(t){return new i(t.width,t.height,t.widthSegments,t.heightSegments)}};var at=4,jt={...m,tile:new Xt(10,10),repeat:new Xt(1,1),collision:{static:!0},subdivisions:at,randomizeHeight:!1,heightScale:1};function qt(i){let t=i.subdivisions??at,e=i.heightMap2D,o=i.heightMap,n=i.subdivisionsX??t,s=i.subdivisionsZ??t;return e&&e.length>0&&e[0]?.length>0?(s=e.length-1,n=e[0].length-1):o&&o.length>0&&(n=o.length-1),{subdivisionsX:n,subdivisionsZ:s}}var Ot=class extends ${collider(t){let e=E(t.tile,gt),{subdivisionsX:o,subdivisionsZ:n}=qt(t),s=new Ut(e.x,1,e.y),a=t._builders?.meshBuilder?.heightData??new Float32Array((o+1)*(n+1));return{shape:{type:"heightfield",rows:o,cols:n,heights:a,scale:[s.x,1,s.z]}}}},Pt=class extends K{heightData=new Float32Array;columnsRows=new Map;subdivisionsX=at;subdivisionsZ=at;build(t){let e=E(t.tile,gt),{subdivisionsX:o,subdivisionsZ:n}=qt(t);this.subdivisionsX=o,this.subdivisionsZ=n;let s=new Ut(e.x,1,e.y),a=t.heightScale??1,r=new rt(s.x,s.z,o,n),l=new Ae(s.x,s.z,o,n),p=o>0?s.x/o:1,O=n>0?s.z/n:1,u=r.attributes.position.array,d=l.attributes.position.array,b=new Map,f=t.heightMap2D,y=t.heightMap,_=t.randomizeHeight??!1,g=(h,C)=>h<0?0:h>C?C:h;for(let h=0;h<d.length;h+=3){let C=d[h],T=d[h+1],S=g(Math.round((C+s.x/2)/p),o),v=g(Math.round((s.z/2-T)/O),n),M=0;if(f){let Mt=f[v];Mt&&(M=Mt[S]??0)}else y&&y.length>0?M=y[S]??0:_&&(M=Math.random()*4);let G=M*a;d[h+2]=G,u[h+1]=G,b.get(v)||b.set(v,new Map),b.get(v).set(S,G)}return this.columnsRows=b,r}postBuild(){let t=[];for(let e=0;e<=this.subdivisionsX;++e)for(let o=0;o<=this.subdivisionsZ;++o){let n=this.columnsRows.get(o);t.push(n?.get(e)??0)}this.heightData=new Float32Array(t)}},St=class extends D{createEntity(t){return new B(t)}},$t=Symbol("Plane"),B=class extends c{static type=$t;constructor(t){super(),this.options=Z(jt,t)}};function Kt(...i){return R({args:i,defaultConfig:jt,EntityClass:B,BuilderClass:St,MeshBuilderClass:Pt,CollisionBuilderClass:Ot,entityType:B.type,cloneFactory:t=>Kt(t??{})})}import{Vector3 as Ve}from"three";var Qt={...m,size:new Ve(1,1,1),collision:{static:!0}},Jt=Symbol("Zone"),lt=class extends c{static type=Jt;_enteredZone=new Map;_exitedZone=new Map;_zoneEntities=new Map;constructor(t){super(),this.options=Z(Qt,t)}handlePostCollision({delta:t}){return this._enteredZone.forEach((e,o)=>{this.exited(t,o)}),this._enteredZone.size>0}handleIntersectionEvent({other:t,delta:e}){this._enteredZone.get(t.uuid)?this.held(e,t):(this.entered(t),this._zoneEntities.set(t.uuid,t))}onEnter(t){return this.options.onEnter=t,this}onHeld(t){return this.options.onHeld=t,this}onExit(t){return this.options.onExit=t,this}entered(t){this._enteredZone.set(t.uuid,1),this.options.onEnter&&this.options.onEnter({self:this,visitor:t,globals:V.globals})}exited(t,e){let o=this._exitedZone.get(e);if(o&&o>1+t){this._exitedZone.delete(e),this._enteredZone.delete(e);let n=this._zoneEntities.get(e);this.options.onExit&&this.options.onExit({self:this,visitor:n,globals:V.globals});return}this._exitedZone.set(e,1+t)}held(t,e){let o=this._enteredZone.get(e.uuid)??0;this._enteredZone.set(e.uuid,o+t),this._exitedZone.set(e.uuid,1),this.options.onHeld&&this.options.onHeld({delta:t,self:this,visitor:e,globals:V.globals,heldTime:o})}};function te(...i){let t=w(i,Qt),e=new lt(t);return e.add(q({size:t.size,static:t.collision?.static??!0,collisionType:t.collisionType,collisionFilter:t.collisionFilter})),x(e,o=>te(o??{}))}import{Color as ee,Group as Ye,Sprite as Ne,SpriteMaterial as We,CanvasTexture as ie,LinearFilter as ct,Vector2 as pt,ClampToEdgeWrapping as oe,ShaderMaterial as ne,Mesh as Xe,PlaneGeometry as Ue,Vector3 as se}from"three";var H={position:void 0,width:120,height:48,fillColor:"#FFFFFF",strokeColor:null,strokeWidth:0,radius:0,padding:0,stickToViewport:!0,screenPosition:new pt(24,24),zDistance:1,anchor:new pt(0,0)},wt=class extends D{createEntity(t){return new k(t)}},re=Symbol("Rect"),k=class i extends c{static type=re;_sprite=null;_mesh=null;_texture=null;_canvas=null;_ctx=null;_cameraRef=null;_lastCanvasW=0;_lastCanvasH=0;constructor(t){super(),this.options=Z(H,t),this.options.screenPosition=E(this.options.screenPosition,H.screenPosition),this.options.anchor=E(this.options.anchor,H.anchor),this.group=new Ye,this.createSprite(),this.prependSetup(this.rectSetup.bind(this)),this.prependUpdate(this.rectUpdate.bind(this))}createSprite(){this._canvas=document.createElement("canvas"),this._ctx=this._canvas.getContext("2d"),this._texture=new ie(this._canvas),this._texture.minFilter=ct,this._texture.magFilter=ct;let t=new We({map:this._texture,transparent:!0,depthTest:!1,depthWrite:!1,alphaTest:.5});this._sprite=new Ne(t),this.group?.add(this._sprite),this.redrawRect()}redrawRect(){if(!this._canvas||!this._ctx)return;let t=Math.max(2,Math.floor(this.options.width??120)),e=Math.max(2,Math.floor(this.options.height??48)),o=this.options.padding??0,n=this.options.strokeWidth??0,s=t+o*2+n,a=e+o*2+n,r=Math.max(2,s),l=Math.max(2,a),p=r!==this._lastCanvasW||l!==this._lastCanvasH;this._canvas.width=r,this._canvas.height=l,this._lastCanvasW=r,this._lastCanvasH=l,this._ctx.clearRect(0,0,this._canvas.width,this._canvas.height);let O=Math.max(0,this.options.radius??0),u=Math.floor(o+n/2),d=Math.floor(o+n/2),b=Math.floor(t),f=Math.floor(e);if(this._ctx.beginPath(),O>0?this.roundedRectPath(this._ctx,u,d,b,f,O):this._ctx.rect(u,d,b,f),this.options.fillColor&&(this._ctx.fillStyle=this.toCssColor(this.options.fillColor),this._ctx.fill()),this.options.strokeColor&&n>0&&(this._ctx.lineWidth=n,this._ctx.strokeStyle=this.toCssColor(this.options.strokeColor),this._ctx.stroke()),this._texture){if(p&&(this._texture.dispose(),this._texture=new ie(this._canvas),this._texture.minFilter=ct,this._texture.magFilter=ct,this._texture.wrapS=oe,this._texture.wrapT=oe,this._sprite&&this._sprite.material instanceof ne)){let y=this._sprite.material;y.uniforms?.tDiffuse&&(y.uniforms.tDiffuse.value=this._texture),y.uniforms?.iResolution&&y.uniforms.iResolution.value.set(this._canvas.width,this._canvas.height,1)}this._texture.image=this._canvas,this._texture.needsUpdate=!0,this._sprite&&this._sprite.material&&(this._sprite.material.map=this._texture,this._sprite.material.needsUpdate=!0)}}getWidth(){return this.options.width??0}getHeight(){return this.options.height??0}roundedRectPath(t,e,o,n,s,a){let r=Math.min(a,Math.floor(Math.min(n,s)/2));t.moveTo(e+r,o),t.lineTo(e+n-r,o),t.quadraticCurveTo(e+n,o,e+n,o+r),t.lineTo(e+n,o+s-r),t.quadraticCurveTo(e+n,o+s,e+n-r,o+s),t.lineTo(e+r,o+s),t.quadraticCurveTo(e,o+s,e,o+s-r),t.lineTo(e,o+r),t.quadraticCurveTo(e,o,e+r,o)}toCssColor(t){return typeof t=="string"?t:`#${(t instanceof ee?t:new ee(t)).getHexString()}`}getResolution(){try{let t=this._cameraRef?.renderer?.domElement;if(t)return{width:t.clientWidth||1,height:t.clientHeight||1}}catch{}return{width:this._cameraRef?.screenResolution?.x??1,height:this._cameraRef?.screenResolution?.y??1}}rectSetup(t){if(this._cameraRef=t.camera,this.options.stickToViewport&&this._cameraRef&&this._cameraRef.camera.add(this.group),this.materials?.length&&this._sprite){let e=this.materials[0];e instanceof ne&&(e.transparent=!0,e.depthTest=!1,e.depthWrite=!1,this._texture&&(e.uniforms?.tDiffuse&&(e.uniforms.tDiffuse.value=this._texture),e.uniforms?.iResolution&&this._canvas&&e.uniforms.iResolution.value.set(this._canvas.width,this._canvas.height,1)),this._mesh=new Xe(new Ue(1,1),e),this.group?.add(this._mesh),this._sprite.visible=!1)}}rectUpdate(t){if(this._sprite){if(this._cameraRef&&this.options.bounds){let e=this.computeScreenBoundsFromOptions(this.options.bounds);if(e){let{x:o,y:n,width:s,height:a}=e,r=Math.max(2,Math.floor(s)),l=Math.max(2,Math.floor(a)),p=r!==(this.options.width??0)||l!==(this.options.height??0);this.options.screenPosition=new pt(Math.floor(o),Math.floor(n)),this.options.width=r,this.options.height=l,this.options.anchor=new pt(0,0),p&&this.redrawRect()}}this.options.stickToViewport&&this._cameraRef&&this.updateStickyTransform()}}updateStickyTransform(){if(!this._sprite||!this._cameraRef)return;let t=this._cameraRef.camera,{width:e,height:o}=this.getResolution(),n=E(this.options.screenPosition,H.screenPosition),s=n.x,a=n.y,r=Math.max(.001,this.options.zDistance??1),l=1,p=1;if(t.isPerspectiveCamera){let S=t,v=Math.tan(S.fov*Math.PI/180/2)*r;l=v*S.aspect,p=v}else if(t.isOrthographicCamera){let S=t;l=(S.right-S.left)/2,p=(S.top-S.bottom)/2}let O=s/e*2-1,u=1-a/o*2,d=O*l,b=u*p,f=1,y=1;if(this._canvas){let v=p*2/o,M=this._canvas.height;y=Math.max(1e-4,M*v);let G=this._canvas.width/this._canvas.height;f=y*G,this._sprite.scale.set(f,y,1),this._mesh&&this._mesh.scale.set(f,y,1)}let _=E(this.options.anchor,H.anchor),g=Math.min(100,Math.max(0,_.x))/100,h=Math.min(100,Math.max(0,_.y))/100,C=(.5-g)*f,T=(h-.5)*y;this.group?.position.set(d+C,b+T,-r)}worldToScreen(t){if(!this._cameraRef)return{x:0,y:0};let e=this._cameraRef.camera,{width:o,height:n}=this.getResolution(),s=t.clone().project(e),a=(s.x+1)/2*o,r=(1-s.y)/2*n;return{x:a,y:r}}computeScreenBoundsFromOptions(t){if(!this._cameraRef)return null;if(t.screen)return{...t.screen};if(t.world){let{left:e,right:o,top:n,bottom:s,z:a=0}=t.world,r=this.worldToScreen(new se(e,n,a)),l=this.worldToScreen(new se(o,s,a)),p=Math.min(r.x,l.x),O=Math.min(r.y,l.y),u=Math.abs(l.x-r.x),d=Math.abs(l.y-r.y);return{x:p,y:O,width:u,height:d}}return null}updateRect(t){this.options={...this.options,...t},this.redrawRect(),this.options.stickToViewport&&this._cameraRef&&this.updateStickyTransform()}buildInfo(){return{...new P(this).buildDebugInfo(),type:String(i.type),width:this.options.width??0,height:this.options.height??0,sticky:this.options.stickToViewport}}};function ae(...i){return R({args:i,defaultConfig:{...H},EntityClass:k,BuilderClass:wt,entityType:k.type,cloneFactory:t=>ae(t??{})})}import{Group as je,RingGeometry as qe}from"three";var le={...m,innerRadius:0,outerRadius:1,thetaSegments:32},Ct=class extends ${collider(t){let e=t.outerRadius??1;return{shape:{type:"cylinder",halfHeight:.1/2,radius:e}}}},vt=class extends K{build(t){let e=t.innerRadius??0,o=t.outerRadius??1,n=t.thetaSegments??32,s=new qe(e,o,n);return s.rotateX(-Math.PI/2),s}},_t=class extends D{createEntity(t){return new F(t)}build(){let t=super.build();return t.mesh&&!t.group&&(t.group=new je,t.group.add(t.mesh)),t}},ce=Symbol("Disk"),F=class i extends c{static type=ce;constructor(t){super(),this.options={...le,...t}}buildInfo(){let e=new P(this).buildDebugInfo(),o=this.options.innerRadius??0,n=this.options.outerRadius??1;return{...e,type:String(i.type),innerRadius:o.toFixed(2),outerRadius:n.toFixed(2)}}};function pe(...i){return R({args:i,defaultConfig:le,EntityClass:F,BuilderClass:_t,MeshBuilderClass:vt,CollisionBuilderClass:Ct,entityType:F.type,cloneFactory:t=>pe(t??{})})}var he={...m,radius:1,height:2,radialSegments:32},me=Symbol("Cone"),ht=class i extends c{static type=me;constructor(t){super(),this.options={...he,...t}}buildInfo(){let e=new P(this).buildDebugInfo(),o=this.options.radius??1,n=this.options.height??2;return{...e,type:String(i.type),radius:o.toFixed(2),height:n.toFixed(2)}}};function ue(...i){let t=w(i,he),e=new ht(t);return e.add(tt({radius:t.radius,height:t.height,radialSegments:t.radialSegments,material:t.material,color:t.color}),W({radius:t.radius,height:t.height,static:t.collision?.static,sensor:t.collision?.sensor,gravityScale:t.collision?.gravityScale,lockRotations:t.collision?.lockRotations,lockTranslations:t.collision?.lockTranslations,collisionType:t.collisionType,collisionFilter:t.collisionFilter})),x(e,o=>ue(o??{}))}var de={...m,radius:1,height:2},ye=Symbol("Pyramid"),mt=class i extends c{static type=ye;constructor(t){super(),this.options={...de,...t}}buildInfo(){let e=new P(this).buildDebugInfo(),o=this.options.radius??1,n=this.options.height??2;return{...e,type:String(i.type),radius:o.toFixed(2),height:n.toFixed(2)}}};function fe(...i){let t=w(i,de),e=new mt(t);return e.add(et({radius:t.radius,height:t.height,material:t.material,color:t.color}),X({radius:t.radius,height:t.height,static:t.collision?.static,sensor:t.collision?.sensor,gravityScale:t.collision?.gravityScale,lockRotations:t.collision?.lockRotations,lockTranslations:t.collision?.lockTranslations,collisionType:t.collisionType,collisionFilter:t.collisionFilter})),x(e,o=>fe(o??{}))}var ge={...m,radiusTop:1,radiusBottom:1,height:2,radialSegments:32},xe=Symbol("Cylinder"),ut=class i extends c{static type=xe;constructor(t){super(),this.options={...ge,...t}}buildInfo(){let e=new P(this).buildDebugInfo(),o=this.options.radiusTop??1,n=this.options.radiusBottom??1,s=this.options.height??2;return{...e,type:String(i.type),radiusTop:o.toFixed(2),radiusBottom:n.toFixed(2),height:s.toFixed(2)}}};function be(...i){let t=w(i,ge),e=new ut(t);return e.add(it({radiusTop:t.radiusTop,radiusBottom:t.radiusBottom,height:t.height,radialSegments:t.radialSegments,material:t.material,color:t.color}),U({radiusTop:t.radiusTop,radiusBottom:t.radiusBottom,height:t.height,static:t.collision?.static,sensor:t.collision?.sensor,gravityScale:t.collision?.gravityScale,lockRotations:t.collision?.lockRotations,lockTranslations:t.collision?.lockTranslations,collisionType:t.collisionType,collisionFilter:t.collisionFilter})),x(e,o=>be(o??{}))}var Oe={...m,radius:.5,length:1,capSegments:10,radialSegments:20},Pe=Symbol("Pill"),dt=class i extends c{static type=Pe;constructor(t){super(),this.options={...Oe,...t}}buildInfo(){let e=new P(this).buildDebugInfo(),o=this.options.radius??.5,n=this.options.length??1;return{...e,type:String(i.type),radius:o.toFixed(2),length:n.toFixed(2)}}};function Se(...i){let t=w(i,Oe),e=new dt(t);return e.add(ot({radius:t.radius,length:t.length,capSegments:t.capSegments,radialSegments:t.radialSegments,material:t.material,color:t.color}),j({radius:t.radius,length:t.length,static:t.collision?.static,sensor:t.collision?.sensor,gravityScale:t.collision?.gravityScale,lockRotations:t.collision?.lockRotations,lockTranslations:t.collision?.lockTranslations,collisionType:t.collisionType,collisionFilter:t.collisionFilter})),x(e,o=>Se(o??{}))}import{Group as $e,Quaternion as Ke,Vector3 as Qe}from"three";import{ParticleEmitterBehavior as Et}from"@zylem/behaviors/particle-emitter";var Je={...m,effect:{create(){throw new Error("createParticleSystem(...) requires an effect or preset definition.")}},preset:void 0,autoplay:!0,localOffset:void 0,followPosition:!0,followRotation:!0,autoDestroy:!1},we=Symbol("ParticleSystem");function ti(i){return{effect:i.preset??i.effect,autoplay:i.autoplay,localOffset:i.localOffset,followPosition:i.followPosition,followRotation:i.followRotation,autoDestroy:i.autoDestroy}}var yt=class i extends c{static type=we;particleHandle=null;constructor(t,e=!0){super(),this.options=Z(Je,t),this.group=new $e;let o=this.options.position;o&&this.group.position.copy(Ht(o)),this.__zylemParticleSystemEntity=!0,this.bindStandaloneTransforms(),e&&(this.particleHandle=this.use(Et,ti(this.options)))}bindStandaloneTransforms(){let t=()=>{this.options.position=new Qe(this.group?.position.x??0,this.group?.position.y??0,this.group?.position.z??0)},e=()=>{this.group&&(this._rotation2DAngle=this.group.rotation.z)};this.setPosition=(o,n,s)=>{this.group?.position.set(o,n,s),t()},this.setPositionX=o=>{this.group&&(this.group.position.x=o,t())},this.setPositionY=o=>{this.group&&(this.group.position.y=o,t())},this.setPositionZ=o=>{this.group&&(this.group.position.z=o,t())},this.getPosition=()=>this.group?{x:this.group.position.x,y:this.group.position.y,z:this.group.position.z}:null,this.setRotation=(o,n,s)=>{this.group?.rotation.set(o,n,s),e()},this.setRotationX=o=>{this.group&&(this.group.rotation.x=o,e())},this.setRotationY=o=>{this.group&&(this.group.rotation.y=o,e())},this.setRotationZ=o=>{this.group&&(this.group.rotation.z=o,e())},this.setRotationDegrees=(o,n,s)=>{this.group?.rotation.set(o*Math.PI/180,n*Math.PI/180,s*Math.PI/180),e()},this.setRotationDegreesX=o=>{this.group&&(this.group.rotation.x=o*Math.PI/180,e())},this.setRotationDegreesY=o=>{this.group&&(this.group.rotation.y=o*Math.PI/180,e())},this.setRotationDegreesZ=o=>{this.group&&(this.group.rotation.z=o*Math.PI/180,e())},this.rotateX=o=>{this.group?.rotateX(o),e()},this.rotateY=o=>{this.group?.rotateY(o),e()},this.rotateZ=o=>{this.group?.rotateZ(o),e()},this.getRotation=()=>{if(!this.group)return null;let o=new Ke;return this.group.getWorldQuaternion(o),o}}resolveParticleHandle(){if(this.particleHandle)return this.particleHandle;let t=this.getBehaviorRefs().find(n=>n.descriptor.key===Et.key);if(!t)return null;let e={getFSM:()=>t.fsm??null,getOptions:()=>t.options,ref:t},o=Et.createHandle?.(t)??{};return this.particleHandle={...e,...o},this.particleHandle}play(){this.resolveParticleHandle()?.play()}stop(){this.resolveParticleHandle()?.stop()}pause(){this.resolveParticleHandle()?.pause()}restart(){this.resolveParticleHandle()?.restart()}burst(){this.resolveParticleHandle()?.burst()}isPlaying(){return this.resolveParticleHandle()?.isPlaying()??!1}getSystem(){return this.resolveParticleHandle()?.getSystem()}buildInfo(){return{...super.buildInfo(),type:String(i.type)}}};function Ce(i,t=!0){let e=new yt(i,t);return x(e,o=>Ce(o,!1))}function ei(i){return Ce(i,!0)}import{AmbientLight as ii,DirectionalLight as oi,Group as ni,HemisphereLight as si,Object3D as ri,PointLight as ai,SpotLight as li}from"three";var ve=Symbol("Light"),ci={x:0,y:0,z:0},A=16777215,pi={mapSize:2048,near:.1,far:500,bias:0,radius:1,left:-100,right:100,top:100,bottom:-100},hi={mapSize:1024,near:.1,far:500,bias:0,radius:1},ft=class extends c{static type=ve;light=null;lightTarget=null;constructor(t){super(),this.options={...t}}create(){super.create();let t=new ni,{light:e,target:o}=mi(this.options);return t.add(e),o&&t.add(o),this.group=t,this.light=e,this.lightTarget=o,this}_cleanup(t){this.light?.shadow?.map?.dispose?.(),this.light=null,this.lightTarget=null,super._cleanup(t)}};function mi(i){switch(i.type){case"ambient":return{light:ui(i),target:null};case"hemisphere":return{light:di(i),target:null};case"directional":return yi(i);case"point":return{light:fi(i),target:null};case"spot":return gi(i)}}function ui(i){let t=new ii(i.color??A,i.intensity??1);return i.name&&(t.name=i.name),t}function di(i){let t=i.skyColor??i.color??A,e=i.groundColor??0,o=new si(t,e,i.intensity??1);return i.name&&(o.name=i.name),o}function yi(i){let t=new oi(i.color??A,i.intensity??1);i.name&&(t.name=i.name),xi(t,i.castShadow??!1,i.shadow);let e=_e(i.position,i.target);return e&&(t.target=e),{light:t,target:e}}function fi(i){let t=new ai(i.color??A,i.intensity??1,i.distance,i.decay);return i.name&&(t.name=i.name),Ee(t,i.castShadow??!1,i.shadow),t}function gi(i){let t=new li(i.color??A,i.intensity??1,i.distance,i.angle,i.penumbra,i.decay);i.name&&(t.name=i.name),Ee(t,i.castShadow??!1,i.shadow);let e=_e(i.position,i.target);return e&&(t.target=e),{light:t,target:e}}function _e(i,t){if(!t)return null;let e=i??ci,o=new ri;return o.position.set(t.x-e.x,t.y-e.y,t.z-e.z),o}function xi(i,t,e){if(!t){i.castShadow=!1;return}i.castShadow=!0;let o={...pi,...e??{}};i.shadow.mapSize.set(o.mapSize,o.mapSize),i.shadow.camera.near=o.near,i.shadow.camera.far=o.far,i.shadow.camera.left=o.left,i.shadow.camera.right=o.right,i.shadow.camera.top=o.top,i.shadow.camera.bottom=o.bottom,i.shadow.bias=o.bias,i.shadow.radius=o.radius,i.shadow.camera.updateProjectionMatrix()}function Ee(i,t,e){if(!t){i.castShadow=!1;return}i.castShadow=!0;let o={...hi,...e??{}};i.shadow.mapSize.set(o.mapSize,o.mapSize),i.shadow.camera.near=o.near,i.shadow.camera.far=o.far,i.shadow.bias=o.bias,i.shadow.radius=o.radius,i.shadow.camera.updateProjectionMatrix()}function bi(i){return new ft(i)}import{Group as Oi,Sprite as Pi,SpriteMaterial as Si,CanvasTexture as wi,LinearFilter as Ze,Color as Te,ClampToEdgeWrapping as Me}from"three";import{getCooldown as Re}from"@zylem/behaviors/cooldown";var Ci={"top-left":{fx:0,fy:0},"top-center":{fx:.5,fy:0},"top-right":{fx:1,fy:0},"center-left":{fx:0,fy:.5},center:{fx:.5,fy:.5},"center-right":{fx:1,fy:.5},"bottom-left":{fx:0,fy:1},"bottom-center":{fx:.5,fy:1},"bottom-right":{fx:1,fy:1}},De=192,vi={xs:8,sm:16,md:32,lg:48,xl:64},Zt={position:void 0,cooldown:"",iconSize:"md",fillColor:"#333333",showTimer:!0,stickToViewport:!0,screenAnchor:"top-left",screenPosition:{x:0,y:0},zDistance:1,overlayColor:"rgba(0, 0, 0, 0.65)"},_i=Symbol("CooldownIcon"),Tt=class extends c{static type=_i;_sprite=null;_texture=null;_canvas=null;_ctx=null;_cameraRef=null;_iconTexture=null;_iconImage=null;_lastRenderedProgress=-1;constructor(t){super(),this.options=Z(Zt,t),this.options.screenPosition=E(this.options.screenPosition,Zt.screenPosition),this.group=new Oi,this.createSprite(),this.prependSetup(this.iconSetup.bind(this)),this.prependUpdate(this.iconUpdate.bind(this)),this.onCleanup(this.iconDestroy.bind(this))}createSprite(){this._canvas=document.createElement("canvas"),this._canvas.width=256,this._canvas.height=256,this._ctx=this._canvas.getContext("2d"),this._texture=new wi(this._canvas),this._texture.minFilter=Ze,this._texture.magFilter=Ze,this._texture.wrapS=Me,this._texture.wrapT=Me;let e=new Si({map:this._texture,transparent:!0,depthTest:!1,depthWrite:!1});if(this._sprite=new Pi(e),this.group?.add(this._sprite),this.options.icon){let o=new Image;o.crossOrigin="anonymous",o.onload=()=>{this._iconImage=o,this.redraw(this._lastRenderedProgress>=0?this._lastRenderedProgress:1)},o.src=this.options.icon}this.redraw(1)}redraw(t){if(!this._canvas||!this._ctx)return;let e=this._ctx,o=this._canvas.width,n=this._canvas.height,s=o/2,a=n/2,r=Math.min(s,a);if(e.clearRect(0,0,o,n),this._iconImage?e.drawImage(this._iconImage,0,0,o,n):(e.fillStyle=this.toCssColor(this.options.fillColor??"#333333"),e.fillRect(0,0,o,n)),t<1){let l=(1-t)*Math.PI*2,p=-Math.PI/2,O=p+l;if(e.save(),e.fillStyle=this.options.overlayColor??"rgba(0, 0, 0, 0.65)",e.beginPath(),e.moveTo(s,a),e.arc(s,a,r+1,p,O,!1),e.closePath(),e.fill(),e.restore(),this.options.showTimer){let u=Re(this.options.cooldown);if(u){let d=Math.max(0,u.duration-u.elapsed),b=d>=10?Math.ceil(d).toString():d.toFixed(1),f=Math.floor(o*.3);e.font=`bold ${f}px sans-serif`,e.textAlign="center",e.textBaseline="middle",e.fillStyle="#FFFFFF",e.strokeStyle="#000000",e.lineWidth=2,e.strokeText(b,s,a),e.fillText(b,s,a)}}}this._texture&&(this._texture.needsUpdate=!0),this._lastRenderedProgress=t}toCssColor(t){return typeof t=="string"?t:`#${(t instanceof Te?t:new Te(t)).getHexString()}`}getResolution(){try{let t=this._cameraRef?.renderer?.domElement;if(t)return{width:t.clientWidth||1,height:t.clientHeight||1}}catch{}return{width:this._cameraRef?.screenResolution?.x??1,height:this._cameraRef?.screenResolution?.y??1}}iconSetup(t){this._sprite||this.createSprite(),this._cameraRef=t.camera,this.options.stickToViewport&&this._cameraRef&&(this._cameraRef.camera.add(this.group),this.updateStickyTransform())}iconUpdate(t){let o=Re(this.options.cooldown)?.progress??1;(Math.abs(o-this._lastRenderedProgress)>.02||o===1&&this._lastRenderedProgress!==1)&&this.redraw(o),this.options.stickToViewport&&this._cameraRef&&this.updateStickyTransform()}resolveScreenPosition(t,e){let o=this.options.screenAnchor??"top-left",n=Bt(this.options.screenPosition,It),s=n.x,a=n.y,{fx:r,fy:l}=Ci[o],p=r*t,O=l*e,u=e/De;return{px:p+s*u,py:O+a*u}}resolveIconSize(t){let e=this.options.iconSize??"md",o,n;typeof e=="string"?o=n=vi[e]:typeof e=="number"?o=n=e:(o=e.width,n=e.height);let s=t/De;return{widthPx:o*s,heightPx:n*s}}computeWorldExtents(t,e){let o=1,n=1;if(t.isPerspectiveCamera){let s=t,a=Math.tan(s.fov*Math.PI/180/2)*e;o=a*s.aspect,n=a}else if(t.isOrthographicCamera){let s=t;o=(s.right-s.left)/2,n=(s.top-s.bottom)/2}return{worldHalfW:o,worldHalfH:n}}updateStickyTransform(){if(!this._sprite||!this._cameraRef)return;let t=this._cameraRef.camera,{width:e,height:o}=this.getResolution(),{px:n,py:s}=this.resolveScreenPosition(e,o),a=Math.max(.001,this.options.zDistance??1),{worldHalfW:r,worldHalfH:l}=this.computeWorldExtents(t,a),p=n/e*2-1,O=1-s/o*2,u=p*r,d=O*l;{let f=l*2/o,{widthPx:y,heightPx:_}=this.resolveIconSize(o),g=Math.max(1e-4,y*f),h=Math.max(1e-4,_*f);this._sprite.scale.set(g,h,1)}this.group?.position.set(u,d,-a)}iconDestroy(){this._texture?.dispose(),this._sprite?.material&&this._sprite.material.dispose(),this._sprite&&this._sprite.removeFromParent(),this.group?.removeFromParent(),this._iconTexture?.dispose(),this._sprite=null,this._texture=null,this._canvas=null,this._ctx=null,this._cameraRef=null,this._iconTexture=null,this._iconImage=null}};function Ie(...i){let t=i.filter(o=>!(o instanceof Dt)),e={...Zt};for(let o of t)e={...e,...o};return x(new Tt(e),o=>Ie(o??{}))}function Ei(i,t,e){e({me:i,globals:t})}function Zi(i,t){let e=t??Rt();Ei(i,e,i.nodeDestroy.bind(i))}export{Q as a,J as b,tt as c,et as d,it as e,ot as f,At as g,nt as h,Vt as i,Nt as j,st as k,Wt as l,$t as m,B as n,Kt as o,Jt as p,lt as q,te as r,re as s,k as t,ae as u,ce as v,F as w,pe as x,me as y,ht as z,ue as A,ye as B,mt as C,fe as D,xe as E,ut as F,be as G,Pe as H,dt as I,Se as J,we as K,yt as L,ei as M,ve as N,ft as O,bi as P,Ie as Q,Zi as R};
@@ -0,0 +1 @@
1
+ import{b as d,p as b,q as V,r as y,t as D,u as C,v as B,x as v}from"./chunk-3I537JFL.js";import{c as k}from"./chunk-CM5YRNBJ.js";import{c as m,d as f,h as u,i as E,j as x}from"./chunk-7WRQ2UAN.js";import{Color as $,Group as lt,Sprite as ct,SpriteMaterial as ht,CanvasTexture as U,LinearFilter as w,Vector2 as mt,ClampToEdgeWrapping as H}from"three";import{MeshStandardMaterial as rt,MeshBasicMaterial as ot,MeshPhongMaterial as at}from"three";function pt(i){return i&&typeof i.getDebugInfo=="function"}var c=class{entity;constructor(t){this.entity=t}getPositionString(){if(this.entity.mesh){let{x:r,y:s,z:o}=this.entity.mesh.position;return`${r.toFixed(2)}, ${s.toFixed(2)}, ${o.toFixed(2)}`}let{x:t,y:e,z:n}=this.entity.options.position||{x:0,y:0,z:0};return`${t.toFixed(2)}, ${e.toFixed(2)}, ${n.toFixed(2)}`}getRotationString(){if(this.entity.mesh){let{x:s,y:o,z:a}=this.entity.mesh.rotation,p=l=>(l*180/Math.PI).toFixed(1);return`${p(s)}\xB0, ${p(o)}\xB0, ${p(a)}\xB0`}let{x:t,y:e,z:n}=this.entity.options.rotation||{x:0,y:0,z:0},r=s=>(s*180/Math.PI).toFixed(1);return`${r(t)}\xB0, ${r(e)}\xB0, ${r(n)}\xB0`}getMaterialInfo(){if(!this.entity.mesh||!this.entity.mesh.material)return{type:"none"};let t=Array.isArray(this.entity.mesh.material)?this.entity.mesh.material[0]:this.entity.mesh.material,e={type:t.type};return(t instanceof rt||t instanceof ot||t instanceof at)&&(e.color=`#${t.color.getHexString()}`,e.opacity=t.opacity,e.transparent=t.transparent),"roughness"in t&&(e.roughness=t.roughness),"metalness"in t&&(e.metalness=t.metalness),e}getPhysicsInfo(){if(!this.entity.body)return null;let t={type:this.entity.body.bodyType(),mass:this.entity.body.mass(),isEnabled:this.entity.body.isEnabled(),isSleeping:this.entity.body.isSleeping()},e=this.entity.body.linvel();return t.velocity=`${e.x.toFixed(2)}, ${e.y.toFixed(2)}, ${e.z.toFixed(2)}`,t}buildDebugInfo(){let t={name:this.entity.name||this.entity.uuid,uuid:this.entity.uuid,position:this.getPositionString(),rotation:this.getRotationString(),material:this.getMaterialInfo()},e=this.getPhysicsInfo();if(e&&(t.physics=e),pt(this.entity)){let n=this.entity.getDebugInfo();return{...t,...n}}return t}};var g={position:void 0,text:"",fontFamily:'Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace',fontSize:18,fontColor:"#FFFFFF",backgroundColor:null,padding:4,stickToViewport:!0,screenPosition:new mt(24,24),zDistance:1},O=class extends v{createEntity(t){return new S(t)}},ut=Symbol("Text"),S=class i extends y{static type=ut;_sprite=null;_texture=null;_canvas=null;_ctx=null;_cameraRef=null;_lastCanvasW=0;_lastCanvasH=0;constructor(t){super(),this.options=d(g,t),this.options.screenPosition=E(this.options.screenPosition,g.screenPosition),this.prependSetup(this.textSetup.bind(this)),this.prependUpdate(this.textUpdate.bind(this)),this.onCleanup(this.textDestroy.bind(this))}create(){return this._sprite=null,this._texture=null,this._canvas=null,this._ctx=null,this._lastCanvasW=0,this._lastCanvasH=0,this.group=new lt,this.createSprite(),super.create()}createSprite(){this._canvas=document.createElement("canvas"),this._ctx=this._canvas.getContext("2d"),this._texture=new U(this._canvas),this._texture.minFilter=w,this._texture.magFilter=w;let t=new ht({map:this._texture,transparent:!0,depthTest:!1,depthWrite:!1,alphaTest:.5});this._sprite=new ct(t),this.group?.add(this._sprite),this.redrawText(this.options.text??"")}measureAndResizeCanvas(t,e,n,r){if(!this._canvas||!this._ctx)return{sizeChanged:!1};this._ctx.font=`${e}px ${n}`;let s=this._ctx.measureText(t),o=Math.ceil(s.width),a=Math.ceil(e*1.4),p=Math.max(2,o+r*2),l=Math.max(2,a+r*2),T=p!==this._lastCanvasW||l!==this._lastCanvasH;return this._canvas.width=p,this._canvas.height=l,this._lastCanvasW=p,this._lastCanvasH=l,{sizeChanged:T}}drawCenteredText(t,e,n){!this._canvas||!this._ctx||(this._ctx.font=`${e}px ${n}`,this._ctx.textAlign="center",this._ctx.textBaseline="middle",this._ctx.clearRect(0,0,this._canvas.width,this._canvas.height),this.options.backgroundColor&&(this._ctx.fillStyle=this.toCssColor(this.options.backgroundColor),this._ctx.fillRect(0,0,this._canvas.width,this._canvas.height)),this._ctx.fillStyle=this.toCssColor(this.options.fontColor??"#FFFFFF"),this._ctx.fillText(t,this._canvas.width/2,this._canvas.height/2))}updateTexture(t){!this._texture||!this._canvas||(t&&(this._texture.dispose(),this._texture=new U(this._canvas),this._texture.minFilter=w,this._texture.magFilter=w,this._texture.wrapS=H,this._texture.wrapT=H),this._texture.image=this._canvas,this._texture.needsUpdate=!0,this._sprite&&this._sprite.material&&(this._sprite.material.map=this._texture,this._sprite.material.needsUpdate=!0))}redrawText(t){if(!this._canvas||!this._ctx)return;let e=this.options.fontSize??18,n=this.options.fontFamily??g.fontFamily,r=this.options.padding??4,{sizeChanged:s}=this.measureAndResizeCanvas(t,e,n,r);this.drawCenteredText(t,e,n),this.updateTexture(!!s),this.options.stickToViewport&&this._cameraRef?this.updateStickyTransform():this.updateWorldSpriteScale()}toCssColor(t){return typeof t=="string"?t:`#${(t instanceof $?t:new $(t)).getHexString()}`}textSetup(t){this._cameraRef=t.camera,this.options.stickToViewport&&this._cameraRef&&(this._cameraRef.camera.add(this.group),this.updateStickyTransform())}textUpdate(t){this._sprite&&this.options.stickToViewport&&this._cameraRef&&this.updateStickyTransform()}getResolution(){return{width:this._cameraRef?.screenResolution.x??1,height:this._cameraRef?.screenResolution.y??1}}getScreenPixels(t,e,n){let r=t.x>=0&&t.x<=1,s=t.y>=0&&t.y<=1;return{px:r?t.x*e:t.x,py:s?t.y*n:t.y}}computeWorldExtents(t,e){let n=1,r=1;if(t.isPerspectiveCamera){let s=t,o=Math.tan(s.fov*Math.PI/180/2)*e;n=o*s.aspect,r=o}else if(t.isOrthographicCamera){let s=t;n=(s.right-s.left)/2,r=(s.top-s.bottom)/2}return{worldHalfW:n,worldHalfH:r}}updateSpriteScale(t,e){if(!this._canvas||!this._sprite)return;let r=t*2/e,s=this._canvas.height,o=Math.max(1e-4,s*r),a=this._canvas.width/this._canvas.height,p=o*a;this._sprite.scale.set(p,o,1)}updateWorldSpriteScale(){if(!this._canvas||!this._sprite)return;let t=this._canvas.width/Math.max(1,this._canvas.height),e=Math.max(1,this.options.fontSize??18),n=Math.max(.25,e/32),r=n*t;this._sprite.scale.set(r,n,1)}updateStickyTransform(){if(!this._sprite||!this._cameraRef)return;let t=this._cameraRef.camera,{width:e,height:n}=this.getResolution(),r=E(this.options.screenPosition,g.screenPosition),{px:s,py:o}=this.getScreenPixels(r,e,n),a=Math.max(.001,this.options.zDistance??1),{worldHalfW:p,worldHalfH:l}=this.computeWorldExtents(t,a),T=s/e*2-1,it=1-o/n*2,nt=T*p,st=it*l;this.group?.position.set(nt,st,-a),this.updateSpriteScale(l,n)}updateText(t){this.options.text=t,this.redrawText(t),this.options.stickToViewport&&this._cameraRef&&this.updateStickyTransform()}buildInfo(){return{...new c(this).buildDebugInfo(),type:String(i.type),text:this.options.text??"",sticky:this.options.stickToViewport}}textDestroy(){this._texture?.dispose(),this._sprite?.material&&this._sprite.material.dispose(),this._sprite&&this._sprite.removeFromParent(),this.group?.removeFromParent(),this._sprite=null,this._texture=null,this._canvas=null,this._ctx=null,this._cameraRef=null}};function F(...i){return C({args:i,defaultConfig:{...g},EntityClass:S,BuilderClass:O,entityType:S.type,cloneFactory:t=>F(t??{})})}import{Euler as dt,Group as W,Quaternion as yt,Vector3 as ft}from"three";import{TextureLoader as X,SpriteMaterial as N,Sprite as Y,SRGBColorSpace as j}from"three";import{ClampToEdgeWrapping as Q,LinearFilter as xt,NearestFilter as gt}from"three";var q={...b,size:new ft(1,1,1),images:[],animations:[]},I=class extends B{collider(t){let e=x(t.collisionSize,t.size??f);return{shape:{type:"box",halfExtents:[e.x/2,e.y/2,e.z/2]}}}},R=class extends v{createEntity(t){return new _(t)}},St=Symbol("Sprite"),_=class i extends y{static type=St;sprites=[];spriteMap=new Map;currentSpriteIndex=0;animations=new Map;currentAnimation=null;currentAnimationFrame="";currentAnimationIndex=0;currentAnimationTime=0;sheetTexture=null;flippedX=!1;constructor(t){super(),this.options=d(q,t),this.prependSetup(this.spriteSetup.bind(this)),this.prependUpdate(this.spriteUpdate.bind(this)),this.onCleanup(this.spriteDestroy.bind(this))}create(){return this.sprites=[],this.spriteMap.clear(),this.animations.clear(),this.currentAnimation=null,this.currentAnimationFrame="",this.currentAnimationIndex=0,this.currentAnimationTime=0,this.sheetTexture=null,this.group=void 0,this.options?.sheet?this.createSpriteFromSheet(this.options.sheet):this.createSpritesFromImages(this.options?.images||[]),this.createAnimations(this.options?.animations||[]),super.create()}createSpritesFromImages(t){let e=new X,n=x(this.options.size,f);t.forEach((r,s)=>{let o=e.load(r.file);o.colorSpace=j,o.anisotropy=k;let a=new N({map:o,transparent:!0}),p=new Y(a);p.position.normalize(),p.scale.set(n.x,n.y,n.z),p.visible=s===0,this.sprites.push(p),this.spriteMap.set(r.name,s)}),this.group=new W,this.group.add(...this.sprites)}createSpriteFromSheet(t){let e=x(this.options.size,f),n=new X().load(t.file);n.colorSpace=j,n.wrapS=Q,n.wrapT=Q;let r=t.filter==="linear"?xt:gt;n.magFilter=r,n.minFilter=r,n.generateMipmaps=!1,n.repeat.set(1/t.columns,1/t.rows);let s=new N({map:n,transparent:!0}),o=new Y(s);o.position.normalize(),o.scale.set(e.x,e.y,e.z),this.sheetTexture=n,this.sprites.push(o),t.frames.forEach((p,l)=>{p&&this.spriteMap.set(p,l)}),this.group=new W,this.group.add(o);let a=t.frames.find(p=>!!p);a&&this.setSprite(a)}createAnimations(t){t.forEach(e=>{let{name:n,frames:r,loop:s=!1,speed:o=1}=e,a={frames:r.map((p,l)=>({key:p,index:l,duration:typeof o=="number"?o:o[l]})),loop:s};this.animations.set(n,a)})}setSprite(t){let n=this.spriteMap.get(t)??0;if(this.currentSpriteIndex=n,this.sheetTexture){this.applySheetFrame(n);return}this.sprites.forEach((r,s)=>{r.visible=this.currentSpriteIndex===s})}setFlipX(t){if(this.flippedX!==t){if(this.flippedX=t,this.sheetTexture){this.applySheetFrame(this.currentSpriteIndex);return}this.sprites.forEach(e=>{e.material.map?.repeat.setX(t?-1:1),e.material.map?.offset.setX(t?1:0)})}}isFlippedX(){return this.flippedX}applySheetFrame(t){let e=this.options.sheet,n=this.sheetTexture;if(!e||!n)return;let r=t%e.columns,s=Math.floor(t/e.columns),o=1/e.columns,a=1/e.rows;n.repeat.x=this.flippedX?-o:o,n.offset.x=this.flippedX?(r+1)*o:r*o,n.offset.y=1-(s+1)*a}setAnimation(t,e){let n=this.animations.get(t);if(!n)return;let{loop:r,frames:s}=n;if(s.length!==0){for(t!==this.currentAnimation?(this.currentAnimation=t,this.currentAnimationIndex=0,this.currentAnimationTime=0):this.currentAnimationTime+=e;;){let o=s[this.currentAnimationIndex].duration;if(!(o>0)||this.currentAnimationTime<o)break;if(this.currentAnimationTime-=o,this.currentAnimationIndex+1<s.length)this.currentAnimationIndex++;else if(r)this.currentAnimationIndex=0;else{this.currentAnimationTime=0;break}}this.currentAnimationFrame=s[this.currentAnimationIndex].key,this.setSprite(this.currentAnimationFrame)}}getCurrentRotationQuaternion(){return this.transformStore?.dirty.rotation?this.transformStore.rotation:this.body?.rotation?.()??null}syncSpriteMaterials(){let t=this.getCurrentRotationQuaternion();this.sprites.forEach(e=>{if(e.material&&t){let r=new yt(t.x,t.y,t.z,t.w),s=new dt().setFromQuaternion(r,"XYZ");e.material.rotation=s.z}let n=x(this.options.size,f);e.scale.set(n.x,n.y,n.z)})}spriteSetup(t){this.syncSpriteMaterials()}spriteUpdate(t){this.syncSpriteMaterials()}spriteDestroy(t){this.sprites.forEach(e=>{e.removeFromParent()}),this.group?.remove(...this.sprites),this.group?.removeFromParent(),this.sheetTexture?.dispose(),this.sheetTexture=null}buildInfo(){return{...new c(this).buildDebugInfo(),type:String(i.type)}}};function z(...i){return C({args:i,defaultConfig:q,EntityClass:_,BuilderClass:R,CollisionBuilderClass:I,entityType:_.type,cloneFactory:t=>z(t??{})})}import{Color as tt,Group as bt}from"three";import{Line2NodeMaterial as Ct}from"three/webgpu";import{Line2 as vt}from"three/addons/lines/webgpu/Line2.js";import{Color as J}from"three";import{LineGeometry as _t}from"three/addons/lines/LineGeometry.js";function P(i){let t=[];for(let e of i){let{x:n,y:r,z:s}=u(e,m);t.push(n,r,s)}return t}function L(i,t,e){if(!i||i.length===0)return;let n=[],r=new J(e);for(let s=0;s<t;s++){let o=i[s]??i[i.length-1]??e,a=new J(o??r);n.push(a.r,a.g,a.b)}return n}function K(i){let t=new _t,e=P(i.points);t.setPositions(e);let n=L(i.colors,i.points.length,"#ffffff");return n&&t.setColors(n),t}var h={...b,points:[{x:0,y:0,z:0},{x:1,y:0,z:0}],linewidth:1,worldUnits:!0,alphaToCoverage:!1,opacity:1,transparent:!1,dashed:!1,dashSize:1,gapSize:1,pickThreshold:0},wt=Symbol("Line");function M(i,t){if(!i||i.length<2)throw new Error(`${t}: at least two points are required`);return i}function et(i){return i instanceof tt?i.clone():new tt(i??"#ffffff")}function Tt(i){let t=!!i.colors?.length,e=new Ct({color:et(i.color).getHex(),linewidth:i.linewidth??h.linewidth,worldUnits:i.worldUnits??h.worldUnits,vertexColors:t,dashed:i.dashed??!1,dashSize:i.dashSize??h.dashSize,gapSize:i.gapSize??h.gapSize,transparent:i.transparent??!1,opacity:i.opacity??1});return e.alphaToCoverage=i.alphaToCoverage??!1,e}function Et(i){return!i.point||!i.pointOnLine||i.faceIndex==null?null:{point:i.point.clone(),pointOnLine:i.pointOnLine.clone(),faceIndex:i.faceIndex,distance:i.distance}}function Ot(i,t,e={}){let n=t.getLineObject();if(!n)return null;let r=e.threshold??t.options.pickThreshold??0,s=i.params.Line2??{threshold:0};s.threshold=r,i.params.Line2=s;let a=i.intersectObject(n,!1)[0];return a?Et(a):null}var Z=class i extends y{static type=wt;_line=null;_geometry=null;_material=null;constructor(t){super();let e=d(h,t);e.points=M(e.points,"ZylemLine").map(n=>u(n,m)),this.options=e}create(){return this.disposeLineResources(),this.group=new bt,this.rebuildLine(),this.applyGroupPosition(),super.create()}setPoints(t,e){if(M(t,"setPoints"),this.options.points=t.map(r=>u(r,m)),e&&(this.options.colors=e),!this._line||!this._geometry||!this._material)return this;this._geometry.setPositions(P(this.options.points));let n=L(this.options.colors,this.options.points.length,et(this.options.color));return n&&this._geometry.setColors(n),this._material.vertexColors=!!this.options.colors?.length,this.options.dashed&&this._line.computeLineDistances(),this._geometry.computeBoundingBox(),this._geometry.computeBoundingSphere(),this}getLineObject(){return this._line}pickFromRaycaster(t,e={}){return Ot(t,this,e)}buildInfo(){return{...new c(this).buildDebugInfo(),type:String(i.type),points:this.options.points.length,linewidth:this.options.linewidth??h.linewidth,worldUnits:this.options.worldUnits??h.worldUnits}}rebuildLine(){this._geometry=K({points:this.options.points,colors:this.options.colors}),this._material=Tt(this.options),this._line=new vt(this._geometry,this._material),this.options.dashed&&this._line.computeLineDistances(),this.group?.add(this._line)}applyGroupPosition(){if(!this.group)return;let t=u(this.options.position,m);this.group.position.set(t.x,t.y,t.z)}_cleanup(t){this.disposeLineResources(),super._cleanup(t)}disposeLineResources(){this._line?.removeFromParent(),this._geometry?.dispose(),this._material?.dispose(),this._line=null,this._geometry=null,this._material=null}};function A(...i){let t=V(i,h);M(t.points,"createLine");let e=new Z(t);return D(e,n=>A(n??{}))}var G={registry:new Map,register(i,t){this.registry.set(i,t)},createFromBlueprint(i){let t=this.registry.get(i.type);if(!t)throw new Error(`Unknown entity type: ${i.type}`);let e={...i.data,position:i.position?{x:i.position[0],y:i.position[1],z:0}:void 0,name:i.id};return t(e)}};G.register("text",i=>F(i));G.register("sprite",i=>z(i));G.register("line",i=>A(i));function we(i){return{template:i,generate(t){let e=[];for(let n=0;n<t;n++)e.push(i.clone());return e}}}export{c as a,ut as b,S as c,F as d,St as e,_ as f,z as g,wt as h,Ot as i,Z as j,A as k,G as l,we as m};
@@ -0,0 +1,9 @@
1
+ import{a as s,e as o,g as a}from"./chunk-W5SXED5T.js";import{announceBridgeReady as c}from"@zylem/bridge";var n=class r extends HTMLElement{_game=null;_state={};container;resizeObserver=null;_viewportProfile="auto";static HOST_CONFIG_MARKER=Symbol("zylem:host-config");constructor(){super(),this.attachShadow({mode:"open"});let e=document.createElement("style");e.textContent=`
2
+ :host {
3
+ display: block;
4
+ width: 100%;
5
+ height: 100%;
6
+ min-width: 0;
7
+ min-height: 0;
8
+ }
9
+ `,this.container=document.createElement("div"),this.container.style.width="100%",this.container.style.height="100%",this.container.style.position="relative",this.container.style.outline="none",this.container.tabIndex=0,this.shadowRoot.append(e,this.container)}focus(){this.container.focus()}connectedCallback(){typeof ResizeObserver<"u"&&!this.resizeObserver&&(this.resizeObserver=new ResizeObserver(()=>{this.syncDisplayRuntime()}),this.resizeObserver.observe(this)),this.syncDisplayRuntime()}set game(e){this._game&&this._game.dispose(),this._game=e,this.attachHostContainer(e),this.syncDisplayRuntime(),e.start(),c(this)}get game(){return this._game}set state(e){this._state=e,this.syncDebugState(),this.syncToolbarState()}get state(){return this._state}set viewportProfile(e){let t=e==="mobile"||e==="desktop"?e:"auto";this._viewportProfile!==t&&(this._viewportProfile=t,this.syncDisplayRuntime())}get viewportProfile(){return this._viewportProfile}static get observedAttributes(){return["viewport-profile"]}attributeChangedCallback(e,t,i){e==="viewport-profile"&&(this.viewportProfile=i??"auto")}syncDebugState(){let e=this._state.gameState?.debugFlag;e!==void 0&&(s.enabled=e)}syncToolbarState(){let{tool:e,paused:t}=this._state.toolbarState??{};e!==void 0&&a(e),t!==void 0&&o(t)}disconnectedCallback(){this.resizeObserver?.disconnect(),this.resizeObserver=null,this._game&&(this._game.dispose(),this._game=null)}attachHostContainer(e){let t=r.HOST_CONFIG_MARKER,i=e.options.find(l=>!!l?.[t]);if(i){i.container=this.container;return}e.options.push({container:this.container,[t]:!0})}syncDisplayRuntime(){if(!this._game)return;let e=this.getBoundingClientRect(),t=Math.round(e.width||this.clientWidth||0),i=Math.round(e.height||this.clientHeight||0);this._game.setDisplayRuntime({deviceProfile:this._viewportProfile,viewportSize:t>0&&i>0?{width:t,height:i}:void 0})}};customElements.define("zylem-game",n);export{n as a};
@@ -0,0 +1,19 @@
1
+ import{a as g}from"./chunk-C5NEGC3S.js";import{AmbientLight as k,Object3D as R,PerspectiveCamera as U,RenderTarget as T,Scene as C,Color as O,LinearFilter as w,SpotLight as P,Vector3 as v}from"three";function d(a,e,t,i={}){let s=e*4,r=new Uint8ClampedArray(t*s),n=null;if(i.srgb){n=new Uint8Array(256);for(let o=0;o<256;o+=1){let c=o/255,u=c<=.0031308?c*12.92:1.055*Math.pow(c,1/2.4)-.055;n[o]=Math.round(Math.max(0,Math.min(1,u))*255)}}for(let o=0;o<t;o+=1){let c=(i.flipY?t-1-o:o)*s,u=o*s;if(n===null){r.set(a.subarray(c,c+s),u);continue}for(let l=0;l<s;l+=4)r[u+l]=n[a[c+l]],r[u+l+1]=n[a[c+l+1]],r[u+l+2]=n[a[c+l+2]],r[u+l+3]=a[c+l+3]}return r}var x=`
2
+ const encodeReadbackPixels = ${d.toString()};
3
+
4
+ self.onmessage = async (event) => {
5
+ const { id, buffer, width, height, options } = event.data;
6
+ try {
7
+ const src = new Uint8ClampedArray(buffer);
8
+ const pixels = encodeReadbackPixels(src, width, height, options);
9
+ const canvas = new OffscreenCanvas(width, height);
10
+ const ctx = canvas.getContext('2d');
11
+ if (!ctx) throw new Error('OffscreenCanvas 2d context unavailable');
12
+ ctx.putImageData(new ImageData(pixels, width, height), 0, 0);
13
+ const blob = await canvas.convertToBlob({ type: 'image/png' });
14
+ self.postMessage({ id, blob });
15
+ } catch (error) {
16
+ self.postMessage({ id, error: String(error) });
17
+ }
18
+ };
19
+ `,h=class{worker=null;workerFailed=!1;nextId=1;pending=new Map;isSupported(){return!this.workerFailed&&typeof Worker<"u"&&typeof OffscreenCanvas<"u"&&typeof URL<"u"&&typeof Blob<"u"}async encodeThumbnail(e,t,i,s={}){if(!this.isSupported())return null;let r=this.ensureWorker();if(!r)return null;let n=new Uint8Array(e.byteLength);n.set(e instanceof Uint8Array?e:new Uint8Array(e.buffer,e.byteOffset,e.byteLength));let o=this.nextId++;try{let c=await new Promise((u,l)=>{this.pending.set(o,{resolve:u,reject:l}),r.postMessage({id:o,buffer:n.buffer,width:t,height:i,options:s},[n.buffer])});return URL.createObjectURL(c)}catch{return null}}dispose(){this.worker&&(this.worker.terminate(),this.worker=null);for(let{reject:e}of this.pending.values())e(new Error("EntityPayloadWorker disposed"));this.pending.clear()}ensureWorker(){if(this.worker)return this.worker;try{let e=new Blob([x],{type:"text/javascript"}),t=URL.createObjectURL(e),i=new Worker(t,{type:"module"});return URL.revokeObjectURL(t),i.onmessage=s=>{let{id:r}=s.data,n=this.pending.get(r);n&&(this.pending.delete(r),"blob"in s.data?n.resolve(s.data.blob):n.reject(new Error(s.data.error)))},i.onerror=()=>{this.workerFailed=!0,this.dispose()},this.worker=i,i}catch{return this.workerFailed=!0,null}}},y=new h;var W=128,S=256,M=1,E=32,p=class{cache=new Map;inFlight=new Map;renderer=null;size;maxEntries;queue=[];activeRenders=0;constructor(e=W,t=S){this.size=e,this.maxEntries=t}setRenderer(e){this.renderer=e}get(e){let t=this.cache.get(e);return t?(this.touch(e,t),t):null}invalidate(e){this.cache.delete(e),this.inFlight.delete(e),this.queue=this.queue.filter(t=>t.uuid!==e?!0:(t.resolve(null),!1))}clear(){this.cache.clear(),this.inFlight.clear();for(let e of this.queue)e.resolve(null);this.queue=[]}get cacheSize(){return this.cache.size}get pendingCount(){return this.queue.length}async ensure(e,t){let i=this.cache.get(e);if(i)return this.touch(e,i),i;let s=this.inFlight.get(e);if(s)return s;if(!t||!this.renderer)return null;let r=new Promise(n=>{if(this.queue.push({uuid:e,object:t,resolve:n}),this.queue.length>E){let o=this.queue.splice(0,this.queue.length-E);for(let c of o)this.inFlight.delete(c.uuid),c.resolve(null)}this.drainQueue()});return this.inFlight.set(e,r),r}drainQueue(){for(;this.activeRenders<M&&this.queue.length>0;){let e=this.queue.shift();if(!e)return;this.activeRenders+=1,this.render(e.uuid,e.object).then(t=>{t&&(this.cache.set(e.uuid,t),this.evictOverflow()),e.resolve(t)}).catch(t=>{console.warn("EntityThumbnailCache: failed to render thumbnail",e.uuid,t),e.resolve(null)}).finally(()=>{this.activeRenders-=1,this.inFlight.delete(e.uuid),this.drainQueue()})}}touch(e,t){this.cache.delete(e),this.cache.set(e,t)}evictOverflow(){for(;this.cache.size>this.maxEntries;){let e=this.cache.keys().next();if(e.done)return;this.cache.delete(e.value)}}async render(e,t){let i=this.renderer;if(!i)return null;let s=new C;s.background=new O(3815994);let r=t.clone(!0);r.position.set(0,0,0),r.rotation.set(0,0,0),r.updateMatrixWorld(!0),s.add(r);let n=new U(50,1,.1,100),o=g(r,n);F(s,n,o);let c=new T(this.size,this.size,{minFilter:w,magFilter:w}),u=i.getRenderTarget(),l=i.getScissorTest();try{i.setScissorTest(!1),i.setRenderTarget(c),i.render(s,n)}finally{i.setRenderTarget(u),i.setScissorTest(l)}let f=await i.readRenderTargetPixelsAsync(c,0,0,this.size,this.size);c.dispose(),s.remove(r);let b={flipY:A(i),srgb:!0},m=await y.encodeThumbnail(f,this.size,this.size,b)??D(f,this.size,this.size,b);return m?{uuid:e,dataUrl:m,bounds:{width:o.width,height:o.height,depth:o.depth}}:null}},Q=new p;function A(a){return a?.backend?.isWebGLBackend===!0}function F(a,e,t){a.add(new k(16777215,.7)),e.updateMatrixWorld(!0);let i=new v().setFromMatrixColumn(e.matrixWorld,0),s=new v().setFromMatrixColumn(e.matrixWorld,1),r=e.position.distanceTo(t.center)||1,n=new P(16777215,5);n.position.copy(e.position).addScaledVector(i,r*.35).addScaledVector(s,r*.45),n.decay=0,n.distance=0,n.penumbra=.5,n.angle=L(Math.atan(t.maxDim/r)+.25,.4,Math.PI/3),n.castShadow=!1;let o=new R;o.position.copy(t.center),a.add(o),n.target=o,a.add(n)}function L(a,e,t){return Math.min(t,Math.max(e,a))}function D(a,e,t,i={}){if(typeof document>"u")return null;let s=document.createElement("canvas");s.width=e,s.height=t;let r=s.getContext("2d");if(!r)return null;let n=a instanceof Uint8Array?a:new Uint8Array(a.buffer,a.byteOffset,a.byteLength),o=r.createImageData(e,t);return o.data.set(d(n,e,t,i)),r.putImageData(o,0,0),s.toDataURL("image/png")}export{p as a,Q as b};
@@ -0,0 +1 @@
1
+ import{proxy as u}from"valtio/vanilla";var e=u({enabled:!1,paused:!1,tool:"none",selectedEntityId:null,hoveredEntityId:null,flags:new Set}),o=null;function a(t){return o=t,()=>{o===t&&(o=null)}}function l(t){return!t||!o?null:o(t)}function i(t,n){if(t==null)return null;if(typeof t=="string")return t;let r=t.uuid;if(typeof r=="string")return console.warn(`${n}: received a live entity. Pass the UUID instead \u2014 storing entities in debugState makes valtio deep-proxy the scene graph.`),r;throw new TypeError(`${n} expects an entity UUID string or null, received ${typeof t}.`)}function g(){return e.paused}function c(t){e.paused=t}function E(){return e.tool}function p(t){e.tool=t}function f(){return e.selectedEntityId}function d(t){let n=i(t,"setSelectedEntityId");e.selectedEntityId!==n&&(e.selectedEntityId=n)}function v(){return e.hoveredEntityId}function s(t){let n=i(t,"setHoveredEntityId");e.hoveredEntityId!==n&&(e.hoveredEntityId=n)}function x(){s(null)}function b(){return l(e.selectedEntityId)}function I(){return l(e.hoveredEntityId)}function D(t){d(i(t,"setSelectedEntity"))}export{e as a,a as b,l as c,g as d,c as e,E as f,p as g,f as h,d as i,v as j,s as k,x as l,b as m,I as n,D as o};
@@ -1 +1 @@
1
- import{Quaternion as v}from"three";import{Quaternion as p}from"three";var h=new WeakMap,m=new p,x=new p,c=new p;function f(t){return{x:t.x,y:t.y,z:t.z}}function b(t){return{x:t.x,y:t.y,z:t.z,w:t.w}}function r(t){return{position:f(t.position),rotation:b(t.rotation)}}function u(t){return Number.isFinite(t)?Math.max(0,Math.min(1,t)):0}function l(t){return{position:f(t.translation()),rotation:b(t.rotation())}}function g(t){let e=r(t);return{previous:r(e),current:e}}function w(t){let e=l(t),o=h.get(t)??g(e);return o.previous=r(e),o.current=r(e),h.set(t,o),o}function d(t,e,o){let s=u(o);return m.set(t.rotation.x,t.rotation.y,t.rotation.z,t.rotation.w),x.set(e.rotation.x,e.rotation.y,e.rotation.z,e.rotation.w),c.slerpQuaternions(m,x,s),{position:{x:t.position.x+(e.position.x-t.position.x)*s,y:t.position.y+(e.position.y-t.position.y)*s,z:t.position.z+(e.position.z-t.position.z)*s},rotation:{x:c.x,y:c.y,z:c.z,w:c.w}}}function k(t,e){if(R(t))return t.getRenderPose(e);let o=h.get(t);if(!o)return l(t);let s=l(t);if(!H(s,o.current)){let n=w(t);return r(n.current)}return d(o.previous,o.current,e)}function R(t){return t!=null&&typeof t=="object"&&typeof t.getPoseHistory=="function"&&typeof t.getRenderPose=="function"}function H(t,e){return t.position.x===e.position.x&&t.position.y===e.position.y&&t.position.z===e.position.z&&t.rotation.x===e.rotation.x&&t.rotation.y===e.rotation.y&&t.rotation.z===e.rotation.z&&t.rotation.w===e.rotation.w}var P={x:0,y:0,z:0},a=new v,z=new v,S=class t{constructor(e,o,s){this.simulation=e;this.handle=o;this.clock=s;this.interpolationValidAfterStep=s.steps+2}poseScratch={position:[0,0,0],rotation:[0,0,0,1]};renderScratch={position:[0,0,0],rotation:[0,0,0,1],scale:1,custom:[0,0,0,0],isSleeping:!1};previousScratch={position:[0,0,0],rotation:[0,0,0,1],scale:1,custom:[0,0,0,0],isSleeping:!1};interpolationValidAfterStep;markPoseDiscontinuity(){this.interpolationValidAfterStep=this.clock.steps+2}isInterpolationStale(){return this.clock.steps<this.interpolationValidAfterStep}translation(){let e=this.simulation.getPose(this.handle,this.poseScratch);return e?{x:e.position[0],y:e.position[1],z:e.position[2]}:{...P}}rotation(){let e=this.simulation.getPose(this.handle,this.poseScratch);return e?{x:e.rotation[0],y:e.rotation[1],z:e.rotation[2],w:e.rotation[3]}:{x:0,y:0,z:0,w:1}}linvel(){let e=this.simulation.getLinearVelocity(this.handle);return e?{x:e[0],y:e[1],z:e[2]}:{...P}}angvel(){let e=this.simulation.adapter.getAngularVelocity(this.handle.slot);return e?{x:e[0],y:e[1],z:e[2]}:{...P}}setTranslation(e,o=!0){this.simulation.setPosition(this.handle,e.x,e.y,e.z),this.markPoseDiscontinuity()}setRotation(e,o=!0){this.simulation.setRotation(this.handle,e.x,e.y,e.z,e.w),this.markPoseDiscontinuity()}setLinvel(e,o=!0){this.simulation.setLinearVelocity(this.handle,e.x,e.y,e.z)}setAngvel(e,o=!0){this.simulation.setAngularVelocity(this.handle,e.x,e.y,e.z)}applyImpulse(e,o=!0){this.simulation.applyImpulse(this.handle,e.x,e.y,e.z)}lockRotations(e,o=!0){e&&this.setAngvel({x:0,y:0,z:0})}lockTranslations(e,o=!0){e&&this.setLinvel({x:0,y:0,z:0})}setLinearDamping(e){}setGravityScale(e,o=!0){}bodyInfo(){return this.simulation.getBodyInfo(this.handle)}bodyType(){return this.bodyInfo()?.bodyType??0}mass(){return this.bodyInfo()?.mass??0}isSleeping(){return this.bodyInfo()?.isSleeping??!1}isEnabled(){return this.bodyInfo()?.isEnabled??!0}livePose(){let e=this.simulation.getPose(this.handle,this.poseScratch);return e?{position:{x:e.position[0],y:e.position[1],z:e.position[2]},rotation:{x:e.rotation[0],y:e.rotation[1],z:e.rotation[2],w:e.rotation[3]}}:{position:{...P},rotation:{x:0,y:0,z:0,w:1}}}static slotToPose(e){return{position:{x:e.position[0],y:e.position[1],z:e.position[2]},rotation:{x:e.rotation[0],y:e.rotation[1],z:e.rotation[2],w:e.rotation[3]}}}getPoseHistory(){if(this.isInterpolationStale()){let i=this.livePose();return{previous:r(i),current:i}}let e=this.simulation.readRenderSlot(this.handle,this.renderScratch),o=this.simulation.readPreviousRenderSlot(this.handle,this.previousScratch),s=e?t.slotToPose(e):this.livePose();return{previous:o?t.slotToPose(o):r(s),current:s}}getRenderPose(e){let o=this.getPoseHistory();return d(o.previous,o.current,e)}isRenderSleeping(){return this.simulation.readRenderSlot(this.handle,this.renderScratch)?.isSleeping===!0}writeRenderPose(e,o,s){if(this.isInterpolationStale()){this.writeLivePose(o,s);return}let n=this.simulation.readRenderSlot(this.handle,this.renderScratch);if(!n){this.writeLivePose(o,s);return}let i=this.simulation.readPreviousRenderSlot(this.handle,this.previousScratch)??n,y=u(e);o.x=i.position[0]+(n.position[0]-i.position[0])*y,o.y=i.position[1]+(n.position[1]-i.position[1])*y,o.z=i.position[2]+(n.position[2]-i.position[2])*y,a.set(i.rotation[0],i.rotation[1],i.rotation[2],i.rotation[3]),z.set(n.rotation[0],n.rotation[1],n.rotation[2],n.rotation[3]),a.slerp(z,y),s.x=a.x,s.y=a.y,s.z=a.z,s.w=a.w}writeLivePose(e,o){let s=this.simulation.getPose(this.handle,this.poseScratch);s?(e.x=s.position[0],e.y=s.position[1],e.z=s.position[2],o.x=s.rotation[0],o.y=s.rotation[1],o.z=s.rotation[2],o.w=s.rotation[3]):(e.x=0,e.y=0,e.z=0,o.x=0,o.y=0,o.z=0,o.w=1)}};export{k as a,S as b};
1
+ import{Quaternion as g}from"three";import{Quaternion as p}from"three";var h=new WeakMap,m=new p,x=new p,c=new p;function f(t){return{x:t.x,y:t.y,z:t.z}}function b(t){return{x:t.x,y:t.y,z:t.z,w:t.w}}function r(t){return{position:f(t.position),rotation:b(t.rotation)}}function u(t){return Number.isFinite(t)?Math.max(0,Math.min(1,t)):0}function l(t){return{position:f(t.translation()),rotation:b(t.rotation())}}function v(t){let e=r(t);return{previous:r(e),current:e}}function w(t){let e=l(t),o=h.get(t)??v(e);return o.previous=r(e),o.current=r(e),h.set(t,o),o}function d(t,e,o){let s=u(o);return m.set(t.rotation.x,t.rotation.y,t.rotation.z,t.rotation.w),x.set(e.rotation.x,e.rotation.y,e.rotation.z,e.rotation.w),c.slerpQuaternions(m,x,s),{position:{x:t.position.x+(e.position.x-t.position.x)*s,y:t.position.y+(e.position.y-t.position.y)*s,z:t.position.z+(e.position.z-t.position.z)*s},rotation:{x:c.x,y:c.y,z:c.z,w:c.w}}}function k(t,e){if(R(t))return t.getRenderPose(e);let o=h.get(t);if(!o)return l(t);let s=l(t);if(!H(s,o.current)){let n=w(t);return r(n.current)}return d(o.previous,o.current,e)}function R(t){return t!=null&&typeof t=="object"&&typeof t.getPoseHistory=="function"&&typeof t.getRenderPose=="function"}function H(t,e){return t.position.x===e.position.x&&t.position.y===e.position.y&&t.position.z===e.position.z&&t.rotation.x===e.rotation.x&&t.rotation.y===e.rotation.y&&t.rotation.z===e.rotation.z&&t.rotation.w===e.rotation.w}var P={x:0,y:0,z:0},a=new g,z=new g,S=class t{constructor(e,o,s){this.simulation=e;this.handle=o;this.clock=s;this.interpolationValidAfterStep=s.steps+2}poseScratch={position:[0,0,0],rotation:[0,0,0,1]};renderScratch={position:[0,0,0],rotation:[0,0,0,1],scale:1,custom:[0,0,0,0],isSleeping:!1};previousScratch={position:[0,0,0],rotation:[0,0,0,1],scale:1,custom:[0,0,0,0],isSleeping:!1};interpolationValidAfterStep;markPoseDiscontinuity(){this.interpolationValidAfterStep=this.clock.steps+2}isInterpolationStale(){return this.clock.steps<this.interpolationValidAfterStep}translation(){let e=this.simulation.getPose(this.handle,this.poseScratch);return e?{x:e.position[0],y:e.position[1],z:e.position[2]}:{...P}}rotation(){let e=this.simulation.getPose(this.handle,this.poseScratch);return e?{x:e.rotation[0],y:e.rotation[1],z:e.rotation[2],w:e.rotation[3]}:{x:0,y:0,z:0,w:1}}linvel(){let e=this.simulation.getLinearVelocity(this.handle);return e?{x:e[0],y:e[1],z:e[2]}:{...P}}angvel(){let e=this.simulation.adapter.getAngularVelocity(this.handle.slot);return e?{x:e[0],y:e[1],z:e[2]}:{...P}}setTranslation(e,o=!0){this.simulation.setPosition(this.handle,e.x,e.y,e.z),this.markPoseDiscontinuity()}setRotation(e,o=!0){this.simulation.setRotation(this.handle,e.x,e.y,e.z,e.w),this.markPoseDiscontinuity()}setLinvel(e,o=!0){this.simulation.setLinearVelocity(this.handle,e.x,e.y,e.z)}setAngvel(e,o=!0){this.simulation.setAngularVelocity(this.handle,e.x,e.y,e.z)}applyImpulse(e,o=!0){this.simulation.applyImpulse(this.handle,e.x,e.y,e.z)}lockRotations(e,o=!0){e&&this.setAngvel({x:0,y:0,z:0})}lockTranslations(e,o=!0){e&&this.setLinvel({x:0,y:0,z:0})}setLinearDamping(e){}setGravityScale(e,o=!0){}bodyInfo(){return this.simulation.getBodyInfo(this.handle)}bodyType(){return this.bodyInfo()?.bodyType??0}mass(){return this.bodyInfo()?.mass??0}isSleeping(){return this.bodyInfo()?.isSleeping??!1}isEnabled(){return this.bodyInfo()?.isEnabled??!0}livePose(){let e=this.simulation.getPose(this.handle,this.poseScratch);return e?{position:{x:e.position[0],y:e.position[1],z:e.position[2]},rotation:{x:e.rotation[0],y:e.rotation[1],z:e.rotation[2],w:e.rotation[3]}}:{position:{...P},rotation:{x:0,y:0,z:0,w:1}}}static slotToPose(e){return{position:{x:e.position[0],y:e.position[1],z:e.position[2]},rotation:{x:e.rotation[0],y:e.rotation[1],z:e.rotation[2],w:e.rotation[3]}}}getPoseHistory(){if(this.isInterpolationStale()){let i=this.livePose();return{previous:r(i),current:i}}let e=this.simulation.readRenderSlot(this.handle,this.renderScratch),o=this.simulation.readPreviousRenderSlot(this.handle,this.previousScratch),s=e?t.slotToPose(e):this.livePose();return{previous:o?t.slotToPose(o):r(s),current:s}}getRenderPose(e){let o=this.getPoseHistory();return d(o.previous,o.current,e)}isRenderSleeping(){return this.simulation.readRenderSlot(this.handle,this.renderScratch)?.isSleeping===!0}writeRenderPose(e,o,s){if(this.isInterpolationStale()){this.writeLivePose(o,s);return}let n=this.simulation.readRenderSlot(this.handle,this.renderScratch);if(!n){this.writeLivePose(o,s);return}let i=this.simulation.readPreviousRenderSlot(this.handle,this.previousScratch)??n,y=u(e);o.x=i.position[0]+(n.position[0]-i.position[0])*y,o.y=i.position[1]+(n.position[1]-i.position[1])*y,o.z=i.position[2]+(n.position[2]-i.position[2])*y,a.set(i.rotation[0],i.rotation[1],i.rotation[2],i.rotation[3]),z.set(n.rotation[0],n.rotation[1],n.rotation[2],n.rotation[3]),a.slerp(z,y),s.x=a.x,s.y=a.y,s.z=a.z,s.w=a.w}writeLivePose(e,o){let s=this.simulation.getPose(this.handle,this.poseScratch);s?(e.x=s.position[0],e.y=s.position[1],e.z=s.position[2],o.x=s.rotation[0],o.y=s.rotation[1],o.z=s.rotation[2],o.w=s.rotation[3]):(e.x=0,e.y=0,e.z=0,o.x=0,o.y=0,o.z=0,o.w=1)}};export{k as a,S as b};
@@ -1,5 +1,5 @@
1
1
  import { SimulationBodyDefinition, SimulationColliderDefinition } from '@zylem/behaviors/core';
2
- import { e as Vec3Input } from './vector-DN6zlPoE.js';
2
+ import { e as Vec3Input } from './vector-DPbwlzgG.js';
3
3
 
4
4
  /** Per-axis lock input: `true` locks all axes, or pass an [x, y, z] tuple. */
5
5
  type LockAxesInput = boolean | readonly [boolean, boolean, boolean];
package/dist/core.d.ts CHANGED
@@ -1,19 +1,19 @@
1
- import { B as Stage, E as StageStateInterface, C as CameraWrapper } from './game-DbqBQiFC.js';
2
- export { A as AspectRatio, q as AspectRatioValue, k as CameraManager, j as CameraOptions, D as DeviceProfile, p as FirstPersonOptions, l as FirstPersonPerspective, o as Fixed2DOptions, F as Fixed2DPerspective, G as Game, b as GameConfigLike, d as GameDeviceConfig, a as GameLoadingEvent, P as PerspectiveOptions, y as RenderBundleManager, z as RenderStrategyManager, R as ResolutionInput, e as ResolveGameConfigRuntime, v as RetroPreset, w as RetroPresetKey, x as RetroResolution, S as StageConfigLike, h as StageOptions, n as ThirdPersonOptions, T as ThirdPersonPerspective, i as createCamera, c as createGame, m as createPerspective, f as createStage, g as gameConfig, r as getDisplayAspect, t as getPresetResolution, u as parseResolution, s as stageConfig } from './game-DbqBQiFC.js';
1
+ import { B as Stage, E as StageStateInterface, C as CameraWrapper } from './game-4fsy55uN.js';
2
+ export { A as AspectRatio, q as AspectRatioValue, k as CameraManager, j as CameraOptions, D as DeviceProfile, p as FirstPersonOptions, l as FirstPersonPerspective, o as Fixed2DOptions, F as Fixed2DPerspective, G as Game, b as GameConfigLike, d as GameDeviceConfig, a as GameLoadingEvent, P as PerspectiveOptions, y as RenderBundleManager, z as RenderStrategyManager, R as ResolutionInput, e as ResolveGameConfigRuntime, v as RetroPreset, w as RetroPresetKey, x as RetroResolution, S as StageConfigLike, h as StageOptions, n as ThirdPersonOptions, T as ThirdPersonPerspective, i as createCamera, c as createGame, m as createPerspective, f as createStage, g as gameConfig, r as getDisplayAspect, t as getPresetResolution, u as parseResolution, s as stageConfig } from './game-4fsy55uN.js';
3
3
  export { G as GameInputConfig, a as GameInputPlayerConfig, K as KeyboardMapping, M as MouseConfig, b as MouseMapping, V as VirtualTouchButtonConfig, d as VirtualTouchButtonSlot, c as VirtualTouchButtonsConfig, e as VirtualTouchConfig, f as VirtualTouchJoystickConfig, g as VirtualTouchJoysticksConfig, h as VirtualTouchPosition, i as VirtualTouchStyle, Z as ZylemGameConfig } from './game-interfaces-vF5sRi1n.js';
4
4
  import { Vector2 } from 'three';
5
- import { G as GameEntity, B as BaseNode, N as NodeInterface, a as GameEntityOptions } from './entity-BGEq1yfC.js';
5
+ import { G as GameEntity, B as BaseNode, N as NodeInterface, a as GameEntityOptions } from './entity-BI7cSlK8.js';
6
6
  import { S as StageBlueprint } from './blueprints-TbGY-h53.js';
7
7
  import { a as SetupContext, k as LoadedContext, U as UpdateContext, D as DestroyContext, l as CleanupContext } from './base-node-life-cycle-BK9xebT9.js';
8
8
  export { L as LoadingEvent, S as StageNavigationOptions } from './base-node-life-cycle-BK9xebT9.js';
9
9
  export { S as StageTransitionConfig, a as StageTransitionEasing, Z as ZylemTransitionShader, c as crossfadeTransitionShader } from './stage-transition-CmGpV4tc.js';
10
- import { f as CameraBehavior } from './zylem-camera-Du2UPW9O.js';
11
- export { g as CameraAction, d as CameraContext, e as CameraPerspective, j as CameraPipeline, h as CameraPipelineState, C as CameraPose, P as PerspectiveType, a as Perspectives, c as PoseDelta, T as TransformLike, V as Viewport, b as ZylemRenderer, i as isWebGPUSupported } from './zylem-camera-Du2UPW9O.js';
12
- import { e as Vec3Input, c as Vec3 } from './vector-DN6zlPoE.js';
13
- export { f as VEC2_ONE, g as VEC2_ZERO, h as VEC3_ONE, i as VEC3_ZERO, V as Vec2, a as Vec2Components, b as Vec2Input, d as Vec3Components, n as normalizeVec2, j as normalizeVec3, t as toThreeVector2, k as toThreeVector3 } from './vector-DN6zlPoE.js';
14
- import { S as StageEntity } from './entity-B9yZeBm4.js';
15
- import './entity-type-map-CW6RHQkx.js';
16
- import './material-DbSuZBbP.js';
10
+ import { f as CameraBehavior } from './zylem-camera-B73ZNcgs.js';
11
+ export { g as CameraAction, d as CameraContext, e as CameraPerspective, j as CameraPipeline, h as CameraPipelineState, C as CameraPose, P as PerspectiveType, a as Perspectives, c as PoseDelta, T as TransformLike, V as Viewport, b as ZylemRenderer, i as isWebGPUSupported } from './zylem-camera-B73ZNcgs.js';
12
+ import { e as Vec3Input, c as Vec3 } from './vector-DPbwlzgG.js';
13
+ export { f as VEC2_ONE, g as VEC2_ZERO, h as VEC3_ONE, i as VEC3_ZERO, V as Vec2, a as Vec2Components, b as Vec2Input, d as Vec3Components, n as normalizeVec2, j as normalizeVec3, t as toThreeVector2, k as toThreeVector3 } from './vector-DPbwlzgG.js';
14
+ import { S as StageEntity } from './entity-DDks47JB.js';
15
+ import './entity-type-map-COHu4fkW.js';
16
+ import './material-BKPYeBC6.js';
17
17
  import 'three/webgpu';
18
18
  import '@zylem/behaviors/core';
19
19
  import '@zylem/behaviors/particle-emitter';
@@ -21,7 +21,7 @@ import 'three/addons/lines/webgpu/Line2.js';
21
21
  import './events.js';
22
22
  import 'mitt';
23
23
  import './default-controls-CAKJ5zlo.js';
24
- import './collision-builder-B_tm8OVy.js';
24
+ import './collision-builder-4TVDzXsp.js';
25
25
  import '@sinclair/typebox';
26
26
 
27
27
  /**
package/dist/core.js CHANGED
@@ -1 +1 @@
1
- import{a as b,b as c,c as d,d as e,e as f,f as H,g as I,h as J,i as K,j as L,k as M,l as N,m as O,n as P,o as Q}from"./chunk-3PRBSSTS.js";import{a as g}from"./chunk-7GYFZKK7.js";import"./chunk-COM6HJ2L.js";import{a,c as h,d as i,e as j,f as s,g as t,h as u,i as v,k as w,l as x,m as y,n as z,o as A,p as B,q as C,r as D,s as E,t as F,v as G}from"./chunk-CFVRRRZZ.js";import"./chunk-VS2D4B3W.js";import"./chunk-JQKS42G4.js";import"./chunk-YAOXFYOD.js";import"./chunk-MZZCDXFB.js";import"./chunk-KVSJE4XD.js";import"./chunk-CM5YRNBJ.js";import"./chunk-YHEWKN7N.js";import"./chunk-QXVH6POE.js";import"./chunk-EVYHPR3J.js";import"./chunk-D2PATZCC.js";import"./chunk-4QLJUQSJ.js";import{a as k,b as l,c as m,d as n,g as o,h as p,i as q,j as r}from"./chunk-7WRQ2UAN.js";import"./chunk-BH53MBAZ.js";import"./chunk-XRP4JJXL.js";import"./chunk-PCFF4LLO.js";import"./chunk-UG22Z42P.js";export{b as AspectRatio,B as CameraManager,w as CameraPipeline,C as CameraWrapper,z as FirstPersonPerspective,y as Fixed2DPerspective,J as Game,v as Perspectives,s as RenderBundleManager,t as RenderStrategyManager,M as STAGE_STATE_CHANGE,I as StageManager,x as ThirdPersonPerspective,l as VEC2_ONE,k as VEC2_ZERO,n as VEC3_ONE,m as VEC3_ZERO,D as createCamera,P as createFollowTarget,K as createGame,A as createPerspective,G as createStage,g as crossfadeTransitionShader,O as dispatchStageState,L as entitySpawner,f as gameConfig,c as getDisplayAspect,d as getPresetResolution,N as initStageStateDispatcher,j as isManagedRenderEntity,a as isWebGPUSupported,o as normalizeVec2,p as normalizeVec3,e as parseResolution,h as resolveRenderCategory,Q as setCameraFeed,u as setStageFrameProfilerEnabled,E as stageConfig,H as stageState,q as toThreeVector2,r as toThreeVector3,i as usesManagedRenderPath,F as vessel};
1
+ import{a as b,b as c,c as d,d as e,e as f,f as H,g as I,h as J,i as K,j as L,k as M,l as N,m as O,n as P,o as Q}from"./chunk-6B5JP7T5.js";import{a,c as h,d as i,e as j,f as s,g as t,h as u,i as v,k as w,l as x,m as y,n as z,o as A,p as B,q as C,r as D,s as E,t as F,v as G}from"./chunk-4CHZUWLF.js";import{a as g}from"./chunk-7GYFZKK7.js";import"./chunk-VIPINV7V.js";import"./chunk-C5NEGC3S.js";import"./chunk-D3JO4HW2.js";import"./chunk-LKFF6XJC.js";import"./chunk-W5SXED5T.js";import"./chunk-WBQ5TNRZ.js";import"./chunk-PNLNC3FA.js";import"./chunk-3I537JFL.js";import"./chunk-CM5YRNBJ.js";import"./chunk-AIQ6IVT5.js";import"./chunk-QXVH6POE.js";import"./chunk-EVYHPR3J.js";import"./chunk-D2PATZCC.js";import"./chunk-4QLJUQSJ.js";import{a as k,b as l,c as m,d as n,g as o,h as p,i as q,j as r}from"./chunk-7WRQ2UAN.js";import"./chunk-BH53MBAZ.js";import"./chunk-XRP4JJXL.js";import"./chunk-PCFF4LLO.js";import"./chunk-UG22Z42P.js";export{b as AspectRatio,B as CameraManager,w as CameraPipeline,C as CameraWrapper,z as FirstPersonPerspective,y as Fixed2DPerspective,J as Game,v as Perspectives,s as RenderBundleManager,t as RenderStrategyManager,M as STAGE_STATE_CHANGE,I as StageManager,x as ThirdPersonPerspective,l as VEC2_ONE,k as VEC2_ZERO,n as VEC3_ONE,m as VEC3_ZERO,D as createCamera,P as createFollowTarget,K as createGame,A as createPerspective,G as createStage,g as crossfadeTransitionShader,O as dispatchStageState,L as entitySpawner,f as gameConfig,c as getDisplayAspect,d as getPresetResolution,N as initStageStateDispatcher,j as isManagedRenderEntity,a as isWebGPUSupported,o as normalizeVec2,p as normalizeVec3,e as parseResolution,h as resolveRenderCategory,Q as setCameraFeed,u as setStageFrameProfilerEnabled,E as stageConfig,H as stageState,q as toThreeVector2,r as toThreeVector3,i as usesManagedRenderPath,F as vessel};
@@ -0,0 +1,49 @@
1
+ import { G as GameEntity } from './entity-BI7cSlK8.js';
2
+
3
+ type DebugTools = 'select' | 'translate' | 'rotate' | 'scale' | 'delete' | 'add' | 'none';
4
+ interface DebugState {
5
+ enabled: boolean;
6
+ paused: boolean;
7
+ tool: DebugTools;
8
+ /**
9
+ * UUID of the selected entity, never the entity itself. Valtio deep-proxies
10
+ * any object assigned into a proxy, so storing a live `GameEntity` here
11
+ * would walk `group.parent` into the entire THREE scene graph and
12
+ * `physicsWorldRef` into the Rapier world, freezing the tab and handing
13
+ * Proxy wrappers to engine code that expects real instances.
14
+ */
15
+ selectedEntityId: string | null;
16
+ /** UUID of the hovered entity. Same constraint as `selectedEntityId`. */
17
+ hoveredEntityId: string | null;
18
+ flags: Set<string>;
19
+ }
20
+ declare const debugState: DebugState;
21
+ /** Resolves a UUID to the live entity owned by the active stage. */
22
+ type DebugEntityResolver = (uuid: string) => GameEntity<any> | null;
23
+ /**
24
+ * Register the active stage's entity resolver so `getSelectedEntity` /
25
+ * `getHoveredEntity` can hand back live entities without the reactive store
26
+ * ever holding one.
27
+ *
28
+ * @returns An unregister function.
29
+ */
30
+ declare function registerDebugEntityResolver(resolver: DebugEntityResolver): () => void;
31
+ /** Resolve a UUID through the active stage, or null when unavailable. */
32
+ declare function resolveDebugEntity(uuid: string | null): GameEntity<any> | null;
33
+ declare function setPaused(paused: boolean): void;
34
+ declare function setDebugTool(tool: DebugTools): void;
35
+ declare function getSelectedEntityId(): string | null;
36
+ declare function setSelectedEntityId(uuid: string | null): void;
37
+ declare function getHoveredEntityId(): string | null;
38
+ declare function setHoveredEntityId(uuid: string | null): void;
39
+ /** The live selected entity, resolved on demand through the active stage. */
40
+ declare function getSelectedEntity(): GameEntity<any> | null;
41
+ /** The live hovered entity, resolved on demand through the active stage. */
42
+ declare function getHoveredEntity(): GameEntity<any> | null;
43
+ /**
44
+ * @deprecated Pass a UUID to {@link setSelectedEntityId} instead. Accepts a
45
+ * live entity only to keep the previous public API working.
46
+ */
47
+ declare function setSelectedEntity(entity: GameEntity<any> | string | null): void;
48
+
49
+ export { type DebugTools as D, setPaused as a, setSelectedEntity as b, setSelectedEntityId as c, debugState as d, getSelectedEntity as e, setHoveredEntityId as f, getSelectedEntityId as g, getHoveredEntityId as h, getHoveredEntity as i, resolveDebugEntity as j, type DebugEntityResolver as k, registerDebugEntityResolver as r, setDebugTool as s };