@zylem/game-lib 0.9.5 → 0.9.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/actions.d.ts +2 -2
- package/dist/api/game-lib.api.json +526 -175
- package/dist/api/game-lib.api.md +41 -11
- package/dist/api/game-lib.d.ts +172 -26
- package/dist/api/game-lib.typedoc.json +48943 -48302
- package/dist/bridge.d.ts +8 -1
- package/dist/bridge.js +1 -1
- package/dist/catalog.js +1 -1
- package/dist/{chunk-BQRMYLYD.js → chunk-273CUPEO.js} +1 -1
- package/dist/chunk-5V52N34T.js +1 -0
- package/dist/{chunk-YQS7CGXE.js → chunk-FUZDTRCU.js} +1 -1
- package/dist/{chunk-4CZZZCFB.js → chunk-JCGW5PIR.js} +1 -1
- package/dist/chunk-KIFB427K.js +1 -0
- package/dist/chunk-P6IOYQHU.js +1 -0
- package/dist/{chunk-2IJLXFWY.js → chunk-RPMV7GDX.js} +4 -4
- package/dist/chunk-UM5VNQPY.js +1 -0
- package/dist/chunk-VKWJHFUR.js +1 -0
- package/dist/chunk-VXE3CV3K.js +1 -0
- package/dist/chunk-Y23IJJPD.js +1 -0
- package/dist/chunk-YRHRMVHS.js +1 -0
- package/dist/cinematics.d.ts +4 -3
- package/dist/core.d.ts +20 -7
- package/dist/core.js +1 -1
- package/dist/{debug-state-Cg3f5FB6.d.ts → debug-state-DhVkY2aM.d.ts} +2 -2
- package/dist/debug.d.ts +2 -2
- package/dist/debug.js +1 -1
- package/dist/{entity-XqvuWgPm.d.ts → entity-DC0P747T.d.ts} +5 -0
- package/dist/{entity-type-map-CrsrKT8c.d.ts → entity-type-map-B0S5cfv7.d.ts} +52 -13
- package/dist/entity.d.ts +5 -17
- package/dist/entity.js +1 -1
- package/dist/{game-default-BAZPDNPS.js → game-default-VUMUMTXA.js} +1 -1
- package/dist/{game-DBt7iVu4.d.ts → game-mu6OSCrq.d.ts} +7 -7
- package/dist/level-types-D10LiOcn.d.ts +91 -0
- package/dist/public.d.ts +8 -7
- package/dist/public.js +1 -1
- package/dist/{stage-PBmwT5-Y.d.ts → stage-B_KdSEK6.d.ts} +15 -2
- package/dist/web-components.d.ts +6 -5
- package/dist/web-components.js +1 -1
- package/package.json +3 -3
- package/dist/chunk-3CLQWJ2I.js +0 -1
- package/dist/chunk-GPCSX3M6.js +0 -1
- package/dist/chunk-K3NNXZIJ.js +0 -1
- package/dist/chunk-KP6DLLJO.js +0 -1
- package/dist/chunk-LI43BZQN.js +0 -1
- package/dist/chunk-NK4IXK5V.js +0 -1
- package/dist/chunk-STVEILJJ.js +0 -1
- package/dist/chunk-VSFULLND.js +0 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{b as Ue,d as H,j as A,x as J,y as U}from"./chunk-NK4IXK5V.js";import{g as Fe}from"./chunk-PCFF4LLO.js";import{b as x}from"./chunk-OCQ7A5IK.js";import{b as We,c as je}from"./chunk-VSFULLND.js";import{c as K,e as Ke,f as Je}from"./chunk-2HSR5XDQ.js";import{e as ce,g as me,h as _e,i as he,j as Xe,k as Ye,l as ge,n as Ze}from"./chunk-3CLQWJ2I.js";import{d as v,g as He,h as de}from"./chunk-GPCSX3M6.js";import{k as et}from"./chunk-LI43BZQN.js";import{a as ye,t as be}from"./chunk-KP6DLLJO.js";import{j as $e}from"./chunk-6FGXC4T6.js";import{a as Ne,b as G}from"./chunk-AIQ6IVT5.js";import{t as Qe}from"./chunk-2XMG3NJS.js";import{b as qe}from"./chunk-7GYFZKK7.js";import{c as k}from"./chunk-D2PATZCC.js";import{c as ke,d as V,e as Ae,h as De,i as ze,j as Ve,k as pe,l as O,m as Oe}from"./chunk-4QLJUQSJ.js";import{j as fe}from"./chunk-7WRQ2UAN.js";import{l as L}from"./chunk-UG22Z42P.js";function ft(){return{pressed:!1,released:!1,held:0}}function yt(){return{value:0,held:0}}function $(a){let e=new Map;if(!a)return e;for(let[t,n]of Object.entries(a)){if(!n||n.length===0)continue;let i=[];for(let o of n){let[s,r]=(o||"").split(".");if(!s||!r)continue;let l=s.toLowerCase(),p=r.toLowerCase();if(l==="buttons"){let u={a:"A",b:"B",x:"X",y:"Y",start:"Start",select:"Select",l:"L",r:"R"}[p];u&&i.push({category:"buttons",property:u})}else if(l==="directions"){let u={up:"Up",down:"Down",left:"Left",right:"Right"}[p];u&&i.push({category:"directions",property:u})}else if(l==="shoulders"){let u={ltrigger:"LTrigger",rtrigger:"RTrigger"}[p];u&&i.push({category:"shoulders",property:u})}else if(l==="axes"){let u={left:{property:"Horizontal",direction:-1},right:{property:"Horizontal",direction:1},up:{property:"Vertical",direction:-1},down:{property:"Vertical",direction:1},secondaryleft:{property:"SecondaryHorizontal",direction:-1},secondaryright:{property:"SecondaryHorizontal",direction:1},secondaryup:{property:"SecondaryVertical",direction:-1},secondarydown:{property:"SecondaryVertical",direction:1}}[p];u&&i.push({category:"axes",property:u.property,axisDirection:u.direction})}}i.length>0&&e.set(t,i)}return e}function m(a,e){return!a&&!e?ft():a?e?{pressed:a.pressed||e.pressed,released:a.released||e.released,held:a.held+e.held}:{...a}:{...e}}function w(a,e){return!a&&!e?yt():a?e?{value:a.value+e.value,held:a.held+e.held}:{...a}:{...e}}var D=class{keyStates=new Map;keyButtonStates=new Map;analogStates=new Map;compiledMapping;includeDefaultBase=!0;onKeyDown=({key:e})=>this.keyStates.set(e,!0);onKeyUp=({key:e})=>this.keyStates.set(e,!1);constructor(e,t){this.includeDefaultBase=t?.includeDefaultBase??!0,this.compiledMapping=$(e??null),window.addEventListener("keydown",this.onKeyDown),window.addEventListener("keyup",this.onKeyUp)}dispose(){window.removeEventListener("keydown",this.onKeyDown),window.removeEventListener("keyup",this.onKeyUp),this.keyStates.clear(),this.keyButtonStates.clear(),this.analogStates.clear()}isKeyPressed(e){return this.keyStates.get(e)||!1}handleButtonState(e,t){let n=this.keyButtonStates.get(e);n||(n={pressed:!1,released:!1,held:0},this.keyButtonStates.set(e,n));let i=this.isKeyPressed(e);return n.pressed=i&&n.held===0,n.released=!i&&n.held>0,n.held=i?n.held+t:0,n}handleAnalogState(e,t,n){let i=`${e}:${t}`,o=this.analogStates.get(i);return o||(o={value:0,held:0},this.analogStates.set(i,o)),o.value=this.getAxisValue(e,t),o.held=o.value!==0?o.held+n:0,o}applyCustomMapping(e,t){if(this.compiledMapping.size===0)return e;let n=new Map;for(let[i,o]of this.compiledMapping.entries()){let s=null;for(let r of o)if(r.category==="axes")n.has(r.property)||n.set(r.property,0),this.isKeyPressed(i)&&n.set(r.property,n.get(r.property)+r.axisDirection);else{s||(s=this.handleButtonState(i,t));let l=e[r.category]??={};l[r.property]=m(l[r.property],s)}}if(n.size>0){e.axes||(e.axes={});for(let[i,o]of n.entries()){let s=`custom:${i}`,r=this.analogStates.get(s);r||(r={value:0,held:0},this.analogStates.set(s,r)),r.value=o,r.held=o!==0?r.held+t:0,e.axes[i]=w(e.axes[i],r)}}return e}getInput(e){let t={};return this.includeDefaultBase&&(t.buttons={A:this.handleButtonState("z",e),B:this.handleButtonState("x",e),X:this.handleButtonState("a",e),Y:this.handleButtonState("s",e),Start:this.handleButtonState(" ",e),Select:this.handleButtonState("Enter",e),L:this.handleButtonState("q",e),R:this.handleButtonState("e",e)},t.directions={Up:this.handleButtonState("ArrowUp",e),Down:this.handleButtonState("ArrowDown",e),Left:this.handleButtonState("ArrowLeft",e),Right:this.handleButtonState("ArrowRight",e)},t.shoulders={LTrigger:this.handleButtonState("Q",e),RTrigger:this.handleButtonState("E",e)}),this.applyCustomMapping(t,e)}getName(){return"keyboard"}getAxisValue(e,t){return(this.isKeyPressed(t)?1:0)-(this.isKeyPressed(e)?1:0)}isConnected(){return!0}};var W=class{gamepadIndex;connected=!1;buttonStates={};analogStates={};onConnected=e=>{e.gamepad.index===this.gamepadIndex&&(this.connected=!0)};onDisconnected=e=>{e.gamepad.index===this.gamepadIndex&&(this.connected=!1)};constructor(e){this.gamepadIndex=e,window.addEventListener("gamepadconnected",this.onConnected),window.addEventListener("gamepaddisconnected",this.onDisconnected)}dispose(){window.removeEventListener("gamepadconnected",this.onConnected),window.removeEventListener("gamepaddisconnected",this.onDisconnected),this.buttonStates={},this.analogStates={}}handleButtonState(e,t,n){let i=this.buttonStates[e];i||(i={pressed:!1,released:!1,held:0},this.buttonStates[e]=i);let o=t.buttons[e].pressed;return i.pressed=o&&i.held===0,i.released=!o&&i.held>0,i.held=o?i.held+n:0,i}handleAnalogState(e,t,n){let i=this.analogStates[e];return i||(i={value:0,held:0},this.analogStates[e]=i),i.value=t.axes[e],i.held=i.value!==0?i.held+n:0,i}getInput(e){let t=navigator.getGamepads()[this.gamepadIndex];return t?{buttons:{A:this.handleButtonState(0,t,e),B:this.handleButtonState(1,t,e),X:this.handleButtonState(2,t,e),Y:this.handleButtonState(3,t,e),Start:this.handleButtonState(9,t,e),Select:this.handleButtonState(8,t,e),L:this.handleButtonState(4,t,e),R:this.handleButtonState(5,t,e)},directions:{Up:this.handleButtonState(12,t,e),Down:this.handleButtonState(13,t,e),Left:this.handleButtonState(14,t,e),Right:this.handleButtonState(15,t,e)},axes:{Horizontal:this.handleAnalogState(0,t,e),Vertical:this.handleAnalogState(1,t,e),SecondaryHorizontal:this.handleAnalogState(2,t,e),SecondaryVertical:this.handleAnalogState(3,t,e)},shoulders:{LTrigger:this.handleButtonState(6,t,e),RTrigger:this.handleButtonState(7,t,e)}}:{}}getName(){return`gamepad-${this.gamepadIndex+1}`}isConnected(){return this.connected}};import{subscribe as bt}from"valtio/vanilla";var vt=.002;function j(a,e,t){return Math.max(e,Math.min(t,a))}function St(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 F=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=St(this.targetElement);if(n){let i=n.getBoundingClientRect();if(i.width>0&&i.height>0){let o=i.left+i.width/2,s=i.top+i.height/2;this.pointerCenterX=j((e-o)/(i.width/2),-1,1),this.pointerCenterY=j((t-s)/(i.height/2),-1,1);return}}this.pointerCenterX=j((this.pointerX-.5)*2,-1,1),this.pointerCenterY=j((this.pointerY-.5)*2,-1,1)}onMouseMove=e=>{this.updatePointerPosition(e.clientX,e.clientY),!(v.enabled||this.lookMode==="screenCenter")&&(this.movementX+=e.movementX,this.movementY+=e.movementY)};onMouseDown=e=>{let t=e.target;t instanceof HTMLCanvasElement&&this.targetElement.contains(t)&&(this.mouseButtonDown.add(e.button),this.usePointerLock&&!this.isLocked&&!v.enabled&&this.targetElement.requestPointerLock())};onMouseUp=e=>{this.mouseButtonDown.delete(e.button)};onContextMenu=e=>{e.preventDefault()};onPointerLockChange=()=>{this.isLocked=document.pointerLockElement===this.targetElement};constructor(e,t){this.sensitivity=e?.sensitivity??vt,this.lookMode=e?.lookMode??"delta",this.usePointerLock=e?.pointerLock??!1,this.compiledMapping=$(e?.mapping??null),this.targetElement=t??document.body,window.addEventListener("mousemove",this.onMouseMove),this.targetElement.addEventListener("mousedown",this.onMouseDown),this.targetElement.addEventListener("mouseup",this.onMouseUp),this.targetElement.addEventListener("contextmenu",this.onContextMenu),this.usePointerLock&&(document.addEventListener("pointerlockchange",this.onPointerLockChange),this.debugUnsubscribe=bt(v,()=>{v.enabled&&document.pointerLockElement===this.targetElement&&document.exitPointerLock()}))}dispose(){window.removeEventListener("mousemove",this.onMouseMove),this.targetElement.removeEventListener("mousedown",this.onMouseDown),this.targetElement.removeEventListener("mouseup",this.onMouseUp),this.targetElement.removeEventListener("contextmenu",this.onContextMenu),document.removeEventListener("pointerlockchange",this.onPointerLockChange),this.debugUnsubscribe?.(),this.debugUnsubscribe=null,this.isLocked&&document.exitPointerLock(),this.buttonStates.clear(),this.analogStates.clear(),this.mouseButtonDown.clear(),this.movementX=0,this.movementY=0}handleMouseButton(e,t){let n=this.buttonStates.get(e);n||(n={pressed:!1,released:!1,held:0},this.buttonStates.set(e,n));let i=this.mouseButtonDown.has(e);return n.pressed=i&&n.held===0,n.released=!i&&n.held>0,n.held=i?n.held+t:0,n}handleMovementAxis(e,t){let n=this.analogStates.get(e);n||(n={value:0,held:0},this.analogStates.set(e,n));let i=e==="x"?this.movementX:this.movementY;return n.value=Math.max(-1,Math.min(1,i*this.sensitivity)),n.held=n.value!==0?n.held+t:0,n}applyCustomMapping(e,t){if(this.compiledMapping.size===0)return e;let n=new Map,i={leftbutton:()=>this.handleMouseButton(0,t),rightbutton:()=>this.handleMouseButton(2,t),middlebutton:()=>this.handleMouseButton(1,t)};for(let[o,s]of this.compiledMapping.entries()){let r=o.toLowerCase();for(let l of s)if(l.category==="axes")n.has(l.property)||n.set(l.property,0),r==="movex"?n.set(l.property,n.get(l.property)+Math.max(-1,Math.min(1,this.movementX*this.sensitivity))*l.axisDirection):r==="movey"?n.set(l.property,n.get(l.property)+Math.max(-1,Math.min(1,this.movementY*this.sensitivity))*l.axisDirection):r in i&&this.mouseButtonDown.has(this.buttonIndexForAction(r))&&n.set(l.property,n.get(l.property)+l.axisDirection);else{let p=i[r];if(p){let g=p();if(g){let u=e[l.category]??={};u[l.property]=m(u[l.property],g)}}}}if(n.size>0){e.axes||(e.axes={});for(let[o,s]of n.entries()){let r=`custom:${o}`,l=this.analogStates.get(r);l||(l={value:0,held:0},this.analogStates.set(r,l)),l.value=Math.max(-1,Math.min(1,s)),l.held=s!==0?l.held+t:0,e.axes[o]=w(e.axes[o],l)}}return e}buttonIndexForAction(e){switch(e){case"leftbutton":return 0;case"middlebutton":return 1;case"rightbutton":return 2;default:return-1}}getInput(e){v.enabled&&(this.movementX=0,this.movementY=0);let t={value:0,held:0},n=this.lookMode==="delta",i={axes:{Horizontal:t,Vertical:t,SecondaryHorizontal:n?this.handleMovementAxis("x",e):t,SecondaryVertical:n?this.handleMovementAxis("y",e):t},shoulders:{LTrigger:this.handleMouseButton(0,e),RTrigger:this.handleMouseButton(2,e)},pointer:{x:this.pointerX,y:this.pointerY,centerX:this.pointerCenterX,centerY:this.pointerCenterY}};return this.movementX=0,this.movementY=0,this.applyCustomMapping(i,e)}getName(){return"mouse"}isConnected(){return!0}};function N(a={}){if(typeof window>"u"||typeof navigator>"u")return!1;let e=navigator.userAgent,t=/android/i.test(e)||/iPad|iPhone|iPod/.test(e),n="ontouchstart"in window||navigator.maxTouchPoints>0,i=typeof window.matchMedia=="function"?window.matchMedia("(pointer: coarse)").matches:!1,o=a.viewportSize?.width??window.innerWidth??0,s=a.viewportSize?.height??window.innerHeight??0,r=Math.max(o,s),l=r===0||r<=1024;return a.allowViewportOnly&&a.viewportSize?l:t||(n||i)&&l}var wt=["A","B","X","Y","Start","Select","L","R","LTrigger","RTrigger","Up","Down","Left","Right"],Ct=new Set(["flex","flexGrow","flexShrink","fontWeight","lineHeight","opacity","order","zIndex","zoom"]),xt={A:{size:72,label:"A",position:{right:98,bottom:44}},B:{size:72,label:"B",position:{right:24,bottom:108}},X:{size:72,label:"X",position:{right:172,bottom:108}},Y:{size:72,label:"Y",position:{right:98,bottom:172}},Start:{size:64,label:"Start",position:{left:"50%",top:24,transform:"translateX(28px)"}},Select:{size:64,label:"Select",position:{left:"50%",top:24,transform:"translateX(-108px)"}},L:{size:62,label:"L",position:{left:28,bottom:184}},R:{size:62,label:"R",position:{right:236,bottom:184}},LTrigger:{size:76,label:"LT",position:{left:24,top:24}},RTrigger:{size:76,label:"RT",position:{right:24,top:24}},Up:{enabled:!1,size:64,label:"Up"},Down:{enabled:!1,size:64,label:"Down"},Left:{enabled:!1,size:64,label:"Left"},Right:{enabled:!1,size:64,label:"Right"}},Gt={left:{size:140,thumbSize:58,maxDistance:44,deadzone:.12,directionThreshold:.34,horizontalAxis:"Horizontal",verticalAxis:"Vertical",emitDirections:!0,position:{left:24,bottom:24}},right:{size:140,thumbSize:58,maxDistance:44,deadzone:.12,directionThreshold:.34,horizontalAxis:"SecondaryHorizontal",verticalAxis:"SecondaryVertical",emitDirections:!1,position:{right:24,bottom:236}}},X=class{config;targetElement;buttonStates=new Map;analogStates=new Map;buttons=new Map;joysticks=new Map;rootElement=null;enabled=!1;onPointerMove=e=>{for(let t of this.joysticks.values())t.pointerId===e.pointerId&&(this.consumeEvent(e),this.updateJoystickFromPoint(t,e.clientX,e.clientY))};onPointerUp=e=>{for(let t of this.buttons.values())t.pointerId===e.pointerId&&(this.consumeEvent(e),this.releaseButton(t));for(let t of this.joysticks.values())t.pointerId===e.pointerId&&(this.consumeEvent(e),this.releaseJoystick(t))};onWindowBlur=()=>{for(let e of this.buttons.values())this.releaseButton(e);for(let e of this.joysticks.values())this.releaseJoystick(e)};constructor(e,t){this.config=e??{},this.targetElement=t??document.body,this.enabled=this.resolveEnabledState(),this.enabled&&(this.mountControls(),window.addEventListener("pointermove",this.onPointerMove),window.addEventListener("pointerup",this.onPointerUp),window.addEventListener("pointercancel",this.onPointerUp),window.addEventListener("blur",this.onWindowBlur))}getInput(e){if(!this.enabled)return{};let t={};for(let n of this.buttons.values()){let i=this.handleButtonState(`button:${n.slot}`,n.pointerId!==null,e);this.assignButtonState(t,this.resolveButtonTarget(n.slot),i)}for(let n of this.joysticks.values()){let i=this.handleAnalogState(`joystick:${n.id}:x`,n.valueX,e),o=this.handleAnalogState(`joystick:${n.id}:y`,n.valueY,e);this.assignAxisState(t,n.config.horizontalAxis,i),this.assignAxisState(t,n.config.verticalAxis,o),n.config.emitDirections&&(this.assignButtonState(t,this.resolveButtonTarget("Left"),this.handleButtonState(`joystick:${n.id}:left`,n.valueX<=-n.config.directionThreshold,e)),this.assignButtonState(t,this.resolveButtonTarget("Right"),this.handleButtonState(`joystick:${n.id}:right`,n.valueX>=n.config.directionThreshold,e)),this.assignButtonState(t,this.resolveButtonTarget("Up"),this.handleButtonState(`joystick:${n.id}:up`,n.valueY<=-n.config.directionThreshold,e)),this.assignButtonState(t,this.resolveButtonTarget("Down"),this.handleButtonState(`joystick:${n.id}:down`,n.valueY>=n.config.directionThreshold,e)))}return t}getName(){return"virtual-touch"}isConnected(){return this.enabled}dispose(){window.removeEventListener("pointermove",this.onPointerMove),window.removeEventListener("pointerup",this.onPointerUp),window.removeEventListener("pointercancel",this.onPointerUp),window.removeEventListener("blur",this.onWindowBlur),this.rootElement?.remove(),this.rootElement=null,this.buttons.clear(),this.joysticks.clear(),this.buttonStates.clear(),this.analogStates.clear()}resolveEnabledState(){return typeof window>"u"||typeof document>"u"?!1:this.config.enabled===!0?!0:this.config.enabled===!1?!1:N()}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),_(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 wt){let i=xt[n],o=e?.[n];if(o===!1)continue;let s={...i,...o??{},style:{...i.style,...o?.style},position:{...i.position,...o?.position},label:o?.label??i.label??n,size:o?.size??i.size??72};s.enabled!==!1&&t.push([n,s])}return t}resolveJoysticks(){if(this.config.joysticks===!1)return[];let e=this.config.joysticks,t=[];for(let n of["left","right"]){let i=Gt[n],o=e?.[n];if(o===!1)continue;let s={...i,...o??{},style:{...i.style,...o?.style},position:{...i.position,...o?.position},svg:{...i.svg,...o?.svg},size:o?.size??i.size??140,thumbSize:o?.thumbSize??i.thumbSize??58,maxDistance:o?.maxDistance??i.maxDistance??44,deadzone:o?.deadzone??i.deadzone??.12,directionThreshold:o?.directionThreshold??i.directionThreshold??.34,horizontalAxis:o?.horizontalAxis??i.horizontalAxis??"Horizontal",verticalAxis:o?.verticalAxis??i.verticalAxis??"Vertical",emitDirections:o?.emitDirections??i.emitDirections??!1};s.enabled!==!1&&t.push([n,s])}return t}createButton(e,t){let n=document.createElement("button"),i=document.createElement("div");n.type="button",n.ariaLabel=t.label,n.className=`zylem-virtual-touch__button zylem-virtual-touch__button--${e}`,n.dataset.zylemTouchButton=e,n.dataset.active="false",n.style.position="absolute",n.style.width=`${t.size}px`,n.style.height=`${t.size}px`,n.style.padding="0",n.style.margin="0",n.style.border="0",n.style.background="transparent",n.style.pointerEvents="auto",n.style.touchAction="none",n.style.cursor="pointer",n.style.appearance="none",n.style.outline="none",n.style.userSelect="none",n.style.WebkitTapHighlightColor="transparent",_(n,t.position),_(n,t.style),this.appendClassName(n,t.className),i.className="zylem-virtual-touch__button-content",i.style.width="100%",i.style.height="100%",i.style.pointerEvents="none",i.style.transform="scale(1)",i.style.transformOrigin="center",i.style.transition="transform 120ms ease, opacity 120ms ease",i.style.opacity="0.92",i.innerHTML=t.svg??Rt(t.label),n.appendChild(i),n.addEventListener("pointerdown",s=>{if(!tt(s))return;let r=this.buttons.get(e);!r||r.pointerId!==null||(this.consumeEvent(s),r.pointerId=s.pointerId,this.updateButtonVisual(r,!0))});let o={slot:e,config:t,element:n,content:i,pointerId:null};return this.buttons.set(e,o),n}createJoystick(e,t){let n=document.createElement("div"),i=document.createElement("div"),o=document.createElement("div");n.className=`zylem-virtual-touch__joystick zylem-virtual-touch__joystick--${e}`,n.dataset.zylemTouchJoystick=e,n.dataset.active="false",n.style.position="absolute",n.style.width=`${t.size}px`,n.style.height=`${t.size}px`,n.style.pointerEvents="auto",n.style.touchAction="none",n.style.userSelect="none",_(n,t.position),_(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??Tt(),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??Pt(),n.append(i,o);let s={id:e,config:t,element:n,base:i,thumb:o,pointerId:null,centerX:0,centerY:0,rawX:0,rawY:0,valueX:0,valueY:0};return this.joysticks.set(e,s),n.addEventListener("pointerdown",r=>{if(!tt(r))return;let l=this.joysticks.get(e);if(!l||l.pointerId!==null)return;this.consumeEvent(r);let p=l.element.getBoundingClientRect();l.pointerId=r.pointerId,l.centerX=p.left+p.width/2,l.centerY=p.top+p.height/2,this.updateJoystickVisual(l,!0),this.updateJoystickFromPoint(l,r.clientX,r.clientY)}),n}handleButtonState(e,t,n){let i=this.buttonStates.get(e);return i||(i={pressed:!1,released:!1,held:0},this.buttonStates.set(e,i)),i.pressed=t&&i.held===0,i.released=!t&&i.held>0,i.held=t?i.held+n:0,i}handleAnalogState(e,t,n){let i=this.analogStates.get(e);return i||(i={value:0,held:0},this.analogStates.set(e,i)),i.value=t,i.held=t!==0?i.held+n:0,i}assignAxisState(e,t,n){e.axes||(e.axes={}),e.axes[t]=w(e.axes[t],n)}assignButtonState(e,t,n){if(t.category==="buttons"){e.buttons??={},e.buttons[t.property]=m(e.buttons[t.property],n);return}if(t.category==="directions"){e.directions??={},e.directions[t.property]=m(e.directions[t.property],n);return}e.shoulders??={},e.shoulders[t.property]=m(e.shoulders[t.property],n)}resolveButtonTarget(e){switch(e){case"LTrigger":case"RTrigger":return{category:"shoulders",property:e};case"Up":case"Down":case"Left":case"Right":return{category:"directions",property:e};default:return{category:"buttons",property:e}}}updateJoystickFromPoint(e,t,n){let i=t-e.centerX,o=n-e.centerY,s=Math.hypot(i,o),r=e.config.maxDistance,l=s>r&&s>0?r/s:1;e.rawX=i*l,e.rawY=o*l;let p=Et(e.rawX/r,e.rawY/r,e.config.deadzone);e.valueX=p.x,e.valueY=p.y,e.thumb.style.transform=`translate(-50%, -50%) translate(${e.rawX}px, ${e.rawY}px)`}releaseButton(e){e.pointerId=null,this.updateButtonVisual(e,!1)}releaseJoystick(e){e.pointerId=null,e.rawX=0,e.rawY=0,e.valueX=0,e.valueY=0,e.thumb.style.transform="translate(-50%, -50%) translate(0px, 0px)",this.updateJoystickVisual(e,!1)}updateButtonVisual(e,t){e.element.dataset.active=String(t),e.content.style.transform=t?"scale(0.94)":"scale(1)",e.content.style.opacity=t?"1":"0.92"}updateJoystickVisual(e,t){e.element.dataset.active=String(t),e.base.style.opacity=t?"1":"0.88",e.thumb.style.opacity=t?"1":"0.94"}consumeEvent(e){e.cancelable&&e.preventDefault(),e.stopPropagation()}appendClassName(e,t){t&&(e.className=`${e.className} ${t}`.trim())}};function _(a,e){if(e)for(let[t,n]of Object.entries(e)){if(n==null)continue;let i=typeof n=="number"&&!Ct.has(t)?`${n}px`:String(n);t.includes("-")?a.style.setProperty(t,i):a.style[t]=i}}function Et(a,e,t){let n=Math.hypot(a,e);if(n===0||n<=t)return{x:0,y:0};let o=Math.min(1,(n-t)/Math.max(1-t,1e-4))/n;return{x:a*o,y:e*o}}function Rt(a){let e=Bt(a);return`
|
|
1
|
+
import{b as Fe,d as H,k as D,y as J,z as F}from"./chunk-P6IOYQHU.js";import{g as Ue}from"./chunk-PCFF4LLO.js";import{b as x}from"./chunk-OCQ7A5IK.js";import{b as We,c as je}from"./chunk-KIFB427K.js";import{c as K,e as Ke,f as Je}from"./chunk-2HSR5XDQ.js";import{e as ce,g as me,h as Ne,i as he,j as Xe,k as Ye,l as ge,n as Ze}from"./chunk-VKWJHFUR.js";import{d as v,g as He,h as de}from"./chunk-UM5VNQPY.js";import{k as et}from"./chunk-YRHRMVHS.js";import{a as ye,t as be}from"./chunk-VXE3CV3K.js";import{j as $e}from"./chunk-6FGXC4T6.js";import{a as _e,b as E}from"./chunk-AIQ6IVT5.js";import{t as Qe}from"./chunk-2XMG3NJS.js";import{b as qe}from"./chunk-7GYFZKK7.js";import{c as k}from"./chunk-D2PATZCC.js";import{c as ke,d as V,e as De,h as Ae,i as ze,j as Ve,k as pe,l as O,m as Oe}from"./chunk-4QLJUQSJ.js";import{j as fe}from"./chunk-7WRQ2UAN.js";import{l as L}from"./chunk-UG22Z42P.js";function yt(){return{pressed:!1,released:!1,held:0}}function bt(){return{value:0,held:0}}function $(a){let e=new Map;if(!a)return e;for(let[t,n]of Object.entries(a)){if(!n||n.length===0)continue;let i=[];for(let o of n){let[s,r]=(o||"").split(".");if(!s||!r)continue;let l=s.toLowerCase(),p=r.toLowerCase();if(l==="buttons"){let u={a:"A",b:"B",x:"X",y:"Y",start:"Start",select:"Select",l:"L",r:"R"}[p];u&&i.push({category:"buttons",property:u})}else if(l==="directions"){let u={up:"Up",down:"Down",left:"Left",right:"Right"}[p];u&&i.push({category:"directions",property:u})}else if(l==="shoulders"){let u={ltrigger:"LTrigger",rtrigger:"RTrigger"}[p];u&&i.push({category:"shoulders",property:u})}else if(l==="axes"){let u={left:{property:"Horizontal",direction:-1},right:{property:"Horizontal",direction:1},up:{property:"Vertical",direction:-1},down:{property:"Vertical",direction:1},secondaryleft:{property:"SecondaryHorizontal",direction:-1},secondaryright:{property:"SecondaryHorizontal",direction:1},secondaryup:{property:"SecondaryVertical",direction:-1},secondarydown:{property:"SecondaryVertical",direction:1}}[p];u&&i.push({category:"axes",property:u.property,axisDirection:u.direction})}}i.length>0&&e.set(t,i)}return e}function m(a,e){return!a&&!e?yt():a?e?{pressed:a.pressed||e.pressed,released:a.released||e.released,held:a.held+e.held}:{...a}:{...e}}function w(a,e){return!a&&!e?bt():a?e?{value:a.value+e.value,held:a.held+e.held}:{...a}:{...e}}var A=class{keyStates=new Map;keyButtonStates=new Map;analogStates=new Map;compiledMapping;includeDefaultBase=!0;onKeyDown=({key:e})=>this.keyStates.set(e,!0);onKeyUp=({key:e})=>this.keyStates.set(e,!1);constructor(e,t){this.includeDefaultBase=t?.includeDefaultBase??!0,this.compiledMapping=$(e??null),window.addEventListener("keydown",this.onKeyDown),window.addEventListener("keyup",this.onKeyUp)}dispose(){window.removeEventListener("keydown",this.onKeyDown),window.removeEventListener("keyup",this.onKeyUp),this.keyStates.clear(),this.keyButtonStates.clear(),this.analogStates.clear()}isKeyPressed(e){return this.keyStates.get(e)||!1}handleButtonState(e,t){let n=this.keyButtonStates.get(e);n||(n={pressed:!1,released:!1,held:0},this.keyButtonStates.set(e,n));let i=this.isKeyPressed(e);return n.pressed=i&&n.held===0,n.released=!i&&n.held>0,n.held=i?n.held+t:0,n}handleAnalogState(e,t,n){let i=`${e}:${t}`,o=this.analogStates.get(i);return o||(o={value:0,held:0},this.analogStates.set(i,o)),o.value=this.getAxisValue(e,t),o.held=o.value!==0?o.held+n:0,o}applyCustomMapping(e,t){if(this.compiledMapping.size===0)return e;let n=new Map;for(let[i,o]of this.compiledMapping.entries()){let s=null;for(let r of o)if(r.category==="axes")n.has(r.property)||n.set(r.property,0),this.isKeyPressed(i)&&n.set(r.property,n.get(r.property)+r.axisDirection);else{s||(s=this.handleButtonState(i,t));let l=e[r.category]??={};l[r.property]=m(l[r.property],s)}}if(n.size>0){e.axes||(e.axes={});for(let[i,o]of n.entries()){let s=`custom:${i}`,r=this.analogStates.get(s);r||(r={value:0,held:0},this.analogStates.set(s,r)),r.value=o,r.held=o!==0?r.held+t:0,e.axes[i]=w(e.axes[i],r)}}return e}getInput(e){let t={};return this.includeDefaultBase&&(t.buttons={A:this.handleButtonState("z",e),B:this.handleButtonState("x",e),X:this.handleButtonState("a",e),Y:this.handleButtonState("s",e),Start:this.handleButtonState(" ",e),Select:this.handleButtonState("Enter",e),L:this.handleButtonState("q",e),R:this.handleButtonState("e",e)},t.directions={Up:this.handleButtonState("ArrowUp",e),Down:this.handleButtonState("ArrowDown",e),Left:this.handleButtonState("ArrowLeft",e),Right:this.handleButtonState("ArrowRight",e)},t.shoulders={LTrigger:this.handleButtonState("Q",e),RTrigger:this.handleButtonState("E",e)}),this.applyCustomMapping(t,e)}getName(){return"keyboard"}getAxisValue(e,t){return(this.isKeyPressed(t)?1:0)-(this.isKeyPressed(e)?1:0)}isConnected(){return!0}};var W=class{gamepadIndex;connected=!1;buttonStates={};analogStates={};onConnected=e=>{e.gamepad.index===this.gamepadIndex&&(this.connected=!0)};onDisconnected=e=>{e.gamepad.index===this.gamepadIndex&&(this.connected=!1)};constructor(e){this.gamepadIndex=e,window.addEventListener("gamepadconnected",this.onConnected),window.addEventListener("gamepaddisconnected",this.onDisconnected)}dispose(){window.removeEventListener("gamepadconnected",this.onConnected),window.removeEventListener("gamepaddisconnected",this.onDisconnected),this.buttonStates={},this.analogStates={}}handleButtonState(e,t,n){let i=this.buttonStates[e];i||(i={pressed:!1,released:!1,held:0},this.buttonStates[e]=i);let o=t.buttons[e].pressed;return i.pressed=o&&i.held===0,i.released=!o&&i.held>0,i.held=o?i.held+n:0,i}handleAnalogState(e,t,n){let i=this.analogStates[e];return i||(i={value:0,held:0},this.analogStates[e]=i),i.value=t.axes[e],i.held=i.value!==0?i.held+n:0,i}getInput(e){let t=navigator.getGamepads()[this.gamepadIndex];return t?{buttons:{A:this.handleButtonState(0,t,e),B:this.handleButtonState(1,t,e),X:this.handleButtonState(2,t,e),Y:this.handleButtonState(3,t,e),Start:this.handleButtonState(9,t,e),Select:this.handleButtonState(8,t,e),L:this.handleButtonState(4,t,e),R:this.handleButtonState(5,t,e)},directions:{Up:this.handleButtonState(12,t,e),Down:this.handleButtonState(13,t,e),Left:this.handleButtonState(14,t,e),Right:this.handleButtonState(15,t,e)},axes:{Horizontal:this.handleAnalogState(0,t,e),Vertical:this.handleAnalogState(1,t,e),SecondaryHorizontal:this.handleAnalogState(2,t,e),SecondaryVertical:this.handleAnalogState(3,t,e)},shoulders:{LTrigger:this.handleButtonState(6,t,e),RTrigger:this.handleButtonState(7,t,e)}}:{}}getName(){return`gamepad-${this.gamepadIndex+1}`}isConnected(){return this.connected}};import{subscribe as vt}from"valtio/vanilla";var St=.002;function j(a,e,t){return Math.max(e,Math.min(t,a))}function wt(a){if(a instanceof HTMLCanvasElement)return a;let e=a.querySelector("canvas");if(e instanceof HTMLCanvasElement)return e;for(let t of a.querySelectorAll("*")){let n=t.shadowRoot;if(!n)continue;let i=n.querySelector("canvas");if(i instanceof HTMLCanvasElement)return i}return null}var U=class{buttonStates=new Map;analogStates=new Map;compiledMapping;movementX=0;movementY=0;pointerX=.5;pointerY=.5;pointerCenterX=0;pointerCenterY=0;mouseButtonDown=new Set;sensitivity;usePointerLock;lookMode;isLocked=!1;targetElement;debugUnsubscribe=null;updatePointerPosition(e,t){this.pointerX=e/window.innerWidth,this.pointerY=t/window.innerHeight;let n=wt(this.targetElement);if(n){let i=n.getBoundingClientRect();if(i.width>0&&i.height>0){let o=i.left+i.width/2,s=i.top+i.height/2;this.pointerCenterX=j((e-o)/(i.width/2),-1,1),this.pointerCenterY=j((t-s)/(i.height/2),-1,1);return}}this.pointerCenterX=j((this.pointerX-.5)*2,-1,1),this.pointerCenterY=j((this.pointerY-.5)*2,-1,1)}onMouseMove=e=>{this.updatePointerPosition(e.clientX,e.clientY),!(v.enabled||this.lookMode==="screenCenter")&&(this.movementX+=e.movementX,this.movementY+=e.movementY)};onMouseDown=e=>{let t=e.target;t instanceof HTMLCanvasElement&&this.targetElement.contains(t)&&(this.mouseButtonDown.add(e.button),this.usePointerLock&&!this.isLocked&&!v.enabled&&this.targetElement.requestPointerLock())};onMouseUp=e=>{this.mouseButtonDown.delete(e.button)};onContextMenu=e=>{e.preventDefault()};onPointerLockChange=()=>{this.isLocked=document.pointerLockElement===this.targetElement};constructor(e,t){this.sensitivity=e?.sensitivity??St,this.lookMode=e?.lookMode??"delta",this.usePointerLock=e?.pointerLock??!1,this.compiledMapping=$(e?.mapping??null),this.targetElement=t??document.body,window.addEventListener("mousemove",this.onMouseMove),this.targetElement.addEventListener("mousedown",this.onMouseDown),this.targetElement.addEventListener("mouseup",this.onMouseUp),this.targetElement.addEventListener("contextmenu",this.onContextMenu),this.usePointerLock&&(document.addEventListener("pointerlockchange",this.onPointerLockChange),this.debugUnsubscribe=vt(v,()=>{v.enabled&&document.pointerLockElement===this.targetElement&&document.exitPointerLock()}))}dispose(){window.removeEventListener("mousemove",this.onMouseMove),this.targetElement.removeEventListener("mousedown",this.onMouseDown),this.targetElement.removeEventListener("mouseup",this.onMouseUp),this.targetElement.removeEventListener("contextmenu",this.onContextMenu),document.removeEventListener("pointerlockchange",this.onPointerLockChange),this.debugUnsubscribe?.(),this.debugUnsubscribe=null,this.isLocked&&document.exitPointerLock(),this.buttonStates.clear(),this.analogStates.clear(),this.mouseButtonDown.clear(),this.movementX=0,this.movementY=0}handleMouseButton(e,t){let n=this.buttonStates.get(e);n||(n={pressed:!1,released:!1,held:0},this.buttonStates.set(e,n));let i=this.mouseButtonDown.has(e);return n.pressed=i&&n.held===0,n.released=!i&&n.held>0,n.held=i?n.held+t:0,n}handleMovementAxis(e,t){let n=this.analogStates.get(e);n||(n={value:0,held:0},this.analogStates.set(e,n));let i=e==="x"?this.movementX:this.movementY;return n.value=Math.max(-1,Math.min(1,i*this.sensitivity)),n.held=n.value!==0?n.held+t:0,n}applyCustomMapping(e,t){if(this.compiledMapping.size===0)return e;let n=new Map,i={leftbutton:()=>this.handleMouseButton(0,t),rightbutton:()=>this.handleMouseButton(2,t),middlebutton:()=>this.handleMouseButton(1,t)};for(let[o,s]of this.compiledMapping.entries()){let r=o.toLowerCase();for(let l of s)if(l.category==="axes")n.has(l.property)||n.set(l.property,0),r==="movex"?n.set(l.property,n.get(l.property)+Math.max(-1,Math.min(1,this.movementX*this.sensitivity))*l.axisDirection):r==="movey"?n.set(l.property,n.get(l.property)+Math.max(-1,Math.min(1,this.movementY*this.sensitivity))*l.axisDirection):r in i&&this.mouseButtonDown.has(this.buttonIndexForAction(r))&&n.set(l.property,n.get(l.property)+l.axisDirection);else{let p=i[r];if(p){let g=p();if(g){let u=e[l.category]??={};u[l.property]=m(u[l.property],g)}}}}if(n.size>0){e.axes||(e.axes={});for(let[o,s]of n.entries()){let r=`custom:${o}`,l=this.analogStates.get(r);l||(l={value:0,held:0},this.analogStates.set(r,l)),l.value=Math.max(-1,Math.min(1,s)),l.held=s!==0?l.held+t:0,e.axes[o]=w(e.axes[o],l)}}return e}buttonIndexForAction(e){switch(e){case"leftbutton":return 0;case"middlebutton":return 1;case"rightbutton":return 2;default:return-1}}getInput(e){v.enabled&&(this.movementX=0,this.movementY=0);let t={value:0,held:0},n=this.lookMode==="delta",i={axes:{Horizontal:t,Vertical:t,SecondaryHorizontal:n?this.handleMovementAxis("x",e):t,SecondaryVertical:n?this.handleMovementAxis("y",e):t},shoulders:{LTrigger:this.handleMouseButton(0,e),RTrigger:this.handleMouseButton(2,e)},pointer:{x:this.pointerX,y:this.pointerY,centerX:this.pointerCenterX,centerY:this.pointerCenterY}};return this.movementX=0,this.movementY=0,this.applyCustomMapping(i,e)}getName(){return"mouse"}isConnected(){return!0}};function _(a={}){if(typeof window>"u"||typeof navigator>"u")return!1;let e=navigator.userAgent,t=/android/i.test(e)||/iPad|iPhone|iPod/.test(e),n="ontouchstart"in window||navigator.maxTouchPoints>0,i=typeof window.matchMedia=="function"?window.matchMedia("(pointer: coarse)").matches:!1,o=a.viewportSize?.width??window.innerWidth??0,s=a.viewportSize?.height??window.innerHeight??0,r=Math.max(o,s),l=r===0||r<=1024;return a.allowViewportOnly&&a.viewportSize?l:t||(n||i)&&l}var Ct=["A","B","X","Y","Start","Select","L","R","LTrigger","RTrigger","Up","Down","Left","Right"],xt=new Set(["flex","flexGrow","flexShrink","fontWeight","lineHeight","opacity","order","zIndex","zoom"]),Et={A:{size:72,label:"A",position:{right:98,bottom:44}},B:{size:72,label:"B",position:{right:24,bottom:108}},X:{size:72,label:"X",position:{right:172,bottom:108}},Y:{size:72,label:"Y",position:{right:98,bottom:172}},Start:{size:64,label:"Start",position:{left:"50%",top:24,transform:"translateX(28px)"}},Select:{size:64,label:"Select",position:{left:"50%",top:24,transform:"translateX(-108px)"}},L:{size:62,label:"L",position:{left:28,bottom:184}},R:{size:62,label:"R",position:{right:236,bottom:184}},LTrigger:{size:76,label:"LT",position:{left:24,top:24}},RTrigger:{size:76,label:"RT",position:{right:24,top:24}},Up:{enabled:!1,size:64,label:"Up"},Down:{enabled:!1,size:64,label:"Down"},Left:{enabled:!1,size:64,label:"Left"},Right:{enabled:!1,size:64,label:"Right"}},Gt={left:{size:140,thumbSize:58,maxDistance:44,deadzone:.12,directionThreshold:.34,horizontalAxis:"Horizontal",verticalAxis:"Vertical",emitDirections:!0,position:{left:24,bottom:24}},right:{size:140,thumbSize:58,maxDistance:44,deadzone:.12,directionThreshold:.34,horizontalAxis:"SecondaryHorizontal",verticalAxis:"SecondaryVertical",emitDirections:!1,position:{right:24,bottom:236}}},X=class{config;targetElement;buttonStates=new Map;analogStates=new Map;buttons=new Map;joysticks=new Map;rootElement=null;enabled=!1;onPointerMove=e=>{for(let t of this.joysticks.values())t.pointerId===e.pointerId&&(this.consumeEvent(e),this.updateJoystickFromPoint(t,e.clientX,e.clientY))};onPointerUp=e=>{for(let t of this.buttons.values())t.pointerId===e.pointerId&&(this.consumeEvent(e),this.releaseButton(t));for(let t of this.joysticks.values())t.pointerId===e.pointerId&&(this.consumeEvent(e),this.releaseJoystick(t))};onWindowBlur=()=>{for(let e of this.buttons.values())this.releaseButton(e);for(let e of this.joysticks.values())this.releaseJoystick(e)};constructor(e,t){this.config=e??{},this.targetElement=t??document.body,this.enabled=this.resolveEnabledState(),this.enabled&&(this.mountControls(),window.addEventListener("pointermove",this.onPointerMove),window.addEventListener("pointerup",this.onPointerUp),window.addEventListener("pointercancel",this.onPointerUp),window.addEventListener("blur",this.onWindowBlur))}getInput(e){if(!this.enabled)return{};let t={};for(let n of this.buttons.values()){let i=this.handleButtonState(`button:${n.slot}`,n.pointerId!==null,e);this.assignButtonState(t,this.resolveButtonTarget(n.slot),i)}for(let n of this.joysticks.values()){let i=this.handleAnalogState(`joystick:${n.id}:x`,n.valueX,e),o=this.handleAnalogState(`joystick:${n.id}:y`,n.valueY,e);this.assignAxisState(t,n.config.horizontalAxis,i),this.assignAxisState(t,n.config.verticalAxis,o),n.config.emitDirections&&(this.assignButtonState(t,this.resolveButtonTarget("Left"),this.handleButtonState(`joystick:${n.id}:left`,n.valueX<=-n.config.directionThreshold,e)),this.assignButtonState(t,this.resolveButtonTarget("Right"),this.handleButtonState(`joystick:${n.id}:right`,n.valueX>=n.config.directionThreshold,e)),this.assignButtonState(t,this.resolveButtonTarget("Up"),this.handleButtonState(`joystick:${n.id}:up`,n.valueY<=-n.config.directionThreshold,e)),this.assignButtonState(t,this.resolveButtonTarget("Down"),this.handleButtonState(`joystick:${n.id}:down`,n.valueY>=n.config.directionThreshold,e)))}return t}getName(){return"virtual-touch"}isConnected(){return this.enabled}dispose(){window.removeEventListener("pointermove",this.onPointerMove),window.removeEventListener("pointerup",this.onPointerUp),window.removeEventListener("pointercancel",this.onPointerUp),window.removeEventListener("blur",this.onWindowBlur),this.rootElement?.remove(),this.rootElement=null,this.buttons.clear(),this.joysticks.clear(),this.buttonStates.clear(),this.analogStates.clear()}resolveEnabledState(){return typeof window>"u"||typeof document>"u"?!1:this.config.enabled===!0?!0:this.config.enabled===!1?!1:_()}mountControls(){this.rootElement=document.createElement("div"),this.rootElement.className="zylem-virtual-touch",this.rootElement.dataset.zylemTouchRoot="true",this.rootElement.style.position="absolute",this.rootElement.style.inset="0",this.rootElement.style.pointerEvents="none",this.rootElement.style.touchAction="none",this.rootElement.style.userSelect="none",this.rootElement.style.WebkitUserSelect="none",this.rootElement.style.WebkitTouchCallout="none",this.rootElement.style.color="rgba(245, 247, 255, 0.96)",this.rootElement.style.zIndex="20",this.appendClassName(this.rootElement,this.config.className),N(this.rootElement,this.config.style),this.rootElement.addEventListener("contextmenu",e=>e.preventDefault());for(let[e,t]of this.resolveButtons())this.rootElement.appendChild(this.createButton(e,t));for(let[e,t]of this.resolveJoysticks())this.rootElement.appendChild(this.createJoystick(e,t));this.targetElement.appendChild(this.rootElement)}resolveButtons(){if(this.config.buttons===!1)return[];let e=this.config.buttons,t=[];for(let n of Ct){let i=Et[n],o=e?.[n];if(o===!1)continue;let s={...i,...o??{},style:{...i.style,...o?.style},position:{...i.position,...o?.position},label:o?.label??i.label??n,size:o?.size??i.size??72};s.enabled!==!1&&t.push([n,s])}return t}resolveJoysticks(){if(this.config.joysticks===!1)return[];let e=this.config.joysticks,t=[];for(let n of["left","right"]){let i=Gt[n],o=e?.[n];if(o===!1)continue;let s={...i,...o??{},style:{...i.style,...o?.style},position:{...i.position,...o?.position},svg:{...i.svg,...o?.svg},size:o?.size??i.size??140,thumbSize:o?.thumbSize??i.thumbSize??58,maxDistance:o?.maxDistance??i.maxDistance??44,deadzone:o?.deadzone??i.deadzone??.12,directionThreshold:o?.directionThreshold??i.directionThreshold??.34,horizontalAxis:o?.horizontalAxis??i.horizontalAxis??"Horizontal",verticalAxis:o?.verticalAxis??i.verticalAxis??"Vertical",emitDirections:o?.emitDirections??i.emitDirections??!1};s.enabled!==!1&&t.push([n,s])}return t}createButton(e,t){let n=document.createElement("button"),i=document.createElement("div");n.type="button",n.ariaLabel=t.label,n.className=`zylem-virtual-touch__button zylem-virtual-touch__button--${e}`,n.dataset.zylemTouchButton=e,n.dataset.active="false",n.style.position="absolute",n.style.width=`${t.size}px`,n.style.height=`${t.size}px`,n.style.padding="0",n.style.margin="0",n.style.border="0",n.style.background="transparent",n.style.pointerEvents="auto",n.style.touchAction="none",n.style.cursor="pointer",n.style.appearance="none",n.style.outline="none",n.style.userSelect="none",n.style.WebkitTapHighlightColor="transparent",N(n,t.position),N(n,t.style),this.appendClassName(n,t.className),i.className="zylem-virtual-touch__button-content",i.style.width="100%",i.style.height="100%",i.style.pointerEvents="none",i.style.transform="scale(1)",i.style.transformOrigin="center",i.style.transition="transform 120ms ease, opacity 120ms ease",i.style.opacity="0.92",i.innerHTML=t.svg??Rt(t.label),n.appendChild(i),n.addEventListener("pointerdown",s=>{if(!tt(s))return;let r=this.buttons.get(e);!r||r.pointerId!==null||(this.consumeEvent(s),r.pointerId=s.pointerId,this.updateButtonVisual(r,!0))});let o={slot:e,config:t,element:n,content:i,pointerId:null};return this.buttons.set(e,o),n}createJoystick(e,t){let n=document.createElement("div"),i=document.createElement("div"),o=document.createElement("div");n.className=`zylem-virtual-touch__joystick zylem-virtual-touch__joystick--${e}`,n.dataset.zylemTouchJoystick=e,n.dataset.active="false",n.style.position="absolute",n.style.width=`${t.size}px`,n.style.height=`${t.size}px`,n.style.pointerEvents="auto",n.style.touchAction="none",n.style.userSelect="none",N(n,t.position),N(n,t.style),this.appendClassName(n,t.className),i.className="zylem-virtual-touch__joystick-base",i.style.position="absolute",i.style.inset="0",i.style.pointerEvents="none",i.style.opacity="0.88",i.style.transition="opacity 120ms ease",i.innerHTML=t.svg?.base??Pt(),o.className="zylem-virtual-touch__joystick-thumb",o.style.position="absolute",o.style.left="50%",o.style.top="50%",o.style.width=`${t.thumbSize}px`,o.style.height=`${t.thumbSize}px`,o.style.pointerEvents="none",o.style.transform="translate(-50%, -50%) translate(0px, 0px)",o.style.transition="transform 60ms linear, opacity 120ms ease",o.style.opacity="0.94",o.innerHTML=t.svg?.thumb??Bt(),n.append(i,o);let s={id:e,config:t,element:n,base:i,thumb:o,pointerId:null,centerX:0,centerY:0,rawX:0,rawY:0,valueX:0,valueY:0};return this.joysticks.set(e,s),n.addEventListener("pointerdown",r=>{if(!tt(r))return;let l=this.joysticks.get(e);if(!l||l.pointerId!==null)return;this.consumeEvent(r);let p=l.element.getBoundingClientRect();l.pointerId=r.pointerId,l.centerX=p.left+p.width/2,l.centerY=p.top+p.height/2,this.updateJoystickVisual(l,!0),this.updateJoystickFromPoint(l,r.clientX,r.clientY)}),n}handleButtonState(e,t,n){let i=this.buttonStates.get(e);return i||(i={pressed:!1,released:!1,held:0},this.buttonStates.set(e,i)),i.pressed=t&&i.held===0,i.released=!t&&i.held>0,i.held=t?i.held+n:0,i}handleAnalogState(e,t,n){let i=this.analogStates.get(e);return i||(i={value:0,held:0},this.analogStates.set(e,i)),i.value=t,i.held=t!==0?i.held+n:0,i}assignAxisState(e,t,n){e.axes||(e.axes={}),e.axes[t]=w(e.axes[t],n)}assignButtonState(e,t,n){if(t.category==="buttons"){e.buttons??={},e.buttons[t.property]=m(e.buttons[t.property],n);return}if(t.category==="directions"){e.directions??={},e.directions[t.property]=m(e.directions[t.property],n);return}e.shoulders??={},e.shoulders[t.property]=m(e.shoulders[t.property],n)}resolveButtonTarget(e){switch(e){case"LTrigger":case"RTrigger":return{category:"shoulders",property:e};case"Up":case"Down":case"Left":case"Right":return{category:"directions",property:e};default:return{category:"buttons",property:e}}}updateJoystickFromPoint(e,t,n){let i=t-e.centerX,o=n-e.centerY,s=Math.hypot(i,o),r=e.config.maxDistance,l=s>r&&s>0?r/s:1;e.rawX=i*l,e.rawY=o*l;let p=Tt(e.rawX/r,e.rawY/r,e.config.deadzone);e.valueX=p.x,e.valueY=p.y,e.thumb.style.transform=`translate(-50%, -50%) translate(${e.rawX}px, ${e.rawY}px)`}releaseButton(e){e.pointerId=null,this.updateButtonVisual(e,!1)}releaseJoystick(e){e.pointerId=null,e.rawX=0,e.rawY=0,e.valueX=0,e.valueY=0,e.thumb.style.transform="translate(-50%, -50%) translate(0px, 0px)",this.updateJoystickVisual(e,!1)}updateButtonVisual(e,t){e.element.dataset.active=String(t),e.content.style.transform=t?"scale(0.94)":"scale(1)",e.content.style.opacity=t?"1":"0.92"}updateJoystickVisual(e,t){e.element.dataset.active=String(t),e.base.style.opacity=t?"1":"0.88",e.thumb.style.opacity=t?"1":"0.94"}consumeEvent(e){e.cancelable&&e.preventDefault(),e.stopPropagation()}appendClassName(e,t){t&&(e.className=`${e.className} ${t}`.trim())}};function N(a,e){if(e)for(let[t,n]of Object.entries(e)){if(n==null)continue;let i=typeof n=="number"&&!xt.has(t)?`${n}px`:String(n);t.includes("-")?a.style.setProperty(t,i):a.style[t]=i}}function Tt(a,e,t){let n=Math.hypot(a,e);if(n===0||n<=t)return{x:0,y:0};let o=Math.min(1,(n-t)/Math.max(1-t,1e-4))/n;return{x:a*o,y:e*o}}function Rt(a){let e=Mt(a);return`
|
|
2
2
|
<svg viewBox="0 0 100 100" width="100%" height="100%" aria-hidden="true">
|
|
3
3
|
<circle cx="50" cy="50" r="45" fill="rgba(12,18,24,0.72)" stroke="currentColor" stroke-width="4" />
|
|
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" />
|
|
@@ -12,13 +12,13 @@ import{b as Ue,d as H,j as A,x as J,y as U}from"./chunk-NK4IXK5V.js";import{g as
|
|
|
12
12
|
fill="currentColor"
|
|
13
13
|
>${e}</text>
|
|
14
14
|
</svg>
|
|
15
|
-
`}function
|
|
15
|
+
`}function Pt(){return`
|
|
16
16
|
<svg viewBox="0 0 140 140" width="100%" height="100%" aria-hidden="true">
|
|
17
17
|
<circle cx="70" cy="70" r="62" fill="rgba(10,16,20,0.64)" stroke="currentColor" stroke-width="4" />
|
|
18
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
19
|
</svg>
|
|
20
|
-
`}function
|
|
20
|
+
`}function Bt(){return`
|
|
21
21
|
<svg viewBox="0 0 64 64" width="100%" height="100%" aria-hidden="true">
|
|
22
22
|
<circle cx="32" cy="32" r="28" fill="rgba(22,30,38,0.9)" stroke="currentColor" stroke-width="3.5" />
|
|
23
23
|
</svg>
|
|
24
|
-
`}function Bt(a){return a.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""").replaceAll("'","'")}function tt(a){return a.pointerType==="touch"}var q=class{inputMap=new Map;currentInputs={};previousInputs={};targetElement;mouseTargetElement;constructor(e,t){this.targetElement=t?.targetElement,this.mouseTargetElement=t?.mouseTargetElement??t?.targetElement;let n=this.buildPlayerEntries(e);for(let{player:i,config:o,gamepadIndex:s,isP1:r}of n)this.addConfigurableProviders(i,o,r),this.addInputProvider(i,new W(s))}configure(e){let t=this.buildPlayerEntries(e);for(let{player:n,config:i,isP1:o}of t){let r=(this.inputMap.get(n)??[]).filter(l=>l instanceof D||l instanceof F||l instanceof X?(l.dispose(),!1):!0);this.inputMap.set(n,[...this.createConfigurableProviders(i,o),...r])}}addInputProvider(e,t){this.inputMap.has(e)||this.inputMap.set(e,[]),this.inputMap.get(e)?.push(t)}dispose(){for(let e of this.inputMap.values())for(let t of e)t.dispose?.();this.inputMap.clear(),this.currentInputs={},this.previousInputs={}}getInputs(e){let t={};return this.inputMap.forEach((n,i)=>{let o=`p${i}`,s=n.reduce((r,l)=>{let p=l.getInput(e);return this.mergeInputs(r,p)},{});t[o]={playerNumber:i,...s}}),t}buildPlayerEntries(e){return[{player:1,config:e?.p1,gamepadIndex:0,isP1:!0},{player:2,config:e?.p2,gamepadIndex:1,isP1:!1},{player:3,config:e?.p3,gamepadIndex:2,isP1:!1},{player:4,config:e?.p4,gamepadIndex:3,isP1:!1},{player:5,config:e?.p5,gamepadIndex:4,isP1:!1},{player:6,config:e?.p6,gamepadIndex:5,isP1:!1},{player:7,config:e?.p7,gamepadIndex:6,isP1:!1},{player:8,config:e?.p8,gamepadIndex:7,isP1:!1}]}addConfigurableProviders(e,t,n){for(let i of this.createConfigurableProviders(t,n))this.addInputProvider(e,i)}createConfigurableProviders(e,t){let n=[];if(e?.key){let i=e.includeDefaults??t;n.push(new D(e.key,{includeDefaultBase:i}))}else t&&n.push(new D);return e?.mouse&&n.push(new F(e.mouse,this.mouseTargetElement)),e?.touch&&n.push(new X(e.touch,this.targetElement)),n}mergeInputs(e,t){return{buttons:{A:m(e.buttons?.A,t.buttons?.A),B:m(e.buttons?.B,t.buttons?.B),X:m(e.buttons?.X,t.buttons?.X),Y:m(e.buttons?.Y,t.buttons?.Y),Start:m(e.buttons?.Start,t.buttons?.Start),Select:m(e.buttons?.Select,t.buttons?.Select),L:m(e.buttons?.L,t.buttons?.L),R:m(e.buttons?.R,t.buttons?.R)},directions:{Up:m(e.directions?.Up,t.directions?.Up),Down:m(e.directions?.Down,t.directions?.Down),Left:m(e.directions?.Left,t.directions?.Left),Right:m(e.directions?.Right,t.directions?.Right)},axes:{Horizontal:w(e.axes?.Horizontal,t.axes?.Horizontal),Vertical:w(e.axes?.Vertical,t.axes?.Vertical),SecondaryHorizontal:w(e.axes?.SecondaryHorizontal,t.axes?.SecondaryHorizontal),SecondaryVertical:w(e.axes?.SecondaryVertical,t.axes?.SecondaryVertical)},shoulders:{LTrigger:m(e.shoulders?.LTrigger,t.shoulders?.LTrigger),RTrigger:m(e.shoulders?.RTrigger,t.shoulders?.RTrigger)},pointer:t.pointer??e.pointer}}};var Q=class{_previousTime;_currentTime;_startTime;_delta;_elapsed;_timescale;_document;_pageVisibilityHandler;constructor(){this._previousTime=0,this._currentTime=0,this._startTime=ve(),this._delta=0,this._elapsed=0,this._timescale=1,this._document=null,this._pageVisibilityHandler=null}connect(e){this._document=e,e.hidden!==void 0&&(this._pageVisibilityHandler=Mt.bind(this),e.addEventListener("visibilitychange",this._pageVisibilityHandler,!1))}disconnect(){this._pageVisibilityHandler!==null&&(this._document.removeEventListener("visibilitychange",this._pageVisibilityHandler),this._pageVisibilityHandler=null),this._document=null}getDelta(){return this._delta/1e3}getElapsed(){return this._elapsed/1e3}getTimescale(){return this._timescale}setTimescale(e){return this._timescale=e,this}reset(){return this._currentTime=ve()-this._startTime,this}dispose(){this.disconnect()}update(e){return this._pageVisibilityHandler!==null&&this._document.hidden===!0?this._delta=0:(this._previousTime=this._currentTime,this._currentTime=(e!==void 0?e:ve())-this._startTime,this._delta=(this._currentTime-this._previousTime)*this._timescale,this._elapsed+=this._delta),this}};function ve(){return performance.now()}function Mt(){this._document.hidden===!1&&this.reset()}var Y={FourByThree:1.3333333333333333,SixteenByNine:1.7777777777777777,NineBySixteen:.5625,TwentyOneByNine:2.3333333333333335,OneByOne:1},ee=class{container;canvas;aspectRatio;onResize;handleResizeBound;resizeObserver=null;constructor(e){this.container=e.container,this.canvas=e.canvas,this.aspectRatio=(typeof e.aspectRatio=="number",e.aspectRatio),this.onResize=e.onResize,this.handleResizeBound=this.apply.bind(this)}attach(){window.addEventListener("resize",this.handleResizeBound),typeof ResizeObserver<"u"&&(this.resizeObserver=new ResizeObserver(this.handleResizeBound),this.resizeObserver.observe(this.container)),this.apply()}detach(){window.removeEventListener("resize",this.handleResizeBound),this.resizeObserver?.disconnect(),this.resizeObserver=null}measure(){let e=this.container.getBoundingClientRect(),t=Math.round(e.width||this.container.clientWidth||0),n=Math.round(e.height||this.container.clientHeight||0);if(t>0&&n>0){if(t/n>this.aspectRatio){let p=n;return{width:Math.round(p*this.aspectRatio),height:p}}let r=t,l=Math.round(r/this.aspectRatio);return{width:r,height:l}}if(t>0){let s=t,r=Math.round(s/this.aspectRatio);return{width:s,height:r}}if(n>0){let s=n;return{width:Math.round(s*this.aspectRatio),height:s}}let i=window.innerWidth,o=Math.round(i/this.aspectRatio);return{width:i,height:o}}apply(){let{width:e,height:t}=this.measure();this.canvas.style.width=`${e}px`,this.canvas.style.height=`${t}px`,this.onResize?.(e,t)}};var nt={NES:{displayAspect:1.3333333333333333,resolutions:[{key:"256x240",width:256,height:240,notes:"Standard NTSC; effective 240p."}]},SNES:{displayAspect:1.3333333333333333,resolutions:[{key:"256x224",width:256,height:224,notes:"Common 240p-equivalent mode."},{key:"512x448",width:512,height:448,notes:"Hi-res interlaced (480i)."}]},N64:{displayAspect:1.3333333333333333,resolutions:[{key:"320x240",width:320,height:240,notes:"Common 240p mode."},{key:"640x480",width:640,height:480,notes:"Higher resolution (480i)."}]},PS1:{displayAspect:1.3333333333333333,resolutions:[{key:"320x240",width:320,height:240,notes:"Progressive 240p common."},{key:"640x480",width:640,height:480,notes:"Interlaced 480i for higher detail."}]},PS2:{displayAspect:1.3333333333333333,resolutions:[{key:"640x480",width:640,height:480,notes:"480i/480p baseline."},{key:"720x480",width:720,height:480,notes:"480p (widescreen capable in some titles)."},{key:"1280x720",width:1280,height:720,notes:"720p (select titles)."}]},PS5:{displayAspect:1.7777777777777777,resolutions:[{key:"720x480",width:720,height:480,notes:"Legacy compatibility."},{key:"1280x720",width:1280,height:720,notes:"720p."},{key:"1920x1080",width:1920,height:1080,notes:"1080p."},{key:"2560x1440",width:2560,height:1440,notes:"1440p."},{key:"3840x2160",width:3840,height:2160,notes:"4K (up to 120Hz)."},{key:"7680x4320",width:7680,height:4320,notes:"8K (limited)."}]},XboxOne:{displayAspect:1.7777777777777777,resolutions:[{key:"1280x720",width:1280,height:720,notes:"720p (original)."},{key:"1920x1080",width:1920,height:1080,notes:"1080p (original)."},{key:"3840x2160",width:3840,height:2160,notes:"4K UHD (S/X models)."}]},MobilePortrait:{displayAspect:.5625,resolutions:[{key:"360x640",width:360,height:640,notes:"Low-density phone portrait baseline."},{key:"720x1280",width:720,height:1280,notes:"HD phone portrait."},{key:"1080x1920",width:1080,height:1920,notes:"Full HD phone portrait."}]}};function Se(a){return nt[a].displayAspect}function we(a,e){let t=nt[a]?.resolutions||[];if(!e)return t[0];let n=e.toLowerCase().replace(/\s+/g,"").replace("\xD7","x");return t.find(i=>i.key.toLowerCase()===n)}function Ce(a){if(!a)return null;let t=String(a).toLowerCase().trim().replace(/\s+/g,"").replace("\xD7","x").match(/^(\d+)x(\d+)$/);if(!t)return null;let n=parseInt(t[1],10),i=parseInt(t[2],10);return!Number.isFinite(n)||!Number.isFinite(i)?null:{width:n,height:i}}var xe=null,Ge=class{constructor(e,t,n,i,o,s,r,l,p,g,u,d,S){this.id=e;this.globals=t;this.stages=n;this.debug=i;this.time=o;this.input=s;this.aspectRatio=r;this.internalResolution=l;this.fullscreen=p;this.bodyBackground=g;this.container=u;this.containerId=d;this.canvas=S}};function It(a={}){return a.deviceProfile==="mobile"?!0:a.deviceProfile==="desktop"?!1:a.viewportSize?N({viewportSize:a.viewportSize,allowViewportOnly:!0}):N()}function Lt(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 kt(a){let e=a?.id??"zylem";return{id:e,globals:a?.globals??{},stages:a?.stages??[],debug:!!a?.debug,time:a?.time??0,input:a?.input,aspectRatio:Y.SixteenByNine,fullscreen:!0,bodyBackground:"#000000",containerId:e}}var it=360;function at(a,e){if(!a)return;if(typeof a=="string"){if(a==="native")return xe;let i=Ce(a);if(i)return i;if(e){let o=we(e,a);if(o)return{width:o.width,height:o.height}}return}let t=a.width,n=a.height;if(Number.isFinite(t)&&Number.isFinite(n))return{width:t,height:n}}function At(a,e,t,n){if(typeof a=="number")return a;if(typeof a=="string")return Y[a]??t;if(e)try{return Se(e)||t}catch{return t}return n?n.width/n.height:t}function Dt(a){let e=Number.isFinite(a)&&a>0?a:Y.SixteenByNine;if(e>=1){let i=it;return{width:Math.round(i*e),height:i}}let t=it,n=Math.round(t/e);return{width:t,height:n}}function Z(a,e={}){let t=kt({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=Lt(n,a?.container??null),o=a?.mobile,s=It(e),r=s?o?.preset??a?.preset:a?.preset,l=at(a?.resolution,a?.preset),p=at(o?.resolution,o?.preset??a?.preset),g=(s?ot(p):void 0)??ot(l),u=s?o?.aspectRatio??a?.aspectRatio:a?.aspectRatio,d=At(u,r,t.aspectRatio,g),S=zt(s,p,l,d),f=a?.fullscreen??t.fullscreen,E=a?.bodyBackground??t.bodyBackground,P=a?.canvas??void 0,B=Vt(a?.input??t.input,o?.controls);return new Ge(a?.id??t.id,a?.globals??t.globals,a?.stages??t.stages,!!(a?.debug??t.debug),a?.time??t.time,B,d,S,f,E,i,n,P)}function ot(a){if(a)return a}function zt(a,e,t,n){if(a)return e===xe?void 0:e??Dt(n);if(t!==xe)return t}function Vt(a,e){if(!e)return a;let n=Fe("p1",{enabled:"auto",...e===!0?{}:e});return L(n,a??{})}function Ot(a){return{...a}}var te=class{id;container;canvas;bodyBackground;fullscreen;aspectRatio;ratioDelegate=null;overlayContainer=null;constructor(e){this.id=e.id,this.container=this.ensureContainer(e.containerId??e.id,e.container),this.canvas=e.canvas??document.createElement("canvas"),this.bodyBackground=e.bodyBackground,this.fullscreen=!!e.fullscreen,this.aspectRatio=(typeof e.aspectRatio=="number",e.aspectRatio)}applyBodyBackground(){this.bodyBackground&&(document.body.style.background=this.bodyBackground)}mountCanvas(){this.mountChildren(this.canvas)}mountRenderer(e,t){this.mountChildren(e),this.canvas=e,this.attachAspectRatio(t)}getOverlayContainer(){return this.ensureOverlayContainer()}centerIfFullscreen(){if(!this.fullscreen)return;let e=this.container.style;e.display="flex",e.alignItems="center",e.justifyContent="center",e.position="relative",e.inset="0"}attachAspectRatio(e){this.ratioDelegate?(this.ratioDelegate.canvas=this.canvas,this.ratioDelegate.onResize=e,this.ratioDelegate.aspectRatio=this.aspectRatio,this.ratioDelegate.apply()):(this.ratioDelegate=new ee({container:this.container,canvas:this.canvas,aspectRatio:this.aspectRatio,onResize:e}),this.ratioDelegate.attach())}setAspectRatio(e){this.aspectRatio=e,this.ratioDelegate&&(this.ratioDelegate.aspectRatio=e,this.ratioDelegate.apply())}reapplyLayout(){this.ratioDelegate?.apply()}destroy(){this.ratioDelegate?.detach(),this.ratioDelegate=null}mountChildren(e){for(;this.container.firstChild;)this.container.removeChild(this.container.firstChild);this.container.appendChild(e),this.container.appendChild(this.ensureOverlayContainer())}ensureOverlayContainer(){if(this.overlayContainer)return this.overlayContainer;let e=document.createElement("div");return e.dataset.zylemOverlayRoot="true",e.style.position="absolute",e.style.inset="0",e.style.pointerEvents="none",e.style.touchAction="none",e.style.zIndex="10",this.overlayContainer=e,e}ensureContainer(e,t){if(t)return t;if(e){let o=document.getElementById(e);if(o)return o}let n=e||this.id||"zylem-root",i=document.createElement("main");return i.setAttribute("id",n),i.style.position="relative",i.style.width="100%",i.style.height="100%",document.body.appendChild(i),i}};import Ht from"stats.js";import{subscribe as Ut}from"valtio/vanilla";var ne=class{statsRef=null;unsubscribe=null;constructor(){this.updateDebugUI(),this.unsubscribe=Ut(v,()=>{this.updateDebugUI()})}begin(){this.statsRef?.begin()}end(){this.statsRef?.end()}updateDebugUI(){v.enabled&&!this.statsRef?(this.statsRef=new Ht,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)):!v.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 ie=class{loadingHandlers=[];stageLoadingUnsubscribes=[];onLoading(e){return this.loadingHandlers.push(e),()=>{this.loadingHandlers=this.loadingHandlers.filter(t=>t!==e)}}emit(e){for(let n of this.loadingHandlers)try{n(e)}catch(i){console.error("Game loading handler failed",i)}let t=`loading:${e.type}`;G.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 Ft}from"@zylem/bridge";var ae=class{container=null;camera=null;rendererManager=null;gameCanvas=null;config=null;stage=null;mounted=!1;setGameCanvas(e){this.gameCanvas=e,this.tryMount()}setConfig(e){this.config=e,this.tryMount()}setContainer(e){this.container=e,this.tryMount()}setStage(e){this.stage=e,this.mounted&&this.gameCanvas?.reapplyLayout()}setCamera(e){this.camera=e,this.tryMount()}setRendererManager(e){this.rendererManager=e,this.tryMount()}tryMount(){this.mounted||!this.container||!this.gameCanvas||(this.rendererManager?this.mountWithRendererManager():this.camera&&this.mountWithCamera())}mountWithRendererManager(){if(!this.rendererManager||!this.gameCanvas)return;let e=this.rendererManager.getDomElement();this.gameCanvas.mountRenderer(e,(t,n)=>{if(!this.rendererManager)return;let i=this.config?.internalResolution;if(i)this.rendererManager.setPixelRatio(1),this.rendererManager.resize(i.width,i.height),this.stage?.resize(i.width,i.height);else{let o=window.devicePixelRatio||1;this.rendererManager.setPixelRatio(o),this.rendererManager.resize(t,n),this.stage?.resize(t,n)}}),this.mounted=!0}mountWithCamera(){if(!this.camera||!this.gameCanvas)return;let e=this.camera.getDomElement();this.gameCanvas.mountRenderer(e,(t,n)=>{if(!this.camera)return;let i=this.config?.internalResolution;if(i)this.camera.setPixelRatio(1),this.camera.resize(i.width,i.height);else{let o=window.devicePixelRatio||1;this.camera.setPixelRatio(o),this.camera.resize(t,n)}}),this.mounted=!0}reset(){this.camera=null,this.stage=null,this.mounted=!1}dispose(){this.container=null,this.camera=null,this.rendererManager=null,this.gameCanvas=null,this.config=null,this.stage=null,this.mounted=!1}};var oe=class a{id;initialGlobals={};customSetup=null;customUpdate=null;customDestroy=null;stages=[];stageMap=new Map;currentStageId="";previousTimeStamp=0;totalTime=0;timer;inputManager;wrapperRef;globalInputConfig;defaultCamera=null;rendererManager=null;container=null;canvas=null;aspectRatioDelegate=null;resolvedConfig=null;gameCanvas=null;animationFrameId=null;isDisposed=!1;loadInFlight=!1;hasStarted=!1;debugDelegate=null;loadingDelegate=new ie;rendererObserver=new ae;eventBusUnsubscribes=[];thumbnailUnsubscribes=[];lastPublishedGameConfig=null;gameBridge=new Ze;cutscenePreview=new Qe(()=>this.currentStage()?.wrappedStage??null,e=>this.gameBridge.publishCutsceneStatus(e),{},e=>this.gameBridge.publishCutsceneView(e));catalogUnsubscribe=null;gameUpdateParams={};stageSetupParams={};stageUpdateParams={};frameCallback=e=>this.loop(e);sourceOptions;displayRuntime;static FRAME_LIMIT=120;static FRAME_DURATION=1e3/a.FRAME_LIMIT;static MAX_DELTA_SECONDS=1/30;constructor(e,t,n={}){this.wrapperRef=t,this.timer=new Q,this.timer.connect(document),this.sourceOptions={...e},this.displayRuntime={...n};let i=Z(e,this.displayRuntime);this.globalInputConfig=i.input,this.id=i.id,this.stages=i.stages||[],this.container=i.container,this.canvas=i.canvas??null,this.resolvedConfig=i,this.loadGameCanvas(i),this.container=this.gameCanvas?.container??this.container,this.inputManager=new q(i.input,{targetElement:this.gameCanvas?.getOverlayContainer(),mouseTargetElement:this.gameCanvas?.container}),this.loadDebugOptions(e),this.setGlobals(e),We(),je(),this.gameBridge.connect({resolveEntity:o=>this.currentStage()?.wrappedStage?.entityDelegate.childrenMap.get(o)??null,setStageVariable:(o,s)=>{let r=this.currentStage()?.wrappedStage?.state;r&&(r.variables[o]=s)},createEntity:(o,s,r)=>{this.createCatalogEntity(o,s,r)},applySceneOperation:(o,s)=>{this.currentStage()?.wrappedStage?.debugDelegate?.applySceneOperation(o,s)},pickEntity:o=>this.pickEntityAtNdc(o),cutscene:this.cutscenePreview,cameraPose:()=>this.cutscenePreview.cameraPose(),applySwatches:o=>{let s=this.currentStage()?.wrappedStage?.debugDelegate;return s?s.applySwatches(o):{results:o.uuids.flatMap(r=>o.swatches.map(l=>({uuid:r,kind:l.kind,source:l.source,ok:!1,reason:"entity-not-found"}))),entries:[]}}}),this.publishEntityCatalog(),this.catalogUnsubscribe=Je(()=>this.publishEntityCatalog())}pickEntityAtNdc(e){let t=this.currentStage()?.wrappedStage,n=t?.debugDelegate?.pickAtNdc(e.x,e.y);if(!t||!n)return null;let i=t.entityDelegate.childrenMap.get(n.uuid);return i?this.buildEntitySummary(i)??{uuid:n.uuid,name:n.name||"Unnamed",type:ge(i),position:he(i).position,rotation:he(i).rotation,scale:me(i)}:null}publishEntityCatalog(){this.gameBridge.publishCatalog(Ke())}createCatalogEntity(e,t,n){let i=this.currentStage()?.wrappedStage,o=K(e);if(!i||!o)return;let s=n?.position??{x:0,y:0,z:0},r=o.create({position:s,props:{...o.defaultProps??{},...t??{}}});r&&Promise.resolve(r).then(l=>l&&i.entityDelegate.spawnEntity(l)).catch(l=>{console.error("entity:create failed",l)})}setDisplayRuntime(e){this.displayRuntime={...e};let t=Z(this.sourceOptions,this.displayRuntime);this.resolvedConfig=t,this.rendererObserver.setConfig(t),this.gameCanvas?.setAspectRatio(t.aspectRatio),this.publishGameConfig()}loadGameCanvas(e){this.gameCanvas=new te({id:e.id,container:e.container,containerId:e.containerId,canvas:this.canvas??void 0,bodyBackground:e.bodyBackground,fullscreen:e.fullscreen,aspectRatio:e.aspectRatio}),this.gameCanvas.applyBodyBackground(),this.gameCanvas.mountCanvas(),this.gameCanvas.centerIfFullscreen(),this.rendererObserver.setGameCanvas(this.gameCanvas),this.resolvedConfig&&this.rendererObserver.setConfig(this.resolvedConfig),this.container&&this.rendererObserver.setContainer(this.container),this.subscribeToEventBus()}loadDebugOptions(e){e.debug!==void 0&&(v.enabled=!!e.debug),this.debugDelegate=new ne}isLoading(){return this.loadInFlight}async loadStage(e,t=0,n){if(this.loadInFlight){console.warn("loadStage ignored: a stage load is already in progress");return}this.loadInFlight=!0;try{await this.performLoadStage(e,t,n)}finally{this.loadInFlight=!1}}async performLoadStage(e,t=0,n){let i=n?qe(n):null;this.cutscenePreview.releaseStage();let o=this.currentStage()??null,s=o?.wrappedStage??null,r=s?.scene?.scene??null,l=s?.cameraManagerRef?.primaryCamera?.camera??s?.cameraRef?.camera??null;i&&this.rendererManager?.initialized&&o&&r&&l&&this.rendererManager.beginSnapshotTransition(i,r,l),this.unloadCurrentStage();let g=e.options[0];if(this.loadingDelegate.wireStageLoading(e,t),this.rendererManager||(this.rendererManager=new Ue,await this.rendererManager.initRenderer()),x.setRenderer(this.rendererManager.renderer),await e.load(this.id,g?.camera,this.rendererManager),this.stageMap.set(e.wrappedStage.uuid,e),this.currentStageId=e.wrappedStage.uuid,this.defaultCamera=e.wrappedStage.cameraRef,this.wireEntityThumbnails(e),this.rendererObserver.setStage(e.wrappedStage??null),this.rendererManager&&this.rendererObserver.setRendererManager(this.rendererManager),this.applyInputConfig(e),e.onInputConfigChanged=()=>this.applyInputConfig(e),this.hasStarted&&e.wrappedStage&&!e.wrappedStage.hasSetup){let u=this.params(),d={...this.stageSetupParams};d.inputs=u.inputs,d.globals=u.globals,d.camera=u.camera,d.stage=u.stage,d.game=u.game,d.me=e.wrappedStage,e.start(d)}this.publishGameConfig(),this.publishStageSnapshot(),this.cutscenePreview.stageReady()}applyInputConfig(e){let t=L(this.globalInputConfig??{},e.inputConfig??{});this.inputManager.configure(t)}setGlobalInputConfig(e){this.globalInputConfig=e;let t=this.currentStage();t&&this.applyInputConfig(t)}unloadCurrentStage(){if(!this.currentStageId)return;let e=this.getStage(this.currentStageId);if(e){if(this.clearEntityThumbnailWiring(),x.clear(),e.onInputConfigChanged=null,e?.wrappedStage){try{e.wrappedStage.nodeDestroy({me:e.wrappedStage,globals:V.globals})}catch(t){console.error("Failed to destroy previous stage",t)}e.wrappedStage=null}e.dispose(),this.stageMap.delete(this.currentStageId),this.currentStageId="",this.defaultCamera=null,this.rendererObserver.reset()}}setGlobals(e){this.initialGlobals={...e.globals};for(let t in this.initialGlobals){let n=this.initialGlobals[t];n===void 0&&console.error(`global ${t} is undefined`),Ae(t,n)}}params(){let e=this.currentStage(),t=this.timer.getDelta(),n=this.inputManager.getInputs(t),i=e?.wrappedStage?.cameraRef||this.defaultCamera,o=this.gameUpdateParams;return o.delta=t,o.inputs=n,o.globals=Ve(),o.me=this,o.camera=i,o.stage=e,o.game=this.wrapperRef,o}start(){let e=this.currentStage(),t=this.params(),n=this.stageSetupParams;n.inputs=t.inputs,n.globals=t.globals,n.camera=t.camera,n.stage=t.stage,n.game=t.game,n.me=e.wrappedStage,e.start(n),this.customSetup&&this.customSetup(t),this.hasStarted=!0,this.loop(0)}step(e){let t=this.currentStage();if(!t||!t.wrappedStage)return;let n=this.params(),i=e!==void 0?e:n.delta,o=Math.min(Math.max(i,0),a.MAX_DELTA_SECONDS);n.delta=o,this.customUpdate&&this.customUpdate(n);let s=this.currentStage();if(s!==t||!s?.wrappedStage){this.totalTime+=o,V.time=this.totalTime;return}let r=this.stageUpdateParams;r.delta=n.delta,r.inputs=n.inputs,r.globals=n.globals,r.camera=n.camera,r.stage=n.stage,r.game=n.game,r.me=t.wrappedStage,t.wrappedStage?.nodeUpdate(r),this.totalTime+=o,V.time=this.totalTime}loop(e){this.debugDelegate?.begin(),He()||(this.timer.update(e),this.step(),this.previousTimeStamp=e),this.debugDelegate?.end(),this.outOfLoop(),this.cutscenePreview.frame(),this.isDisposed||(this.animationFrameId=requestAnimationFrame(this.frameCallback))}dispose(){this.isDisposed=!0,this.cutscenePreview.unload(),this.catalogUnsubscribe?.(),this.catalogUnsubscribe=null,this.gameBridge.disconnect(),this.animationFrameId!==null&&(cancelAnimationFrame(this.animationFrameId),this.animationFrameId=null),this.unloadCurrentStage(),this.debugDelegate&&(this.debugDelegate.dispose(),this.debugDelegate=null),this.eventBusUnsubscribes.forEach(e=>e()),this.eventBusUnsubscribes=[],this.rendererObserver.dispose(),this.inputManager.dispose(),this.rendererManager&&(x.setRenderer(null),this.rendererManager.dispose(),this.rendererManager=null),x.clear(),Ft().channel.reset(),this.timer.dispose(),this.customDestroy&&this.customDestroy({me:this,globals:V.globals}),O()}outOfLoop(){let e=this.currentStage();e&&e.wrappedStage.outOfLoop()}getStage(e){return this.stageMap.get(e)}currentStage(){return this.getStage(this.currentStageId)}onLoading(e){return this.loadingDelegate.onLoading(e)}buildStageConfigPayload(){let e=this.currentStage();if(!e?.wrappedStage)return null;let t=e.wrappedStage.state,n=t.backgroundColor,i=typeof n=="string"?n:`#${n.getHexString()}`;return{id:e.wrappedStage.uuid,backgroundColor:i,backgroundImage:t.backgroundImage,gravity:{x:t.gravity.x,y:t.gravity.y,z:t.gravity.z},inputs:t.inputs,variables:t.variables}}buildEntitySummary(e){if(H(e.options))return null;let t=e.position??{x:0,y:0,z:0},n=e.rotation??{x:0,y:0,z:0},i=me(e),o=_e(e),s=x.get(e.uuid);return{uuid:e.uuid,name:e.name||"Unnamed",type:ge(e),position:{x:t.x??0,y:t.y??0,z:t.z??0},rotation:{x:n.x??0,y:n.y??0,z:n.z??0},scale:i,quaternion:o,thumbnail:s?.dataUrl??null,bounds:s?.bounds}}buildEntitiesPayload(){let e=this.currentStage();if(!e?.wrappedStage)return[];let t=[];return e.wrappedStage.entityDelegate.childrenMap.forEach(n=>{let i=this.buildEntitySummary(n);i&&t.push(i)}),t}wireEntityThumbnails(e){if(this.clearEntityThumbnailWiring(),!e.wrappedStage)return;let t=s=>{if(!this.gameBridge.wantsThumbnails()||H(s.options))return;let r=s.group??s.mesh??null;r&&x.ensure(s.uuid,r).then(l=>{l&&!this.isDisposed&&this.gameBridge.queueThumbnails([{uuid:s.uuid,url:l.dataUrl,bounds:l.bounds}])})},n=e.wrappedStage.onEntityAdded(s=>{if(this.gameBridge.wantsEntityUpdates()){let r=this.buildEntitySummary(s);r&&this.gameBridge.queueEntityUpsert([r])}t(s)},{replayExisting:!0});this.thumbnailUnsubscribes.push(n);let i=s=>{if(!s.success)return;let r=e.wrappedStage?.entityDelegate.childrenMap.get(s.entityId);r&&(x.invalidate(s.entityId),t(r))};G.on("entity:model:loaded",i),this.thumbnailUnsubscribes.push(()=>{G.off("entity:model:loaded",i)});let o=s=>{x.invalidate(s.entityId),this.gameBridge.wantsEntityUpdates()&&this.gameBridge.queueEntityRemoved([s.entityId])};G.on("entity:destroyed",o),this.thumbnailUnsubscribes.push(()=>{G.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(H(i.options))continue;let o=i.group??i.mesh??null;o&&x.ensure(i.uuid,o).then(s=>{s&&!this.isDisposed&&this.gameBridge.queueThumbnails([{uuid:i.uuid,url:s.dataUrl,bounds:s.bounds}])})}}});this.thumbnailUnsubscribes.push(t)}clearEntityThumbnailWiring(){this.thumbnailUnsubscribes.forEach(e=>{try{e()}catch{}}),this.thumbnailUnsubscribes=[]}buildGameConfigPayload(){return this.resolvedConfig?{id:this.resolvedConfig.id,aspectRatio:this.resolvedConfig.aspectRatio,fullscreen:this.resolvedConfig.fullscreen,bodyBackground:this.resolvedConfig.bodyBackground,internalResolution:this.resolvedConfig.internalResolution,debug:this.resolvedConfig.debug}:null}publishGameConfig(){let e=this.buildGameConfigPayload();if(!e)return;let t=JSON.stringify(e);t!==this.lastPublishedGameConfig&&(this.lastPublishedGameConfig=t,this.gameBridge.publishConfig(e))}publishStageSnapshot(){this.gameBridge.publishStageSnapshot({stage:this.buildStageConfigPayload(),entities:this.buildEntitiesPayload()})}subscribeToEventBus(){this.eventBusUnsubscribes.push(ke.on("game:state:updated",e=>{this.gameBridge.publishVariable({path:e.path,value:e.value,previousValue:e.previousValue})}))}};async function rt(a){let{getGameDefaultConfig:e}=await import("./game-default-BAZPDNPS.js"),t={...e()},n=[],i=[],o=[];Object.values(a).forEach(r=>{if(r instanceof J)i.push(r);else if(r instanceof be)o.push(r);else if(r instanceof ye)o.push(r);else if(r?.constructor?.name==="Object"&&typeof r=="object"){let l=Object.assign({...e()},{...r});n.push(l)}}),n.forEach(r=>{t=Object.assign(t,{...r})});let s=t;return s.input=n[0].input,i.forEach(r=>{r.addEntities(o)}),i.length?s.stages=i:s.stages[0].addEntities(o),s}function st(a){return!!a.find(t=>t instanceof J)}function Ee(a){for(let e of a)if(e&&typeof e=="object"&&!(e instanceof J)&&!(e instanceof ye)&&!(e instanceof be)){let t=e;if(t.globals)return t.globals}}import{proxy as Nt}from"valtio/vanilla";import{get as _t,set as Xt}from"idb-keyval";import{pack as Yt,unpack as Zt}from"msgpackr";var h=Nt({previous:null,current:null,next:null,isLoading:!1}),re={staticRegistry:new Map,registerStaticStage(a,e){this.staticRegistry.set(a,e)},async loadStageData(a){try{let e=await _t(a);if(e)return Zt(e)}catch(e){console.warn(`Failed to load stage ${a} from storage`,e)}if(this.staticRegistry.has(a))return this.staticRegistry.get(a);throw new Error(`Stage ${a} not found in storage and static loading not fully implemented.`)},async transitionForward(a,e){if(!h.isLoading){h.isLoading=!0;try{h.current&&await Xt(h.current.id,Yt(h.current)),h.previous=h.current,h.current=h.next,h.current?.id!==a&&(e?h.current=await e(a):h.current=await this.loadStageData(a)),h.next=null}catch(t){console.error("Failed to transition stage:",t)}finally{h.isLoading=!1}}},async preloadNext(a,e){e?h.next=await e(a):h.next=await this.loadStageData(a)}};var Re={async createFromBlueprint(a){let e=U({});if(a.entities)for(let t of a.entities)try{let n=await et.createFromBlueprint(t);e.add(n)}catch(n){console.error(`Failed to create entity ${t.id} for stage ${a.id}`,n)}return e}};var se=class{wrappedGame=null;options;setupCallbacks=[];updateCallbacks=[];destroyCallbacks=[];pendingLoadingCallbacks=[];globalChangeCallbacks=[];globalChangesCallbacks=[];activeGlobalSubscriptions=[];eventDelegate=new Ne;pendingInputConfig=null;displayRuntime={};refErrorMessage="lost reference to game";constructor(e){this.options=e,st(e)||this.options.push(U());let t=Ee(e);t&&pe(t)}onSetup(...e){return this.setupCallbacks.push(...e),this}onUpdate(...e){return this.updateCallbacks.push(...e),this}onDestroy(...e){return this.destroyCallbacks.push(...e),this}setInputConfiguration(...e){let t=L(...e);return this.pendingInputConfig=t,this.wrappedGame&&this.wrappedGame.setGlobalInputConfig(t),this}async start(){O();let e=Ee(this.options);e&&pe(e);let t=await this.load();return this.wrappedGame=t,this.setOverrides(),this.registerGlobalSubscriptions(),t.start(),this}setDisplayRuntime(e){return this.displayRuntime={...this.displayRuntime,...e},this.wrappedGame&&this.wrappedGame.setDisplayRuntime(this.displayRuntime),this}setDeviceProfile(e){return this.setDisplayRuntime({deviceProfile:e})}setViewportSize(e,t){return this.setDisplayRuntime({viewportSize:{width:e,height:t}})}async load(){let e=await rt(this.options),t=Z(e,this.displayRuntime);this.pendingInputConfig&&(t.input=L(t.input??{},this.pendingInputConfig));let n=new oe({...e,...t},this,this.displayRuntime);for(let i of this.pendingLoadingCallbacks)n.onLoading(i);return await n.loadStage(e.stages[0]),n}setOverrides(){if(!this.wrappedGame){console.error(this.refErrorMessage);return}this.wrappedGame.customSetup=e=>{this.setupCallbacks.forEach(t=>t(e))},this.wrappedGame.customUpdate=e=>{this.updateCallbacks.forEach(t=>t(e))},this.wrappedGame.customDestroy=e=>{this.destroyCallbacks.forEach(t=>t(e))}}onGlobalChange(e,t){return this.globalChangeCallbacks.push({path:e,callback:t}),this}onGlobalChanges(e,t){return this.globalChangesCallbacks.push({paths:e,callback:t}),this}registerGlobalSubscriptions(){for(let{path:e,callback:t}of this.globalChangeCallbacks){let n=De(e,i=>{t(i,this.getCurrentStage())});this.activeGlobalSubscriptions.push(n)}for(let{paths:e,callback:t}of this.globalChangesCallbacks){let n=ze(e,i=>{t(i,this.getCurrentStage())});this.activeGlobalSubscriptions.push(n)}}getCurrentStage(){return this.wrappedGame?.currentStage()??null}experimental={getRuntime:()=>this.getCurrentStage()?.wrappedStage?.world?.simulation??null};async pause(){de(!0)}async resume(){de(!1),this.wrappedGame&&(this.wrappedGame.previousTimeStamp=0,this.wrappedGame.timer.reset())}step(e=1/60){if(!this.wrappedGame){console.error(this.refErrorMessage);return}this.wrappedGame.step(e)}async reset(e){if(!this.wrappedGame){console.error(this.refErrorMessage);return}this.wrappedGame.isLoading()||await this.wrappedGame.loadStage(this.wrappedGame.stages[0],0,e?.transition)}previousStage(e){if(!this.wrappedGame){console.error(this.refErrorMessage);return}if(this.wrappedGame.isLoading())return;let t=this.wrappedGame.currentStageId,n=this.wrappedGame.stages.findIndex(o=>o.wrappedStage?.uuid===t),i=this.wrappedGame.stages[n-1];if(!i){console.error("previous stage called on first stage");return}this.wrappedGame.loadStage(i,n-1,e?.transition)}async loadStageFromId(e){if(!this.wrappedGame){console.error(this.refErrorMessage);return}try{let t=await re.loadStageData(e),n=await Re.createFromBlueprint(t);await this.wrappedGame.loadStage(n),h.current=t}catch(t){console.error(`Failed to load stage ${e}`,t)}}nextStage(e){if(!this.wrappedGame){console.error(this.refErrorMessage);return}if(this.wrappedGame.isLoading())return;if(h.next){console.log("next stage called");let o=h.next.id;if(re.transitionForward(o),h.current){Re.createFromBlueprint(h.current).then(s=>{this.wrappedGame?.loadStage(s,0,e?.transition)});return}}let t=this.wrappedGame.currentStageId,n=this.wrappedGame.stages.findIndex(o=>o.wrappedStage?.uuid===t),i=this.wrappedGame.stages[n+1];if(!i){console.error("next stage called on last stage");return}this.wrappedGame.loadStage(i,n+1,e?.transition)}async goToStage(){}async end(){}dispose(){this.eventDelegate.dispose();for(let e of this.activeGlobalSubscriptions)e();this.activeGlobalSubscriptions=[],this.wrappedGame&&(this.wrappedGame.dispose(),this.wrappedGame=null),Oe(),O(),$e.clearSharedMaterialCache()}dispatch(e,t){this.eventDelegate.dispatch(e,t),G.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 Kt(...a){return new se(a)}function Jt(a,e,t){return ce(e,n=>$t(a,n),t)}async function $t(a,e){let t=K(e.typeId);if(!t)return;let n=e.pose.position??{x:0,y:0,z:0},i=await t.create({position:n,props:{...t.defaultProps??{}}});i&&(await a.spawnEntity(i),Ye(i,e.pose),e.pose.scale&&Xe(i))}import{Euler as Wt,Quaternion as jt,Vector2 as qt}from"three";function Qt(a){return{spawn:async(e,t,n)=>{let i=await Promise.resolve(a(t,n));return e.add(i),i},spawnRelative:async(e,t,n=new qt(0,1))=>{if(!e.body){console.warn("body missing for entity during spawnRelative");return}let{x:i,y:o,z:s}=e.body.translation(),r=e._rotation2DAngle??0;try{let u=e.body.rotation(),d=new jt(u.x,u.y,u.z,u.w);r=new Wt().setFromQuaternion(d,"XYZ").z}catch{}let l=Math.sin(-r)*(n.x??0),p=Math.cos(-r)*(n.y??0),g=await Promise.resolve(a(i+l,o+p));return t.add(g),g}}}import{subscribe as en}from"valtio/vanilla";var Te="STAGE_STATE_CHANGE";function tn(){return en(k,()=>{let a={entities:k.entities,variables:k.variables};window.dispatchEvent(new CustomEvent(Te,{detail:a}))})}function nn(){let a={entities:k.entities,variables:k.variables};window.dispatchEvent(new CustomEvent(Te,{detail:a}))}import{MathUtils as an,Vector3 as on}from"three";var lt={targetKey:"primary",offset:new on(0,0,0),lerpFactor:.1};function rn(a){let e={...lt,...a,offset:fe(a?.offset,lt.offset)},t=null;return{priority:0,enabled:!0,onAttach(){t=null},update(n,i){let o=n.targets[e.targetKey];if(!o)return i;let s=o.position.clone().add(e.offset),r=A(i);if(!t)t=s.clone();else{let l=an.clamp(e.lerpFactor,0,1),p=1-Math.pow(1-l,n.dt*60);t.lerp(s,p)}return r.position.copy(t),r.lookAt=o.position.clone(),r},onDetach(){t=null}}}import{MathUtils as Pe,Vector3 as ut}from"three";var sn={x:"delay",y:"settle",z:"delay"},pt=["x","y","z"];function ln(a){let e={...sn,...a?.axes},t=a?.targetKey??"primary",n=a?.lerpFactor??.1,i=a?.window??0,o=a?.settleSpeed??.75,s=a?.settleTime??.15,r=a?.settleLerp??.08,l=a?.lookahead??0,p=null,g=null,u=null,d={x:0,y:0,z:0},S=new ut,f=new ut,E=()=>{p=null,g=null,u=null,d.x=d.y=d.z=0,S.set(0,0,0)};return{priority:0,enabled:!0,onAttach:E,onDetach:E,update(P,B){let M=P.targets[t];if(!M)return B;let b=M.position,y=p??b.clone(),C=g??b.clone(),I=u??b.clone();p=y,g=C,u=I;let R=P.dt,z=R>1e-8?1/R:0,mt=dt(n,R),ht=dt(r,R);if(l>0){f.set(0,0,0);for(let c of pt)e[c]==="delay"&&(f[c]=(b[c]-I[c])*z);f.lengthSq()>1e-8&&S.copy(f).normalize()}for(let c of pt){let Le=e[c];if(Le==="off"){y[c]=b[c];continue}let gt=Math.abs((b[c]-I[c])*z);if(Le==="settle"){gt<=o?(d[c]+=R,d[c]>=s&&(C[c]=b[c])):d[c]=0,y[c]=Pe.lerp(y[c],C[c],ht);continue}let ue=b[c];l>0&&(ue+=S[c]*l),!(Math.abs(ue-y[c])<=i)&&(y[c]=Pe.lerp(y[c],ue,mt))}I.copy(b);let T=A(B),Be=y.x-b.x,Me=y.y-b.y,Ie=y.z-b.z;return T.position.x+=Be,T.position.y+=Me,T.position.z+=Ie,T.lookAt&&(T.lookAt.x+=Be,T.lookAt.y+=Me,T.lookAt.z+=Ie),T}}}function dt(a,e){let t=Pe.clamp(a,0,1);return 1-Math.pow(1-t,e*60)}import{MathUtils as le}from"three";function un(a){let e=a?.sampleInput??(()=>({})),t=le.clamp(a?.edgeMargin??.08,0,.5),n=a?.edgeSpeed??12,i=a?.panSpeed??16,o=a?.followLerp??.12,s=a?.breakFollowOnPan??!0,r=a?.followKey??null,l=!1,p=null,g=()=>{p=null,l=!1};return{priority:0,enabled:!0,onAttach:g,onDetach:g,setFollowKey(u){r=u,l=!1},update(u,d){let S=d.lookAt??d.position,f=p??S.clone();p=f;let E=e()??{},P=E.pan?.x??0,B=E.pan?.y??0,M=pn(E.pointer,t);(Math.abs(P)>.01||Math.abs(B)>.01||M.x!==0||M.y!==0)&&s&&(l=!0);let y=!l&&r?u.targets[r]:void 0;if(y){let z=dn(o,u.dt);f.x=le.lerp(f.x,y.position.x,z),f.z=le.lerp(f.z,y.position.z,z)}else f.x+=(P*i+M.x*n)*u.dt,f.z+=(-B*i+M.y*n)*u.dt;let C=A(d),I=f.x-S.x,R=f.z-S.z;return C.position.x+=I,C.position.z+=R,C.lookAt&&(C.lookAt.x+=I,C.lookAt.z+=R),C}}}function pn(a,e){if(!a||e<=0)return{x:0,y:0};let t=a.centered?(a.x+1)/2:a.x,n=a.centered?(a.y+1)/2:a.y;return{x:ct(t,e),y:ct(n,e)}}function ct(a,e){return a<e?-((e-a)/e):a>1-e?(a-(1-e))/e:0}function dn(a,e){let t=le.clamp(a,0,1);return 1-Math.pow(1-t,e*60)}import{MeshBasicMaterial as cn}from"three";function mn(a,e,t){let n=e.cameraRef;if(!n.renderTarget){let s=t?.width??512,r=t?.height??512;n.createRenderTarget(s,r)}let i=n.getRenderTexture();if(!i){console.warn("setCameraFeed: Failed to obtain render texture from camera.");return}if(!a.mesh){console.warn("setCameraFeed: Entity has no mesh to apply the camera feed to.");return}let o=new cn({map:i});a.mesh.material=o}export{Y as a,Se as b,we as c,Ce as d,Ot as e,h as f,re as g,se as h,Kt as i,Jt as j,Qt as k,Te as l,tn as m,nn as n,rn as o,ln as p,un as q,mn as r};
|
|
24
|
+
`}function Mt(a){return a.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""").replaceAll("'","'")}function tt(a){return a.pointerType==="touch"}var q=class{inputMap=new Map;currentInputs={};previousInputs={};targetElement;mouseTargetElement;constructor(e,t){this.targetElement=t?.targetElement,this.mouseTargetElement=t?.mouseTargetElement??t?.targetElement;let n=this.buildPlayerEntries(e);for(let{player:i,config:o,gamepadIndex:s,isP1:r}of n)this.addConfigurableProviders(i,o,r),this.addInputProvider(i,new W(s))}configure(e){let t=this.buildPlayerEntries(e);for(let{player:n,config:i,isP1:o}of t){let r=(this.inputMap.get(n)??[]).filter(l=>l instanceof A||l instanceof U||l instanceof X?(l.dispose(),!1):!0);this.inputMap.set(n,[...this.createConfigurableProviders(i,o),...r])}}addInputProvider(e,t){this.inputMap.has(e)||this.inputMap.set(e,[]),this.inputMap.get(e)?.push(t)}dispose(){for(let e of this.inputMap.values())for(let t of e)t.dispose?.();this.inputMap.clear(),this.currentInputs={},this.previousInputs={}}getInputs(e){let t={};return this.inputMap.forEach((n,i)=>{let o=`p${i}`,s=n.reduce((r,l)=>{let p=l.getInput(e);return this.mergeInputs(r,p)},{});t[o]={playerNumber:i,...s}}),t}buildPlayerEntries(e){return[{player:1,config:e?.p1,gamepadIndex:0,isP1:!0},{player:2,config:e?.p2,gamepadIndex:1,isP1:!1},{player:3,config:e?.p3,gamepadIndex:2,isP1:!1},{player:4,config:e?.p4,gamepadIndex:3,isP1:!1},{player:5,config:e?.p5,gamepadIndex:4,isP1:!1},{player:6,config:e?.p6,gamepadIndex:5,isP1:!1},{player:7,config:e?.p7,gamepadIndex:6,isP1:!1},{player:8,config:e?.p8,gamepadIndex:7,isP1:!1}]}addConfigurableProviders(e,t,n){for(let i of this.createConfigurableProviders(t,n))this.addInputProvider(e,i)}createConfigurableProviders(e,t){let n=[];if(e?.key){let i=e.includeDefaults??t;n.push(new A(e.key,{includeDefaultBase:i}))}else t&&n.push(new A);return e?.mouse&&n.push(new U(e.mouse,this.mouseTargetElement)),e?.touch&&n.push(new X(e.touch,this.targetElement)),n}mergeInputs(e,t){return{buttons:{A:m(e.buttons?.A,t.buttons?.A),B:m(e.buttons?.B,t.buttons?.B),X:m(e.buttons?.X,t.buttons?.X),Y:m(e.buttons?.Y,t.buttons?.Y),Start:m(e.buttons?.Start,t.buttons?.Start),Select:m(e.buttons?.Select,t.buttons?.Select),L:m(e.buttons?.L,t.buttons?.L),R:m(e.buttons?.R,t.buttons?.R)},directions:{Up:m(e.directions?.Up,t.directions?.Up),Down:m(e.directions?.Down,t.directions?.Down),Left:m(e.directions?.Left,t.directions?.Left),Right:m(e.directions?.Right,t.directions?.Right)},axes:{Horizontal:w(e.axes?.Horizontal,t.axes?.Horizontal),Vertical:w(e.axes?.Vertical,t.axes?.Vertical),SecondaryHorizontal:w(e.axes?.SecondaryHorizontal,t.axes?.SecondaryHorizontal),SecondaryVertical:w(e.axes?.SecondaryVertical,t.axes?.SecondaryVertical)},shoulders:{LTrigger:m(e.shoulders?.LTrigger,t.shoulders?.LTrigger),RTrigger:m(e.shoulders?.RTrigger,t.shoulders?.RTrigger)},pointer:t.pointer??e.pointer}}};var Q=class{_previousTime;_currentTime;_startTime;_delta;_elapsed;_timescale;_document;_pageVisibilityHandler;constructor(){this._previousTime=0,this._currentTime=0,this._startTime=ve(),this._delta=0,this._elapsed=0,this._timescale=1,this._document=null,this._pageVisibilityHandler=null}connect(e){this._document=e,e.hidden!==void 0&&(this._pageVisibilityHandler=It.bind(this),e.addEventListener("visibilitychange",this._pageVisibilityHandler,!1))}disconnect(){this._pageVisibilityHandler!==null&&(this._document.removeEventListener("visibilitychange",this._pageVisibilityHandler),this._pageVisibilityHandler=null),this._document=null}getDelta(){return this._delta/1e3}getElapsed(){return this._elapsed/1e3}getTimescale(){return this._timescale}setTimescale(e){return this._timescale=e,this}reset(){return this._currentTime=ve()-this._startTime,this}dispose(){this.disconnect()}update(e){return this._pageVisibilityHandler!==null&&this._document.hidden===!0?this._delta=0:(this._previousTime=this._currentTime,this._currentTime=(e!==void 0?e:ve())-this._startTime,this._delta=(this._currentTime-this._previousTime)*this._timescale,this._elapsed+=this._delta),this}};function ve(){return performance.now()}function It(){this._document.hidden===!1&&this.reset()}var Y={FourByThree:1.3333333333333333,SixteenByNine:1.7777777777777777,NineBySixteen:.5625,TwentyOneByNine:2.3333333333333335,OneByOne:1},ee=class{container;canvas;aspectRatio;onResize;handleResizeBound;resizeObserver=null;constructor(e){this.container=e.container,this.canvas=e.canvas,this.aspectRatio=(typeof e.aspectRatio=="number",e.aspectRatio),this.onResize=e.onResize,this.handleResizeBound=this.apply.bind(this)}attach(){window.addEventListener("resize",this.handleResizeBound),typeof ResizeObserver<"u"&&(this.resizeObserver=new ResizeObserver(this.handleResizeBound),this.resizeObserver.observe(this.container)),this.apply()}detach(){window.removeEventListener("resize",this.handleResizeBound),this.resizeObserver?.disconnect(),this.resizeObserver=null}measure(){let e=this.container.getBoundingClientRect(),t=Math.round(e.width||this.container.clientWidth||0),n=Math.round(e.height||this.container.clientHeight||0);if(t>0&&n>0){if(t/n>this.aspectRatio){let p=n;return{width:Math.round(p*this.aspectRatio),height:p}}let r=t,l=Math.round(r/this.aspectRatio);return{width:r,height:l}}if(t>0){let s=t,r=Math.round(s/this.aspectRatio);return{width:s,height:r}}if(n>0){let s=n;return{width:Math.round(s*this.aspectRatio),height:s}}let i=window.innerWidth,o=Math.round(i/this.aspectRatio);return{width:i,height:o}}apply(){let{width:e,height:t}=this.measure();this.canvas.style.width=`${e}px`,this.canvas.style.height=`${t}px`,this.onResize?.(e,t)}};var nt={NES:{displayAspect:1.3333333333333333,resolutions:[{key:"256x240",width:256,height:240,notes:"Standard NTSC; effective 240p."}]},SNES:{displayAspect:1.3333333333333333,resolutions:[{key:"256x224",width:256,height:224,notes:"Common 240p-equivalent mode."},{key:"512x448",width:512,height:448,notes:"Hi-res interlaced (480i)."}]},N64:{displayAspect:1.3333333333333333,resolutions:[{key:"320x240",width:320,height:240,notes:"Common 240p mode."},{key:"640x480",width:640,height:480,notes:"Higher resolution (480i)."}]},PS1:{displayAspect:1.3333333333333333,resolutions:[{key:"320x240",width:320,height:240,notes:"Progressive 240p common."},{key:"640x480",width:640,height:480,notes:"Interlaced 480i for higher detail."}]},PS2:{displayAspect:1.3333333333333333,resolutions:[{key:"640x480",width:640,height:480,notes:"480i/480p baseline."},{key:"720x480",width:720,height:480,notes:"480p (widescreen capable in some titles)."},{key:"1280x720",width:1280,height:720,notes:"720p (select titles)."}]},PS5:{displayAspect:1.7777777777777777,resolutions:[{key:"720x480",width:720,height:480,notes:"Legacy compatibility."},{key:"1280x720",width:1280,height:720,notes:"720p."},{key:"1920x1080",width:1920,height:1080,notes:"1080p."},{key:"2560x1440",width:2560,height:1440,notes:"1440p."},{key:"3840x2160",width:3840,height:2160,notes:"4K (up to 120Hz)."},{key:"7680x4320",width:7680,height:4320,notes:"8K (limited)."}]},XboxOne:{displayAspect:1.7777777777777777,resolutions:[{key:"1280x720",width:1280,height:720,notes:"720p (original)."},{key:"1920x1080",width:1920,height:1080,notes:"1080p (original)."},{key:"3840x2160",width:3840,height:2160,notes:"4K UHD (S/X models)."}]},MobilePortrait:{displayAspect:.5625,resolutions:[{key:"360x640",width:360,height:640,notes:"Low-density phone portrait baseline."},{key:"720x1280",width:720,height:1280,notes:"HD phone portrait."},{key:"1080x1920",width:1080,height:1920,notes:"Full HD phone portrait."}]}};function Se(a){return nt[a].displayAspect}function we(a,e){let t=nt[a]?.resolutions||[];if(!e)return t[0];let n=e.toLowerCase().replace(/\s+/g,"").replace("\xD7","x");return t.find(i=>i.key.toLowerCase()===n)}function Ce(a){if(!a)return null;let t=String(a).toLowerCase().trim().replace(/\s+/g,"").replace("\xD7","x").match(/^(\d+)x(\d+)$/);if(!t)return null;let n=parseInt(t[1],10),i=parseInt(t[2],10);return!Number.isFinite(n)||!Number.isFinite(i)?null:{width:n,height:i}}var xe=null,Ee=class{constructor(e,t,n,i,o,s,r,l,p,g,u,d,S){this.id=e;this.globals=t;this.stages=n;this.debug=i;this.time=o;this.input=s;this.aspectRatio=r;this.internalResolution=l;this.fullscreen=p;this.bodyBackground=g;this.container=u;this.containerId=d;this.canvas=S}};function Lt(a={}){return a.deviceProfile==="mobile"?!0:a.deviceProfile==="desktop"?!1:a.viewportSize?_({viewportSize:a.viewportSize,allowViewportOnly:!0}):_()}function kt(a,e){if(e)return e;if(a){let i=document.getElementById(a);if(i)return i}let t=a||"zylem-root",n=document.createElement("main");return n.setAttribute("id",t),n.style.position="relative",n.style.width="100%",n.style.height="100%",document.body.appendChild(n),n}function Dt(a){let e=a?.id??"zylem";return{id:e,globals:a?.globals??{},stages:a?.stages??[],debug:!!a?.debug,time:a?.time??0,input:a?.input,aspectRatio:Y.SixteenByNine,fullscreen:!0,bodyBackground:"#000000",containerId:e}}var it=360;function at(a,e){if(!a)return;if(typeof a=="string"){if(a==="native")return xe;let i=Ce(a);if(i)return i;if(e){let o=we(e,a);if(o)return{width:o.width,height:o.height}}return}let t=a.width,n=a.height;if(Number.isFinite(t)&&Number.isFinite(n))return{width:t,height:n}}function At(a,e,t,n){if(typeof a=="number")return a;if(typeof a=="string")return Y[a]??t;if(e)try{return Se(e)||t}catch{return t}return n?n.width/n.height:t}function zt(a){let e=Number.isFinite(a)&&a>0?a:Y.SixteenByNine;if(e>=1){let i=it;return{width:Math.round(i*e),height:i}}let t=it,n=Math.round(t/e);return{width:t,height:n}}function Z(a,e={}){let t=Dt({id:a?.id??"zylem",debug:!!a?.debug,time:a?.time??0,input:a?.input,stages:a?.stages??[],globals:a?.globals??{}}),n=a?.containerId??t.containerId,i=kt(n,a?.container??null),o=a?.mobile,s=Lt(e),r=s?o?.preset??a?.preset:a?.preset,l=at(a?.resolution,a?.preset),p=at(o?.resolution,o?.preset??a?.preset),g=(s?ot(p):void 0)??ot(l),u=s?o?.aspectRatio??a?.aspectRatio:a?.aspectRatio,d=At(u,r,t.aspectRatio,g),S=Vt(s,p,l,d),f=a?.fullscreen??t.fullscreen,G=a?.bodyBackground??t.bodyBackground,P=a?.canvas??void 0,B=Ot(a?.input??t.input,o?.controls);return new Ee(a?.id??t.id,a?.globals??t.globals,a?.stages??t.stages,!!(a?.debug??t.debug),a?.time??t.time,B,d,S,f,G,i,n,P)}function ot(a){if(a)return a}function Vt(a,e,t,n){if(a)return e===xe?void 0:e??zt(n);if(t!==xe)return t}function Ot(a,e){if(!e)return a;let n=Ue("p1",{enabled:"auto",...e===!0?{}:e});return L(n,a??{})}function Ht(a){return{...a}}var te=class{id;container;canvas;bodyBackground;fullscreen;aspectRatio;ratioDelegate=null;overlayContainer=null;constructor(e){this.id=e.id,this.container=this.ensureContainer(e.containerId??e.id,e.container),this.canvas=e.canvas??document.createElement("canvas"),this.bodyBackground=e.bodyBackground,this.fullscreen=!!e.fullscreen,this.aspectRatio=(typeof e.aspectRatio=="number",e.aspectRatio)}applyBodyBackground(){this.bodyBackground&&(document.body.style.background=this.bodyBackground)}mountCanvas(){this.mountChildren(this.canvas)}mountRenderer(e,t){this.mountChildren(e),this.canvas=e,this.attachAspectRatio(t)}getOverlayContainer(){return this.ensureOverlayContainer()}centerIfFullscreen(){if(!this.fullscreen)return;let e=this.container.style;e.display="flex",e.alignItems="center",e.justifyContent="center",e.position="relative",e.inset="0"}attachAspectRatio(e){this.ratioDelegate?(this.ratioDelegate.canvas=this.canvas,this.ratioDelegate.onResize=e,this.ratioDelegate.aspectRatio=this.aspectRatio,this.ratioDelegate.apply()):(this.ratioDelegate=new ee({container:this.container,canvas:this.canvas,aspectRatio:this.aspectRatio,onResize:e}),this.ratioDelegate.attach())}setAspectRatio(e){this.aspectRatio=e,this.ratioDelegate&&(this.ratioDelegate.aspectRatio=e,this.ratioDelegate.apply())}reapplyLayout(){this.ratioDelegate?.apply()}destroy(){this.ratioDelegate?.detach(),this.ratioDelegate=null}mountChildren(e){for(;this.container.firstChild;)this.container.removeChild(this.container.firstChild);this.container.appendChild(e),this.container.appendChild(this.ensureOverlayContainer())}ensureOverlayContainer(){if(this.overlayContainer)return this.overlayContainer;let e=document.createElement("div");return e.dataset.zylemOverlayRoot="true",e.style.position="absolute",e.style.inset="0",e.style.pointerEvents="none",e.style.touchAction="none",e.style.zIndex="10",this.overlayContainer=e,e}ensureContainer(e,t){if(t)return t;if(e){let o=document.getElementById(e);if(o)return o}let n=e||this.id||"zylem-root",i=document.createElement("main");return i.setAttribute("id",n),i.style.position="relative",i.style.width="100%",i.style.height="100%",document.body.appendChild(i),i}};import Ft from"stats.js";import{subscribe as Ut}from"valtio/vanilla";var rt="zylem-fps-host",ne=class{statsRef=null;unsubscribe=null;host=null;onFpsHost=e=>{let t=e.detail;this.host=t?.element??null,this.attachStats()};constructor(){typeof window<"u"&&window.addEventListener(rt,this.onFpsHost),this.updateDebugUI(),this.unsubscribe=Ut(v,()=>{this.updateDebugUI()})}begin(){this.statsRef?.begin()}end(){this.statsRef?.end()}styleForPanel(e){e.style.position="relative",e.style.top="auto",e.style.right="auto",e.style.bottom="auto",e.style.left="auto",e.style.zIndex="auto"}detachStats(){let e=this.statsRef?.dom;e?.parentNode&&e.parentNode.removeChild(e)}attachStats(){if(this.statsRef){if(!this.host){this.detachStats();return}this.styleForPanel(this.statsRef.dom),this.statsRef.dom.parentNode!==this.host&&this.host.appendChild(this.statsRef.dom)}}updateDebugUI(){v.enabled&&!this.statsRef?(this.statsRef=new Ft,this.statsRef.showPanel(0),this.attachStats()):!v.enabled&&this.statsRef&&(this.detachStats(),this.statsRef=null)}dispose(){typeof window<"u"&&window.removeEventListener(rt,this.onFpsHost),this.unsubscribe&&(this.unsubscribe(),this.unsubscribe=null),this.detachStats(),this.statsRef=null,this.host=null}};var ie=class{loadingHandlers=[];stageLoadingUnsubscribes=[];onLoading(e){return this.loadingHandlers.push(e),()=>{this.loadingHandlers=this.loadingHandlers.filter(t=>t!==e)}}emit(e){for(let n of this.loadingHandlers)try{n(e)}catch(i){console.error("Game loading handler failed",i)}let t=`loading:${e.type}`;E.emit(t,e)}wireStageLoading(e,t){let n=e.onLoading(i=>{this.emit({type:i.type,message:i.message??"",progress:i.progress??0,current:i.current,total:i.total,stageName:e.uuid??`Stage ${t}`,stageIndex:t})});typeof n=="function"&&this.stageLoadingUnsubscribes.push(n)}unwireAllStages(){for(let e of this.stageLoadingUnsubscribes)try{e()}catch{}this.stageLoadingUnsubscribes=[]}dispose(){this.unwireAllStages(),this.loadingHandlers=[]}};import{getZylemBridge as _t}from"@zylem/bridge";var ae=class{container=null;camera=null;rendererManager=null;gameCanvas=null;config=null;stage=null;mounted=!1;setGameCanvas(e){this.gameCanvas=e,this.tryMount()}setConfig(e){this.config=e,this.tryMount()}setContainer(e){this.container=e,this.tryMount()}setStage(e){this.stage=e,this.mounted&&this.gameCanvas?.reapplyLayout()}setCamera(e){this.camera=e,this.tryMount()}setRendererManager(e){this.rendererManager=e,this.tryMount()}tryMount(){this.mounted||!this.container||!this.gameCanvas||(this.rendererManager?this.mountWithRendererManager():this.camera&&this.mountWithCamera())}mountWithRendererManager(){if(!this.rendererManager||!this.gameCanvas)return;let e=this.rendererManager.getDomElement();this.gameCanvas.mountRenderer(e,(t,n)=>{if(!this.rendererManager)return;let i=this.config?.internalResolution;if(i)this.rendererManager.setPixelRatio(1),this.rendererManager.resize(i.width,i.height),this.stage?.resize(i.width,i.height);else{let o=window.devicePixelRatio||1;this.rendererManager.setPixelRatio(o),this.rendererManager.resize(t,n),this.stage?.resize(t,n)}}),this.mounted=!0}mountWithCamera(){if(!this.camera||!this.gameCanvas)return;let e=this.camera.getDomElement();this.gameCanvas.mountRenderer(e,(t,n)=>{if(!this.camera)return;let i=this.config?.internalResolution;if(i)this.camera.setPixelRatio(1),this.camera.resize(i.width,i.height);else{let o=window.devicePixelRatio||1;this.camera.setPixelRatio(o),this.camera.resize(t,n)}}),this.mounted=!0}reset(){this.camera=null,this.stage=null,this.mounted=!1}dispose(){this.container=null,this.camera=null,this.rendererManager=null,this.gameCanvas=null,this.config=null,this.stage=null,this.mounted=!1}};var oe=class a{id;initialGlobals={};customSetup=null;customUpdate=null;customDestroy=null;stages=[];stageMap=new Map;currentStageId="";previousTimeStamp=0;totalTime=0;timer;inputManager;wrapperRef;globalInputConfig;defaultCamera=null;rendererManager=null;container=null;canvas=null;aspectRatioDelegate=null;resolvedConfig=null;gameCanvas=null;animationFrameId=null;isDisposed=!1;loadInFlight=!1;hasStarted=!1;debugDelegate=null;loadingDelegate=new ie;rendererObserver=new ae;eventBusUnsubscribes=[];thumbnailUnsubscribes=[];lastPublishedGameConfig=null;gameBridge=new Ze;cutscenePreview=new Qe(()=>this.currentStage()?.wrappedStage??null,e=>this.gameBridge.publishCutsceneStatus(e),{},e=>this.gameBridge.publishCutsceneView(e));catalogUnsubscribe=null;gameUpdateParams={};stageSetupParams={};stageUpdateParams={};frameCallback=e=>this.loop(e);sourceOptions;displayRuntime;static FRAME_LIMIT=120;static FRAME_DURATION=1e3/a.FRAME_LIMIT;static MAX_DELTA_SECONDS=1/30;constructor(e,t,n={}){this.wrapperRef=t,this.timer=new Q,this.timer.connect(document),this.sourceOptions={...e},this.displayRuntime={...n};let i=Z(e,this.displayRuntime);this.globalInputConfig=i.input,this.id=i.id,this.stages=i.stages||[],this.container=i.container,this.canvas=i.canvas??null,this.resolvedConfig=i,this.loadGameCanvas(i),this.container=this.gameCanvas?.container??this.container,this.inputManager=new q(i.input,{targetElement:this.gameCanvas?.getOverlayContainer(),mouseTargetElement:this.gameCanvas?.container}),this.loadDebugOptions(e),this.setGlobals(e),We(),je(),this.gameBridge.connect({resolveEntity:o=>this.currentStage()?.wrappedStage?.entityDelegate.childrenMap.get(o)??null,setStageVariable:(o,s)=>{let r=this.currentStage()?.wrappedStage?.state;r&&(r.variables[o]=s)},createEntity:(o,s,r)=>{this.createCatalogEntity(o,s,r)},applySceneOperation:(o,s)=>{this.currentStage()?.wrappedStage?.debugDelegate?.applySceneOperation(o,s)},pickEntity:o=>this.pickEntityAtNdc(o),cutscene:this.cutscenePreview,cameraPose:()=>this.cutscenePreview.cameraPose(),levelSync:o=>{this.currentStage()?.wrappedStage?.debugDelegate?.syncLevel(o)},levelPlay:o=>{this.currentStage()?.wrappedStage?.debugDelegate?.playLevel(o)},levelClose:()=>{this.currentStage()?.wrappedStage?.debugDelegate?.closeLevel()},applySwatches:o=>{let s=this.currentStage()?.wrappedStage?.debugDelegate;return s?s.applySwatches(o):{results:o.uuids.flatMap(r=>o.swatches.map(l=>({uuid:r,kind:l.kind,source:l.source,ok:!1,reason:"entity-not-found"}))),entries:[]}}}),this.publishEntityCatalog(),this.catalogUnsubscribe=Je(()=>this.publishEntityCatalog())}pickEntityAtNdc(e){let t=this.currentStage()?.wrappedStage,n=t?.debugDelegate?.pickAtNdc(e.x,e.y);if(!t||!n)return null;let i=t.entityDelegate.childrenMap.get(n.uuid);return i?this.buildEntitySummary(i)??{uuid:n.uuid,name:n.name||"Unnamed",type:ge(i),position:he(i).position,rotation:he(i).rotation,scale:me(i)}:null}publishEntityCatalog(){this.gameBridge.publishCatalog(Ke())}createCatalogEntity(e,t,n){let i=this.currentStage()?.wrappedStage,o=K(e);if(!i||!o)return;let s=n?.position??{x:0,y:0,z:0},r=o.create({position:s,props:{...o.defaultProps??{},...t??{}}});r&&Promise.resolve(r).then(l=>l&&i.entityDelegate.spawnEntity(l)).catch(l=>{console.error("entity:create failed",l)})}setDisplayRuntime(e){this.displayRuntime={...e};let t=Z(this.sourceOptions,this.displayRuntime);this.resolvedConfig=t,this.rendererObserver.setConfig(t),this.gameCanvas?.setAspectRatio(t.aspectRatio),this.publishGameConfig()}loadGameCanvas(e){this.gameCanvas=new te({id:e.id,container:e.container,containerId:e.containerId,canvas:this.canvas??void 0,bodyBackground:e.bodyBackground,fullscreen:e.fullscreen,aspectRatio:e.aspectRatio}),this.gameCanvas.applyBodyBackground(),this.gameCanvas.mountCanvas(),this.gameCanvas.centerIfFullscreen(),this.rendererObserver.setGameCanvas(this.gameCanvas),this.resolvedConfig&&this.rendererObserver.setConfig(this.resolvedConfig),this.container&&this.rendererObserver.setContainer(this.container),this.subscribeToEventBus()}loadDebugOptions(e){e.debug!==void 0&&(v.enabled=!!e.debug),this.debugDelegate=new ne}isLoading(){return this.loadInFlight}async loadStage(e,t=0,n){if(this.loadInFlight){console.warn("loadStage ignored: a stage load is already in progress");return}this.loadInFlight=!0;try{await this.performLoadStage(e,t,n)}finally{this.loadInFlight=!1}}async performLoadStage(e,t=0,n){let i=n?qe(n):null;this.cutscenePreview.releaseStage();let o=this.currentStage()??null,s=o?.wrappedStage??null,r=s?.scene?.scene??null,l=s?.cameraManagerRef?.primaryCamera?.camera??s?.cameraRef?.camera??null;i&&this.rendererManager?.initialized&&o&&r&&l&&this.rendererManager.beginSnapshotTransition(i,r,l),this.unloadCurrentStage();let g=e.options[0];if(this.loadingDelegate.wireStageLoading(e,t),this.rendererManager||(this.rendererManager=new Fe,await this.rendererManager.initRenderer()),x.setRenderer(this.rendererManager.renderer),await e.load(this.id,g?.camera,this.rendererManager),this.stageMap.set(e.wrappedStage.uuid,e),this.currentStageId=e.wrappedStage.uuid,this.defaultCamera=e.wrappedStage.cameraRef,this.wireEntityThumbnails(e),this.rendererObserver.setStage(e.wrappedStage??null),this.rendererManager&&this.rendererObserver.setRendererManager(this.rendererManager),this.applyInputConfig(e),e.onInputConfigChanged=()=>this.applyInputConfig(e),this.hasStarted&&e.wrappedStage&&!e.wrappedStage.hasSetup){let u=this.params(),d={...this.stageSetupParams};d.inputs=u.inputs,d.globals=u.globals,d.camera=u.camera,d.stage=u.stage,d.game=u.game,d.me=e.wrappedStage,e.start(d)}this.publishGameConfig(),this.publishStageSnapshot(),this.cutscenePreview.stageReady()}applyInputConfig(e){let t=L(this.globalInputConfig??{},e.inputConfig??{});this.inputManager.configure(t)}setGlobalInputConfig(e){this.globalInputConfig=e;let t=this.currentStage();t&&this.applyInputConfig(t)}unloadCurrentStage(){if(!this.currentStageId)return;let e=this.getStage(this.currentStageId);if(e){if(this.clearEntityThumbnailWiring(),x.clear(),e.onInputConfigChanged=null,e?.wrappedStage){try{e.wrappedStage.nodeDestroy({me:e.wrappedStage,globals:V.globals})}catch(t){console.error("Failed to destroy previous stage",t)}e.wrappedStage=null}e.dispose(),this.stageMap.delete(this.currentStageId),this.currentStageId="",this.defaultCamera=null,this.rendererObserver.reset()}}setGlobals(e){this.initialGlobals={...e.globals};for(let t in this.initialGlobals){let n=this.initialGlobals[t];n===void 0&&console.error(`global ${t} is undefined`),De(t,n)}}params(){let e=this.currentStage(),t=this.timer.getDelta(),n=this.inputManager.getInputs(t),i=e?.wrappedStage?.cameraRef||this.defaultCamera,o=this.gameUpdateParams;return o.delta=t,o.inputs=n,o.globals=Ve(),o.me=this,o.camera=i,o.stage=e,o.game=this.wrapperRef,o}start(){let e=this.currentStage(),t=this.params(),n=this.stageSetupParams;n.inputs=t.inputs,n.globals=t.globals,n.camera=t.camera,n.stage=t.stage,n.game=t.game,n.me=e.wrappedStage,e.start(n),this.customSetup&&this.customSetup(t),this.hasStarted=!0,this.loop(0)}step(e){let t=this.currentStage();if(!t||!t.wrappedStage)return;let n=this.params(),i=e!==void 0?e:n.delta,o=Math.min(Math.max(i,0),a.MAX_DELTA_SECONDS);n.delta=o,this.customUpdate&&this.customUpdate(n);let s=this.currentStage();if(s!==t||!s?.wrappedStage){this.totalTime+=o,V.time=this.totalTime;return}let r=this.stageUpdateParams;r.delta=n.delta,r.inputs=n.inputs,r.globals=n.globals,r.camera=n.camera,r.stage=n.stage,r.game=n.game,r.me=t.wrappedStage,t.wrappedStage?.nodeUpdate(r),this.totalTime+=o,V.time=this.totalTime}loop(e){this.debugDelegate?.begin(),He()||(this.timer.update(e),this.step(),this.previousTimeStamp=e),this.debugDelegate?.end(),this.outOfLoop(),this.cutscenePreview.frame(),this.isDisposed||(this.animationFrameId=requestAnimationFrame(this.frameCallback))}dispose(){this.isDisposed=!0,this.cutscenePreview.unload(),this.catalogUnsubscribe?.(),this.catalogUnsubscribe=null,this.gameBridge.disconnect(),this.animationFrameId!==null&&(cancelAnimationFrame(this.animationFrameId),this.animationFrameId=null),this.unloadCurrentStage(),this.debugDelegate&&(this.debugDelegate.dispose(),this.debugDelegate=null),this.eventBusUnsubscribes.forEach(e=>e()),this.eventBusUnsubscribes=[],this.rendererObserver.dispose(),this.inputManager.dispose(),this.rendererManager&&(x.setRenderer(null),this.rendererManager.dispose(),this.rendererManager=null),x.clear(),_t().channel.reset(),this.timer.dispose(),this.customDestroy&&this.customDestroy({me:this,globals:V.globals}),O()}outOfLoop(){let e=this.currentStage();e&&e.wrappedStage.outOfLoop()}getStage(e){return this.stageMap.get(e)}currentStage(){return this.getStage(this.currentStageId)}onLoading(e){return this.loadingDelegate.onLoading(e)}buildStageConfigPayload(){let e=this.currentStage();if(!e?.wrappedStage)return null;let t=e.wrappedStage.state,n=t.backgroundColor,i=typeof n=="string"?n:`#${n.getHexString()}`;return{id:e.wrappedStage.uuid,backgroundColor:i,backgroundImage:t.backgroundImage,gravity:{x:t.gravity.x,y:t.gravity.y,z:t.gravity.z},inputs:t.inputs,variables:t.variables}}buildEntitySummary(e){if(e.options?.editorOwned||H(e.options))return null;let t=e.position??{x:0,y:0,z:0},n=e.rotation??{x:0,y:0,z:0},i=me(e),o=Ne(e),s=x.get(e.uuid);return{uuid:e.uuid,name:e.name||"Unnamed",type:ge(e),position:{x:t.x??0,y:t.y??0,z:t.z??0},rotation:{x:n.x??0,y:n.y??0,z:n.z??0},scale:i,quaternion:o,thumbnail:s?.dataUrl??null,bounds:s?.bounds}}buildEntitiesPayload(){let e=this.currentStage();if(!e?.wrappedStage)return[];let t=[];return e.wrappedStage.entityDelegate.childrenMap.forEach(n=>{let i=this.buildEntitySummary(n);i&&t.push(i)}),t}wireEntityThumbnails(e){if(this.clearEntityThumbnailWiring(),!e.wrappedStage)return;let t=s=>{if(s.options?.editorOwned||!this.gameBridge.wantsThumbnails()||H(s.options))return;let r=s.group??s.mesh??null;r&&x.ensure(s.uuid,r).then(l=>{l&&!this.isDisposed&&this.gameBridge.queueThumbnails([{uuid:s.uuid,url:l.dataUrl,bounds:l.bounds}])})},n=e.wrappedStage.onEntityAdded(s=>{if(this.gameBridge.wantsEntityUpdates()){let r=this.buildEntitySummary(s);r&&this.gameBridge.queueEntityUpsert([r])}t(s)},{replayExisting:!0});this.thumbnailUnsubscribes.push(n);let i=s=>{if(!s.success)return;let r=e.wrappedStage?.entityDelegate.childrenMap.get(s.entityId);r&&(x.invalidate(s.entityId),t(r))};E.on("entity:model:loaded",i),this.thumbnailUnsubscribes.push(()=>{E.off("entity:model:loaded",i)});let o=s=>{x.invalidate(s.entityId),this.gameBridge.wantsEntityUpdates()&&this.gameBridge.queueEntityRemoved([s.entityId])};E.on("entity:destroyed",o),this.thumbnailUnsubscribes.push(()=>{E.off("entity:destroyed",o)}),this.wireEditorBackfill(e)}wireEditorBackfill(e){let t=this.gameBridge.onEditorAttached(()=>{if(!(this.isDisposed||this.currentStage()!==e)){this.lastPublishedGameConfig=null,this.publishGameConfig(),this.publishStageSnapshot();for(let n of e.wrappedStage?.entityDelegate.childrenMap.values()??[]){let i=n;if(i.options?.editorOwned||H(i.options))continue;let o=i.group??i.mesh??null;o&&x.ensure(i.uuid,o).then(s=>{s&&!this.isDisposed&&this.gameBridge.queueThumbnails([{uuid:i.uuid,url:s.dataUrl,bounds:s.bounds}])})}}});this.thumbnailUnsubscribes.push(t)}clearEntityThumbnailWiring(){this.thumbnailUnsubscribes.forEach(e=>{try{e()}catch{}}),this.thumbnailUnsubscribes=[]}buildGameConfigPayload(){return this.resolvedConfig?{id:this.resolvedConfig.id,aspectRatio:this.resolvedConfig.aspectRatio,fullscreen:this.resolvedConfig.fullscreen,bodyBackground:this.resolvedConfig.bodyBackground,internalResolution:this.resolvedConfig.internalResolution,debug:this.resolvedConfig.debug}:null}publishGameConfig(){let e=this.buildGameConfigPayload();if(!e)return;let t=JSON.stringify(e);t!==this.lastPublishedGameConfig&&(this.lastPublishedGameConfig=t,this.gameBridge.publishConfig(e))}publishStageSnapshot(){this.gameBridge.publishStageSnapshot({stage:this.buildStageConfigPayload(),entities:this.buildEntitiesPayload()})}subscribeToEventBus(){this.eventBusUnsubscribes.push(ke.on("game:state:updated",e=>{this.gameBridge.publishVariable({path:e.path,value:e.value,previousValue:e.previousValue})}))}};async function st(a){let{getGameDefaultConfig:e}=await import("./game-default-VUMUMTXA.js"),t={...e()},n=[],i=[],o=[];Object.values(a).forEach(r=>{if(r instanceof J)i.push(r);else if(r instanceof be)o.push(r);else if(r instanceof ye)o.push(r);else if(r?.constructor?.name==="Object"&&typeof r=="object"){let l=Object.assign({...e()},{...r});n.push(l)}}),n.forEach(r=>{t=Object.assign(t,{...r})});let s=t;return s.input=n[0].input,i.forEach(r=>{r.addEntities(o)}),i.length?s.stages=i:s.stages[0].addEntities(o),s}function lt(a){return!!a.find(t=>t instanceof J)}function Ge(a){for(let e of a)if(e&&typeof e=="object"&&!(e instanceof J)&&!(e instanceof ye)&&!(e instanceof be)){let t=e;if(t.globals)return t.globals}}import{proxy as Nt}from"valtio/vanilla";import{get as Xt,set as Yt}from"idb-keyval";import{pack as Zt,unpack as Kt}from"msgpackr";var h=Nt({previous:null,current:null,next:null,isLoading:!1}),re={staticRegistry:new Map,registerStaticStage(a,e){this.staticRegistry.set(a,e)},async loadStageData(a){try{let e=await Xt(a);if(e)return Kt(e)}catch(e){console.warn(`Failed to load stage ${a} from storage`,e)}if(this.staticRegistry.has(a))return this.staticRegistry.get(a);throw new Error(`Stage ${a} not found in storage and static loading not fully implemented.`)},async transitionForward(a,e){if(!h.isLoading){h.isLoading=!0;try{h.current&&await Yt(h.current.id,Zt(h.current)),h.previous=h.current,h.current=h.next,h.current?.id!==a&&(e?h.current=await e(a):h.current=await this.loadStageData(a)),h.next=null}catch(t){console.error("Failed to transition stage:",t)}finally{h.isLoading=!1}}},async preloadNext(a,e){e?h.next=await e(a):h.next=await this.loadStageData(a)}};var Te={async createFromBlueprint(a){let e=F({});if(a.entities)for(let t of a.entities)try{let n=await et.createFromBlueprint(t);e.add(n)}catch(n){console.error(`Failed to create entity ${t.id} for stage ${a.id}`,n)}return e}};var se=class{wrappedGame=null;options;setupCallbacks=[];updateCallbacks=[];destroyCallbacks=[];pendingLoadingCallbacks=[];globalChangeCallbacks=[];globalChangesCallbacks=[];activeGlobalSubscriptions=[];eventDelegate=new _e;pendingInputConfig=null;displayRuntime={};refErrorMessage="lost reference to game";constructor(e){this.options=e,lt(e)||this.options.push(F());let t=Ge(e);t&&pe(t)}onSetup(...e){return this.setupCallbacks.push(...e),this}onUpdate(...e){return this.updateCallbacks.push(...e),this}onDestroy(...e){return this.destroyCallbacks.push(...e),this}setInputConfiguration(...e){let t=L(...e);return this.pendingInputConfig=t,this.wrappedGame&&this.wrappedGame.setGlobalInputConfig(t),this}async start(){O();let e=Ge(this.options);e&&pe(e);let t=await this.load();return this.wrappedGame=t,this.setOverrides(),this.registerGlobalSubscriptions(),t.start(),this}setDisplayRuntime(e){return this.displayRuntime={...this.displayRuntime,...e},this.wrappedGame&&this.wrappedGame.setDisplayRuntime(this.displayRuntime),this}setDeviceProfile(e){return this.setDisplayRuntime({deviceProfile:e})}setViewportSize(e,t){return this.setDisplayRuntime({viewportSize:{width:e,height:t}})}async load(){let e=await st(this.options),t=Z(e,this.displayRuntime);this.pendingInputConfig&&(t.input=L(t.input??{},this.pendingInputConfig));let n=new oe({...e,...t},this,this.displayRuntime);for(let i of this.pendingLoadingCallbacks)n.onLoading(i);return await n.loadStage(e.stages[0]),n}setOverrides(){if(!this.wrappedGame){console.error(this.refErrorMessage);return}this.wrappedGame.customSetup=e=>{this.setupCallbacks.forEach(t=>t(e))},this.wrappedGame.customUpdate=e=>{this.updateCallbacks.forEach(t=>t(e))},this.wrappedGame.customDestroy=e=>{this.destroyCallbacks.forEach(t=>t(e))}}onGlobalChange(e,t){return this.globalChangeCallbacks.push({path:e,callback:t}),this}onGlobalChanges(e,t){return this.globalChangesCallbacks.push({paths:e,callback:t}),this}registerGlobalSubscriptions(){for(let{path:e,callback:t}of this.globalChangeCallbacks){let n=Ae(e,i=>{t(i,this.getCurrentStage())});this.activeGlobalSubscriptions.push(n)}for(let{paths:e,callback:t}of this.globalChangesCallbacks){let n=ze(e,i=>{t(i,this.getCurrentStage())});this.activeGlobalSubscriptions.push(n)}}getCurrentStage(){return this.wrappedGame?.currentStage()??null}experimental={getRuntime:()=>this.getCurrentStage()?.wrappedStage?.world?.simulation??null};async pause(){de(!0)}async resume(){de(!1),this.wrappedGame&&(this.wrappedGame.previousTimeStamp=0,this.wrappedGame.timer.reset())}step(e=1/60){if(!this.wrappedGame){console.error(this.refErrorMessage);return}this.wrappedGame.step(e)}async reset(e){if(!this.wrappedGame){console.error(this.refErrorMessage);return}this.wrappedGame.isLoading()||await this.wrappedGame.loadStage(this.wrappedGame.stages[0],0,e?.transition)}previousStage(e){if(!this.wrappedGame){console.error(this.refErrorMessage);return}if(this.wrappedGame.isLoading())return;let t=this.wrappedGame.currentStageId,n=this.wrappedGame.stages.findIndex(o=>o.wrappedStage?.uuid===t),i=this.wrappedGame.stages[n-1];if(!i){console.error("previous stage called on first stage");return}this.wrappedGame.loadStage(i,n-1,e?.transition)}async loadStageFromId(e){if(!this.wrappedGame){console.error(this.refErrorMessage);return}try{let t=await re.loadStageData(e),n=await Te.createFromBlueprint(t);await this.wrappedGame.loadStage(n),h.current=t}catch(t){console.error(`Failed to load stage ${e}`,t)}}nextStage(e){if(!this.wrappedGame){console.error(this.refErrorMessage);return}if(this.wrappedGame.isLoading())return;if(h.next){console.log("next stage called");let o=h.next.id;if(re.transitionForward(o),h.current){Te.createFromBlueprint(h.current).then(s=>{this.wrappedGame?.loadStage(s,0,e?.transition)});return}}let t=this.wrappedGame.currentStageId,n=this.wrappedGame.stages.findIndex(o=>o.wrappedStage?.uuid===t),i=this.wrappedGame.stages[n+1];if(!i){console.error("next stage called on last stage");return}this.wrappedGame.loadStage(i,n+1,e?.transition)}async goToStage(){}async end(){}dispose(){this.eventDelegate.dispose();for(let e of this.activeGlobalSubscriptions)e();this.activeGlobalSubscriptions=[],this.wrappedGame&&(this.wrappedGame.dispose(),this.wrappedGame=null),Oe(),O(),$e.clearSharedMaterialCache()}dispatch(e,t){this.eventDelegate.dispatch(e,t),E.emit(e,t)}listen(e,t){return this.eventDelegate.listen(e,t)}onLoading(e){return this.wrappedGame?this.wrappedGame.onLoading(e):(this.pendingLoadingCallbacks.push(e),()=>{this.pendingLoadingCallbacks=this.pendingLoadingCallbacks.filter(t=>t!==e),this.wrappedGame})}};function Jt(...a){return new se(a)}function $t(a,e,t){return ce(e,n=>Wt(a,n),t)}async function Wt(a,e){let t=K(e.typeId);if(!t)return;let n=e.pose.position??{x:0,y:0,z:0},i=await t.create({position:n,props:{...t.defaultProps??{}}});i&&(await a.spawnEntity(i),Ye(i,e.pose),e.pose.scale&&Xe(i))}import{Euler as jt,Quaternion as qt,Vector2 as Qt}from"three";function en(a){return{spawn:async(e,t,n)=>{let i=await Promise.resolve(a(t,n));return e.add(i),i},spawnRelative:async(e,t,n=new Qt(0,1))=>{if(!e.body){console.warn("body missing for entity during spawnRelative");return}let{x:i,y:o,z:s}=e.body.translation(),r=e._rotation2DAngle??0;try{let u=e.body.rotation(),d=new qt(u.x,u.y,u.z,u.w);r=new jt().setFromQuaternion(d,"XYZ").z}catch{}let l=Math.sin(-r)*(n.x??0),p=Math.cos(-r)*(n.y??0),g=await Promise.resolve(a(i+l,o+p));return t.add(g),g}}}import{subscribe as tn}from"valtio/vanilla";var Re="STAGE_STATE_CHANGE";function nn(){return tn(k,()=>{let a={entities:k.entities,variables:k.variables};window.dispatchEvent(new CustomEvent(Re,{detail:a}))})}function an(){let a={entities:k.entities,variables:k.variables};window.dispatchEvent(new CustomEvent(Re,{detail:a}))}import{MathUtils as on,Vector3 as rn}from"three";var ut={targetKey:"primary",offset:new rn(0,0,0),lerpFactor:.1};function sn(a){let e={...ut,...a,offset:fe(a?.offset,ut.offset)},t=null;return{priority:0,enabled:!0,onAttach(){t=null},update(n,i){let o=n.targets[e.targetKey];if(!o)return i;let s=o.position.clone().add(e.offset),r=D(i);if(!t)t=s.clone();else{let l=on.clamp(e.lerpFactor,0,1),p=1-Math.pow(1-l,n.dt*60);t.lerp(s,p)}return r.position.copy(t),r.lookAt=o.position.clone(),r},onDetach(){t=null}}}import{MathUtils as Pe,Vector3 as pt}from"three";var ln={x:"delay",y:"settle",z:"delay"},dt=["x","y","z"];function un(a){let e={...ln,...a?.axes},t=a?.targetKey??"primary",n=a?.lerpFactor??.1,i=a?.window??0,o=a?.settleSpeed??.75,s=a?.settleTime??.15,r=a?.settleLerp??.08,l=a?.lookahead??0,p=null,g=null,u=null,d={x:0,y:0,z:0},S=new pt,f=new pt,G=()=>{p=null,g=null,u=null,d.x=d.y=d.z=0,S.set(0,0,0)};return{priority:0,enabled:!0,onAttach:G,onDetach:G,update(P,B){let M=P.targets[t];if(!M)return B;let b=M.position,y=p??b.clone(),C=g??b.clone(),I=u??b.clone();p=y,g=C,u=I;let T=P.dt,z=T>1e-8?1/T:0,ht=ct(n,T),gt=ct(r,T);if(l>0){f.set(0,0,0);for(let c of dt)e[c]==="delay"&&(f[c]=(b[c]-I[c])*z);f.lengthSq()>1e-8&&S.copy(f).normalize()}for(let c of dt){let Le=e[c];if(Le==="off"){y[c]=b[c];continue}let ft=Math.abs((b[c]-I[c])*z);if(Le==="settle"){ft<=o?(d[c]+=T,d[c]>=s&&(C[c]=b[c])):d[c]=0,y[c]=Pe.lerp(y[c],C[c],gt);continue}let ue=b[c];l>0&&(ue+=S[c]*l),!(Math.abs(ue-y[c])<=i)&&(y[c]=Pe.lerp(y[c],ue,ht))}I.copy(b);let R=D(B),Be=y.x-b.x,Me=y.y-b.y,Ie=y.z-b.z;return R.position.x+=Be,R.position.y+=Me,R.position.z+=Ie,R.lookAt&&(R.lookAt.x+=Be,R.lookAt.y+=Me,R.lookAt.z+=Ie),R}}}function ct(a,e){let t=Pe.clamp(a,0,1);return 1-Math.pow(1-t,e*60)}import{MathUtils as le}from"three";function pn(a){let e=a?.sampleInput??(()=>({})),t=le.clamp(a?.edgeMargin??.08,0,.5),n=a?.edgeSpeed??12,i=a?.panSpeed??16,o=a?.followLerp??.12,s=a?.breakFollowOnPan??!0,r=a?.followKey??null,l=!1,p=null,g=()=>{p=null,l=!1};return{priority:0,enabled:!0,onAttach:g,onDetach:g,setFollowKey(u){r=u,l=!1},update(u,d){let S=d.lookAt??d.position,f=p??S.clone();p=f;let G=e()??{},P=G.pan?.x??0,B=G.pan?.y??0,M=dn(G.pointer,t);(Math.abs(P)>.01||Math.abs(B)>.01||M.x!==0||M.y!==0)&&s&&(l=!0);let y=!l&&r?u.targets[r]:void 0;if(y){let z=cn(o,u.dt);f.x=le.lerp(f.x,y.position.x,z),f.z=le.lerp(f.z,y.position.z,z)}else f.x+=(P*i+M.x*n)*u.dt,f.z+=(-B*i+M.y*n)*u.dt;let C=D(d),I=f.x-S.x,T=f.z-S.z;return C.position.x+=I,C.position.z+=T,C.lookAt&&(C.lookAt.x+=I,C.lookAt.z+=T),C}}}function dn(a,e){if(!a||e<=0)return{x:0,y:0};let t=a.centered?(a.x+1)/2:a.x,n=a.centered?(a.y+1)/2:a.y;return{x:mt(t,e),y:mt(n,e)}}function mt(a,e){return a<e?-((e-a)/e):a>1-e?(a-(1-e))/e:0}function cn(a,e){let t=le.clamp(a,0,1);return 1-Math.pow(1-t,e*60)}import{MeshBasicMaterial as mn}from"three";function hn(a,e,t){let n=e.cameraRef;if(!n.renderTarget){let s=t?.width??512,r=t?.height??512;n.createRenderTarget(s,r)}let i=n.getRenderTexture();if(!i){console.warn("setCameraFeed: Failed to obtain render texture from camera.");return}if(!a.mesh){console.warn("setCameraFeed: Entity has no mesh to apply the camera feed to.");return}let o=new mn({map:i});a.mesh.material=o}export{Y as a,Se as b,we as c,Ce as d,Ht as e,h as f,re as g,se as h,Jt as i,$t as j,en as k,Re as l,nn as m,an as n,sn as o,un as p,pn as q,hn as r};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{proxy as c}from"valtio/vanilla";var a=["translate","rotate","scale"];function b(e){return a.includes(e)}var y={enabled:!0,translate:.25,rotate:Math.PI/12,scale:.1},t=c({enabled:!1,paused:!1,tool:"none",selectedEntityId:null,selectedEntityIds:[],hoveredEntityId:null,snap:{...y},gridVisible:!1,addTypeId:null,addTypeProps:null,pickMode:!1,flags:new Set}),l=null;function S(e){return l=e,()=>{l===e&&(l=null)}}function d(e){return!e||!l?null:l(e)}function s(e,n){if(e==null)return null;if(typeof e=="string")return e;let o=e.uuid;if(typeof o=="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.`),o;throw new TypeError(`${n} expects an entity UUID string or null, received ${typeof e}.`)}function v(){return t.paused}function T(e){t.paused=e}function m(){return t.tool}function h(e){t.tool=e}function D(){return t.enabled||t.tool!=="none"||t.pickMode}function k(e){t.pickMode=e,!e&&t.tool!=="select"&&t.tool!=="delete"&&x()}function P(){return t.pickMode}function R(){return t.selectedEntityId}function p(e){let n=s(e,"setSelectedEntityId");t.selectedEntityId!==n&&(t.selectedEntityId=n,t.selectedEntityIds=n?[n]:[])}function M(){return[...t.selectedEntityIds]}function u(e){let n=e.map((i,r)=>s(i,`setSelectedEntityIds[${r}]`)).filter(i=>i!==null);n.length===t.selectedEntityIds.length&&n.every((i,r)=>t.selectedEntityIds[r]===i)||(t.selectedEntityIds=n,t.selectedEntityId=n[0]??null)}function g(e){let n=t.selectedEntityIds,o=e.filter((i,r)=>!n.includes(i)&&e.indexOf(i)===r);o.length!==0&&u([...n,...o])}function f(e){let n=new Set(e);u(t.selectedEntityIds.filter(o=>!n.has(o)))}function w(e){let n=s(e,"toggleSelectedEntityId");n&&(t.selectedEntityIds.includes(n)?f([n]):g([n]))}function G(){return{...t.snap}}function O(e){Object.assign(t.snap,e)}function H(e){t.gridVisible=e}function A(e,n){t.addTypeId=e,t.addTypeProps=e?n??null:null}function U(){return t.hoveredEntityId}function E(e){let n=s(e,"setHoveredEntityId");t.hoveredEntityId!==n&&(t.hoveredEntityId=n)}function x(){E(null)}function F(){return d(t.selectedEntityId)}function N(){return d(t.hoveredEntityId)}function V(e){p(s(e,"setSelectedEntity"))}export{a,b,y as c,t as d,S as e,d as f,v as g,T as h,m as i,h as j,D as k,k as l,P as m,R as n,p as o,M as p,u as q,g as r,f as s,w as t,G as u,O as v,H as w,A as x,U as y,E as z,x as A,F as B,N as C,V as D};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{b as k,c as B,d as I}from"./chunk-273CUPEO.js";import{d as s,h as v,j as g,l as S,o as E,q as p,r as C,s as w,t as P,v as x,w as D,x as A}from"./chunk-UM5VNQPY.js";function L(){return new Promise(t=>{let e=new MessageChannel;e.port1.onmessage=()=>t(),e.port2.postMessage(void 0)})}async function O(t,e,i={}){let n=Math.max(1,i.batchSize??5),o=0;for(let a of t.entries)await e(a),o+=1,o%n===0&&await L();return o%n!==0&&await L(),{spawned:o}}import{subscribe as H}from"valtio/vanilla";import{announceBridgeReady as M,getZylemBridge as h}from"@zylem/bridge";var te="game",ne={side:"editor:side",top:"editor:top",isometric:"editor:isometric",free:"editor:free"},d=!1,c=new Set;function ie(){return d}function oe(t){return c.add(t),d&&t.ensureEditorCameras(),()=>{c.delete(t)}}function u(t){if(!t&&!d)return Promise.resolve();if(d=t,!t){for(let e of c)e.destroyEditorCameras();return Promise.resolve()}return Promise.all([...c].map(e=>e.ensureEditorCameras())).then(()=>{})}function z(t){let e=!1;for(let i of c)i.activateCameraById(t)&&(e=!0);return e}function y(t,e){return[t[0]*e.x,t[1]*e.y,t[2]*e.z]}function V(t,e){let i=new Float32Array(t.length);for(let n=0;n<t.length;n+=3)i[n]=t[n]*e.x,i[n+1]=t[n+1]*e.y,i[n+2]=t[n+2]*e.z;return i}function K(t,e){let{shape:i}=t,n=t.offset?y(t.offset,e):t.offset,o;switch(i.type){case"box":o={type:"box",halfExtents:y(i.halfExtents,e)};break;case"sphere":o={type:"sphere",radius:i.radius*Math.max(e.x,e.y,e.z)};break;case"capsule":case"cylinder":case"cone":o={type:i.type,halfHeight:i.halfHeight*e.y,radius:i.radius*Math.max(e.x,e.z)};break;case"convexHull":o={type:"convexHull",vertices:V(i.vertices,e)};break;case"trimesh":o={type:"trimesh",vertices:V(i.vertices,e),indices:i.indices};break;case"heightfield":o={...i,scale:y(i.scale,e)};break;default:o=i;break}return{...t,shape:o,offset:n}}function F(t){if(!t.colliderBaseline){let e=t.colliderDescs.length?t.colliderDescs:t.colliderDesc?[t.colliderDesc]:[];t.colliderBaseline=e.map(i=>({...i}))}return t.colliderBaseline}function T(t){if(!t.colliderScaleDirty)return!1;t.colliderScaleDirty=!1;let e=F(t);if(!e.length)return!1;let i=t.getScale(),n=e.map(r=>K(r,i));t.colliderDescs=n,t.colliderDesc=n[0];let o=t.physicsWorldRef;if(!o)return!0;let a=t.getPose();return o.destroyEntity(t),a&&t.bodyDesc&&(t.bodyDesc.position=[a.position.x,a.position.y,a.position.z],t.bodyDesc.rotation=[a.rotation.x,a.rotation.y,a.rotation.z,a.rotation.w]),o.addEntity(t),!0}function R(t){return(t?.group??t?.mesh)?.scale}function N(t){let i=(typeof t?.getScale=="function"?t.getScale():void 0)??t?.scale??R(t)??{};return{x:i.x??1,y:i.y??1,z:i.z??1}}function me(t){let e=typeof t?.getPose=="function"?t.getPose():null;if(!e?.rotation)return;let{x:i,y:n,z:o,w:a}=e.rotation;return{x:i,y:n,z:o,w:a}}function f(t){let e=typeof t?.getPose=="function"?t.getPose():null,i=e?.position??{x:0,y:0,z:0},n=e?.rotation??{x:0,y:0,z:0,w:1};return{position:{x:i.x,y:i.y,z:i.z},rotation:I(n),quaternion:{x:n.x,y:n.y,z:n.z,w:n.w},scale:N(t)}}function $(t,e){if(typeof t?.setScale=="function"){t.setScale(e.x,e.y,e.z);return}R(t)?.set?.(e.x,e.y,e.z)}function W(t){!t||typeof t.getScale!="function"||T(t)}function _(t,e){if(!t)return!1;let i=e.quaternion??(e.rotation?B(e.rotation):void 0),n=!1;return(e.position||i)&&typeof t.setPose=="function"&&(n=t.setPose({position:e.position,rotation:i})),e.scale&&($(t,e.scale),n=!0),n}function Q(t){let e=t?.constructor?.type;return e?String(e).replace("Symbol(","").replace(")",""):"Unknown"}function j(t){let e=t;if(!e?.uuid)return;let i=h().channel;if(!i.hasSubscribers("entity:upsert"))return;let n=f(t);i.queue("entity:upsert",[{uuid:e.uuid,name:e.name||"Unnamed",type:Q(t),position:n.position,rotation:n.rotation,scale:n.scale,quaternion:n.quaternion}])}function fe(t,e){h().channel.send("game:notice",{level:t,message:e})}function Z(t,e,i){let n=[...new Set(t.swatches.map(r=>r.source))],o=[...new Set(e.map(r=>r.uuid))],a=o.length===1?i(o[0])||"entity":`${o.length} entities`;return`Apply ${n.join(", ")} to ${a}`}function J(t,e){return!e||t.length!==e.length?!1:t.every((i,n)=>i===e[n])}function X(t,e){switch(e){case"add":C(t);break;case"subtract":w(t);break;case"toggle":for(let i of t)P(i);break;default:p(t);break}}function m(t,e,i){return t.on.bind(t)(e,i)}function Y(t,e){return t.on.bind(t)("camera:activate",({id:n})=>e(n))}var q=class{channel;unsubscribes=[];host=null;editorKnown={};applyingSceneOperation=!1;editorCameraFrame=0;constructor(){this.channel=h().channel}connect(e,i){this.disconnect(),this.host=e,this.unsubscribes.push(this.channel.on("debug:set",({enabled:n})=>{this.editorKnown.debug=n,s.enabled=n}),this.channel.on("tool:set",({tool:n})=>{g(n)}),this.channel.on("playback:set",({paused:n})=>{this.editorKnown.paused=n,v(n)}),this.channel.on("entity:select",({uuid:n,uuids:o,mode:a})=>{o?X(o,a??"replace"):E(n),this.editorKnown.selectedUuid=s.selectedEntityId,this.editorKnown.selectedUuids=[...s.selectedEntityIds]}),this.channel.on("entity:focus",({uuid:n})=>{k(n)}),this.channel.on("entity:transform",({uuid:n,position:o,rotation:a,quaternion:r,scale:b})=>{let l=this.host?.resolveEntity(n);if(!l)return;let U=f(l);if(_(l,{position:o,rotation:a,quaternion:r,scale:b}),b&&W(l),j(l),this.applyingSceneOperation)return;let G=f(l);this.channel.send("scene:operation",{opId:`tx-${n}-${Date.now().toString(36)}`,kind:"transform",label:`Set ${l.name||"entity"} transform`,entries:[{uuid:n,before:U,after:G}]})}),this.channel.on("entity:create",({typeId:n,props:o,pose:a})=>{this.host?.createEntity?.(n,o,a)}),this.channel.on("level:load",({buffer:n})=>{this.loadLevel(n)}),m(this.channel,"level:sync",n=>{this.host?.levelSync?.(n)}),m(this.channel,"level:play",({document:n})=>{this.host?.levelPlay?.(n)}),m(this.channel,"level:close",()=>{this.host?.levelClose?.()}),this.channel.on("scene:operation:apply",({op:n,direction:o})=>{this.applyingSceneOperation=!0;try{this.host?.applySceneOperation?.(n,o)}finally{this.applyingSceneOperation=!1}}),this.channel.on("add:type:set",({typeId:n,props:o})=>{A(n,o??null)}),this.channel.on("snap:set",n=>{x(n)}),this.channel.on("grid:set",({visible:n})=>{D(n)}),this.channel.on("stage:variable:set",({key:n,value:o})=>{this.host?.setStageVariable?.(n,o)}),this.channel.on("pick:mode:set",({enabled:n})=>{S(n)}),this.channel.on("entity:pick",({requestId:n,ndc:o})=>{let a=this.host?.pickEntity?.(o)??null;this.channel.send("entity:pick:result",{requestId:n,hit:a})}),this.channel.on("entity:apply-swatch",n=>{this.handleApplySwatch(n)}),this.channel.on("cutscene:load",n=>this.host?.cutscene?.load(n)),this.channel.on("cutscene:play",({from:n})=>this.host?.cutscene?.play(n)),this.channel.on("cutscene:pause",()=>this.host?.cutscene?.pause()),this.channel.on("cutscene:stop",()=>this.host?.cutscene?.stop()),this.channel.on("cutscene:seek",({time:n})=>this.host?.cutscene?.seek(n)),this.channel.on("cutscene:unload",()=>this.host?.cutscene?.unload()),this.channel.on("camera:pose:get",({requestId:n})=>{let o=this.host?.cameraPose?.();o&&this.channel.send("camera:pose",{requestId:n,...o})}),Y(this.channel,z),this.onEditorAttached(()=>{this.attachEditorCameras()}),this.onEditorDetached(()=>{this.detachEditorCameras()}),H(s,()=>this.publishDebugStateChanges())),this.publishDebugStateChanges(),this.editorIsAttached()&&this.attachEditorCameras(),M(i)}publishCutsceneStatus(e){this.channel.queue("cutscene:status",e)}publishCutsceneView(e){this.channel.queue("cutscene:view",e)}disconnect(){for(let e of this.unsubscribes)e();this.unsubscribes=[],this.host=null,this.editorKnown={},this.detachEditorCameras()}handleApplySwatch(e){let i=e.opId??`swatch-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`,n=this.host?.applySwatches?this.host.applySwatches({...e,opId:i}):{results:e.uuids.flatMap(a=>e.swatches.map(r=>({uuid:a,kind:r.kind,source:r.source,ok:!1,reason:"entity-not-found"}))),entries:[]},o=[...new Set(n.entries.map(a=>a.uuid))];e.select&&o.length>0&&p(o),n.entries.length>0&&!this.applyingSceneOperation&&this.channel.send("scene:operation",{opId:i,kind:"swatch",label:Z(e,n.entries,a=>this.host?.resolveEntity(a)?.name),entries:n.entries}),this.channel.send("entity:swatch-applied",{opId:i,results:n.results})}publishDebugStateChanges(){let e={};s.paused!==this.editorKnown.paused&&(this.editorKnown.paused=s.paused,e.paused=s.paused),s.enabled!==this.editorKnown.debug&&(this.editorKnown.debug=s.enabled,e.debug=s.enabled),(e.paused!==void 0||e.debug!==void 0)&&this.publishStatus(e),(s.selectedEntityId!==this.editorKnown.selectedUuid||s.hoveredEntityId!==this.editorKnown.hoveredUuid||!J(s.selectedEntityIds,this.editorKnown.selectedUuids))&&(this.editorKnown.selectedUuid=s.selectedEntityId,this.editorKnown.selectedUuids=[...s.selectedEntityIds],this.editorKnown.hoveredUuid=s.hoveredEntityId,this.channel.queue("entity:selection",{selectedUuid:s.selectedEntityId,hoveredUuid:s.hoveredEntityId,selectedUuids:[...s.selectedEntityIds]}))}wantsEntityUpdates(){return this.channel.hasSubscribers("entity:upsert")||this.channel.hasSubscribers("stage:snapshot")}wantsThumbnails(){return this.channel.hasSubscribers("entity:thumbnail")}onEditorAttached(e){return this.channel.onSubscriberAdded(i=>{if(i!=="entity:upsert"&&i!=="entity:thumbnail")return;let n=i==="entity:upsert"?"entity:thumbnail":"entity:upsert";this.channel.subscriberCount(n)>0||e()})}onEditorDetached(e){let i=this.channel;return typeof i.onSubscriberRemoved!="function"?()=>{}:i.onSubscriberRemoved(n=>{if(n!=="entity:upsert"&&n!=="entity:thumbnail")return;let o=n==="entity:upsert"?"entity:thumbnail":"entity:upsert";this.channel.subscriberCount(o)>0||e()})}editorIsAttached(){return this.channel.hasSubscribers("entity:upsert")||this.channel.hasSubscribers("entity:thumbnail")}attachEditorCameras(){u(!0),this.watchEditorDetached()}detachEditorCameras(){this.stopWatchingEditorDetached(),u(!1)}watchEditorDetached(){if(typeof this.channel.onSubscriberRemoved=="function"||this.editorCameraFrame)return;let i=()=>{if(!this.editorIsAttached()){this.editorCameraFrame=0,u(!1);return}this.editorCameraFrame=requestAnimationFrame(i)};this.editorCameraFrame=requestAnimationFrame(i)}stopWatchingEditorDetached(){this.editorCameraFrame&&(cancelAnimationFrame(this.editorCameraFrame),this.editorCameraFrame=0)}publishConfig(e){this.channel.send("game:config",e)}publishLoading(e){this.channel.send("game:loading",e)}publishStatus(e){this.channel.queue("game:status",e)}publishVariable(e){this.channel.send("game:variable",e)}async loadLevel(e){let{spawned:i}=await O(e,n=>{this.host?.createEntity?.(n.typeId,void 0,n.pose)});this.publishNotice("info",`Streamed ${i} level entries`)}publishNotice(e,i){this.channel.send("game:notice",{level:e,message:i})}publishStageSnapshot(e){this.channel.send("stage:snapshot",e)}queueEntityUpsert(e){e.length&&this.channel.queue("entity:upsert",e)}queueEntityRemoved(e){e.length&&this.channel.queue("entity:removed",{uuids:e})}queueThumbnails(e){e.length&&this.channel.queue("entity:thumbnail",e)}publishCatalog(e){this.channel.send("catalog:snapshot",{entities:e})}publishSceneOperation(e){this.channel.send("scene:operation",e)}wantsSceneOperations(){return this.channel.hasSubscribers("scene:operation")}};function be(t){h().channel.send("scene:operation",t)}export{te as a,ne as b,ie as c,oe as d,O as e,T as f,N as g,me as h,f as i,W as j,_ as k,Q as l,fe as m,q as n,be as o};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{d as K,j as B}from"./chunk-6FGXC4T6.js";import{a as N,b as U}from"./chunk-AIQ6IVT5.js";import{e as q}from"./chunk-UUOPT2N4.js";import{a as A,b as $,c as Q}from"./chunk-EVYHPR3J.js";import{d as P}from"./chunk-4QLJUQSJ.js";import{c as m,d as T,e as H,f as X,g as j,h as c,i as Y,j as R}from"./chunk-7WRQ2UAN.js";import{p as W}from"./chunk-XRP4JJXL.js";import{StageBodyKind as te}from"@zylem/behaviors/core";import{Color as Pe,Vector2 as J,Vector3 as ee}from"three";function g(i){if(!i||typeof i!="object")return!1;let e=Object.getPrototypeOf(i);return e===Object.prototype||e===null}function l(i){if(i==null||typeof i=="function"||typeof i!="object")return i;if(i instanceof Pe||i instanceof J||i instanceof ee)return i.clone();if(i instanceof Float32Array)return new Float32Array(i);if(Array.isArray(i))return i.map(e=>l(e));if(g(i)){let e={};for(let[t,o]of Object.entries(i))t!=="_builders"&&(e[t]=l(o));return e}return i}function u(i,e){let t=l(i);if(!e)return t;if(!g(t)||!g(e))return l(e);let o=t;for(let[n,s]of Object.entries(e)){if(n==="_builders"||s===void 0)continue;let r=o[n];if(n==="shader"){o[n]=l(s);continue}if(r instanceof J&&H(s)){o[n]=Y(s,r);continue}if(r instanceof ee&&X(s)){o[n]=R(s,r);continue}if(g(r)&&g(s)){o[n]=u(r,s);continue}o[n]=l(s)}return o}function ie(i){return i&&i.__kind==="collision"}function z(i){return i.cloneComponent()}function Re(i,e){let t={kind:i?te.Static:te.Dynamic,position:[0,0,0],gravityScale:e.gravityScale??1,canSleep:e.canSleep??!1,ccdEnabled:e.ccdEnabled??!0},o=A(e.lockRotations);o&&(t.lockRotation=o);let n=A(e.lockTranslations);return n&&(t.lockTranslation=n),t}function Be(i,e){if(e.offset){let t=c(e.offset,m);i.offset=[t.x,t.y,t.z]}e.sensor&&(i.sensor=!0),e.collisionType&&(i.collisionGroups=$(e.collisionType,e.collisionFilter))}function h(i,e,t){return Be(i,e),{__kind:"collision",bodyDesc:Re(e.static??!1,e),colliderDesc:i,cloneComponent:t}}function we(i={}){let e=c(i.size,T),t={shape:{type:"box",halfExtents:[e.x/2,e.y/2,e.z/2]}},o=l(i);return h(t,i,()=>we(o))}function Se(i={}){let e={shape:{type:"sphere",radius:i.radius??1}},t=l(i);return h(e,i,()=>Se(t))}function Me(i={}){let e=i.radius??1,o={shape:{type:"cone",halfHeight:(i.height??2)/2,radius:e}},n=l(i);return h(o,i,()=>Me(n))}function De(i={}){let e=i.radius??1,o={shape:{type:"cone",halfHeight:(i.height??2)/2,radius:e}},n=l(i);return h(o,i,()=>De(n))}function _e(i={}){let e=Math.max(i.radiusTop??1,i.radiusBottom??1),o={shape:{type:"cylinder",halfHeight:(i.height??2)/2,radius:e}},n=l(i);return h(o,i,()=>_e(n))}function ke(i={}){let e=i.radius??.5,o={shape:{type:"capsule",halfHeight:(i.length??1)/2,radius:e}},n=l(i);return h(o,i,()=>ke(n))}function Te(i={}){let e=j(i.tile,{x:10,y:10}),t=i.subdivisions??10,o=(t+1)*(t+1),n=i.heightData??new Float32Array(o),s={shape:{type:"heightfield",rows:t,cols:t,heights:n,scale:[e.x,1,e.y]}},r={...i,static:i.static??!0},a=l(r);return h(s,r,()=>Te(a))}function I(i={}){let e=c(i.size,T),t={shape:{type:"box",halfExtents:[e.x/2,e.y/2,e.z/2]},sensor:!0},o={...i,static:i.static??!0,sensor:!0},n=l(o);return h(t,o,()=>I(n))}import{Mesh as me,ShaderMaterial as Ue,Group as He}from"three";var oe=import.meta.env.VITE_DEBUG_FLAG==="true";import{nanoid as Ae}from"nanoid";var p=class i{parent=null;children=[];options;uuid="";name="";markedForRemoval=!1;lifecycleCallbacks={setup:[],loaded:[],update:[],destroy:[],cleanup:[]};trackLifecycleRegistrations=!1;userLifecycleRegistrations=[];constructor(e=[]){let t=e.filter(o=>!(o instanceof i)).reduce((o,n)=>({...o,...n}),{});this.options=t,this.uuid=Ae()}onSetup(...e){return this.lifecycleCallbacks.setup.push(...e),this.recordLifecycleRegistration("onSetup",e),this}onLoaded(...e){return this.lifecycleCallbacks.loaded.push(...e),this.recordLifecycleRegistration("onLoaded",e),this}onUpdate(...e){return this.lifecycleCallbacks.update.push(...e),this.recordLifecycleRegistration("onUpdate",e),this}onDestroy(...e){return this.lifecycleCallbacks.destroy.push(...e),this.recordLifecycleRegistration("onDestroy",e),this}onCleanup(...e){return this.lifecycleCallbacks.cleanup.push(...e),this.recordLifecycleRegistration("onCleanup",e),this}prependSetup(...e){return this.lifecycleCallbacks.setup.unshift(...e),this.recordLifecycleRegistration("prependSetup",e),this}prependUpdate(...e){return this.lifecycleCallbacks.update.unshift(...e),this.recordLifecycleRegistration("prependUpdate",e),this}setParent(e){this.parent=e}getParent(){return this.parent}add(e){this.children.push(e),e.setParent(this)}remove(e){let t=this.children.indexOf(e);t!==-1&&(this.children.splice(t,1),e.setParent(null))}getChildren(){return this.children}isComposite(){return this.children.length>0}enableUserLifecycleTracking(){this.trackLifecycleRegistrations=!0}replayUserLifecycleRegistrationsTo(e,t){for(let o of this.userLifecycleRegistrations){let n=t?o.callbacks.map(s=>t(s)):[...o.callbacks];switch(o.method){case"onSetup":e.onSetup(...n);break;case"onLoaded":e.onLoaded(...n);break;case"onUpdate":e.onUpdate(...n);break;case"onDestroy":e.onDestroy(...n);break;case"onCleanup":e.onCleanup(...n);break;case"prependSetup":e.prependSetup(...n);break;case"prependUpdate":e.prependUpdate(...n);break}}}cloneChildrenInto(e){for(let t of this.children)e.add(ze(t))}nodeSetup(e){this.markedForRemoval=!1,typeof this._setup=="function"&&this._setup(e);for(let t of this.lifecycleCallbacks.setup)t(e);this.children.forEach(t=>t.nodeSetup(e))}nodeUpdate(e){if(!this.markedForRemoval){typeof this._update=="function"&&this._update(e),typeof this._tickActions=="function"&&this._tickActions(e.delta);for(let t of this.lifecycleCallbacks.update)t(e);this.children.forEach(t=>t.nodeUpdate(e))}}nodeDestroy(e){if(!this.markedForRemoval){this.children.forEach(t=>t.nodeDestroy(e));for(let t of this.lifecycleCallbacks.destroy)t(e);typeof this._destroy=="function"&&this._destroy(e),this.markedForRemoval=!0;for(let t of this.lifecycleCallbacks.cleanup)t(e);typeof this._cleanup=="function"&&this._cleanup(e)}}async nodeLoaded(e){typeof this._loaded=="function"&&await this._loaded(e);for(let t of this.lifecycleCallbacks.loaded)t(e)}nodeCleanup(e){this.children.forEach(t=>t.nodeCleanup?.(e));for(let t of this.lifecycleCallbacks.cleanup)t(e);typeof this._cleanup=="function"&&this._cleanup(e)}getOptions(){return this.options}setOptions(e){this.options={...this.options,...e}}recordLifecycleRegistration(e,t){!this.trackLifecycleRegistrations||t.length===0||this.userLifecycleRegistrations.push({method:e,callbacks:[...t]})}};function ze(i){let e=i?.clone;if(typeof e!="function")throw new Error(`Cannot clone child node "${i.name||i.uuid||"unknown"}": missing clone() support.`);return e.call(i)}import{createTransformStore as Xe}from"@zylem/behaviors/core";import{makeMoveable as Ie}from"@zylem/behaviors/core";function ne(i){let e=Ie(i);return W(e)}import{clearVelocityIntent as fe}from"@zylem/behaviors/core";import{Color as Ze,Vector3 as Ne}from"three";import{Quaternion as Ge}from"three";var se=Symbol("explicitSpawnPosition"),w=new Ge;function re(i){return i.filter(e=>!(e instanceof p)).some(e=>e!=null&&typeof e=="object"&&"position"in e)}function ae(i){i[se]=!0}function Ve(i){return i._spawnPositionExplicit?!0:i.options[se]===!0}function Fe(i){return i.options.hideUntilPositioned!==!1}function le(i){return i._spawnPlacementPending===!0}function Le(i){return i._spawnPositionExplicit===!0||i._spawnPlacementReady===!0}function S(i){let e=i.group??i.mesh;if(e){if(i.physicsAttached&&i.body)try{let t=i.body.translation();e.position.set(t.x,t.y,t.z);return}catch{}if(i.wasmStageRef&&(i.runtimeHandle??-1)>=0){let t=i.wasmStageRef.getPose(i.runtimeHandle);if(t){e.position.set(t.position[0],t.position[1],t.position[2]);return}}if(i.options.position){let t=c(i.options.position,m);e.position.set(t.x,t.y,t.z)}}}function ce(i){let e=i.group??i.mesh;if(!(!e||i.controlledRotation)){if(i.physicsAttached&&i.body)try{let t=i.body.rotation();w.set(t.x,t.y,t.z,t.w),e.setRotationFromQuaternion(w);return}catch{}if(i.wasmStageRef&&(i.runtimeHandle??-1)>=0){let t=i.wasmStageRef.getPose(i.runtimeHandle);t&&(w.set(t.rotation[0],t.rotation[1],t.rotation[2],t.rotation[3]),e.setRotationFromQuaternion(w))}}}function x(i,e){i.group&&(i.group.visible=e),i.mesh&&(i.mesh.visible=e)}function Pt(i){if(i._spawnInProgress=!0,i._spawnPlacementReady=!1,!Fe(i)){i._spawnPlacementPending=!1;return}i._spawnPositionExplicit=Ve(i),i._spawnPlacementPending=!0,x(i,!1)}function Rt(i){i._spawnInProgress=!1}function pe(i){i._spawnPlacementReady=!0}function G(i){if(i._spawnPlacementPending){if(S(i),i._spawnPlacementPending=!1,i.options.visible===!1){x(i,!1);return}x(i,!0)}}function Bt(i){!le(i)||i.options.hideUntilPositioned===!0&&!Le(i)||G(i)}function ue(i){S(i),i._spawnPlacementPending=!1,x(i,!0)}function wt(i){le(i)&&x(i,!1)}var M={position:new Ne(0,0,0),material:{color:new Ze("#ffffff"),shader:K},collision:{static:!1}};function de(i,e){let t=i.filter(n=>!(n instanceof p)),o=u(e);for(let n of t)o=u(o,n);return re(i)&&ae(o),o}function je(i){return i!=null&&typeof i=="object"}function he(i){return{phase:i?.phase??"stay",cooldownMs:i?.cooldownMs}}function Ye(){return typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()}var v=class extends p{group;mesh;materials;bodyDesc=null;body=null;physicsAttached=!1;physicsWorldRef=null;colliderDesc;custom={};colliderBaseline=null;colliderScaleDirty=!1;colliderDescs=[];compoundMeshes=[];debugInfo={};debugMaterial;collisionDelegate={collision:[],cooldowns:new Map,nextId:0};collisionType;packKey=null;bundleKey=null;instanceId=-1;isInstanced=!1;isBundled=!1;runtimeHandle=-1;runtimeAttached=!1;wasmStageRef=null;eventDelegate=new N;behaviorRefs=[];cloneFactory=null;trackAddedComponents=!1;trackedComponents=[];transformStore;_scale={x:1,y:1,z:1};_spawnPlacementPending=!1;_spawnPositionExplicit=!1;_spawnPlacementReady=!1;_spawnInProgress=!1;moveX;moveY;moveZ;moveXY;moveXZ;move;resetVelocity;moveForwardXY;getPosition;getVelocity;setPosition;setPositionX;setPositionY;setPositionZ;wrapAroundXY;wrapAround3D;rotateInDirection;rotateYEuler;rotateEuler;rotateX;rotateY;rotateZ;setRotationY;setRotationX;setRotationZ;setRotationDegrees;setRotationDegreesY;setRotationDegreesX;setRotationDegreesZ;setRotation;getRotation;constructor(){super(),this.transformStore=Xe(),ne(this),this.wrapSpawnPlacementMutators()}wrapSpawnPlacementMutators(){let e=()=>{pe(this),!this._spawnInProgress&&(S(this),G(this))},t=r=>(a,f,y)=>{!this.body&&!(this.wasmStageRef&&this.runtimeHandle>=0)||(r(a,f,y),e())},o=r=>a=>{!this.body&&!(this.wasmStageRef&&this.runtimeHandle>=0)||(r(a),e())};this.setPosition=t(this.setPosition.bind(this)),this.setPositionX=o(this.setPositionX.bind(this)),this.setPositionY=o(this.setPositionY.bind(this)),this.setPositionZ=o(this.setPositionZ.bind(this));let n=()=>{this._spawnInProgress||ce(this)},s=this.setPose.bind(this);this.setPose=r=>{let a=s(r);return a&&(r.position!=null&&e(),r.rotation!=null&&n(),a)}}reveal(){this.options.visible=!0,ue(this)}getPose(){if(this.wasmStageRef&&this.runtimeHandle>=0){let n=this.wasmStageRef.getPose(this.runtimeHandle);if(n)return{position:{x:n.position[0],y:n.position[1],z:n.position[2]},rotation:{x:n.rotation[0],y:n.rotation[1],z:n.rotation[2],w:n.rotation[3]}}}let e=this.body;if(!e)return null;let t=e.translation(),o=e.rotation();return{position:{x:t.x,y:t.y,z:t.z},rotation:{x:o.x,y:o.y,z:o.z,w:o.w}}}setPose(e){if(this.wasmStageRef&&this.runtimeHandle>=0){let o=!0;if(e.position){let n=c(e.position);o=this.wasmStageRef.setPosition(this.runtimeHandle,n.x,n.y,n.z)&&o}if(e.rotation){let{x:n,y:s,z:r,w:a}=e.rotation;o=this.wasmStageRef.setRotation(this.runtimeHandle,n,s,r,a)&&o}return o&&this.body?.markPoseDiscontinuity(),o}let t=this.body;if(!t)return!1;if(e.position){let o=c(e.position);t.setTranslation({x:o.x,y:o.y,z:o.z},!0)}return e.rotation&&t.setRotation(e.rotation,!0),!0}getScale(){return{...this._scale}}setScale(e,t,o){this._scale={x:e,y:t,z:o},(this.group??this.mesh)?.scale.set(e,t,o),this.colliderScaleDirty=!0}add(...e){for(let t of e)t instanceof me?(this.addMeshComponent(t),this.trackComponent(t)):ie(t)?(this.addCollisionComponent(t),this.trackComponent(t)):super.add(t);return this}addMeshComponent(e){if(this.mesh)this.compoundMeshes.push(e),this.group||(this.group=new He,this.group.add(this.mesh)),this.group.add(e);else if(this.mesh=e,this.materials||(this.materials=[]),e.material){let t=e.material;Array.isArray(t)?this.materials.push(...t):this.materials.push(t)}}addCollisionComponent(e){if(this.bodyDesc)this.colliderDescs.push(e.colliderDesc);else{this.bodyDesc=e.bodyDesc,this.colliderDesc=e.colliderDesc,this.colliderDescs.push(e.colliderDesc);let t=c(this.options?.position,m);this.bodyDesc.position=[t.x,t.y,t.z]}}trackComponent(e){if(this.trackAddedComponents){if(e instanceof me){this.trackedComponents.push({kind:"mesh",component:ye(e)});return}this.trackedComponents.push({kind:"collision",component:z(e)})}}_actions=[];runAction(e){return this._actions.push(e),e}action(e){return e.persistent=!0,this._actions.push(e),e}clearActions(){this._actions.length=0}_tickActions(e){if(this._actions.length===0)return;let t=this.transformStore;t.velocity.x=0,t.velocity.y=0,t.velocity.z=0,fe(t,"actions"),t.angularVelocity.x=0,t.angularVelocity.y=0,t.angularVelocity.z=0,t.dirty.angularVelocity=!1;for(let o=this._actions.length-1;o>=0;o--){let n=this._actions[o];n.tick(this,e),n.done&&!n.persistent&&this._actions.splice(o,1)}this._actions.length===0&&(t.velocity.x=0,t.velocity.y=0,t.velocity.z=0,fe(t,"actions"),t.angularVelocity.x=0,t.angularVelocity.y=0,t.angularVelocity.z=0,t.dirty.angularVelocity=!1)}create(){return this.name=this.options.name||"",this}clone(e){if(!this.cloneFactory)throw new Error(`Cannot clone ${this.constructor.name}: clone() is only supported for entities created by official factory helpers.`);let t=this.cloneFactory(u(this.options,e)),o=this.copyBehaviorRefsTo(t),n=r=>We(r,o);this.replayUserLifecycleRegistrationsTo(t,n);let s=this.getCollisionRegistrations();if(s.length>0)for(let r of s)t.onCollision(n(r.callback),r.options);for(let r of this.trackedComponents){if(r.kind==="mesh"){t.add(ye(r.component));continue}t.add(z(r.component))}return this.cloneChildrenInto(t),t}finalizeCloneSupport(e){return this.cloneFactory=e,this.enableUserLifecycleTracking(),this.trackAddedComponents=!0,this}onCollision(...e){let t=[...this.collisionDelegate.collision??[]],o=this.collisionDelegate.nextId??0;if(e.length===1||e.length===2&&(e[1]==null||je(e[1]))){let n=e[0];if(!n)return this;let s=e[1];return t.push({id:o,callback:n,options:he(s)}),o+=1,this.collisionDelegate.collision=t,this.collisionDelegate.nextId=o,this}for(let n of e)t.push({id:o,callback:n,options:he()}),o+=1;return this.collisionDelegate.collision=t,this.collisionDelegate.nextId=o,this}use(e,t){let o={descriptor:e,options:{...e.defaultOptions,...t}};this.behaviorRefs.push(o);let n={getFSM:()=>o.fsm??null,getOptions:()=>o.options,ref:o},s=e.createHandle?.(o)??{};return{...n,...s}}getBehaviorRefs(){return this.behaviorRefs}getBehaviorRef(e){return this.behaviorRefs.find(t=>t.descriptor.key===e.key)??null}hasBehavior(e){return this.getBehaviorRef(e)!==null}removeBehavior(e){let t="descriptor"in e?this.behaviorRefs.indexOf(e):this.behaviorRefs.findIndex(n=>n.descriptor.key===e.key);if(t===-1)return null;let[o]=this.behaviorRefs.splice(t,1);return o??null}restoreBehaviorRef(e){this.behaviorRefs.includes(e)||this.behaviorRefs.push(e)}getCollisionCallbacks(){return this.getCollisionRegistrations().map(e=>e.callback)}getCollisionRegistrations(){return(this.collisionDelegate.collision??[]).map(e=>({id:e.id,callback:e.callback,options:{...e.options}}))}copyBehaviorRefsTo(e){let t=new Map;for(let o of this.behaviorRefs){e.use(o.descriptor,l(o.options));let n=e.getBehaviorRefs().at(-1);n&&t.set(o,n)}return t}_setup(e){for(let t=this._actions.length-1;t>=0;t--){let o=this._actions[t];o.done&&!o.persistent?this._actions.splice(t,1):o.reset()}}async _loaded(e){}_update(e){this.updateMaterials(e)}_destroy(e){}_cleanup(e){this.disposeEvents();for(let t of this.compoundMeshes)t.geometry?.dispose(),Array.isArray(t.material)?t.material.forEach(o=>o.dispose()):t.material?.dispose();this.compoundMeshes.length=0,this.debugMaterial?.dispose(),this.debugMaterial=void 0,this.group?.removeFromParent()}_collision(e,t,o={phase:"stay",nowMs:Ye()}){if(!this.collisionDelegate.collision?.length)return;let n=this.collisionDelegate.cooldowns??new Map;this.collisionDelegate.cooldowns=n;for(let s of this.collisionDelegate.collision){if(s.options.phase!==o.phase)continue;let r=s.options.cooldownMs;if(r!=null){let a=`${s.id}:${e.uuid}`,f=n.get(a);if(f!=null&&o.nowMs-f<r)continue;n.set(a,o.nowMs)}s.callback({entity:this,other:e,globals:t})}}hasMaterial(){return this.mesh!==void 0||this.compoundMeshes.length>0}getMaterials(){return this.materials?[...this.materials]:[]}setMaterial(e,t={}){if(!this.hasMaterial())return null;let o=new B,n=this.constructor.type??Symbol.for("zylem:entity");return o.build(e,n),this.replaceMaterials(o.materials,t)}replaceMaterials(e,t={}){if(!this.hasMaterial()||e.length===0)return null;let{disposePrevious:o=!0}=t,n=this.materials?[...this.materials]:[],s=r=>{Array.isArray(r.material)?r.material=r.material.map((a,f)=>e[f%e.length]):r.material=e[0]};this.mesh&&s(this.mesh);for(let r of this.compoundMeshes)s(r);if(this.materials=[...e],o)for(let r of n)e.includes(r)||r.dispose();return n}updateMaterials(e){if(this.materials?.length)for(let t of this.materials)t instanceof Ue&&t.uniforms&&t.uniforms.iTime&&(t.uniforms.iTime.value+=e.delta)}buildInfo(){let e={};return e.name=this.name,e.uuid=this.uuid,e}dispatch(e,t){this.eventDelegate.dispatch(e,t),U.emit(e,t)}listen(e,t){return this.eventDelegate.listen(e,t)}disposeEvents(){this.eventDelegate.dispose()}};function Ke(i){let e=new v;return e.options={...M,...i},E(e,t=>Ke(t??{}))}function ye(i){let e=i.clone(!0),t=[],o=[];i.traverse(n=>t.push(n)),e.traverse(n=>o.push(n));for(let n=0;n<t.length;n++){let s=t[n],r=o[n];s?.geometry?.clone&&(r.geometry=s.geometry.clone()),s?.material&&(r.material=Array.isArray(s.material)?s.material.map(a=>a.clone()):s.material.clone())}return e}function We(i,e){return e.size===0?i:((...t)=>{let o=Array.from(e.entries()).map(([n,s])=>({sourceRef:n,options:n.options,fsm:n.fsm,hasFSM:Object.prototype.hasOwnProperty.call(n,"fsm"),targetRef:s}));for(let n of o)n.sourceRef.options=n.targetRef.options,n.targetRef.fsm===void 0?delete n.sourceRef.fsm:n.sourceRef.fsm=n.targetRef.fsm;try{return i(...t)}finally{for(let n=o.length-1;n>=0;n--){let s=o[n];s.sourceRef.options=s.options,s.hasFSM?s.sourceRef.fsm=s.fsm:delete s.sourceRef.fsm}}})}function E(i,e){return i.finalizeCloneSupport(e),i}function be(i){return typeof i?.load=="function"&&typeof i?.data=="function"}var D=class{entityReference;constructor(e){this.entityReference=e}load(){this.entityReference.load&&this.entityReference.load()}data(){return this.entityReference.data?this.entityReference.data():null}};function ai(i){let{args:e,defaultConfig:t,EntityClass:o,BuilderClass:n,entityType:s,MeshBuilderClass:r,CollisionBuilderClass:a,cloneFactory:f}=i,y=null,b,L=e.findIndex(d=>!(d instanceof p));L!==-1&&(b=e.splice(L,1).find(C=>!(C instanceof p)));let Oe=b?u(t,b):u(t);e.push(Oe);for(let d of e){if(d instanceof p)continue;let C=null,k=new o(d);try{if(be(k)){let O=new D(k);O.load(),C=O.data()}}catch(O){console.error("Error creating entity with loader:",O)}y=new n(d,k,r?new r(C):null,a?new a(C):null),d.material&&y.withMaterial(d.material,s)}if(!y)throw new Error(`missing options for ${String(s)}, builder is not initialized.`);let Z=y.build();return b!=null&&typeof b=="object"&&"position"in b&&(Z._spawnPositionExplicit=!0),E(Z,d=>f(d))}import{Vector3 as V}from"three";var Ce={...M,size:new V(1,1,1),collision:{static:!0}},$e=Symbol("Zone"),F=class extends v{static type=$e;_enteredZone=new Map;_exitedZone=new Map;_zoneEntities=new Map;constructor(e){super(),this.options=u(Ce,e)}getSelectionBounds(e){let t=R(this.options.size,new V(1,1,1)),o=this.getPose()?.position??c(this.options.position,m);return e.setFromCenterAndSize(new V(o.x,o.y,o.z),t),q(e)}handlePostCollision({delta:e}){return this._enteredZone.forEach((t,o)=>{this.exited(e,o)}),this._enteredZone.size>0}handleIntersectionEvent({other:e,delta:t}){this._enteredZone.get(e.uuid)?this.held(t,e):(this.entered(e),this._zoneEntities.set(e.uuid,e))}onEnter(e){return this.options.onEnter=e,this}onHeld(e){return this.options.onHeld=e,this}onExit(e){return this.options.onExit=e,this}entered(e){this._enteredZone.set(e.uuid,1),this.options.onEnter&&this.options.onEnter({self:this,visitor:e,globals:P.globals})}exited(e,t){let o=this._exitedZone.get(t);if(o&&o>1+e){this._exitedZone.delete(t),this._enteredZone.delete(t);let n=this._zoneEntities.get(t);this.options.onExit&&this.options.onExit({self:this,visitor:n,globals:P.globals});return}this._exitedZone.set(t,1+e)}held(e,t){let o=this._enteredZone.get(t.uuid)??0;this._enteredZone.set(t.uuid,o+e),this._exitedZone.set(t.uuid,1),this.options.onHeld&&this.options.onHeld({delta:e,self:this,visitor:t,globals:P.globals,heldTime:o})}};function Qe(...i){let e=de(i,Ce),t=new F(e);return t.add(I({size:e.size,static:e.collision?.static??!0,collisionType:e.collisionType,collisionFilter:e.collisionFilter})),E(t,o=>Qe(o??{}))}import{BufferGeometry as Je,Mesh as ge,Color as et}from"three";import{Mesh as qe}from"three";var _=class{_build(e,t,o){let n=new qe(t,o.at(-1));return n.position.set(0,0,0),n.castShadow=!0,n.receiveShadow=!0,n}_postBuild(){}};var xe=class extends Q{},ve=class extends _{build(e){return new Je}postBuild(){}},Ee=class{meshBuilder;collisionBuilder;materialBuilder;options;entity;constructor(e,t,o,n){this.options=e,this.entity=t,this.meshBuilder=o,this.collisionBuilder=n,this.materialBuilder=new B;let s={meshBuilder:this.meshBuilder,collisionBuilder:this.collisionBuilder,materialBuilder:this.materialBuilder};this.options._builders=s,t&&t.options&&(t.options._builders=s)}withPosition(e){return this.options.position=e,this}withMaterial(e,t){return this.materialBuilder&&this.materialBuilder.build(e,t),this}applyMaterialToGroup(e,t){e.traverse(o=>{o instanceof ge&&o.type==="SkinnedMesh"&&t[0]&&!o.material.map&&(o.material=t[0]),o.castShadow=!0,o.receiveShadow=!0})}build(){let e=this.entity;if(this.materialBuilder&&(e.materials=this.materialBuilder.materials),this.meshBuilder&&e.materials){let t=this.meshBuilder.build(this.options);e.mesh=this.meshBuilder._build(this.options,t,e.materials),this.meshBuilder.postBuild()}if(e.group&&e.materials&&this.applyMaterialToGroup(e.group,e.materials),this.collisionBuilder){this.collisionBuilder.withCollision(this.options?.collision||{});let[t,o]=this.collisionBuilder.build(this.options);e.bodyDesc=t,e.colliderDesc=o,e.colliderDescs.push(o);let{x:n,y:s,z:r}=c(this.options.position,m);e.bodyDesc.position=[n,s,r]}if(this.options.collisionType&&(e.collisionType=this.options.collisionType),this.options.color instanceof et){let t=o=>{let n=o;n&&n.color&&n.color.set&&n.color.set(this.options.color)};if(e.materials?.length)for(let o of e.materials)t(o);if(e.mesh&&e.mesh.material){let o=e.mesh.material;Array.isArray(o)?o.forEach(t):t(o)}e.group&&e.group.traverse(o=>{if(o instanceof ge&&o.material){let n=o.material;Array.isArray(n)?n.forEach(t):t(n)}})}return e}};export{p as a,u as b,we as c,Se as d,Me as e,De as f,_e as g,ke as h,Te as i,I as j,le as k,S as l,Pt as m,Rt as n,Bt as o,ue as p,wt as q,M as r,de as s,v as t,Ke as u,E as v,xe as w,ve as x,Ee as y,ai as z,$e as A,F as B,Qe as C};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{G as b,H as I,I as Z}from"./chunk-5V52N34T.js";import{a as O,b as a,r as T,t as l,v as p}from"./chunk-VXE3CV3K.js";import{e as w}from"./chunk-UUOPT2N4.js";import{j as C}from"./chunk-4QLJUQSJ.js";import{a as S,g as _,i as v,j as E}from"./chunk-7WRQ2UAN.js";import{Group as N,Quaternion as U,Vector3 as d}from"three";import{ParticleEmitterBehavior as u}from"@zylem/behaviors/particle-emitter";var X={...T,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},M=Symbol("ParticleSystem"),y=1,W=new d(y,y,y),R=new d;function Q(i){return{effect:i.preset??i.effect,autoplay:i.autoplay,localOffset:i.localOffset,followPosition:i.followPosition,followRotation:i.followRotation,autoDestroy:i.autoDestroy}}var c=class i extends l{static type=M;particleHandle=null;getSelectionBounds(o){return this.group?(this.group.getWorldPosition(R),o.setFromCenterAndSize(R,W),w(o)):null}constructor(o,e=!0){super(),this.options=a(X,o),this.group=new N;let t=this.options.position;t&&this.group.position.copy(E(t)),this.__zylemParticleSystemEntity=!0,this.bindStandaloneTransforms(),e&&(this.particleHandle=this.use(u,Q(this.options)))}bindStandaloneTransforms(){let o=()=>{this.options.position=new d(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=(t,r,n)=>{this.group?.position.set(t,r,n),o()},this.setPositionX=t=>{this.group&&(this.group.position.x=t,o())},this.setPositionY=t=>{this.group&&(this.group.position.y=t,o())},this.setPositionZ=t=>{this.group&&(this.group.position.z=t,o())},this.getPosition=()=>this.group?{x:this.group.position.x,y:this.group.position.y,z:this.group.position.z}:null,this.setRotation=(t,r,n)=>{this.group?.rotation.set(t,r,n),e()},this.setRotationX=t=>{this.group&&(this.group.rotation.x=t,e())},this.setRotationY=t=>{this.group&&(this.group.rotation.y=t,e())},this.setRotationZ=t=>{this.group&&(this.group.rotation.z=t,e())},this.setRotationDegrees=(t,r,n)=>{this.group?.rotation.set(t*Math.PI/180,r*Math.PI/180,n*Math.PI/180),e()},this.setRotationDegreesX=t=>{this.group&&(this.group.rotation.x=t*Math.PI/180,e())},this.setRotationDegreesY=t=>{this.group&&(this.group.rotation.y=t*Math.PI/180,e())},this.setRotationDegreesZ=t=>{this.group&&(this.group.rotation.z=t*Math.PI/180,e())},this.rotateX=t=>{this.group?.rotateX(t),e()},this.rotateY=t=>{this.group?.rotateY(t),e()},this.rotateZ=t=>{this.group?.rotateZ(t),e()},this.getRotation=()=>{if(!this.group)return null;let t=new U;return this.group.getWorldQuaternion(t),t}}resolveParticleHandle(){if(this.particleHandle)return this.particleHandle;let o=this.getBehaviorRefs().find(r=>r.descriptor.key===u.key);if(!o)return null;let e={getFSM:()=>o.fsm??null,getOptions:()=>o.options,ref:o},t=u.createHandle?.(o)??{};return this.particleHandle={...e,...t},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 H(i,o=!0){let e=new c(i,o);return p(e,t=>H(t,!1))}function $(i){return H(i,!0)}import{Group as q,Sprite as K,SpriteMaterial as j,CanvasTexture as J,LinearFilter as z,Color as D,ClampToEdgeWrapping as B}from"three";import{getCooldown as Y}from"@zylem/behaviors/cooldown";var L=192,tt={xs:8,sm:16,md:32,lg:48,xl:64},f={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)"},et=Symbol("CooldownIcon"),P=class extends l{static type=et;_sprite=null;_texture=null;_canvas=null;_ctx=null;_cameraRef=null;_iconTexture=null;_iconImage=null;_lastRenderedProgress=-1;constructor(o){super(),this.options=a(f,o),this.options.screenPosition=v(this.options.screenPosition,f.screenPosition),this.group=new q,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 J(this._canvas),this._texture.minFilter=z,this._texture.magFilter=z,this._texture.wrapS=B,this._texture.wrapT=B;let e=new j({map:this._texture,transparent:!0,depthTest:!1,depthWrite:!1});if(this._sprite=new K(e),this.group?.add(this._sprite),this.options.icon){let t=new Image;t.crossOrigin="anonymous",t.onload=()=>{this._iconImage=t,this.redraw(this._lastRenderedProgress>=0?this._lastRenderedProgress:1)},t.src=this.options.icon}this.redraw(1)}redraw(o){if(!this._canvas||!this._ctx)return;let e=this._ctx,t=this._canvas.width,r=this._canvas.height,n=t/2,s=r/2,A=Math.min(n,s);if(e.clearRect(0,0,t,r),this._iconImage?e.drawImage(this._iconImage,0,0,t,r):(e.fillStyle=this.toCssColor(this.options.fillColor??"#333333"),e.fillRect(0,0,t,r)),o<1){let k=(1-o)*Math.PI*2,g=-Math.PI/2,V=g+k;if(e.save(),e.fillStyle=this.options.overlayColor??"rgba(0, 0, 0, 0.65)",e.beginPath(),e.moveTo(n,s),e.arc(n,s,A+1,g,V,!1),e.closePath(),e.fill(),e.restore(),this.options.showTimer){let m=Y(this.options.cooldown);if(m){let h=Math.max(0,m.duration-m.elapsed),x=h>=10?Math.ceil(h).toString():h.toFixed(1),G=Math.floor(t*.3);e.font=`bold ${G}px sans-serif`,e.textAlign="center",e.textBaseline="middle",e.fillStyle="#FFFFFF",e.strokeStyle="#000000",e.lineWidth=2,e.strokeText(x,n,s),e.fillText(x,n,s)}}}this._texture&&(this._texture.needsUpdate=!0),this._lastRenderedProgress=o}toCssColor(o){return typeof o=="string"?o:`#${(o instanceof D?o:new D(o)).getHexString()}`}iconSetup(o){this._sprite||this.createSprite(),this._cameraRef=o.camera,this.options.stickToViewport&&this._cameraRef&&(this._cameraRef.camera.add(this.group),this.updateStickyTransform())}iconUpdate(o){let t=Y(this.options.cooldown)?.progress??1;(Math.abs(t-this._lastRenderedProgress)>.02||t===1&&this._lastRenderedProgress!==1)&&this.redraw(t),this.options.stickToViewport&&this._cameraRef&&this.updateStickyTransform()}resolveIconSize(o){let e=this.options.iconSize??"md",t,r;typeof e=="string"?t=r=tt[e]:typeof e=="number"?t=r=e:(t=e.width,r=e.height);let n=o/L;return{widthPx:t*n,heightPx:r*n}}updateStickyTransform(){if(!this._sprite||!this._cameraRef)return;let o=I(this._cameraRef),e=o.height/L,t=_(this.options.screenPosition,S),{widthPx:r,heightPx:n}=this.resolveIconSize(o.height),s=Z({camera:this._cameraRef.camera,viewport:o,point:b(this.options.screenAnchor??"top-left",{x:t.x*e,y:t.y*e},o),pivot:{x:.5,y:.5},size:{width:r,height:n},zDistance:this.options.zDistance??1});this._sprite.scale.set(s.scale.x,s.scale.y,1),this.group?.position.set(s.position.x,s.position.y,s.position.z)}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 F(...i){let o=i.filter(t=>!(t instanceof O)),e={...f};for(let t of o)e={...e,...t};return p(new P(e),t=>F(t??{}))}function ot(i,o,e){e({me:i,globals:o})}function it(i,o){let e=o??C();ot(i,e,i.nodeDestroy.bind(i))}export{M as a,c as b,$ as c,F as d,it as e};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{F as U,G as B,H as X,I as N,a as f}from"./chunk-5V52N34T.js";import{b as u,r as C,s as k,t as d,v as G,w as D,y as v,z as b}from"./chunk-VXE3CV3K.js";import{e as V}from"./chunk-6FGXC4T6.js";import{c as h,d as y,h as m,i as T,j as x}from"./chunk-7WRQ2UAN.js";import{Color as W,Group as ot,Sprite as at,SpriteMaterial as pt,CanvasTexture as H,LinearFilter as w,Vector2 as lt,ClampToEdgeWrapping as Y}from"three";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 lt(24,24),zDistance:1},E=class extends v{createEntity(t){return new _(t)}},ct=Symbol("Text"),_=class i extends d{static type=ct;_sprite=null;_texture=null;_canvas=null;_ctx=null;_cameraRef=null;_lastCanvasW=0;_lastCanvasH=0;constructor(t){super(),this.options=u(g,t),this.options.screenPosition=T(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 ot,this.createSprite(),super.create()}createSprite(){this._canvas=document.createElement("canvas"),this._ctx=this._canvas.getContext("2d"),this._texture=new H(this._canvas),this._texture.minFilter=w,this._texture.magFilter=w;let t=new pt({map:this._texture,transparent:!0,depthTest:!1,depthWrite:!1,alphaTest:.5});this._sprite=new at(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),st=p!==this._lastCanvasW||l!==this._lastCanvasH;return this._canvas.width=p,this._canvas.height=l,this._lastCanvasW=p,this._lastCanvasH=l,{sizeChanged:st}}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 H(this._canvas),this._texture.minFilter=w,this._texture.magFilter=w,this._texture.wrapS=Y,this._texture.wrapT=Y),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 W?t:new W(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()}screenPoint(t){let e=T(this.options.screenPosition,g.screenPosition);if(this.options.screenAnchor)return B(this.options.screenAnchor,e,t);let n=e.x>=0&&e.x<=1,r=e.y>=0&&e.y<=1;return{x:n?e.x*t.width:e.x,y:r?e.y*t.height:e.y}}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||!this._canvas)return;let t=X(this._cameraRef),e=N({camera:this._cameraRef.camera,viewport:t,point:this.screenPoint(t),pivot:this.options.screenAnchor?U(this.options.screenAnchor):{x:.5,y:.5},size:{width:this._canvas.width,height:this._canvas.height},zDistance:this.options.zDistance??1});this._sprite.scale.set(e.scale.x,e.scale.y,1),this.group?.position.set(e.position.x,e.position.y,e.position.z)}updateText(t){this.options.text=t,this.redrawText(t),this.options.stickToViewport&&this._cameraRef&&this.updateStickyTransform()}buildInfo(){return{...new f(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 O(...i){return b({args:i,defaultConfig:{...g},EntityClass:_,BuilderClass:E,entityType:_.type,cloneFactory:t=>O(t??{})})}import{Euler as ht,Group as $,Quaternion as mt,Vector3 as ut}from"three";import{TextureLoader as j,SpriteMaterial as Q,Sprite as q,SRGBColorSpace as J}from"three";import{ClampToEdgeWrapping as K,LinearFilter as dt,NearestFilter as ft}from"three";var tt={...C,size:new ut(1,1,1),images:[],animations:[]},F=class extends D{collider(t){let e=x(t.collisionSize,t.size??y);return{shape:{type:"box",halfExtents:[e.x/2,e.y/2,e.z/2]}}}},z=class extends v{createEntity(t){return new S(t)}},yt=Symbol("Sprite"),S=class i extends d{static type=yt;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=u(tt,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 j,n=x(this.options.size,y);t.forEach((r,s)=>{let o=e.load(r.file);o.colorSpace=J,o.anisotropy=V;let a=new Q({map:o,transparent:!0}),p=new q(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 $,this.group.add(...this.sprites)}createSpriteFromSheet(t){let e=x(this.options.size,y),n=new j().load(t.file);n.colorSpace=J,n.wrapS=K,n.wrapT=K;let r=t.filter==="linear"?dt:ft;n.magFilter=r,n.minFilter=r,n.generateMipmaps=!1,n.repeat.set(1/t.columns,1/t.rows);let s=new Q({map:n,transparent:!0}),o=new q(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 $,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 mt(t.x,t.y,t.z,t.w),s=new ht().setFromQuaternion(r,"XYZ");e.material.rotation=s.z}let n=x(this.options.size,y);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 f(this).buildDebugInfo(),type:String(i.type)}}};function L(...i){return b({args:i,defaultConfig:tt,EntityClass:S,BuilderClass:z,CollisionBuilderClass:F,entityType:S.type,cloneFactory:t=>L(t??{})})}import{Color as nt,Group as gt}from"three";import{Line2NodeMaterial as _t}from"three/webgpu";import{Line2 as St}from"three/addons/lines/webgpu/Line2.js";import{Color as et}from"three";import{LineGeometry as xt}from"three/addons/lines/LineGeometry.js";function I(i){let t=[];for(let e of i){let{x:n,y:r,z:s}=m(e,h);t.push(n,r,s)}return t}function A(i,t,e){if(!i||i.length===0)return;let n=[],r=new et(e);for(let s=0;s<t;s++){let o=i[s]??i[i.length-1]??e,a=new et(o??r);n.push(a.r,a.g,a.b)}return n}function it(i){let t=new xt,e=I(i.points);t.setPositions(e);let n=A(i.colors,i.points.length,"#ffffff");return n&&t.setColors(n),t}var c={...C,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},Ct=Symbol("Line");function R(i,t){if(!i||i.length<2)throw new Error(`${t}: at least two points are required`);return i}function rt(i){return i instanceof nt?i.clone():new nt(i??"#ffffff")}function vt(i){let t=!!i.colors?.length,e=new _t({color:rt(i.color).getHex(),linewidth:i.linewidth??c.linewidth,worldUnits:i.worldUnits??c.worldUnits,vertexColors:t,dashed:i.dashed??!1,dashSize:i.dashSize??c.dashSize,gapSize:i.gapSize??c.gapSize,transparent:i.transparent??!1,opacity:i.opacity??1});return e.alphaToCoverage=i.alphaToCoverage??!1,e}function bt(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 wt(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?bt(a):null}var P=class i extends d{static type=Ct;_line=null;_geometry=null;_material=null;constructor(t){super();let e=u(c,t);e.points=R(e.points,"ZylemLine").map(n=>m(n,h)),this.options=e}create(){return this.disposeLineResources(),this.group=new gt,this.rebuildLine(),this.applyGroupPosition(),super.create()}setPoints(t,e){if(R(t,"setPoints"),this.options.points=t.map(r=>m(r,h)),e&&(this.options.colors=e),!this._line||!this._geometry||!this._material)return this;this._geometry.setPositions(I(this.options.points));let n=A(this.options.colors,this.options.points.length,rt(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 wt(t,this,e)}buildInfo(){return{...new f(this).buildDebugInfo(),type:String(i.type),points:this.options.points.length,linewidth:this.options.linewidth??c.linewidth,worldUnits:this.options.worldUnits??c.worldUnits}}rebuildLine(){this._geometry=it({points:this.options.points,colors:this.options.colors}),this._material=vt(this.options),this._line=new St(this._geometry,this._material),this.options.dashed&&this._line.computeLineDistances(),this.group?.add(this._line)}applyGroupPosition(){if(!this.group)return;let t=m(this.options.position,h);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 Z(...i){let t=k(i,c);R(t.points,"createLine");let e=new P(t);return G(e,n=>Z(n??{}))}var M={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)}};M.register("text",i=>O(i));M.register("sprite",i=>L(i));M.register("line",i=>Z(i));function Se(i){return{template:i,generate(t){let e=[];for(let n=0;n<t;n++)e.push(i.clone());return e}}}export{ct as a,_ as b,O as c,yt as d,S as e,L as f,Ct as g,wt as h,P as i,Z as j,M as k,Se as l};
|
package/dist/cinematics.d.ts
CHANGED
|
@@ -2,7 +2,7 @@ import { k as CutsceneEasing, V as Vec3Def, h as CutsceneScene, n as CameraShot,
|
|
|
2
2
|
export { A as AudioItemSchema, q as AudioTrack, l as CameraKeyframe, c as CameraKeyframeSchema, m as CameraPoseDef, d as CameraShotSchema, j as CutsceneCameraKind, b as CutsceneCameraSchema, C as CutsceneDefinitionSchema, u as CutsceneEvent, e as CutsceneEventSchema, a as CutsceneSceneSchema, r as CutsceneTrack, f as CutsceneTrackSchema, D as DollyPathSchema, E as EventItemSchema, p as EventTrack, S as SceneTransitionSchema, t as ShotBlend } from './cutscene-definition-C479fkei.js';
|
|
3
3
|
import { f as CameraBehavior, d as CameraContext, C as CameraPose, l as ZylemCamera } from './zylem-camera-CWhIGXlW.js';
|
|
4
4
|
import { Z as ZylemTransitionShader } from './stage-transition-CmGpV4tc.js';
|
|
5
|
-
import { Z as ZylemStage, q as Stage } from './stage-
|
|
5
|
+
import { Z as ZylemStage, q as Stage } from './stage-B_KdSEK6.js';
|
|
6
6
|
import { g as SongDefinition } from './song-definition-rEKksP0B.js';
|
|
7
7
|
import { CutsceneStatusPayload, CutsceneViewPayload, CutsceneLoadPayload, CameraPosePayload } from '@zylem/bridge';
|
|
8
8
|
import '@sinclair/typebox';
|
|
@@ -13,8 +13,8 @@ import '@zylem/behaviors/core';
|
|
|
13
13
|
import 'three/webgpu';
|
|
14
14
|
import './base-node-idopiSw5.js';
|
|
15
15
|
import './base-node-life-cycle-BK9xebT9.js';
|
|
16
|
-
import './entity-type-map-
|
|
17
|
-
import './entity-
|
|
16
|
+
import './entity-type-map-B0S5cfv7.js';
|
|
17
|
+
import './entity-DC0P747T.js';
|
|
18
18
|
import './vector-D3eDzvcA.js';
|
|
19
19
|
import './material-CxxAyJYp.js';
|
|
20
20
|
import './collision-builder-BckxkdmA.js';
|
|
@@ -24,6 +24,7 @@ import './selection-bounds-BKmSo9aG.js';
|
|
|
24
24
|
import '@zylem/behaviors/particle-emitter';
|
|
25
25
|
import 'three/addons/lines/webgpu/Line2.js';
|
|
26
26
|
import './game-interfaces-vF5sRi1n.js';
|
|
27
|
+
import './level-types-D10LiOcn.js';
|
|
27
28
|
|
|
28
29
|
/**
|
|
29
30
|
* Pure evaluation of a cutscene at a point in time: which scene and shot are
|
package/dist/core.d.ts
CHANGED
|
@@ -1,13 +1,14 @@
|
|
|
1
|
-
import { S as StageStateInterface } from './game-
|
|
2
|
-
export { A as AspectRatio, f as AspectRatioValue, D as DeviceProfile, G as Game, b as GameConfigLike, d as GameDeviceConfig, a as GameLoadingEvent, R as ResolutionInput, e as ResolveGameConfigRuntime, j as RetroPreset, k as RetroPresetKey, l as RetroResolution, c as createGame, g as gameConfig, h as getDisplayAspect, i as getPresetResolution, p as parseResolution } from './game-
|
|
1
|
+
import { S as StageStateInterface } from './game-mu6OSCrq.js';
|
|
2
|
+
export { A as AspectRatio, f as AspectRatioValue, D as DeviceProfile, G as Game, b as GameConfigLike, d as GameDeviceConfig, a as GameLoadingEvent, R as ResolutionInput, e as ResolveGameConfigRuntime, j as RetroPreset, k as RetroPresetKey, l as RetroResolution, c as createGame, g as gameConfig, h as getDisplayAspect, i as getPresetResolution, p as parseResolution } from './game-mu6OSCrq.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
|
-
import { q as Stage, C as CameraWrapper } from './stage-
|
|
5
|
-
export { e as CameraManager, d as CameraOptions, l as FirstPersonOptions, f as FirstPersonPerspective, k as Fixed2DOptions, F as Fixed2DPerspective, n as IsometricOptions, I as IsometricPerspective, P as PerspectiveOptions, R as RenderBundleManager, p as RenderStrategyManager, m as SecondPersonOptions, g as SecondPersonPerspective, S as StageConfigLike, a as StageOptions, j as ThirdPersonOptions, T as ThirdPersonPerspective, o as TopDownOptions, h as TopDownPerspective, b as createCamera, i as createPerspective, c as createStage, s as stageConfig } from './stage-
|
|
4
|
+
import { q as Stage, C as CameraWrapper } from './stage-B_KdSEK6.js';
|
|
5
|
+
export { e as CameraManager, d as CameraOptions, l as FirstPersonOptions, f as FirstPersonPerspective, k as Fixed2DOptions, F as Fixed2DPerspective, n as IsometricOptions, I as IsometricPerspective, P as PerspectiveOptions, R as RenderBundleManager, p as RenderStrategyManager, m as SecondPersonOptions, g as SecondPersonPerspective, S as StageConfigLike, a as StageOptions, j as ThirdPersonOptions, T as ThirdPersonPerspective, o as TopDownOptions, h as TopDownPerspective, b as createCamera, i as createPerspective, c as createStage, s as stageConfig } from './stage-B_KdSEK6.js';
|
|
6
6
|
import { LevelBuffer, LevelEntry } from '@zylem/bridge';
|
|
7
7
|
export { LevelBuffer } from '@zylem/bridge';
|
|
8
8
|
import { B as BaseNode, N as NodeInterface } from './base-node-idopiSw5.js';
|
|
9
|
+
import { L as LevelDocument } from './level-types-D10LiOcn.js';
|
|
9
10
|
import { Vector2 } from 'three';
|
|
10
|
-
import { G as GameEntity, a as GameEntityOptions } from './entity-
|
|
11
|
+
import { G as GameEntity, a as GameEntityOptions } from './entity-DC0P747T.js';
|
|
11
12
|
import { S as StageBlueprint } from './blueprints-TbGY-h53.js';
|
|
12
13
|
import { a as SetupContext, k as LoadedContext, U as UpdateContext, D as DestroyContext, l as CleanupContext } from './base-node-life-cycle-BK9xebT9.js';
|
|
13
14
|
export { L as LoadingEvent, S as StageNavigationOptions } from './base-node-life-cycle-BK9xebT9.js';
|
|
@@ -21,7 +22,7 @@ import './default-controls-CAKJ5zlo.js';
|
|
|
21
22
|
import './events.js';
|
|
22
23
|
import 'mitt';
|
|
23
24
|
import '@zylem/behaviors/core';
|
|
24
|
-
import './entity-type-map-
|
|
25
|
+
import './entity-type-map-B0S5cfv7.js';
|
|
25
26
|
import './material-CxxAyJYp.js';
|
|
26
27
|
import 'three/webgpu';
|
|
27
28
|
import './selection-bounds-BKmSo9aG.js';
|
|
@@ -78,6 +79,18 @@ interface LevelStage {
|
|
|
78
79
|
*/
|
|
79
80
|
declare function streamLevelOnStage(stage: LevelStage, buffer: LevelBuffer, options?: StreamLevelOptions): Promise<StreamLevelResult>;
|
|
80
81
|
|
|
82
|
+
/**
|
|
83
|
+
* The stage's picture of the level document.
|
|
84
|
+
*
|
|
85
|
+
* The editor owns the file. This session draws it, reports finished gestures,
|
|
86
|
+
* and on play swaps the brush faces for one static body of convex hulls.
|
|
87
|
+
* Nothing it creates is a normal stage entity except play-mode trigger zones,
|
|
88
|
+
* and those are marked editor-owned so they are not published back.
|
|
89
|
+
*/
|
|
90
|
+
|
|
91
|
+
/** The document currently previewed or playing, for hosts that spawn from markers. */
|
|
92
|
+
declare function getActiveLevelDocument(): LevelDocument | null;
|
|
93
|
+
|
|
81
94
|
/**
|
|
82
95
|
* Authoring helper for spawning entities into a live stage at runtime.
|
|
83
96
|
*
|
|
@@ -386,4 +399,4 @@ declare function isManagedRenderEntity(entity: {
|
|
|
386
399
|
*/
|
|
387
400
|
type Vect3 = Vec3;
|
|
388
401
|
|
|
389
|
-
export { CameraBehavior, type CameraFeedOptions, CameraWrapper, type FollowTargetOptions, type LevelStage, type PlatformAxisMode, type PlatformAxisModes, type PlatformFollowOptions, type RenderCategory, STAGE_STATE_CHANGE, SetupContext, StageBlueprint, StageEntity, StageManager, type StageStateChangeEvent, type StrategyPanBehavior, type StrategyPanInput, type StrategyPanOptions, type StrategyPointer, type StreamLevelOptions, type StreamLevelResult, UpdateContext, Vec3, Vec3Input, type Vect3, createFollowTarget, createPlatformFollow, createStrategyPan, dispatchStageState, entitySpawner, initStageStateDispatcher, isManagedRenderEntity, resolveRenderCategory, setCameraFeed, setStageFrameProfilerEnabled, stageState, streamLevel, streamLevelOnStage, usesManagedRenderPath, vessel };
|
|
402
|
+
export { CameraBehavior, type CameraFeedOptions, CameraWrapper, type FollowTargetOptions, LevelDocument, type LevelStage, type PlatformAxisMode, type PlatformAxisModes, type PlatformFollowOptions, type RenderCategory, STAGE_STATE_CHANGE, SetupContext, StageBlueprint, StageEntity, StageManager, type StageStateChangeEvent, type StrategyPanBehavior, type StrategyPanInput, type StrategyPanOptions, type StrategyPointer, type StreamLevelOptions, type StreamLevelResult, UpdateContext, Vec3, Vec3Input, type Vect3, createFollowTarget, createPlatformFollow, createStrategyPan, dispatchStageState, entitySpawner, getActiveLevelDocument, initStageStateDispatcher, isManagedRenderEntity, resolveRenderCategory, setCameraFeed, setStageFrameProfilerEnabled, stageState, streamLevel, streamLevelOnStage, usesManagedRenderPath, vessel };
|