const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./materialx.eMaybKAQ.js","./materialx.CnHmG--Y.js","./rolldown-runtime.CYVBeYYp.js","./three@0.169.19.js","./rapier3d.DBFmcAzL.js","./needle-engine.dep.DFJFZC0m.js","./postprocessing.Wy71DpiM.js","./N8AO.C2WXsanG.js","./postprocessing.ao.BRYreHJS.js","./three-examples.extras@0.169.19.js","./peerjs.UdR1_Ath.js","./needle-engine.BJP2NBoC.js","./needle-engine.dep.B3nA4wQ5.js","./three-mesh-bvh.B-oXEGo2.js","./GenerateMeshBVHWorker.DMD7ZOpN.js","./needle-engine@5.0.3.js","./needle-engine.extras.CWxm8YHB.js","./needle-engine-webxr.BfNO-tft.js","./gltf-progressive.BBJGcb3s.js","./three-examples@0.169.19.js","./needle-engine-particles.Bz_Ei_ja.js","./three-quarks.DALdLWPD.js","./needle-engine.extras.1SuflpgE.js"])))=>i.map(i=>d[i]); import{n as e,r as t,t as n}from"./rolldown-runtime.CYVBeYYp.js";import{d as r}from"./materialx.CnHmG--Y.js";import{$n as i,A as a,Ar as o,At as s,B as c,Bt as l,Cn as u,Fr as d,Ft as f,Gn as p,H as m,Ir as h,Jt as g,Kn as _,L as v,Nt as ee,On as y,Ot as b,Pr as te,Qn as ne,Qt as re,S as ie,St as ae,Wt as oe,X as se,Xt as ce,Yt as le,Z as ue,Zn as de,Zt as x,_ as fe,_n as pe,_r as me,a as he,ct as ge,d as _e,dt as ve,et as ye,fn as S,gn as C,gr as be,h as xe,i as Se,in as Ce,it as we,jr as Te,jt as Ee,k as De,kr as w,lr as Oe,mn as ke,mr as Ae,nr as je,o as Me,on as Ne,or as Pe,p as Fe,pr as Ie,qt as T,rr as Le,rt as Re,sr as ze,st as Be,tr as Ve,tt as He,ur as Ue,ut as We,v as Ge,vn as Ke,w as qe,wn as E,x as Je,xr as Ye,y as Xe,yn as Ze}from"./three@0.169.19.js";import{a as Qe,c as $e,i as et,n as tt,o as D,r as nt,s as rt,t as it}from"./three-mesh-ui.CgGzZ3ml.js";import{A as at,C as ot,E as st,M as ct,S as lt,T as ut,_ as dt,a as ft,h as pt,i as mt,v as ht,w as gt,y as _t}from"./three-examples@0.169.19.js";import{n as vt,o as yt,r as bt,t as xt}from"./gltf-progressive.BBJGcb3s.js";var St=window.location.search.includes(`debugcontext`),O;(function(e){e.ContextRegistered=`ContextRegistered`,e.ContextCreationStart=`ContextCreationStart`,e.ContextCreated=`ContextCreated`,e.ContextFirstFrameRendered=`ContextFirstFrameRendered`,e.ContextDestroying=`ContextDestroying`,e.ContextDestroyed=`ContextDestroyed`,e.MissingCamera=`MissingCamera`,e.ContextClearing=`ContextClearing`,e.ContextCleared=`ContextCleared`})(O||={});var k=class{static get Current(){return globalThis[`NeedleEngine.Context.Current`]}static set Current(e){globalThis[`NeedleEngine.Context.Current`]=e}static get All(){return this.Registered}static Registered=[];static register(e){this.Registered.indexOf(e)===-1&&(St&&console.warn(`Registering context`),this.Registered.push(e),this.dispatchCallback(O.ContextRegistered,e))}static unregister(e){let t=this.Registered.indexOf(e);t!==-1&&(St&&console.warn(`Unregistering context`),this.Registered.splice(t,1))}static _callbacks={};static registerCallback(e,t){this._callbacks[e]||(this._callbacks[e]=[]),this._callbacks[e].push(t)}static unregisterCallback(e,t){if(!this._callbacks[e])return;let n=this._callbacks[e].indexOf(t);n!==-1&&this._callbacks[e].splice(n,1)}static dispatchCallback(e,t,n){if(!this._callbacks[e])return!0;let r={event:e,context:t};if(n)for(let e in n)r[e]=n[e];let i=[];return this._callbacks[e].forEach(e=>{let t=e(r);t instanceof Promise&&i.push(t)}),Promise.all(i)}static addContextCreatedCallback(e){this.registerCallback(O.ContextCreated,e)}static addContextDestroyedCallback(e){this.registerCallback(O.ContextDestroyed,e)}},Ct=new Map;function wt(e=globalThis.location?.hostname){if(Ct.has(e))return Ct.get(e);let t=/(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})|localhost/.test(e);return Ct.set(e,t),t===!0}function Tt(){return window.location.hostname.includes(`glitch.me`)}var Et=()=>e=>e;function Dt(e){return Et()(e)}function Ot(){return!!A(`debug`)}var kt=class{_factory;_cache=[];_maxSize;_index=0;constructor(e,t){this._factory=e,this._maxSize=t}get(){let e=this._index%this._maxSize;return this._index++,this._cache.length<=e&&(this._cache[e]=this._factory()),this._cache[e]}},At=!1,jt=[];typeof window<`u`&&setTimeout(()=>{if(At){let e={},t=new URL(window.location.href),n=new URL(t);n.searchParams.append(`console`,``);let r=n.toString().replace(/=$|=(?=&)/g,``);for(let n of jt){let r=new URL(t);r.searchParams.append(n,``),e[n]=r.toString().replace(/=$|=(?=&)/g,``)}console.log(`🌵 ?help: Debug Options for Needle Engine. Append any of these parameters to the URL to enable specific debug options. Example: ${r} will show an onscreen console window.`);let i=At===!0?``:` (containing "${At}")`;console.group(`Available URL parameters:`+i);for(let t of Object.keys(e).sort())typeof At==`string`&&!t.toLowerCase().includes(At.toLowerCase())||(console.groupCollapsed(t),console.log(`Reload with this flag enabled:`),console.log(e[t]),console.groupEnd());console.groupEnd()}},100);function Mt(){return new URLSearchParams(globalThis.location?.search)}function A(e){At&&!jt.includes(e)&&jt.push(e);let t=Mt();if(t.has(e)){let n=t.get(e);if(n){let e=Number(n);return isNaN(e)?n:e}else return!0}return!1}At=A(`help`);function Nt(e,t){let n=Mt();n.has(e)?n.set(e,t):n.append(e,t),document.location.search=n.toString()}function Pt(e,t,n=!0){let r=Mt();r.has(e)?t===null?r.delete(e):r.set(e,t):t!==null&&r.append(e,t),n?It(e,r):Lt(e,r)}function Ft(e,t,n){e.has(t)?e.set(t,n.toString()):e.append(t,n.toString())}function It(e,t,n){window.history.pushState(n,e,`?`+t.toString())}function Lt(e,t,n){window.history.replaceState(n,e,`?`+t.toString())}function Rt(e){for(var t=``,n=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789`,r=n.length,i=0;i{setTimeout(t,e)})}function qt(e,t){if(e<=0)return Promise.resolve();if(t||=k.Current,!t)return Promise.reject(`No context`);let n=t.time.frameCount+e;return new Promise((e,r)=>{if(!t)return r(`No context`);let i=()=>{t.time.frameCount>=n&&(t.pre_update_callbacks.splice(t.pre_update_callbacks.indexOf(i),1),e())};t.pre_update_callbacks.push(i)})}var Jt=A(`debugresolveurl`),Yt=`rel:`;function Xt(e,t){return Zt(e,t)}function Zt(e,t){if(t===void 0)return Jt&&console.warn(`getPath: uri is undefined, returning uri`,t),t;if(t.startsWith(`./`))return t;if(t.startsWith(`http`))return Jt&&console.warn(`getPath: uri is absolute, returning uri`,t),t;if(e===void 0)return Jt&&console.warn(`getPath: source is undefined, returning uri`,t),t;t.startsWith(`rel:`)&&(t=t.substring(4));let n=e.lastIndexOf(`/`);if(n>=0){let r=e.substring(0,n+1);for(;r.endsWith(`/`)&&t.startsWith(`/`);)t=t.substring(1);let i=r+t;return Jt&&console.log(`source:`,e,`changed uri from`,t,` to `,i,` basePath: `+r),i}return t}function Qt(e){if(e)return e=e.trim(),e=e.split(`?`)[0]?.split(`#`)[0],e}var $t=class{subscribeWrite(e){this.writeCallbacks.push(e)}unsubscribeWrite(e){let t=this.writeCallbacks.indexOf(e);t!==-1&&this.writeCallbacks.splice(t,1)}writeCallbacks=[];constructor(e,t){this._object=e,this._prop=t,this._wrapperProp=Symbol(`$`+t),this.apply()}_applied=!1;_object;_prop;_wrapperProp;apply(){if(this._applied||!this._object)return;let e=this._object,t=this._prop;if(e[t]===void 0)return;this._applied=!0,e[this._wrapperProp]!==void 0&&console.warn(`Watcher is being applied to an object that already has a wrapper property. This is not (yet) supported`);let n=e[t];e[this._wrapperProp]=n,Object.defineProperty(e,t,{get:()=>e[this._wrapperProp],set:t=>{e[this._wrapperProp]=t;for(let e of this.writeCallbacks)e(t,this._prop)}})}revoke(){if(!this._applied||!this._object)return;this._applied=!1;let e=this._object,t=this._prop;Reflect.deleteProperty(e,t),e[t]=e[this._wrapperProp],Reflect.deleteProperty(e,this._wrapperProp)}dispose(){this.revoke(),this.writeCallbacks.length=0,this._object=null}},en=class e{_watches=[];constructor(t,n){if(Array.isArray(n))for(let r of n)this._watches.push(new e(t,r));else this._watches.push(new $t(t,n))}subscribeWrite(e){for(let t of this._watches)t.subscribeWrite(e)}unsubscribeWrite(e){for(let t of this._watches)t.unsubscribeWrite(e)}apply(){for(let e of this._watches)e.apply()}revoke(){for(let e of this._watches)e.revoke()}dispose(){for(let e of this._watches)e.dispose();this._watches.length=0}},tn=Symbol(`needle:watches`);function nn(e,t){if(!e[tn])if(e instanceof w)e[tn]=new en(e,[`x`,`y`]);else if(e instanceof o)e[tn]=new en(e,[`x`,`y`,`z`]);else if(e instanceof Te||e instanceof E)e[tn]=new en(e,[`x`,`y`,`z`,`w`]);else return!1;return e[tn].subscribeWrite(t),!0}function rn(e,t){if(!e)return;let n=e[tn];n&&n.unsubscribeWrite(t)}var j;(function(e){let t;function n(){if(t!==void 0)return t;let e=window.navigator.userAgent,n=/Windows|MacOS|Mac OS/.test(e),r=/Windows NT/.test(e)&&/Edg/.test(e)&&!/Win64/.test(e);return t=n&&!r&&!y()}e.isDesktop=n;let r;function i(){return r===void 0?r=window.orientation!==void 0||navigator.userAgent.indexOf(`IEMobile`)!==-1?!0:/iPhone|iPad|iPod|Android|IEMobile/i.test(navigator.userAgent):r}e.isMobileDevice=i;function a(){return s()}e.isIPad=a;let o;function s(){if(o!==void 0)return o;let e=navigator.userAgent.toLowerCase();return o=/iPad/.test(navigator.userAgent)||e.includes(`macintosh`)&&`ontouchend`in document}e.isiPad=s;let c;function l(){return c===void 0?c=/Android/.test(navigator.userAgent):c}e.isAndroidDevice=l;let u;function d(){return u===void 0?u=/WebXRViewer\//i.test(navigator.userAgent):u}e.isMozillaXR=d;let f;function p(){return f===void 0?f=/NeedleAppClip\//i.test(navigator.userAgent):f}e.isNeedleAppClip=p;let m;function h(){if(m!==void 0)return m;if(y()||s())return m=!1;let e=navigator.userAgent.toLowerCase();return m=navigator.userAgentData?navigator.userAgentData.platform===`macOS`:e.includes(`mac os x`)||e.includes(`macintosh`)}e.isMacOS=h;let g;function _(){return g===void 0?g=s()&&`xr`in navigator&&ae():g}e.isVisionOS=_;let v,ee=[`iPad Simulator`,`iPhone Simulator`,`iPod Simulator`,`iPad`,`iPhone`,`iPod`];function y(){return v===void 0?v=ee.includes(navigator.platform)||navigator.userAgent.includes(`Mac`)&&`ontouchend`in document:v}e.isiOS=y;let b;function te(){return b===void 0&&(b=/^((?!chrome|android).)*safari/i.test(navigator.userAgent)),b}e.isSafari=te;let ne;function re(){return ne===void 0?ne=navigator.userAgent.includes(`OculusBrowser`):ne}e.isQuest=re;let ie;function ae(){return ie===void 0&&(ie=document.createElement(`a`).relList.supports(`ar`)),ie}e.supportsQuickLookAR=ae;async function oe(){try{return(await navigator.permissions.query({name:`microphone`})).state!==`denied`}catch(e){return console.error("Error querying `microphone` permissions.",e),!1}}e.microphonePermissionsGranted=oe;let se;function ce(){if(se!==void 0)return se;let e=navigator.userAgent.match(/iPhone OS (\d+_\d+)/);if(e&&(se=e[1].replace(`_`,`.`)),!se){let e=navigator.userAgent.match(/(?:\(Macintosh;|iPhone;|iPad;).*Version\/(\d+\.\d+)/);e&&(se=e[1])}return se||=null,se}e.getiOSVersion=ce;let le;function ue(){if(le!==void 0)return le;let e=navigator.userAgent.match(/(?:CriOS|Chrome)\/(\d+\.\d+\.\d+\.\d+)/);return le=e?e[1].replace(`_`,`.`):null,le}e.getChromeVersion=ue;let de;function x(){if(de!==void 0)return de;let e=navigator.userAgent.match(/Version\/(\d+\.\d+)/);return de=e&&te()?e[1]:null,de}e.getSafariVersion=x})(j||={});function an(){return j.isDesktop()}function on(){return j.isMobileDevice()}function sn(){return j.isiPad()}function cn(){return j.isiPad()}function ln(){return j.isAndroidDevice()}function un(){return j.isMozillaXR()}function dn(){return j.isMacOS()}function fn(){return j.isiOS()}function pn(){return j.isSafari()}function mn(){return j.isQuest()}async function hn(){return j.microphonePermissionsGranted()}var gn=new WeakMap;function _n(e,t,n){if(!gn.get(e)){let t=new MutationObserver(t=>{yn(e,t)});gn.set(e,{observer:t,attributeChangedListeners:new Map}),t.observe(e,{attributes:!0})}let r=gn.get(e).attributeChangedListeners;return r.has(t)||r.set(t,[]),r.get(t).push(n),()=>{vn(e,t,n)}}function vn(e,t,n){if(!gn.get(e))return;let r=gn.get(e).attributeChangedListeners;if(!r.has(t))return;let i=r.get(t),a=i.indexOf(n);a!==-1&&(i.splice(a,1),i.length<=0&&(r.delete(t),gn.get(e)?.observer.disconnect(),gn.delete(e)))}function yn(e,t){let n=gn.get(e).attributeChangedListeners;for(let r of t)if(r.type===`attributes`){let t=r.attributeName,i=e.getAttribute(t);if(n.has(t))for(let e of n.get(t))e(i)}}var bn=class{reason;constructor(e){this.reason=e}};async function xn(e){let t=await Promise.allSettled(e).catch(e=>[new bn(e.message)]),n=!1,r=t.map(e=>`value`in e?e.value:(n=!0,new bn(e.reason)));return{anyFailed:n,results:r}}var Sn=A(`debugdebug`),Cn=!1;(A(`noerrors`)||A(`nooverlaymessages`))&&(Cn=!0);var wn=`needle_engine_global_error_container`,Tn;(function(e){e[e.Log=0]=`Log`,e[e.Warn=1]=`Warn`,e[e.Error=2]=`Error`})(Tn||={});function En(){return Fn}var Dn=[];function On(e){Dn.push(e)}var kn=!1;function An(...e){if(!kn){kn=!0;try{for(let t=0;t0&&(e+=` `),e+=r)}else typeof t==`string`&&(e=t);if(Rn.has(e))return;Rn.add(e)}let a=k.Current,o=a?.domElement??document.querySelector(`needle-engine`);if(a?.isInAR&&(o=a.arOverlayElement),o){if(Array.isArray(t)){let e=``;for(let n=0;n0&&(e+=` `),e+=r)}t=e}!t||t.length<=0||Hn(e,o,t,n)}}var Bn=new Map,Vn=.2;function Hn(e,t,n,r={}){if(n==null)return;let i=Gn(t);if(i.childElementCount>=20){let e=i.lastElementChild;Jn(e)}n.length>400&&(n=n.substring(0,400)+`...`);let a=r.key??n;if(Bn.has(a)){Bn.get(a)?.update(n,r);return}let o=Yn(e,n);i.prepend(o);let s=()=>{Bn.delete(a),Jn(o)},c=setTimeout(s,Math.max(Vn,r.duration??10)*1e3);Bn.set(a,{update:(e,t)=>{e.length>400&&(e=e.substring(0,400)+`...`),o.innerHTML=e,t.duration&&(clearTimeout(c),c=setTimeout(s,Math.max(Vn,t.duration)*1e3))},removeFunction:s})}function Un(){Sn&&console.log(`Clearing messages`);for(let e of Bn.values())e?.removeFunction.call(e);Bn.clear()}var Wn=` @import url('https://fonts.googleapis.com/css2?family=Roboto+Flex:opsz,wght@8..144,100..1000&display=swap'); div[data-needle_engine_debug_overlay] { font-family: 'Roboto Flex', sans-serif; font-weight: 400; font-size: 16px; } div[data-needle_engine_debug_overlay] strong { font-weight: 700; } div[data-needle_engine_debug_overlay] a { color: white; text-decoration: none; border-bottom: 1px solid rgba(255, 255, 255, 0.3); } div[data-needle_engine_debug_overlay] a:hover { text-decoration: none; border: none; } div[data-needle_engine_debug_overlay] .log strong { color: rgba(200,200,200,.9); } div[data-needle_engine_debug_overlay] .warn strong { color: rgba(255,255,230, 1); } div[data-needle_engine_debug_overlay] .error strong { color: rgba(255,100,120, 1); } `;function Gn(e){globalThis[wn]||(globalThis[wn]=new Map);let t=globalThis[wn];if(t.has(e))return t.get(e);{let n=document.createElement(`div`);t.set(e,n),n.setAttribute(`data-needle_engine_debug_overlay`,``),n.classList.add(`debug-container`),n.style.cssText=` position: absolute; top: 0; right: 5px; padding-top: env(safe-area-inset-top, 0px); max-width: 70%; max-height: calc(100% - 105px); z-index: 100000; pointer-events: scroll; display: flex; align-items: end; flex-direction: column; color: white; overflow: auto; word-break: break-word; `,j.isNeedleAppClip()&&(n.style.left=`5px`,n.style.right=`unset`);let r=document.querySelector(`meta[name="viewport"]`);r&&!r.getAttribute(`content`)?.includes(`viewport-fit=`)&&r.setAttribute(`content`,r.getAttribute(`content`)+`,viewport-fit=cover`),e.shadowRoot?e.shadowRoot.appendChild(n):e.appendChild(n);let i=document.createElement(`style`);return i.innerHTML=Wn,n.appendChild(i),n}}var Kn=Symbol(`logtype`),qn=new Map;function Jn(e){e.remove();let t=e[Kn],n=qn.get(t)??[];n.push(e),qn.set(t,n)}function Yn(e,t){if(qn.has(e)){let n=qn.get(e);if(n.length>0){let e=n.pop();return e.innerHTML=t,e}}let n=document.createElement(`div`);switch(n.setAttribute(`data-id`,`__needle_engine_debug_overlay`),n.style.marginRight=`5px`,n.style.padding=`.5em`,n.style.backgroundColor=`rgba(0,0,0,.9)`,n.style.marginTop=`5px`,n.style.marginBottom=`3px`,n.style.borderRadius=`8px`,n.style.pointerEvents=`all`,n.style.userSelect=`text`,n.style.maxWidth=`250px`,n.style.whiteSpace=`pre-wrap`,n.style[`backdrop-filter`]=`blur(10px)`,n.style[`-webkit-backdrop-filter`]=`blur(10px)`,n.style.backgroundColor=`rgba(20,20,20,.8)`,n.style.boxShadow=`inset 0 0 80px rgba(0,0,0,.2), 0 0 5px rgba(0,0,0,.2)`,n.style.border=`1px solid rgba(160,160,160,.2)`,n[Kn]=e,e){case Tn.Log:n.classList.add(`log`),n.style.color=`rgba(200,200,200,.7)`,n.style.backgroundColor=`rgba(40,40,40,.7)`;break;case Tn.Warn:n.classList.add(`warn`),n.style.color=`rgb(255, 255, 150)`,n.style.backgroundColor=`rgba(50,50,20,.8)`;break;case Tn.Error:n.classList.add(`error`),n.style.color=`rgb(255, 50, 50`,n.style.backgroundColor=`rgba(50,20,20,.8)`;break}return n.title=`Open the browser console (F12) for more information`,n.innerHTML=t,n}var Xn=A(`nodevlogs`),Zn,Qn;function M(){if(Xn)return!1;if(Zn!==void 0)return Zn;if(Qn!==void 0)return Qn;let e=wt();return e||=window.location.hostname.endsWith(`.local-credentialless.webcontainer.io`),Qn=e,e}function $n(e){Zn=e}var er=class{random(e,t){return Array.isArray(e)?e.length<=0?null:e[Math.floor(Math.random()*e.length)]:e!==void 0&&t!==void 0?Math.random()*(t-e)+e:Math.random()}randomVector3(e,t=0,n=1){e.x=this.random(t,n),e.y=this.random(t,n),e.z=this.random(t,n)}clamp(e,t,n){return en?n:e}clamp01(e){return this.clamp(e,0,1)}lerp(e,t,n){return n=n<0?0:n,n=n>1?1:n,e+(t-e)*n}inverseLerp(e,t,n){return(n-e)/(t-e)}remap(e,t,n,r,i){return r+(i-r)*(e-t)/(n-t)}moveTowards(e,t,n){return e+=n,(n<0&&e0&&e>t)&&(e=t),e}Rad2Deg=180/Math.PI;Deg2Rad=Math.PI/180;Epsilon=1e-5;toDegrees(e){return e*180/Math.PI}toRadians(e){return e*Math.PI/180}tan(e){return Math.tan(e)}gammaToLinear(e){return e**2.2}linearToGamma(e){return e**(1/2.2)}approximately(e,t,n=2**-52){for(let r of tr){let i=e[r],a=t[r];if(i===void 0||a===void 0)break;if(Math.abs(i-a)>n)return!1}return!0}easeInOutCubic(e){return e<.5?4*e*e*e:1-(-2*e+2)**3/2}},tr=[`x`,`y`,`z`,`w`],N=new er,nr=class{y;s;alpha=0;constructor(e){this.setAlpha(e),this.y=null,this.s=null}setAlpha(e){if(e<=0||e>1)throw Error();this.alpha=e}filter(e,t){t&&this.setAlpha(t);let n;return n=this.y?this.alpha*e+(1-this.alpha)*this.s:e,this.y=e,this.s=n,n}lastValue(){return this.y}reset(e){this.y=e,this.s=e}},rr=class{freq;minCutOff;beta;dCutOff;x;dx;lasttime;constructor(e,t=1,n=0,r=1){if(e<=0||t<=0||r<=0)throw Error();this.freq=e,this.minCutOff=t,this.beta=n,this.dCutOff=r,this.x=new nr(this.alpha(this.minCutOff)),this.dx=new nr(this.alpha(this.dCutOff)),this.lasttime=null}alpha(e){let t=1/this.freq;return 1/(1+1/(2*Math.PI*e)/t)}filter(e,t=null){this.lasttime&&t&&(this.freq=1/(t-this.lasttime)),this.lasttime=t;let n=this.x.lastValue(),r=n?(e-n)*this.freq:0,i=this.dx.filter(r,this.alpha(this.dCutOff)),a=this.minCutOff+this.beta*Math.abs(i);return this.x.filter(e,this.alpha(a))}reset(e){e!=null&&this.x.reset(e),this.x.alpha=this.alpha(this.minCutOff),this.dx.alpha=this.alpha(this.dCutOff),this.lasttime=null}},ir=class{x;y;z;constructor(e,t=1,n=0,r=1){this.x=new rr(e,t,n,r),this.y=new rr(e,t,n,r),this.z=new rr(e,t,n,r)}filter(e,t,n=null){t.x=this.x.filter(e.x,n),t.y=this.y.filter(e.y,n),t.z=this.z.filter(e.z,n)}reset(e){this.x.reset(e?.x),this.y.reset(e?.y),this.z.reset(e?.z)}},ar=`needle:cameraController`;function or(e){return e[ar]}function sr(e,t,n){n?e[ar]=t:e[ar]===t&&(e[ar]=null)}var cr=`needle:autofit`;function lr(e){return e[cr]===void 0?!0:e[cr]!==!1}function ur(e,t){e[cr]=t}var dr=void 0,fr={x:0,y:0,width:0,height:0},pr=A(`debugfocusrect`);function mr(e,t,n,r,i){e instanceof Element&&(pr&&e instanceof HTMLElement&&(e.style.outline=`2px dashed rgba(255, 150, 0, .8)`),e=e.getBoundingClientRect()),dr=i.domElement.getBoundingClientRect();let a=fr;a.x=e.x,a.y=e.y,a.width=e.width,a.height=e.height,a.x-=dr.x,a.y-=dr.y;let o=dr.width,s=dr.height,c=r.view,l=t.zoom,u=c?.offsetX||0,d=c?.offsetY||0,f=dr.width,p=dr.height;f/=l,p/=l,u=f*(l-1)*.5,d=p*(l-1)*.5;let m=a.x+a.width*.5,h=a.y+a.height*.5,g=dr.width*.5,_=dr.height*.5,v=m-g,ee=h-_;u-=v/l,d-=ee/l,t.offsetX!==void 0&&(u+=t.offsetX*(dr.width*.5)),t.offsetY!==void 0&&(d-=t.offsetY*(dr.height*.5));let y=c?.offsetX||u,b=c?.offsetY||d;u=N.lerp(y,u,n),d=N.lerp(b,d,n);let te=c?.width||o,ne=c?.height||s;f=N.lerp(te,f,n),p=N.lerp(ne,p,n),r.setViewOffset(o,s,u,d,f,p),r.updateProjectionMatrix(),t.damping>0&&(t.damping*=1-n,t.damping<.01&&(t.damping=0),t.damping=Math.max(0,t.damping))}function hr(e,t,n){let r=e.length(),i=t.length(),a=N.lerp(r,i,n);return e.lerp(t,n).normalize().multiplyScalar(a)}var gr=new E,_r=new E().setFromAxisAngle(new o(0,1,0),Math.PI);function vr(e,t){e.lookAt(t),e.quaternion.multiply(_r)}function yr(e,t,n=!0,r=!1){if(e===t)return;gr.copy(e.quaternion);let i=Or(t),a=Or(e);if(r){if(Fr(e,Pr(t)),n){let t=a.y,n=a.sub(Kr(e));n.y=t,e.lookAt(n),e.quaternion.multiply(_r)}Number.isNaN(e.quaternion.x)&&e.quaternion.copy(gr);return}n&&(i.y=a.y),e.lookAt(i),Number.isNaN(e.quaternion.x)&&e.quaternion.copy(gr)}function br(e,t,n,r=1){if(n){let i=P(0,0,0),a=t.x/window.innerWidth*2-1,o=-(t.y/window.innerHeight)*2+1;i.set(a,o,0),i.unproject(n);let s=n.worldPosition,c=e.worldPosition.distanceTo(s),l=i.sub(s);l.multiplyScalar(r*3.6*c);let u=n.worldPosition.add(l);return e.lookAt(u),u}return null}var xr=new kt(()=>new o,100);function P(e,t,n){let r=xr.get();return r.set(0,0,0),e instanceof o?r.copy(e):Array.isArray(e)?r.set(e[0],e[1],e[2]):e instanceof DOMPointReadOnly?r.set(e.x,e.y,e.z):typeof e==`number`?(r.x=e,r.y=t===void 0?r.x:t,r.z=n===void 0?r.x:n):typeof e==`object`&&(r.x=e.x,r.y=e.y,r.z=e.z),r}var Sr=new kt(()=>new a,30);function Cr(e){let t=Sr.get();return e?t.copy(e):t.set(0,0,0),t}var wr=new kt(()=>new E,100);function Tr(e,t,n,r){let i=wr.get();return i.identity(),e instanceof E?i.copy(e):e instanceof DOMPointReadOnly?i.set(e.x,e.y,e.z,e.w):typeof e==`number`&&t!==void 0&&n!==void 0&&r!==void 0?i.set(e,t,n,r):typeof e==`object`&&`x`in e&&`y`in e&&`z`in e&&`w`in e&&i.set(e.x,e.y,e.z,e.w),i}var Er=new kt(()=>new o,100),Dr=Symbol(`lastMatrixWorldUpdateKey`);function Or(e,t=null,n=!0){let r=t??Er.get();return e?e.parent?(n&&e.updateWorldMatrix(!0,!1),e.matrixWorldNeedsUpdate&&e[Dr]!==Date.now()&&(e[Dr]=Date.now(),e.updateMatrixWorld()),r.setFromMatrixPosition(e.matrixWorld),r):r.copy(e.position):r.set(0,0,0)}function kr(e,t){if(!e)return e;let n=Er.get();return t!==n&&n.copy(t),e.parent!==null&&e.parent.worldToLocal(n),e.position.set(n.x,n.y,n.z),e}function Ar(e,t,n,r){let i=Er.get();return i.set(t,n,r),kr(e,i),e}var jr=new kt(()=>new E,100),Mr=new E,Nr=new E;function Pr(e,t=null){if(!e)return jr.get().identity();let n=t??jr.get();return e.parent?(e.getWorldQuaternion(n),n):n.copy(e.quaternion)}function Fr(e,t){if(!e)return;t!==Mr&&Mr.copy(t);let n=Mr;(e?.parent)?.getWorldQuaternion(Nr),Nr.invert();let r=Nr.multiply(n);e.quaternion.set(r.x,r.y,r.z,r.w)}function Ir(e,t,n,r,i){Mr.set(t,n,r,i),Fr(e,Mr)}var Lr=new kt(()=>new o,100),Rr=new o;function zr(e,t=null){return t||=Lr.get(),e?e.parent?(e.getWorldScale(t),t):t.copy(e.scale):t.set(0,0,0)}function Br(e,t){if(!e)return;if(!e.parent){e.scale.copy(t);return}let n=Rr;e.parent.getWorldScale(n),e.scale.copy(t),e.scale.divide(n)}var Vr=new o,Hr=new E;function Ur(e){return Pr(e,Hr),Vr.set(0,0,1).applyQuaternion(Hr)}var Wr=new kt(()=>new o,100),Gr=new E;function Kr(e,t){return t||=Wr.get().set(0,0,1),Pr(e,Gr),t.applyQuaternion(Gr)}var qr=new He,Jr=new He,Yr=new o;function Xr(e){let t=jr.get();return e.getWorldQuaternion(t),Jr.setFromQuaternion(t),Jr}function Zr(e,t){Fr(e,jr.get().setFromEuler(t))}function Qr(e){let t=Xr(e),n=Yr;return n.set(t.x,t.y,t.z),n.x=N.toDegrees(n.x),n.y=N.toDegrees(n.y),n.z=N.toDegrees(n.z),n}function $r(e,t){ei(e,t.x,t.y,t.z,!0)}function ei(e,t,n,r,i=!0){i&&(t=N.toRadians(t),n=N.toRadians(n),r=N.toRadians(r)),qr.set(t,n,r),Mr.setFromEuler(qr),Fr(e,Mr)}function ti(e,t=!0){e&&(t?(function e(t){console.groupCollapsed((t.name?t.name:`(no name : `+t.type+`)`)+` %o`,t),t.children.forEach(e),console.groupEnd()})(e):e.traverse(function(e){for(var t=`|___`,n=e;n.parent!==null;)t=` `+t,n=n.parent;console.log(t+e.name+` <`+e.type+`>`)}))}function ni(e){let t=e?.name||``;if(!e)return t;let n=e.parent;for(;n;)t=n.name+`/`+t,n=n.parent;return t}function ri(e){if(e){let t=e;return t.blendMode!==void 0&&t.clampWhenFinished!==void 0&&t.enabled!==void 0&&t.fadeIn!==void 0&&t.getClip!==void 0}return!1}var ii=class e extends Ve{static vertex=` varying vec2 vUv; void main(){ vUv = uv; gl_Position = vec4(position.xy, 0., 1.0); }`;constructor(){super({vertexShader:e.vertex,uniforms:{map:new Ye(null),flipY:new Ye(!0),writeDepth:new Ye(!1),depthTexture:new Ye(null)},fragmentShader:` uniform sampler2D map; uniform bool flipY; uniform bool writeDepth; uniform sampler2D depthTexture; varying vec2 vUv; void main(){ vec2 uv = vUv; if (flipY) uv.y = 1.0 - uv.y; gl_FragColor = texture2D(map, uv); if (writeDepth) { float depth = texture2D(depthTexture, uv).r; gl_FragDepth = depth; // float linearDepth = (depth - 0.99) * 100.0; // Enhance near 1.0 values // gl_FragColor = vec4(linearDepth, linearDepth, linearDepth, 1.0); } }`})}reset(){this.uniforms.map.value=null,this.uniforms.flipY.value=!0,this.uniforms.writeDepth.value=!1,this.uniforms.depthTexture.value=null,this.needsUpdate=!0,this.uniformsNeedUpdate=!0}},ai=class e{static planeGeometry=new Ke(2,2,1,1);static renderer=new h({antialias:!1,alpha:!0});static perspectiveCam=new C;static orthographicCam=new ke;static scene=new ne;static blitMaterial=new ii;static mesh=new x(e.planeGeometry,e.blitMaterial);static copyTexture(e,t){t||=this.blitMaterial,this.blitMaterial.reset();let n=t||this.blitMaterial;n.uniforms.map.value=e,n.needsUpdate=!0,n.uniformsNeedUpdate=!0;let r=n.vertexShader;n.vertexShader=ii.vertex;let i=this.mesh;i.material=n,i.frustumCulled=!1,this.scene.children.length=0,this.scene.add(i),this.renderer.setSize(e.image.width,e.image.height),this.renderer.clear(),this.renderer.render(this.scene,this.perspectiveCam);let a=new be(this.renderer.domElement);return a.name=`Copy`,a.needsUpdate=!0,n.vertexShader=r,a}static blit(e,t,n){let{renderer:r=this.renderer,blitMaterial:i=this.blitMaterial,flipY:o=!1,depthTexture:s=null,depthTest:c=!0,depthWrite:l=!0}=n||{};this.blitMaterial.reset(),i.uniforms.map&&(i.uniforms.map.value=e),i.uniforms.flipY&&(i.uniforms.flipY.value=o),s?(i.uniforms.writeDepth=new Ye(!0),i.uniforms.depthTexture.value=s):(i.uniforms.writeDepth=new Ye(!1),i.uniforms.depthTexture.value=null),i.needsUpdate=!0,i.uniformsNeedUpdate=!0;let u=this.mesh;u.material=i,u.frustumCulled=!1,this.scene.children.length=0,this.scene.add(u);let d=r.getRenderTarget(),f=r.getContext();c?f.enable(f.DEPTH_TEST):f.disable(f.DEPTH_TEST),r.state.buffers.depth.setMask(l),r.setClearColor(new a(0,0,0),0),r.setRenderTarget(t),r.clear(),r.render(this.scene,this.perspectiveCam),r.setRenderTarget(d),f.enable(f.DEPTH_TEST),r.state.buffers.depth.setMask(!0)}static textureToCanvas(e,t=!1){if(!e)return null;(t===!0||e.isCompressedTexture===!0)&&(e=oi(e));let n=e.image;if(ci(n)){let e=document.createElement(`canvas`);e.width=n.width,e.height=n.height;let t=e.getContext(`2d`);return t?(t.drawImage(n,0,0,n.width,n.height,0,0,e.width,e.height),e):(console.error(`Failed getting canvas 2d context`),null)}return null}};function oi(e){return ai.copyTexture(e)}function si(e,t=!1){return ai.textureToCanvas(e,t)}function ci(e){return typeof HTMLImageElement<`u`&&e instanceof HTMLImageElement||typeof HTMLCanvasElement<`u`&&e instanceof HTMLCanvasElement||typeof OffscreenCanvas<`u`&&e instanceof OffscreenCanvas||typeof ImageBitmap<`u`&&e instanceof ImageBitmap}function li(e){let t=e.type;return t===`Mesh`||t===`SkinnedMesh`}function ui(e,t){t?e[`needle:rendercustomshadow`]=!0:e[`needle:rendercustomshadow`]=!1}function di(e){return!!(e&&(e[`needle:rendercustomshadow`]===!0||e[`needle:rendercustomshadow`]==null))}function fi(e,t=void 0,n=void 0,r=void 0){let i=r||new fe;i.makeEmpty();let a=[];function o(e){let r=!0;if(e.visible&&lr(e)!==!1&&!(e.type===`TransformControlsGizmo`||e.type===`TransformControlsPlane`)){if(e instanceof Ge&&(r=!1),e instanceof We&&(r=!1),e instanceof ct&&(r=!1),e.isGizmo===!0&&(r=!1),e.material instanceof je&&(r=!1),li(e)||(r=!1),n&&e.layers.test(n)===!1&&(r=!1),r&&(t&&Array.isArray(t)&&t?.includes(e)||typeof t==`function`&&t(e)===!0))return;if(e.isUI!==!0){if(r){let t=e.children;e.children=a;let n=e.position,r=e.scale;if(Number.isNaN(n.x)||Number.isNaN(n.y)||Number.isNaN(n.z)){console.warn(`Object \"${e.name}\" has NaN values in position or scale.... will ignore it`,n,r);return}e.geometry===null&&(e.geometry=void 0),i.expandByObject(e,!0),e.children=t}for(let t of e.children)o(t)}}}let s=!1;Array.isArray(e)||(e=[e]);for(let t of e)t&&(s=!0,t.updateMatrixWorld(),o(t));return s||console.warn(`No objects to fit camera to...`),i}function pi(e,t,n){let r=fi([e],n?.ignore),i=new o;r.getSize(i);let a=new o;r.getCenter(a);let s=new o;t.getSize(s);let c=new o;t.getCenter(c);let l=new o;l.set(s.x/i.x,s.y/i.y,s.z/i.z);let u=Math.min(l.x,l.y,l.z),d=n?.scale!==!1;if(d&&Br(e,zr(e).multiplyScalar(u)),n?.position!==!1){let n=new o;r.getCenter(n),n.y=r.min.y;let i=new o;t.getCenter(i),i.y=t.min.y;let a=i.clone().sub(n);d&&a.multiplyScalar(u),kr(e,Or(e).add(a))}return{boundsBefore:r,scale:l}}function mi(e,t){let n=fi([e]),r=new o;n.getCenter(r),r.y=n.min.y;let i=t.clone().sub(r);return kr(e,Or(e).add(i)),{offset:i,bounds:n}}function hi(e,t,n,r){if(Array.isArray(t)){let n=!0;for(let r=0;r{M()&&k.Current?.isInXR&&(_i(!0),wi(`error`,...e))});function _i(e){if(e){if(gi)return;gi=!0,xi()}else{if(!gi)return;gi=!1,Si()}}var vi={log:void 0,warn:void 0,error:void 0},yi=class{familyName=`needle-xr`;root=null;context=null;defaultFontSize=.06;constructor(){this.ensureFont()}onEnable(){this.context=k.Current||k.All[0],this.context.pre_render_callbacks.push(this.onBeforeRender)}onDisable(){this.context?.pre_render_callbacks.splice(this.context?.pre_render_callbacks.indexOf(this.onBeforeRender),1),this.root?.removeFromParent()}targetObject=new S;userForwardViewPoint=new o;oneEuroFilter=new ir(90,.8);_lastElementRemoveTime=0;onBeforeRender=()=>{let e=this.context?.mainCamera;if(this.context&&e instanceof C){let t=this.getRoot();Number.isNaN(t.position.x)&&t.position.set(0,0,0),Number.isNaN(t.quaternion.x)&&t.quaternion.set(0,0,0,1),this.context.scene.add(this.targetObject);let n=this.context.xr?.rigScale??1,r=3.5*n,i=e.worldForward;i.y=0,i.normalize().multiplyScalar(r),this.userForwardViewPoint.copy(e.worldPosition).sub(i),this.targetObject.position.distanceTo(this.userForwardViewPoint)>2*n&&(this.targetObject.position.copy(this.userForwardViewPoint),yr(this.targetObject,e,!0,!0),this.targetObject.rotateY(Math.PI)),this.oneEuroFilter.filter(this.targetObject.position,t.position,this.context.time.time);let a=this.context.time.deltaTime;if(t.quaternion.slerp(this.targetObject.quaternion,a*5),t.scale.setScalar(n),this.targetObject.removeFromParent(),this.context.scene.add(t),this.context.time.time-this._lastElementRemoveTime>.1){this._lastElementRemoveTime=this.context.time.time;let e=Date.now();for(let t=0;t2e4){n.removeFromParent(),this._textBuffer.push(n),this._activeTexts.splice(t,1);break}}}}};addLog(e,t){let n=this.getRoot(),r=this.getText(),i=16777215,a=0;switch(e){case`log`:i=16777215,a=0;break;case`warn`:i=16772761,a=4465152;break;case`error`:i=16755370,a=7798784;break}t.length>1e3&&(t=t.substring(0,1e3)+`...`),r.textContent=`[`+new Date().toISOString().split(`T`)[1].split(`.`)[0]+`] `+t,r.visible=!0,r._activatedTime=Date.now(),n.add(r),this._activeTexts.push(r),this.context&&this.context.scene.add(n),r.set({backgroundColor:i,color:a}),D.update()}ensureFont(){let e=D.FontLibrary.getFontFamily(this.familyName);e||(e=D.FontLibrary.addFontFamily(this.familyName),e.addVariant(`normal`,`normal`,`https://cdn.needle.tools/static/fonts/msdf/arial/arial-msdf.json`,`https://cdn.needle.tools/static/fonts/msdf/arial/arial.png`)?.addEventListener(`ready`,()=>{D.update()}))}textOptions={fontSize:this.defaultFontSize,fontFamily:this.familyName,padding:.03,margin:.005,color:0,backgroundColor:16777215,backgroundOpacity:.4,borderRadius:.03,offset:.025};_textBuffer=[];_activeTexts=[];getText(){let e=this.getRoot();if(this._textBuffer.length>0){let e=this._textBuffer.pop();return e.visible=!0,setTimeout(()=>this.disableDepthTestRecursive(e),100),e}if(e.children.length>20&&this._activeTexts.length>0)return this._activeTexts.shift();let t=new D.Text(this.textOptions);return setTimeout(()=>this.disableDepthTestRecursive(t),500),setTimeout(()=>this.disableDepthTestRecursive(t),1500),t}disableDepthTestRecursive(e,t=0){for(let n=0;nn&&t[r]===`0`;)r--;return t.substring(0,r+1)}return e.toString()}else if(Array.isArray(e)){let n=`[`;for(let i=0;i=60&&(o+=` `,o+=i(t),n+=o,o=``)}return n+=o,n+=` }`,n}return e}function i(e){let t=``;for(let n=0;ne.stopAllAction()),this.mixers.length=0}registerAnimationMixer(e){if(!e){console.warn(`AnimationsRegistry.registerAnimationMixer called with null or undefined mixer`);return}this.mixers.includes(e)||this.mixers.push(e)}unregisterAnimationMixer(e){if(!e){console.warn(`AnimationsRegistry.unregisterAnimationMixer called with null or undefined mixer`);return}let t=this.mixers.indexOf(e);t!==-1&&this.mixers.splice(t,1)}},Pi=class{static testIfRootCanAnimate(e,t){let n=e.getRoot();return n&&(n.userData.static||n.matrixAutoUpdate===!1||n.matrixWorldAutoUpdate===!1)?((t===!0||t===void 0&&M())&&console.warn(`AnimationUtils: The root object (${n.name||n.type}) of this AnimationAction has matrixAutoUpdate or matrixWorldAutoUpdate set to false. This may prevent the animation from working correctly. If the object is marked as static, try to change it to dynamic.`,{static:n.userData.static,name:n.userData.name,tag:n.userData.tag,matrixAutoUpdate:n.matrixAutoUpdate,matrixWorldAutoUpdate:n.matrixWorldAutoUpdate}),!1):!0}static tryGetActionsFromMixer(e){return e._actions||null}static tryGetAnimationClipsFromObjectHierarchy(e,t){if(t||=[],e)e.animations&&t.push(...e.animations);else return t;if(e.children)for(let n of e.children)this.tryGetAnimationClipsFromObjectHierarchy(n,t);return t}static autoplayAnimations(e){if(!e||!e.animations)return console.debug(`No animations found in file`),null;let t=`scene`in e?e.scene:e,n=[];for(let i=0;i0)for(let e=0;e=0;e--){let t=r[e];t.prefix===n&&(t.prefix=null),t.postfix===n&&(t.postfix=null),!t.prefix&&!t.postfix&&r.splice(e,1)}}var $i=Symbol(`Needle:Patches:WrappedFunction`);function ea(e,t,n){if(e[$i])return e;let r=function(...r){aa(t,n,this,...r);let i=e.apply(this,r);return oa(t,n,this,i,...r),i};return r[$i]=!0,r}var ta=`Needle:Patches`;function na(){return globalThis[`Needle:Patches`]||(globalThis[ta]=new WeakMap),globalThis[ta]}function ra(e,t){let n=na().get(e);return n?n.get(t):null}function ia(e,t,n,r){let i=na().get(e);i||(i=new Map,na().set(e,i));let a=i.get(t);a||(a=[],i.set(t,a)),a.push({prefix:n,postfix:r})}function aa(e,t,n,...r){if(!n)return;let i=ra(e,t);if(i)for(let e of i)e.prefix?.call(n,...r)}function oa(e,t,n,r,...i){if(!n)return;let a=ra(e,t);if(a)for(let e of a)e.postfix?.call(n,r,...i)}function sa(e,t){if(window.SPECTOR){console.log(window.SPECTOR);let n=new URLSearchParams(window.location.search);if(n.has(`spector`)){let r=Number.parseInt(n.get(`spector`)||`0`)||0;console.log(`Scheduled Spector capture at frame #`+r);let i=new window.SPECTOR.Spector;i.spyCanvases=!0,a();return;function a(){if(r>e.time.frame)return window.requestAnimationFrame(()=>a());let n=i.captureCanvas(t);n&&n instanceof Promise?n.then(()=>i.displayUI()):i.displayUI()}}else M()&&console.debug(`Spector available: Add '?spector=' to the URL to enable it and capture a frame.`)}}function ca(e){let t=e;return!!(t.parser&&t.parser.json)}var la;(function(e){e[e.None=0]=`None`,e[e.DontExport=1]=`DontExport`})(la||={});var ua=Symbol(`component-name`);function da(e){return e&&e.isComponent}var fa=Symbol(`object`),pa=new kt(()=>new o,20),ma=class{_point;_normal;_tangentVelocity;distance;impulse;friction;get point(){return pa.get().set(this._point.x,this._point.y,this._point.z)}get normal(){return pa.get().set(this._normal.x,this._normal.y,this._normal.z)}get tangentVelocity(){return pa.get().set(this._tangentVelocity.x,this._tangentVelocity.y,this._tangentVelocity.z)}constructor(e,t,n,r,i,a){this._point=e,this.distance=t,this._normal=n,this.impulse=r,this.friction=i,this._tangentVelocity=a}},ha=class{contacts;constructor(e,t,n){this.me=e,this._collider=t,this._gameObject=t.gameObject,this.contacts=n}me;_collider;get collider(){return this._collider}_gameObject;get gameObject(){return this._gameObject}get rigidBody(){return this.collider?.attachedRigidbody}},ga=class{object;collider;constructor(e,t){this.object=e,this.collider=t}},_a=class e{context;static _managers=new WeakMap;static get(e){return da(e)?this._managers.get(e.context):this._managers.get(e)}constructor(e){this.context=e,this.root.style.cssText=` position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; clip: rect(0, 0, 0, 0); white-space: nowrap; border: 0; `,this.root.setAttribute(`role`,`region`),this.root.setAttribute(`aria-label`,`3D Needle Engine scene`),this.liveRegion.setAttribute(`aria-live`,`polite`),this.liveRegion.setAttribute(`aria-atomic`,`true`),this.liveRegion.setAttribute(`role`,`status`),this.root.appendChild(this.liveRegion),this.enabled=!0}_enabled;set enabled(t){t!==this._enabled&&(this._enabled=t,t?(e._managers.set(this.context,this),(this.context.domElement.shadowRoot||this.context.domElement).prepend(this.root)):this.root.remove())}clear(){this.root.childNodes.forEach(e=>e.remove()),this.root.appendChild(this.liveRegion)}dispose(){this.root.remove(),e._managers.delete(this.context)}root=document.createElement(`div`);liveRegion=document.createElement(`div`);treeElements=new WeakMap;updateElement(e,t){let n=this.treeElements.get(e);n||(n=document.createElement(`div`),this.treeElements.set(e,n),this.root.appendChild(n),typeof t==`object`&&(t.role&&n.setAttribute(`role`,t.role),t.label&&n.setAttribute(`aria-label`,t.label),t.hidden!==void 0&&n.setAttribute(`aria-hidden`,String(t.hidden)),t.busy!==void 0&&n.setAttribute(`aria-busy`,String(t.busy))))}focus(e){let t=this.treeElements.get(e);t&&t.focus()}unfocus(e){let t=this.treeElements.get(e);t&&t.blur()}hover(e,t){let n=this.treeElements.get(e);this.liveRegion.textContent=t||n?.getAttribute(`aria-label`)||``}removeElement(e){this.treeElements.get(e)?.remove(),this.treeElements.delete(e)}set liveRegionMode(e){this.liveRegion.setAttribute(`aria-live`,e)}},va,ya=null;function ba(){return va}function xa(e){if(e==null){console.warn(`Oh no: someone tried registering a non-existend gltf-loader. When you see this log it might mean that needle-engine is being imported multiple times. Please check your project setup.`);return}ya!==e&&(ya=e,va=new e)}var Sa=n(((e,t)=>{(function(){var e=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/`,n={rotl:function(e,t){return e<>>32-t},rotr:function(e,t){return e<<32-t|e>>>t},endian:function(e){if(e.constructor==Number)return n.rotl(e,8)&16711935|n.rotl(e,24)&4278255360;for(var t=0;t0;e--)t.push(Math.floor(Math.random()*256));return t},bytesToWords:function(e){for(var t=[],n=0,r=0;n>>5]|=e[n]<<24-r%32;return t},wordsToBytes:function(e){for(var t=[],n=0;n>>5]>>>24-n%32&255);return t},bytesToHex:function(e){for(var t=[],n=0;n>>4).toString(16)),t.push((e[n]&15).toString(16));return t.join(``)},hexToBytes:function(e){for(var t=[],n=0;n>>6*(3-a)&63)):n.push(`=`);return n.join(``)},base64ToBytes:function(t){t=t.replace(/[^A-Z0-9+\/]/gi,``);for(var n=[],r=0,i=0;r>>6-i*2);return n}};t.exports=n})()})),Ca=n(((e,t)=>{var n={utf8:{stringToBytes:function(e){return n.bin.stringToBytes(unescape(encodeURIComponent(e)))},bytesToString:function(e){return decodeURIComponent(escape(n.bin.bytesToString(e)))}},bin:{stringToBytes:function(e){for(var t=[],n=0;n{t.exports=function(e){return e!=null&&(n(e)||r(e)||!!e._isBuffer)};function n(e){return!!e.constructor&&typeof e.constructor.isBuffer==`function`&&e.constructor.isBuffer(e)}function r(e){return typeof e.readFloatLE==`function`&&typeof e.slice==`function`&&n(e.slice(0,0))}})),Ta=t(n(((e,t)=>{(function(){var e=Sa(),n=Ca().utf8,r=wa(),i=Ca().bin,a=function(t,o){t.constructor==String?t=o&&o.encoding===`binary`?i.stringToBytes(t):n.stringToBytes(t):r(t)?t=Array.prototype.slice.call(t,0):!Array.isArray(t)&&t.constructor!==Uint8Array&&(t=t.toString());for(var s=e.bytesToWords(t),c=t.length*8,l=1732584193,u=-271733879,d=-1732584194,f=271733878,p=0;p>>24)&16711935|(s[p]<<24|s[p]>>>8)&4278255360;s[c>>>5]|=128<>>9<<4)+14]=c;for(var m=a._ff,h=a._gg,g=a._hh,_=a._ii,p=0;p>>0,u=u+ee>>>0,d=d+y>>>0,f=f+b>>>0}return e.endian([l,u,d,f])};a._ff=function(e,t,n,r,i,a,o){var s=e+(t&n|~t&r)+(i>>>0)+o;return(s<>>32-a)+t},a._gg=function(e,t,n,r,i,a,o){var s=e+(t&r|n&~r)+(i>>>0)+o;return(s<>>32-a)+t},a._hh=function(e,t,n,r,i,a,o){var s=e+(t^n^r)+(i>>>0)+o;return(s<>>32-a)+t},a._ii=function(e,t,n,r,i,a,o){var s=e+(n^(t|~r))+(i>>>0)+o;return(s<>>32-a)+t},a._blocksize=16,a._digestsize=16,t.exports=function(t,n){if(t==null)throw Error(`Illegal argument `+t);var r=e.wordsToBytes(a(t,n));return n&&n.asBytes?r:n&&n.asString?i.bytesToString(r):e.bytesToHex(r)}})()}))(),1),Ea=new Map,Da=new Map,Oa=0;function ka(e,t,n){if(Ea.has(t)||Ea.set(t,[]),Ea.get(t).push({method:e,options:{once:!1,...n}}),Oa<30){let e=Da.get(t);e&&e?.length>100&&(Oa+=1,console.warn(`You have ${e.length} methods registered for Event ${t}. This might be a performance issue! Consider unregistering the methods when they are not needed anymore! To unregister you can call the function returned by your event hook (e.g.const unregister = onStart(...)) or by using the once option like onStart(()=>{}, { once:true }). See https://engine.needle.tools/docs/scripting.html#special-lifecycle-hooks for more information.`))}}function Aa(e,t){let n=Da.get(t);if(n){for(let t=0;t0&&Fa(e,r,n);let i=Ea.get(t);if(i&&i.length>0){let r=[...i];i.length=0,Fa(e,r,n),r.length>0&&(Da.has(t)||Da.set(t,[]),Da.get(t).push(...r))}}var Na=[],Pa={context:null};function Fa(e,t,n){Na.length=0;for(let e=0;eAa(e,O.ContextCreated)}function Ra(e,t){return ka(e,O.ContextClearing,t),()=>Aa(e,O.ContextClearing)}function za(e,t){return ka(e,O.ContextDestroying,t),()=>Aa(e,O.ContextDestroying)}function Ba(e,t){return ka(e,z.Start,t),()=>Aa(e,z.Start)}function Va(e,t){return ka(e,z.Update,t),()=>Aa(e,z.Update)}function Ha(e,t){return ka(e,z.OnBeforeRender,t),()=>Aa(e,z.OnBeforeRender)}function Ua(e,t){return ka(e,z.OnAfterRender,t),()=>Aa(e,z.OnAfterRender)}var Wa=A(`debuglicense`),Ga=[],Ka=`basic`;Wa&&console.log(`License Type: `+Ka);function qa(){switch(Ka){case`pro`:case`enterprise`:return!0}return!1}function Ja(){switch(Ka){case`indie`:return!0}return!1}function Ya(){switch(Ka){case`edu`:return!0}return!1}function Xa(){return qa()||Ja()||Ya()}function Za(e){if(qa()||Ja()||Ya())return e(!0);Ga.push(e)}function Qa(e){for(let t of Ga)try{t(e)}catch{}}var $a;(function(e){window.addEventListener(`error`,e=>{a(B.Current,`unhandled_error`,e)}),window.addEventListener(`unhandledrejection`,e=>{a(B.Current,`unhandled_promise_rejection`,{message:e.reason?.message,stack:e.reason?.stack,timestamp:Date.now()})}),La((e=>t(e)),{once:!0});function t(e){if(!n(e)){Wa&&console.debug(`Telemetry is disabled via no-telemetry attribute`);return}return o({site_id:`dabb8317376f`,type:`pageview`,pathname:window.location.pathname,hostname:window.location.hostname,page_title:document.title,referrer:document.referrer,user_agent:navigator.userAgent,querystring:window.location.search,language:navigator.language,screenWidth:window.screen.width,screenHeight:window.screen.height,event_name:`page_view`}).then(t=>{if(t instanceof Response&&t.ok&&wt()){let t=(e.domElement?.getAttribute(`src`)||``)+Bi+Vi+Hi+Ui;window.sessionStorage.getItem(`session_key`)!==t&&(window.sessionStorage.setItem(`session_key`,t),i(e,`info`,{src:e.domElement?.getAttribute(`src`)||``,version:Bi,generator:Vi,build_time:Hi,public_key:Ui}))}})}function n(e){let t=e?.domElement;if(t||=document.querySelector(`needle-engine`),!t&&!e)return!1;let n=t?.getAttribute(`no-telemetry`);return(n===``||n===`true`||n===`1`)&&(Ka===`pro`||Ka===`enterprise`)?(Wa&&console.debug(`Telemetry is disabled via no-telemetry attribute`),!1):!0}e.isAllowed=n;let r=`dabb8317376f`;async function i(e,t,i){if(!n(e)){Wa&&console.debug(`Telemetry is disabled`);return}return o({site_id:r,type:`custom_event`,pathname:window.location.pathname,event_name:t,properties:i?JSON.stringify(i):void 0})}e.sendEvent=i;async function a(e,t,i){if(!n(e)){Wa&&console.debug(`Telemetry is disabled`);return}return i instanceof ErrorEvent?i={message:i.message,stack:i.error?.stack,filename:i.filename,lineno:i.lineno,colno:i.colno,timestamp:i.timeStamp||Date.now()}:i instanceof Error&&(i={message:i.message,stack:i.stack,timestamp:Date.now()}),o({site_id:r,type:`error`,event_name:t||`error`,properties:JSON.stringify({error_name:t,message:i.message,stack:i.stack,filename:i.filename,lineno:i.lineno,colno:i.colno,timestamp:i.timestamp})})}e.sendError=a;function o(e){try{return fetch(`https://needle.tools/api/v1/rum/t`,{method:`POST`,body:JSON.stringify(e),headers:{"Content-Type":`application/json`},keepalive:!0,mode:`cors`,priority:`low`}).catch(e=>{Wa&&console.error(`Failed to send telemetry`,e)})}catch(e){Wa&&console.error(e)}return Promise.resolve()}})($a||={}),k.registerCallback(O.ContextRegistered,e=>{ao(e.context),io(e.context),setTimeout(()=>fo(e.context),2e3)});var eo=void 0,to=!1,no=``;async function ro(){if(eo)return eo;if(Ka===`basic`)try{let e=`https://needle.tools/api/v1/needle-engine/check?location=`+encodeURIComponent(window.location.href)+`&version=`+Bi+`&generator=`+encodeURIComponent(Vi),t=await fetch(e,{method:`GET`}).catch(e=>{Wa&&console.error(`License check failed`,e)});t?.status===200?(to=!1,Wa&&console.log(`License check succeeded`),Ka=`pro`,Qa(!0)):t?.status===403?(Qa(!1),to=!0,no=await t.text()):(Qa(!1),Wa&&console.log(`License check failed with status `+t?.status))}catch(e){Qa(!1),Wa&&console.error(`License check failed`,e)}else Wa&&console.log(`Runtime license check is skipped because license is already applied as "`+Ka+`"`)}eo=ro();async function io(e){function t(){let e=document.createElement(`div`);e.className=`needle-forbidden`,e.style.cssText=` position: fixed; top: 0; left: 0; width: 100%; height: 100%; pointer-events: all; zIndex: 2147483647; line-height: 1.5; backdrop-filter: blur(15px); -webkit-backdrop-filter: blur(15px); `;let t=e.style.cssText,n=document.createElement(`div`);e.appendChild(n),n.style.cssText=` position: absolute; left: 0; right: 0; top:0; bottom: 0; padding: 10%; color: white; font-size: 20px; font-family: sans-serif; text-align: center; pointer-events: all; display: flex; justify-content: center; align-items: center; background-color: rgba(0,0,0,.3); text-shadow: 0 0 2px black; `;let r=n.style.cssText,i=no?.length>1?no:`This web application has been paused.
You might be in violation of the Needle Engine terms of use.
Please contact the Needle support if you think this is a mistake.`;return n.innerHTML=i,setInterval(()=>{n.innerHTML!==i&&(n.innerHTML=i),n.parentNode!==e&&e.appendChild(n),e.style.cssText!==t&&(e.style.cssText=t),n.style.cssText!==r&&(n.style.cssText=r)},500),e}let n=t(),r=n.style.cssText;setInterval(()=>{to===!0&&(n.style.cssText!==r&&(n=t()),e.domElement.shadowRoot?n.parentNode!==e.domElement.shadowRoot&&e.domElement.shadowRoot?.appendChild(n):n.parentNode!=document.body&&document.body.appendChild(n))},500)}async function ao(e){try{if(!qa()&&!Ja())return oo(e)}catch(t){return Wa&&console.log(`License check failed`,t),oo(e)}Wa&&oo(e)}async function oo(e){let t=!1;e.domElement.addEventListener(`ready`,()=>t=!0),await eo?.catch(()=>{}),!(qa()||Ja())&&(Xa()===!1&&uo(),t?so(e):e.domElement.addEventListener(`ready`,()=>{so(e)}))}function so(e){let t=` position: relative; display: block; background-size: 20px; background-position: 10px 5px; background-repeat:no-repeat; background-image:url('${co}'); background-max-size: 40px; padding: 10px; padding-left: 30px; `;if(Ka===`edu`)navigator.webdriver?console.log(`This project is supported by Needle for Education – https://needle.tools`):console.log(`%c This project is supported by Needle for Education – https://needle.tools`,t);else return;let n=document.createElement(`div`);n.className=`needle-non-commercial-use`,n.innerHTML=`Made with Needle for Education`,e.domElement.shadowRoot?.appendChild(n);let r=` position: absolute; font-family: system-ui, Avenir, Helvetica, Arial, sans-serif; font-size: 12px; color: rgb(100, 100, 100); /*mix-blend-mode: difference;*/ background-color: transparent; z-index: 10000; cursor: pointer; user-select: none; opacity: 0; bottom: 6px; right: 12px; transform: translateY(0px); transition: all .5s ease-in-out 1s; `;n.style.cssText=r,n.addEventListener(`click`,()=>{window.open(`https://needle.tools`,`_blank`)});let i=n.style.cssText;setTimeout(()=>{r=r.replace(`opacity: 0`,`opacity: 1`),r=r.replace(`transform: translateY(10px)`,`transform: translateY(0)`),n.style.cssText=r,i=n.style.cssText},100);let a=setInterval(()=>{let t=e.domElement.shadowRoot||e.domElement;n.parentNode!==t&&t.appendChild(n),i!=n.style.cssText&&(n.style.cssText=r,i=n.style.cssText)},1e3);Ya()&&setTimeout(()=>{clearInterval(a),n?.remove(),setTimeout(()=>{e.domElement.parentNode&&so(e)},1e3*60*5)},2e4)}var co=`data:image/webp;base64,UklGRrABAABXRUJQVlA4WAoAAAAQAAAAHwAAHwAAQUxQSKEAAAARN6CmbSM4WR7vdARON11EBDq3fLiNbVtVzpMCPlKAEzsx0Y/x+Ovuv4dn0EFE/ydAvz6YggXzgh5sVgXM/zOC/4sii7qgGvB5N7hmuQYwkvazWAu1JPW41FXSHq6pnaQWvqYH18Fc0j1hO/BFTtIeSBlJi5w6qIIO7IOrwhFsB2Yxukif0FTRLpXswHR8MxbslKe9VZsn/Ub5C7YFOpqSTABWUDgg6AAAAFAGAJ0BKiAAIAA+7VyoTqmkpCI3+qgBMB2JbACdMt69DwMIQBLhkTO6XwY00UEDK6cNIDnuNibPf0EgAP7Y1myuiQHLDsF/0h5unrGh6WAbv7aegg2ZMd3uRKfT/3SJztcaujYfTvMXspfCTmYcoO6a+vhC3ss4M8uM58t4siiu59I4aOl59e9Sr6xoxYlHf2v+NnBNpJYeJf8jABQAId/PXuBkLEFkiCucgSGEcfhvajql/j3reCGl0M5/9gQWy7ayNPs+wlvIxFnNfSlfuND4CZOCyxOHhRqOmHN4ULHo3tCSrUNvgAA=`,lo=0;async function uo(e){let t=Date.now();if(t-lo<2e3)return;lo=t;let n=` position: relative; display: block; font-size: 18px; background-size: 20px; background-position: 10px 5px; background-repeat:no-repeat; background-image:url('${co}'); background-max-size: 40px; margin-bottom: 5px; margin-top: .3em; margin-bottom: .5em; padding: .2em; padding-left: 25px; border-radius: .5em; border: 2px solid rgba(160,160,160,.3); `,r=`Needle Engine — No license active, commercial use is not allowed. Visit https://needle.tools/pricing for more information and licensing options! v${Bi}`;B.Current?.xr||navigator.webdriver?console.log(r):console.log(`%c `+r,n)}async function fo(e){if(!window.crossOriginIsolated){if(!$a.isAllowed(e)){Wa&&console.debug(`Telemetry is disabled via no-telemetry attribute`);return}try{{let e=window.location.href.split(`?`)[0],t={license:Ka,url:e,hostname:window.location.hostname,pathname:window.location.pathname,version:Bi,generator:Vi,build_time:Hi,public_key:Ui},n=navigator.sendBeacon?.(`https://needle.tools/api/v1/needle-engine/ping`,JSON.stringify(t));Wa&&console.debug(`Sent beacon: `+n)}}catch(e){Wa&&console.log(`Failed to send non-commercial usage message to analytics backend`,e)}}}var po=typeof Ta==`function`?Ta:Ta.default,mo;(function(e){e.baseUrl=`https://networking.needle.tools`;function t(e){return po(new Uint8Array(e))}e.hashMD5=t;function n(e){let t=po(new Uint8Array(e),{encoding:`binary`,asBytes:!0});return btoa(String.fromCharCode(...t))}e.hashMD5_Base64=n;function r(e){let t=new Uint8Array(e);return crypto.subtle.digest(`SHA-256`,t).then(e=>btoa(String.fromCharCode(...new Uint8Array(e))))}e.hashSha256=r;function i(e){let t=e.filesize/1024/1024;return Xa()?t<50:t<5}e.canUpload=i;async function a(t,r){let i=e.baseUrl;if(!i)return console.error(`Blob storage base url is not set`),null;if(!t.name)return console.error(`Upload: file name is missing`),null;let a=null;a=t instanceof File?await t.arrayBuffer():t.data;let o=a.byteLength,s=o/1024/1024;if(s>50)return r?.silent!==!0&&Ei(`File (${s.toFixed(1)}MB) is too large for uploading (see console for details)`),console.warn(`Your file is too large for uploading (${s.toFixed(1)}MB). Max allowed size is 50MB`),null;if(!Xa()&&s>5)return r?.silent!==!0&&Ei(`File is too large for uploading. Please get a commercial license to upload files larger than 5MB`),console.warn(`Your file is too large for uploading (${s.toFixed(1)}MB). Max size is 5MB for non-commercial users. Please get a commercial license at https://needle.tools/pricing for larger files (up to 50MB)`),null;if(o<1)return console.warn(`Your file is too small for uploading (${s.toFixed(1)}MB). Min size is 1 byte`),null;let c=n(a),l={filename:t.name,"Content-Md5":c,"Content-Type":t.type||`application/octet-stream`,FileSize:o.toString(),"Content-Disposition":`attachment; filename=\"${t.name}\"`,"x-amz-server-side-encryption":`AES256`},u=await fetch(i+`/api/needle/blob`,{method:`POST`,headers:l,signal:r?.abort}).then(e=>e.json()).catch(e=>(console.error(e),null));if(u==null)return console.warn(`Upload failed...`),null;if(`error`in u)return console.error(u.error),null;if(`upload`in u&&u.upload){console.debug(`Uploading file`,u.upload);let e=!1,t=null;for(let i=0;i<3;i++)try{if(e)break;if(r?.abort?.aborted)return console.debug(`Aborted upload`),null;let a=await n(u.upload);a instanceof Error?(t=a,await Kt(1e3*i)):a.ok&&(console.debug(`File uploaded successfully`),e=!0)}catch(e){console.error(e)}if(!e)return console.error(t?.message||`Failed to upload file`),null;function n(e){return r?.onProgress?.call(null,{progress01:0,state:`inprogress`}),fetch(e,{method:`PUT`,headers:l,body:a,signal:r?.abort}).then(e=>(r?.onProgress?.call(null,{progress01:1,state:`finished`}),e)).catch(e=>e)}}if(`download`in u){let e=i+u.download;return console.debug(`File found in blob storage`,e),{key:u.key,success:!0,download_url:e}}return null}e.upload=a;function o(t){return`${e.baseUrl}/api/needle/blob/${t}`}e.getBlobUrlForKey=o;async function s(e,t){let n=new we;n.setResponseType(`arraybuffer`);let r=await n.loadAsync(e,e=>{t&&t.call(null,e)});return r instanceof ArrayBuffer?new Uint8Array(r):(console.error(`Download failed, no arraybuffer returned`),null)}e.download=s})(mo||={});var ho=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;function go(e){return typeof e==`string`&&ho.test(e)}var _o=[];for(let e=0;e<256;++e)_o.push((e+256).toString(16).slice(1));function vo(e,t=0){return _o[e[t+0]]+_o[e[t+1]]+_o[e[t+2]]+_o[e[t+3]]+`-`+_o[e[t+4]]+_o[e[t+5]]+`-`+_o[e[t+6]]+_o[e[t+7]]+`-`+_o[e[t+8]]+_o[e[t+9]]+`-`+_o[e[t+10]]+_o[e[t+11]]+_o[e[t+12]]+_o[e[t+13]]+_o[e[t+14]]+_o[e[t+15]]}function yo(e){if(!go(e))throw TypeError(`Invalid UUID`);let t,n=new Uint8Array(16);return n[0]=(t=parseInt(e.slice(0,8),16))>>>24,n[1]=t>>>16&255,n[2]=t>>>8&255,n[3]=t&255,n[4]=(t=parseInt(e.slice(9,13),16))>>>8,n[5]=t&255,n[6]=(t=parseInt(e.slice(14,18),16))>>>8,n[7]=t&255,n[8]=(t=parseInt(e.slice(19,23),16))>>>8,n[9]=t&255,n[10]=(t=parseInt(e.slice(24,36),16))/1099511627776&255,n[11]=t/4294967296&255,n[12]=t>>>24&255,n[13]=t>>>16&255,n[14]=t>>>8&255,n[15]=t&255,n}function bo(e){e=unescape(encodeURIComponent(e));let t=[];for(let n=0;n>>32-t}function Eo(e){let t=[1518500249,1859775393,2400959708,3395469782],n=[1732584193,4023233417,2562383102,271733878,3285377520];if(typeof e==`string`){let t=unescape(encodeURIComponent(e));e=[];for(let n=0;n>>0;l=c,c=s,s=To(o,30)>>>0,o=i,i=a}n[0]=n[0]+i>>>0,n[1]=n[1]+o>>>0,n[2]=n[2]+s>>>0,n[3]=n[3]+c>>>0,n[4]=n[4]+l>>>0}return[n[0]>>24&255,n[0]>>16&255,n[0]>>8&255,n[0]&255,n[1]>>24&255,n[1]>>16&255,n[1]>>8&255,n[1]&255,n[2]>>24&255,n[2]>>16&255,n[2]>>8&255,n[2]&255,n[3]>>24&255,n[3]>>16&255,n[3]>>8&255,n[3]&255,n[4]>>24&255,n[4]>>16&255,n[4]>>8&255,n[4]&255]}var Do=Co(`v5`,80,Eo),Oo;(function(e){e[e.OnConnection=0]=`OnConnection`,e[e.OnRoomJoin=1]=`OnRoomJoin`,e[e.Queued=2]=`Queued`,e[e.Immediate=3]=`Immediate`})(Oo||={}),k.registerCallback(O.ContextCreated,e=>{let t=e.context;Ho(t),Io(t)});var ko=A(`debugcomponents`),Ao=`eff8ba80-635d-11ec-90d6-0242ac120003`,jo=class e{get seed(){return this._seed}set seed(e){this._seed=e}_originalSeed;_seed;constructor(t){typeof t==`string`&&(t=e.hash(t)),this._originalSeed=t,this._seed=t}reset(){this._seed=this._originalSeed}generateUUID(e){if(typeof e==`string`)return Do(e,Ao);let t=this._seed;return--this._seed,Do(t.toString(),Ao)}initialize(t){typeof t==`string`?this._seed=e.hash(t):this._seed=t}static createFromString(t){return new e(this.hash(t))}static hash(e){let t=0;for(let n=0;n{ko&&console.log(`[Remote] Destroyed`,e.scene,t);let n=jf(t.guid,e.scene);n&&zf(n)})}var Lo=class{filename;hash;size;constructor(e,t,n){this.filename=e,this.hash=t,this.size=n}},Ro=class{guid;originalGuid;seed;visible;hostData;dontSave;parent;position;rotation;scale;preventCreation=void 0;deleteStateOnDisconnect;constructor(e,t){this.originalGuid=e,this.guid=t}};function zo(e,t,n,r){let i=e;if(!i.guid)return console.warn(`Can not instantiate: No guid`,i),null;if(t.context||=B.Current,!t.context)return console.error(`Missing network instantiate options / reference to network connection in sync instantiate`),null;let a=t?{...t}:null,{instance:o,seed:s}=Uo(i,t);if(o){let e=o;if(e.guid){ko&&console.log(`[Local] new instance`,`gameobject:`,o?.guid);let c=new Ro(i.guid,e.guid);c.seed=s,t.deleteOnDisconnect===!0&&(c.deleteStateOnDisconnect=!0),a&&(a.position&&(Array.isArray(a.position)?c.position={x:a.position[0],y:a.position[1],z:a.position[2]}:c.position={x:a.position.x,y:a.position.y,z:a.position.z}),a.rotation&&(a.rotation instanceof He?a.rotation=new E().setFromEuler(a.rotation):a.rotation instanceof Array&&(a.rotation=new E().fromArray(a.rotation)),c.rotation={x:a.rotation.x,y:a.rotation.y,z:a.rotation.z,w:a.rotation.w}),a.scale&&(Array.isArray(a.scale)?c.scale={x:a.scale[0],y:a.scale[1],z:a.scale[2]}:c.scale={x:a.scale.x,y:a.scale.y,z:a.scale.z})),c.position||={x:e.position.x,y:e.position.y,z:e.position.z},c.rotation||={x:e.quaternion.x,y:e.quaternion.y,z:e.quaternion.z,w:e.quaternion.w},c.scale||={x:e.scale.x,y:e.scale.y,z:e.scale.z},c.visible=i.visible,a?.parent&&(typeof a.parent==`string`?c.parent=a.parent:a.parent?.guid?c.parent=a.parent.guid:a.parent instanceof ne?c.parent=`scene`:console.warn(`Unsupported parent type in sync instantiate options: `+a.parent?.name)),c.hostData=n,r===!1&&(c.dontSave=!0),!t?.context?.connection&&M()&&console.debug(`Object will be instantiated but it will not be synced: not connected`,i.guid),t.context.connection.isInRoom&&Vo.push(new WeakRef(e)),t?.context?.connection.send(Mo.NewInstanceCreated,c)}else console.warn(`Missing guid, can not send new instance event`,e)}return o}function Bo(){return Math.random()*9999999}var Vo=[];function Ho(e){let t=e.connection.beginListen(Mo.NewInstanceCreated,async t=>{let n=await Ko(t.originalGuid,e.scene);if(t.preventCreation===!0)return;if(!n){console.warn(`could not find object that was instantiated: `+t.guid);return}let r=new Tf;t.position&&(r.position=new o(t.position.x,t.position.y,t.position.z)),t.rotation&&(r.rotation=new E(t.rotation.x,t.rotation.y,t.rotation.z,t.rotation.w)),t.scale&&(r.scale=new o(t.scale.x,t.scale.y,t.scale.z)),r.parent=t.parent,t.seed&&(r.idProvider=new jo(t.seed)),r.visible=t.visible,r.context=e,ko&&e.alias&&console.log(`[Remote] instantiate in: `+e.alias);let i=Wf(n,r);Vo.push(new WeakRef(i)),i&&(t.parent===`scene`&&e.scene.add(i),ko&&console.log(`[Remote] new instance`,`gameobject:`,i?.guid,n))}),n=e.connection.beginListen(`left-room`,()=>{Vo.length>0&&console.debug(`Left networking room, cleaning up ${Vo.length} instantiated objects`);for(let e of Vo){let t=e.deref();t&&t.destroy()}Vo.length=0});return()=>{e.connection.stopListen(Mo.NewInstanceCreated,t),e.connection.stopListen(`left-room`,n)}}function Uo(e,t){let n=Bo(),r=t??new Tf;return r.idProvider=new jo(n),{seed:n,instance:Wf(e,r)}}var Wo={};function Go(e,t){Wo[e]=t}async function Ko(e,t){let n=Wo[e];if(n!=null){let t=await n(e);if(t)return t}return qo(e,t)}function qo(e,t){if(t===null||!e)return null;if(t.guid===e)return t;if(t.children)for(let n of t.children){let t=qo(e,n);if(t)return t}return null}var Jo=A(`gizmos`),Yo=A(`debugextension`),Xo=A(`debugresolvedependencies`),Zo=[`/extensions/`,`extensions/`],Qo=[{prefix:`/nodes/`,dependencyName:`node`},{prefix:`/meshes/`,dependencyName:`mesh`},{prefix:`/materials/`,dependencyName:`material`},{prefix:`/textures/`,dependencyName:`texture`},{prefix:`/animations/`,dependencyName:`animation`},{prefix:`nodes/`,dependencyName:`node`},{prefix:`meshes/`,dependencyName:`mesh`},{prefix:`materials/`,dependencyName:`material`},{prefix:`textures/`,dependencyName:`texture`},{prefix:`animations/`,dependencyName:`animation`}];async function $o(e,t){Xo&&console.log(e,t);let n=[];ns(Qo,e,t,n);let r=await Promise.all(n);return typeof t==`string`&&r.length===1?r[0]:r}function es(e,t){return!e||!t?!1:e[`needle:identifier`]!=null&&t[`needle:identifier`]!=null?e[`needle:identifier`]===t[`needle:identifier`]:!1}function ts(e,t){e[`needle:identifier`]=t}function ns(e,t,n,r){if(typeof n==`object`&&n)for(let i of Object.keys(n)){let a=n[i];if(typeof a==`string`){let o=rs(t,a);if(o!=null)typeof o.then==`function`?r.push(o.then(e=>n[i]=e)):n[i]=o;else{let o=is(e,t,a);if(o){r.push(o.then(e=>(n[i]=e,e)));continue}}}else if(Array.isArray(a))for(let n=0;na[n]=e)):a[n]=o;continue}for(let o of e){let e=as(o.prefix,i);if(e>=0){Xo&&console.log(o,e,o.dependencyName),r.push(t.getDependency(o.dependencyName,e).then(e=>a[n]=e));break}}typeof i==`object`&&ns(e,t,i,r)}else typeof a==`object`&&ns(e,t,a,r)}else if(typeof n==`string`){let i=is(e,t,n);i&&r.push(i)}}function rs(e,t){if(e&&e.plugins&&typeof t==`string`){for(let n of Zo)if(t.startsWith(n)){let r=t.substring(n.length),i=r.indexOf(`/`);i>=0&&(r=r.substring(0,i));let a=e.plugins[r];if(Yo&&console.log(r,a),typeof a?.resolve==`function`){let i=t.substring(n.length+r.length+1);return a.resolve(e,i)}break}}return null}function is(e,t,n){for(let r of e){let e=as(r.prefix,n);if(e>=0)return Xo&&console.warn(`GET DEPENDENCY`,r,e,r.dependencyName),t.getDependency(r.dependencyName,e)}return null}function as(e,t){if(typeof t==`string`&&t.startsWith(e)){let n=t.substring(e.length),r=Number.parseInt(n);if(r>=0)return r}return-1}var os=`NEEDLE_persistent_assets`;function ss(e){return e?.___persistentAsset===!0}var cs=class{get name(){return os}parser;constructor(e){this.parser=e}async afterRoot(e){if(!this.parser?.json?.extensions)return;let t=this.parser.json.extensions[os];if(!t)return;Yo&&console.log(t);let n=[];for(let e of t?.assets){let t=$o(this.parser,e);t&&n.push(t)}await Promise.all(n)}resolve(e,t){let n=Number.parseInt(t);if(n>=0){Yo&&console.log(t);let r=e.json.extensions[os];if(r){let e=r?.assets[n];if(e&&typeof e==`object`){e.___persistentAsset=!0;let t=e.__type;t&&ji.get(t)}return e}}return null}},ls=A(`debugserializer`),us=new class{register(e,t){if(this.typeMap.has(e)){let n=this.typeMap.get(e);if(n===t)return;ls&&console.warn(`Type: `+e+` is already registered`,t,n)}ls&&console.log(`Register type serializer`,t.name,t,e),this.typeMap.set(e,t)}typeMap=new Map;getSerializer(e){if(e)return this.typeMap.get(e)}getSerializerForConstructor(e,t=0){if(t>20)return;if(!e||!e.constructor){ls&&console.log(`invalid type`);return}let n=e.name,r=this.getSerializer(e);if(r!==void 0)return ls&&console.log(`FOUND SERIALIZER`,r?.name,e.name,e.constructor.name,`for type: `+n,r,e,this.typeMap),r;let i=Object.getPrototypeOf(e);if(i&&i!==e){let e=this.getSerializerForConstructor(i,++t);if(e){let t=i.constructor||i.prototype;ls&&console.log(`FOUND SERIALIZER(in constructor) `+t.constructor.name,t.name,t,e),this.register(t,e)}return e}ls&&console.warn(`No serializer found for `+n,e,e.name,e.constructor.name)}},ds=class{name;constructor(e,t){if(this.name=t,Array.isArray(e))for(let t of e)us.register(t,this);else us.register(e,this)}},fs=class{isDevMode=wt();cache={};registerDefinedKeys(e,t){if(this.isDevMode&&this.cache[e]===void 0){this.cache[e]=Object.keys(t);let n=t;n.$serializedTypes&&Object.keys(n.$serializedTypes)&&this.cache[e].push(...Object.keys(n.$serializedTypes)),ls&&console.log(`registerDefinedKeys for `+e,this.cache[e],t)}}getDefinedKey(e,t){return this.cache[e]===void 0?!1:this.cache[e].includes(t)}},ps=class{root;gltf;gltfId;object;target;nodeId;nodeToObject;objectToNode;context;path;type;serializable;implementationInformation;constructor(e){this.root=e}};function ms(e,t){let n=e.$serializedTypes;if(n===void 0)return null;let r={};for(let i in n){let n=e[i];if(typeof n==`object`&&n){let e=us.getSerializerForConstructor(n);if(e){r[i]=e.onSerialize(n,t);continue}}r[i]=n}function i(t){let n=ji._types;for(let[t,r]of n)if(r===e.constructor)return t;return t.__name||t.constructor.name}return r.name=i(e),typeof e.guid==`string`&&(r.guid=e.guid),r}var hs=[];function gs(e,t){return e?(typeof e.$serializedTypes==`object`&&(t||={},Object.assign(t,e.$serializedTypes)),gs(Object.getPrototypeOf(e),t)):t}function _s(e,t,n){if(!e)return!1;if(n.target=e,e.onBeforeDeserialize!==void 0){let r=e.onBeforeDeserialize(t,n);if(typeof r==`boolean`)return r}let r=gs(e);if(t){if(typeof t.guid==`string`&&(e.guid=t.guid),r)for(let i in r){let a=r[i],o=t[i];if(ls&&console.log(i,o,e,a),e[i]!==void 0&&o===void 0||(n.type=void 0,n.path=i,n.serializable=a,e.onBeforeDeserializeMember!==void 0&&e.onBeforeDeserializeMember(i,o,n)===!0))continue;if(a===null)e[i]=o;else{if(Array.isArray(a))for(let t=0;tPlease rename "`+t+`" to "`+a+`" in `+r),console.warn(`Please use lowercase for field: "`+t+`" in `+r,o,e));continue}if(o!=null){if(typeof o==`object`&&(i===void 0||!i.isObject3D)){if(typeof o.node==`number`||typeof o.guid==`string`){if(o.could_not_resolve)continue;if(!(i!==void 0&&Object.keys(i).length>1)){zn(Tn.Warn,`Missing serialization for object reference!\n\nPlease change to: \n@serializable(Object3D)\n${a}? : Object3D;\n\nin ${r}.ts\nSee documentation`),console.warn(r,a,e[a],e);continue}}else if(!Array.isArray(i)){let e=i.constructor?.name;if(e===`Object`&&!i.constructor[`did_warn:missing_serializable`]){i.constructor[`did_warn:missing_serializable`]=!0;let t=`You might be missing a @serializable(Type) decorator for field "`+a+`" in `+r+`.ts`;console.warn(t+`\n${a}:`,o,e),zn(Tn.Warn,`Dev Warning: Are you missing a type in @serializable? Please check the browser console for details`)}}}if(typeof i==`string`&&typeof o==`string`&&(o.endsWith(`.gltf`)||o.endsWith(`.glb`))){zn(Tn.Warn,`Missing serialization for object reference!\n\nPlease change to: \n@serializable(AssetReference)\n${a}? : AssetReference;\n\nin script ${r}.ts\ndocumentation`),console.warn(r,a,e[a],e);continue}}}}function bs(e,t){for(let n of Object.keys(t)){let r=t[n];if(typeof r==`object`&&r&&r!==void 0){let t=e[n];if(!t){ls&&console.log(n,`is undefined on`,e);continue}for(let e of Object.keys(r))if(t[e]===void 0&&Ss(r[e])&&!Ss(t)){let n=xs(t,e);if(n&&(n?.writable===void 0||n?.writable===!1)&&n.set===void 0){ls&&console.warn(`Property is not writable "`+e+`"`,t,n,r[e],t[e]);continue}t[e]=r[e]}}}}function xs(e,t){for(;e;){let n=Object.getOwnPropertyDescriptor(e,t);if(n)return n;e=Object.getPrototypeOf(e)}}function Ss(e){switch(typeof e){case`number`:case`string`:case`boolean`:return!0}return!1}function Cs(e,t,n,r,i){let a=typeof t==`function`&&t.prototype===void 0,o=t;if(a)try{if(o=t?.call(t,i),a=!1,o==null)return}catch(t){console.error(`Error in callback`,t,e)}if(n.type=o,!a&&i&&(i instanceof T||i instanceof x||i instanceof ie||i instanceof Se))return i;if(r||={serializer:us.getSerializerForConstructor(o)},i&&typeof i==`object`&&ss(i)){if(i.__concreteInstance)return i.__concreteInstance;let t=i;if(!t.$serializedTypes&&o.prototype.$serializedTypes&&(t.$serializedTypes=o.prototype.$serializedTypes),t.$serializedTypes&&_s(t,e,n),i&&o!==void 0)try{let t=null;r.serializer&&(t=r.serializer.onDeserialize(e,n)),t||(t=new o,Yo&&console.log(`Create concrete instance for persistent asset`,i,`instance:`,t),Es(t,i)),i.__concreteInstance=t,i=t}catch(e){console.error(`Error creating instance or creating values on instance`,e,i,o)}return i}if(Array.isArray(e)){let i=[];for(let a=0;a=0&&this._context.pre_update_callbacks.splice(e,1);for(let e in this._assetReferences)this._assetReferences[e]?.unload();this._assetReferences={}}preUpdate=()=>{};findAssetReference(e){return this._assetReferences[e]||null}registerAssetReference(e){return e.url&&(this._assetReferences[e.url]?console.warn(`Asset reference already registered`,e):this._assetReferences[e.url]=e),e}unregisterAssetReference(e){e.url&&delete this._assetReferences[e.url]}},As=Symbol(`assetReference`),js=class e{static getOrCreateFromUrl(t,n){if(!n&&(n=B.Current,!n))throw Error(`Context is required when sourceId is a string. When you call this method from a component you can call it with "getOrCreate(this, url)" where "this" is the component.`);let r=n.addressables,i=r.findAssetReference(t);if(i)return i;let a=new e(t,n.hash);return r.registerAssetReference(a),a}static getOrCreate(t,n,r){if(typeof t==`string`){if(!r&&(r=B.Current,!r))throw Error(`Context is required when sourceId is a string. When you call this method from a component you can call it with "getOrCreate(this, url)" where "this" is the component.`)}else r=t.context,t=t.sourceId;let i=Zt(t,n);Os&&console.log(`GetOrCreate Addressable from`,t,n,`FinalPath=`,i);let a=r.addressables,o=a.findAssetReference(i);if(o)return o;let s=new e(i,r.hash);return a.registerAssetReference(s),s}isAssetReference=!0;get rawAsset(){return this._rawAsset}get asset(){return this._glbRoot??(this._rawAsset?.scene||null)}set asset(e){e?this._rawAsset={animations:e.animations,scene:e,scenes:[e]}:this._rawAsset=null}get uri(){return this._url}get url(){return this._url}get urlName(){return this._urlName}get hasUrl(){return this._url!==void 0&&(this._url.startsWith(`http`)||this._url.startsWith(`blob:`)||this._url.startsWith(`www.`)||this._url.includes(`/`))}_rawAsset=null;_glbRoot;_url;_urlName;_progressListeners=[];_isLoadingRawBinary=!1;_rawBinary;constructor(...e){typeof e[0]==`object`?`url`in e[0]?this._url=e[0].url:(this._url=``,e[0].asset&&(this.asset=e[0].asset)):(this._url=e[0],e[2]instanceof S&&(this.asset=e[2]));let t=this._url.lastIndexOf(`/`);if(t>=0){this._urlName=this._url.substring(t+1);let e=this._urlName.lastIndexOf(`.`);e>=0&&(this._urlName=this._urlName.substring(0,e))}else this._urlName=this._url;Go(this._url,this.onResolvePrefab.bind(this))}async onResolvePrefab(e){return e===this.url&&(this.mustLoad&&await this.loadAssetAsync(),this.asset)?this.asset:null}get mustLoad(){return!this.asset||this.asset.__destroyed===!0||Nf(this.asset)===!0}_loadingPromise=null;isLoaded(){return this._rawBinary||this.asset!==void 0}unload(){this.asset&&(Os&&console.log(`Unload`,this.asset),`scene`in this.asset&&this.asset.scene&&zf(this.asset.scene,!0,!0),zf(this.asset,!0,!0)),this.asset=null,this._rawBinary=void 0,this._glbRoot=null,this._loadingPromise=null,B.Current&&B.Current.addressables.unregisterAssetReference(this)}async preload(){return!this.mustLoad||this._isLoadingRawBinary?null:this._rawBinary===void 0?(this._isLoadingRawBinary=!0,Os&&console.log(`Preload`,this.url),this._rawBinary=(await mo.download(this.url,e=>{this.raiseProgressEvent(e)}))?.buffer??null,this._isLoadingRawBinary=!1,this._rawBinary):this._rawBinary}async loadAssetAsync(e){if(Os&&console.log(`[AssetReference] loadAssetAsync`,this.url),!this.mustLoad)return this.asset?.parent&&console.warn(`[AssetReference] "${this.urlName}" is already loaded and parented to "${this.asset.parent.name||`scene`}". loadAssetAsync() returns the same shared instance — use .instantiate() to create a new copy.`),this.asset;if(e&&this._progressListeners.push(e),this._loadingPromise!==null)return this._loadingPromise.then(e=>this.asset);let t=B.Current;if(this._rawBinary){if(!(this._rawBinary instanceof ArrayBuffer))return console.error(`[AssetReference] Failed loading – Invalid data. Must be of type ArrayBuffer. `+typeof this._rawBinary),null;this._loadingPromise=ba().parseSync(t,this._rawBinary,this.url,null),this.raiseProgressEvent(new ProgressEvent(`progress`,{loaded:this._rawBinary.byteLength,total:this._rawBinary.byteLength}))}else Os&&console.log(`Load async`,this.url),this._loadingPromise=ba().loadSync(t,this.url,this.url,null,e=>{this.raiseProgressEvent(e)});this._loadingPromise.finally(()=>this._loadingPromise=null);let n=await this._loadingPromise;return this._progressListeners.length=0,this._glbRoot=this.tryGetActualGameObjectRoot(n),n?(n[As]=this,this._glbRoot&&(this._glbRoot[As]=this),this.asset&&(this.asset[As]=this),ep(t),n.scene!==void 0&&(this._rawAsset=n),this.asset):null}instantiate(e){return this.onInstantiate(e,!1)}instantiateSynced(e,t=!0){return this.onInstantiate(e,!0,t)}beginListenDownload(e){this._progressListeners.indexOf(e)<0&&this._progressListeners.push(e)}endListenDownload(e){let t=this._progressListeners.indexOf(e);t>=0&&this._progressListeners.splice(t,1)}raiseProgressEvent(e){for(let t of this._progressListeners)t(this,e)}static currentlyInstantiating=new Map;async onInstantiate(t,n=!1,r){let i=B.Current,a=new Tf;if(t instanceof S?a.parent=t:t&&(Object.assign(a,t),a.cloneAssign(t)),a.parent===void 0&&(a.parent=i.scene),this.mustLoad&&await this.loadAssetAsync(),Os&&console.log(`Instantiate`,this.url,`parent:`,t),this.asset){Os&&console.log(`Add to scene`,this.asset);let t=e.currentlyInstantiating.get(this.url);if(t!==void 0&&t>=1e4)return console.error(`Recursive or too many instantiations of `+this.url+` in the same frame (`+t+`)`),null;try{if(t===void 0&&(t=0),t+=1,e.currentlyInstantiating.set(this.url,t),n){a.context=i;let e=this.asset;e.guid=this.url;let t=zo(e,a,void 0,r);if(t)return t}else{let e=Wf(this.asset,a);if(e)return e}}finally{i.post_render_callbacks.push(()=>{t===void 0||t<0?t=0:--t,e.currentlyInstantiating.set(this.url,t)})}}else Os&&console.warn(`Failed to load asset`,this.url);return null}tryGetActualGameObjectRoot(e){if(e&&e.scene){let t=e.scene;if(t.isGroup&&t.children.length===1&&t.children[0].name+`glb`===t.name){let e=t.children[0];return e.animations=t.animations,e}else return t}return null}};new class extends ds{constructor(){super([js],`AssetReferenceSerializer`)}onSerialize(e,t){if(e&&e.uri!==void 0&&typeof e.uri==`string`)return e.uri}onDeserialize(e,t){if(typeof e==`string`)return t.context?t.gltfId?js.getOrCreate(t.gltfId,e,t.context):(console.error(`Missing source id`),null):(console.error(`Missing context`),null);if(e instanceof S){if(!t.context)return console.error(`Missing context`),null;if(!t.gltfId)return console.error(`Missing source id`),null;let n=e,r=t.context,i=n.guid??n.uuid,a=r.addressables.findAssetReference(i);if(a)return a;let o=new js(i,void 0,n);return r.addressables.registerAssetReference(o),o}return null}};var Ms=Promise.resolve(null),Ns=class e{static imageReferences=new Map;static getOrCreate(t){let n=e.imageReferences.get(t);return n||(n=new e(t),e.imageReferences.set(t,n)),n}constructor(e){this.url=e}url;_bitmap;_bitmapObject;dispose(){this._bitmapObject&&this._bitmapObject.close(),this._bitmap=void 0}createHTMLImage(){let e=new Image;return e.src=this.url,e}loader=null;createTexture(){return this.url?(this.loader||=new me,this.loader.setCrossOrigin(`anonymous`),this.loader.loadAsync(this.url).then(e=>(e&&!e.name?.length&&(e.name=this.url.split(`/`).pop()??this.url),e))):(console.error(`Can not load texture without url`),Ms)}getBitmap(){return this._bitmap||=new Promise((e,t)=>{let n=document.createElement(`img`);n.addEventListener(`load`,()=>{this._bitmap=createImageBitmap(n).then(t=>(this._bitmapObject=t,e(t),t))}),n.addEventListener(`error`,t=>{console.error(`Failed to load image:`+this.url,t),e(null)}),n.src=this.url}),this._bitmap}},Ps=class extends ds{constructor(){super([Ns],`ImageReferenceSerializer`)}onSerialize(e,t){return null}onDeserialize(e,t){if(typeof e==`string`){let n=Zt(t.gltfId,e);return Ns.getOrCreate(n)}}};new Ps;var Fs=class e{static cache=new Map;static getOrCreate(t){let n=e.cache.get(t);return n||(n=new e(t),e.cache.set(t,n)),n}async loadRaw(){return this.res||=fetch(this.url),this.res.then(e=>e.blob())}async loadText(){return this.res||=fetch(this.url),this.res.then(e=>e.text())}url;res;constructor(e){this.url=e}},Is=class extends ds{constructor(){super([Fs],`FileReferenceSerializer`)}onSerialize(e,t){return null}onDeserialize(e,t){if(typeof e==`string`){let n=Zt(t.gltfId,e);return Fs.getOrCreate(n)}}};new Is;var Ls;(function(e){e.Visible=`application-visible`,e.Hidden=`application-hidden`,e.MuteChanged=`application-mutechanged`})(Ls||={});var Rs=!1,zs=[];function Bs(){if(Rs)return;M()&&console.debug(`[Needle Engine] User input registered: Media playback is now allowed.`),Rs=!0;let e=[...zs];zs.length=0,e.forEach(e=>e())}document.addEventListener(`mousedown`,Bs),document.addEventListener(`pointerup`,Bs),document.addEventListener(`click`,Bs),document.addEventListener(`dragstart`,Bs),document.addEventListener(`touchend`,Bs),document.addEventListener(`keydown`,Bs),typeof window<`u`&&`userActivation`in navigator&&navigator.userActivation?.isActive&&(M()&&console.debug(`[Needle Engine] User input already active: Media playback is now allowed.`),zs.length=0,Rs=!0);var Vs=class e extends EventTarget{static get userInteractionRegistered(){return Rs}static registerWaitForAllowAudio=e.registerWaitForInteraction;static registerWaitForInteraction(e){if(e!==null){if(Rs){e();return}zs.indexOf(e)===-1&&zs.push(e)}}static unregisterWaitForInteraction(e){let t=zs.indexOf(e);t!==-1&&zs.splice(t,1)}_mute=!1;get muted(){return this._mute}set muted(e){e!==this._mute&&(this._mute=e,this.dispatchEvent(new Event(Ls.MuteChanged)))}context;get hasFocus(){return document.hasFocus()}get isVisible(){return this._isVisible}_isVisible=!0;constructor(e){super(),this.context=e,window.addEventListener(`visibilitychange`,this.onVisiblityChanged.bind(this),!1)}onVisiblityChanged(e){switch(e.target.visibilityState){case`hidden`:this._isVisible=!1,this.dispatchEvent(new Event(Ls.Hidden));break;case`visible`:this._isVisible=!0,this.dispatchEvent(new Event(Ls.Visible));break}}};function*Hs(e,t=null){let n=t?t.time:B.Current.time,r=n.time;for(;n.time-rt=!1),e.catch(()=>t=!1);t;)yield}var Gs;(function(e){e[e.Quad=0]=`Quad`,e[e.Cube=1]=`Cube`,e[e.Sphere=2]=`Sphere`,e[e.Cylinder=3]=`Cylinder`,e[e.RoundedCube=10]=`RoundedCube`})(Gs||={});var Ks=class{static createText(e,t){let n=null,r=t?.font||Ys(t?.familyFamily||null);r instanceof lt?n=this.#e(e,r,t):n??=new ie;let i=t?.color||16777215,a=new x(n,t?.material??new Ce({color:i}));return this.applyDefaultObjectOptions(a,t),r instanceof Promise?r.then(n=>{a.geometry=this.#e(e,n,t),t?.onGeometry&&t.onGeometry(a)}):t?.onGeometry&&t.onGeometry(a),a}static#e(e,t,n){let r=n?.depth||.1;return new gt(e,{font:t,size:1,depth:r,height:r,bevelEnabled:n?.bevel||!1,bevelThickness:.01,bevelOffset:.01,bevelSize:.01})}static createOccluder(e){let t=new re({colorWrite:!1,depthWrite:!0,side:2});return this.createPrimitive(e,{material:t})}static createPrimitive(e,t){let n,r=t?.color||16777215;switch(e){case`Quad`:case Gs.Quad:{let e=new Ke(1,1,1,1),i=t?.material??new Ce({color:r});t?.texture&&`map`in i&&(i.map=t.texture),n=new x(e,i),n.name=`Quad`}break;case`Cube`:case Gs.Cube:{let e=new Xe(1,1,1),i=t?.material??new Ce({color:r});t?.texture&&`map`in i&&(i.map=t.texture),n=new x(e,i),n.name=`Cube`}break;case Gs.RoundedCube:case`RoundedCube`:{let e=qs(1,1,1,.1,2),i=t?.material??new Ce({color:r});t?.texture&&`map`in i&&(i.map=t.texture),n=new x(e,i),n.name=`RoundedCube`}break;case`Sphere`:case Gs.Sphere:{let e=new Ue(.5,16,16),i=t?.material??new Ce({color:r});t?.texture&&`map`in i&&(i.map=t.texture),n=new x(e,i),n.name=`Sphere`}break;case`Cylinder`:case Gs.Cylinder:{let e=new c(.5,.5,1,32),i=t?.material??new Ce({color:r});t?.texture&&`map`in i&&(i.map=t.texture),n=new x(e,i),n.name=`Cylinder`}break;case`ShaderBall`:n=new ve,n.name=`ShaderBall`,Qs(n,t);break}return this.applyDefaultObjectOptions(n,t),n}static createSprite(e){let t=new Ae({color:16777215});e?.texture&&`map`in t&&(t.map=e.texture);let n=new Ie(t);return this.applyDefaultObjectOptions(n,e),n}static applyDefaultObjectOptions(e,t){e.receiveShadow=!0,e.castShadow=!0,t?.name&&(e.name=t.name),t?.position&&(Array.isArray(t.position)?e.position.set(t.position[0],t.position[1],t.position[2]):e.position.set(t.position.x||0,t.position.y||0,t.position.z||0)),t?.rotation&&(Array.isArray(t.rotation)?e.rotation.set(t.rotation[0],t.rotation[1],t.rotation[2]):e.rotation.set(t.rotation.x||0,t.rotation.y||0,t.rotation.z||0)),t?.scale&&(typeof t.scale==`number`?e.scale.set(t.scale,t.scale,t.scale):Array.isArray(t.scale)?e.scale.set(t.scale[0],t.scale[1],t.scale[2]):e.scale.set(t.scale.x||1,t.scale.y||1,t.scale.z||1)),t?.receiveShadow!=null&&(e.receiveShadow=t.receiveShadow),t?.castShadow!=null&&(e.castShadow=t.castShadow),t?.parent&&t.parent.add(e)}};function qs(e,t,n,r,i){let a=new Le,o=1e-5,s=r-o;a.absarc(o,o,o,-Math.PI/2,-Math.PI,!0),a.absarc(o,t-s*2,o,Math.PI,Math.PI/2,!0),a.absarc(e-s*2,t-s*2,o,Math.PI/2,0,!0),a.absarc(e-s*2,o,o,0,-Math.PI/2,!0);let c=new Re(a,{bevelEnabled:!0,bevelSegments:i*2,steps:1,bevelSize:s,bevelThickness:r,curveSegments:i,UVGenerator:{generateTopUV:(n,r)=>{let i=[];for(let n=0;n{let c=[];return c.push(new w(r[i]/e,r[i+1]/t)),c.push(new w(r[a]/e,r[a+1]/t)),c.push(new w(r[o]/e,r[o+1]/t)),c.push(new w(r[s]/e,r[s+1]/t)),c}}});return c.scale(1,1,1-r),c.center(),c.index||c.setIndex(Array.from({length:c.attributes.position.count},(e,t)=>t)),c.computeVertexNormals(),c}var Js=new Map;function Ys(e){let t=``;switch(e){default:case`OpenSans`:t=`https://cdn.needle.tools/static/fonts/facetype/Open Sans_Regular_ascii.json`;break;case`Helvetiker`:t=`https://cdn.needle.tools/static/fonts/facetype/Helvetiker_Regular_ascii.json`;break}if(Js.has(t)){let e=Js.get(t);if(e)return e}let n=new ot,r=new Promise((e,r)=>{n.load(t,n=>{Js.set(t,n),e(n)},void 0,r)});return Js.set(t,r),r}var Xs=!1,Zs=null;function Qs(e,t){if(Zs===null){let e=new at,t=yt(null);e.setDRACOLoader(t.dracoLoader),e.setKTX2Loader(t.ktx2Loader),Xs=!0,Zs=e.loadAsync(`https://cdn.needle.tools/static/models/shaderball.glb`).then(e=>{let t=e.scene;return t.position.y-=.5,t}).catch(e=>(console.warn(`Failed to load shaderball mesh: `+e.message),ec())).finally(()=>{Xs=!1})}if(Xs){let n=ec();n.name=`ShaderBall-Placeholder`;let r=n.children[0];r?.type===`Mesh`&&$s(r,t),e.add(n)}Zs.then(n=>{e.children.forEach(t=>{t.name===`ShaderBall-Placeholder`&&e.remove(t)});let r=n.clone(),i=r.children[0];i?.type===`Mesh`&&(i.geometry.attributes.tangent||i.geometry.computeTangents(),$s(i,t)),e.add(r)})}function $s(e,t){if(t?.color||t?.material||t?.texture){let n=t?.material??e.material?.clone()??new Ce;t.color&&`color`in n&&n.color instanceof a&&n.color.set(t.color),t?.texture&&`map`in n&&(n.map=t.texture),e.material=n}}function ec(){return new ve().add(Ks.createPrimitive(`Sphere`,{material:new re({transparent:!0,opacity:.1})}))}var I=A(`debuginput`),tc;(function(e){e.Mouse=`mouse`,e.Touch=`touch`,e.Controller=`controller`,e.Hand=`hand`})(tc||={});var nc;(function(e){e.PointerDown=`pointerdown`,e.PointerUp=`pointerup`,e.PointerMove=`pointermove`})(nc||={});var rc;(function(e){e.KeyDown=`keydown`,e.KeyUp=`keyup`,e.KeyPressed=`keypress`})(rc||={});var L;(function(e){e.PointerDown=`pointerdown`,e.PointerUp=`pointerup`,e.PointerMove=`pointermove`,e.KeyDown=`keydown`,e.KeyUp=`keyup`,e.KeyPressed=`keypress`})(L||={});var ic=class extends PointerEvent{clientZ;deviceIndex;origin;source;mode;get isSpatial(){return this.mode!=`screen`}get ray(){return this._ray||=new p(this.space.worldPosition.clone(),this.space.worldForward.clone()),this._ray}set ray(e){this._ray=e}get hasRay(){return this._ray!==void 0}_ray;space;isClick=!1;isDoubleClick=!1;get used(){return this._used}_used=!1;use(){this._used=!0}get pointerId(){return this._pointerid}_pointerid;get pointerType(){return this._pointerType}_pointerType;buttonName=void 0;get type(){return this._type}_type;metadata={};intersections=[];constructor(e,t,n){super(e,n),this.clientZ=n.clientZ,this._pointerid=n.pointerId,this._pointerType=n.pointerType,this._type=e,this.deviceIndex=n.deviceIndex,this.origin=n.origin,this.source=t,this.mode=n.mode,this._ray=n.ray,this.space=n.device,this.buttonName=n.buttonName}_immediatePropagationStopped=!1;get immediatePropagationStopped(){return this._immediatePropagationStopped}_propagationStopped=!1;get propagationStopped(){return this._immediatePropagationStopped||this._propagationStopped}stopImmediatePropagation(){this._immediatePropagationStopped=!0,super.stopImmediatePropagation(),this.source?.stopImmediatePropagation()}stopPropagation(){this._propagationStopped=!0,super.stopPropagation(),this.source?.stopPropagation(),I&&console.warn(`Stop propagation...`,this.pointerId,this.pointerType)}},ac=class extends KeyboardEvent{source;constructor(e,t,n){super(e,n),this.source=t}stopImmediatePropagation(){super.stopImmediatePropagation(),this.source?.stopImmediatePropagation()}},oc=class{key;keyType;source;constructor(e){this.key=e.key,this.keyType=e.type,this.source=e}},sc;(function(e){e[e.Early=-100]=`Early`,e[e.Default=0]=`Default`,e[e.Late=100]=`Late`})(sc||={});var cc=class{_eventListeners={};addEventListener(e,t,n){if(this._eventListeners[e]||(this._eventListeners[e]=[]),!t||typeof t!=`function`){console.error(`Invalid call to addEventListener: callback is required and must be a function!`);return}n=n?{...n}:{};let r=0;n?.queue!=null&&(r=n.queue);let i=this._eventListeners[e],a=i.find(e=>e.priority===r);a?a.listeners.push({callback:t,options:n}):(i.push({priority:r,listeners:[{callback:t,options:n}]}),i.sort((e,t)=>e.priority-t.priority))}removeEventListener(e,t,n){if(!this._eventListeners[e]||!t)return;let r=this._eventListeners[e];if(n?.queue!=null){let e=r.find(e=>e.priority===n.queue);if(!e)return;let i=e.listeners.findIndex(e=>e.callback===t);i>=0&&e.listeners.splice(i,1)}else for(let e of r){let n=e.listeners.findIndex(e=>e.callback===t);n>=0&&e.listeners.splice(n,1)}}dispatchEvent(e){let t=!1;if(e instanceof ac){let t=this._eventListeners[e.type];if(t)for(let n of t)for(let t=0;t10&&this._setCursorTypes.shift(),this.updateCursor()}unsetCursor(e){for(let t=this._setCursorTypes.length-1;t>=0;t--)if(this._setCursorTypes[t]===e){this._setCursorTypes.splice(t,1),this.updateCursor();break}}updateCursor(){this._setCursorTypes?.length==0?this.context.domElement.style.cursor=`default`:this.context.domElement.style.cursor=this._setCursorTypes[this._setCursorTypes.length-1]}getIsPointerIdInUse(e){for(let t of this._pointerEventsPressed)if(t.pointerId===e&&t.used)return!0;return!1}getPointerPressedCount(){let e=0;for(let t=0;t=this._pointerPositions.length?null:this._pointerPositions[e]}getPointerPositionLastFrame(e){return e>=this._pointerPositionsLastFrame.length?null:this._pointerPositionsLastFrame[e]}getPointerPositionDelta(e){return e>=this._pointerPositionsDelta.length?null:this._pointerPositionsDelta[e]}getPointerPositionRC(e){return e>=this._pointerPositionsRC.length?null:this._pointerPositionsRC[e]}getPointerDown(e){return e>=this._pointerDown.length?!1:this._pointerDown[e]}getPointerUp(e){return e>=this._pointerUp.length?!1:this._pointerUp[e]}getPointerPressed(e){return e>=this._pointerPressed.length?!1:this._pointerPressed[e]}getPointerClicked(e){return e>=this._pointerClick.length?!1:this._pointerClick[e]}getPointerDoubleClicked(e){return e>=this._pointerDoubleClick.length?!1:this._pointerDoubleClick[e]}getPointerDownTime(e){return e>=this._pointerDownTime.length?-1:this._pointerDownTime[e]}getPointerUpTime(e){return e>=this._pointerUpTime.length?-1:this._pointerUpTime[e]}getPointerLongPress(e){return e>=this._pointerDownTime.length?!1:this.getPointerPressed(e)&&this.context.time.time-this._pointerDownTime[e]>this._longPressTimeThreshold}getIsMouse(e){return e<0||e>=this._pointerTypes.length?!1:this._pointerTypes[e]===tc.Mouse}getIsTouch(e){return e<0||e>=this._pointerTypes.length?!1:this._pointerTypes[e]===tc.Touch}getTouchesPressedCount(){let e=0;for(let t=0;t=this._mouseWheelChanged.length?!1:this._mouseWheelChanged[e]}getMouseWheelDeltaY(e=0){return e>=this._mouseWheelDeltaY.length?0:this._mouseWheelDeltaY[e]}getPointerEvent(e){if(!(e>=this._pointerEvent.length))return this._pointerEvent[e]??void 0}*foreachPointerId(e){for(let t=0;t=0&&n.splice(r,1)}getFirstPressedButtonForPointer(e){let t=this._pressedStack.get(e);if(t)return t[0]}getLatestPressedButtonForPointer(e){let t=this._pressedStack.get(e);if(t)return t[t.length-1]}getKeyDown(e){if(e!==void 0)return this.isKeyDown(e);for(let e in this.keysPressed){let t=this.keysPressed[e];if(t.startFrame===this.context.time.frameCount)return t.key}return null}getKeyPressed(e){if(e!==void 0)return this.isKeyPressed(e);for(let e in this.keysPressed){let t=this.keysPressed[e];if(t.pressed)return t.key}return null}getKeyUp(e){if(e!==void 0)return this.isKeyUp(e);for(let e in this.keysPressed){let t=this.keysPressed[e];return t.pressed===!1&&t.frame===this.context.time.frameCount}return null}isKeyDown(e){if(!this.context.application.isVisible||!this.context.application.hasFocus)return!1;let t=this.getCodeForCommonKeyName(e);if(t!==null){for(let e of t)if(this.isKeyDown(e))return!0;return!1}let n=this.keysPressed[e];return n?n.startFrame===this.context.time.frameCount&&n.pressed:!1}isKeyUp(e){if(!this.context.application.isVisible||!this.context.application.hasFocus)return!1;let t=this.getCodeForCommonKeyName(e);if(t!==null){for(let e of t)if(this.isKeyUp(e))return!0;return!1}let n=this.keysPressed[e];return n?n.frame===this.context.time.frameCount&&n.pressed===!1:!1}isKeyPressed(e){if(!this.context.application.isVisible||!this.context.application.hasFocus)return!1;let t=this.getCodeForCommonKeyName(e);if(t!==null){for(let e of t)if(this.isKeyPressed(e))return!0;return!1}let n=this.keysPressed[e];return n&&n.pressed||!1}getCodeForCommonKeyName(e){if(e.length===1){if(e>=`0`&&e<=`9`)return[`Digit`+e];if(e>=`a`&&e<=`z`)return[`Key`+e.toUpperCase()];if(e==` `)return[`Space`]}switch(e){case`shift`:case`Shift`:return[`ShiftLeft`,`ShiftRight`];case`control`:case`Control`:return[`ControlLeft`,`ControlRight`];case`alt`:case`Alt`:return[`AltLeft`,`AltRight`]}return null}createInputEvent(e){switch(e.type){case L.PointerDown:I&&Ti(`Create Pointer down`),this.onDownButton(e.deviceIndex,e.button),this.onDown(e);break;case L.PointerMove:I&&Ti(`Create Pointer move`),this.onMove(e);break;case L.PointerUp:I&&Ti(`Create Pointer up`),this.onUp(e),this.onReleaseButton(e.deviceIndex,e.button);break}}convertScreenspaceToRaycastSpace(e){return e.x=(e.x-this.context.domX)/this.context.domWidth*2-1,e.y=-((e.y-this.context.domY)/this.context.domHeight)*2+1,e}constructor(e){this.context=e,this.context.post_render_callbacks.push(this.onEndOfFrame)}_htmlEventSource;bindEvents(){this.unbindEvents(),this._htmlEventSource=this.context.renderer.domElement,window.addEventListener(`contextmenu`,this.onContextMenu),this._htmlEventSource.addEventListener(`pointerdown`,this.onPointerDown,{passive:!0}),window.addEventListener(`pointermove`,this.onPointerMove,{passive:!0,capture:!0}),window.addEventListener(`pointerup`,this.onPointerUp,{passive:!0}),window.addEventListener(`pointercancel`,this.onPointerCancel,{passive:!0}),window.addEventListener(`touchstart`,this.onTouchStart,{passive:!0}),window.addEventListener(`touchmove`,this.onTouchMove,{passive:!0}),window.addEventListener(`touchend`,this.onTouchEnd,{passive:!0}),this._htmlEventSource.addEventListener(`wheel`,this.onMouseWheel,{passive:!0}),window.addEventListener(`wheel`,this.onWheelWindow,{passive:!0}),window.addEventListener(`keydown`,this.onKeyDown,!1),window.addEventListener(`keypress`,this.onKeyPressed,!1),window.addEventListener(`keyup`,this.onKeyUp,!1),window.addEventListener(`blur`,this.onLostFocus)}unbindEvents(){for(let e in this._eventListeners)this._eventListeners[e].length=0;window.removeEventListener(`contextmenu`,this.onContextMenu),this._htmlEventSource?.removeEventListener(`pointerdown`,this.onPointerDown),window.removeEventListener(`pointermove`,this.onPointerMove),window.removeEventListener(`pointerup`,this.onPointerUp),window.removeEventListener(`pointercancel`,this.onPointerCancel),window.removeEventListener(`touchstart`,this.onTouchStart),window.removeEventListener(`touchmove`,this.onTouchMove),window.removeEventListener(`touchend`,this.onTouchEnd),this._htmlEventSource?.removeEventListener(`wheel`,this.onMouseWheel,!1),window.removeEventListener(`wheel`,this.onWheelWindow,!1),window.removeEventListener(`keydown`,this.onKeyDown,!1),window.removeEventListener(`keypress`,this.onKeyPressed,!1),window.removeEventListener(`keyup`,this.onKeyUp,!1),window.removeEventListener(`blur`,this.onLostFocus)}dispose(){let e=this.context.post_render_callbacks.indexOf(this.onEndOfFrame);e>=0&&this.context.post_render_callbacks.splice(e,1),this.unbindEvents()}onLostFocus=()=>{for(let e in this.keysPressed)this.keysPressed[e].pressed=!1};_receivedPointerMoveEventsThisFrame=[];onEndOfFrame=()=>{this._receivedPointerMoveEventsThisFrame.length=0;for(let e=0;e{this.canReceiveInput(e)};keysPressed={};onKeyDown=e=>{if(I&&console.log(`key down ${e.code}, ${this.context.application.hasFocus}`,e),!this.context.application.hasFocus)return;let t=this.keysPressed[e.code];if(t&&t.pressed)return;this.keysPressed[e.code]={pressed:!0,frame:this.context.time.frameCount+1,startFrame:this.context.time.frameCount+1,key:e.key,code:e.code};let n=new ac(L.KeyDown,e,e);this.onDispatchEvent(n)};onKeyPressed=e=>{if(!this.context.application.hasFocus)return;let t=this.keysPressed[e.code];if(!t)return;t.pressed=!0,t.frame=this.context.time.frameCount+1;let n=new ac(L.KeyPressed,e,e);this.onDispatchEvent(n)};onKeyUp=e=>{if(!this.context.application.hasFocus)return;let t=this.keysPressed[e.code];if(!t)return;t.pressed=!1,t.frame=this.context.time.frameCount+1;let n=new ac(L.KeyUp,e,e);this.onDispatchEvent(n)};onWheelWindow=e=>{document.pointerLockElement&&this.onMouseWheel(e)};onMouseWheel=e=>{if(this.canReceiveInput(e)===!1)return;this._mouseWheelDeltaY.length<=0&&this._mouseWheelDeltaY.push(0),this._mouseWheelChanged.length<=0&&this._mouseWheelChanged.push(!1),this._mouseWheelChanged[0]=!0;let t=this._mouseWheelDeltaY[0];this._mouseWheelDeltaY[0]=t+e.deltaY};onPointerDown=e=>{if(this.context.isInAR||this.canReceiveInput(e)===!1)return;e.target instanceof HTMLElement&&e.target.setPointerCapture(e.pointerId);let t=this.getPointerId(e);I&&Ti(`pointer down #${t}, identifier:${e.pointerId}`);let n=this.getAndUpdateSpatialObjectForScreenPosition(t,e.clientX,e.clientY),r=new ic(L.PointerDown,e,{origin:this,mode:`screen`,deviceIndex:0,pointerId:t,button:e.button,clientX:e.clientX,clientY:e.clientY,pointerType:e.pointerType,buttonName:this.getButtonName(e),device:n,pressure:e.pressure});this.onDown(r)};onPointerMove=e=>{if(this.context.isInAR||this._receivedPointerMoveEventsThisFrame.includes(e.pointerId))return;this._receivedPointerMoveEventsThisFrame.push(e.pointerId);let t=e.button;e.pointerType===`mouse`&&(t=this.getFirstPressedButtonForPointer(0)??0);let n=this.getPointerId(e,t);t===-1&&(t=n);let r=this.getAndUpdateSpatialObjectForScreenPosition(n,e.clientX,e.clientY),i=new ic(L.PointerMove,e,{origin:this,mode:`screen`,deviceIndex:0,pointerId:n,button:t,clientX:e.clientX,clientY:e.clientY,pointerType:e.pointerType,buttonName:this.getButtonName(e),device:r,pressure:e.pressure});this.onMove(i)};onPointerCancel=e=>{this.context.isInAR||(I&&console.log(`Pointer cancel`,e),this.onPointerUp(e))};onPointerUp=e=>{if(this.context.isInAR)return;e.target instanceof HTMLElement&&e.target.releasePointerCapture(e.pointerId);let t=this.getPointerId(e),n=new ic(L.PointerUp,e,{origin:this,mode:`screen`,deviceIndex:0,pointerId:t,button:e.button,clientX:e.clientX,clientY:e.clientY,pointerType:e.pointerType,buttonName:this.getButtonName(e),device:this.getAndUpdateSpatialObjectForScreenPosition(t,e.clientX,e.clientY),pressure:e.pressure});this.onUp(n),this._pointerIds[t]=-1,I&&console.log(`ID=`+t,`PointerId=`+e.pointerId,`ALL:`,[...this._pointerIds])};getPointerId(e,t){return e.pointerType===`mouse`?0+(t??e.button):this.getPointerIndex(e.pointerId)}getButtonName(e){let t=e.button;if(e.pointerType===`mouse`)switch(t){case 0:return`left`;case 1:return`middle`;case 2:return`right`}return`unknown`}onTouchStart=e=>{if(this.context.isInAR)for(let t=0;t{if(this.context.isInAR)for(let t=0;t{if(this.context.isInAR)for(let t=0;t=t.x&&n<=t.right&&r>=t.y&&r<=t.bottom;return I&&!i&&console.log(`Not in rect`,t,n,r),i}onDown(e){let t=e.pointerId;if(this.getPointerPressed(t)){I&&console.warn(`Received pointerDown event for pointerId that is already pressed: ${t}/${e.button}`,I?e:``);return}if(I&&console.log(e.pointerType,`DOWN`,t,e.button),this.isInRect(e)){for(this.setPointerState(t,this._pointerPressed,!0),this.setPointerState(t,this._pointerDown,!0),this.setPointerStateT(t,this._pointerEvent,e.source);t>=this._pointerTypes.length;)this._pointerTypes.push(e.pointerType);for(this._pointerTypes[t]=e.pointerType;t>=this._pointerPositionDown.length;)this._pointerPositionDown.push(new o);for(this._pointerPositionDown[t].set(e.clientX,e.clientY,e.clientZ??0);t>=this._pointerPositions.length;)this._pointerPositions.push(new w);this._pointerPositions[t].set(e.clientX,e.clientY),t>=this._pointerDownTime.length&&this._pointerDownTime.push(0),this._pointerDownTime[t]=this.context.time.realtimeSinceStartup,this.updatePointerPosition(e),this._pointerEventsPressed.push(e),this.onDispatchEvent(e)}}onMove(e){let t=e.pointerId,n=this.getPointerPressed(t);n===!1&&!this.isInRect(e)||e.pointerType===tc.Touch&&!n||(this.updatePointerPosition(e),this.setPointerStateT(t,this._pointerEvent,e.source),this.onDispatchEvent(e))}onUp(e){let t=e.pointerId;if(!this.getPointerPressed(t)){I&&console.warn(`Received pointerUp for pointerId that is not pressed: ${t}/${e.button}`,I?e:``);return}I&&console.log(e.pointerType,`UP`,t),this.setPointerState(t,this._pointerPressed,!1),this.setPointerStateT(t,this._pointerEvent,e.source),this.setPointerState(t,this._pointerUp,!0),this.updatePointerPosition(e);for(let e=this._pointerEventsPressed.length-1;e>=0;e--)if(this._pointerEventsPressed[e].pointerId===t){this._pointerEventsPressed.splice(e,1);break}if(!this._pointerPositionDown[t]){I&&Ei(`[Received pointer up event without matching down event for button: `+t),console.warn(`Received pointer up event without matching down event for button: `+t);return}let n=this._pointerUpTime[t],r=this._pointerDownTime[t],i=this.context.time.realtimeSinceStartup,a=i-r;if(t>=this._pointerUpTime.length&&this._pointerUpTime.push(-99),this._pointerUpTime[t]=i,a<1){let r=e.clientX-this._pointerPositionDown[t].x,a=e.clientY-this._pointerPositionDown[t].y,o=0;if(e.isSpatial&&e.clientZ!=null&&(o=e.clientZ-this._pointerPositionDown[t].z,r*=200,a*=200,o*=200),Math.abs(r)<5&&Math.abs(a)<5&&Math.abs(o)<5){this.setPointerState(t,this._pointerClick,!0),e.isClick=!0;let s=i-n;I&&console.log(`CLICK`,t,r,a,o,s),s0&&(this.setPointerState(t,this._pointerDoubleClick,!0),e.isDoubleClick=!0)}}this.onDispatchEvent(e)}updatePointerPosition(e){let t=e.pointerId;for(;t>=this._pointerPositions.length;)this._pointerPositions.push(new w);for(;t>=this._pointerPositionsLastFrame.length;)this._pointerPositionsLastFrame.push(new w);for(;t>=this._pointerPositionsDelta.length;)this._pointerPositionsDelta.push(new w);let n=this._pointerPositionsLastFrame[t];n.copy(this._pointerPositions[t]);let r=this._pointerPositionsDelta[t],i=e.clientX-n.x,a=e.clientY-n.y;if(e.source instanceof MouseEvent||e.source instanceof TouchEvent){let t=e.source;i===0&&t.movementX!==0&&(i=t.movementX||0),a===0&&t.movementY!==0&&(a=t.movementY||0)}r.x+=i,r.y+=a,this._pointerPositions[t].x=e.clientX,this._pointerPositions[t].y=e.clientY;let o=e.clientX,s=e.clientY;for(;t>=this._pointerPositionsRC.length;)this._pointerPositionsRC.push(new w);let c=this._pointerPositionsRC[t];c.set(o,s),this.convertScreenspaceToRaycastSpace(c)}getPointerIndex(e){let t=-1;for(let n=0;n(e.postprocess(t),t.name=`PMREM_`+t.name,lc&&console.log(`NEEDLE_pmrem: loaded PMREM texture`,t),t))):(console.warn(`NEEDLE_pmrem: No KTX2Loader available on GLTFLoader — cannot load PMREM texture`),null)}static postprocess(e){return e.mapping=306,e}},dc=`NEEDLE_lightmaps`,fc=A(`debuglightmapsextension`)||A(`debuglightmaps`),pc;(function(e){e[e.Lightmap=0]=`Lightmap`,e[e.Skybox=1]=`Skybox`,e[e.Reflection=2]=`Reflection`})(pc||={});var mc=class{get name(){return dc}parser;registry;source;constructor(e,t,n){this.parser=e,this.registry=t,this.source=n}afterRoot(e){let t=this.parser.json.extensions;if(t){let e=t[dc];if(e){let t=e.textures;return t?.length?(fc&&console.log(e),new Promise(async(e,n)=>{let r=[];for(let e of t)if(e.pointer){fc&&console.log(e);let t=null;if(e.pointer.startsWith(`/textures/`)||e.pointer.startsWith(`textures/`))fc&&console.log(`Load texture from gltf`,e.pointer),t=$o(this.parser,e.pointer).then(t=>this.resolveTexture(e,t));else if(typeof e.pointer==`string`){fc&&console.log(`Load texture from path`,e.pointer);let n=Zt(this.source,e.pointer),r=n.endsWith(`.pmrem.ktx2`),i;i=n.endsWith(`.exr`)?new _t(this.parser.options.manager):n.endsWith(`.hdr`)?new ht(this.parser.options.manager):r?this.parser.options.ktx2Loader:new me(this.parser.options.manager),t=i.loadAsync(n,void 0).then(t=>(r&&t&&uc.postprocess(t),this.resolveTexture(e,t)))}else e.pointer;t&&r.push(t)}let i=await xn(r);i?.anyFailed&&(M()||fc)&&console.error(`[NEEDLE_lightmaps]Error during extension loading:`,i),e()})):null}}return null}resolveTexture(e,t){let n=t;fc&&console.log(`Light Texture loaded:`,n),n?.isTexture&&(this.registry?(n.colorSpace=l,this.registry.registerTexture(this.source,e.type,n,e.index)):console.log(pc[e.type],e.pointer,n))}},hc=!!A(`debuglightmaps`),gc=class{context;map=new Map;clear(){this.map.clear()}constructor(e){this.context=e}registerTexture(e,t,n,r){hc&&console.log(`Registering `,pc[t]+` "`+e+`"`,n),this.map.has(e)||this.map.set(e,new Map);let i=this.map.get(e),a=i?.get(t)??[];a.length0)for(let e=0;e`+(t/r.lastScreenCoverage).toFixed(0)+(n?``:`,`)}let d=o?o[i]?.density:-1,f=`LOD `+n.mesh_lod+` TEX `+n.texture_lod;if(_c==`density`&&(f+=` `+a+` tris `+(d/r.lastScreenCoverage).toFixed(0)+` dens `+(r.lastScreenCoverage*100).toFixed(1)+`% cov `+(r.lastCentrality*100).toFixed(1)+`% centr `+(vc.min.x.toFixed(2)+`-`+vc.max.x.toFixed(2)+`x`+vc.min.y.toFixed(2)+`-`+vc.max.y.toFixed(2))+` scr`),r.lastScreenCoverage>.1){let t=e,n=t.worldForward,r=t.worldPosition,a=P(n).multiplyScalar(c*.7).add(s),o=a.distanceTo(r),u=l[Math.min(l.length-1,Math.max(0,i))]+`88`,d=this.context.domHeight>0?screen.height/this.context.domHeight:1,p=e.isPerspectiveCamera?Math.tan(e.fov*Math.PI/180/2):1;H.DrawLabel(a,f,o*.012*d*p,void 0,16777215,u)}}}}},xc=new Int32Array(2),Sc=new Float32Array(xc.buffer),Cc=new Float64Array(xc.buffer),wc=new Uint16Array(new Uint8Array([1,0]).buffer)[0]===1,Tc=class e{constructor(e,t){this.low=e|0,this.high=t|0}static create(t,n){return t==0&&n==0?e.ZERO:new e(t,n)}toFloat64(){return(this.low>>>0)+this.high*4294967296}equals(e){return this.low==e.low&&this.high==e.high}};Tc.ZERO=new Tc(0,0);var Ec;(function(e){e[e.UTF8_BYTES=1]=`UTF8_BYTES`,e[e.UTF16_STRING=2]=`UTF16_STRING`})(Ec||={});var Dc=class e{constructor(e){this.bytes_=e,this.position_=0}static allocate(t){return new e(new Uint8Array(t))}clear(){this.position_=0}bytes(){return this.bytes_}position(){return this.position_}setPosition(e){this.position_=e}capacity(){return this.bytes_.length}readInt8(e){return this.readUint8(e)<<24>>24}readUint8(e){return this.bytes_[e]}readInt16(e){return this.readUint16(e)<<16>>16}readUint16(e){return this.bytes_[e]|this.bytes_[e+1]<<8}readInt32(e){return this.bytes_[e]|this.bytes_[e+1]<<8|this.bytes_[e+2]<<16|this.bytes_[e+3]<<24}readUint32(e){return this.readInt32(e)>>>0}readInt64(e){return new Tc(this.readInt32(e),this.readInt32(e+4))}readUint64(e){return new Tc(this.readUint32(e),this.readUint32(e+4))}readFloat32(e){return xc[0]=this.readInt32(e),Sc[0]}readFloat64(e){return xc[+!wc]=this.readInt32(e),xc[+!!wc]=this.readInt32(e+4),Cc[0]}writeInt8(e,t){this.bytes_[e]=t}writeUint8(e,t){this.bytes_[e]=t}writeInt16(e,t){this.bytes_[e]=t,this.bytes_[e+1]=t>>8}writeUint16(e,t){this.bytes_[e]=t,this.bytes_[e+1]=t>>8}writeInt32(e,t){this.bytes_[e]=t,this.bytes_[e+1]=t>>8,this.bytes_[e+2]=t>>16,this.bytes_[e+3]=t>>24}writeUint32(e,t){this.bytes_[e]=t,this.bytes_[e+1]=t>>8,this.bytes_[e+2]=t>>16,this.bytes_[e+3]=t>>24}writeInt64(e,t){this.writeInt32(e,t.low),this.writeInt32(e+4,t.high)}writeUint64(e,t){this.writeUint32(e,t.low),this.writeUint32(e+4,t.high)}writeFloat32(e,t){Sc[0]=t,this.writeInt32(e,xc[0])}writeFloat64(e,t){Cc[0]=t,this.writeInt32(e,xc[+!wc]),this.writeInt32(e+4,xc[+!!wc])}getBufferIdentifier(){if(this.bytes_.length>10)+55296,(t&1023)+56320))}return r}__union_with_string(e,t){return typeof e==`string`?this.__string(t):this.__union(e,t)}__indirect(e){return e+this.readInt32(e)}__vector(e){return e+this.readInt32(e)+4}__vector_len(e){return this.readInt32(e+this.readInt32(e))}__has_identifier(e){if(e.length!=4)throw Error(`FlatBuffers: file identifier must be length 4`);for(let t=0;t<4;t++)if(e.charCodeAt(t)!=this.readInt8(this.position()+4+t))return!1;return!0}createLong(e,t){return Tc.create(e,t)}createScalarList(e,t){let n=[];for(let r=0;rthis.minalign&&(this.minalign=t);let r=~(this.bb.capacity()-this.space+n)+1&t-1;for(;this.space=0&&this.vtable[t]==0;t--);let n=t+1;for(;t>=0;t--)this.addInt16(this.vtable[t]==0?0:e-this.vtable[t]);this.addInt16(e-this.object_start);let r=(n+2)*2;this.addInt16(r);let i=0,a=this.space;outer_loop:for(t=0;t=0;t--)this.writeInt8(e.charCodeAt(t))}this.prep(this.minalign,4+r),this.addOffset(e),r&&this.addInt32(this.bb.capacity()-this.space),this.bb.setPosition(this.space)}finishSizePrefixed(e,t){this.finish(e,t,!0)}requiredField(e,t){let n=this.bb.capacity()-e,r=n-this.bb.readInt32(n);if(this.bb.readInt16(r+t)==0)throw Error(`FlatBuffers: field `+t+` must be set`)}startVector(e,t,n){this.notNested(),this.vector_num_elems=t,this.prep(4,e*t),this.prep(n,e*t)}endVector(){return this.writeInt32(this.vector_num_elems),this.offset()}createSharedString(e){if(!e)return 0;if(this.string_maps||=new Map,this.string_maps.has(e))return this.string_maps.get(e);let t=this.createString(e);return this.string_maps.set(e,t),t}createString(e){if(!e)return 0;let t;if(e instanceof Uint8Array)t=e;else{t=[];let n=0;for(;n=56320)r=i;else{let t=e.charCodeAt(n++);r=(i<<10)+t+-56613888}r<128?t.push(r):(r<2048?t.push(r>>6&31|192):(r<65536?t.push(r>>12&15|224):t.push(r>>18&7|240,r>>12&63|128),t.push(r>>6&63|128)),t.push(r&63|128))}}this.addInt8(0),this.startVector(1,t.length,1),this.bb.setPosition(this.space-=t.length);for(let e=0,n=this.space,r=this.bb.bytes();e{t.push(e)})},async load(){if(n.MODULE)return n.MODULE;let r=await e();n.MODULE=r,n.MAYBEMODULE=r;for(let e of t)e(r);return t.length=0,r}};return n}var Pc={MaterialX:Nc(()=>r(()=>import(`./materialx.eMaybKAQ.js`),__vite__mapDeps([0,1,2,3]),import.meta.url)),RAPIER_PHYSICS:Nc(()=>r(()=>import(`./rapier3d.DBFmcAzL.js`).then(e=>e.t),__vite__mapDeps([4,2]),import.meta.url)),POSTPROCESSING:Nc(()=>r(()=>import(`./needle-engine.dep.DFJFZC0m.js`),__vite__mapDeps([5,6,3,2]),import.meta.url)),POSTPROCESSING_AO:Nc(()=>r(()=>import(`./N8AO.C2WXsanG.js`),__vite__mapDeps([7,8,6,3,2,9]),import.meta.url)),PEERJS:Nc(()=>r(()=>import(`./peerjs.UdR1_Ath.js`).then(e=>e.t),__vite__mapDeps([10,2]),import.meta.url))},Fc=void 0;function Ic(){return Fc}function Lc(e){Fc=e}async function Rc(e,t){let n=(await Pc.PEERJS.load()).default;return t||={},t={...Fc,...t},e?new n(e,t):new n(t)}async function zc(){let e=await Pc.PEERJS.load();return e.default===void 0?e:e.default}var Bc;(function(e){e.ConnectionList=`connection-list`})(Bc||={});var Vc=class{get isHost(){return this._host!==void 0}_host;_client;_clientData;constructor(){this.onEnable()}onEnable(){this.trySetupHost(`HOST-5980e65c-8438-453e-8b35-f13c736dcd81`)}async trySetupHost(e){let t=new(await(zc()))(e);t.on(`error`,t=>{console.error(t),this._host=void 0,this.trySetupClient(e)}),t.on(`open`,e=>{this._host=new Uc(t)})}async trySetupClient(e){this._client=new(await(zc())),this._client.on(`error`,e=>{console.error(`Client error`,e)}),this._client.on(`open`,t=>{console.log(`client connected`,t),this._clientData=this._client.connect(e,{metadata:{id:t}}),this._clientData.on(`open`,()=>{console.log(`Connected to host`)}),this._clientData.on(`data`,e=>{console.log(`<<`,e)})})}},Hc=class{_peer;constructor(e){this._peer=e}},Uc=class extends Hc{get isHost(){return!0}_connections=[];constructor(e){super(e),console.log(`I AM THE HOST`),this._peer?.on(`connection`,this.onConnection.bind(this)),this._peer.on(`close`,()=>{this.broadcast(`BYE`)}),setInterval(()=>{this.broadcast(`HELLO`)},2e3)}onConnection(e){console.log(`host connection`,e),e.on(`open`,()=>{this._connections.push(e),this.broadcastConnection(e)})}broadcastConnection(e){let t=this._connections.map(e=>e.metadata?.id).filter(e=>e!==void 0);this.broadcast({type:Bc.ConnectionList,connections:t})}broadcast(e){if(e!=null){console.log(`>>`,e);for(let t in this._peer.connections){let n=this._peer.connections[t];if(n)if(Array.isArray(n))for(let t of n)t&&t.send(e);else console.warn(n)}}}},Wc=`https://urls.needle.tools/default-networking-backend/index`,Gc=`wss://networking-2.needle.tools/socket`,Kc=!!A(`debugnet`),qc=!!(Kc||A(`debugowner`)),Jc=A(`debugnetbin`),Yc;(function(e){e.ConnectionInfo=`connection-start-info`})(Yc||={});var Xc;(function(e){e.Join=`join-room`,e.Leave=`leave-room`,e.JoinedRoom=`joined-room`,e.LeftRoom=`left-room`,e.UserJoinedRoom=`user-joined-room`,e.UserLeftRoom=`user-left-room`,e.RoomStateSent=`room-state-sent`})(Xc||={});var Zc=class{room;viewId;allowEditing;inRoom},Qc=class{room},$c=class{userId},el;(function(e){e.RequestHasOwner=`request-has-owner`,e.ResponseHasOwner=`response-has-owner`,e.RequestIsOwner=`request-is-owner`,e.ResponseIsOwner=`response-is-owner`,e.RequestOwnership=`request-ownership`,e.GainedOwnership=`gained-ownership`,e.RemoveOwnership=`remove-ownership`,e.LostOwnership=`lost-ownership`,e.GainedOwnershipBroadcast=`gained-ownership-broadcast`,e.LostOwnershipBroadcast=`lost-ownership-broadcast`})(el||={});var tl=class{guid;connection;get hasOwnership(){return this._hasOwnership}get isOwned(){return this._isOwned}get isConnected(){return this.connection.isConnected}_hasOwnership=!1;_isOwned=void 0;_gainSubscription;_lostSubscription;_hasOwnerResponse;constructor(e,t){this.connection=e,this.guid=t,this._gainSubscription=this.onGainedOwnership.bind(this),this._lostSubscription=this.onLostOwnership.bind(this),e.beginListen(el.LostOwnership,this._lostSubscription),e.beginListen(el.GainedOwnershipBroadcast,this._gainSubscription),this._hasOwnerResponse=this.onHasOwnerResponse.bind(this),e.beginListen(el.ResponseHasOwner,this._hasOwnerResponse)}_isWaitingForOwnershipResponseCallback=null;updateIsOwned(){this.connection.send(el.RequestHasOwner,{guid:this.guid})}onHasOwnerResponse(e){e.guid===this.guid&&(this._isOwned=e.value)}requestOwnershipIfNotOwned(){return this._isWaitingForOwnershipResponseCallback===null?(this._isWaitingForOwnershipResponseCallback=this.waitForHasOwnershipRequestResponse.bind(this),this.connection.beginListen(el.ResponseHasOwner,this._isWaitingForOwnershipResponseCallback),this.connection.send(el.RequestHasOwner,{guid:this.guid}),this):this}waitForHasOwnershipRequestResponse(e){e.guid===this.guid&&(this._isWaitingForOwnershipResponseCallback&&=(this.connection.stopListen(el.ResponseHasOwner,this._isWaitingForOwnershipResponseCallback),null),this._isOwned=e.value,e.value||(qc&&console.log(`request ownership`,this.guid),this.requestOwnership()))}requestOwnershipAsync(){return new Promise((e,t)=>{this.requestOwnership();let n=0,r=()=>{if(n++>10)return t(`Timeout`);setTimeout(()=>{this.hasOwnership?e(this):r()},100)};r()})}requestOwnership(){return qc&&console.log(`Request ownership`,this.guid),this.connection.send(el.RequestOwnership,{guid:this.guid}),this}freeOwnership(){return this.connection.send(el.RemoveOwnership,{guid:this.guid}),this._isWaitingForOwnershipResponseCallback&&=(this.connection.stopListen(el.ResponseHasOwner,this._isWaitingForOwnershipResponseCallback),null),this}destroy(){this.connection.stopListen(el.GainedOwnership,this._gainSubscription),this.connection.stopListen(el.LostOwnership,this._lostSubscription),this.connection.stopListen(el.ResponseHasOwner,this._hasOwnerResponse),this._isWaitingForOwnershipResponseCallback&&=(this.connection.stopListen(el.ResponseHasOwner,this._isWaitingForOwnershipResponseCallback),null)}onGainedOwnership(e){e.guid===this.guid&&(this._isOwned=!0,this.connection.connectionId===e.owner?(qc&&console.log(`GAINED OWNERSHIP`,this.guid),this._hasOwnership=!0):this._hasOwnership=!1)}onLostOwnership(e){e===this.guid&&(qc&&console.log(`LOST OWNERSHIP`,this.guid),this._hasOwnership=!1,this._isOwned=!1)}},nl=class{context;_peer=null;constructor(e){this.context=e}get peer(){return this._peer||=new Vc,this._peer}tryGetState(e){return e===`invalid`?null:this._state[e]}get connectionId(){return this._connectionId}get isDebugEnabled(){return Kc}get isConnected(){return this.connected}get currentRoomName(){return this._currentRoomName}get allowEditing(){return this._currentRoomAllowEditing}get currentRoomViewId(){return this._currentRoomViewId}getViewOnlyUrl(){if(this.currentRoomViewId===null)return null;let e=new URL(window.location.href);return e.searchParams.set(`view`,this.currentRoomViewId),e.href}get isInRoom(){return this._isInRoom}get currentLatency(){return this._currentDelay}get currentServerUrl(){return this._ws?.url??null}sendPing(){this.send(`ping`,{time:this.context.time.time})}userIsInRoom(e){return this._currentInRoom.indexOf(e)!==-1}_usersInRoomCopy=[];usersInRoom(e=null){e||=this._usersInRoomCopy,e.length=0;for(let t of this._currentInRoom)e.push(t);return e}joinRoom(e,t=!1){return e?e.length>1024?(console.error(`Room name too long, can not join: "`+e+`". Max length is 1024 characters.`),!1):(this.isInRoom&&this.currentRoomName!==e&&console.warn(`Needle Engine is already connected to a networking room. Connecting to multiple rooms is not supported`),this.connect(),Kc&&console.log(`join: `+e),this.send(Xc.Join,{room:e,viewOnly:t},Oo.OnConnection),!0):(console.error(`Missing room name, can not join: "`+e+`"`),!1)}leaveRoom(e=null){return e||=this.currentRoomName,e?(this.send(Xc.Leave,{room:e}),!0):(console.error(`Missing room name, can not join: "`+e+`"`),!1)}send(e,t=null,n=Oo.Queued){if(t===null&&(t={}),n===Oo.Queued){this._defaultMessagesBuffer.push({key:e,value:t});return}return this.sendWithWebsocket(e,t,n)}sendDeleteRemoteState(e){this.send(`delete-state`,{guid:e,dontSave:!0}),delete this._state[e]}sendDeleteRemoteStateAll(){this.send(`delete-all-state`),this._state={}}sendBinary(e){Jc&&console.log(`<< send binary`,this.context.time.frame,e.length/1024+` KB`),this._ws?.send(e)}_defaultMessagesBuffer=[];_defaultMessagesBufferArray=[];sendBufferedMessagesNow(){if(!this._ws)return;this._defaultMessagesBufferArray.length=0;let e=Object.keys(this._defaultMessagesBuffer).length;for(let t in this._defaultMessagesBuffer){let n=this._defaultMessagesBuffer[t];if(e<=1){this.sendWithWebsocket(n.key,n.value,Oo.Immediate);break}let r=this.toMessage(n.key,n.value);this._defaultMessagesBufferArray.push(r)}if(this._defaultMessagesBuffer.length=0,this._defaultMessagesBufferArray.length>0&&Kc&&console.log(`SEND BUFFERED`,this._defaultMessagesBufferArray.length),this._defaultMessagesBufferArray.length<=0)return;let t=JSON.stringify(this._defaultMessagesBufferArray);this._ws?.send(t)}beginListen(e,t){return this._listeners[e]||(this._listeners[e]=[]),this._listeners[e].push(t),t}stopListening(e,t){return this.stopListen(e,t)}stopListen(e,t){if(!t||!this._listeners[e])return;let n=this._listeners[e].indexOf(t);n>=0&&this._listeners[e].splice(n,1)}beginListenBinary(e,t){return this._listenersBinary[e]||(this._listenersBinary[e]=[]),this._listenersBinary[e].push(t),t}stopListenBinary(e,t){if(!this._listenersBinary[e])return;let n=this._listenersBinary[e].indexOf(t);n>=0&&this._listenersBinary[e].splice(n,1)}netWebSocketUrlProvider;registerProvider(e){this.netWebSocketUrlProvider=e}async connect(e){if(this.connected&&e&&e!==Gc)return Promise.reject(`Can not connect to different server url. Please disconnect first.`);if(this.connected)return Promise.resolve(!0);e&&console.debug(`Connecting to user provided url `+e);let t=e||this.netWebSocketUrlProvider?.getWebsocketUrl();return t?Gc=t:Tt()&&(Gc=`wss://`+window.location.host+`/socket`),this.connectWebsocket()}disconnect(){this._ws?.close(),this._ws=void 0,Gc=void 0,this._currentRoomAllowEditing=!0,this._currentRoomName=null,this._currentRoomViewId=null,this._isInRoom=!1,this._currentInRoom.length=0,this._state={},this._currentDelay=-1}_listeners={};_listenersBinary={};connected=!1;channelId;_connectionId=null;_ws;_waitingForSocket={};_isInRoom=!1;_currentRoomName=null;_currentRoomViewId=null;_currentRoomAllowEditing=!0;_currentInRoom=[];_state={};_currentDelay=-1;_connectingToWebsocketPromise=null;connectWebsocket(){return this._connectingToWebsocketPromise?this._connectingToWebsocketPromise:this._connectingToWebsocketPromise=new Promise(async(e,t)=>{let n=!1,i=t=>{n||(n=!0,e(t))};if(Gc===void 0&&(console.log(`Fetch default backend url: `+Wc),Gc=await(await fetch(Wc)).text()),Gc===void 0){i(!1);return}console.debug(`Connecting to networking backend on `+Gc);let a=await r(()=>import(`./needle-engine.BJP2NBoC.js`).then(e=>e.t),__vite__mapDeps([11,2]),import.meta.url),o=a.default?.WebsocketBuilder??a.WebsocketBuilder,s=a.default?.ExponentialBackoff??a.ExponentialBackoff,c=new o(Gc).withMaxRetries(10).withBackoff(new s(2e3,4)).onOpen(()=>{this._connectingToWebsocketPromise=null,this._ws=c,this.connected=!0,M()||Kc?console.log(`Connected to networking backend `+Gc):console.debug(`Connected to networking backend`,Gc),i(!0),this.onSendQueued(Oo.OnConnection)}).onClose(e=>{this._connectingToWebsocketPromise=null,this.connected=!1,this._isInRoom=!1,i(!1);let t=`Websocket connection closed...`;Gc?.includes(`/socket`)||(t+=` Do you perhaps mean to connect to "/socket"?`),console.error(t)}).onError(e=>{console.error(`Websocket connection failed...`),i(!1),$a.sendEvent(this.context,`networking`,{event:`connection_error`})}).onRetry(()=>{console.log(`Retry connecting to networking websocket`)}).build();c.addEventListener(a.WebsocketEvent.message,(e,t)=>{this.onMessage(e,t)})})}onMessage(e,t){let n=t.data;try{if(typeof n!=`string`){n.size&&this.handleIncomingBinaryMessage(n);return}let e=JSON.parse(n);if(Array.isArray(e))for(let t of e)this.handleIncomingStringMessage(t);else this.handleIncomingStringMessage(e);return}catch(e){Kc&&n===`pong`?console.log(`<<`,n):M()&&console.error(`Failed to parse message`,e)}}async handleIncomingBinaryMessage(e){Jc&&console.log(`<< bin`,this.context.time.frame);let t=await e.arrayBuffer(),n=new Dc(new Uint8Array(t)),r=n.getBufferIdentifier(),i=this._listenersBinary[r],a=jc(n),o=Mc(a);if(o&&typeof o==`string`&&(this._state[o]=a),!i)return;let s=a??n;for(let e of i)e(s)}handleIncomingStringMessage(e){if(Kc&&console.log(`<<`,e.key??e),e.key)switch(e.key){case Yc.ConnectionInfo:if(e.data){let t=e.data;t&&(console.assert(t.id!==void 0&&t.id!==null&&t.id.length>0,`server did not send connection id`,t.id),console.debug(`Your id is: `+t.id,this.context.alias??``),this._connectionId=t.id,$a.sendEvent(this.context,`networking`,{event:`connected`}))}else console.warn(`Expected connection id in `+e.key);break;case Xc.JoinedRoom:if(Kc&&console.log(e),e){this._isInRoom=!0;let t=e;this._currentRoomName=t.room,this._currentRoomViewId=t.viewId,this._currentRoomAllowEditing=t.allowEditing??!0,this._currentInRoom.length=0,this._currentInRoom.push(...t.inRoom),(Jc||M())&&console.debug(`Joined Needle Engine Room: `+t.room);let n=new URL(window.location.href);n.searchParams.has(`room`)&&n.searchParams.delete(`room`),n.searchParams.set(`view`,this._currentRoomViewId),console.debug(`Room view id: ${this._currentRoomViewId}\n${n.href}`)}this.onSendQueued(Oo.OnRoomJoin),$a.sendEvent(this.context,`networking`,{event:`joined_room`,room:this._currentRoomName});break;case Xc.LeftRoom:let t=e;t.room===this.currentRoomName&&(this._isInRoom=!1,this._currentRoomName=null,this._currentRoomAllowEditing=!0,this._currentInRoom.length=0,(Jc||M())&&console.debug(`Left Needle Engine Room: `+t.room)),$a.sendEvent(this.context,`networking`,{event:`left_room`,room:t.room});break;case Xc.UserJoinedRoom:if(e.data){let t=e.data;this._currentInRoom.push(t.userId),Kc&&console.log(t.userId+` joined`,`now in room:`,this._currentInRoom)}break;case Xc.UserLeftRoom:if(e.data){let t=e.data,n=this._currentInRoom.indexOf(t.userId);n>=0&&(Kc&&console.log(t.userId+` left`,`now in room:`,this._currentInRoom),this._currentInRoom.splice(n,1)),t.userId===this.connectionId&&console.log(`you left the room`)}break;case`all-room-state-deleted`:Kc&&console.log(`RECEIVED all-room-state-deleted`),this._state={};break;case`ping`:case`pong`:let n=e.data?.time;n&&(this._currentDelay=this.context.time.time-n),Kc&&console.log(`Current latency: ${(this._currentDelay*1e3).toFixed()} ms`,`Clients in room: `+this._currentInRoom?.length);break}let t=e.data;t&&(this._state[t.guid]=t);let n=this._listeners[e.key];if(n){n=[...n];for(let t of n)try{t(e.data)}catch(t){console.error(`Error invoking callback for "`+e.key+`"`,t)}}}toMessage(e,t){return{key:e,data:t}}sendWithWebsocket(e,t,n=Oo.OnRoomJoin){if(!this._ws){let r=this._waitingForSocket[n]||[];r.push(()=>this.sendWithWebsocket(e,t,n)),this._waitingForSocket[n]=r;return}let r=JSON.stringify(this.toMessage(e,t));Kc&&console.log(`>>`,e),this._ws.send(r)}onSendQueued(e){let t=this._waitingForSocket[e];if(t){for(let e of t)e();t.length=0}}},rl=A(`debugplayerview`),il;(function(e){e.Browser=`browser`,e.Headset=`headset`,e.Handheld=`handheld`})(il||={});var al=class{userId;context;viewDevice=il.Browser;get currentObject(){return this._object}set currentObject(e){this._object=e}get isConnected(){return this.context.connection.userIsInRoom(this.userId)}removed=!1;_object;constructor(e,t){this.userId=e,this.context=t}},ol=class{context;playerViews=new Map;constructor(e){this.context=e}setPlayerView(e,t,n){let r=this.playerViews.get(e);r||(r=new al(e,this.context),this.playerViews.set(e,r)),r.viewDevice=n,r.currentObject=t,r.removed=!1}getPlayerView(e){if(e){if(!this.context.connection.userIsInRoom(e)){this.playerViews.delete(e);return}return this.playerViews.get(e)}}removePlayerView(e,t){let n=this.playerViews.get(e);n?.viewDevice===t&&(rl&&console.log(`REMOVE`,e),n.removed=!0,this.playerViews.delete(e))}},sl=new we;async function cl(e){return new Promise((t,n)=>{sl.load(e,t,void 0,n)})}var ll=new Uint8Array(4);ll[0]=255,ll[1]=255,ll[2]=255,ll[3]=255;var ul=new m(ll,1,1,y);function dl(e,t=1){let n=`alpha`in e,r=t*t,i=new Uint8Array(4*r),a=Math.floor(e.r*255),o=Math.floor(e.g*255),s=Math.floor(e.b*255);for(let t=0;t{let r=this.loaded.get(t);r?e(r):n(`Shader not found`)});let n=new ml(e,await cl(t));return this.loaded.set(t,n),n}};function hl(e,t){let n=e.elements;t||=[],t.length=0;for(let e=0;e<16;e+=4){let r=n[e],i=n[e+1],a=n[e+2],o=n[e+3],s=new Te(r,i,a,o);t.push(s)}return t}var gl=[],_l=[];function vl(e,t){if(gl.length===0)for(let e=0;e<27;e++)gl.push(0);t||=gl;for(let e=0;e<27;e++)_l[e]=t[e];t=_l,e.unity_SHAr={value:new Te(t[9],t[3],t[6],t[0])},e.unity_SHBr={value:new Te(t[12],t[15],t[18],t[21])},e.unity_SHAg={value:new Te(t[10],t[4],t[7],t[1])},e.unity_SHBg={value:new Te(t[13],t[16],t[19],t[22])},e.unity_SHAb={value:new Te(t[11],t[5],t[8],t[2])},e.unity_SHBb={value:new Te(t[14],t[17],t[20],t[23])},e.unity_SHC={value:new Te(t[24],t[25],t[26],1)}}var yl=class{vertexShader;fragmentShader;technique;constructor(e,t,n){this.vertexShader=e,this.fragmentShader=t,this.technique=n}};async function bl(e,t){if(!e)return console.error(`Can not find technique: no shader data`),null;let n=e.programs[t],r=n.vertexShader,i=n.fragmentShader;if(r!==void 0&&i!==void 0){let n=e.shaders[r],a=e.shaders[i];if(n.uri&&a.uri||n.code&&a.code){if(!n.code&&n.uri&&await xl(n),!a.code&&a.uri&&await xl(a),!n.code||!a.code)return null;let r=e.techniques[t];return new yl(n.code,a.code,r)}}return console.error(`Shader technique not found`,t),null}async function xl(e){let t=e.uri;t&&(t.endsWith(`.glsl`)?e.code=(await new we().loadAsync(t)).toString():e.code=Sl(e.uri))}function Sl(e){return decodeURIComponent(Array.prototype.map.call(atob(e),function(e){return`%`+(`00`+e.charCodeAt(0).toString(16)).slice(-2)}).join(``))}var Cl=A(`debugenvlight`),wl;(function(e){e[e.Skybox=0]=`Skybox`,e[e.Trilight=1]=`Trilight`,e[e.Flat=3]=`Flat`,e[e.Custom=4]=`Custom`})(wl||={});var Tl;(function(e){e[e.Skybox=0]=`Skybox`,e[e.Custom=1]=`Custom`})(Tl||={});var El=class{context;constructor(e){this.context=e,this.context.pre_update_callbacks.push(this.preUpdate.bind(this))}_currentLightSettingsId;_sceneLightSettings;get currentLightSettingsId(){return this._currentLightSettingsId}preUpdate(){let e=this.context.time;this._timevec4.x=e.time,this._timevec4.y=Math.sin(e.time),this._timevec4.z=Math.cos(e.time),this._timevec4.w=e.deltaTime}_timevec4=new Te;get timeVec4(){return this._timevec4}get environmentIntensity(){if(!this._sceneLightSettings||!this._currentLightSettingsId)return 1;let e=this._sceneLightSettings.get(this._currentLightSettingsId);return e?e.ambientIntensity:1}get sceneLightSettings(){return this._sceneLightSettings?.values()}enable(e){e instanceof js&&(e=e.url);let t=this._sceneLightSettings?.get(e);return t?(Cl&&console.log(`Enable scene light settings`,e,t),e!==this._currentLightSettingsId&&this._currentLightSettingsId&&this.disable(this._currentLightSettingsId),this._currentLightSettingsId=e,t.enabled=!0,!0):(Cl&&console.warn(`No light settings found for`,e),!1)}disable(e){if(e instanceof js&&(e=e.url),e==null)return!1;let t=this._sceneLightSettings?.get(e);return t?(Cl&&console.log(`Disable scene light settings`,e,t),t.enabled=!1,!0):!1}enableCurrent(){return this._currentLightSettingsId?(this.enable(this._currentLightSettingsId),this._currentLightSettingsId??null):null}disableCurrent(){if(this._currentLightSettingsId){let e=this._currentLightSettingsId;return this.disable(this._currentLightSettingsId),e}return null}internalRegisterSceneLightSettings(e){let t=e.sourceId;if(!t){console.error(`Missing source id for scene light settings, can not register:`,e);return}Cl&&console.log(`Register `+e?.sourceId+` lighting`,e),this._sceneLightSettings||=new Map,this._sceneLightSettings.set(t,e)}internalUnregisterSceneLightSettings(e){let t=e.sourceId;if(!t){console.error(`Missing source id for scene light settings, can not unregister:`,e);return}Cl&&console.log(`Unregister `+e?.sourceId+` lighting`,e),this._sceneLightSettings&&this._sceneLightSettings.delete(t)}internalRegisterReflection(e,t){Cl&&console.log(`Register reflection`,e,t);let n=new Dl(this.context,t,1);this._lighting[e]=n}internalGetReflection(e){return this._lighting[e]}__currentReflectionId=null;internalEnableReflection(e){this.__currentReflectionId=e;let t=this._sceneLightSettings?.get(e);switch(Cl&&console.log(`Enable reflection`,e,t?wl[t.ambientMode]:`Unknown ambient mode`,t),t?.ambientMode){case wl.Skybox:case wl.Custom:let t=this.internalGetReflection(e);if(t&&t.Source){Cl&&console.log(`Setting environment reflection`,t);let e=this.context.scene,n=t.Source;return n.mapping!==306&&(n.mapping=303),e.environment=n,e.environmentIntensity=this.environmentIntensity||1,n}else Cl&&console.warn(`Could not find reflection for source`,e);break}if(t?.environmentReflectionSource===Tl.Custom)switch(t?.ambientMode){case wl.Trilight:if(t.ambientTrilight){let e=t.ambientTrilight,n=fl(e[0],e[1],e[2],64,64);return n.colorSpace=de,n.mapping=303,this.context.scene.environment=n,n}else console.error(`Missing ambient trilight`,t.sourceId);case wl.Flat:if(t.ambientLight){let e=dl(t.ambientLight,64);return e.colorSpace=de,e.mapping=303,this.context.scene.environment=e,e}else console.error(`Missing ambientlight`,t.sourceId)}return null}internalDisableReflection(e){if(e&&e!==this.__currentReflectionId){Cl&&console.log(`Not disabling reflection for`,e,`because it is not the current light settings id`,this.__currentReflectionId);return}Cl&&console.log(`Disable reflection`,e);let t=this.context.scene;t.environment=null}_lighting={}},Dl=class{get Source(){return this._source}_source;constructor(e,t,n=1){this._source=t,t.mapping!==306&&(t.mapping=303)}},Ol=A(`timescale`),kl=1;typeof Ol==`number`&&(kl=Ol);var Al=class{get time(){return this._time}set time(e){this._time=e}_time=0;get deltaTime(){return this._deltaTime}set deltaTime(e){this._deltaTime=e}_deltaTime=0;get deltaTimeUnscaled(){return this._deltaTimeUnscaled}_deltaTimeUnscaled=0;timeScale=1;get frame(){return this._frame}set frame(e){this._frame=e}_frame=0;get frameCount(){return this.frame}get realtimeSinceStartup(){return this.clock.elapsedTime}get fps(){return 1/this.deltaTime}get smoothedFps(){return this._smoothedFps}get smoothedDeltaTime(){return 1/this._smoothedFps}clock=new De;_smoothedFps=0;_smoothedDeltaTime=0;_fpsSamples=[];_fpsSampleIndex=0;constructor(){typeof kl==`number`&&(this.timeScale=kl)}update(){this.deltaTime=this.clock.getDelta(),this.deltaTime=Math.min(.1,this.deltaTime),this._deltaTimeUnscaled=this.deltaTime,this.deltaTime<=0&&(this.deltaTime=1e-12),this.deltaTime*=this.timeScale,this.frame+=1,this.time+=this.deltaTime,this._fpsSamples.length<60?this._fpsSamples.push(this.deltaTime):this._fpsSamples[this._fpsSampleIndex++%60]=this.deltaTime;let e=0;for(let t=0;t=0&&t>=0){let n=i.tonemapping_pars_fragment.substring(e,t+42);i.tonemapping_pars_fragment=i.tonemapping_pars_fragment.replace(n,` float startCompression = 0.8; float desaturation = 0.5; // Patched tonemapping function vec3 NeutralToneMapping( vec3 color ) { color *= toneMappingExposure; float d = 1. - startCompression; // float peak = dot(color, vec3(0.299, 0.587, 0.114)); float peak = max(color.r, max(color.g, color.b)); if (peak < startCompression) return color; float newPeak = 1. - d * d / (peak + d - startCompression); float invPeak = 1. / peak; float extraBrightness = dot(color * (1. - startCompression * invPeak), vec3(1, 1, 1)); color *= newPeak * invPeak; float g = 1. - 3. / (desaturation * extraBrightness + 3.); return mix(color, vec3(1, 1, 1), g); } `)}else M()&&console.error(`Couldn't find NeutralToneMapping in ShaderChunk.tonemapping_pars_fragment`)}function Pl(){let e=i.tonemapping_pars_fragment.indexOf(`vec3 AgXToneMapping( vec3 color ) {`),t=i.tonemapping_pars_fragment.indexOf(`return color;`,e);if(e>=0&&t>=0){let n=i.tonemapping_pars_fragment.substring(e,t+13);i.tonemapping_pars_fragment=i.tonemapping_pars_fragment.replace(n,` // 0: Default, 1: Golden, 2: Punchy #define AGX_LOOK 0 vec3 userSlope = vec3(1.0); vec3 userOffset = vec3(0.0); vec3 userPower = vec3(1.0); float userSaturation = 1.0; // Mean error^2: 3.6705141e-06 vec3 _agxDefaultContrastApprox(vec3 x) { vec3 x2 = x * x; vec3 x4 = x2 * x2; return + 15.5 * x4 * x2 - 40.14 * x4 * x + 31.96 * x4 - 6.868 * x2 * x + 0.4298 * x2 + 0.1191 * x - 0.00232; } vec3 _agx(vec3 val) { const mat3 agx_mat = mat3( 0.842479062253094, 0.0423282422610123, 0.0423756549057051, 0.0784335999999992, 0.878468636469772, 0.0784336, 0.0792237451477643, 0.0791661274605434, 0.879142973793104); const float min_ev = -12.47393; const float max_ev = 4.026069; // val = pow(val, vec3(2.2)); // Input transform (inset) val = agx_mat * val; // Log2 space encoding val = clamp(log2(val), min_ev, max_ev); val = (val - min_ev) / (max_ev - min_ev); // Apply sigmoid function approximation val = _agxDefaultContrastApprox(val); return val; } vec3 _agxEotf(vec3 val) { const mat3 agx_mat_inv = mat3( 1.19687900512017, -0.0528968517574562, -0.0529716355144438, -0.0980208811401368, 1.15190312990417, -0.0980434501171241, -0.0990297440797205, -0.0989611768448433, 1.15107367264116); // Inverse input transform (outset) val = agx_mat_inv * val; // sRGB IEC 61966-2-1 2.2 Exponent Reference EOTF Display // NOTE: We're linearizing the output here. Comment/adjust when // *not* using a sRGB render target val = pow(val, vec3(2.2)); return val; } vec3 _agxLook(vec3 val) { const vec3 lw = vec3(0.2126, 0.7152, 0.0722); float luma = dot(val, lw); // Default vec3 offset = vec3(0.0); vec3 slope = vec3(1.0); vec3 power = vec3(1.0); float sat = 1.0; #if AGX_LOOK == 1 // Golden slope = vec3(1.0, 0.9, 0.5); power = vec3(0.8); sat = 0.8; #elif AGX_LOOK == 2 // Punchy slope = vec3(1.0); power = vec3(1.35, 1.35, 1.35); sat = 1.4; #endif // Needle slope = vec3(1.05); power = vec3(1.10, 1.10, 1.10); sat = 1.15; // User // slope = userSlope; // offset = userOffset; // power = userPower; // sat = userSaturation; // ASC CDL val = pow(val * slope + offset, power); return luma + sat * (val - luma); } vec3 AgXToneMapping( vec3 color ) { // apply AGX color *= toneMappingExposure; color = max(color, vec3(0.001)); // Prevent NaN color = _agx(color); color = _agxLook(color); // Optional color = _agxEotf(color); return color; `)}else M()&&console.error(`Couldn't find AgXToneMapping in ShaderChunk.tonemapping_pars_fragment`)}function Fl(e){if(typeof e==`string`)switch(e=e.toLowerCase(),e){case`none`:return 0;case`neutral`:return 7;case`aces`:return 4;case`agx`:return 6;case`khronos_neutral`:return 7;default:console.warn(`[PostProcessing] Unknown tone mapping mode`,e);return}}var Il=[];function Ll(e){Il.indexOf(e)===-1&&Il.push(e)}function Rl(e){let t=Il.indexOf(e);t!==-1&&Il.splice(t,1)}var zl=[];function Bl(e){zl.indexOf(e)===-1&&zl.push(e)}function Vl(e){let t=zl.indexOf(e);t!==-1&&zl.splice(t,1)}function Hl(e){globalThis.dispatchEvent(new CustomEvent(`needle-xrsession-start`,{detail:e}));for(let t=0;t`);``+btoa(` `);var Gl=`data:image/svg+xml;charset=utf-8;base64,`+btoa(``),Kl;(function(e){function t(e){return e===`0`||e?.toLowerCase()===`false`}e.isFalsey=t;function n(e,n,r){let i=e.getAttribute(n);return t(i)?null:(r?.onAttribute?.call(null,i),i)}e.getAttributeValueIfNotFalsey=n;function r(e,n,r){let i=e.getAttribute(n);return i===null?null:t(i)?(r?.onAttribute?.call(null,i,!0),!1):(r?.onAttribute?.call(null,i,!1),i)}e.getAttributeAndCheckFalsey=r})(Kl||={});async function ql(e){if(!globalThis.QRCode){let e=`https://cdn.jsdelivr.net/gh/davidshimjs/qrcodejs@gh-pages/qrcode.min.js`,t=document.head.querySelector(`script[src="${e}"]`);t||(t=document.createElement(`script`),t.src=e,document.head.appendChild(t)),await new Promise((e,n)=>{t.addEventListener(`load`,()=>{e(!0)})})}let t=globalThis.QRCode,n=e.domElement??document.createElement(`div`),r=new t(n,{width:e.width??256,height:e.height??256,colorDark:`#000000`,colorLight:`#ffffff`,correctLevel:e.showLogo?t.CorrectionLevel.H:t.CorrectLevel.M,...e}),i=r?._oQRCode.moduleCount||0,a=r?._oDrawing?._elCanvas,o=.25;o=i<40?Math.floor(i/4)/i:Math.floor(i/6)/i;let s=Math.floor(i/20)/i;try{let t=await Jl(a,{showLogo:e.showLogo,logoSize:o,logoPadding:s}).catch(e=>{});t&&(n.innerHTML=``,n.append(t))}catch{}if(e.showUrl!==!1&&e.text){let t=n.querySelector(`.qr-code-link-label`),r=e.text.replace(/^(https?:\/\/)?(www\.)?/,``).replace(/\/+$/,``).replace(/\?+$/,``);if(r=`Scan to visit `+r,t)t.textContent=r;else{let t=document.createElement(`div`);t.classList.add(`qr-code-link-label`),e.text=r,t.textContent=e.text,t.addEventListener(`click`,e=>{e.stopImmediatePropagation()}),t.style.textAlign=`center`,t.style.fontSize=`0.8em`,t.style.marginTop=`0.1em`,t.style.color=`#000000`,t.style.fontFamily=`'Roboto Flex', sans-serif`,t.style.opacity=`0.5`,t.style.wordBreak=`break-all`,t.style.wordWrap=`break-word`,t.style.marginBottom=`0.3em`,n.style.width=`calc(210px + 20px)`,n.appendChild(t)}}return n}async function Jl(e,t){if(!e)return;let n=t.logoPadding||1/32,r=new Image,i=document.querySelector(`needle-engine`);i||console.debug(`[QR Code] No web component found`);let a=Xa(),o=null;if(o=Kl.getAttributeAndCheckFalsey(i,`qrcode-logo-src`),a&&t.showLogo!==!0&&o===!1||(o||=Kl.getAttributeAndCheckFalsey(i,`logo-src`),a&&t.showLogo!==!0&&o===!1)||(o||=Kl.getAttributeAndCheckFalsey(i,`loading-logo-src`,{onAttribute:()=>{M()?console.warn(`[QR Code] 'loading-logo-src' is deprecated, please use 'logo-src' or 'qrcode-logo-src' instead.`):console.debug(`[QR Code] 'loading-logo-src' is deprecated.`)}}),a&&t.showLogo!==!0&&o===!1)||(o&&!a&&(console.warn(`[QR Code] Custom logo is only available with a commercial license. Using default Needle logo. Please get a commercial license at https://needle.tools/pricing.`),o=null),o||=Wl,!o))return;let s=!1;t.showLogo!==!1&&(r.src=o,s=await new Promise((e,t)=>{r.onload=()=>e(!0),r.onerror=t=>{let n=o===Wl?null:`'`+o+`'`;console.error(`[QR Code] Error loading logo image for QR code`,n,M()?t:``),e(!1)}}));let c=document.createElement(`canvas`);c.width=e.width+8,c.height=e.height+8;let l=c.getContext(`2d`);if(!l)return;l.fillStyle=`#ffffff`,l.fillRect(0,0,c.width,c.height),l.drawImage(e,8/2,8/2),l.imageSmoothingEnabled=!0,l.imageSmoothingQuality=`high`,l.mozImageSmoothingEnabled=!0,l.webkitImageSmoothingEnabled=!0,l.globalCompositeOperation=`lighten`;let u=l.createLinearGradient(0,0,0,c.height);u.addColorStop(0,`rgb(45, 45, 45)`),u.addColorStop(1,`rgb(45, 45, 45)`),l.fillStyle=u,l.fillRect(0,0,c.width,c.height),l.globalCompositeOperation=`source-over`;let d=Math.min(e.width,e.height)*(t.logoSize||.25),f=d;if(s){let t=r.width/r.height;t>1?f=d/t:d=f*t;let i=n*e.width,a=Math.max(d,f),o=Math.round(a+i),s=Math.round(a+i),u=(c.width-a)/2,p=(c.height-a)/2;l.shadowColor=`transparent`,l.shadowBlur=20;let m=Math.round(u-i/2),h=Math.round(p-i/2);l.beginPath(),l.moveTo(m+0,h),l.lineTo(m+o-0,h),l.quadraticCurveTo(m+o,h,m+o,h+0),l.lineTo(m+o,h+s-0),l.quadraticCurveTo(m+o,h+s,m+o-0,h+s),l.lineTo(m+0,h+s),l.quadraticCurveTo(m,h+s,m,h+s-0),l.lineTo(m,h+0),l.quadraticCurveTo(m,h,m+0,h),l.fillStyle=`#ffffff`,l.closePath(),l.fill(),l.clip(),l.shadowColor=`transparent`;let g=(c.width-d)/2,_=(c.height-f)/2;l.drawImage(r,g,_,d,f)}let p=c.toDataURL(`image/png`),m=document.createElement(`img`);return m.src=p,m.style.width=`100%`,m.style.height=`auto`,m}var Yl=`Material Symbols Outlined`;function Xl(e){let t=document.createElement(`span`);return t.style.maxWidth=`48px`,t.style.maxHeight=`48px`,t.style.overflow=`hidden`,t.classList.add(`material-symbols-outlined`,`notranslate`),t.setAttribute(`translate`,`no`),t.innerText=e,t.style.visibility=`hidden`,t.style.userSelect=`none`,t.setAttribute(`role`,`img`),t.setAttribute(`aria-label`,e+` icon`),t.setAttribute(`aria-hidden`,`true`),tu(Yl).then(n=>{n?(t.style.visibility=``,t.innerText=e):e===`more_vert`?(t.style.visibility=``,t.innerText=`More`):t.style.display=`none`}),t}function Zl(e){return e.classList?.contains(`material-symbols-outlined`)||!1}var Ql=new Map;async function $l(e){if(await tu(Yl),Ql.has(e))return Ql.get(e);let t=document.createElement(`canvas`);t.width=48,t.height=48;let n=t.getContext(`2d`);if(n){n.font=`48px '${Yl}'`,n.fillStyle=`black`,n.fillText(e,0,48);let r=t.toDataURL(),i=new be;return i.name=e+` icon`,i.image=new Image,i.image.src=r,i.needsUpdate=!0,Ql.set(e,i),i}return Ql.set(e,null),null}var eu=new Map;async function tu(e,t=5,n=0){document.fonts.check(`1em '${e}'`)||await document.fonts.ready;let r=eu.get(e)||document.fonts.load(`1em '${e}'`).then(e=>e?.length>0).finally(()=>{eu.delete(e)});return eu.set(e,r),await r?!0:n{setTimeout(()=>{r(tu(e,t,n+1))},1e3)}):!1}function nu(e,t){e.setAttribute(`priority`,String(t))}function ru(e){let t=e.getAttribute(`priority`);if(t){let e=Number.parseFloat(t);if(!Number.isNaN(e))return e}}var iu=class e{static _instance;static get instance(){return this.getOrCreate()}static getOrCreate(){return this._instance||=new e,this._instance}static create(){return new e}_fullscreenButton;get fullscreenButton(){return this._fullscreenButton}createFullscreenButton(e){if(this._fullscreenButton)return this._fullscreenButton;if(!document.fullscreenEnabled)return M()&&console.warn(`NeedleMenu: Fullscreen button could not be created, device doesn't support the Fullscreen API`),null;let t=document.createElement(`button`);this._fullscreenButton=t,t.classList.add(`fullscreen-button`),t.title=`Click to enter fullscreen mode`,nu(t,3);let n=Xl(`fullscreen`),r=Xl(`fullscreen_exit`);return t.appendChild(n),t.onclick=()=>{document.fullscreenElement?document.exitFullscreen():`webkitRequestFullscreen`in e.domElement&&typeof e.domElement.webkitRequestFullscreen==`function`?e.domElement.webkitRequestFullscreen():`requestFullscreen`in e.domElement&&e.domElement.requestFullscreen()},document.addEventListener(`fullscreenchange`,()=>{document.fullscreenElement?(n.remove(),t.appendChild(r),t.title=`Click to enter fullscreen mode`):(r.remove(),t.appendChild(n),t.title=`Click to exit fullscreen mode`)}),globalThis.addEventListener(`needle-xrsession-start`,()=>{t.style.display=`none`}),globalThis.addEventListener(`needle-xrsession-end`,()=>{t.style.display=``}),t}_muteButton;get muteButton(){return this._muteButton}createMuteButton(e){if(this._muteButton)return this._muteButton;let t=document.createElement(`button`);this._muteButton=t,t.classList.add(`mute-button`),t.title=`Click to mute/unmute`;let n=Xl(`volume_off`),r=Xl(`volume_up`);return nu(t,1),e.application.muted?t.appendChild(n):t.appendChild(r),t.onclick=()=>{e.application.muted?(n.remove(),t.appendChild(r),e.application.muted=!1):(r.remove(),t.appendChild(n),e.application.muted=!0)},t}_qrButton;get qrButton(){return this._qrButton}_customQRButtonUrl;set qrButtonUrl(e){try{new URL(e),this._customQRButtonUrl=e}catch{console.warn(`[Needle] QR code button URL is not a valid URL '${e}'`)}}get qrButtonUrl(){return this._customQRButtonUrl||window.location.href}createQRCode(e){if(this._qrButton)return this._qrButton;let t=this,n=document.createElement(`button`);this._qrButton=n,n.innerText=`QR Code`,n.prepend(Xl(`qr_code`)),n.title=`Scan this QR code with your phone to open this page`,this.hideElementDuringXRSession(n),nu(this._qrButton,20);let r=document.createElement(`div`);r.style.cssText=` position: fixed; display: inline-block; padding: 0.5rem; background-color: white; border-radius: 0.4rem; cursor: pointer; z-index: 1000; box-shadow: 0 0 12px rgba(0, 0, 0, 0.2); `;let i=document.createElement(`div`);i.classList.add(`qr-code-container`),r.appendChild(i),n.addEventListener(`click`,()=>{if(r.parentNode)return o();M()&&window.location.href.includes(`://localhost`)&&Ei(`To access your website from another device in the same local network you have to use the IP address instead of localhost. The IP address is logged in your development server console when you start the server.`),a()});async function a(){await s();let t=document.body.querySelector(`needle-engine`),a=e?.anchorElement?.parentElement||t||document.body;a.appendChild(r);let c=i.getBoundingClientRect(),l=n.getBoundingClientRect();r.style.left=l.left+l.width*.5-c.width*.5+`px`,l.top{r.style.opacity=`1`,window.addEventListener(`click`,o,{once:!0})}),window.addEventListener(`resize`,o),window.addEventListener(`scroll`,o),document.fullscreenElement?document.fullscreenElement.appendChild(r):a.appendChild(r)}function o(){r.style.pointerEvents=`none`,r.style.transition=`opacity 0.2s`,r.style.opacity=`0`,setTimeout(()=>r.parentNode?.removeChild(r),500),window.removeEventListener(`click`,o),window.removeEventListener(`resize`,o),window.removeEventListener(`scroll`,o)}async function s(){let e=await ql({text:t.qrButtonUrl,width:200,height:200});i.innerHTML=``,i.appendChild(e)}return n.addEventListener(`pointerenter`,()=>{s()},{once:!0}),n}hideElementDuringXRSession(e){Ll(t=>{e[`previous-display`]=e.style.display,e.style.display=`none`}),Bl(t=>{e[`previous-display`]!=null&&(e.style.display=e[`previous-display`])})}},au=`https://fonts.googleapis.com/css2?family=Roboto+Flex:opsz,wght@8..144,100..1000&display=swap`,ou=`https://fonts.googleapis.com/css2?family=Material+Symbols+Outlined:opsz,wght,FILL,GRAD@24,400,0,0&display=block`;function su(e,t){let n=t?.element||document.head,r=Array.from(n.querySelectorAll(`link[href*='${e}']`));if(r.length<=0){let t=document.createElement(`link`);t.href=e,t.rel=`preload`,t.as=`style`,t.crossOrigin=``,t.onload=()=>{t.rel=`stylesheet`},n.appendChild(t),r.push(t)}if(t?.loadedCallback)for(let e=0;e :host { position: relative; min-width: fit-content; /* height: 100%; can not have height 100% because of align-items: stretch; in the parent */ display: flex; } .wrapper { position: relative; display: grid; grid-template-columns: auto auto; padding: .1rem; } .wrapper:hover { cursor: pointer; } img { height: 100%; align-self: end; transition: transform 0.2s; } img.with-text { width: 11.5ch; &:hover { transform: scale(1.02); } } img.compact { width: 1.7em; &:hover { transform: scale(1.1); } } span { font-size: 1rem; white-space: nowrap; }
`,this._root.appendChild(e.content.cloneNode(!0)),this.wrapper=this._root.querySelector(`.wrapper`),this._root.appendChild(this.wrapper),this.logoElement=this._root.querySelector(`img.logo`),this.addEventListener(`click`,()=>{globalThis.open(`https://needle.tools`,`_blank`)})}ensureInitialized(){this._didInitialize||(this._didInitialize=!0,this.initializeDom())}connectedCallback(){this.ensureInitialized(),this.wrapper&&(this.wrapper.setAttribute(`title`,`Made with Needle Engine`),this.setAttribute(`aria-label`,`Needle Engine logo. Click to open the Needle Engine website.`))}_root;wrapper;logoElement;setLogoVisible(e){this.ensureInitialized(),this.logoElement&&(this.logoElement.style.display=e?`block`:`none`)}setType(e){this.ensureInitialized(),this.logoElement&&(e===`full`?(this.logoElement.src=Gl,this.logoElement.classList.remove(`with-text`),this.logoElement.classList.remove(`compact`)):(this.logoElement.src=Wl,this.logoElement.classList.add(`with-text`),this.logoElement.classList.add(`compact`)))}},du=A(`debugspatialmenu`),fu=class{_context;needleMenu;htmlButtonsMap=new Map;enabled=!0;constructor(e,t){this._context=e,this._context.pre_render_callbacks.push(this.preRender),this.needleMenu=t;let n=this.needleMenu.shadowRoot?.querySelector(`.options`);n?new MutationObserver(e=>{if(this.enabled&&!(this._context.isInXR==0&&!du))for(let t of e)t.type===`childList`&&(t.addedNodes.forEach(e=>{this.createButtonFromHTMLNode(e)}),t.removedNodes.forEach(e=>{let t=e,n=this.htmlButtonsMap.get(t);n&&(this.htmlButtonsMap.delete(t),n.remove(),D.update())}))}).observe(n,{childList:!0}):console.error(`Could not find options container in needle menu`)}setEnabled(e){this.enabled=e,e||this.menu?.removeFromParent()}userRequestedMenu=!1;setDisplay(e){return this.enabled?(this.userRequestedMenu=e,!0):!1}onDestroy(){let e=this._context.pre_render_callbacks.indexOf(this.preRender);e>-1&&this._context.pre_render_callbacks.splice(e,1)}uiisDirty=!1;markDirty(){this.uiisDirty=!0}_showNeedleLogo;showNeedleLogo(e){this._showNeedleLogo=e}_wasInXR=!1;preRender=()=>{if(!this.enabled){this.menu?.removeFromParent();return}du&&j.isDesktop()&&this.updateMenu();let e=this._context.xr;if(!(e?.running&&(e?.isPassThrough||e?.isVR))){this._wasInXR&&(this._wasInXR=!1,this.onExitXR());return}this._wasInXR||(this._wasInXR=!0,this.onEnterXR()),this.updateMenu()};onEnterXR(){let e=this.needleMenu.shadowRoot?.querySelector(`.options`);e&&e.childNodes.forEach(e=>{this.createButtonFromHTMLNode(e)})}onExitXR(){this.menu?.removeFromParent()}createButtonFromHTMLNode(e){let t=this.getMenu(),n=this.htmlButtonsMap.get(e);if(n){n.add();return}if(e instanceof HTMLButtonElement){let n=this.createButton(t,e);this.htmlButtonsMap.set(e,n),n.add()}else e instanceof HTMLSlotElement&&e.assignedNodes().forEach(e=>{this.createButtonFromHTMLNode(e)})}_menuTarget=new S;positionFilter=new ir(90,.5);updateMenu(){let e=this.getMenu();this.handleNeedleWatermark(),this._context.scene.add(e);let t=this._context.mainCamera,n=this._context.xr?.rigScale||1;if(t){let r=t.worldPosition,i=t.worldForward.multiplyScalar(-1),a=i.y>.6,o=i.y>.4,s=(e.visible?o:a)||this.userRequestedMenu,c=!e.visible&&s;e.visible=s||j.isDesktop()&&du,i.multiplyScalar(3*n),r.add(i),c&&(e.position.copy(this._menuTarget.position),e.position.y+=.25,this._menuTarget.position.copy(e.position),this.positionFilter.reset(e.position),e.quaternion.copy(this._menuTarget.quaternion),this.markDirty());let l=this._menuTarget.position.distanceTo(r);(c||l>1.5*n)&&(this.ensureRenderOnTop(this.menu),this._menuTarget.position.copy(r),this._context.scene.add(this._menuTarget),yr(this._menuTarget,this._context.mainCamera,!0,!0),this._menuTarget.removeFromParent()),this.positionFilter.filter(this._menuTarget.position,e.position,this._context.time.time),this.menu?.quaternion.slerp(this._menuTarget.quaternion,this._context.time.deltaTime*5),this.menu?.scale.setScalar(n)}this.uiisDirty&&(this.uiisDirty=!1,D.update())}ensureRenderOnTop(e,t=0){e instanceof x&&(e.material.depthTest=!1,e.material.depthWrite=!1),e.renderOrder=1e3+t*2;for(let n of e.children)this.ensureRenderOnTop(n,t+1)}familyName=`Needle Spatial Menu`;menu;get isVisible(){return this.menu?.visible}getMenu(){if(this.menu)return this.menu;this.ensureFont(),this.menu=new D.Block({boxSizing:`border-box`,fontFamily:this.familyName,height:`auto`,fontSize:.1,color:0,lineHeight:1,backgroundColor:16777215,backgroundOpacity:.55,borderRadius:1,whiteSpace:`pre-wrap`,flexDirection:`row`,alignItems:`center`,padding:new Te(0,.05,0,.05),borderColor:0,borderOpacity:.05,borderWidth:.005});let e=ji.get(`ObjectRaycaster`);return e&&Dp(this.menu,new e),this.menu}_poweredByNeedleElement;handleNeedleWatermark(){if(!this._poweredByNeedleElement){this._poweredByNeedleElement=new D.Block({width:`auto`,height:`auto`,fontSize:.05,whiteSpace:`pre-wrap`,flexDirection:`row`,flexWrap:`wrap`,justifyContent:`center`,margin:.02,borderRadius:.02,padding:.02,backgroundColor:16777215,backgroundOpacity:1}),this._poweredByNeedleElement[`needle:use_eventsystem`]=!0;let e=new mu(this._context,()=>globalThis.open(`https://needle.tools`,`_self`));Dp(this._poweredByNeedleElement,e);let t=new D.Text({textContent:`Powered by`,width:`auto`,height:`auto`}),n=new D.Text({textContent:`needle`,width:`auto`,height:`auto`,fontSize:.07,margin:new Te(0,0,0,.02)});this._poweredByNeedleElement.add(t),this._poweredByNeedleElement.add(n),this.menu?.add(this._poweredByNeedleElement),this.markDirty(),new me().load(`https://cdn.needle.tools/static/branding/poweredbyneedle.webp`,r=>{if(r){e.allowModifyUI=!1,t.removeFromParent(),n.removeFromParent();let i=r.image.width/r.image.height;this._poweredByNeedleElement?.set({backgroundImage:r,backgroundOpacity:1,width:.1*i,height:.1}),this.markDirty()}})}if(this.menu){let e=this.menu.children.indexOf(this._poweredByNeedleElement);!this._showNeedleLogo&&qa()?e>=0&&(this._poweredByNeedleElement.removeFromParent(),this.markDirty()):(this._poweredByNeedleElement.visible=!0,this.menu.add(this._poweredByNeedleElement),e!==this.menu.children.indexOf(this._poweredByNeedleElement)&&this.markDirty())}}ensureFont(){let e=D.FontLibrary.getFontFamily(this.familyName);e||(e=D.FontLibrary.addFontFamily(this.familyName),e.addVariant(`normal`,`normal`,`https://cdn.needle.tools/static/fonts/msdf/arial/arial-msdf.json`,`https://cdn.needle.tools/static/fonts/msdf/arial/arial.png`)?.addEventListener(`ready`,()=>{this.markDirty()}))}createButton(e,t){let n=new D.Block({width:`auto`,height:`auto`,whiteSpace:`pre-wrap`,flexDirection:`row`,flexWrap:`wrap`,justifyContent:`center`,backgroundColor:16777215,backgroundOpacity:0,padding:.02,margin:.01,borderRadius:.02,cursor:`pointer`,fontSize:.05}),r=new D.Text({textContent:``,width:`auto`,justifyContent:`center`,alignItems:`center`,backgroundOpacity:0,backgroundColor:16777215,fontFamily:this.familyName,color:0,borderRadius:.02,padding:.01});return n.add(r),n[`needle:use_eventsystem`]=!0,Dp(n,new mu(this._context,()=>t.click())),new pu(this,e,t,n,r)}},pu=class{menu;root;htmlbutton;spatialContainer;spatialText;spatialIcon;constructor(e,t,n,r,i){this.menu=e,this.root=t,this.htmlbutton=n,this.spatialContainer=r,this.spatialText=i,new MutationObserver(e=>{for(let t of e)t.type===`attributes`?t.attributeName===`style`&&this.updateVisible():t.type===`childList`&&this.updateText()}).observe(n,{attributes:!0,childList:!0}),this.updateText()}add(){this.spatialContainer.parent!=this.root&&(this.root.add(this.spatialContainer),this.menu.markDirty(),this.updateVisible(),this.updateText())}remove(){this.spatialContainer.parent&&(this.spatialContainer.removeFromParent(),this.menu.markDirty())}updateVisible(){let e=this.spatialContainer.visible;this.spatialContainer.visible=this.htmlbutton.style.display!==`none`,e!==this.spatialContainer.visible&&this.menu.markDirty()}_lastText=``;updateText(){let e=``,t=``;this.htmlbutton.childNodes.forEach(n=>{n.nodeType===Node.TEXT_NODE?e+=n.textContent:n instanceof HTMLElement&&Zl(n)&&n.textContent&&(t=n.textContent)}),this._lastText!==e&&(this._lastText=e,this.spatialText.name=e,this.spatialText.set({textContent:e}),this.menu.markDirty()),e.length<=0?this.spatialText.parent&&(this.spatialText.removeFromParent(),this.menu.markDirty()):this.spatialText.parent||(this.spatialContainer.add(this.spatialText),this.menu.markDirty()),t&&this.createIcon(t)}_lastTexture;async createIcon(e){if(!this.spatialIcon){let t=await $l(e);if(t&&!this.spatialIcon){let e=.08,n=new D.Block({width:e,height:e,backgroundColor:16777215,backgroundImage:t,backgroundOpacity:1,margin:new Te(0,.005,0,0)});this.spatialIcon=n,this.spatialContainer.add(n),this.menu.markDirty()}}if(e!=this._lastTexture){this._lastTexture=e;let t=await $l(e);t&&(this.spatialIcon?.set({backgroundImage:t}),this.menu.markDirty())}let t=this.spatialContainer.children.indexOf(this.spatialIcon);t>0&&(this.spatialContainer.children.splice(t,1),this.spatialContainer.children.unshift(this.spatialIcon),this.menu.markDirty())}},mu=class{isComponent=!0;enabled=!0;get activeAndEnabled(){return!0}__internalAwake(){}__internalEnable(){}__internalDisable(){}__internalStart(){}onEnable(){}onDisable(){}gameObject;allowModifyUI=!0;get element(){return this.gameObject}context;onclick;constructor(e,t){this.context=e,this.onclick=t}onPointerEnter(){this.context.input.setCursor(`pointer`),this.allowModifyUI&&(this.element.set({backgroundOpacity:1}),D.update())}onPointerExit(){this.context.input.unsetCursor(`pointer`),this.allowModifyUI&&(this.element.set({backgroundOpacity:0}),D.update())}onPointerDown(e){e.use()}onPointerUp(e){e.use()}onPointerClick(e){e.use(),this.onclick()}},hu=`needle-menu`,gu=A(`debugmenu`),_u=A(`debugnoncommercial`),vu=class{static setElementPriority(e,t){nu(e,t)}static getElementPriority(e){return ru(e)}_context;_menu;_spatialMenu;constructor(e){this._menu=yu.getOrCreate(e.domElement,e),this._menu.ensureInitialized(),this._context=e,this._spatialMenu=new fu(e,this._menu),window.addEventListener(`message`,this.onPostMessage),Ll(this.onStartXR)}onDestroy(){window.removeEventListener(`message`,this.onPostMessage),this._menu.remove(),this._spatialMenu.onDestroy()}onPostMessage=e=>{if(e.origin===globalThis.location.origin&&typeof e.data==`object`){let t=e.data,n=t.type;if(n===`needle:menu`){let e=t.button;if(e){if(!e.label)return console.error(`NeedleMenu: buttoninfo.label is required`);if(!e.onclick)return console.error(`NeedleMenu: buttoninfo.onclick is required`);let t=document.createElement(`button`);if(t.textContent=e.label,e.icon){let n=Xl(e.icon);t.prepend(n)}e.priority&&t.setAttribute(`priority`,e.priority.toString()),t.onclick=()=>{if(e.onclick){let t=e.onclick.startsWith(`http`)||e.onclick.startsWith(`www.`),n=e.target||`_blank`;t?globalThis.open(e.onclick,n):console.error(`NeedleMenu: onclick is not a valid link`,e.onclick)}},$a.sendEvent(this._context,`needle-menu`,{action:`button_added_via_postmessage`}),this._menu.appendChild(t)}else gu&&console.error(`NeedleMenu: unknown postMessage event`,t)}else gu&&console.warn(`NeedleMenu: unknown postMessage type`,n,t)}};onStartXR=e=>{e.session.isScreenBasedAR&&(this._menu.previousParent=this._menu.parentNode,this._context.arOverlayElement.appendChild(this._menu),e.session.session.addEventListener(`end`,this.onExitXR),this._menu.closeFoldout())};onExitXR=()=>{this._menu.previousParent&&(this._menu.previousParent.appendChild(this._menu),delete this._menu.previousParent)};setPosition(e){this._menu.setPosition(e)}setVisible(e){this._menu.setVisible(e)}showNeedleLogo(e){this._menu.showNeedleLogo(e),this._spatialMenu?.showNeedleLogo(e)}get logoIsVisible(){return this._menu.logoIsVisible}showSpatialMenu(e){this._spatialMenu.setEnabled(e)}setSpatialMenuVisible(e){this._spatialMenu.setDisplay(e)}get spatialMenuIsVisible(){return this._spatialMenu.isVisible}showQRCodeButton(e){if(e===`desktop-only`&&(e=!j.isMobileDevice()),e){let e=iu.getOrCreate().createQRCode();return e.style.display=``,this._menu.appendChild(e),e}else{let e=iu.getOrCreate().qrButton;return e&&(e.style.display=`none`),e??null}}showAudioPlaybackOption(e){if(!e){this._muteButton?.remove();return}this._muteButton=iu.getOrCreate().createMuteButton(this._context),this._menu.appendChild(this._muteButton)}_muteButton;showFullscreenOption(e){if(!e){this._fullscreenButton?.remove();return}this._fullscreenButton=iu.getOrCreate().createFullscreenButton(this._context),this._fullscreenButton&&this._menu.appendChild(this._fullscreenButton)}_fullscreenButton;appendChild(e){return this._menu.appendChild(e)}},yu=class e extends HTMLElement{static create(){return customElements.get(hu)||customElements.define(hu,e),document.createElement(hu)}static getOrCreate(t,n){let r=t.querySelector(hu);return!r&&t.shadowRoot&&(r=t.shadowRoot.querySelector(hu)),r||=window.document.body.querySelector(hu),r||(r=e.create(),t.shadowRoot?t.shadowRoot.appendChild(r):t.appendChild(r)),r._domElement=t,r._context=n,r}_domElement=null;_context=null;_didInitialize=!1;constructor(){super()}initializeDom(){let e=document.createElement(`template`);e.innerHTML=`
`;let t=this.attachShadow({mode:`open`});cu(),su(ou,{loadedCallback:()=>{this.handleSizeChange()}}),su(ou,{element:t});let n=e.content.cloneNode(!0);t?.appendChild(n),this.root=t.querySelector(`#root`),this.wrapper=this.root?.querySelector(`.wrapper`),this.options=this.root?.querySelector(`.options.main-container`),this.optionsCompactMode=this.root?.querySelector(`.options.compact-only`),this.logoContainer=this.root?.querySelector(`.logo`),this.compactMenuButton=this.root?.querySelector(`.compact-menu-button`),this.compactMenuButton.append(Xl(`more_vert`)),this.foldout=this.root?.querySelector(`.foldout`),this.root?.appendChild(this.wrapper),this.wrapper.classList.add(`wrapper`);let r=uu.create();r.setType(`compact`),r.style.minHeight=`1rem`,this.logoContainer.append(r),this.logoContainer.addEventListener(`click`,()=>{globalThis.open(`https://needle.tools`,`_blank`)});try{window.requestAnimationFrame(()=>Za(e=>{if(e==1&&Xa()&&!_u){let e=this._userRequestedLogoVisible;e===void 0&&(e=!1),this.___onSetLogoVisible(e)}else this.___onSetLogoVisible(!0)}))}catch(e){console.error(`[Needle Menu] License check failed.`,e)}this.compactMenuButton.addEventListener(`click`,e=>{e.preventDefault(),this.root.classList.toggle(`open`)});let i=this._context;setTimeout(()=>i=this._context);let a=0,o=(e,t)=>{gu&&console.log(`Set menu visible`,t),i?.isInAR&&i.arOverlayElement?e!=i.arOverlayElement&&i.arOverlayElement.appendChild(this):this.parentNode!=this._domElement?.shadowRoot&&this._domElement?.shadowRoot?.appendChild(this),this.style.display=t?`flex`:`none`,this.style.visibility=`visible`,this.style.opacity=`1`},s=!1;new MutationObserver(e=>{if(!s)try{s=!0,this.onChangeDetected(e);let t=this?.parentNode;if((this.style.display!=`flex`||this.style.visibility!=`visible`||this.style.opacity!=`1`||t!=this._domElement?.shadowRoot)&&!Xa()){let e=a++;wt()&&this._userRequestedMenuVisible===!1?(e===0&&o(t,this._userRequestedMenuVisible),e===1&&console.warn(`Needle Menu Warning: You need a PRO license to hide the Needle Engine menu → The menu will be visible in your deployed website if you don't have a PRO license. See https://needle.tools/pricing for details.`)):e===0?o(t,!0):setTimeout(()=>o(t,!0),5)}}finally{s=!1}}).observe(this.root,{childList:!0,subtree:!0,attributes:!0}),gu&&this.___insertDebugOptions()}ensureInitialized(){this._didInitialize||(this._didInitialize=!0,this.initializeDom())}_sizeChangeInterval;connectedCallback(){this.ensureInitialized(),window.addEventListener(`resize`,this.handleSizeChange),this.handleMenuVisible(),this._sizeChangeInterval=setInterval(()=>this.handleSizeChange(void 0,!1),5e3),setTimeout(()=>{this._domElement?.addEventListener(`resize`,this.handleSizeChange),this._domElement?.addEventListener(`click`,this.#e)},1)}disconnectedCallback(){window.removeEventListener(`resize`,this.handleSizeChange),clearInterval(this._sizeChangeInterval),this._domElement?.removeEventListener(`resize`,this.handleSizeChange),this._context?.domElement.removeEventListener(`click`,this.#e)}#e=e=>{if(!e.defaultPrevented&&e.target==this._domElement&&e instanceof PointerEvent&&e.button===0&&this.root.classList.contains(`open`)){let t=this.foldout.getBoundingClientRect(),n=e;n.clientX>t.left&&n.clientXt.top&&n.clientY{$a.sendEvent(this._context,`needle-menu`,{action:`button_clicked`,element:t.target instanceof Node?t.target.nodeName:e.nodeName,label:e.textContent,title:e instanceof HTMLElement?e.title:void 0,pointerid:t instanceof PointerEvent?t.pointerId:void 0})}))}append(...e){for(let t of e)if(typeof t==`string`){let e=document.createTextNode(t);this.trackElement(e),this.options.appendChild(e)}else this.trackElement(t),this.options.appendChild(t)}appendChild(e){if(!(e instanceof Node)){let t=document.createElement(`button`);if(t.textContent=e.label,t.onclick=e.onClick,t.setAttribute(`priority`,e.priority?.toString()??`0`),e.title&&(t.title=e.title),e.icon){let n=Xl(e.icon);e.iconSide===`right`?t.appendChild(n):t.prepend(n)}e.class&&t.classList.add(e.class),e=t}return this.trackElement(e),this.options.appendChild(e)}prepend(...e){for(let t of e)if(typeof t==`string`){let e=document.createTextNode(t);this.trackElement(e),this.options.prepend(e)}else this.trackElement(t),this.options.prepend(t)}_isHandlingChange=!1;_pauseMutationObserverOptionsContainer=!1;onChangeDetected(e){if(!this._isHandlingChange){this._isHandlingChange=!0;try{this.handleMenuVisible();for(let t of e)t.target==this.options&&(this._pauseMutationObserverOptionsContainer||this.onOptionsChildrenChanged(t))}finally{this._isHandlingChange=!1}}}onOptionsChildrenChanged(e){if(this.root.classList.toggle(`has-options`,this.hasAnyVisibleOptions),this.root.classList.toggle(`has-no-options`,!this.hasAnyVisibleOptions),this.handleSizeChange(void 0,!0),e.type===`childList`&&e.addedNodes.length>0){let e=Array.from(this.options.children);e.sort((e,t)=>parseInt(e.getAttribute(`priority`)||`0`)-parseInt(t.getAttribute(`priority`)||`0`));let t=!1;for(let n=0;n{if(!this._domElement)return;let n=this._domElement.clientWidth;if(n<100){clearTimeout(this._timeoutHandleSize),this.root.classList.add(`compact`),this.foldout.classList.add(`floating-panel-style`);return}let r=n-20;if(!t&&Math.abs(r-this._lastAvailableWidthChange)<1)return;this._lastAvailableWidthChange=r,clearTimeout(this._timeoutHandleSize),this._timeoutHandleSize=setTimeout(()=>{let e=o();e<0?(this.root.classList.add(`compact`),this.foldout.classList.add(`floating-panel-style`)):e>0&&(this.root.classList.remove(`compact`),this.foldout.classList.remove(`floating-panel-style`),o()<0&&(this.root.classList.add(`compact`),this.foldout.classList.add(`floating-panel-style`))),this._pauseMutationObserverOptionsContainer=!0,this.updateCompactFoldoutItem(),window.requestAnimationFrame(()=>this._pauseMutationObserverOptionsContainer=!1)},150);let i=()=>{let e=0;return e+=this.options.getBoundingClientRect().width,e+=this.optionsCompactMode.getBoundingClientRect().width,e+=10*this.options.childElementCount,e+=this.logoContainer.style.display==`none`?0:this.logoContainer.getBoundingClientRect().width,e},a=-1,o=()=>{let e=r-i();return gu&&e!==a&&(a=e,Ti(`Menu space left: ${e.toFixed(0)}px`)),e}};updateCompactFoldoutItem(){if(this.root.classList.contains(`compact`)){let e=null,t=-1e7,n=n=>{if(n instanceof HTMLElement){let r=vu.getElementPriority(n);if(r!==void 0&&r>=t){let i=window.getComputedStyle(n);if(i.display===`none`||i.visibility===`hidden`||i.opacity===`0`)return;e=n,t=r}}};for(let e=0;e{this.options.appendChild(e)});let t=e;this.optionsCompactMode.appendChild(t)}else e||this.optionsCompactMode.childNodes.forEach(e=>{this.options.appendChild(e)})}else this.optionsCompactMode.childNodes.forEach(e=>{this.options.appendChild(e)})}___insertDebugOptions(){window.addEventListener(`keydown`,e=>{e.key===`p`&&this.setPosition(this.root.classList.contains(`top`)?`bottom`:`top`)});let e=document.createElement(`button`);e.textContent=`Hide Buttons`,e.onclick=()=>{let e=Array(this.options.children.length);for(let t=0;t{for(let t of e)this.options.appendChild(t)},1e3)},this.appendChild(e);let t=document.createElement(`button`);t.textContent=`Toggle Logo`,t.addEventListener(`click`,()=>{this.logoContainer.style.display=this.logoContainer.style.display===`none`?``:`none`}),this.appendChild(t)}},R=A(`debugcontext`),bu=A(`stats`),xu=A(`debugactive`),Su=A(`debugframerate`),Cu=A(`debugcoroutine`),wu={},Tu=class{name;alias;hash;runInBackground;domElement;renderer;camera;scene},z;(function(e){e[e.Start=-1]=`Start`,e[e.EarlyUpdate=0]=`EarlyUpdate`,e[e.Update=1]=`Update`,e[e.LateUpdate=2]=`LateUpdate`,e[e.OnBeforeRender=3]=`OnBeforeRender`,e[e.OnAfterRender=4]=`OnAfterRender`,e[e.PrePhysicsStep=9]=`PrePhysicsStep`,e[e.PostPhysicsStep=10]=`PostPhysicsStep`,e[e.Undefined=-1]=`Undefined`})(z||={});function Eu(e,t){if(!e)return;if(!e.isComponent){(M()||R)&&console.error(`Registered script is not a Needle Engine component. The script will be ignored. Please make sure your component extends "Behaviour" imported from "@needle-tools/engine" `,e);return}t||(t=B.Current,R&&console.warn(`> Registering component without context`));let n=t?.new_scripts;n.includes(e)||n.push(e)}var B=class e{static _defaultTargetFramerate={value:90,toString(){return this.value}};static get DefaultTargetFrameRate(){return e._defaultTargetFramerate.value}static set DefaultTargetFrameRate(t){e._defaultTargetFramerate.value=t}static _defaultWebglRendererParameters={antialias:!0,alpha:!1,powerPreference:j.isiOS()||j.isMacOS()?`default`:`high-performance`,stencil:!0};static get DefaultWebGLRendererParameters(){return e._defaultWebglRendererParameters}get version(){return Bi}static get Current(){return k.Current}static set Current(e){k.Current=e}static get All(){return k.All}name;alias;isManagedExternally=!1;isPaused=!1;runInBackground=!1;targetFrameRate;physicsSteps=1;hash;domElement;appendHTMLElement(e){return this.domElement.shadowRoot?this.domElement.shadowRoot.appendChild(e):this.domElement.appendChild(e)}get resolutionScaleFactor(){return this._resolutionScaleFactor}set resolutionScaleFactor(e){if(e!==this._resolutionScaleFactor&&typeof e==`number`){if(e<=0){console.error(`Invalid resolution scale factor`,e);return}this._resolutionScaleFactor=e,this.updateSize()}}_resolutionScaleFactor=1;_boundingClientRectFrame=-1;_boundingClientRect=null;_domX;_domY;calculateBoundingClientRect(){if(this.xr){this._domX=0,this._domY=0;return}this._boundingClientRectFrame!==this.time.frame&&(this._boundingClientRectFrame=this.time.frame,this._boundingClientRect=this.domElement.getBoundingClientRect(),this._domX=this._boundingClientRect.x,this._domY=this._boundingClientRect.y)}get domWidth(){return this.isInAR?window.innerWidth:this.domElement.clientWidth}get domHeight(){return this.isInAR?window.innerHeight:this.domElement.clientHeight}get domX(){return this.calculateBoundingClientRect(),this._domX}get domY(){return this.calculateBoundingClientRect(),this._domY}get isInXR(){return this.renderer?.xr?.isPresenting||!1}xr=null;get xrSessionMode(){return this.xr?.mode}get isInVR(){return this.xrSessionMode===`immersive-vr`}get isInAR(){return this.xrSessionMode===`immersive-ar`}get isInPassThrough(){return this.xr?this.xr.isPassThrough:!1}get xrSession(){return this.renderer?.xr?.getSession()}get xrFrame(){return this._xrFrame}get xrCamera(){return this.renderer.xr.isPresenting?this.renderer?.xr?.getCamera():void 0}_xrFrame=null;get arOverlayElement(){let e=this.domElement;return typeof e.getAROverlayContainer==`function`?e.getAROverlayContainer():this.domElement}get currentFrameEvent(){return this._currentFrameEvent}_currentFrameEvent=z.Undefined;scene;renderer;composer=null;scripts=[];scripts_pausedChanged=[];scripts_earlyUpdate=[];scripts_update=[];scripts_lateUpdate=[];scripts_onBeforeRender=[];scripts_onAfterRender=[];scripts_WithCorroutines=[];scripts_immersive_vr=[];scripts_immersive_ar=[];coroutines={};post_setup_callbacks=[];pre_update_callbacks=[];pre_render_callbacks=[];post_render_callbacks=[];pre_update_oneshot_callbacks=[];new_scripts=[];new_script_start=[];new_scripts_pre_setup_callbacks=[];new_scripts_post_setup_callbacks=[];new_scripts_xr=[];mainCameraComponent=void 0;get mainCamera(){if(this._mainCamera)return this._mainCamera;if(this.mainCameraComponent){let e=this.mainCameraComponent;return e.threeCamera||e.buildCamera(),e.threeCamera}return this._fallbackCamera||=new C(75,this.domWidth/this.domHeight,.1,1e3),this._fallbackCamera}set mainCamera(e){this._mainCamera=e}_mainCamera=null;_fallbackCamera=null;application;animations;time;input;physics;connection;assets;mainLight=null;get rendererData(){return this.sceneLighting}sceneLighting;addressables;lightmaps;players;lodsManager;menu;accessibility;get isCreated(){return this._isCreated}get rootSourceId(){return this.rootSceneSourceIdentifiers[0]||void 0}_needsUpdateSize=!1;_isCreated=!1;_isCreating=!1;_isVisible=!1;_stats=bu?new ut:null;constructor(e){this.name=e?.name||``,this.alias=e?.alias,this.domElement=e?.domElement||document.body,this.hash=e?.hash,e?.renderer&&(this.renderer=e.renderer,this.isManagedExternally=!0),e?.runInBackground!==void 0&&(this.runInBackground=e.runInBackground),e?.scene?this.scene=e.scene:this.scene=new ne,e?.camera&&(this._mainCamera=e.camera),this.application=new Vs(this),this.time=new Al,this.input=new cc(this),this.physics=new jd(this),this.connection=new nl(this),this.assets=new Vd,this.sceneLighting=new El(this),this.addressables=new ks(this),this.lightmaps=new gc(this),this.players=new ol(this),this.menu=new vu(this),this.lodsManager=new bc(this),this.animations=new Ni(this),this.accessibility=new _a(this);let t=()=>this._needsUpdateSize=!0;window.addEventListener(`resize`,t),this._disposeCallbacks.push(()=>window.removeEventListener(`resize`,t));let n=new ResizeObserver(e=>this._needsUpdateSize=!0);n.observe(this.domElement),this._disposeCallbacks.push(()=>n.disconnect()),this._intersectionObserver=new IntersectionObserver(e=>{this._isVisible=e[0].isIntersecting}),this._disposeCallbacks.push(()=>this._intersectionObserver?.disconnect()),k.register(this)}createNewRenderer(t){if(this.renderer?.dispose(),t={...e.DefaultWebGLRendererParameters,...t},!t.canvas){let e=this.domElement?.shadowRoot?.querySelector(`canvas`);e?(t.canvas=e,R&&console.log(`Using canvas from shadow root`,e)):R&&console.warn(`No canvas found in shadow root, creating new canvas. This may cause input events to not work correctly. To fix this, make sure to use the canvas provided by the Needle Engine Web Component (e.g. by using context.createNewRenderer() without parameters or passing the canvas from the shadow root explicitly).`)}return R&&console.log(`Using Renderer Parameters:`,t,this.domElement),this.renderer=new h(t),this.renderer.domElement.setAttribute(`aria-label`,`3D rendering`),this.renderer.domElement.setAttribute(`role`,`img`),this.renderer.debug.checkShaderErrors=M()||A(`checkshadererrors`)===!0,this.renderer.toneMappingExposure=1,this.renderer.toneMapping=0,this.renderer.setClearColor(new a(`lightgrey`),0),this.renderer.shadowMap.enabled=!0,this.renderer.shadowMap.type=2,this.renderer.setSize(this.domWidth,this.domHeight),this.renderer.outputColorSpace=de,this.renderer.nodes={library:new Fe,modelViewMatrix:null,modelNormalViewMatrix:null},this.lodsManager.setRenderer(this.renderer),this.input.bindEvents(),sa(this,this.renderer.domElement),this.renderer}_intersectionObserver=null;internalOnUpdateVisible(){this._intersectionObserver?.disconnect(),this._intersectionObserver?.observe(this.domElement)}_disposeCallbacks=[];requestSizeUpdate(){this._needsUpdateSize=!0}maxRenderResolution;get devicePixelRatio(){return this._devicePixelRatio}set devicePixelRatio(e){e!==this._devicePixelRatio&&(this._devicePixelRatio=e,this._needsUpdateSize=!0)}_devicePixelRatio=`auto`;updateSize(e=!1){if(e||!this.isManagedExternally&&this.renderer.xr?.isPresenting===!1){this._needsUpdateSize=!1;let e=this.resolutionScaleFactor,t=this.domWidth*e,n=this.domHeight*e;this.maxRenderResolution&&(this.maxRenderResolution.x=Math.max(1,this.maxRenderResolution.x),t=Math.min(this.maxRenderResolution.x,t),this.maxRenderResolution.y=Math.max(1,this.maxRenderResolution.y),n=Math.min(this.maxRenderResolution.y,n));let r=this.mainCamera;this.updateAspect(r),this.renderer.setSize(t,n,!0),this.renderer.domElement.style.width=`100%`,this.renderer.domElement.style.height=`100%`;let i=typeof this.devicePixelRatio==`number`?this.devicePixelRatio:this.devicePixelRatio===`auto`?Math.min(2,window.devicePixelRatio):void 0;i!==void 0&&this.renderer.setPixelRatio(i),this.composer&&(this.composer.setSize?.call(this.composer,t,n),i!==void 0&&`setPixelRatio`in this.composer&&typeof this.composer.setPixelRatio==`function`&&this.composer.setPixelRatio?.call(this.composer,window.devicePixelRatio))}}updateAspect(e,t,n){if(!e)return;t===void 0&&(t=this.domWidth),n===void 0&&(n=this.domHeight);let r=t/n;if(e.isPerspectiveCamera){let t=e,n=t.aspect;t.aspect=r,n!==t.aspect&&e.updateProjectionMatrix()}else if(e.isOrthographicCamera){let t=e,n=t.top-t.bottom,i=n*r/2,a=n/2;(t.left!=-i||t.top!=a)&&(t.left=-i,t.right=i,t.top=a,t.bottom=-a,e.updateProjectionMatrix())}}recreate(){this.clear(),this.create(this._originalCreationArgs)}_originalCreationArgs;async onCreate(e){return this.create(e)}async create(e){try{this._isCreating=!0,e!==this._originalCreationArgs&&(this._originalCreationArgs=Gt(e)),window.addEventListener(`unhandledrejection`,this.onUnhandledRejection);let t=await this.internalOnCreate(e);return this._isCreated=t,t}finally{window.removeEventListener(`unhandledrejection`,this.onUnhandledRejection),this._isCreating=!1}}onUnhandledRejection=e=>{this.onError(e.reason)};onError(e){this.domElement.dispatchEvent(new CustomEvent(`error`,{detail:e}))}clear(){k.dispatchCallback(O.ContextClearing,this),ja(this,O.ContextClearing),zf(this.scene,!0,!0),this.scene=new ne,this.addressables?.dispose(),this.lightmaps?.clear(),this.physics?.engine?.clearCaches(),this.lodsManager.disable(),this.accessibility?.clear(),this._onBeforeRenderListeners.clear(),this._onAfterRenderListeners.clear(),this.isManagedExternally||this.renderer&&(this.renderer.renderLists.dispose(),this.renderer.state.reset(),this.renderer.resetState()),k.dispatchCallback(O.ContextCleared,this)}dispose(){this.internalOnDestroy(),this.accessibility.dispose()}onDestroy(){this.internalOnDestroy()}internalOnDestroy(){e.Current=this,k.dispatchCallback(O.ContextDestroying,this),ja(this,O.ContextDestroying),this.clear(),this.renderer?.setAnimationLoop(null),this.renderer&&(this.renderer.setClearAlpha(0),this.renderer.clear(),this.isManagedExternally||(R&&console.log(`Disposing renderer`),this.renderer.dispose())),this.scene=null,this.renderer=null,this.input.dispose(),this.menu.onDestroy(),this.animations.onDestroy();for(let e of this._disposeCallbacks)try{e()}catch(t){console.error(`Error in on dispose callback:`,t,e)}this.domElement?.parentElement&&this.domElement.parentElement.removeChild(this.domElement),this._isCreated=!1,k.dispatchCallback(O.ContextDestroyed,this),ja(this,O.ContextDestroyed),k.unregister(this),e.Current===this&&(e.Current=null)}registerCoroutineUpdate(e,t,n){return typeof t?.next==`function`?(this.coroutines[n]||(this.coroutines[n]=[]),this.coroutines[n].push({comp:e,main:t}),t):(console.error(`Registered invalid coroutine function from `+e.name+` Coroutine functions must be generators: "*myCoroutine() {...}" Start a coroutine from a component by calling "this.startCoroutine(myCoroutine())"`),t)}unregisterCoroutineUpdate(e,t){if(!this.coroutines[t])return;let n=this.coroutines[t].findIndex(t=>t.main===e);n>=0&&this.coroutines[t].splice(n,1)}stopAllCoroutinesFrom(e){for(let t in this.coroutines){let n=this.coroutines[t];for(let t=n.length-1;t>=0;t--)n[t].comp===e&&n.splice(t,1)}}_cameraStack=[];setCurrentCamera(e){if(!e)return;if(e.threeCamera||e.buildCamera(),!e.threeCamera){console.warn(`Camera component is missing camera`,e);return}let t=this._cameraStack.indexOf(e);t>=0&&this._cameraStack.splice(t,1),this._cameraStack.push(e),this.mainCameraComponent=e;let n=e.threeCamera;n.isPerspectiveCamera&&this.updateAspect(n),this.mainCameraComponent?.applyClearFlagsIfIsActiveCamera()}removeCamera(e){if(!e)return;let t=this._cameraStack.indexOf(e);if(t>=0&&this._cameraStack.splice(t,1),this.mainCameraComponent===e&&(this.mainCameraComponent=void 0,this._cameraStack.length>0)){let e=this._cameraStack[this._cameraStack.length-1];this.setCurrentCamera(e)}}_onBeforeRenderListeners=new Map;_onAfterRenderListeners=new Map;addBeforeRenderListener(e,t){if(!this._onBeforeRenderListeners.has(e.uuid)){let t=[];this._onBeforeRenderListeners.set(e.uuid,t),e.onBeforeRender=this._createRenderCallbackWrapper(t)}this._onBeforeRenderListeners.get(e.uuid).push(t)}removeBeforeRenderListener(e,t){if(this._onBeforeRenderListeners.has(e.uuid)){let n=this._onBeforeRenderListeners.get(e.uuid),r=n.indexOf(t);r>=0&&n.splice(r,1)}}addAfterRenderListener(e,t){if(!this._onAfterRenderListeners.has(e.uuid)){let t=[];this._onAfterRenderListeners.set(e.uuid,t),e.onAfterRender=this._createRenderCallbackWrapper(t)}this._onAfterRenderListeners.get(e.uuid)?.push(t)}removeAfterRenderListener(e,t){if(this._onAfterRenderListeners.has(e.uuid)){let n=this._onAfterRenderListeners.get(e.uuid),r=n.indexOf(t);r>=0&&n.splice(r,1)}}_createRenderCallbackWrapper(e){return(t,n,r,i,a,o)=>{for(let s=0;s{if(R||M()){if(Di(`Needle Engine dependencies failed to load. Please check the console for more details`),e instanceof ReferenceError){let t=`YourComponentName`,n=e.message.indexOf(`'`);if(n>0){let r=e.message.indexOf(`'`,n+1);if(r>0){let i=e.message.substring(n+1,r);i.length>3&&(t=i)}}console.error(`Needle Engine dependencies failed to load:\n\n# Make sure you don't have circular imports in your scripts!\n\nPossible solutions: \n→ Replace @serializable(${t}) in your script with @serializable(Behaviour)\n→ If you only need type information try importing the type only, e.g: import { type ${t} }\n\n---`,e);return}console.error(`Needle Engine dependencies failed to load`,e)}}).then(()=>{R&&console.log(`Needle Engine dependencies are ready`)})),this.clear();let i=this.renderer,a=!i||i.isDisposed===!0;this.isManagedExternally===!1&&a?this.createNewRenderer():this.lodsManager.setRenderer(this.renderer),this.renderer?.setAnimationLoop(null),e.Current=this,await k.dispatchCallback(O.ContextCreationStart,this);let o=!0,s;try{e.Current=this,s=t?await this.internalLoadInitialContent(n,t):[]}catch(e){console.error(e),o=!1}if(!o)return this.onError(`Failed to load initial content`),!1;if(n!==this._createId||t?.abortSignal?.aborted)return!1;if(this.internalOnUpdateVisible(),!this.renderer)return R&&console.warn(`Context has no renderer (perhaps it was disconnected?`,this.domElement.isConnected),!1;!this.isManagedExternally&&!this.domElement.shadowRoot&&this.domElement.prepend(this.renderer.domElement),e.Current=this,e.Current=this;for(let e=0;e{let n=e;if(n?.isCamera){if(dp(n.gameObject),!n.activeAndEnabled)return;if(n.tag===`MainCamera`)return t=n,!0;t=n}}),t?this.setCurrentCamera(t):!k.dispatchCallback(O.MissingCamera,this,{files:s})&&!this.mainCamera&&!this.isManagedExternally&&console.warn(`Missing camera in main scene`,this)}this.input.bindEvents(),e.Current=this,ep(this),this.physics.engine&&(this.physics.engine?.step(0),this.physics.engine?.postStep()),!this.isManagedExternally&&this.composer&&this.mainCamera,this._needsUpdateSize=!0,this._stats&&(this._stats.showPanel(0),this._stats.dom.style.position=`absolute`,this.domElement.shadowRoot?.appendChild(this._stats.dom)),R&&ti(this.scene,!0),this.targetFrameRate===void 0?(R&&console.warn(`No target framerate set, using default`,e.DefaultTargetFrameRate),this.targetFrameRate=e._defaultTargetFramerate):R&&console.log(`Target framerate set to`,this.targetFrameRate),this._dispatchReadyAfterFrame=!0;let c=k.dispatchCallback(O.ContextCreated,this,{files:s});if(c){let e=this.domElement;`internalSetLoadingMessage`in e&&typeof e.internalSetLoadingMessage==`function`&&e?.internalSetLoadingMessage(`finish loading`),await c}if(t?.abortSignal?.aborted)return!1;let l=this.rootSourceId;return l&&this.sceneLighting.enable(l),ja(this,O.ContextCreated),R&&console.log(`Context Created...`,this.renderer,this.renderer.domElement),this._isCreating=!1,!this.isManagedExternally&&!t?.abortSignal?.aborted&&this.restartRenderLoop(),!0}rootSceneSourceIdentifiers=[];async internalLoadInitialContent(e,t){this.rootSceneSourceIdentifiers.length=0;let n=[];if(t.files.length===0)return n;let r=[...t.files];this.rootSceneSourceIdentifiers.push(...r);let i={name:``,progress:null,index:0,count:r.length},a=ba();for(let o=0;o{t.abortSignal?.aborted||(i.name=s,i.progress=e,i.index=o,i.count=r.length,t.onLoadingProgress?.call(this,i))});t?.onLoadingFinished?.call(this,o,s,c??null),c?n.push({src:s,file:c}):console.warn(`Could not load file: `+s)}if(e!==this._createId||t.abortSignal?.aborted){R&&console.log(`Aborting loading because create id changed or abort signal was set`,e,this._createId);for(let e of n)if(e&&e.file)for(let t of e.file.scenes)zf(t,!0,!0)}else{let e=!1;for(let t of n)t&&t.file&&(t.file.scene?(e=!0,this.scene.add(t.file.scene)):console.warn(`No scene found in loaded file`));if(!e){for(let e of n)if(e&&e.file&&`parser`in e.file){let t=0;if(!Array.isArray(e.file.parser.json.materials))continue;for(let n=0;n{this.isManagedExternally||this.update(e,t)}),!0):(console.error(`Can not start render loop without renderer`),!1)}_renderlooperrors=0;update(t,n){if(n===void 0&&(n=null),M()||R||$f())try{this.internalStep(t,n),this._renderlooperrors=0}catch(t){this._renderlooperrors+=1,(M()||R)&&(t instanceof Error||t instanceof TypeError)&&Ti(`Caught unhandled exception during render-loop - see console for details.`,{type:Tn.Error}),console.error(`Frame #`+this.time.frame+` `,t),this._renderlooperrors>=3&&(console.warn(`Stopping render loop due to error`),this.renderer.setAnimationLoop(null),$a.sendError(e.Current,`renderloop`,t instanceof Error?t:Error(String(t)))),this.domElement.dispatchEvent(new CustomEvent(`error`,{detail:t}))}else this.internalStep(t,n)}updatePhysics(e){this.internalUpdatePhysics(e)}setCameraFocusRect(e,t){let n=this._focusRect;if(this._focusRect=e,t&&Object.assign(this.focusRectSettings,t),t?.damping===void 0&&n){let e=n;n instanceof HTMLElement&&(e=n.getBoundingClientRect()),e&&`top`in e&&e.bottom>=-100&&e.right>=-100&&e.top<=window.innerHeight+100&&e.left<=window.innerWidth+100&&(this.focusRectSettings.damping=.2)}}get focusRect(){return this._focusRect}get focusRectSize(){let e=this._focusRect;if(e&&(e instanceof DOMRect||`width`in e&&`height`in e&&`x`in e&&`y`in e))return{x:e.x,y:e.y,width:e.width,height:e.height};if(e instanceof HTMLElement){let t=e.getBoundingClientRect();return{x:t.x,y:t.y,width:t.width,height:t.height}}return null}focusRectSettings={damping:0,zoom:1,offsetX:0,offsetY:0};_focusRect=null;_lastTimestamp=0;_accumulatedTime=0;_dispatchReadyAfterFrame=!1;internalStep(e,t){this.internalOnBeforeRender(e,t)!==!1&&(this.internalOnRender(),this.internalOnAfterRender())}internalOnBeforeRender(t,n){this.renderer.info.autoReset=!!n,this.renderer.info.autoReset===!1&&this.renderer.info.reset(),this._needsVisibleUpdate=!0;let r=n!==null&&this._xrFrame===null;if(this._xrFrame=n,r&&this.domElement.dispatchEvent(new CustomEvent(`xr-session-started`,{detail:{context:this,session:this.xrSession,frame:n}})),this._currentFrameEvent=z.Undefined,this.isManagedExternally===!1&&this.isInXR===!1&&this.targetFrameRate!==void 0){this._lastTimestamp===0&&(this._lastTimestamp=t),this._accumulatedTime+=(t-this._lastTimestamp)/1e3,this._lastTimestamp=t;let e=this.targetFrameRate;if(typeof e==`object`&&(e=e.value),this._accumulatedTime<1/(e+1))return!1;this._accumulatedTime=0}if(this._stats?.begin(),e.Current=this,this.onHandlePaused())return!1;for(e.Current=this,this.time.update(),Su&&console.log(`FPS`,this.time.smoothedFps.toFixed(0)),ep(this),lp(this.scene),np(this),ja(this,z.Start);this._cameraStack.length>0&&(!this.mainCameraComponent||this.mainCameraComponent.destroyed);){this._cameraStack.splice(this._cameraStack.length-1,1);let e=this._cameraStack[this._cameraStack.length-1];this.setCurrentCamera(e)}if(this.pre_update_oneshot_callbacks){for(let e in this.pre_update_oneshot_callbacks)this.pre_update_oneshot_callbacks[e]();this.pre_update_oneshot_callbacks.length=0}if(this.pre_update_callbacks)for(let e in this.pre_update_callbacks)this.pre_update_callbacks[e]();this._currentFrameEvent=z.EarlyUpdate;for(let t=0;t0&&this.internalUpdatePhysics(this.physicsSteps),this.isVisibleToUser||this.runInBackground){this._currentFrameEvent=z.OnBeforeRender;for(let t=0;t0?this.time.deltaTime/e.damping:1;mr(this._focusRect,this.focusRectSettings,t,this.mainCamera,this.renderer)}}return!0}internalUpdatePhysics(e){if(!this.physics.engine)return!1;let t=e,n=this.time.deltaTime/t;for(let e=0;e0){let e=i[i.length-1].next();if(e.done&&i.pop(),t(e)&&(r.chained||=[],r.chained.push(e.value)),!e.done)continue}let a=r.main.next();if(a.done===!0){n.splice(e,1),--e;continue}let o=a.value;if(t(o)){if(o.next().done)continue;r.chained||=[],r.chained.push(o)}else if(o instanceof Promise){let e=o;r.chained||=[];let t=Ws(e);r.chained?.push(t);continue}}catch(e){console.error(e)}}function t(e){return!!(e&&e.next&&e.return)}}},Du={Handedness:Object.freeze({NONE:`none`,LEFT:`left`,RIGHT:`right`}),ComponentState:Object.freeze({DEFAULT:`default`,TOUCHED:`touched`,PRESSED:`pressed`}),ComponentProperty:Object.freeze({BUTTON:`button`,X_AXIS:`xAxis`,Y_AXIS:`yAxis`,STATE:`state`}),ComponentType:Object.freeze({TRIGGER:`trigger`,SQUEEZE:`squeeze`,TOUCHPAD:`touchpad`,THUMBSTICK:`thumbstick`,BUTTON:`button`}),ButtonTouchThreshold:.05,AxisTouchThreshold:.1,VisualResponseProperty:Object.freeze({TRANSFORM:`transform`,VISIBILITY:`visibility`})};async function Ou(e){let t=await fetch(e);if(t.ok)return t.json();throw Error(t.statusText)}async function ku(e){if(!e)throw Error(`No basePath supplied`);return await Ou(`${e}/profilesList.json`)}async function Au(e,t,n=null,r=!0){if(!e)throw Error(`No xrInputSource supplied`);if(!t)throw Error(`No basePath supplied`);let i=await ku(t),a;if(e.profiles.some(e=>{let n=i[e];return n&&(a={profileId:e,profilePath:`${t}/${n.path}`,deprecated:!!n.deprecated}),!!a}),!a){if(!n)throw Error(`No matching profile name found`);let e=i[n];if(!e)throw Error(`No matching profile name found and default profile "${n}" missing.`);a={profileId:n,profilePath:`${t}/${e.path}`,deprecated:!!e.deprecated}}let o=await Ou(a.profilePath),s;if(r){let t;if(t=e.handedness===`any`?o.layouts[Object.keys(o.layouts)[0]]:o.layouts[e.handedness],!t)throw Error(`No matching handedness, ${e.handedness}, in profile ${a.profileId}`);t.assetPath&&(s=a.profilePath.replace(`profile.json`,t.assetPath))}return{profile:o,assetPath:s}}var ju={xAxis:0,yAxis:0,button:0,state:Du.ComponentState.DEFAULT};function Mu(e=0,t=0){let n=e,r=t;if(Math.sqrt(e*e+t*t)>1){let i=Math.atan2(t,e);n=Math.cos(i),r=Math.sin(i)}return{normalizedXAxis:n*.5+.5,normalizedYAxis:r*.5+.5}}var Nu=class{constructor(e){this.componentProperty=e.componentProperty,this.states=e.states,this.valueNodeName=e.valueNodeName,this.valueNodeProperty=e.valueNodeProperty,this.valueNodeProperty===Du.VisualResponseProperty.TRANSFORM&&(this.minNodeName=e.minNodeName,this.maxNodeName=e.maxNodeName),this.value=0,this.updateFromComponent(ju)}updateFromComponent({xAxis:e,yAxis:t,button:n,state:r}){let{normalizedXAxis:i,normalizedYAxis:a}=Mu(e,t);switch(this.componentProperty){case Du.ComponentProperty.X_AXIS:this.value=this.states.includes(r)?i:.5;break;case Du.ComponentProperty.Y_AXIS:this.value=this.states.includes(r)?a:.5;break;case Du.ComponentProperty.BUTTON:this.value=this.states.includes(r)?n:0;break;case Du.ComponentProperty.STATE:this.valueNodeProperty===Du.VisualResponseProperty.VISIBILITY?this.value=this.states.includes(r):this.value=+!!this.states.includes(r);break;default:throw Error(`Unexpected visualResponse componentProperty ${this.componentProperty}`)}}},Pu=class{constructor(e,t){if(!e||!t||!t.visualResponses||!t.gamepadIndices||Object.keys(t.gamepadIndices).length===0)throw Error(`Invalid arguments supplied`);this.id=e,this.type=t.type,this.rootNodeName=t.rootNodeName,this.touchPointNodeName=t.touchPointNodeName,this.visualResponses={},Object.keys(t.visualResponses).forEach(e=>{let n=new Nu(t.visualResponses[e]);this.visualResponses[e]=n}),this.gamepadIndices=Object.assign({},t.gamepadIndices),this.values={state:Du.ComponentState.DEFAULT,button:this.gamepadIndices.button===void 0?void 0:0,xAxis:this.gamepadIndices.xAxis===void 0?void 0:0,yAxis:this.gamepadIndices.yAxis===void 0?void 0:0}}get data(){return{id:this.id,...this.values}}updateFromGamepad(e){if(this.values.state=Du.ComponentState.DEFAULT,this.gamepadIndices.button!==void 0&&e.buttons.length>this.gamepadIndices.button){let t=e.buttons[this.gamepadIndices.button];this.values.button=t.value,this.values.button=this.values.button<0?0:this.values.button,this.values.button=this.values.button>1?1:this.values.button,t.pressed||this.values.button===1?this.values.state=Du.ComponentState.PRESSED:(t.touched||this.values.button>Du.ButtonTouchThreshold)&&(this.values.state=Du.ComponentState.TOUCHED)}this.gamepadIndices.xAxis!==void 0&&e.axes.length>this.gamepadIndices.xAxis&&(this.values.xAxis=e.axes[this.gamepadIndices.xAxis],this.values.xAxis=this.values.xAxis<-1?-1:this.values.xAxis,this.values.xAxis=this.values.xAxis>1?1:this.values.xAxis,this.values.state===Du.ComponentState.DEFAULT&&Math.abs(this.values.xAxis)>Du.AxisTouchThreshold&&(this.values.state=Du.ComponentState.TOUCHED)),this.gamepadIndices.yAxis!==void 0&&e.axes.length>this.gamepadIndices.yAxis&&(this.values.yAxis=e.axes[this.gamepadIndices.yAxis],this.values.yAxis=this.values.yAxis<-1?-1:this.values.yAxis,this.values.yAxis=this.values.yAxis>1?1:this.values.yAxis,this.values.state===Du.ComponentState.DEFAULT&&Math.abs(this.values.yAxis)>Du.AxisTouchThreshold&&(this.values.state=Du.ComponentState.TOUCHED)),Object.values(this.visualResponses).forEach(e=>{e.updateFromComponent(this.values)})}},Fu=class{constructor(e,t,n){if(!e)throw Error(`No xrInputSource supplied`);if(!t)throw Error(`No profile supplied`);this.xrInputSource=e,this.assetUrl=n,this.id=t.profileId,this.layoutDescription=t.layouts[e.handedness],this.components={},Object.keys(this.layoutDescription.components).forEach(e=>{let t=this.layoutDescription.components[e];this.components[e]=new Pu(e,t)}),this.updateFromGamepad()}get gripSpace(){return this.xrInputSource.gripSpace}get targetRaySpace(){return this.xrInputSource.targetRaySpace}get data(){let e=[];return Object.values(this.components).forEach(t=>{e.push(t.data)}),e}updateFromGamepad(){Object.values(this.components).forEach(e=>{e.updateFromGamepad(this.xrInputSource.gamepad)})}},Iu=new ce().makeRotationY(Math.PI),Lu=new E().setFromAxisAngle(new o(0,1,0),Math.PI),Ru=A(`debugwebxr`),zu=class{priority=-1e5;gameObject;isXRRig(){return!0}get isActive(){return this.gameObject.visible}constructor(){if(this.gameObject=new S,this.gameObject.name=`Implicit XR Rig`,Ru){let e=Sd(16733661);e.position.y+=.5,this.gameObject.add(e)}}},Bu=A(`debugwebxr`),Vu=A(`debugcustomgesture`),Hu=`https://cdn.jsdelivr.net/npm/@webxr-input-profiles/assets@1.0/dist/profiles`,Uu=`generic-trigger`,Wu=new E().setFromEuler(new He(g.degToRad(0),g.degToRad(-90),g.degToRad(-90))),Gu=new o(.04,-.04,0),Ku=class{xr;get context(){return this.xr.context}inputSource;index=0;emitEvents=!0;get connected(){return this._connected}_connected=!0;get isTracking(){return this._isTracking}_isTracking=!1;get gamepad(){return this.__gamepad??=this.inputSource.gamepad}__gamepad;get isHand(){return this.hand!=null}get hand(){return this.__hand??=this.inputSource.hand}__hand;get handObject(){return this.context.renderer.xr.getHand(this.index)}get profiles(){return this.inputSource.profiles}get layout(){return this._layout}get targetRayMode(){return this.inputSource.targetRayMode}get targetRaySpace(){return this.inputSource.targetRaySpace}get gripSpace(){return this.inputSource.gripSpace}get side(){return this.__side??=this.inputSource.handedness}__side=void 0;get isRight(){return this.side===`right`}get isLeft(){return this.side===`left`}get isStylus(){return this._isMxInk}getHitTestSource(){return this._hitTestSource||this._requestHitTestSource(),this._hitTestSource}get hasHitTestSource(){return this._hitTestSource}cancelHitTestSource(){this._hitTestSource&&=(this._hitTestSource.cancel(),void 0)}_hitTestSource=void 0;_hasSelectEvent=!1;get hasSelectEvent(){return this._hasSelectEvent}_isMxInk=!1;_isMetaQuestTouchController=!1;getHitTest(){return this.xr.getHitTest(this)}_handJointPoses=new Map;getHandJointPose(e,t){if(t||=this.xr.frame,!this.hand||!t?.getJointPose||!this.xr.referenceSpace)return null;let n=this._handJointPoses?.get(e);return n||(n=t.getJointPose(e,this.xr.referenceSpace),n&&this._handJointPoses.set(e,n),n)}_gripMatrix=new ce;_gripPosition=new o;_gripQuaternion=new E;_linearVelocity=new o;_rayPositionRaw=new o;_rayRotationRaw=new E;_rayMatrix=new ce;_rayPosition=new o;_rayQuaternion=new E;get gripPosition(){return P(this._gripPosition)}get gripQuaternion(){return Tr(this._gripQuaternion)}get gripMatrix(){return this._gripMatrix}get gripLinearVelocity(){return P(this._linearVelocity).applyQuaternion(Lu)}get rayPosition(){return P(this._rayPosition)}get rayQuaternion(){return Tr(this._rayQuaternion)}get gripWorldPosition(){return P(this._gripWorldPosition)}_gripWorldPosition=new o;get gripWorldQuaternion(){return Tr(this._gripWorldQuaternion)}_gripWorldQuaternion=new E;get rayWorldPosition(){return P(this._rayWorldPosition)}_rayWorldPosition=new o;updateRayWorldPosition(){let e=this.xr.context.mainCamera?.parent;this._rayWorldPosition.copy(this._rayPositionRaw),e&&this._rayWorldPosition.applyMatrix4(e.matrixWorld)}get rayWorldQuaternion(){return Tr(this._rayWorldQuaternion)}_rayWorldQuaternion=new E;get pinchPosition(){return P(this._pinchPosition)}_pinchPosition=new o;updateRayWorldQuaternion(){let e=this.xr.context.mainCamera?.parent,t=e?Pr(e):void 0;this._rayWorldQuaternion.copy(this._rayRotationRaw).multiply(Lu),t&&this._rayWorldQuaternion.premultiply(t)}get ray(){return this._ray.origin.copy(this.rayWorldPosition),this._ray.direction.copy(P(0,0,1).applyQuaternion(this.rayWorldQuaternion)),this._ray}_ray;_hand_wristDotUp=void 0;get handWristDotUp(){if(this._hand_wristDotUp!==void 0)return this._hand_wristDotUp;let e=this.handObject?.joints.wrist;if(e){let t=P(0,1,0).applyQuaternion(e.quaternion);return this._hand_wristDotUp=P(0,1,0).dot(t)}}get isHandUpsideDown(){return this.handWristDotUp===void 0?!1:this.handWristDotUp<-.7}get isTeleportGesture(){return this.isHandUpsideDown&&this.getGesture(`pinch`)?.isDown}get object(){return this._object}_object;_gripSpaceObject;_raySpaceObject;model=null;_debugAxesHelper=new _e(.15);_debugGripAxesHelper=new _e(.07);_debugRayAxesHelper=new _e(.07);async getModelUrl(){return this.getMotionController?.then(e=>e?.assetUrl||null)}constructor(e,t,n){this.xr=e,this.inputSource=t,this.index=n,this._object=new S,this._object.name=`NeedleXRController_${n}`,Bu&&(this._object.add(this._debugAxesHelper),this._gripSpaceObject=new S,this._raySpaceObject=new S,this._gripSpaceObject.name=`NeedleXRController_${n}_gripSpace`,this._raySpaceObject.name=`NeedleXRController_${n}_raySpace`,this._gripSpaceObject.add(this._debugGripAxesHelper),this._raySpaceObject.add(this._debugRayAxesHelper),this.xr.context.scene.add(this._gripSpaceObject),this.xr.context.scene.add(this._raySpaceObject)),this.xr.context.scene.add(this._object),this._ray=new p,this.pointerInit={origin:this,pointerType:this.hand?`hand`:`controller`,deviceIndex:this.index,pointerId:-1,mode:this.inputSource.targetRayMode,ray:this._ray,device:this._object,buttonName:`none`},this.initialize(),this.subscribeEvents()}_hitTestSourcePromise=null;_requestHitTestSource(){return this._hitTestSourcePromise?this._hitTestSourcePromise:this.xr.mode===`immersive-ar`&&this.inputSource.targetRayMode===`tracked-pointer`&&this.xr.session.requestHitTestSourceForTransientInput?this._hitTestSourcePromise=this.xr.session.requestHitTestSourceForTransientInput({profile:this.inputSource.profiles[0],offsetRay:new XRRay})?.then(e=>(this._hitTestSourcePromise=null,this.connected?this._hitTestSource=e:(e.cancel(),null)))??null:null}onPointerHits=e=>{};onUpdate(e){this.onUpdateFrame(e),this.updateInputEvents(),this.onUpdateMove()}onRenderDebug(){H.DrawSphere(this.rayWorldPosition,.003),H.DrawDirection(this.rayWorldPosition,P(0,0,10).applyQuaternion(this.rayWorldQuaternion));let e=(this.inputSource.gripSpace?this.gripWorldPosition:this.object.worldPosition).sub(this.object.worldForward.multiplyScalar(.1)),t=this.inputSource.profiles.join(` `),n=`Controller[${this.index}] (${this.inputSource.targetRayMode}, ${this.side}) C:${this.connected?`x`:`-`} T:${this.isTracking?`x`:`-`} Hand:${this.inputSource.hand?`x`:`-`} Pen: ${this._isMxInk?`x`:`-`}`;if(this.inputSource.hand&&(n+=`\nPinch: ${this.getGesture(`pinch`)?.value.toFixed(3)}`),n+=` `+t,n+=` `+(this.inputSource.targetRaySpace?`Ray: x`:`Ray: -`)+(this.inputSource.gripSpace?` Grip: x`:` Grip: -`)+(this.inputSource.gamepad?` Gamepad: ${this.inputSource.gamepad.mapping}`:` Gamepad: -`),this.inputSource.gamepad){let e=this.inputSource.gamepad,t=`[btns `+e.buttons.length+`]: `+e.buttons.map(e=>e.value.toPrecision(1)).join(`,`);t+=` [axes `+e.axes.length+`]: `+e.axes.map(e=>e.toPrecision(1)).join(`,`),n+=` `+t}if(this._layout){n+=` Layout: `;for(let e of Object.keys(this._layout.components||{})){let t=this.getStick(e),r=this._layout.components[e]?.gamepadIndices,i=r?Object.entries(r).map(e=>e[0][0].toUpperCase()+e[0].slice(1)+`=`+e[1]).join(`,`):``;n+=`\n ${e}: ${this._layout.components[e]?.type} [${i}] (${t.x.toPrecision(2)},${t.y.toPrecision(2)})`}}H.DrawLabel(e,n,.006)}onUpdateFrame(e){if(this._handJointPoses.clear(),this._hand_wristDotUp=void 0,!this.xr.referenceSpace||!this.inputSource.gamepad?.connected){this._isTracking=!1;return}let t=e.getPose(this.inputSource.targetRaySpace,this.xr.referenceSpace);this._isTracking=t!=null;let n=null,r=null,i=null,a=null;if(t){let e=t.transform;this._rayMatrix.fromArray(e.matrix).premultiply(Iu),this._rayMatrix.decompose(this._rayPosition,this._rayQuaternion,P(1,1,1)),i=P(e.position),a=Tr(e.orientation),this._rayPositionRaw.copy(i),this._rayRotationRaw.copy(a)}if(this.inputSource.gripSpace){let t=e.getPose(this.inputSource.gripSpace,this.xr.referenceSpace);if(t){let e=t.transform;if(n=P(e.position),r=Tr(e.orientation),this._gripMatrix.fromArray(e.matrix).premultiply(Iu),this._gripMatrix.decompose(this._gripPosition,this._gripQuaternion,P(1,1,1)),`linearVelocity`in t&&t.linearVelocity){let e=t.linearVelocity;this._linearVelocity.set(e.x,e.y,e.z)}}}this.xr.context.mainCamera?.parent&&(this._object.parent!==this.xr.context.mainCamera?.parent&&this.xr.context.mainCamera.parent.add(this._object),this._gripSpaceObject!==void 0&&this._gripSpaceObject?.parent!==this.xr.context.mainCamera?.parent&&this.xr.context.mainCamera.parent.add(this._gripSpaceObject),this._raySpaceObject!==void 0&&this._raySpaceObject?.parent!==this.xr.context.mainCamera?.parent&&this.xr.context.mainCamera.parent.add(this._raySpaceObject));let o=this.hand;if(o){let t=!1,i=o.get(`wrist`),a=i&&this.getHandJointPose(i,e);if(a){t=!0;let e=a.transform.position,n=a.transform.orientation;this._object.position.set(e.x,e.y,e.z),this._object.quaternion.set(n.x,n.y,n.z,n.w).multiply(Lu)}t||(this._object.position.copy(this._rayPosition),this._object.quaternion.copy(this._rayQuaternion).multiply(Lu));let s=o.get(`middle-finger-metacarpal`),c=s&&this.getHandJointPose(s,e);c&&(this._gripMatrix.fromArray(c.transform.matrix).premultiply(Iu),this._gripMatrix.decompose(this._gripPosition,this._gripQuaternion,P(1,1,1)),n=P().copy(c.transform.position),r=Tr().copy(c.transform.orientation),r.multiply(Wu),n.add(P(Gu).applyQuaternion(r)))}else this.inputSource.gripSpace&&this.targetRayMode===`transient-pointer`&&n&&r?(this._object.position.copy(n),this._object.quaternion.copy(r).multiply(Lu)):i&&a&&(this._object.position.copy(i),this._object.quaternion.copy(a).multiply(Lu));Bu&&(i&&a&&(this._raySpaceObject?.position.copy(i),this._raySpaceObject?.quaternion.copy(a).multiply(Lu)),n&&r&&(this._gripSpaceObject?.position.copy(n),this._gripSpaceObject?.quaternion.copy(r).multiply(Lu)));let s=this.xr.context.mainCamera?.parent,c=s?Pr(s):void 0;n&&r&&(this._gripWorldPosition.copy(n),s&&this._gripWorldPosition.applyMatrix4(s.matrixWorld),this._gripWorldQuaternion.copy(r),this._gripWorldQuaternion.multiply(Lu),c&&this._gripWorldQuaternion.premultiply(c)),this.updateRayWorldPosition(),this.updateRayWorldQuaternion()}onDisconnected(){this._connected=!1,Bu&&console.warn(`Controller disconnected`,this.index);for(let e of this._object.children)this.xr.context.scene.attach(e);this._object?.removeFromParent(),this._debugAxesHelper?.removeFromParent(),this._debugGripAxesHelper?.removeFromParent(),this._debugRayAxesHelper?.removeFromParent(),this._gripSpaceObject?.removeFromParent(),this._raySpaceObject?.removeFromParent(),this.unsubscribeEvents(),this._hitTestSource&&=(this._hitTestSource.cancel(),void 0)}getButton(e){if(!this._layout)return;switch(e){case`primary-button`:if(this.isLeft)e=`x-button`;else if(this.isRight)e=`a-button`;else return;break;case`primary`:return this.hand?this.getGesture(`pinch`):this.toNeedleGamepadButton(0,e);case`xr-standard-trigger`:if(this.inputSource.gamepad)return this.toNeedleGamepadButton(0,e);break;case`xr-standard-squeeze`:if(this.inputSource.gamepad)return this.toNeedleGamepadButton(1,e);break;case`xr-standard-thumbstick`:if(this.inputSource.gamepad)return this.toNeedleGamepadButton(3,e);break}if(this._buttonMap.has(e))return this.toNeedleGamepadButton(this._buttonMap.get(e),e);let t=this._layout?.components[e];if(t?.gamepadIndices)switch(t.type){case`button`:case`squeeze`:if(this.inputSource.gamepad){let n=t.gamepadIndices.button;return this._buttonMap.set(e,n),this.toNeedleGamepadButton(n,e)}break;default:console.warn(`Unsupported component type`,t.type);break}this._buttonMap.set(e,void 0)}getGesture(e){let t=this.states[e];if(!t)return null;this.states[e]=t;let n=this._needleGamepadButtons[e]||new Ju(void 0,e);return n.pressed=t.pressed,n.value=t.value,n.isDown=t.isDown,n.isUp=t.isUp,this._needleGamepadButtons[e]=n,n}getPointerId(e){if((e===`primary`||e===`pinch`)&&(e=0),typeof e!=`number`){let t=this._buttonMap.get(e);if(t===void 0)return;e=t}return this.index*10+e}_needleGamepadButtons={};toNeedleGamepadButton(e,t){if(!this.inputSource.gamepad?.buttons)return;let n=this.inputSource.gamepad?.buttons[e],r=this.states[e],i=this._needleGamepadButtons[e]||new Ju(e,t);return n&&(i.pressed=n.pressed,i.value=n.value,i.touched=n.touched),r&&(i.isDown=r.isDown,i.isUp=r.isUp),this._needleGamepadButtons[e]=i,i}getStick(e){if(!this._layout||this.isHand)return{x:0,y:0,z:0};e===`primary`&&this._layout.components[`xr-standard-thumbstick`]&&(e=`xr-standard-thumbstick`);let t=this._layout?.components[e];if(t?.gamepadIndices)switch(t.type){case`thumbstick`:case`touchpad`:if(this.inputSource.gamepad){let e=t.gamepadIndices.xAxis,n=t.gamepadIndices.yAxis,r=this.inputSource.gamepad.axes[e]||0,i=this.inputSource.gamepad.axes[n]||0;r*=-1,i*=-1;let a=t.gamepadIndices.button,o=this.inputSource.gamepad?.buttons[a]?.value||0;return{x:r,y:i,z:o}}}return{x:0,y:0,z:0}}_buttonMap=new Map;_motioncontroller;_layout;getMotionController;initialize(){if(this._hasSelectEvent=this.profiles.includes(`generic-hand-select`)||this.profiles.some(e=>e.startsWith(`generic-trigger`)),this._isMetaQuestTouchController=this.profiles.includes(`meta-quest-touch-plus`)||this.profiles.includes(`oculus-touch-v3`),this._isMxInk=this.profiles.includes(`logitech-mx-ink`),!this._layout){if(this.inputSource.targetRayMode===`transient-pointer`)return;this.getMotionController=Au(this.inputSource,Hu,Uu).then(e=>{if(!this.connected)return null;if(this._motioncontroller=new Fu(this.inputSource,e.profile,e.assetPath||``),this._layout=e.profile.layouts[this.inputSource.handedness],this._layout){if(!this._layout.gamepad?.length){this._layout.gamepad=[];for(let e in this._layout.components){let t=this._layout.components[e];this._layout.gamepad[t.gamepadIndices.button]=e}}this.profiles.length>=1&&this.profiles[0]===`htc-vive-focus-plus`&&this.inputSource.gamepad&&this.inputSource.gamepad.axes.length===4&&!this._layout.components[`xr-standard-thumbstick`]&&(this._layout.components[`xr-standard-thumbstick`]={type:`thumbstick`,gamepadIndices:{xAxis:2,yAxis:3}})}return this._motioncontroller}).catch(e=>(this.inputSource&&console.warn(`Couldn't initialize motion controller profile for `,this.inputSource,e),null))}}emitPointerDownEvent=!0;emitPointerUpEvent=!0;emitPointerMoveEvent=!0;pointerMoveDistanceThreshold=.03;pointerMoveAngleThreshold=.05;subscribeEvents(){this.xr.session.addEventListener(`selectstart`,this.onSelectStart),this.xr.session.addEventListener(`selectend`,this.onSelectEnd),this.xr.session.addEventListener(`squeezestart`,this.onSequeezeStart),this.xr.session.addEventListener(`squeezeend`,this.onSequeezeEnd)}unsubscribeEvents(){this.xr.session.removeEventListener(`selectstart`,this.onSelectStart),this.xr.session.removeEventListener(`selectend`,this.onSelectEnd),this.xr.session.removeEventListener(`squeezestart`,this.onSequeezeStart),this.xr.session.removeEventListener(`squeezeend`,this.onSequeezeEnd)}_selectButtonIndex=void 0;_squeezeButtonIndex=void 0;onSelectStart=e=>{if(!this.emitPointerDownEvent||this.inputSource!==e.inputSource)return;this.onUpdateFrame(e.frame),this._hasSelectEvent=!0;let t=this._layout?.selectComponentId,n=this._layout?.components[t]?.gamepadIndices?.button;n!==void 0&&(this._selectButtonIndex=n),!Vu&&(Bu&&H.DrawDirection(this.rayWorldPosition,P(0,.01,1).applyQuaternion(this.rayWorldQuaternion),16711680,10),this.emitPointerEvent(L.PointerDown,this._selectButtonIndex||0,`xr-standard-trigger`,!0,e))};onSelectEnd=e=>{this.emitPointerUpEvent&&(Vu||this.inputSource===e.inputSource&&this.emitPointerEvent(L.PointerUp,this._selectButtonIndex||0,`xr-standard-trigger`,!0,e))};onSequeezeStart=e=>{this.emitPointerDownEvent&&this.inputSource===e.inputSource&&(this._squeezeButtonIndex=this._layout?.components[`xr-standard-squeeze`]?.gamepadIndices?.button,this._squeezeButtonIndex!==void 0&&(Bu&&H.DrawDirection(this.rayWorldPosition,P(0,.01,1).applyQuaternion(this.rayWorldQuaternion),255,10),this.emitPointerEvent(L.PointerDown,this._squeezeButtonIndex||0,`xr-standard-squeeze`,!0,e)))};onSequeezeEnd=e=>{this.emitPointerUpEvent&&this.inputSource===e.inputSource&&this._squeezeButtonIndex!==void 0&&this.emitPointerEvent(L.PointerUp,this._squeezeButtonIndex||0,`xr-standard-squeeze`,!0,e)};states={};updateInputEvents(){if(this.gamepad?.buttons){for(let e=0;e0&&!n.pressed?(r=`pointerdown`,n.isDown=!0,n.isUp=!1):t.value===0&&n.pressed?(r=`pointerup`,n.isDown=!1,n.isUp=!0):n.pressed&&(r=`pointermove`,n.isDown=!1,n.isUp=!1),n.pressed=t.value>0,n.value=t.value):(t.pressed&&!n.pressed?(r=`pointerdown`,n.isDown=!0,n.isUp=!1):!t.pressed&&n.pressed?(r=`pointerup`,n.isDown=!1,n.isUp=!0):(n.isDown=!1,n.isUp=!1),n.pressed=t.pressed,n.value=t.value),this.states[e]=n;let i=e!==this._selectButtonIndex&&e!==this._squeezeButtonIndex;if(r!=null&&i){let n=this._layout?.gamepad[e];this._isMxInk&&e===4&&(n=`stylus-touch`),this._isMxInk&&e===5&&(n=`stylus-tip`),(Bu||Vu)&&console.log(`Emitting pointer event`,r,e,n,t.value,this.gamepad,this._layout),this.emitPointerEvent(r,e,n??`none`,!1,null,t.value)}}if(this._isMetaQuestTouchController){let e=this.gamepad.buttons.length-1,t=this.states[e];if(t&&t.isDown){let e=this.context.menu;e.spatialMenuIsVisible?e.setSpatialMenuVisible(!1):this.context.menu.setSpatialMenuVisible(!0)}}}if(this.hand){let e=this.handObject;if(e){let t=e.joints[`index-finger-tip`],n=e.joints[`thumb-tip`];if(t&&n){let e=t.position.distanceTo(n.position);this._pinchPosition.lerpVectors(t.position,n.position,.5);let r=this.xr.context.mainCamera?.parent;if(r&&this._pinchPosition.applyMatrix4(r.matrixWorld),e!==0){let t=.02,n=.01,r=this.states.pinch||new qu,i=(t+n)*1.5;r.value=1-(e-t)/i;let a=et+n;a&&!r.pressed?(Vu&&console.log(`pinch start`,e),r.isDown=!0,r.isUp=!1,r.pressed=!0):o&&r.pressed?(r.isDown=!1,r.isUp=!0,r.pressed=!1):(r.isDown=!1,r.isUp=!1),this.states.pinch=r}}}}}_didMoveLastFrame=!1;_lastPointerMovePosition=new o;_lastPointerMoveQuaternion=new E;onUpdateMove(){if(!this.emitPointerMoveEvent)return;let e=!1;if(this._lastPointerMovePosition.distanceTo(this.gripWorldPosition)>this.pointerMoveDistanceThreshold*this.xr.rigScale&&(e=!0),e||this._lastPointerMoveQuaternion.angleTo(this.gripWorldQuaternion)>this.pointerMoveAngleThreshold&&(e=!0),e){this._didMoveLastFrame=!0,this._lastPointerMovePosition.copy(this.gripWorldPosition),this._lastPointerMoveQuaternion.copy(this.gripWorldQuaternion),Bu&&H.DrawLabel(this.rayWorldPosition.add(this.object.worldForward.multiplyScalar(.1)),`move`,.01);let e=this.xr.context.input.getFirstPressedButtonForPointer(this.index);e===void 0&&(e=0);let t=this.gamepad?.buttons[e]?.value;this.emitPointerEvent(`pointermove`,e,`none`,!1,null,t)}else this._didMoveLastFrame=!1}pointerInit;emitPointerEvent(e,t,n,r,i=null,a){if(!this.emitEvents){Bu&&e!==L.PointerMove&&console.warn(`Pointer events are disabled for this controller`,this.index,e,t);return}if(this.xr.mode===`immersive-vr`||this.xr.isPassThrough){this.pointerInit.origin=this,this.pointerInit.pointerId=this.getPointerId(t),this.pointerInit.pointerType=this.hand?`hand`:`controller`,this.pointerInit.button=t,this.pointerInit.buttonName=n,this.pointerInit.isPrimary=r,this.pointerInit.mode=this.inputSource.targetRayMode,this.pointerInit.ray=this.ray,this.pointerInit.device=this.object,this.pointerInit.pressure=a,this.pointerInit.clientX=this._rayPosition.x/this.xr.rigScale,this.pointerInit.clientY=this._rayPosition.y/this.xr.rigScale,this.pointerInit.clientZ=this._rayPosition.z/this.xr.rigScale;let o=B.Current;B.Current=this.xr.context,Bu&&e!==`pointermove`&&console.warn(`Pointer event`,e,t,n,{...this.pointerInit}),this.xr.context.input.createInputEvent(new ic(e,i,this.pointerInit)),B.Current=o}}},qu=class{isDown=!1;isUp=!1;pressed=!1;value=0},Ju=class{index;name;touched=!1;pressed=!1;value=0;isDown=!1;isUp=!1;constructor(e,t){this.index=e,this.name=t}},Yu=A(`debugwebxr`),Xu=class{controllerStates=[];userId;context;userStateEvtName;constructor(e,t){this.userId=e,this.context=t,this.userStateEvtName=`xr-sync-user-state-`+e,this.context.connection.beginListen(this.userStateEvtName,this.onReceivedControllerState)}dispose(){this.context.connection.stopListen(this.userStateEvtName,this.onReceivedControllerState)}onReceivedControllerState=e=>{Yu&&console.log(`XRSync: Received change for ${this.userId}: ${e.type} ${e.handedness}; tracked=${e.isTracking}`);let t=!1;for(let n=0;n=0;t--){let n=this.controllerStates[t],r=!1;for(let t=0;tt.index===e.index);if(t){let n=!1;n||=t.isTracking!=e.isTracking,n&&(t.isTracking=e.isTracking,this.context.connection.send(this.userStateEvtName,t))}else{let t={guid:this.userId+`-`+e.index,isTracking:e.isTracking,handedness:e.side,index:e.index,type:e.hand?`hand`:`controller`};this.controllerStates.push(t),this.context.connection.send(this.userStateEvtName,t),Yu&&console.log(`XRSync: ${t.type} ${t.handedness} added`,t.index)}}},Zu=class{hasState(e){return e?this._states.has(e):!1}isTracking(e,t){if(!e)return;let n=this._states.get(e);if(n)return n.controllerStates.find(e=>e.handedness===t)?.isTracking||!1}getDeviceType(e,t){if(!e)return;let n=this._states.get(e);if(n)return n.controllerStates.find(e=>e.handedness===t)?.type||`unknown`}context;constructor(e){this.context=e,this.context.connection.beginListen(Xc.JoinedRoom,this.onJoinedRoom),this.context.connection.beginListen(Xc.LeftRoom,this.onLeftRoom),this.context.connection.beginListen(Xc.UserJoinedRoom,this.onOtherUserJoinedRoom),this.context.connection.beginListen(Xc.UserLeftRoom,this.onOtherUserLeftRoom)}destroy(){this.context.connection.stopListen(Xc.JoinedRoom,this.onJoinedRoom),this.context.connection.stopListen(Xc.LeftRoom,this.onLeftRoom),this.context.connection.stopListen(Xc.UserJoinedRoom,this.onOtherUserJoinedRoom),this.context.connection.stopListen(Xc.UserLeftRoom,this.onOtherUserLeftRoom)}onJoinedRoom=()=>{if(this.context.connection.connectionId){this._states.has(this.context.connection.connectionId)||(Yu&&console.log(`XRSync: Local user joined room`,this.context.connection.connectionId),this._states.set(this.context.connection.connectionId,new Xu(this.context.connection.connectionId,this.context)));for(let e of this.context.connection.usersInRoom())this._states.has(e)||this._states.set(e,new Xu(e,this.context))}};onLeftRoom=()=>{this.context.connection.connectionId&&(this._states.has(this.context.connection.connectionId)||(this._states.get(this.context.connection.connectionId)?.dispose(),this._states.delete(this.context.connection.connectionId)))};onOtherUserJoinedRoom=e=>{let t=e.userId;this._states.has(t)||(Yu&&console.log(`XRSync: Remote user joined room`,t),this._states.set(t,new Xu(t,this.context)))};onOtherUserLeftRoom=e=>{let t=e.userId;this._states.has(t)||(this._states.get(t)?.dispose(),this._states.delete(t))};_states=new Map;onUpdate(e){this.context.connection.isConnected&&this.context.connection.connectionId&&this._states.get(this.context.connection.connectionId)?.update(e)}onExitXR(e){this.context.connection.isConnected&&this.context.connection.connectionId&&this._states.get(this.context.connection.connectionId)?.onExitXR(e)}},Qu=class{_fadeToColorQuad;_fadeToColorMaterial;constructor(){this._fadeToColorMaterial=new re({color:0,transparent:!0,depthTest:!1,fog:!1,side:2}),this._fadeToColorQuad=new x(new Ke(10,10),this._fadeToColorMaterial)}dispose(){this._fadeToColorQuad.geometry.dispose(),this._fadeToColorMaterial.dispose()}update(e,t){let n=this._fadeToColorQuad,r=this._fadeToColorMaterial;n.parent!==e&&r.opacity>0?e.add(n):r.opacity===0&&n.removeFromParent(),n.layers.set(2),n.material=this._fadeToColorMaterial,n.position.z=-1,n.renderOrder=1/0;let i=this._requestedFadeValue;r.opacity=N.lerp(r.opacity,i,t/.03),Math.abs(r.opacity-i)<=.01&&this._transitionResolve&&(this._transitionResolve(),this._transitionResolve=null,this._transitionPromise=null,this._requestedFadeValue=0)}remove(){this._fadeToColorQuad.removeFromParent()}fadeTransition(){if(this._transitionPromise)return this._transitionPromise;this._requestedFadeValue=1;let e=new Promise(e=>{this._transitionResolve=e});return this._transitionPromise=e,e}_requestedFadeValue=0;_transitionPromise=null;_transitionResolve=null},$u=class e{static _active=null;static get active(){return this._active}static _requestInFlight=!1;static async start(t,n){if(this._active)return console.error(`Cannot start a new XR session while one is already active`),null;if(this._requestInFlight)return console.error(`Cannot start a new XR session while a request is already in flight`),null;if(`xr`in navigator&&navigator.xr){if(!n)return console.error(`XRSessionInit must be provided`),null;this._requestInFlight=!0;let r=await navigator.xr.requestSession(t,n).catch(e=>{console.error(`Failed to start temporary XR session:`,e)});return r?(r.addEventListener(`end`,()=>{this._active=null}),this._requestInFlight?(this._requestInFlight=!1,this._active=new e(t,n,r),this._active):(r.end(),null)):(this._requestInFlight=!1,null)}return null}static async handoff(){return this._active?this._active.handoff():null}static async stop(){this._requestInFlight=!1,this._active&&(await this._active.end(),await Kt(100)),this._active=null}_session;_mode;_init;get isAR(){return this._mode===`immersive-ar`}get isVR(){return this._mode===`immersive-vr`}_renderer;_camera;_scene;constructor(e,t,n){this._mode=e,this._init=t,this._session=n,this._session.addEventListener(`end`,this.onEnd),this._renderer=new h({alpha:!0,antialias:!0}),this._renderer.outputColorSpace=`srgb`,this._renderer.setPixelRatio(Math.min(2,window.devicePixelRatio)),this._renderer.setSize(window.innerWidth,window.innerHeight,!0),j.isNeedleAppClip()&&window.requestAnimationFrame(()=>{let e=Math.min(2,window.devicePixelRatio),t=Math.floor(window.innerWidth*e),n=Math.floor(window.innerHeight*e);this._renderer.domElement.width=t,this._renderer.domElement.height=n}),this._renderer.setAnimationLoop(this.onFrame),this._renderer.xr.setSession(n),this._renderer.xr.enabled=!0,this._camera=new C,this._scene=new ne,this._scene.fog=new Be(4473924,10,250),this._scene.add(this._camera),this.setupScene()}end(){return this._session?this._session.end():Promise.resolve()}async handoff(){if(!this._session)throw Error(`Cannot handoff a session that has already ended`);let e={session:this._session,mode:this._mode,init:this._init};return await this.onBeforeHandoff(),this.onEnd(),this._session=null,e}onEnd=()=>{this._session?.removeEventListener(`end`,this.onEnd),this._renderer.setAnimationLoop(null),this._renderer.dispose(),this._scene.clear()};_lastTime=0;_frames=0;onFrame=(e,t)=>{let n=e-this._lastTime;this.update(e,n),this._camera.parent!==this._scene&&this._scene.add(this._camera),this._renderer.render(this._scene,this._camera),this._lastTime=e,this._frames++};_roomFlyObjects=[];_logoObject=null;get _logoDistance(){return this.isAR?.3:5}get _logoScale(){return this.isAR?.04:1}update(e,t){let n=e*4e-4;for(let e=0;e{if(!r)return;t.material.opacity=1;let a=1024;n.width=a,n.height=a,r.imageSmoothingQuality=`high`;let o=a*.19,s=e?1:i.width/i.height;if(!e){let e=n.height-o*1.5,t=e*s,a=(n.width-t)/2;r.drawImage(i,a,0,t,e)}let c=a*.12,l=`Loading...`;r.shadowBlur=0,r.fillStyle=this.isAR?`white`:`rgba(255,255,255,0.4)`,r.font=`${c}px Arial`,r.shadowBlur=a*.02,r.shadowColor=`rgba(0,0,0,0.5)`,r.shadowOffsetX=0,r.shadowOffsetY=0;let u=r.measureText(l);r.fillText(l,n.width/2-u.width/2,n.height-o/4),r.font=`${c}px Arial`,r.fillText(l,n.width/2-u.width/2,n.height-o/4);let d=new me().load(n.toDataURL());d.generateMipmaps=!0,d.colorSpace=`srgb`,d.anisotropy=4;let f=n.width/n.height;t.scale.x=this._logoScale*f*window.devicePixelRatio,t.scale.y=this._logoScale*window.devicePixelRatio,t.material.map=d,t.material.needsUpdate=!0};i.onload=()=>o(!1),i.onerror=t=>{console.error(`Failed to load temporary XR logo:`,e,t),i.src=Wl},i.crossOrigin=`anonymous`,i.src=e;let s=new ue(16777215,1);s.position.set(0,20,0),s.castShadow=!1,this._scene.add(s);let c=new ue(16777215,1);c.position.set(0,-1,0),c.castShadow=!1,this._scene.add(c);let l=new Ze(16777215,1,100,1);if(l.position.set(0,2,0),l.castShadow=!1,l.distance=200,this._scene.add(l),this.isAR===!1)for(let e=0;e<100;e++){let e=new Ce({color:2236962,metalness:1,roughness:.8}),t=Gs.Sphere,n=Ks.createPrimitive(t,{material:e});n.position.x=N.random(-50,50),n.position.y=N.random(-2,50),n.position.z=N.random(-50,50),n.rotation.x=N.random(0,Math.PI*2),n.rotation.y=N.random(0,Math.PI*2),n.rotation.z=N.random(0,Math.PI*2),n.scale.multiplyScalar(.5+Math.random()*10);let r=n.position.distanceTo(this._camera.position)-n.scale.x;r<10&&(n.position.z+=5,n.position.multiplyScalar(1+1/r)),this._roomFlyObjects.push(n),this._scene.add(n)}}},ed;(function(e){let t=[];function n(){t?.length||M()&&console.warn(`No USDZ exporters found – cannot export USDZ for QuickLook.`);for(let e of t)e.exportAndOpen();return!0}e.exportAndOpen=n;function r(e){t.push(e)}e.registerExporter=r;function i(e){if(!t)return;let n=t.indexOf(e);n>=0&&t.splice(n,1)}e.unregisterExporter=i})(ed||={});var V=A(`debugwebxr`),td=A(`stats`),nd=0;function rd(e){let t=null,n=e;return t=n.getAROverlayContainer?n.getAROverlayContainer():e,t}id();async function id(){let e=`immersive-vr`;try{if(j.isNeedleAppClip()?e=`immersive-ar`:await navigator.xr?.isSessionSupported(`immersive-vr`)||(e=`immersive-ar`),!await navigator.xr?.isSessionSupported(`immersive-ar`)&&e===`immersive-ar`)return}catch(e){console.debug(`[NeedleXRSession:granted] Error while checking XR support:`,e);return}if(A(`debugasap`)){let t=globalThis[`needle:XRSession`];if(t instanceof Promise){delete globalThis[`needle:XRSession`],k.addContextCreatedCallback(async n=>{if(!t)return;_i(!0);let r=await t;if(r){let t=pd.getDefaultSessionInit(e);pd.setSession(e,r,t,n.context)}else console.error(`[NeedleXRSession:granted] ASAP session was rejected`);t=void 0});return}}if(`xr`in navigator){if(/WebXRViewer\//i.test(navigator.userAgent)){console.warn(`WebXRViewer does not support addEventListener`);return}navigator.xr?.addEventListener(`sessiongranted`,async()=>{let t=sessionStorage.getItem(`needle_xr_session_mode`),n=sessionStorage.getItem(`needle_xr_session_init`)??null,r=n?JSON.parse(n):null,i=null;if(cd()&&(await $u.start(t||e,r||pd.getDefaultSessionInit(e)).catch(e=>console.warn(`[NeedleXRSession:granted] TemporaryXRContext start failed:`,e)),await ld(),i=await $u.handoff()),i)pd.setSession(i.mode,i.session,i.init,B.Current);else if(t&&n){console.log(`[NeedleXRSession:granted] Restore last session`);let e=JSON.parse(n);pd.start(t,e).catch(e=>console.warn(e))}else pd.start(e).catch(e=>console.warn(`[NeedleXRSession:granted] failed:`,e))},{once:!0})}}function ad(e,t){sessionStorage.setItem(`needle_xr_session_mode`,e),sessionStorage.setItem(`needle_xr_session_init`,JSON.stringify(t))}function od(){sessionStorage.removeItem(`needle_xr_session_mode`),sessionStorage.removeItem(`needle_xr_session_init`)}var sd=new Set;k.registerCallback(O.ContextCreationStart,async e=>{sd.add(e.context)}),k.registerCallback(O.ContextCreated,async e=>{sd.delete(e.context),ud(e.context?.domElement.getAttribute(`autostart`)||null)});function cd(){return sd.size>0}function ld(){return new Promise(e=>{let t=Date.now(),n=setInterval(()=>{(!cd()||Date.now()-t>6e4)&&(clearInterval(n),e())},100)})}j.isDesktop()&&M()&&window.addEventListener(`keydown`,e=>{(e.key===`x`||e.key===`Escape`)&&pd.active&&pd.stop()});function ud(e){if(e)switch(e?.toLowerCase()){case`ar`:Vs.registerWaitForInteraction(()=>{pd.start(`ar`)});break}}var dd=Symbol(`initial-fov`),fd=Symbol(`initial-near`),pd=class e{static _sync=null;static getXRSync(e){return this._sync||=new Zu(e),this._sync}static get currentSessionRequest(){return this._currentSessionRequestMode}static _currentSessionRequestMode=null;static get active(){return this._activeSession}static get activeMode(){return this._activeSession?.mode??null}static get xrSystem(){return`xr`in navigator?navigator.xr:void 0}static isXRSupported(){return Promise.all([this.isVRSupported(),this.isARSupported()]).then(e=>e.some(e=>e)).catch(()=>!1)}static isVRSupported(){return this.isSessionSupported(`immersive-vr`)}static isARSupported(){return this.isSessionSupported(`immersive-ar`)}static isSessionSupported(e){return this.xrSystem?.isSessionSupported(e).catch(e=>(V&&console.error(e),!1))??Promise.resolve(!1)}static _currentSessionRequest;static _activeSession;static onSessionRequestStart(e){this._sessionRequestStartListeners.push(e)}static offSessionRequestStart(e){let t=this._sessionRequestStartListeners.indexOf(e);t>=0&&this._sessionRequestStartListeners.splice(t,1)}static _sessionRequestStartListeners=[];static onSessionRequestEnd(e){this._sessionRequestEndListeners.push(e)}static offSessionRequestEnd(e){let t=this._sessionRequestEndListeners.indexOf(e);t>=0&&this._sessionRequestEndListeners.splice(t,1)}static _sessionRequestEndListeners=[];static onXRSessionStart(e){this._xrStartListeners.push(e)}static offXRSessionStart(e){let t=this._xrStartListeners.indexOf(e);t>=0&&this._xrStartListeners.splice(t,1)}static _xrStartListeners=[];static onXRSessionEnd(e){this._xrEndListeners.push(e)}static offXRSessionEnd(e){let t=this._xrEndListeners.indexOf(e);t>=0&&this._xrEndListeners.splice(t,1)}static _xrEndListeners=[];static onControllerAdded(e){this._controllerAddedListeners.push(e)}static offControllerAdded(e){let t=this._controllerAddedListeners.indexOf(e);t>=0&&this._controllerAddedListeners.splice(t,1)}static _controllerAddedListeners=[];static onControllerRemoved(e){this._controllerRemovedListeners.push(e)}static offControllerRemoved(e){let t=this._controllerRemovedListeners.indexOf(e);t>=0&&this._controllerRemovedListeners.splice(t,1)}static _controllerRemovedListeners=[];static offerSession(t,n,r){return`xr`in navigator&&navigator.xr&&`offerSession`in navigator.xr?(typeof navigator.xr.offerSession==`function`&&(console.log(`WebXR offerSession is available - requesting mode: `+t),n==`default`&&(n=this.getDefaultSessionInit(t)),navigator.xr.offerSession(t,{...n}).then(i=>e.setSession(t,i,n,r)).catch(e=>{console.log(`XRSession offer rejected (perhaps because another call to offerSession was made or a call to requestSession was made)`)})),!0):!1}static getDefaultSessionInit(e){switch(e){case`immersive-ar`:let t=[`anchors`,`local-floor`,`layers`,`dom-overlay`,`hit-test`,`unbounded`];return j.isVisionOS()||t.push(`hand-tracking`),{optionalFeatures:t};case`immersive-vr`:let n=[`local-floor`,`bounded-floor`,`high-fixed-foveation-level`,`layers`];return j.isVisionOS()||n.push(`hand-tracking`),{optionalFeatures:n};default:return console.warn(`No default session init for mode`,e),{}}}static async start(t,n,r){if(n||={},j.isiOS()){let e=await this.isARSupported().catch(()=>!1);if(j.isVisionOS()&&!e&&(t===`ar`||t===`immersive-ar`)&&(t=`quicklook`),t===`quicklook`)return $a.sendEvent(B.Current,`xr`,{action:`quicklook_export`,source:`NeedleXRSession.start`}),ed.exportAndOpen(),null;if(!e&&(t===`immersive-ar`||t===`ar`)){this.invokeSessionRequestStart(`immersive-ar`,n);let e=new URL(`https://appclip.apple.com/id?p=tools.needle.launch-app.Clip`);e.searchParams.set(`url`,location.href);let r=e.toString();$a.sendEvent(B.Current,`xr`,{action:`app_clip_launch`,source:`NeedleXRSession.start`,url:r});let i=window.top||window;try{console.debug(`iOS device detected - opening Needle App Clip for AR experience`,{mode:t,init:n,url:e}),i.location.href=r}catch(e){console.warn(`Error navigating to AppClip `+r+` `,e),window===window.top?window.location.href=r:window.open(r,`_blank`)}return setTimeout(()=>{this.invokeSessionRequestEnd(`immersive-ar`,n||{},null)},3e3),null}}if(t===`quicklook`)return console.warn(`QuickLook mode is only supported on iOS devices`),null;if(t==`ar`&&(t=`immersive-ar`),M()&&A(`debugxrpreroom`))return console.warn(`Debug: Starting temporary XR session`),await $u.start(t,n||e.getDefaultSessionInit(t)),null;if(this._currentSessionRequest)return console.warn(`A XRSession is already being requested`),(V||M())&&Ei(`A XRSession is already being requested`),this._currentSessionRequest.then(()=>this._activeSession);if(this._activeSession)return console.error(`A XRSession is already running`),this._activeSession;if(r||=B.Current,r||=k.All[0],!r)throw Error(`No Needle Engine Context found`);switch(t){case`immersive-ar`:{if(await this.xrSystem?.isSessionSupported(`immersive-ar`)!==!0)return console.error(t+` is not supported by this browser.`),null;let e=this.getDefaultSessionInit(t),i=rd(r.domElement);i&&!j.isQuest()&&(e.domOverlay={root:i},e.optionalFeatures.push(`dom-overlay`)),n={...e,...n}}break;case`immersive-vr`:if(await this.xrSystem?.isSessionSupported(`immersive-vr`)!==!0)return console.error(t+` is not supported by this browser.`),null;n={...this.getDefaultSessionInit(t),...n};break;default:console.warn(`No default session init for mode`,t);break}n.optionalFeatures??=[],n.requiredFeatures??=[],await $u.stop();let i=t==`immersive-ar`?r.scripts_immersive_ar:r.scripts_immersive_vr;V?console.log(`%cRequesting ${t} session`,`font-weight:bold;`,n,i):console.log(`%cRequesting ${t} session`,`font-weight:bold;`);for(let e of i)e.onBeforeXR&&e.activeAndEnabled&&!e.destroyed&&e.onBeforeXR(t,n);this.invokeSessionRequestStart(t,n),V&&Ti(`Requesting `+t+` session (`+Date.now()+`)`),$a.sendEvent(B.Current,`xr`,{action:`session_request`,mode:t,features:(n.requiredFeatures??[]).concat(n.optionalFeatures??[]).join(`,`),source:`NeedleXRSession.start`}),this._currentSessionRequest=navigator?.xr?.requestSession(t,n),this._currentSessionRequestMode=t;let a=await this._currentSessionRequest?.catch(e=>{console.error(e,`Code: `+e?.code),e?.code===9&&Ei(`Couldn't start XR session. Make sure you allow the required permissions.`),console.log(`If the specified XR configuration is not supported (e.g. entering AR doesnt work) - make sure you access the website on a secure connection (HTTPS) and your device has the required permissions (e.g. camera access)`),location.protocol===`http:`&&Ei(`XR requires a secure connection (HTTPS)`)});return this._currentSessionRequest=void 0,this._currentSessionRequestMode=null,this.invokeSessionRequestEnd(t,n,a),a?this.setSession(t,a,n,r):(console.warn(`XR Session request was rejected`),null)}static invokeSessionRequestStart(e,t){for(let n of this._sessionRequestStartListeners)n({mode:e,init:t})}static invokeSessionRequestEnd(e,t,n){for(let r of this._sessionRequestEndListeners)r({mode:e,init:t,newSession:n||null})}static setSession(t,n,r,i){if(this._activeSession)return console.error(`A XRSession is already running`),this._activeSession;let a=t==`immersive-ar`?i.scripts_immersive_ar:i.scripts_immersive_vr;return this._activeSession=new e(t,n,i,{scripts:a,controller_added:this._controllerAddedListeners,controller_removed:this._controllerRemovedListeners,init:r}),n.addEventListener(`end`,this.onEnd),V?console.log(`%cStarted ${t} session`,`font-weight:bold;`,a):console.log(`%cStarted ${t} session`,`font-weight:bold;`),this._activeSession}static $_stop_request=Symbol();static stop(){let e=this._activeSession;e&&(e[this.$_stop_request]===void 0?(V&&console.log(`[NeedleXRSession] Stopping XR Session... (new)`),e[this.$_stop_request]=setTimeout(()=>{e.end()})):V&&console.warn(`[NeedleXRSession] XR Session stop already requested`))}static onEnd=()=>{V&&console.log(`XR Session ended`),this._activeSession=null};context;get sync(){return e._sync}get running(){return!this._ended&&this.session!=null}session;mode;get interactionMode(){return this.session.interactionMode}get visibilityState(){return this.session.visibilityState}get isVisibleBlurred(){return this.session.visibilityState===`visible-blurred`}get isSystemKeyboardSupported(){return this.session.isSystemKeyboardSupported}get environmentBlendMode(){return this.session.environmentBlendMode}get frame(){return this.context.xrFrame}controllers=[];get leftController(){return this.controllers.find(e=>e.side===`left`)}get rightController(){return this.controllers.find(e=>e.side===`right`)}getController(e){return typeof e==`number`?this.controllers[e]||null:this.controllers.find(t=>t.side===e)||null}get isPassThrough(){return!!(this.environmentBlendMode!==`opaque`&&this.interactionMode===`world-space`||this.mode===`immersive-ar`&&this.environmentBlendMode!==`opaque`&&this.controllers.some(e=>e.inputSource.targetRayMode===`tracked-pointer`)||M()&&j.isDesktop()&&this.mode===`immersive-ar`)}get isAR(){return this.mode===`immersive-ar`}get isVR(){return this.mode===`immersive-vr`}get isScreenBasedAR(){return this.isAR&&!this.isPassThrough}get posePosition(){return this._transformPosition}get poseOrientation(){return this._transformOrientation}get referenceSpace(){return this.context.renderer.xr.getReferenceSpace()}get viewerPose(){return this._viewerPose}get isTrackingImages(){if(this.frame&&`getImageTrackingResults`in this.frame&&typeof this.frame.getImageTrackingResults==`function`)try{let e=this.frame.getImageTrackingResults();for(let t of e)if(t.trackingState===`tracked`)return!0}catch{return!1}return!1}get rig(){let e=this._rigs[0]??null;return e?.gameObject&&Nf(e.gameObject)||e?.isActive===!1?(this.updateActiveXRRig(),this._rigs[0]??null):e}_rigScale=1;_lastRigScaleUpdate=-1;get rigScale(){return this._rigs[0]?(this._lastRigScaleUpdate!==this.context.time.frame&&(this._lastRigScaleUpdate=this.context.time.frame,this._rigScale=this._rigs[0].gameObject.worldScale.x),this._rigScale):1}addRig(e){this._rigs.indexOf(e)>=0||(e.priority===void 0&&(e.priority=0),this._rigs.push(e),this.updateActiveXRRig())}removeRig(e){let t=this._rigs.indexOf(e);t!==-1&&(this._rigs.splice(t,1),this.updateActiveXRRig())}setRigActive(e){let t=this._rigs.indexOf(e),n=this._rigs[0];this._rigs.splice(t,1),this._rigs.unshift(e),e.priority=n?.priority??0,this.updateActiveXRRig()}getUserOffsetInRig(){let e=this.context.mainCamera?.position;if(!e||!this.rig)return P(0,0,0);let t=P(e);return t.x*=-1,t.z*=-1,t.applyQuaternion(Tr(this.rig.gameObject.quaternion)),t}updateActiveXRRig(){let e=this._rigs[0]??null;this._defaultRig.gameObject.parent!==this.context.scene&&this.context.scene.add(this._defaultRig.gameObject),this._defaultRig.gameObject.visible=!0,this._rigs.includes(this._defaultRig)||this._rigs.push(this._defaultRig);let t=this._rigs[0];t&&t.priority===void 0&&(t.priority=0);for(let e=1;et.priority)&&(t=n)}}if(e!==t){let e=this._rigs.indexOf(t);e>=0&&this._rigs.splice(e,1),this._rigs.unshift(t)}V&&(e===t?console.log(`Updated Active XR Rig:`,t,`prev:`,e):console.log(`Updated Active XRRig:`,t,` (the same as before)`))}_rigs=[];_viewerHitTestSource=null;getHitTest(e){if(e)return this.getControllerHitTest(e);if(!this._viewerHitTestSource)return null;let t=this._viewerHitTestSource,n=this.frame.getHitTestResults(t);if(n.length>0){let e=n[0];return this.convertHitTestResult(e)}return null}getControllerHitTest(e){let t=e.getHitTestSource();if(!t)return null;let n=this.frame.getHitTestResultsForTransientInput(t);for(let t of n)if(t.inputSource===e.inputSource)for(let e of t.results)return this.convertHitTestResult(e);return null}convertHitTestResult(e){let t=this.context.renderer.xr.getReferenceSpace(),n=t&&e.getPose(t);if(n){let t=P(n.transform.position),r=Tr(n.transform.orientation),i=this.context.mainCamera;if(i?.parent!==this._cameraRenderParent&&t.applyMatrix4(Iu),i?.parent){t.applyMatrix4(i.parent.matrixWorld),r.multiply(Lu);let e=Pr(i.parent);e.premultiply(Lu),r.premultiply(e)}return{hit:e,position:t,quaternion:r}}return null}convertSpace(e){let t=P(e.position);t.applyMatrix4(Iu);let n=Tr(e.orientation);return n.premultiply(Lu),{position:t,quaternion:n}}_defaultRig;_xr_scripts;_xr_update_scripts=[];_inactive_scripts=[];_controllerAdded;_controllerRemoved;_originalCameraWorldPosition;_originalCameraWorldRotation;_originalCameraWorldScale;_originalCameraParent;_mainCamera=null;constructor(e,t,n,r){ad(e,r.init),this.session=t,this.mode=e,this.context=n,(V||A(`console`))&&_i(!0),this._xr_scripts=[...r.scripts],this._xr_update_scripts=this._xr_scripts.filter(e=>typeof e.onUpdateXR==`function`),this._controllerAdded=r.controller_added,this._controllerRemoved=r.controller_removed,ka(this.onBefore,z.LateUpdate),this.context.pre_render_callbacks.push(this.onBeforeRender),this.context.post_render_callbacks.push(this.onAfterRender),(r.init.optionalFeatures?.includes(`hit-test`)||r.init.requiredFeatures?.includes(`hit-test`))&&t.requestReferenceSpace(`viewer`).then(e=>t.requestHitTestSource?.call(t,{space:e})?.then(e=>this._viewerHitTestSource=e).catch(e=>console.error(e))).catch(e=>console.error(e)),this.context.mainCamera&&(this._originalCameraWorldPosition=Or(this.context.mainCamera,new o),this._originalCameraWorldRotation=Pr(this.context.mainCamera,new E),this._originalCameraWorldScale=zr(this.context.mainCamera,new o),this._originalCameraParent=this.context.mainCamera.parent,this.context.mainCamera instanceof C&&(this.context.mainCamera[dd]=this.context.mainCamera.fov)),this._defaultRig=new zu,this.context.scene.add(this._defaultRig.gameObject),this.addRig(this._defaultRig);for(let e=0;e{for(let t of e.removed)this.disconnectInputSource(t);for(let t of e.added)this.onInputSourceAdded(t)}),this.context.xr=this,this.context.renderer.xr.setSession(this.session).then(this.onRendererSessionSet),`controllerAutoUpdate`in this.context.renderer.xr?(console.debug(`Disabling three.js controllerAutoUpdate`),this.context.renderer.xr.controllerAutoUpdate=!1):V&&console.warn(`controllerAutoUpdate is not available in three.js - cannot disable it`),j.isNeedleAppClip()&&window.requestAnimationFrame(()=>{let e=this.context.renderer.domElement,t=window.devicePixelRatio||1,n=e.width,r=e.height,i=Math.floor(window.innerWidth*t),a=Math.floor(window.innerHeight*t);(Math.abs(n-i)>2||Math.abs(r-a)>2)&&(e.width=i,e.height=a,console.debug(`Applied DPR scaling for Needle AppClip XR session`,t,e.width,e.height))})}onRendererSessionSet=()=>{this.running&&(this.context.renderer.xr.enabled=!0,this.context.renderer.xr.updateCamera(this.context.mainCamera),this.context.mainCameraComponent?.applyClearFlags())};onInputSourceAdded=e=>{if(e.targetRayMode===`screen`)return;let t=0;for(let n=0;nt.inputSource===e)){console.debug(`Controller already exists for input source`,t);return}else if(this._newControllers.find(t=>t.inputSource===e)){console.debug(`Controller already registered for input source`,t);return}let n=new Ku(this,e,t);this._newControllers.push(n)};disconnectInputSource(e){let t=(t,n)=>{if(t.inputSource===e){V&&console.log(`Disconnecting controller`,t.index);let e=n.indexOf(t);e>=0&&n.splice(e,1),this.invokeControllerEvent(t,this._controllerRemoved,`removed`);let r={xr:this,controller:t,change:`removed`};for(let e of this._xr_scripts)e.onXRControllerRemoved&&e.onXRControllerRemoved(r);t.onDisconnected()}},n=[...this.controllers];for(let e=n.length-1;e>=0;e--){let r=n[e];t(r,this.controllers)}let r=[...this._newControllers];for(let e=r.length-1;e>=0;e--){let n=r[e];t(n,this._newControllers)}}end(){this._ended||this.session.end().catch(e=>console.warn(e))}_ended=!1;_newControllers=[];onEnd=t=>{if(this._ended)return;this._ended=!0,console.debug(`XR Session ended`),$a.sendEvent(B.Current,`xr`,{action:`session_end`,mode:this.mode,source:`NeedleXRSession.onEnd`}),od(),this.onAfterRender(),this.revertCustomForward(),this._didStart=!1,this._previousCameraParent=null,this.requestedCameraNearPlane=null,Aa(this.onBefore,z.LateUpdate);let n=this.context.pre_render_callbacks.indexOf(this.onBeforeRender);n>=0&&this.context.pre_render_callbacks.splice(n,1);let r=this.context.post_render_callbacks.indexOf(this.onAfterRender);r>=0&&this.context.post_render_callbacks.splice(r,1),this.context.xr=null,this.context.renderer.xr.enabled=!1,this.context.pre_update_oneshot_callbacks.push(()=>{this.context.mainCameraComponent?.applyClearFlags(),this.context.mainCameraComponent?.applyClippingPlane()}),Ul({session:this});for(let t of e._xrEndListeners)t({xr:this});let i=[...this.controllers];for(let e=0;e{let n=t.xrFrame;if(!n)return;this.context.xr=this,this.context.mainCameraComponent&&this.context.mainCameraComponent!==this._mainCamera&&(this._mainCamera=this.context.mainCameraComponent),this.rig?.isActive==0&&(V&&console.warn(`Latest rig is not active - trying to activate a different rig`,this.rig),this.updateActiveXRRig()),this.rig&&this._mainCamera?.gameObject&&this._mainCamera?.gameObject?.parent!==this.rig.gameObject&&this.rig.gameObject.add(this._mainCamera?.gameObject),this.internalUpdateState(),this.applyCustomForward();let r={xr:this};if(!this._didStart){if(this._didStart=!0,this.mode===`immersive-vr`){let e=fi(this.context.scene.children);if(e){let t=e.getSize(P());if(t.length()>0){let n=this._defaultRig.gameObject;n.position.set(e.min.x+t.x*.5,e.min.y,e.max.z+t.z*.5+1.5);let r=e.getCenter(P());r.y=n.position.y,n.lookAt(r)}}}Hl({session:this}),Bs();for(let t of e._xrStartListeners)t(r);let t=[...this._xr_scripts];V&&console.log(`NeedleXRSession start, handle scripts:`,t);for(let e of t){if(e.destroyed){this._script_to_remove.push(e);continue}if(!e.activeAndEnabled){this.markInactive(e);continue}this.invokeCallback_EnterXR(e);for(let t of this.controllers)this.invokeCallback_ControllerAdded(e,t)}}else if(this.context.new_scripts_xr.length>0){let e=[...this.context.new_scripts_xr];for(let t=0;t0){let e=[...this._newControllers];this._newControllers.length=0;for(let t of e){if(!t.connected){console.warn(`New controller is not connected`,t);continue}this.controllers.push(t);for(let e of this._xr_scripts){if(e.destroyed){this._script_to_remove.push(e);continue}e.activeAndEnabled!==!1&&this.invokeCallback_ControllerAdded(e,t)}}this.controllers.sort((e,t)=>e.index-t.index)}V&&this.context.time.frame%30==0&&this.controllers.length<=0&&this.session.inputSources.length>0&&(_i(!0),console.error(`XRControllers are not added but inputSources are present`));for(let e of this._xr_update_scripts){if(e.destroyed===!0){this._script_to_remove.push(e);continue}if(e.activeAndEnabled===!1){this.markInactive(e);continue}e.onUpdateXR&&e.onUpdateXR(r)}if(this.handleInactiveScripts(),this._script_to_remove.length>0){let e=[...new Set(this._script_to_remove)];this._script_to_remove.length=0;for(let t of e)!t.destroyed&&this.running&&t.onLeaveXR?.(r),this.removeScript(t)}this.sync?.onUpdate(this),this.onRenderDebug()};onRenderDebug(){if(V)for(let e of this.controllers)e.onRenderDebug();if((V||td)&&this.rig&&(nd++,nd>=20)){let e=this.rig.gameObject.worldPosition,t=this.rig.gameObject.worldForward;e.add(t.multiplyScalar(1.5));let n=this.rig.gameObject.worldUp;e.add(n.multiplyScalar(2.5));let r=``;if(r+=`${this.context.time.smoothedFps.toFixed(0)} FPS`,r+=`, calls: ${this.context.renderer.info.render.calls}, tris: ${this.context.renderer.info.render.triangles.toLocaleString()}`,V||td)for(let e of this.controllers)r+=`\n${e.hand?`hand`:`ctrl`} ${e.inputSource.handedness}[${e.index}] con:${e.connected} tr:${e.isTracking} hts:${e.hasHitTestSource?`yes`:`no`}`;nd=0,H.DrawLabel(e,r,void 0,1/60*20)}}onBeforeRender=()=>{this.context.mainCamera&&(this.updateFade(this.context.mainCamera),this.requestedCameraNearPlane!==null&&this.context.mainCamera instanceof C&&(this.context.mainCamera.near=this.requestedCameraNearPlane,this.requestedCameraNearPlane=null))};onAfterRender=()=>{if(this.onUpdateFade_PostRender(),j.isDesktop()||!this._renderOnceOnDevice){let e=this.context.renderer;if(e.xr.isPresenting&&this.context.mainCamera){this._renderOnceOnDevice=!0;let t=e.xr.enabled,n=e.getRenderTarget(),r=this.context.scene.background;e.xr.enabled=!1,e.setRenderTarget(null),this.isPassThrough&&(this.context.scene.background=null),this.context.composer?this.context.composer.render(this.context.time.deltaTime):e.render(this.context.scene,this.context.mainCamera),e.xr.enabled=t,e.setRenderTarget(n),this.context.scene.background=r}}};addScript(e){return this._xr_scripts.includes(e)?!1:(V&&console.log(`Register new XRScript`,e),this._xr_scripts.push(e),typeof e.onUpdateXR==`function`&&this._xr_update_scripts.push(e),!0)}markInactive(e){if(!(this._inactive_scripts.indexOf(e)>=0)){this.removeScript(e,!1),this._inactive_scripts.push(e);for(let t of this.controllers)this.invokeCallback_ControllerRemoved(e,t);this.invokeCallback_LeaveXR(e)}}handleInactiveScripts(){if(this._inactive_scripts.length>0)for(let e=this._inactive_scripts.length-1;e>=0;e--){let t=this._inactive_scripts[e];if(t.activeAndEnabled){this._inactive_scripts.splice(e,1),this.addScript(t),this.invokeCallback_EnterXR(t);for(let e of this.controllers)this.invokeCallback_ControllerAdded(t,e)}}}_script_to_remove=[];removeScript(e,t=!0){V&&console.log(`Remove XRScript`,e);let n=this._xr_scripts.indexOf(e);n>=0&&this._xr_scripts.splice(n,1);let r=this._xr_update_scripts.indexOf(e);if(r>=0&&this._xr_update_scripts.splice(r,1),t){let t=this._inactive_scripts.indexOf(e);t>=0&&this._inactive_scripts.splice(t,1)}}invokeCallback_EnterXR(e){e.onEnterXR&&e.onEnterXR({xr:this})}invokeCallback_ControllerAdded(e,t){e.onXRControllerAdded&&e.onXRControllerAdded({xr:this,controller:t,change:`added`})}invokeCallback_ControllerRemoved(e,t){e.onXRControllerRemoved&&e.onXRControllerRemoved({xr:this,controller:t,change:`removed`})}invokeCallback_LeaveXR(e){e.onLeaveXR&&!e.destroyed&&e.onLeaveXR({xr:this})}syncCameraCullingMask(){let e=this.context.xrCamera,t=this.context.mainCameraComponent?.cullingMask;if(e&&t!==void 0){for(let n of e.cameras)n.layers.mask=t;e.layers.mask=t}else if(e){for(let t of e.cameras)t.layers.enableAll();e.layers.enableAll()}}invokeControllerEvent(e,t,n){for(let r=t.length-1;r>=0;r--){let i=t[r];if(i)try{i({xr:this,controller:e,change:n})}catch(e){console.error(e)}}}_camera;_cameraRenderParent=new S().rotateY(Math.PI);_previousCameraParent;_customforward=!0;originalCameraNearPlane;requestedCameraNearPlane=null;applyCustomForward(){if(this.context.mainCamera&&this._customforward){this._camera=this.context.mainCamera,this._camera.parent!==this._cameraRenderParent&&(this._previousCameraParent=this._camera.parent,this._previousCameraParent?.add(this._cameraRenderParent)),this._cameraRenderParent.name=`XR Camera Render Parent`,this._cameraRenderParent.add(this._camera);{let e=.02;if(this.rig){let t=zr(this.rig.gameObject);e*=t.x}this._camera instanceof C&&Math.abs(this._camera.near-e)>.001&&(this.isAR?this.originalCameraNearPlane=this._camera.near:this._camera.near=e,V&&console.debug(`Setting camera near plane to ${e} (was ${this.originalCameraNearPlane}) to account for XR rendering scale`))}}}revertCustomForward(){this._camera&&this._previousCameraParent&&this._previousCameraParent.add(this._camera),this._previousCameraParent=null,this._camera instanceof C&&this.originalCameraNearPlane!=null&&(this._camera.near=this.originalCameraNearPlane,this.originalCameraNearPlane=void 0)}_viewerPose;_transformOrientation=new E;_transformPosition=new o;internalUpdateState(){let e=this.context.renderer.xr.getReferenceSpace();if(!e){this._viewerPose=void 0;return}if(this._viewerPose=this.frame.getViewerPose(e),this._viewerPose){let e=this._viewerPose.transform;this._transformPosition.set(e.position.x,e.position.y,e.position.z),this._transformOrientation.set(e.orientation.x,e.orientation.y,e.orientation.z,e.orientation.w)}}_transition;get transition(){return this._transition||=new Qu,this._transition}fadeTransition(){return this._transition||=new Qu,this._transition.fadeTransition()}updateFade(e){this._transition&&e instanceof C&&this._transition.update(e,this.context.time.deltaTime)}onUpdateFade_PostRender(){this._transition?.remove()}},md=class e extends a{alpha=1;get isRGBAColor(){return!0}set a(e){this.alpha=e}get a(){return this.alpha}constructor(e,t,n,r){super(),typeof e==`number`&&typeof t==`number`&&typeof n==`number`?(this.set(e,t,n),this.alpha=typeof r==`number`?r:1):e!==void 0&&(this.set(e),this.alpha=1)}clone(){let e=super.clone();return e.alpha=this.alpha,e}copy(e){return this.r=e.r,this.g=e.g,this.b=e.b,`alpha`in e&&typeof e.alpha==`number`?this.alpha=e.alpha:typeof e.a==`number`&&(this.alpha=e.a),this}lerp(e,t){let n=e;return n.alpha!=null&&(this.alpha=N.lerp(this.alpha,n.alpha,t)),super.lerp(e,t)}lerpColors(e,t,n){let r=e,i=t;return r.alpha!=null&&i.alpha!=null&&(this.alpha=N.lerp(r.alpha,i.alpha,n)),super.lerpColors(e,t,n)}multiply(e){let t=e;return t.alpha!=null&&(this.alpha*=t.alpha),super.multiply(e)}fromArray(e,t=0){return this.alpha=e[t+3],super.fromArray(e,t)}static fromColorRepresentation(t){if(typeof t==`string`){if(t.trim()===`transparent`)return new e(0,0,0,0);if(t.startsWith(`#`)&&t.length===9){let n=parseInt(t.slice(1,9),16),r=n>>24&255,i=n>>16&255,a=n>>8&255,o=n>>0&255;return new e(r/255,i/255,a/255,o/255)}else if(t.startsWith(`#`)){let n=parseInt(t.slice(1),16),r=n>>16&255,i=n>>8&255,a=n>>0&255;return new e(r/255,i/255,a/255,1)}else if(t.startsWith(`rgba`)){let n=t.slice(5,-1).split(`,`).map(Number);return new e(n[0]/255,n[1]/255,n[2]/255,n[3])}else if(t.startsWith(`rgb`)){let n=t.slice(4,-1).split(`,`).map(Number);return new e(n[0]/255,n[1]/255,n[2]/255,1)}}else if(Array.isArray(t)){if(t.length===4)return new e(t[0],t[1],t[2],t[3]);if(t.length===3)return new e(t[0],t[1],t[2],1);console.error(`Invalid color array length. Expected 3 or 4, got `+t.length)}return new e(t)}},hd=new o,gd=new o,_d=new E,vd=A(`debuggizmos`),yd=8947848,bd=32,H=class e{constructor(){}static enabled=!0;static isGizmo(e){return e[wd]!==void 0}static setVisible(e){for(let t of Td.timedObjectsBuffer)t.visible=e}static DrawLabel(t,n,r=.05,i=0,a,o,s){if(!e.enabled)return null;a||=yd;let c=pd.active?.rigScale??1,l=Td.getTextLabel(i,n,r*c,a,o);return s instanceof S&&s.add(l),l.position.x=t.x,l.position.y=t.y,l.position.z=t.z,l}static DrawRay(t,n,r=yd,i=0,a=!0){if(!e.enabled)return;let o=Td.getLine(i),s=o.geometry.getAttribute(`position`);s.setXYZ(0,t.x,t.y,t.z),hd.set(n.x,n.y,n.z).multiplyScalar(999999999),s.setXYZ(1,t.x+hd.x,t.y+hd.y,t.z+hd.z),s.needsUpdate=!0,o.material.depthTest=a,o.material.depthWrite=!1,o.material.fog=!1,Cd(o.material,r)}static DrawDirection(t,n,r=yd,i=0,a=!0,o=1){if(!e.enabled)return;let s=Td.getLine(i),c=s.geometry.getAttribute(`position`);c.setXYZ(0,t.x,t.y,t.z),n.w===void 0?(hd.set(n.x,n.y,n.z),hd.multiplyScalar(o)):(hd.set(0,0,-o),_d.set(n.x,n.y,n.z,n.w),hd.applyQuaternion(_d)),c.setXYZ(1,t.x+hd.x,t.y+hd.y,t.z+hd.z),c.needsUpdate=!0,s.material.depthTest=a,s.material.depthWrite=!1,Cd(s.material,r)}static DrawLine(t,n,r=yd,i=0,a=!0){if(!e.enabled)return;let o=Td.getLine(i),s=o.geometry.getAttribute(`position`);s.setXYZ(0,t.x,t.y,t.z),s.setXYZ(1,n.x,n.y,n.z),s.needsUpdate=!0,o.material.depthTest=a,o.material.depthWrite=!1,o.material.fog=!1,Cd(o.material,r)}static DrawCircle(t,n,r,i=yd,a=0,o=!0){if(!e.enabled)return;let s=Td.getCircle(a);s.position.set(t.x,t.y,t.z),s.scale.set(r,r,r),s.quaternion.setFromUnitVectors(this._up,hd.set(n.x,n.y,n.z).normalize()),s.material.depthTest=o,s.material.depthWrite=!1,s.material.fog=!1,Cd(s.material,i)}static DrawWireSphere(t,n,r=yd,i=0,a=!0){if(!e.enabled)return;let o=Td.getSphere(n,i,!0);Ar(o,t.x,t.y,t.z),o.material.depthTest=a,o.material.depthWrite=!1,o.material.fog=!1,Cd(o.material,r)}static DrawSphere(t,n,r=yd,i=0,a=!0){if(!e.enabled)return;let o=Td.getSphere(n,i,!1);Ar(o,t.x,t.y,t.z),o.material.depthTest=a,o.material.depthWrite=!1,Cd(o.material,r)}static DrawWireBox(t,n,r=yd,i=0,a=!0,o=void 0){if(!e.enabled)return;let s=Td.getBox(i);s.position.set(t.x,t.y,t.z),s.scale.set(n.x,n.y,n.z),o?s.quaternion.copy(o):s.quaternion.identity(),s.material.depthTest=a,s.material.wireframe=!0,s.material.depthWrite=!1,s.material.fog=!1,Cd(s.material,r)}static DrawWireBox3(t,n=yd,r=0,i=!0){if(!e.enabled)return;let a=Td.getBox(r);a.position.copy(t.getCenter(hd)),a.scale.copy(t.getSize(hd)),a.material.depthTest=i,a.material.wireframe=!0,a.material.depthWrite=!1,a.material.fog=!1,Cd(a.material,n)}static _up=new o(0,1,0);static DrawArrow(t,n,r=yd,i=0,a=!0,o=!1){if(!e.enabled)return;let s=Td.getArrowHead(i);s.position.set(n.x,n.y,n.z),s.quaternion.setFromUnitVectors(this._up.set(0,1,0),hd.set(n.x,n.y,n.z).sub(gd.set(t.x,t.y,t.z)).normalize());let c=hd.set(n.x,n.y,n.z).sub(gd.set(t.x,t.y,t.z)).length()*.1;s.scale.set(c,c,c),s.material.depthTest=a,s.material.wireframe=o,Cd(s.material,r),this.DrawLine(t,n,r,i,a)}static DrawWireMesh(e){let t=Td.getMesh(e.duration??0);`mesh`in e?(t.geometry=e.mesh.geometry,t.matrixWorld.copy(e.mesh.matrixWorld)):(t.geometry=e.geometry,t.matrixWorld.copy(e.matrix)),t.matrixAutoUpdate=!1,t.matrixWorldAutoUpdate=!1,t.material.depthTest=e.depthTest??!0,t.material.wireframe=!0,Cd(t.material,e.color??yd)}},xd=new Xe(1,1,1);function Sd(e=null){let t=new a(e??14540253);return new f(new ye(xd),new ee({color:t}))}function Cd(e,t){if(Array.isArray(e)){for(let n of e)Cd(n,t);return}let n=t instanceof md?t.a:1;e.color.set(t),e.opacity=n,e.transparent=n<1}var wd=Symbol(`GizmoCache`),Td=class{static familyName=`needle-gizmos`;static ensureFont(){let e=D.FontLibrary.getFontFamily(this.familyName);e||(e=D.FontLibrary.addFontFamily(this.familyName),e.addVariant(`normal`,`normal`,`https://cdn.needle.tools/static/fonts/msdf/arial/arial-msdf.json`,`https://cdn.needle.tools/static/fonts/msdf/arial/arial.png`)?.addEventListener(`ready`,()=>{D.update()}))}static getTextLabel(e,t,n,r,i){this.ensureFont();let a=this.textLabelCache.pop(),o=1;i&&typeof i==`string`&&i?.length>=8&&i.startsWith(`#`)?(o=parseInt(i.substring(7),16)/255,i=i.substring(0,7),vd&&console.log(i,o)):typeof i==`object`&&i.a!==void 0&&(o=i.a);let s={boxSizing:`border-box`,fontFamily:this.familyName,width:`auto`,fontSize:n,color:r,lineHeight:1,backgroundColor:i??void 0,backgroundOpacity:o,textContent:t,borderRadius:.5*n,padding:.8*n,whiteSpace:`pre`,offset:.05*n};if(a)a.set(s);else{a=new Qe(s);let e=this,t=a;t.setText=function(t){this.set({textContent:t}),e.tmuiNeedsUpdate=!0}}return this.tmuiNeedsUpdate=!0,this.registerTimedObject(B.Current,a,e,this.textLabelCache),a}static getBox(e){let t=this.boxesCache.pop();return t||=new x(new Xe(1,1,1)),this.registerTimedObject(B.Current,t,e,this.boxesCache),t}static getLine(e){let t=this.linesCache.pop();if(!t){t=new Ee;let e=t.geometry.getAttribute(`position`);e||(e=new Je(new Float32Array(6),3),t.geometry.setAttribute(`position`,e))}return t.frustumCulled=!1,this.registerTimedObject(B.Current,t,e,this.linesCache),t}static getCircle(e){let t=this.circlesCache.pop();if(!t){t=new Ee;let e=t.geometry.getAttribute(`position`);if(!e){e=new Je(new Float32Array(bd*3),3),t.geometry.setAttribute(`position`,e);let n=P(0,1,0),r=P(0,0,1),i=P(r);i.cross(n).normalize();let a=P(i),o=Math.PI*2/(bd-1);for(let t=0;t{this.onBeforeRender(e,this.timedObjectsBuffer)};this.contextBeforeRenderCallbacks.set(e,t),e.pre_render_callbacks.push(t)}else if(e.pre_render_callbacks[e.pre_render_callbacks.length-1]!==i){let t=e.pre_render_callbacks.indexOf(i);t>=0&&e.pre_render_callbacks.splice(t,1),e.pre_render_callbacks.push(i)}if(!a){let t=()=>{this.onPostRender(e,this.timedObjectsBuffer,this.timesBuffer)};this.contextPostRenderCallbacks.set(e,t),e.post_render_callbacks.push(t)}else if(e.post_render_callbacks[e.post_render_callbacks.length-1]!==a){let t=e.post_render_callbacks.indexOf(a);t>=0&&e.post_render_callbacks.splice(t,1),e.post_render_callbacks.push(a)}t.traverse(e=>{e.layers.disableAll(),e.layers.enable(2)}),t.renderOrder=999999,t[wd]=r,t.castShadow=!1,t.receiveShadow=!1,t.isGizmo=!0,this.timedObjectsBuffer.push(t),this.timesBuffer.push(B.Current.time.realtimeSinceStartup+n),e.scene.add(t)}static timedObjectsBuffer=[];static timesBuffer=[];static contextPostRenderCallbacks=new Map;static contextBeforeRenderCallbacks=new Map;static tmuiNeedsUpdate=!1;static onBeforeRender(e,t){this.tmuiNeedsUpdate&&(this.tmuiNeedsUpdate=!1,D.update());for(let n=0;n=0;e--){let i=t[e];r>=n[e]-1e-6&&(t.splice(e,1),n.splice(e,1),i.removeFromParent(),Nf(i)!=1&&i[wd].push(i))}}},Ed=A(`debugphysics`),Dd=A(`debugworker`),Od=new s,kd=class{static AllLayers=4294967295;ray;cam;screenPoint;raycaster;results;targets;recursive=!0;minDistance;maxDistance;lineThreshold;layerMask;ignore;testObject;useAcceleratedRaycast;allowSlowRaycastFallback=!0;screenPointFromOffset(e,t){this.screenPoint===void 0&&(this.screenPoint=new w),this.screenPoint.x=e/window.innerWidth*2-1,this.screenPoint.y=-(t/window.innerHeight)*2+1}setLayer(e){Od.set(e),this.layerMask=Od}setMask(e){this.layerMask||=new s;let t=this.layerMask;t?t.mask=e:this.layerMask=e}},Ad=class{distance;point;object;constructor(e,t,n){this.object=e,this.distance=t,this.point=n}},jd=class e{static _raycasting=0;static get raycasting(){return this._raycasting>0}raycastPhysicsFast(e,t=void 0,n=1/0,r=!0){return this.context.physics.engine?.raycast(e,t,{maxDistance:n,solid:r})??null}raycastPhysicsFastAndGetNormal(e,t=void 0,n=1/0,r=!0){return this.context.physics.engine?.raycastAndGetNormal(e,t,{maxDistance:n,solid:r})??null}sphereOverlapPhysics(e,t){return this.context.physics.engine?.sphereOverlap(e,t)??null}context;engine;constructor(e){this.context=e}raycaster=new _;defaultRaycastOptions=new kd;targetBuffer=[,];defaultThresholds={Mesh:{},Line:{threshold:-1},LOD:{},Points:{threshold:0},Sprite:{}};sphereResults=[];sphereMask=new s;sphere=new Oe;sphereOverlap(e,t,n=!0,r=!1,i=null){if(this.sphereResults.length=0,!this.context.scene)return this.sphereResults;let a=this.sphereMask;a.enableAll(),a.disable(2);for(let o of this.context.scene.children)this.intersectSphere(o,e,t,a,this.sphereResults,n,r,i);return this.sphereResults.sort((e,t)=>e.distance-t.distance)}raycastFromRay(e,t=null){let n=t??this.defaultRaycastOptions;n.ray=e;let r=this.raycast(n);return n===this.defaultRaycastOptions&&(n.ray=void 0),r}raycast(t=null){Ed&&performance.mark(`raycast.start`),t||=this.defaultRaycastOptions;let n=t.screenPoint??this.context.input.mousePositionRC,r=t.raycaster??this.raycaster;if(r.near=t.minDistance??0,r.far=t.maxDistance??1/0,r.params=this.defaultThresholds,t.lineThreshold===void 0&&(t.lineThreshold=-1),r.params.Line={threshold:t.lineThreshold},t.ray)r.ray.copy(t.ray);else{let e=t.cam??this.context.mainCamera;if(!e)return Ed&&console.error(`Can not perform raycast - no main camera found`),this.defaultRaycastOptions.results&&(this.defaultRaycastOptions.results.length=0),this.defaultRaycastOptions.results??[];let i=this.context.xrCamera;this.context.isInXR&&i instanceof Me&&i.cameras.length>0?r.setFromCamera(n,i.cameras[0]):r.setFromCamera(n,e)}let i=t.targets;i||(i=this.targetBuffer,i.length=1,i[0]=this.context.scene);let a=t.results;this.defaultRaycastOptions.results&&(this.defaultRaycastOptions.results.length=0),a||=(this.defaultRaycastOptions.results||(this.defaultRaycastOptions.results=[]),this.defaultRaycastOptions.results),t.layerMask===void 0?(r.layers.enableAll(),r.layers.disable(2)):t.layerMask instanceof s?r.layers.mask=t.layerMask.mask:r.layers.mask=t.layerMask,Ed&&console.time(`raycast`),a.length=0,e._raycasting++,this.intersect(this.raycaster,i,a,t),a.sort((e,t)=>e.distance-t.distance);let o=t.ignore;return o!==void 0&&o.length>0&&(a=a.filter(e=>!o.includes(e.object))),e._raycasting--,Ed&&(console.timeEnd(`raycast`),console.warn(`#`+this.context.time.frame+`, hits:`,a?.length?[...a]:`nothing`),performance.mark(`raycast.end`),performance.measure(`raycast`,`raycast.start`,`raycast.end`)),a}intersect(e,t,n,r){for(let i of t){if(!i||i.visible===!1||H.isGizmo(i)||r.lineThreshold!==void 0&&r.lineThreshold<0&&i instanceof Ee)continue;let t=!0,a=i,o=a.geometry;if(i.raycastAllowed===!1&&(t=!1),t&&r.testObject){let e=r.testObject?.(i);if(e===!1)continue;e===`continue in children`&&(t=!1)}else t&&(o&&Md(o)||(t=!1));if(t){let t=n.length,s=i.raycastPreference||`lod`,c=s!==`bounds`;if(r.precise===!1&&(c=!1),o&&(c||=o.getAttribute(`position`)?.array?.length<64),a instanceof ct&&(c=!1),s===`lod`){let e=bt(i);e&&(a.geometry=e)}if(!c&&Id(a,e,n)||(r.useAcceleratedRaycast===!1?e.intersectObject(a,!1,n):Ld.runMeshBVHRaycast(e,a,n,this.context,r)),a.geometry=o,Ed&&n.length!=t){let e=n[n.length-1];H.DrawWireSphere(e.point,.1,7798784,1,!1),H.DrawWireMesh({mesh:i,depthTest:!1,duration:.2,color:7798784})}}r.recursive!==!1&&this.intersect(e,i.children,n,r)}return n}tempBoundingBox=new fe;intersectSphere(e,t,n,r,i,a,o,s){let c=e&&e.isMesh&&e.layers.test(r)&&!H.isGizmo(e);c&&=e.visible,c&&=!(e instanceof Ee),c&&=!(e instanceof ct);let l=e,u=l.geometry;if(c&&s){let t=s(e);if(t===!1)return;t===`continue in children`&&(c=!1)}if(u&&Md(u)||(c=!1),c){if(o){let e=this.sphere;e.center.copy(t),e.radius=n;let r=i.length;if(Ld.runMeshBVHRaycast(this.sphere,l,i,this.context,{}),r!=i.length&&!a)return}else if(u.boundingBox||u.computeBoundingBox(),u.boundingBox){l.matrixWorldNeedsUpdate&&l.updateWorldMatrix(!1,!1);let r=this.tempBoundingBox.copy(u.boundingBox).applyMatrix4(l.matrixWorld),o=this.sphere;if(o.center.copy(t),o.radius=n,o.intersectsBox(r)){let t=Or(e),n=new Ad(e,t.distanceTo(o.center),t);if(i.push(n),!a)return}}}if(e.children)for(let c of e.children){let e=i.length;if(this.intersectSphere(c,t,n,r,i,a,o,s),e!=i.length&&!a)return}}};function Md(e){return!(e.index&&e.index.array.length<3)}var Nd=new Oe,Pd=new pe,Fd=new le;function Id(e,t,n){let r=e._computeIntersections;if(!r)return!1;let i=e[`_computeIntersections:Needle`];return i||=e[`_computeIntersections:Needle`]=function(e,t,n){let r=this,i=r.geometry.boundingSphere;if(i){if(r instanceof ct){Pd.setFromNormalAndCoplanarPoint(P(0,1,0),P(0,-r.position.y,0)),Pd.applyMatrix4(r.matrixWorld,Fd);let n=e.ray.intersectPlane(Pd,P());if(n){Nd.copy(i),Nd.applyMatrix4(r.matrixWorld);let a=P(n).sub(e.ray.origin).length();aNd.radius){let e=i.clone().normalize();t.push({distance:a,point:n,object:r,normal:e})}}}},e._computeIntersections=i,t.intersectObject(e,!1,n),e._computeIntersections=r,!0}var Ld;(function(e){let t=0;function n(e,n,r,i,y){if(!n.geometry||!n.geometry.hasAttribute(`position`))return!1;let b=n.geometry;if(n?.isSkinnedMesh){let e=n,t=e.bvhNeedsUpdate;if(!e.staticGenerator)l(),s&&(e.staticGenerator=new s(n),e.staticGenerator.applyWorldTransforms=!1,e.staticGeometry=e.staticGenerator.generate(),b.boundsTree=c?.call(e.staticGeometry),e.staticGeometryLastUpdate=performance.now()+Math.random()*200,e.bvhNeedsUpdate=!0);else if(b.boundsTree&&(e.autoUpdateMeshBvhInterval!==void 0&&e.autoUpdateMeshBvhInterval>=0||t===!0)){let r=performance.now(),i=r-e.staticGeometryLastUpdate,a=e.autoUpdateMeshBvhInterval??100;(t||i>a)&&(Ed&&console.warn(`Physics: updating skinned mesh bvh for ${n.name} after ${i.toFixed(2)}ms`),e.bvhNeedsUpdate=!1,e.staticGeometryLastUpdate=r,e.staticGenerator?.generate(e.staticGeometry),b.boundsTree.refit())}}else if(!b.boundsTree){d||ee();let e=!0;if((i.xr||b[h]===!1||b.getAttribute(`position`)?.isInterleavedBufferAttribute||b.index&&b.index?.isInterleavedBufferAttribute||t>10)&&(e=!1),e&&p){if(b[m]===void 0){let e=null;if(v.length>0){let t=v.shift();t&&!t.running&&(e=t)}if(!e&&g.length<3)try{Dd&&console.warn(`[GenerateMeshBVHWorker] Creating worker with import.meta.url:`,import.meta.url),e=new p,g.push(e)}catch(e){e instanceof DOMException&&e.name===`SecurityError`?(console.warn(`Failed to create MeshBVH worker, falling back to main thread generation. This can happen when running from file://, if the browser does not support workers or if the browser is blocking workers for other reasons.`),console.debug(e),t+=10):(console.error(`Failed to create MeshBVH worker. Please see below for more details:`),console.log(e)),t++}if(e!=null&&!e.running){let t=n.name;Ed&&console.log(`<<<< worker start`,t,e),b[m]=`queued`,performance.mark(`bvh.create.start`);let r=b.clone();try{e.generate(r).then(e=>{b[m]=`done`,b.boundsTree=e}).catch(e=>{b[m]=`failed - `+e?.message,b[h]=!1,Ed&&console.error(`Failed to generate mesh bvh on worker`,e)}).finally(()=>{Ed&&console.log(`>>>>> worker done`,t,{hasBoundsTre:b.boundsTree!=null}),v.push(e),r.dispose(),performance.mark(`bvh.create.end`),performance.measure(`bvh.create (worker)`,`bvh.create.start`,`bvh.create.end`)})}catch(e){console.error(`Failed to generate mesh bvh on worker`,e)}}else Ed&&console.warn(`No worker available`)}}else (!f||!e)&&(l(),o&&(performance.mark(`bvh.create.start`),b.boundsTree=new o(b),performance.mark(`bvh.create.end`),performance.measure(`bvh.create`,`bvh.create.start`,`bvh.create.end`)))}if(e instanceof _){let t=e,i=n.raycast;if(b.boundsTree)l(),a&&(n.acceleratedRaycast||(n.acceleratedRaycast=a.bind(n),Ed&&console.debug(`Physics: bind acceleratedRaycast fn to \"${n.name}\"`)),n.raycast=n.acceleratedRaycast);else if(Ed&&console.warn(`No bounds tree found for mesh`,n.name,{workerTask:b[m],hasAcceleratedRaycast:a!=null}),y.allowSlowRaycastFallback===!1&&(b.getAttribute(`position`)?.array?.length??0)>2e3)return Ed&&console.warn(`Skipping raycast because no bounds tree is available and allowSlowRaycastFallback is false`),!1;let o=t.firstHitOnly;return t.firstHitOnly=!1,t.intersectObject(n,!1,r),t.firstHitOnly=o,n.raycast=i,!0}else if(e instanceof Oe){let t=b.boundsTree;if(t){let i=e;if(u.copy(n.matrixWorld).invert(),i.applyMatrix4(u),t.intersectsSphere(i)){let e=Or(n),t=new Ad(n,e.distanceTo(i.center),e);r.push(t)}}return!0}return!1}e.runMeshBVHRaycast=n;let i=!1,a=null,o=null,s=null,c=null;function l(){i||(i=!0,r(()=>import(`./needle-engine.dep.B3nA4wQ5.js`).then(e=>{a=e.acceleratedRaycast,o=e.MeshBVH,s=e.StaticGeometryGenerator,c=e.computeBoundsTree}),__vite__mapDeps([12,13,3,2]),import.meta.url).catch(e=>{(Ed||M())&&console.error(`Failed to load BVH library...`,e.message)}))}let u=new ce,d=!1,f=!1,p=null,m=Symbol(`Needle:MeshBVH-Worker`),h=Symbol(`Needle:MeshBVH-CanUseWorker`),g=[],v=[];function ee(){d=!0,f=!0,r(()=>import(`./GenerateMeshBVHWorker.DMD7ZOpN.js`).then(e=>{p=e.GenerateMeshBVHWorker}),__vite__mapDeps([14,15,2,16,1,3,17,18,19,20,21,22,6,13]),import.meta.url).catch(e=>{Ed||M()?console.warn(`Failed to setup mesh bvh worker`):console.debug(`Failed to setup mesh bvh worker`,e)}).finally(()=>{f=!1})}})(Ld||={});var Rd=Symbol(`gltf-loader-internal-usage-tracker`),zd=A(`debugusers`),Bd=class e{get name(){return`NEEDLE_internal_usage_tracker`}static isLoading(t){return e._loadingProcesses>0}static _loadingProcesses=0;parser;_getDependency;_loadingId;_loadedObjects=new Set;constructor(e){this.parser=e,this._getDependency=this.parser.getDependency,this._loadingId=Date.now().toString()}beforeRoot(){e._loadingProcesses++;let t=this,n=this._getDependency;return this.parser.getDependency=function(e,r){let i=n.call(this,e,r);return i.then(e=>(e&&(t._loadedObjects.add(e),e[Rd]=t._loadingId),e)),i},null}afterRoot(t){e._loadingProcesses--,this.parser.getDependency=this._getDependency;for(let e of this._loadedObjects)delete e[Rd],e instanceof S&&(e.parent||e instanceof x&&setTimeout(()=>{zd&&console.warn(`> GLTF LOADER: Mesh not used in scene!`,e),e.material=null,e.geometry=null},1e3));return null}},Vd=class{constructor(){window.addEventListener(`unhandledrejection`,e=>{if(e.defaultPrevented)return;let t=e?.reason?.path;if(t){let n=t[0];n&&n.tagName===`IMG`&&(console.warn(`Could not load image: `+n.src),e.preventDefault())}})}},Hd=A(`trackresources`);function Ud(){return Hd===`dispose`}var Wd=!0;Hd===0&&(Wd=!1);function Gd(e){Wd=e}function Kd(){return Wd}var qd=Symbol(`disposable`);function Jd(e,t){e&&(e[qd]=t,nf&&console.warn(`Set disposable`,t,e))}var Yd=Symbol(`disposed`);function Xd(e){return e[Yd]===!0}function U(e){if(e){if(e[qd]===!1){nf&&console.warn(`Object is marked as not disposable`,e);return}if(typeof e==`object`&&(e[Yd]=!0),e instanceof ne)U(e.environment),U(e.background),U(e.customDepthMaterial),U(e.customDistanceMaterial);else if(e instanceof ze)U(e.geometry),U(e.material),U(e.skeleton),U(e.bindMatrix),U(e.bindMatrixInverse),U(e.customDepthMaterial),U(e.customDistanceMaterial),e.visible=!1;else if(e instanceof x)U(e.geometry),U(e.material),U(e.customDepthMaterial),U(e.customDistanceMaterial),e.visible=!1;else if(e instanceof S)e.visible=!1;else if(e instanceof ie){Zd(e);for(let t of Object.keys(e.attributes)){let n=e.attributes[t];U(n)}}else if(e instanceof Je||e instanceof ae)nf&&console.warn(`BufferAttribute dispose not supported`,e.count);else if(e instanceof Array)for(let t of e)t instanceof T&&U(t);else if(e instanceof T){Zd(e);for(let t of Object.keys(e)){let n=e[t];n instanceof be&&U(n)}let t=e.uniforms;if(t)for(let e of Object.keys(t)){let n=t[e];n instanceof be?U(n):n instanceof Ye&&U(n.value)}}else e instanceof be?(Zd(e),Zd(e.source),e.source?.data instanceof ImageBitmap&&Zd(e.source.data)):e instanceof Pe?(Zd(e.boneTexture),e.boneTexture=null):e instanceof xe||!(e instanceof S)&&nf&&console.warn(`Unknown object type`,e)}}function Zd(e){e&&((nf||Ud()||Hd)&&console.warn(`🧨 FREE`,e),e instanceof ImageBitmap||`dispose`in e&&typeof e.dispose==`function`&&e.dispose())}function Qd(e){e instanceof x||e instanceof ze}var $d=new Set;function ef(e,t,n=null,r){if(r||(r=$d,r.clear()),!e)return r;let i=e[rf];if(i)for(let e of i)r.has(e)||n?.call(null,e)!==!1&&(r.add(e),t&&ef(e,!0,n,r));return r}function tf(e){return e[af]}var nf=A(`debugresourceusers`)||A(`debugmemory`),rf=Symbol(`needle-resource-users`),af=Symbol(`needle-resource-users-count`);function of(e,t){Zi(e,t,function(e,t){Wd&&!jd.raycasting&&(lf(rf,this,e,!1),lf(rf,this,t,!0))})}Wd&&(of(x.prototype,`material`),of(x.prototype,`geometry`),of(T.prototype,`map`),of(T.prototype,`bumpMap`),of(T.prototype,`alphaMap`),of(T.prototype,`normalMap`),of(T.prototype,`displacementMap`),of(T.prototype,`roughnessMap`),of(T.prototype,`metalnessMap`),of(T.prototype,`emissiveMap`),of(T.prototype,`specularMap`),of(T.prototype,`envMap`),of(T.prototype,`lightMap`),of(T.prototype,`aoMap`),of(T.prototype,`gradientMap`));function sf(e){if(Wd===!1)return;let t=e[rf];if(t)for(let n of t)lf(rf,n,e,!1)}Wd&&Zi(T.prototype,`dispose`,function(){sf(this)});var cf=0;function lf(e,t,n,r){if(cf>0)return;if(Array.isArray(n)){for(let i of n)lf(e,t,i,r);return}if(!n)return;let i=n[e];if(i||=new Set,r){if(t&&!i.has(t)){i.add(t);let e=n[af]||0;e+=1,n[af]=e,nf&&console.warn(`🟢 Added user of "${n.type}"`,t,n,e,`users:`,i)}}else if(t&&i.has(t)){i.delete(t);let e=n[af]||0;e>0&&(--e,n[af]=e),nf&&console.warn(`🔴 Removed user of "${n.type}"`,t,n,e,`users:`,i),e<=0&&(Bd.isLoading(n)||(Hd&&console.warn(`🔴 Removed all user of "${n.type}"`,n),Ud()&&U(n)))}n[e]=i}try{Zi(h.prototype,`render`,function(){cf++},function(){cf--})}catch(e){console.warn(`Could not wrap WebGLRenderer.render`,e)}var uf=Symbol(`NEEDLE_NEED_UPDATE_INSTANCE`),df=Symbol(`isUsingInstancing`),ff=Symbol(`instancingRenderer`),pf=Symbol(`instancingAutoUpdateBounds`),mf=class e{static isUsingInstancing(e){return e[df]===!0}static getRenderer(e){return e[ff]||null}setAutoUpdateBounds(t,n){let r=e.getRenderer(t);r&&(r[pf]=n)}static markDirty(t,n=!0){if(t&&(this.isUsingInstancing(t)&&(t[uf]=!0,t.matrixWorldNeedsUpdate=!0),n))for(let n of t.children)e.markDirty(n,!0)}},hf=new Map;function gf(e,t){if(!e)return;if(!t){console.warn(`No prototype found`,e,e.prototype,e.constructor);return}let n=hf.get(t);n&&n.apply(e)}function _f(e){let t=vf(e.prototype);hf.set(e,t)}function vf(e){return new yf(e)}var yf=class{$symbol;extensions;descriptors;constructor(e){this.$symbol=Symbol(`prototype-extension`),this.extensions=Object.keys(e),this.descriptors=[];for(let t=0;t.5),e.visible=t,e.visible}function Of(e){return e.needle_isActiveInHierarchy||Af(e)}function kf(e,t){e[df]=t}function Af(e){return mf.isUsingInstancing(e)}function jf(e,t){return Wt(e,t,!0,!0)}var Mf=Symbol(`isDestroyed`);function Nf(e){return e[Mf]}function Pf(e,t){e[Mf]=t}var Ff=Symbol(`isDontDestroy`);function If(e,t=!0){e[Ff]=t}var Lf=[],Rf=[];function zf(e,t=!0,n=!1){Lf.length=0,Rf.length=0,Bf(e,t,!0);for(let e of Lf)e.gameObject=null,e.context=null;for(let e of Rf)Pf(e,!0),n&&(U(e),Qd(e));Rf.length=0,Lf.length=0}function Bf(e,t=!0,n=!0){if(e==null)return;let r=e;if(r.isComponent){if(r[Ff])return;Lf.push(r);let e=r.gameObject;r.__internalDisable(),r.__internalDestroy(),r.gameObject=e;return}if(e[Ff])return;let i=e;Cf&&console.log(i),Rf.push(i);let a=i.userData?.components;if(a!=null&&Array.isArray(a)){let e=a.length;for(let n=0;nr)){for(let n of e.userData.components)t&&n?.isComponent===!0&&n instanceof t,yield n;if(n===!0)for(let n of e.children)yield*Hf(n,t,!0,r,i+1)}}function Uf(e,t,n,r=0){if(e){if(e.isObject3D||``+e,r>1e3){console.warn(`Failed to iterate components: too many levels`);return}if(e.userData?.components)for(let n=0;n0&&(l.animations=[...t.animations]);let u=t.parent;if(u&&u.add(l),n?.position)if(Array.isArray(n.position)){let e=new o;e.fromArray(n.position),l.worldPosition=e}else l.worldPosition=n.position;else l.position.copy(t.position);if(n?.rotation){if(n.rotation instanceof E)l.worldQuaternion=n.rotation;else if(n.rotation instanceof He)l.worldQuaternion=Tr().setFromEuler(n.rotation);else if(Array.isArray(n.rotation)){let e=new He;e.fromArray(n.rotation),l.worldQuaternion=Tr().setFromEuler(e)}}else l.quaternion.copy(t.quaternion);if(n?.scale)if(Array.isArray(n.scale)){let e=new o;e.fromArray(n.scale),n.scale=e}else l.scale.copy(n.scale);else l.scale.copy(t.scale);if(n?.parent&&n.parent!==`scene`){let r=null;if(r=typeof n.parent==`string`?Wt(n.parent,e.scene,!0):n.parent,r){let e=n.keepWorldPosition===!0?r.attach:r.add;e?e.call(r,l):console.error(`Invalid parent object`,r,`received when instantiating:`,t)}else console.warn(`could not find parent:`,n.parent)}for(let[e,n]of Object.entries(t.userData))e!==`components`&&(l.userData[e]=n);if(t.userData?.components){let e=t.userData.components,n=[];l.userData.components=n;for(let t=0;t`,s),i.push(s))}}else if(typeof n==`object`){let i=Yf(r,e,n,t);i===void 0?wf&&console.warn(`Could not find new instance for`,e,n):r[e]=i}}}}function Yf(e,t,n,r){if(n!=null){if(n.isComponent===!0){let i=n.gameObject;if(i){let a=i.uuid,o=r[a]?.clone;if(!o){wf&&console.log(`reference did not change`,t,e,n);return}let s=i.userData.components.indexOf(n);if(s>=0&&o.isObject3D)return wf&&console.log(t,a),o.userData.components[s];console.warn(`could not find component`,t,n)}}else if(n.isObject3D===!0){if(t===`gameObject`)return;let e=n;if(e){let i=r[e.uuid]?.clone;if(i)return wf&&console.log(t,`old`,n,`new`,i),i}}else if(n.isVector4||n.isVector3||n.isVector2||n.isQuaternion||n.isEuler)return n.clone();else if(n.isColor===!0)return n.clone();else if(n.isEventList===!0)return n.__internalOnInstantiate(r)}}function Xf(e,t){try{t?e(t):e()}catch(e){return console.error(e),!1}return!0}var Zf=A(`debugnewscripts`),Qf=A(`debughierarchy`),W=[];function $f(){return W.length>0}function ep(e){if(Zf&&console.log(`Register new components`,e.new_scripts.length,[...e.new_scripts],e.alias?`element: `+e.alias:e.hash,e),e.new_scripts_pre_setup_callbacks.length>0){for(let t of e.new_scripts_pre_setup_callbacks)t&&t();e.new_scripts_pre_setup_callbacks.length=0}if(!(e.new_scripts.length<=0)){W.length=0,e.new_scripts.length>0&&W.push(...e.new_scripts),e.new_scripts.length=0;for(let t=0;t=0&&t.splice(n,1)}function op(e,t){if(e){let n=e;if(n.onBeforeXR||n.onEnterXR||n.onUpdateXR||n.onLeaveXR||n.onXRControllerAdded||n.onXRControllerRemoved)return!(t!=null&&n.supportsXR?.(t)===!1)}return!1}var sp=!0;function cp(){sp=!0}function lp(e,t=!1){if(Ji.experimentalSmartHierarchyUpdate){if(!t&&!sp)return;sp=!1}if(e||=k.Current.scene,!e){console.trace(`Invalid call - no current context.`);return}let n=Ef(e);up(e,n,!0)||(Zf||M()?console.error(`Error updating hierarchy Do you have circular references in your project? Click here for more information.`,e):console.error(`Failed to update active state in hierarchy of "`+e.name+`"`,e),console.warn(` ↑ this error might be caused by circular references. Please make sure you don't have files with circular references (e.g. one GLB 1 is loading GLB 2 which is then loading GLB 1 again).`))}function up(e,t,n,r=0){if(r>1e3)return console.warn(`Hierarchy is too deep (> 1000 level) - will abort updating active state`),!1;let i=Ef(e);if(t&&(t=i,t&&e.parent&&r===0)){let n=e.parent;t=n[Wi],t===void 0&&(n instanceof ne||(t=!0))}let a=e[Wi]!==t;if(a&&(e[Wi]=t,Qf&&console.warn(`ACTIVE CHANGE`,{name:e.name,activeSelf:i,visible:e.visible,activeInHierarchy:t,changed:a,go:e}),n)){let n=e.userData?.components;if(n)for(let e=n.length-1,r=-1;e>-1;e--){let r=n[e];if(t){if(r?.enabled){try{r.__internalAwake()}catch(e){console.error(e)}r.enabled&&r.__internalEnable()}}else r&&r.__didAwake&&r.enabled&&(r.__didEnable=!1,r.onDisable())}}let o=e.children;if(o){if(!a&&!t){let e=!0;for(let t=0,i=o.length;tbp||globalThis.NEEDLE_DEBUG_GETCOMPONENT===!0;function Sp(e){return e==null||e.isObject3D?e:e.object&&e.object.isObject3D?e.object:e}function Cp(e,t){if(!e||!e.userData.components)return t;let n=e.userData.components.indexOf(t);return n<0?t:(Ri.dispatchComponentLifecycleEvent(`removing-component`,t),t.gameObject=null,e.userData.components.splice(n,1),t)}function wp(e,t,n){return Mp(e,t)||Op(e,t,n)}var Tp;function Ep(){return Tp??=new jo(`addComponentIdProvider`)}function Dp(e,t,n=!0){e.userData||={},e.userData.components||(e.userData.components=[]),e.userData.components.push(t),t.gameObject=e,(t.guid===void 0||t.guid===`invalid`)&&(t.guid=Ep().generateUUID()),bf(e),Eu(t,t.context);try{n&&t.__internalAwake&&(dp(e),t.activeAndEnabled&&t.__internalAwake()),Ri.dispatchComponentLifecycleEvent(`component-added`,t)}catch(e){console.error(e)}return t}function Op(e,t,n,r){if(typeof t==`function`){let i=new t;n&&i.__internalNewInstanceCreated(n);let a=!0;return r?.callAwake!=null&&(a=r.callAwake),Dp(e,i,a)}if(t.destroyed)return console.warn(`Can not move/add a destroyed component`,t),t;if(t.gameObject===e)return t;if(t.gameObject&&t.gameObject.userData?.components){let e=t.gameObject.userData.components.indexOf(t);t.gameObject.userData.components.splice(e,1)}if(e.userData||={},!e.userData.components)e.userData.components=[];else if(e.userData.components.includes(t))return t;return e.userData.components.push(t),t.gameObject=e,(t.guid===void 0||t.guid===`invalid`)&&(t.guid=Ep().generateUUID()),n&&t._internalInit(n),Eu(t,t.context),t}function kp(e){if(e.gameObject&&e.gameObject.userData.components){let t=e.gameObject.userData.components.indexOf(e);e.gameObject.userData.components.splice(t,1)}e.__internalDisable&&e.__internalDisable(),ip(e,e.context??B.Current),e.destroy(),e.gameObject=null}var Ap=!1;function jp(e,t,n){if(e==null)return null;if(!e.isObject3D)return console.error(`Object is not object3D`),null;if(!e?.userData?.components||(typeof t==`string`&&(Ap||(Ap=!0,console.warn(`Accessing components by name is not supported. Please use the component type instead. This may keep working in local development but it will fail when bundling your application. You can import other modules your main module to get access to types or if you use npmdefs you can make types available globally using globalThis: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/globalThis`,t))),xp()&&console.log(`[onGetComponent] FIND`,t),t==null))return null;for(let r=0;r{if(t.length){let e=t[0];if(typeof e==`string`&&e.includes(`[hmr] Failed to reload `)){console.log(`[Needle Engine] Hot reloading failed`),window.location.reload();return}}e.apply(console,t)}}function Yp(e){Bp&&console.log(`[HMR] Apply changes`,e,Object.keys(e)),Jp();for(let t of Object.keys(e))try{Vp=!0;let n=ji.get(t);if(!n){Bp&&console.log(`[HMR] Type not found: `+t);continue}let r=e[t],i=Hp.get(r.name),a=`[Needle Engine] Updating type: `+t,o=i?.length??-1;o>0?a+=` x`+o:a+=` (No instances registered)`,console.log(a);let s=Object.getOwnPropertyNames(n.prototype),c=Object.getOwnPropertyDescriptors(r.prototype);for(let r in c)c[r].writable&&(n.prototype[r]=e[t].prototype[r]);for(let e of s)c[e]||delete n.prototype[e];if(i){let e=new r,t=Object.getOwnPropertyDescriptors(e);for(let n of i){let i=n,a=i.isComponent===!0,o=a?i.activeAndEnabled:!0,s=a?i.context:void 0;try{if(a&&s&&ip(i,s),a&&o&&(i.enabled=!1),n.onBeforeHotReloadFields&&n.onBeforeHotReloadFields()===!1)continue;for(let i in t)if(t[i].writable){if(n[i]===void 0)n[i]=e[i];else if(typeof n[i]==`function`&&!n[i].prototype){let e=n[i];if(e.name===`bound `)continue;let t=e.name.substring(6),a=r.prototype[t];a&&(n[i]=a.bind(n))}}n.onAfterHotReloadFields&&n.onAfterHotReloadFields()}finally{a&&s&&rp(i,s),a&&o&&(i.enabled=!0)}}}}catch(e){if(Bp)console.error(e);else return!1}finally{Vp=!1,zn(Tn.Log,`Script changes applied (HMR)`)}return!0}var Xp=e({Behaviour:()=>K,Component:()=>K,GameObject:()=>G}),G=class e extends S{guid;static isDestroyed(e){return Nf(e)}static setActive(e,t,n=!0){e&&(Df(e,t),lp(e),t&&n&&np(B.Current,e))}static isActiveSelf(e){return Ef(e)}static isActiveInHierarchy(e){return Of(e)}static markAsInstancedRendered(e,t){kf(e,t)}static isUsingInstancing(e){return Af(e)}static foreachComponent(e,t,n=!0){return Vf(e,t,n)}static instantiateSynced(e,t){return e?zo(e,t):null}static instantiate(e,t=null){return`isAssetReference`in e,Wf(e,t)}static destroySynced(e,t,n=!0){if(!e)return;let r=e;t??=B.Current,Po(r,t.connection,n)}static destroy(e,t=!0){return zf(e,t)}static add(t,n,r){if(!(!t||!n)){if(t===n){console.warn(`Can not add object to self`,t);return}r||=B.Current,n.add(t),Df(t,!0),lp(t),r?e.foreachComponent(t,e=>{rp(e,r),!e.__internalDidAwakeAndStart&&r.new_script_start.includes(e)===!1&&r.new_script_start.push(e)},!0):console.warn(`Missing context`)}}static remove(t){t&&(t.parent?.remove(t),Df(t,!1),lp(t),e.foreachComponent(t,e=>{tp(e)},!0))}static invokeOnChildren(e,t,...n){this.invoke(e,t,!0,n)}static invoke(e,t,n=!1,...r){e&&this.foreachComponent(e,e=>{let n=e[t];n&&typeof n==`function`&&n?.call(e,...r)},n)}static addNewComponent(e,t,n,r=!0){return Op(e,t,n,{callAwake:r})}static addComponent(e,t,n,r){return Op(e,t,n,r)}static moveComponent(e,t){return Op(e,t)}static removeComponent(e){return Cp(e.gameObject,e),e}static getOrAddComponent(e,t){return wp(e,t)}static getComponent(e,t){return e===null?null:Mp(e,t)}static getComponents(e,t,n=null){return e===null?n??[]:Np(e,t,n)}static findByGuid(e,t){return jf(e,t)}static findObjectOfType(e,t,n=!0){return Rp(e,t??B.Current,n)}static findObjectsOfType(e,t){let n=[];return zp(e,n,t),n}static getComponentInChildren(e,t,n=!1){return Pp(e,t,n)}static getComponentsInChildren(e,t,n=null){return Fp(e,t,n??void 0)}static getComponentInParent(e,t){return Ip(e,t)}static getComponentsInParent(e,t,n=null){return Lp(e,t,n)}static getAllComponents(e){let t=e.userData?.components;return t?[...t]:[]}static*iterateComponents(e){let t=e?.userData?.components;if(t&&Array.isArray(t))for(let e=0;e=.5),!this.__didAwake){this.__isEnabled=e;return}e?this.__internalEnable():this.__internalDisable()}get worldPosition(){return Or(this.gameObject)}set worldPosition(e){kr(this.gameObject,e)}setWorldPosition(e,t,n){Ar(this.gameObject,e,t,n)}get worldQuaternion(){return Pr(this.gameObject)}set worldQuaternion(e){Fr(this.gameObject,e)}setWorldQuaternion(e,t,n,r){Ir(this.gameObject,e,t,n,r)}get worldEuler(){return Xr(this.gameObject)}set worldEuler(e){Zr(this.gameObject,e)}get worldRotation(){return this.gameObject.worldRotation}set worldRotation(e){this.setWorldRotation(e.x,e.y,e.z,!0)}setWorldRotation(e,t,n,r=!0){ei(this.gameObject,e,t,n,r)}static _forward=new o;get forward(){return e._forward.set(0,0,-1).applyQuaternion(this.worldQuaternion)}static _right=new o;get right(){return e._right.set(1,0,0).applyQuaternion(this.worldQuaternion)}static _up=new o;get up(){return e._up.set(0,1,0).applyQuaternion(this.worldQuaternion)}_eventListeners=new Map;addEventListener(e,t){this._eventListeners[e]=this._eventListeners[e]||[],this._eventListeners[e].push(t)}removeEventListener(e,t){if(!this._eventListeners[e])return;let n=this._eventListeners[e].indexOf(t);n>=0&&this._eventListeners[e].splice(n,1)}dispatchEvent(e){if(!e||!this._eventListeners[e.type])return!1;let t=this._eventListeners[e.type];for(let n=0;n0}var em=class{_context;get context(){return this._context??B.Current}get isStateMachineBehaviour(){return!0}},tm=class{name;nameHash;normalizedTime;length;speed;action;hasTransitions;constructor(e,t,n,r){this.name=e.name,this.nameHash=e.hash,this.normalizedTime=t,this.length=n,this.speed=r,this.action=e.motion.action||null,this.hasTransitions=e.transitions?.length>0||!1}};function nm(e,t){return{name:`Empty`,isLooping:!1,guid:t?.generateUUID()??g.generateUUID(),index:-1,clip:new Se(e,0,[])}}var rm;(function(e){e[e.If=1]=`If`,e[e.IfNot=2]=`IfNot`,e[e.Greater=3]=`Greater`,e[e.Less=4]=`Less`,e[e.Equals=6]=`Equals`,e[e.NotEqual=7]=`NotEqual`})(rm||={});var im;(function(e){e[e.Float=1]=`Float`,e[e.Int=3]=`Int`,e[e.Bool=4]=`Bool`,e[e.Trigger=9]=`Trigger`})(im||={});var q=A(`debuganimatorcontroller`),am=A(`debugrootmotion`),om=class e{static createFromClips(t,n={looping:!1,autoTransition:!0,transitionDuration:0}){let r=[];for(let e=0;e=this.model.layers.length){console.warn(`invalid layer`);return}let i=this.model.layers[t].stateMachine;for(let t of i.states)if(t.name===e||t.hash===e){q&&console.log(`transition to `,t),this.transitionTo(t,r,n);return}console.warn(`Could not find `+e+` to play`)}reset(){this.setStartTransition()}setBool(e,t){let n=typeof e==`string`?`name`:`hash`;return this.model?.parameters?.filter(t=>t[n]===e).forEach(e=>e.value=t)}getBool(e){let t=typeof e==`string`?`name`:`hash`;return this.model?.parameters?.find(n=>n[t]===e)?.value??!1}setFloat(e,t){let n=typeof e==`string`?`name`:`hash`,r=this.model?.parameters?.filter(t=>t[n]===e);return r.forEach(e=>e.value=t),r?.length>0}getFloat(e){let t=typeof e==`string`?`name`:`hash`;return this.model?.parameters?.find(n=>n[t]===e)?.value??0}setInteger(e,t){let n=typeof e==`string`?`name`:`hash`;return this.model?.parameters?.filter(t=>t[n]===e).forEach(e=>e.value=t)}getInteger(e){let t=typeof e==`string`?`name`:`hash`;return this.model?.parameters?.find(n=>n[t]===e)?.value??0}setTrigger(e){q&&console.log(`SET TRIGGER`,e);let t=typeof e==`string`?`name`:`hash`;return this.model?.parameters?.filter(n=>n[t]===e).forEach(e=>e.value=!0)}resetTrigger(e){let t=typeof e==`string`?`name`:`hash`;return this.model?.parameters?.filter(n=>n[t]===e).forEach(e=>e.value=!1)}getTrigger(e){let t=typeof e==`string`?`name`:`hash`;return this.model?.parameters?.find(n=>n[t]===e)?.value??!1}isInTransition(){return this._activeStates.length>1}setSpeed(e){this._speed=e}_speed=1;FindState(e){return this.findState(e)}findState(e){if(!e)return null;if(Array.isArray(this.model.layers)){for(let t of this.model.layers)for(let n of t.stateMachine.states)if(n.name===e||n.hash==e)return n}return null}getCurrentStateInfo(){if(!this._activeState)return null;let e=this._activeState.motion.action;if(!e)return null;let t=this._activeState.motion.clip.duration,n=t<=0?0:Math.abs(e.time/t);return new tm(this._activeState,n,t,this._speed)}get currentAction(){return this._activeState&&this._activeState.motion.action||null}normalizedStartOffset=0;animator;model;get context(){return this.animator?.context}get mixer(){return this._mixer}dispose(){if(this._mixer.stopAllAction(),this.animator){this._mixer.uncacheRoot(this.animator.gameObject);for(let e of this._activeStates)e.motion.clip&&this.mixer.uncacheAction(e.motion.clip,this.animator.gameObject)}this.context?.animations.unregisterAnimationMixer(this._mixer)}bind(e){e?this.animator!==e&&(this._mixer&&(this._mixer.stopAllAction(),this.context?.animations.unregisterAnimationMixer(this._mixer)),this.animator=e,this._mixer=new he(this.animator.gameObject),this.context?.animations.registerAnimationMixer(this._mixer),this.createActions(this.animator)):console.error(`AnimatorController.bind: animator is null`)}clone(){if(typeof this.model==`string`)return console.warn(`AnimatorController has not been resolved, can not create model from string`,this.model),null;q&&console.warn(`AnimatorController clone()`,this.model);let t=Gt(this.model,(t,n,r)=>r==null?!0:!(r.type===`Object3D`||r.isObject3D===!0||ri(r)||r.tracks!==void 0||r instanceof e));return console.assert(t!==this.model),new e(t)}update(e){if(!this.animator)return;this.evaluateTransitions(),this.updateActiveStates(e);let t=this.animator.context.time.deltaTime;this.animator.applyRootMotion&&this.rootMotionHandler?.onBeforeUpdate(e),this._mixer.update(t),this.animator.applyRootMotion&&this.rootMotionHandler?.onAfterUpdate(e)}_mixer;_activeState;get activeState(){return this._activeState}constructor(e){this.model=e,q&&console.log(this)}_activeStates=[];updateActiveStates(e){for(let t=0;t1&&(q||M())&&console.warn(`Multiple layers are not supported yet `+this.animator?.name);for(let e of this.model.layers){let t=e.stateMachine;t.defaultState===void 0&&(q&&console.warn(`AnimatorController default state is undefined, will assign state 0 as default`,e),t.defaultState=0);let n=t.states[t.defaultState];this.transitionTo(n,0,this.normalizedStartOffset);break}}evaluateTransitions(){let e=!1;if(!this._activeState){if(this.setStartTransition(),!this._activeState)return;e=!0}let t=this._activeState,n=t.motion.action,r=0;for(let e of t.transitions){if(++r,!e.hasExitTime&&e.conditions.length<=0)continue;let i=!0;for(let t of e.conditions)if(!this.evaluateCondition(t)){i=!1;break}if(i)if(n){let r=t.motion.clip.duration,i=r<=0?1:Math.abs(n.time/r),a=e.exitTime;n.timeScale<0&&(a=1-a);let o=!1;if(e.hasExitTime?n.timeScale>0?o=i>=e.exitTime:n.timeScale<0&&(o=1-i>=e.exitTime):o=!0,o){for(let t of e.conditions){let e=this.model.parameters.find(e=>e.name===t.parameter);e?.type===im.Trigger&&e.value&&(e.value=!1)}if(n.clampWhenFinished=!0,q){let t=this.getState(e.destinationState,0);console.log(`Transition to ${e.destinationState} / ${t?.name}`,e,` Timescale: `+n.timeScale,` Normalized time: `+i.toFixed(3),` Exit Time: `+a,e.hasExitTime)}this.transitionTo(e.destinationState,e.duration,e.offset);return}}else{this.transitionTo(e.destinationState,e.duration,e.offset);return}}n&&this.setTimescale(n,t);let i=!1;if(t.motion.isLooping&&n&&(n.time>=n.getClip().duration?(i=!0,n.reset(),n.time=0,n.play()):n.time<=0&&n.timeScale<0&&(i=!0,n.reset(),n.time=n.getClip().duration,n.play())),!i&&t&&!e&&n&&this.animator&&t.behaviours){let e=n?.getClip().duration,r=n.time/e,i=new tm(this._activeState,r,e,this._speed);for(let e of t.behaviours)e.instance&&e.instance.onStateUpdate?.call(e.instance,this.animator,i,0)}}setTimescale(e,t){let n=t.speed??1;t.speedParameter&&(n*=this.getFloat(t.speedParameter)),n!==void 0&&(e.timeScale=n*this._speed)}getState(e,t){return typeof e==`number`&&(e==-1&&(e=this.model.layers[t].stateMachine.defaultState,e===void 0&&(q&&console.warn(`AnimatorController default state is undefined: `,this.model,`Layer: `+t),e=0)),e=this.model.layers[t].stateMachine.states[e]),e}_heldActions=[];releaseHeldActions(e){for(let t of this._heldActions)t.fadeOut(e);this._heldActions.length=0}transitionTo(e,t,n){if(!this.animator||(e=this.getState(e,0),!e?.motion||!e.motion.clip||!(e.motion.clip instanceof Se)))return;let r=this._activeState===e;if(r){let t=e.motion;if(!t.action_loopback&&t.clip){let e=this.rootMotionHandler?this.animator.gameObject.matrix.clone():null;this._mixer.uncacheAction(t.clip,this.animator.gameObject),e&&e.decompose(this.animator.gameObject.position,this.animator.gameObject.quaternion,this.animator.gameObject.scale),t.action_loopback=this.createAction(t.clip)}}if(this._activeState?.behaviours&&this._activeState.motion.action){let e=this._activeState?.motion.clip.duration,t=this._activeState.motion.action.time/e,n=new tm(this._activeState,t,e,this._speed);for(let e of this._activeState.behaviours)e.instance?.onStateExit?.call(e.instance,this.animator,n,0)}let i=this._activeState?.motion.action;r&&(e.motion.action=e.motion.action_loopback,e.motion.action_loopback=i);let a=this._activeState;this._activeState=e;let o=e.motion?.action,s=e.motion.clip;if(s?.duration<=0&&s.tracks.length<=0?i&&this._heldActions.push(i):i&&(i.fadeOut(t),this.releaseHeldActions(t)),o){if(n=Math.max(0,Math.min(1,n)),e.cycleOffsetParameter){let t=this.getFloat(e.cycleOffsetParameter);typeof t==`number`?(t<0&&(t+=1),n+=t,n%=1):q&&console.warn(`AnimatorController cycle offset parameter is not a number`,e.cycleOffsetParameter)}else typeof e.cycleOffset==`number`&&(n+=e.cycleOffset,n%=1);o.isRunning()&&o.stop(),o.reset(),o.enabled=!0,this.setTimescale(o,e);let i=e.motion.clip.duration;if(o.time=r?0:n*i,o.timeScale<0&&(o.time=i-o.time),o.clampWhenFinished=!0,o.setLoop(oe,0),t>0?o.fadeIn(t):o.weight=1,o.play(),window.requestAnimationFrame(()=>Pi.testIfRootCanAnimate(o)),this.rootMotionHandler&&this.rootMotionHandler.onStart(o),this._activeStates.includes(e)||this._activeStates.push(e),this._activeState.behaviours){let t=new tm(e,n,i,this._speed);for(let e of this._activeState.behaviours)e.instance?.onStateEnter?.call(e.instance,this.animator,t,0)}}else q&&(e.__warned_no_motion||(e.__warned_no_motion=!0,console.warn(`No action`,e.motion,this)));q&&console.log(`TRANSITION FROM `+a?.name+` TO `+e.name,t,i,o,o?.getEffectiveTimeScale(),o?.getEffectiveWeight(),o?.isRunning(),o?.isScheduled(),o?.paused)}createAction(e){if(this._mixer.existingAction(e)&&this._mixer.uncacheAction(e,this.animator?.gameObject),this.animator?.applyRootMotion){this.rootMotionHandler||=new lm(this);let t=this.animator.gameObject;return this.rootMotionHandler.createClip(this._mixer,t,e)}else return this._mixer.clipAction(e)}evaluateCondition(e){let t=this.model.parameters.find(t=>t.name===e.parameter);if(!t)return!1;switch(e.mode){case rm.If:return t.value===!0;case rm.IfNot:return t.value===!1;case rm.Greater:return t.value>e.threshold;case rm.Less:return t.valuee.node.name===this.animator?.gameObject?.name);e?n.motion.clip=e.clip:(q||M())&&console.warn(`Could not find clip for animator "`+this.animator?.gameObject?.name+`"`,n.motion.clips.map(e=>e.node.name))}if(!n.motion.clip){q&&console.warn(`No clip assigned to state`,n);let e=new Se(void 0,void 0,[]);n.motion.clip=e}if(n.motion?.clip){let e=n.motion.clip;if(e instanceof Se){let t=this.createAction(e);n.motion.action=t}else (q||M())&&console.warn(`No valid animationclip assigned`,n)}if(n.behaviours&&Array.isArray(n.behaviours))for(let e of n.behaviours){if(!e?.typeName)continue;let t=ji.get(e.typeName);if(t){let r=new t;r.isStateMachineBehaviour&&(r._context=this.context??void 0,Es(r,e.properties),e.instance=r),q&&console.log(`Created animator controller behaviour`,n.name,e.typeName,e.properties,r)}else (q||M())&&console.warn(`Could not find AnimatorBehaviour type: `+e.typeName)}}}}*enumerateActions(){if(this.model.layers)for(let e of this.model.layers){let t=e.stateMachine;for(let e=0;e(n.createInterpolant=r,this.createdInterpolant=r(),this.originalEvaluate=this.createdInterpolant.evaluate.bind(this.createdInterpolant),this.customEvaluate=e=>{if(this.originalEvaluate)return t(e,this.originalEvaluate(e))},this.createdInterpolant.evaluate=this.customEvaluate,this.createdInterpolant)}dispose(){this.createdInterpolant&&this.originalEvaluate&&(this.createdInterpolant.evaluate=this.originalEvaluate),this.track=void 0,this.createdInterpolant=null,this.originalEvaluate=void 0,this.customEvaluate=void 0}},cm=class e{static lastObjPosition={};static lastObjRotation={};static firstKeyframeRotation={};static spaceRotation={};static effectiveSpaceRotation={};static clipOffsetRotation={};set action(e){this._action=e}get action(){return this._action}get cacheId(){return this.root.uuid}_action;root;clip;positionWrapper=null;rotationWrapper=null;context;positionChange=new o;rotationChange=new E;constructor(t,n,r,i,a){if(this.context=t,this.root=n,this.clip=r,e.firstKeyframeRotation[this.cacheId]||(e.firstKeyframeRotation[this.cacheId]=new E),a){let t=a.values;e.firstKeyframeRotation[this.cacheId].set(t[0],t[1],t[2],t[3])}e.spaceRotation[this.cacheId]||(e.spaceRotation[this.cacheId]=new E),e.effectiveSpaceRotation[this.cacheId]||(e.effectiveSpaceRotation[this.cacheId]=new E),e.clipOffsetRotation[this.cacheId]=new E,a&&e.clipOffsetRotation[this.cacheId].set(a.values[0],a.values[1],a.values[2],a.values[3]).invert(),this.handlePosition(r,i),this.handleRotation(r,a)}onStart(t){if(t.getClip()!==this.clip)return;e.lastObjRotation[this.cacheId]||(e.lastObjRotation[this.cacheId]=this.root.quaternion.clone());let n=e.lastObjRotation[this.cacheId];if(e.spaceRotation[this.cacheId].copy(n),am){let e=new He().setFromQuaternion(n);console.log(`START`,this.clip.name,N.toDegrees(e.y),this.root.position.z)}}getClipRotationOffset(){return e.clipOffsetRotation[this.cacheId]}_prevTime=0;handlePosition(t,n){if(n){let t=this.root;am&&t.add(new _e),e.lastObjPosition[this.cacheId]||(e.lastObjPosition[this.cacheId]=this.root.position.clone());let r=new o,i=new o;this.positionWrapper=new sm(n,(e,n)=>{let a=this.action.getEffectiveWeight();return am&&t.position.length()>8&&t.position.set(0,t.position.y,0),e>this._prevTime&&(r.set(n[0],n[1],n[2]),r.sub(i),r.multiplyScalar(a),r.applyQuaternion(this.getClipRotationOffset()),r.applyQuaternion(t.quaternion),this.positionChange.copy(r)),i.fromArray(n),this._prevTime=e,n[0]=0,n[1]=0,n[2]=0,n})}}static identityQuaternion=new E;handleRotation(e,t){if(t){if(am){let n=t.values,r=new He().setFromQuaternion(new E(n[0],n[1],n[2],n[3]));console.log(e.name,t.name,`FIRST ROTATION IN TRACK`,N.toDegrees(r.y));let i=t.values.length-4,a=new E().set(n[i],n[i+1],n[i+2],n[i+3]),o=new He().setFromQuaternion(a);console.log(e.name,t.name,`LAST ROTATION IN TRACK`,N.toDegrees(o.y))}let n=0,r=new E,i=new E;this.rotationWrapper=new sm(t,(e,t)=>(e>n&&(i.set(t[0],t[1],t[2],t[3]),r.invert(),i.multiply(r),this.rotationChange.copy(i)),r.fromArray(t),n=e,t[0]=0,t[1]=0,t[2]=0,t[3]=1,t))}}onBeforeUpdate(e){this.positionChange.set(0,0,0),this.rotationChange.set(0,0,0,1)}onAfterUpdate(t){return!this.action||(t*=this.action.getEffectiveWeight(),t<=0)?!1:(this.positionChange.multiplyScalar(t),this.rotationChange.slerp(e.identityQuaternion,1-t),!0)}},lm=class{controller;handler=[];root;basePosition=new o;baseQuaternion=new E;baseRotation=new He;constructor(e){this.controller=e}createClip(e,t,n){this.root=t,t&&`name`in t&&t.name;let r=this.findRootTrack(n,`.position`),i=this.findRootTrack(n,`.quaternion`),a=new cm(this.controller.context,t,n,r,i);this.handler.push(a);let o=e.clipAction(n);return a.action=o,o}onStart(e){for(let t of this.handler)t.onStart(e)}onBeforeUpdate(e){this.basePosition.copy(this.root.position),this.baseQuaternion.copy(this.root.quaternion);for(let t of this.handler)t.onBeforeUpdate(e)}summedPosition=new o;summedRotation=new E;onAfterUpdate(e){if(!(e<=0)){this.root.position.copy(this.basePosition),this.root.quaternion.copy(this.baseQuaternion),this.summedPosition.set(0,0,0),this.summedRotation.set(0,0,0,1);for(let t of this.handler)t.onAfterUpdate(e)&&(this.summedPosition.add(t.positionChange),this.summedRotation.multiply(t.rotationChange));this.root.position.add(this.summedPosition),this.root.quaternion.multiply(this.summedRotation)}}findRootTrack(e,t){let n=e.tracks;if(!n)return null;for(let e of n)if(e.name.endsWith(t))return e;return null}};new class extends ds{onSerialize(e,t){}onDeserialize(e,t){if(t.type===om&&e?.__type===`AnimatorController`)return new om(e)}}(om);var um=function(e,t,n,r){var i=arguments.length,a=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r,o;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)a=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(o=e[s])&&(a=(i<3?o(a):i>3?o(t,n,a):o(t,n))||a);return i>3&&a&&Object.defineProperty(t,n,a),a},dm=A(`debuganimator`),fm=class extends K{get isAnimationComponent(){return!0}applyRootMotion=!1;hasRootMotion=!1;keepAnimatorControllerStateOnDisable=!1;set runtimeAnimatorController(e){this._animatorController&&this._animatorController.model===e||(e?e instanceof om?(e.animator&&e.animator!==this&&(console.warn(`AnimatorController can not be bound to multiple animators`,e.model?.name),e.model||console.error(`AnimatorController has no model`),e=new om(e.model)),this._animatorController=e,this._animatorController.bind(this)):(dm&&console.log(`Assign animator controller`,e,this),this._animatorController=new om(e),this.__didAwake&&this._animatorController.bind(this)):this._animatorController=null)}get runtimeAnimatorController(){return this._animatorController}getCurrentStateInfo(){return this.runtimeAnimatorController?.getCurrentStateInfo()}get currentAction(){return this.runtimeAnimatorController?.currentAction||null}get parametersAreDirty(){return this._parametersAreDirty}_parametersAreDirty=!1;get isDirty(){return this._isDirty}_isDirty=!1;Play(e,t=-1,n=-1/0,r=0){this.play(e,t,n,r)}play(e,t=-1,n=-1/0,r=0){this.runtimeAnimatorController?.play(e,t,n,r),this._isDirty=!0}Reset(){this.reset()}reset(){this._animatorController?.reset(),this._isDirty=!0}SetBool(e,t){this.setBool(e,t)}setBool(e,t){dm&&console.log(`setBool`,e,t),this.runtimeAnimatorController?.getBool(e)!==t&&(this._parametersAreDirty=!0),this.runtimeAnimatorController?.setBool(e,t)}GetBool(e){return this.getBool(e)}getBool(e){let t=this.runtimeAnimatorController?.getBool(e)??!1;return dm&&console.log(`getBool`,e,t),t}toggleBool(e){this.setBool(e,!this.getBool(e))}SetFloat(e,t){this.setFloat(e,t)}setFloat(e,t){this.runtimeAnimatorController?.getFloat(e)!==t&&(this._parametersAreDirty=!0),dm&&console.log(`setFloat`,e,t),this.runtimeAnimatorController?.setFloat(e,t)}GetFloat(e){return this.getFloat(e)}getFloat(e){let t=this.runtimeAnimatorController?.getFloat(e)??-1;return dm&&console.log(`getFloat`,e,t),t}SetInteger(e,t){this.setInteger(e,t)}setInteger(e,t){this.runtimeAnimatorController?.getInteger(e)!==t&&(this._parametersAreDirty=!0),dm&&console.log(`setInteger`,e,t),this.runtimeAnimatorController?.setInteger(e,t)}GetInteger(e){return this.getInteger(e)}getInteger(e){let t=this.runtimeAnimatorController?.getInteger(e)??-1;return dm&&console.log(`getInteger`,e,t),t}SetTrigger(e){this.setTrigger(e)}setTrigger(e){this._parametersAreDirty=!0,dm&&console.log(`setTrigger`,e),this.runtimeAnimatorController?.setTrigger(e)}ResetTrigger(e){this.resetTrigger(e)}resetTrigger(e){this._parametersAreDirty=!0,dm&&console.log(`resetTrigger`,e),this.runtimeAnimatorController?.resetTrigger(e)}GetTrigger(e){this.getTrigger(e)}getTrigger(e){let t=this.runtimeAnimatorController?.getTrigger(e);return dm&&console.log(`getTrigger`,e,t),t}IsInTransition(){return this.isInTransition()}isInTransition(){return this.runtimeAnimatorController?.isInTransition()??!1}SetSpeed(e){return this.setSpeed(e)}setSpeed(e){e!==this._speed&&(dm&&console.log(`setSpeed`,e),this._speed=e,this._animatorController?.animator==this&&this._animatorController.setSpeed(e))}set minMaxSpeed(e){this._speed=N.lerp(e.x,e.y,Math.random()),this._animatorController?.animator==this&&this._animatorController.setSpeed(this._speed)}set minMaxOffsetNormalized(e){this._normalizedStartOffset=N.lerp(e.x,e.y,Math.random()),this.runtimeAnimatorController?.animator==this&&(this.runtimeAnimatorController.normalizedStartOffset=this._normalizedStartOffset)}_speed=1;_normalizedStartOffset=0;_animatorController=null;awake(){dm&&console.log(`ANIMATOR`,this.name,this),this.gameObject&&this.initializeRuntimeAnimatorController()}_initializeWithRuntimeAnimatorController;initializeRuntimeAnimatorController(e=!1){let t=e||this.runtimeAnimatorController!==this._initializeWithRuntimeAnimatorController;if(this.runtimeAnimatorController&&t){let e=this.runtimeAnimatorController.clone();this._initializeWithRuntimeAnimatorController=e,e?(console.assert(this.runtimeAnimatorController!==e),this.runtimeAnimatorController=e,console.assert(this.runtimeAnimatorController===e),this.runtimeAnimatorController.bind(this),this.runtimeAnimatorController.setSpeed(this._speed),this.runtimeAnimatorController.normalizedStartOffset=this._normalizedStartOffset):console.warn(`Could not clone animator controller`,this.runtimeAnimatorController)}}onDisable(){this.keepAnimatorControllerStateOnDisable||this._animatorController?.reset()}onBeforeRender(){this._isDirty=!1,this._parametersAreDirty=!1,!$p(this.gameObject)&&this._animatorController&&this._animatorController.update(1)}};um([F()],fm.prototype,`applyRootMotion`,void 0),um([F()],fm.prototype,`hasRootMotion`,void 0),um([F()],fm.prototype,`keepAnimatorControllerStateOnDisable`,void 0),um([F()],fm.prototype,`runtimeAnimatorController`,null);var pm=[],mm=class{enabled=!0;target;methodName;arguments;get canClone(){return this.target instanceof Object}constructor(e,t,n,r){this.target=e,this.methodName=t||null,this.arguments=n,r!=null&&(this.enabled=r)}invoke(...e){if(this.enabled!==!1){if(typeof this.target==`function`)this.arguments?(pm.length=0,e!==void 0&&e.length>0&&pm.push(...e),pm.push(...this.arguments),this.target(...this.arguments),pm.length=0):this.target(...e);else if(this.methodName!=null){let t=this.target[this.methodName];typeof t==`function`?this.arguments?(pm.length=0,e!==void 0&&e.length>0&&pm.push(...e),pm.push(...this.arguments),t.call(this.target,...pm),pm.length=0):t.call(this.target,...e):this.arguments?e!==void 0&&e.length>0?this.target[this.methodName]=e[0]:this.target[this.methodName]=this.arguments[0]:this.target[this.methodName]=e[0]}}}},hm=e=>/^[A-Z]*$/.test(e),gm=class extends Event{args},_m=class e{isEventList=!0;__internalOnInstantiate(t){let n=[];for(let e=0;ee instanceof Object&&e.uuid?t[e.uuid].clone:e?.isComponent?t[e.guid].clone:e);n.push(new mm(e.clone,r.methodName,i,r.enabled))}else M()&&console.warn(`Could not find target for event listener`)}}}return new e(n)}target;key;setEventTarget(e,t){if(this.key=e,this.target=t,this.key!==void 0){let e=``,t=!1;for(let n of this.key)t&&hm(n)&&(e+=`-`),t=!0,e+=n.toLowerCase();this.key=e}}get listenerCount(){return this.methods?.length??0}get isInvoking(){return this._isInvoking}_isInvoking=!1;methods=[];_methodsCopy=[];static from(...t){return new e(t)}constructor(e){if(this.methods=[],Array.isArray(e))for(let t of e)t instanceof mm?this.methods.push(t):typeof t==`function`&&this.methods.push(new mm(t));else typeof e==`function`&&this.methods.push(new mm(e))}invoke(...e){if(this._isInvoking)return console.warn(`Circular event invocation detected. Please check your event listeners for circular references.`,this),!1;if(this.methods?.length<=0)return!1;this._isInvoking=!0;try{this._methodsCopy.length=0,this._methodsCopy.push(...this.methods);for(let t of this._methodsCopy)t.invoke(...e);if(typeof this.target==`object`&&typeof this.key==`string`){let t=this.target.dispatchEvent;if(typeof t==`function`){let n=new gm(this.key);n.args=e,t.call(this.target,n)}}}finally{this._isInvoking=!1,this._methodsCopy.length=0}return!0}addEventListener(e){return this.methods.push(new mm(e)),()=>this.removeEventListener(e)}removeEventListener(e){if(!e)return!1;let t=!1;for(let n=this.methods.length-1;n>=0;n--)this.methods[n].target===e&&(this.methods[n].enabled=!1,this.methods.splice(n,1),t=!0);return t}removeAllEventListeners(){this.methods.length=0}},vm=Symbol(`previous-visibility`),ym=class e extends d{render(e,t,n){if(`addPass`in n)this._unsupported_effectcomposer_warning||=(console.warn(`RenderTexture.render() does not yet support EffectComposer`),!0);else if(n instanceof h){this.onBeforeRender();let r=n.getRenderTarget(),i=n.xr.enabled;n.xr.enabled=!1,n.setRenderTarget(this),n.clear(!0,!0,!0),n.render(e,t),n.setRenderTarget(r),n.xr.enabled=i,this.onAfterRender()}}static _userSet=new Set;onBeforeRender(){e._userSet.clear();let t=ef(this.texture,!0,null,e._userSet);for(let e of t)e instanceof x&&(e[vm]=e.visible,e.visible=!1)}onAfterRender(){for(let t of e._userSet)t instanceof x&&(t.visible=t[vm]);e._userSet.clear()}},bm=function(e,t,n,r){var i=arguments.length,a=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r,o;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)a=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(o=e[s])&&(a=(i<3?o(a):i>3?o(t,n,a):o(t,n))||a);return i>3&&a&&Object.defineProperty(t,n,a),a},xm=A(`debuggroundprojection`),Sm=` #ifdef NEEDLE_USE_CUBE_UV_MAP varying vec3 vNeedleGroundProjectionWorldDirection; #endif `,Cm=` ${Sm} uniform float needleGroundProjectionBlurriness; uniform float needleGroundProjectionBlending; uniform float needleGroundProjectionAlphaFactor; uniform float needleGroundProjectionBackgroundIntensity; float needleGroundProjectionSmoothstep(float edge0, float edge1, float x) { float t = clamp((x - edge0) / max(edge1 - edge0, 0.000001), 0.0, 1.0); return t * t * (3.0 - 2.0 * t); } float needleGroundProjectionDistance() { return length(vec2(0.0, vMapUv.y)); } float needleGroundProjectionBlurFactor(float needleGroundProjectionDistanceValue) { return clamp(needleGroundProjectionSmoothstep(0.5, 1.0, needleGroundProjectionDistanceValue * 2.0), 0.0, 1.0); } `,wm=` #ifdef USE_MAP float needleGroundProjectionDistanceValue = needleGroundProjectionDistance(); float needleGroundProjectionBlurFactorValue = needleGroundProjectionBlurFactor(needleGroundProjectionDistanceValue); vec4 sampledDiffuseColor; #ifdef NEEDLE_USE_CUBE_UV_MAP sampledDiffuseColor = textureCubeUV( map, normalize( vNeedleGroundProjectionWorldDirection ), needleGroundProjectionBlurriness * needleGroundProjectionBlurFactorValue ); #else #ifdef USE_MIPMAP_BIAS sampledDiffuseColor = texture2D( map, vMapUv, mipmapBias ); #else sampledDiffuseColor = texture2D( map, vMapUv ); #endif #endif #ifdef DECODE_VIDEO_TEXTURE // use inline sRGB decode until browsers properly support SRGB8_ALPHA8 with video textures (#26516) sampledDiffuseColor = vec4( mix( pow( sampledDiffuseColor.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), sampledDiffuseColor.rgb * 0.0773993808, vec3( lessThanEqual( sampledDiffuseColor.rgb, vec3( 0.04045 ) ) ) ), sampledDiffuseColor.w ); #endif sampledDiffuseColor.rgb *= mix(1.0, needleGroundProjectionBackgroundIntensity, needleGroundProjectionBlurFactorValue); diffuseColor *= sampledDiffuseColor; #endif `,Tm=` #ifdef USE_MAP if (needleGroundProjectionBlending > 0.000001) { float needleGroundProjectionBrightness = dot(diffuseColor.rgb, vec3(0.299, 0.587, 0.114)); float needleGroundProjectionStepFactor = needleGroundProjectionBlending - needleGroundProjectionBrightness * 0.1; diffuseColor.a *= pow( 1.0 - needleGroundProjectionBlending * needleGroundProjectionSmoothstep( 0.35 * needleGroundProjectionStepFactor, 0.45 * needleGroundProjectionStepFactor, needleGroundProjectionDistanceValue ), 5.0 ); } #endif diffuseColor.a *= needleGroundProjectionAlphaFactor; `;function Em(e){let t=e.image?.height;if(!t)return null;let n=Math.log2(t)-2,r=1/t;return{texelWidth:1/(3*Math.max(2**n,112)),texelHeight:r,maxMip:n}}function Dm(e){let t=e.userData;return t.needleGroundProjectionUniforms??={needleGroundProjectionBlurriness:{value:0},needleGroundProjectionBlending:{value:0},needleGroundProjectionAlphaFactor:{value:1},needleGroundProjectionBackgroundIntensity:{value:1}}}function Om(e,t){let n=Dm(e);e.onBeforeCompile=e=>{e.uniforms.needleGroundProjectionBlurriness=n.needleGroundProjectionBlurriness,e.uniforms.needleGroundProjectionBlending=n.needleGroundProjectionBlending,e.uniforms.needleGroundProjectionAlphaFactor=n.needleGroundProjectionAlphaFactor,e.uniforms.needleGroundProjectionBackgroundIntensity=n.needleGroundProjectionBackgroundIntensity,e.vertexShader=e.vertexShader.replace(`#include `,`#include \n${Sm}`).replace(`#include `,`#include #ifdef NEEDLE_USE_CUBE_UV_MAP // GroundedSkybox mirrors geometry on Z, so undo that before deriving the sampling direction. vNeedleGroundProjectionWorldDirection = transformDirection( vec3( position.x, position.y, -position.z ), modelMatrix ); #endif`),e.fragmentShader=e.fragmentShader.replace(`#include `,`#include ${Cm} #include `).replace(`#include `,wm).replace(`#include `,`${Tm}\n#include `)};let r=e.defines??={},i=JSON.stringify(r),a=t.mapping===306?Em(t):null;a?(r.NEEDLE_USE_CUBE_UV_MAP=1,r.ENVMAP_TYPE_CUBE_UV=1,r.CUBEUV_TEXEL_WIDTH=a.texelWidth,r.CUBEUV_TEXEL_HEIGHT=a.texelHeight,r.CUBEUV_MAX_MIP=`${a.maxMip}.0`):(delete r.NEEDLE_USE_CUBE_UV_MAP,delete r.ENVMAP_TYPE_CUBE_UV,delete r.CUBEUV_TEXEL_WIDTH,delete r.CUBEUV_TEXEL_HEIGHT,delete r.CUBEUV_MAX_MIP),i!==JSON.stringify(r)&&(e.needsUpdate=!0)}var km=class extends K{applyOnAwake=!1;autoFit=!0;set radius(e){this._radius=e,this._projection&&this.updateProjection()}get radius(){return this._radius}_radius=50;set height(e){this._height=e,this._projection&&this.updateProjection()}get height(){return this._height}_height=3;set arBlending(e){this._arblending=e,this._needsTextureUpdate=!0}get arBlending(){return this._arblending}_arblending=0;_lastBackground;_lastRadius;_lastHeight;_projection;_watcher;awake(){this.applyOnAwake&&this.updateAndCreate()}onEnable(){this.context.time.frameCount>0&&this.applyOnAwake&&this.updateAndCreate(),this._watcher||(this._watcher=new en(this.context.scene,`background`),this._watcher.subscribeWrite(e=>{xm&&console.log(`Background changed`,this.context.scene.background),this._needsTextureUpdate=!0}))}onDisable(){this._watcher?.revoke(),this._projection?.removeFromParent()}onEnterXR(){this.activeAndEnabled&&(this._needsTextureUpdate=!0,this.updateProjection())}async onLeaveXR(){this.activeAndEnabled&&(await qt(1),this.updateProjection())}onBeforeRender(){if(this._projection&&this.scene.backgroundRotation&&this._projection.rotation.copy(this.scene.backgroundRotation),this._projection&&this.context.scene.background instanceof be){let e=this.context.scene.backgroundBlurriness??0,t=this._lastBlurriness!==e;this.updateProjectionMaterial(this.context.scene.background,t||this._needsTextureUpdate)}}updateAndCreate(){this.updateProjection(),this._watcher?.apply()}_needsTextureUpdate=!1;updateProjection(){if(!this.context.scene.background){this._projection?.removeFromParent();return}let e=this.context.scene.background;if(!(e instanceof be)){this._projection?.removeFromParent();return}if((this.context.xr?.isPassThrough||this.context.xr?.isAR)&&this.arBlending===0){this._projection?.removeFromParent();return}if(!this.gameObject||this.destroyed)return;let t=!0,n=e!==this._lastBackground||this._height!==this._lastHeight||this._radius!==this._lastRadius;if(!this._projection||n){xm&&console.log(`Create/Update Ground Projection`,e.name),this._projection?.removeFromParent();try{this._projection=new ct(e,this._height,this._radius,64),Om(this._projection.material,e)}catch(e){console.error(`Error creating three GroundProjection`,e);return}this._projection.position.y=this._height-0,this._projection.name=`GroundProjection`,ui(this._projection,!1)}else t=!1;if(this._projection.parent||this.gameObject.add(this._projection),this.autoFit&&t){this._projection.updateWorldMatrix(!0,!0);let e=fi(this.context.scene.children,[this._projection]),t=e.min.y;if(t<1/0){let n=P();n.x=e.min.x+(e.max.x-e.min.x)*.5;let r=zr(this.gameObject).x;n.y=t+this._height*r-0,n.z=e.min.z+(e.max.z-e.min.z)*.5,kr(this._projection,n)}xm&&H.DrawWireBox3(e,65280,5)}this.updateProjectionMaterial(e,!0),this._lastBackground=e,this._lastHeight=this._height,this._lastRadius=this._radius,this._needsTextureUpdate=!1}_blurrynessShader=null;_lastBlurriness=-1;updateProjectionMaterial(e,t=!1){if(!this._projection)return;let n=this.context.scene.backgroundBlurriness??0,r=e.mapping===306,i=e;if(!r&&n>.001){let r=!!this._projection.material.map&&this._projection.material.map!==e;t||!r?i=this.updateBlurriness(e,n):this._projection.material.map&&(i=this._projection.material.map)}this._projection.material.map!==i&&(this._projection.material.map=i);let a=this._projection.material.map??e;a.mapping=e.mapping,Om(this._projection.material,a);let o=Dm(this._projection.material);o.needleGroundProjectionBlurriness.value=r?n:0,o.needleGroundProjectionBackgroundIntensity.value=this.context.scene.backgroundIntensity??1;let s=this._projection.material.transparent;this._projection.material.transparent=this.context.xr?.isAR===!0&&this.arBlending>1e-6,o.needleGroundProjectionBlending.value=this._projection.material.transparent?this.arBlending:0,o.needleGroundProjectionAlphaFactor.value=this.context.isInPassThrough?.95:1,s!==this._projection.material.transparent&&(this._projection.material.needsUpdate=!0),this._projection.material.depthTest=!0,this._projection.material.depthWrite=!1,this._lastBlurriness=n,this._needsTextureUpdate=!1}updateBlurriness(e,t){xm&&console.log(`Update Blurriness`,t),this._blurrynessShader??=new Ve({name:`GroundProjectionBlurriness`,uniforms:{map:{value:e},blurriness:{value:t}},vertexShader:Am,fragmentShader:jm}),this._blurrynessShader.depthWrite=!1,this._blurrynessShader.uniforms.map.value=e,this._blurrynessShader.uniforms.blurriness.value=t,e.needsUpdate=!0;let n=ai.copyTexture(e,this._blurrynessShader);return n.mapping=e.mapping,n}};bm([F()],km.prototype,`applyOnAwake`,void 0),bm([F()],km.prototype,`autoFit`,void 0),bm([F()],km.prototype,`radius`,null),bm([F()],km.prototype,`height`,null),bm([F()],km.prototype,`arBlending`,null);var Am=` varying vec2 vUv; void main() { vUv = uv; gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0); } `,jm=` uniform sampler2D map; uniform float blurriness; varying vec2 vUv; const float PI = 3.14159265359; // Gaussian function float gaussian(float x, float sigma) { return exp(-(x * x) / (2.0 * sigma * sigma)) / (sqrt(2.0 * PI) * sigma); } // Custom smoothstep function for desired falloff float customSmoothstep(float edge0, float edge1, float x) { float t = clamp((x - edge0) / (edge1 - edge0), 0.0, 1.0); return t * t * (3.0 - 2.0 * t); } void main() { vec2 center = vec2(0.0, 0.0); vec2 pos = vUv; pos.x = 0.0; // Only consider vertical distance float distance = length(pos - center); // Calculate blur amount based on custom falloff float blurAmount = customSmoothstep(0.5, 1.0, distance * 2.0); blurAmount = clamp(blurAmount, 0.0, 1.0); // Ensure blur amount is within valid range // Gaussian blur vec2 pixelSize = 1.0 / vec2(textureSize(map, 0)); vec4 color = vec4(0.0); float totalWeight = 0.0; int blurSize = int(60.0 * min(1.0, blurriness) * blurAmount); // Adjust blur size based on distance and blurriness if (blurSize <= 0) { gl_FragColor = texture2D(map, vUv); return; } float lodLevel = log2(float(blurSize)) * 0.5; // Compute LOD level for (int x = -blurSize; x <= blurSize; x++) { for (int y = -blurSize; y <= blurSize; y++) { vec2 offset = vec2(float(x), float(y)) * pixelSize * blurAmount; float weight = gaussian(length(vec2(float(x), float(y))), 1000.0 * blurAmount); // Use a fixed sigma value color += textureLod(map, vUv + offset, lodLevel) * weight; totalWeight += weight; } } color = totalWeight > 0.0 ? color / totalWeight : texture2D(map, vUv); gl_FragColor = color; // #include // #include // Uncomment to visualize blur amount // gl_FragColor = vec4(blurAmount, 0.0, 0.0, 1.0); } `;function Mm(e){if(pd.active)return console.warn(`[OrbitControls] Can not fit camera while XR session is active`),null;let t=B.Current;if(!t)return console.warn(`[OrbitControls] No context found`),null;let n=e?.camera||t.mainCamera;if(!n)return console.warn(`No camera or controls found to fit camera to objects...`),null;e||={},e.autoApply=e.autoApply!==!1,e.minZoom||=0,e.maxZoom||=1/0;let{centerCamera:r,cameraNearFar:i=`auto`,fitOffset:a=1.1,fov:s=n instanceof C?n?.fov:-1}=e,c=new o,l=new o,u=n instanceof C?n.aspect:1,d=fi(e.objects||t.scene,void 0,n?.layers),f=d.clone();d.getCenter(l);let p=new o;if(d.getSize(p),n instanceof C&&n.updateProjectionMatrix(),n.updateMatrixWorld(),d.applyMatrix4(n.matrixWorldInverse),d.getSize(c),d.setFromCenterAndSize(l,c),Number.isNaN(c.x)||Number.isNaN(c.y)||Number.isNaN(c.z))return console.warn(`Camera fit size resultet in NaN`,n,d),null;if(c.length()<=1e-10)return console.warn(`Camera fit size is zero`,d),null;let m=s,h=2*Math.atan(Math.tan(m*Math.PI/360/2)*u)/Math.PI*360,g=c.y/(2*Math.atan(Math.PI*m/360)),_=c.x/(2*Math.atan(Math.PI*h/360)),v=a*Math.max(g,_)+c.z/2;e.maxZoom=v*10,e.minZoom=v*.01,e.debug===!0&&console.log(`Fit camera to objects`,{fitHeightDistance:g,fitWidthDistance:_,distance:v,verticalFov:m,horizontalFov:h});let ee=.05,y=l.clone();if(y.y-=c.y*ee,e.targetOffset&&(e.targetOffset.x!==void 0&&(y.x+=e.targetOffset.x),e.targetOffset.y!==void 0&&(y.y+=e.targetOffset.y),e.targetOffset.z!==void 0&&(y.z+=e.targetOffset.z)),e.relativeTargetOffset&&(e.relativeTargetOffset.x!==void 0&&(y.x+=e.relativeTargetOffset.x*c.x),e.relativeTargetOffset.y!==void 0&&(y.y+=e.relativeTargetOffset.y*c.y),e.relativeTargetOffset.z!==void 0&&(y.z+=e.relativeTargetOffset.z*c.z)),i==null||i==`auto`){let t=Rp(km),r=t?t.radius:0,i=Math.max(p.x,p.y,p.z,r);n instanceof C&&(n.near=v/100,n.far=i+v*10,n.updateProjectionMatrix()),t&&(e.maxZoom=Math.max(Math.min(e.maxZoom,r*.5),v))}e.currentZoom!==void 0&&(e.currentZoome.maxZoom&&(e.maxZoom=e.currentZoom*1.1));let b=l.clone();e.fitDirection?b.sub(new o().copy(e.fitDirection).multiplyScalar(1e6)):b.sub(n.worldPosition),r===`y`&&(b.y=0),b.normalize(),b.multiplyScalar(v),r===`y`&&(b.y+=-ee*4*v);let te=l.clone().sub(b);return e.cameraOffset&&(e.cameraOffset.x!==void 0&&(te.x+=e.cameraOffset.x),e.cameraOffset.y!==void 0&&(te.y+=e.cameraOffset.y),e.cameraOffset.z!==void 0&&(te.z+=e.cameraOffset.z)),e.relativeCameraOffset&&(e.relativeCameraOffset.x!==void 0&&(te.x+=e.relativeCameraOffset.x*c.x),e.relativeCameraOffset.y!==void 0&&(te.y+=e.relativeCameraOffset.y*c.y),e.relativeCameraOffset.z!==void 0&&(te.z+=e.relativeCameraOffset.z*c.z)),n.parent&&(te=n.parent.worldToLocal(te)),e.debug&&(H.DrawWireBox3(d,16777011,10),H.DrawWireBox3(f,65280,10)),e.autoApply&&(n.position.copy(te),n.lookAt(y),s>0&&n instanceof C&&(n.fov=s,n.updateProjectionMatrix())),{camera:n,position:te,lookAt:y,fov:e.fov}}var Nm=function(e,t,n,r){var i=arguments.length,a=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r,o;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)a=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(o=e[s])&&(a=(i<3?o(a):i>3?o(t,n,a):o(t,n))||a);return i>3&&a&&Object.defineProperty(t,n,a),a},Pm=class extends K{constraintActive=!0;locked=!1;sources=[];setConstraintPosition(e){let t=this.sources[0];t&&(t.worldPosition=e)}};Nm([F()],Pm.prototype,`constraintActive`,void 0),Nm([F()],Pm.prototype,`locked`,void 0),Nm([F(S)],Pm.prototype,`sources`,void 0);var Fm=class{bb=null;bb_pos=0;__init(e,t){return this.bb_pos=e,this.bb=t,this}x(){return this.bb.readFloat32(this.bb_pos)}y(){return this.bb.readFloat32(this.bb_pos+4)}z(){return this.bb.readFloat32(this.bb_pos+8)}static sizeOf(){return 12}static createVec3(e,t,n,r){return e.prep(4,12),e.writeFloat32(r),e.writeFloat32(n),e.writeFloat32(t),e.offset()}},Im=class{bb=null;bb_pos=0;__init(e,t){return this.bb_pos=e,this.bb=t,this}position(e){return(e||new Fm).__init(this.bb_pos,this.bb)}rotation(e){return(e||new Fm).__init(this.bb_pos+12,this.bb)}scale(e){return(e||new Fm).__init(this.bb_pos+24,this.bb)}static sizeOf(){return 36}static createTransform(e,t,n,r,i,a,o,s,c,l){return e.prep(4,36),e.prep(4,12),e.writeFloat32(l),e.writeFloat32(c),e.writeFloat32(s),e.prep(4,12),e.writeFloat32(o),e.writeFloat32(a),e.writeFloat32(i),e.prep(4,12),e.writeFloat32(r),e.writeFloat32(n),e.writeFloat32(t),e.offset()}},Lm=class e{bb=null;bb_pos=0;__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsSyncedTransformModel(t,n){return(n||new e).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsSyncedTransformModel(t,n){return t.setPosition(t.position()+4),(n||new e).__init(t.readInt32(t.position())+t.position(),t)}guid(e){let t=this.bb.__offset(this.bb_pos,4);return t?this.bb.__string(this.bb_pos+t,e):null}fast(){let e=this.bb.__offset(this.bb_pos,6);return e?!!this.bb.readInt8(this.bb_pos+e):!1}transform(e){let t=this.bb.__offset(this.bb_pos,8);return t?(e||new Im).__init(this.bb_pos+t,this.bb):null}dontSave(){let e=this.bb.__offset(this.bb_pos,10);return e?!!this.bb.readInt8(this.bb_pos+e):!1}static startSyncedTransformModel(e){e.startObject(4)}static addGuid(e,t){e.addFieldOffset(0,t,0)}static addFast(e,t){e.addFieldInt8(1,+t,0)}static addTransform(e,t){e.addFieldStruct(2,t,0)}static addDontSave(e,t){e.addFieldInt8(3,+t,0)}static endSyncedTransformModel(e){return e.endObject()}static finishSyncedTransformModelBuffer(e,t){e.finish(t)}static finishSizePrefixedSyncedTransformModelBuffer(e,t){e.finish(t,void 0,!0)}},Rm;(function(e){e[e.Average=0]=`Average`,e[e.Multiply=1]=`Multiply`,e[e.Minimum=2]=`Minimum`,e[e.Maximum=3]=`Maximum`})(Rm||={});var zm;(function(e){e[e.Discrete=0]=`Discrete`,e[e.Continuous=1]=`Continuous`})(zm||={});var J;(function(e){e[e.None=0]=`None`,e[e.FreezePositionX=2]=`FreezePositionX`,e[e.FreezePositionY=4]=`FreezePositionY`,e[e.FreezePositionZ=8]=`FreezePositionZ`,e[e.FreezePosition=14]=`FreezePosition`,e[e.FreezeRotationX=16]=`FreezeRotationX`,e[e.FreezeRotationY=32]=`FreezeRotationY`,e[e.FreezeRotationZ=64]=`FreezeRotationZ`,e[e.FreezeRotation=112]=`FreezeRotation`,e[e.FreezeAll=126]=`FreezeAll`})(J||={});var Bm;(function(e){e[e.None=0]=`None`,e[e.X=2]=`X`,e[e.Y=4]=`Y`,e[e.Z=8]=`Z`,e[e.All=-1]=`All`})(Bm||={});var Vm=function(e,t){return function(n,r,i){Hm(n,r,i,e,t)}};function Hm(e,t,n,r,i){if(!i&&!r&&!e.onValidate)return;if(n!==void 0){console.error(`Invalid usage of validate decorator. Only fields can be validated.`,e,t,n),Ti(`Invalid usage of validate decorator. Only fields can be validated. Property: `+t,{type:Tn.Error});return}let a=``;if(a=typeof t==`string`?t:t.name,e.__internalAwake){let t=Symbol(a),n=e.__internalAwake;e.__internalAwake=function(){if(!this.onValidate){M()&&console.warn(`Usage of @validate decorate detected but there is no onValidate method in your class: "`+e.constructor?.name+`"`);return}if(this[t]===void 0){this[t]=this[a];let e=this[a];if(e instanceof w||e instanceof o||e instanceof Te||e instanceof E){let e=this[a];nn(e,()=>{this.onValidate(a)})}Object.defineProperty(this,a,{set:function(e){if(this[Ts]===!0)this[t]=e;else{r?.call(this,e);let n=this[t];this[t]=e,this.onValidate?.call(this,a,n)}},get:function(){return i?.call(this),this[t]}})}n.call(this)}}}var Um=function(e){return function(t,n,r){let i=``;i=typeof n==`string`?n:n.name;let a=e.prototype,o=Object.getOwnPropertyDescriptor(a,i);if(!o?.value){console.warn(`Can not apply prefix: type does not have method named`,n,e);return}let s=o.value,c=t[i];Object.defineProperty(a,i,{value:function(...e){let t=c?.call(this,...e);if(t instanceof Promise){t.then(t=>{if(t!==!1)return s.call(this,...e)});return}if(t!==!1)return s.call(this,...e)}})}},Wm=function(e,t,n,r){var i=arguments.length,a=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r,o;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)a=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(o=e[s])&&(a=(i<3?o(a):i>3?o(t,n,a):o(t,n))||a);return i>3&&a&&Object.defineProperty(t,n,a),a},Gm=class{get isDirty(){return this.positionChanged||this.rotationChanged}positionChanged=!1;rotationChanged=!1;position;quaternion;_positionKeys=[`x`,`y`,`z`];_quaternionKeys=[`_x`,`_y`,`_z`,`_w`];reset(e=!1){if(this.positionChanged=!1,this.rotationChanged=!1,this.mute=!1,e){if(this.position)for(let e of this._positionKeys)delete this.position[e];if(this.quaternion)for(let e of this._quaternionKeys)delete this.quaternion[e]}}syncValues(){for(let e of this._positionKeys)this.position[e]=this.obj.position[e];for(let e of this._quaternionKeys)this.quaternion[e]=this.obj.quaternion[e]}mute=!1;applyValues(){if(this.positionChanged&&this.position)for(let e of this._positionKeys){let t=this.position[e];t!==void 0&&(this.obj.position[e]=t)}if(this.rotationChanged&&this.quaternion)for(let e of this._quaternionKeys){let t=this.quaternion[e];t!==void 0&&(this.obj.quaternion[e]=t)}}context;obj;_positionWatch;_rotationWatch;constructor(e,t){this.context=t,this.obj=e}start(e,t){this.reset(),e&&(this._positionWatch||=new en(this.obj.position,[`x`,`y`,`z`]),this._positionWatch.apply(),this.position={},this._positionWatch.subscribeWrite((e,t)=>{if(this.context.physics.engine?.isUpdating||this.mute)return;let n=this.position[t];Math.abs(n-e)<1e-5||(this.position[t]=e,this.positionChanged=!0)})),t&&(this._rotationWatch||=new en(this.obj.quaternion,[`_x`,`_y`,`_z`,`_w`]),this._rotationWatch.apply(),this.quaternion={},this._rotationWatch.subscribeWrite((e,t)=>{if(this.context.physics.engine?.isUpdating||this.mute)return;let n=this.quaternion[t];Math.abs(n-e)<1e-5||(this.quaternion[t]=e,this.rotationChanged=!0)}));let n=this.obj.matrixWorld.multiplyMatrices.bind(this.obj.matrixWorld),r=new ce;this.obj.matrixWorld.multiplyMatrices=(e,t)=>(this.context.physics.engine?.isUpdating||this.mute||r.equals(e)||(this.positionChanged=!0,this.rotationChanged=!0,r.copy(e)),n(e,t))}stop(){this._positionWatch?.revoke(),this._rotationWatch?.revoke()}},Km=class e extends K{get isRigidbody(){return!0}autoMass=!0;set mass(e){e!==this._mass&&(this._mass=e,this._propertiesChanged=!0,this.__didAwake&&(this.autoMass=!1))}get mass(){return this.autoMass?this.context.physics.engine?.getBody(this)?.mass()??-1:this._mass}_mass=0;useGravity=!0;centerOfMass=new o(0,0,0);constraints=J.None;isKinematic=!1;drag=0;angularDrag=1;detectCollisions=!0;sleepThreshold=.01;collisionDetectionMode=zm.Discrete;get lockPositionX(){return(this.constraints&J.FreezePositionX)!==0}get lockPositionY(){return(this.constraints&J.FreezePositionY)!==0}get lockPositionZ(){return(this.constraints&J.FreezePositionZ)!==0}get lockRotationX(){return(this.constraints&J.FreezeRotationX)!==0}get lockRotationY(){return(this.constraints&J.FreezeRotationY)!==0}get lockRotationZ(){return(this.constraints&J.FreezeRotationZ)!==0}set lockPositionX(e){e?this.constraints|=J.FreezePositionX:this.constraints&=~J.FreezePositionX}set lockPositionY(e){e?this.constraints|=J.FreezePositionY:this.constraints&=~J.FreezePositionY}set lockPositionZ(e){e?this.constraints|=J.FreezePositionZ:this.constraints&=~J.FreezePositionZ}set lockRotationX(e){e?this.constraints|=J.FreezeRotationX:this.constraints&=~J.FreezeRotationX}set lockRotationY(e){e?this.constraints|=J.FreezeRotationY:this.constraints&=~J.FreezeRotationY}set lockRotationZ(e){e?this.constraints|=J.FreezeRotationZ:this.constraints&=~J.FreezeRotationZ}set gravityScale(e){this._gravityScale=e}get gravityScale(){return this._gravityScale}_gravityScale=1;dominanceGroup=0;static tempPosition=new o;_propertiesChanged=!1;_currentVelocity=new o;_smoothedVelocity=new o;_smoothedVelocityGetter=new o;_lastPosition=new o;_watch;awake(){this._watch=void 0,this._propertiesChanged=!1}onEnable(){this._watch||=new Gm(this.gameObject,this.context),this._watch.start(!0,!0),this.startCoroutine(this.beforePhysics(),z.LateUpdate),M()&&(globalThis.NEEDLE_USE_RAPIER?Pc.RAPIER_PHYSICS.ready().then(async()=>{await qt(3),this.context.physics.engine?.getBody(this)||console.warn(`Rigidbody could not be created. Ensure \"${this.name}\" has a Collider component.`)}):console.warn(`Rigidbody could not be created: Rapier physics are explicitly disabled.`))}onDisable(){this._watch?.stop(),this.context.physics.engine?.removeBody(this)}onDestroy(){this.context.physics.engine?.removeBody(this)}onValidate(){this._propertiesChanged=!0}*beforePhysics(){for(;;)this._propertiesChanged&&(this._propertiesChanged=!1,this.context.physics.engine?.updateProperties(this)),this._watch?.isDirty?(this._watch.mute=!0,this._watch.applyValues(),this.context.physics.engine?.updateBody(this,this._watch.positionChanged,this._watch.rotationChanged),this._watch.reset()):this._watch?.syncValues(),this.captureVelocity(),yield}teleport(e,t=!0){this._watch?.reset(!0),t?this.gameObject.position.set(e.x,e.y,e.z):this.setWorldPosition(e.x,e.y,e.z),this.resetForcesAndTorques(),this.resetVelocities()}resetForces(e=!0){this.context.physics.engine?.resetForces(this,e)}resetTorques(e=!0){this.context.physics.engine?.resetTorques(this,e)}resetVelocities(){this.setVelocity(0,0,0),this.setAngularVelocity(0,0,0)}resetForcesAndTorques(){this.resetForces(),this.resetTorques()}wakeUp(){this.context.physics.engine?.wakeup(this)}get isSleeping(){return this.context.physics.engine?.isSleeping(this)}updateProperties(){return this._propertiesChanged=!1,this.context.physics.engine?.updateProperties(this)}applyForce(e,t,n=!0){this._propertiesChanged&&this.updateProperties(),this.context.physics.engine?.addForce(this,e,n)}applyImpulse(e,t=!0){this._propertiesChanged&&this.updateProperties(),this.context.physics.engine?.applyImpulse(this,e,t)}setForce(e,t,n,r=!0){this.context.physics.engine?.resetForces(this,r),typeof e==`number`?(t??=0,n??=0,this.context.physics.engine?.addForce(this,{x:e,y:t,z:n},r)):this.context.physics.engine?.addForce(this,e,r)}getVelocity(){let e=this.context.physics.engine?.getLinearVelocity(this);return e?(this._currentVelocity.x=e.x,this._currentVelocity.y=e.y,this._currentVelocity.z=e.z,this._currentVelocity):this._currentVelocity.set(0,0,0)}setVelocity(e,t,n,r=!0){if(e instanceof o){let t=e;this.context.physics.engine?.setLinearVelocity(this,t,r);return}t===void 0||n===void 0||this.context.physics.engine?.setLinearVelocity(this,{x:e,y:t,z:n},r)}getAngularVelocity(){let e=this.context.physics.engine?.getAngularVelocity(this);return e?(this._currentVelocity.x=e.x,this._currentVelocity.y=e.y,this._currentVelocity.z=e.z,this._currentVelocity):this._currentVelocity.set(0,0,0)}setAngularVelocity(e,t,n,r=!0){if(typeof e==`object`){let t=e;this.context.physics.engine?.setAngularVelocity(this,t,r);return}if(t===void 0||n===void 0||typeof t==`boolean`){console.warn(`setAngularVelocity expects either a Vec3 or 3 numbers`);return}this.context.physics.engine?.setAngularVelocity(this,{x:e,y:t,z:n},r)}setTorque(e,t,n){typeof e==`number`?this.setAngularVelocity(e,t,n):this.setAngularVelocity(e)}get smoothedVelocity(){return this._smoothedVelocityGetter.copy(this._smoothedVelocity),this._smoothedVelocityGetter.multiplyScalar(1/this.context.time.deltaTime)}setBodyFromGameObject(e=null){}captureVelocity(){let t=this.gameObject.matrixWorld;e.tempPosition.setFromMatrixPosition(t);let n=e.tempPosition.sub(this._lastPosition);this._lastPosition.copy(e.tempPosition),this._smoothedVelocity.lerp(n,this.context.time.deltaTime/.1)}};Wm([Vm()],Km.prototype,`autoMass`,void 0),Wm([F()],Km.prototype,`mass`,null),Wm([Vm(),F()],Km.prototype,`useGravity`,void 0),Wm([F(o)],Km.prototype,`centerOfMass`,void 0),Wm([Vm(),F()],Km.prototype,`constraints`,void 0),Wm([Vm(),F()],Km.prototype,`isKinematic`,void 0),Wm([Vm(),F()],Km.prototype,`drag`,void 0),Wm([Vm(),F()],Km.prototype,`angularDrag`,void 0),Wm([Vm(),F()],Km.prototype,`detectCollisions`,void 0),Wm([Vm(),F()],Km.prototype,`sleepThreshold`,void 0),Wm([Vm(),F()],Km.prototype,`collisionDetectionMode`,void 0),Wm([Vm()],Km.prototype,`_gravityScale`,void 0),Wm([Vm()],Km.prototype,`dominanceGroup`,void 0),new o,new E,new o;var qm=A(`debugsync`),Jm=`STRS`;Ac(Jm,Lm.getRootAsSyncedTransformModel);var Ym=new Oc;function Xm(e,t,n=!0){Ym.clear();let r=Ym.createString(e);Lm.startSyncedTransformModel(Ym),Lm.addGuid(Ym,r),Lm.addFast(Ym,n);let i=t.worldPosition,a=t.worldEuler,o=t.gameObject.scale;Lm.addTransform(Ym,Im.createTransform(Ym,i.x,i.y,i.z,a.x,a.y,a.z,o.x,o.y,o.z));let s=Lm.endSyncedTransformModel(Ym);return Ym.finish(s,Jm),Ym.asUint8Array()}var Zm=0,Qm=0;Va(e=>{let t=e.connection.currentServerUrl?.includes(`glitch`)?10:40;Qm=Math.floor(Zm/t),Zm=0,qm&&Qm>0&&console.log(`Sync Transform Fast Interval`,Qm)});var $m=class extends K{overridePhysics=!0;interpolatePosition=!0;interpolateRotation=!0;fastMode=!1;syncDestroy=!1;_model=null;_needsUpdate=!0;rb=null;_wasKinematic=!1;_receivedDataBefore=!1;_targetPosition;_targetRotation;_receivedFastUpdate=!1;_shouldRequestOwnership=!1;requestOwnership(){qm&&console.log(`Request ownership`),this._model?this._model.requestOwnership():(this._shouldRequestOwnership=!0,this._needsUpdate=!0)}freeOwnership(){this._model?.freeOwnership()}hasOwnership(){return this._model?.hasOwnership??void 0}isOwned(){return this._model?.isOwned}joinedRoomCallback=null;receivedDataCallback=null;awake(){qm&&console.log(`new instance`,this.guid,this),this._receivedDataBefore=!1,this._targetPosition=new o,this._targetRotation=new E,this.lastPosition=new o,this.lastRotation=new E,this.lastScale=new o,this.rb=G.getComponentInChildren(this.gameObject,Km),this.rb&&(this._wasKinematic=this.rb.isKinematic),this.receivedUpdate=!0,this._model=new tl(this.context.connection,this.guid),this.context.connection.isConnected&&this.tryGetLastState(),this.joinedRoomCallback=this.tryGetLastState.bind(this),this.context.connection.beginListen(Xc.JoinedRoom,this.joinedRoomCallback),this.receivedDataCallback=this.onReceivedData.bind(this),this.context.connection.beginListenBinary(Jm,this.receivedDataCallback)}onDestroy(){this.syncDestroy&&Fo(this.guid,this.context.connection),this._model=null,this.context.connection.stopListen(Xc.JoinedRoom,this.joinedRoomCallback),this.context.connection.stopListenBinary(Jm,this.receivedDataCallback)}tryGetLastState(){let e=this.context.connection.tryGetState(this.guid);e&&this.onReceivedData(e)}tempEuler=new He;onReceivedData(e){if(!this.destroyed&&typeof e.guid==`function`&&e.guid()===this.guid){qm&&console.log(`new data`,this.context.connection.connectionId,this.context.time.frameCount,this.guid,e),this.receivedUpdate=!0,this._receivedFastUpdate=e.fast();let t=e.transform();if(t){mf.markDirty(this.gameObject,!0);let e=t.position();e&&(this.interpolatePosition&&this._targetPosition?.set(e.x(),e.y(),e.z()),(!this.interpolatePosition||!this._receivedDataBefore)&&this.setWorldPosition(e.x(),e.y(),e.z()));let n=t.rotation();n&&(this.tempEuler.set(n.x(),n.y(),n.z()),this.interpolateRotation&&this._targetRotation.setFromEuler(this.tempEuler),(!this.interpolateRotation||!this._receivedDataBefore)&&Zr(this.gameObject,this.tempEuler));let r=t.scale();r&&this.gameObject.scale.set(r.x(),r.y(),r.z())}this._receivedDataBefore=!0}}onEnable(){this.lastPosition.copy(this.worldPosition),this.lastRotation.copy(this.worldQuaternion),this.lastScale.copy(this.gameObject.scale),this._needsUpdate=!0,this._model&&this._model.updateIsOwned()}onDisable(){this._model&&this._model.freeOwnership()}receivedUpdate=!1;lastPosition;lastRotation;lastScale;onBeforeRender(){if(!this.activeAndEnabled||!this.context.connection.isConnected)return;if(!this.context.connection.isInRoom||!this._model){qm&&console.log(`no model or room`,this.name,this.guid,this.context.connection.isInRoom);return}this._shouldRequestOwnership&&(this._shouldRequestOwnership=!1,this._model.requestOwnership());let e=this.worldPosition,t=this.worldQuaternion,n=this.gameObject.scale;if(this._model.isOwned&&!this.receivedUpdate){let r=this._model.hasOwnership||this.fastMode?1e-4:.001;(e.distanceTo(this.lastPosition)>r||t.angleTo(this.lastRotation)>r||n.distanceTo(this.lastScale)>r)&&(this._model.hasOwnership?this._needsUpdate=!0:(qm&&console.log(this.guid,`reset because not owned but`,this.gameObject.name,this.lastPosition),this.worldPosition=this.lastPosition,e.copy(this.lastPosition),this.worldQuaternion=this.lastRotation,t.copy(this.lastRotation),this.gameObject.scale.copy(this.lastScale),mf.markDirty(this.gameObject,!0),this._needsUpdate=!1))}if(this._model&&!this._model.hasOwnership&&this._model.isOwned&&this._receivedDataBefore){let e=this._receivedFastUpdate||this.fastMode?.5:.3,t=!1;if(this.interpolatePosition&&this._targetPosition){let n=this.worldPosition;n.lerp(this._targetPosition,e),this.worldPosition=n,t=!0}if(this.interpolateRotation&&this._targetRotation){let n=this.worldQuaternion;n.slerp(this._targetRotation,e),this.worldQuaternion=n,t=!0}t&&mf.markDirty(this.gameObject,!0)}if(this.receivedUpdate=!1,this.lastPosition.copy(e),this.lastRotation.copy(t),this.lastScale.copy(n),!this._model||!this._model||this._model.hasOwnership===void 0||!this._model.hasOwnership)return;this.rb&&this.overridePhysics&&this._wasKinematic!==void 0&&(qm&&console.log(`reset kinematic`,this.rb.name,this._wasKinematic),this.rb.isKinematic=this._wasKinematic);let r=this.rb||this.fastMode;if(this._needsUpdate&&(this.context.time.frameCount%10==0||r)){if(Zm++,r&&Qm>0&&this.context.time.frameCount%Qm!==0)return;qm&&console.debug(`[SyncedTransform] Send update`,this.context.connection.connectionId,this.guid,this.gameObject.name,this.gameObject.guid),this._needsUpdate=!1;let e=Xm(this.guid,this,!!r);this.context.connection.sendBinary(e)}}},eh=class e{event;get deviceIndex(){return this.event.deviceIndex}get pointerId(){return this.event.pointerId}button;buttonName;get pressure(){return this.event.pressure}get used(){return this._used}_used=!1;use(){this._used||(this._used=!0,this.event.use())}_propagationStopped=!1;get propagationStopped(){return this._propagationStopped}stopPropagation(){this._propagationStopped=!0,this.event.stopImmediatePropagation()}stopImmediatePropagation(){this._propagationStopped=!0,this.event.stopImmediatePropagation()}z__pointer_ctured=!1;setPointerCapture(){this.z__pointer_ctured=!0}z__pointer_cture_rleased=!1;releasePointerCapture(){this.z__pointer_cture_rleased=!0}inputSource;get mode(){return this.event.mode}object;point;normal;face;distance;instanceId;intersection;isDown;isUp;isPressed;isClick;isDoubleClick;input;constructor(e,t){this.event=t,this.input=e,this.button=t.button}clone(){let t=new e(this.input,this.event);return Object.assign(t,this),t}Use(){this.use()}StopPropagation(){this.event.stopImmediatePropagation()}};function th(e,t){return G.foreachComponent(e,e=>{if(!e.enabled)return;let n=e;if(t)switch(t){case`pointerdown`:if(n.onPointerDown)return!0;break;case`pointerup`:if(n.onPointerUp||n.onPointerClick)return!0;break;case`pointermove`:if(n.onPointerEnter||n.onPointerExit||n.onPointerMove)return!0;break}else if(n.onPointerDown||n.onPointerUp||n.onPointerEnter||n.onPointerExit||n.onPointerClick)return!0},!1)===!0}var nh=function(e,t,n,r){var i=arguments.length,a=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r,o;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)a=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(o=e[s])&&(a=(i<3?o(a):i>3?o(t,n,a):o(t,n))||a);return i>3&&a&&Object.defineProperty(t,n,a),a},rh=class extends K{awake(){gh.createIfNoneExists(this.context)}onEnable(){gh.get(this.context)?.register(this)}onDisable(){gh.get(this.context)?.unregister(this)}},ih=class extends rh{targets=null;raycastHits=[];ignoreSkinnedMeshes=!1;start(){this.targets=[this.gameObject]}performRaycast(e=null){if(!this.targets)return null;e??=new kd,e.targets=this.targets,e.results=this.raycastHits,e.useAcceleratedRaycast=!0;let t=e.testObject;this.ignoreSkinnedMeshes&&(e.testObject=e=>e instanceof ze?`continue in children`:t?t(e):!0);let n=this.context.physics.raycast(e);return e.testObject=t,n}};nh([F()],ih.prototype,`ignoreSkinnedMeshes`,void 0);var ah=class extends ih{constructor(){super(),this.ignoreSkinnedMeshes=!0}},oh=class e extends rh{static allow=!0;performRaycast(t){if(!pd.active||!e.allow||!t?.ray)return null;let n=t.ray.origin;return this.context.physics.sphereOverlap(n,.015,!1,!0)}},sh=class{static getObject(e){let t=e[Yi];return t&&(e=t.isComponent===!0?t.gameObject:t),e}static isInteractable(e,t){if(t&&(t.canvasGroup=void 0,t.graphic=void 0),e==null||!e.visible||(e=this.getObject(e),!e.visible))return!1;let n=this.tryFindCanvasGroup(e);if(n?.isCanvasGroup===!0&&(t&&(t.canvasGroup=n),n.blocksRaycasts===!1||n.interactable===!1))return!1;let r=Vf(e,e=>{if(e.isGraphic===!0)return e},!1);return t&&r?.isGraphic===!0&&(t.graphic=r),!(r?.raycastTarget===!1||r?.layer===2)}static tryFindCanvasGroup(e){if(!e)return null;let t=Vf(e,e=>{if(e.activeAndEnabled){let t=e;if(t.blocksRaycasts!==void 0&&t.interactable!==void 0)return t}},!1);return t===void 0?this.tryFindCanvasGroup(e.parent):t}};function ch(e){return e[Yi]||(e.parent?ch(e.parent):null)}function lh(e){return e.isUI===!0||typeof e[Yi]==`object`}function uh(e,t){if(!e)return;let n=e.material;if(n?.isMaterial===!0){let r=e.parent;r&&r.isText,n.side=t.doubleSided??!0?2:0,n.shadowSide=t.doubleSided?2:0,e.castShadow=t.castShadows?t.castShadows:!1,e.receiveShadow=t.receiveShadows?t.receiveShadows:!1}for(let n of e.children)uh(n,t)}function dh(e,t,n){e[t]===void 0&&console.warn(`Field`,t,`is undefined on`,e);let r=Proxy.revocable(e[t],{set(e,t,r,i){let a=e[t],o=Reflect.set(e,t,r,i);return n(r,a),o}}),i=r.revoke,a=e[t];return r.revoke=()=>{e[t]=a,i()},e[t]=r.proxy,r}var fh=Symbol(`Scheduled action`);function ph(e,t,n=z.OnBeforeRender){let r=e[fh];r||=e[fh]={};let i=t.name;r[n]||(r[n]={});let a=r[n];if(a[i])return;function*o(){t?.call(e),a[i]=null}a[i]=e.startCoroutine(o(),n)}var mh=A(`debugeventsystem`),hh;(function(e){e.BeforeHandleInput=`BeforeHandleInput`,e.AfterHandleInput=`AfterHandleInput`})(hh||={}),La(e=>{gh.createIfNoneExists(e)});var gh=class e extends K{static ensureUpdateMeshUI(e,t,n=!1){_h.update(e,t,n)}static markUIDirty(e){_h.markDirty()}static createIfNoneExists(t){t.scene.getComponent(e)||t.scene.addComponent(e)}static get(t){return this.createIfNoneExists(t),t.scene.getComponent(e)}static get instance(){return this.get(B.Current)}raycaster=[];register(e){e&&this.raycaster&&!this.raycaster.includes(e)&&this.raycaster?.push(e)}unregister(e){let t=this.raycaster?.indexOf(e);t!==void 0&&t!==-1&&this.raycaster?.splice(t,1)}get hasActiveUI(){return this.currentActiveMeshUIComponents.length>0}get isHoveringObjects(){return this.hoveredByID.size>0}awake(){this.gameObject!==this.context.scene&&(console.debug(`[Needle Engine] EventSystem is only allowed on the scene root. Disabling EventSystem on '${this.gameObject.name}'`),this.enabled=!1)}start(){this.context.scene.getComponent(rh)||this.context.scene.addComponent(ih)}onEnable(){this.context.input.addEventListener(L.PointerDown,this.onPointerEvent),this.context.input.addEventListener(L.PointerUp,this.onPointerEvent),this.context.input.addEventListener(L.PointerMove,this.onPointerEvent)}onDisable(){this.context.input.removeEventListener(L.PointerDown,this.onPointerEvent),this.context.input.removeEventListener(L.PointerUp,this.onPointerEvent),this.context.input.removeEventListener(L.PointerMove,this.onPointerEvent)}pressedByID=new Map;hoveredByID=new Map;onBeforeRender(){this.resetMeshUIStates()}onPointerEvent=e=>{if(e===void 0||e.propagationStopped||e.defaultPrevented||e.used)return;let t=new eh(this.context.input,e);this._currentPointerEventName=e.type,t.inputSource=this.context.input,t.isClick=e.isClick,t.isDoubleClick=e.isDoubleClick,t.isDown=e.type==L.PointerDown,t.isUp=e.type==L.PointerUp,t.isPressed=this.context.input.getPointerPressed(e.pointerId);let n=new kd;e.hasRay?n.ray=e.ray:n.screenPoint=this.context.input.getPointerPositionRC(e.pointerId),n.allowSlowRaycastFallback=e.isClick||e.isDoubleClick;let r=this.performRaycast(n);if(mh&&(t.isDown?console.log(`DOWN`,{id:t.pointerId,hits:r.length}):t.isUp&&console.log(`UP`,{id:t.pointerId,hits:r.length}),t.isClick&&console.log(`CLICK`,{id:t.pointerId,hits:r.length})),r){for(let t of r)t.event=e,e.intersections.push(t);e.origin.onPointerHits&&e.origin.onPointerHits({sender:this,event:e,hits:r})}mh&&t.isClick&&Ti(`EventSystem: `+t.pointerId+` - `+this.context.time.frame+` - Up:`+t.isUp+`, Down:`+t.isDown);let i={sender:this,args:t,hasActiveUI:this.currentActiveMeshUIComponents.length>0};this.dispatchEvent(new CustomEvent(hh.BeforeHandleInput,{detail:i})),this.handleIntersections(r,t),this.dispatchEvent(new CustomEvent(hh.AfterHandleInput,{detail:i}))};_sortedHits=[];_testObjectsCache=new Map;_currentlyActiveRaycaster=null;_currentPointerEventName=null;shouldRaycastObject=e=>{let t=e&&`getComponent`in e?e.getComponent(rh):null;if(t&&t!=this._currentlyActiveRaycaster)return!1;let n=null;if(lh(e)&&(n=e[Yi]?.gameObject),this._testObjectsCache.has(e)||n&&this._testObjectsCache.has(n))return this._testObjectsCache.get(e)===!1?`continue in children`:!0;{let t=th(e,this._currentPointerEventName);if(!t&&n&&(t=th(n,this._currentPointerEventName)),t){this._testObjectsCache.set(e,!0);for(let t of e.children)this.shouldRaycastObject_AddToYesCache(t);return!0}return this._testObjectsCache.set(e,!1),`continue in children`}};shouldRaycastObject_AddToYesCache(e){this._testObjectsCache.set(e,!0);for(let t of e.children)this.shouldRaycastObject_AddToYesCache(t)}performRaycast(e){if(!this.raycaster)return null;this._testObjectsCache.clear(),this._sortedHits.length=0,e.testObject=this.shouldRaycastObject;for(let t of this.raycaster){if(!t.activeAndEnabled)continue;this._currentlyActiveRaycaster=t;let n=t.performRaycast(e);this._currentlyActiveRaycaster=null,n&&n.length>0&&this._sortedHits.push(...n)}return this._sortedHits.sort((e,t)=>e.distance-t.distance),this._sortedHits}assignHitInformation(e,t){t?(e.intersection=t,e.point=t.point,e.normal=t.normal,e.face=t.face,e.distance=t.distance,e.instanceId=t.instanceId):(e.intersection=void 0,e.point=void 0,e.normal=void 0,e.face=void 0,e.distance=void 0,e.instanceId=void 0)}handleIntersections(e,t){if(e?.length){e=this.sortCandidates(e);for(let n of e){if(t.event.immediatePropagationStopped)return!1;if(this.assignHitInformation(t,n),this.handleEventOnObject(n.object,t))return!0}}this.assignHitInformation(t,e?.[0]),this.invokePointerCapture(t);let n=this.hoveredByID.get(t.pointerId);return n&&this.propagatePointerExit(n.obj,n.data,null),this.hoveredByID.delete(t.pointerId),t.isUp&&(this.pressedByID.get(t.pointerId)?.handlers.forEach(e=>this.invokeOnPointerUp(t,e)),this.pressedByID.delete(t.pointerId)),!1}_sortingBuffer=[];_noDepthTestingResults=[];sortCandidates(e){this._sortingBuffer.length=0,this._noDepthTestingResults.length=0;for(let t=0;t{t(e)},!1),e=e.parent}handleMainInteraction(e,t,n){let r=this.pressedByID.get(t.pointerId),i=n!==e,a=!0;switch(t.event.pointerType){case`mouse`:case`touch`:let e=this.context.input.getPointerPositionLastFrame(t.pointerId),n=this.context.input.getPointerPosition(t.pointerId);a=e&&!N.approximately(e,n);break;case`controller`:case`hand`:break}this.propagate(e,e=>{let n=e;n.interactable!==!1&&(!n.activeAndEnabled||!n.enabled||(n.onPointerEnter&&i&&this.handlePointerEnter(n,t),t.isDown&&n.onPointerDown&&(n.onPointerDown(t),r?.handlers.add(n),this.handlePointerCapture(t,n)),n.onPointerMove&&(a&&n.onPointerMove(t),this.handlePointerCapture(t,n)),t.isUp&&(n.onPointerUp&&(this.invokeOnPointerUp(t,n),r?.handlers.delete(n)),n.onPointerExit&&t.event?.pointerType===tc.Touch&&(this.handlePointerExit(n,t),this.hoveredByID.delete(t.pointerId))),t.isClick&&n.onPointerClick&&n.onPointerClick(t)))}),t.isUp&&(r?.handlers.forEach(e=>{this.invokeOnPointerUp(t,e)}),this.pressedByID.delete(t.pointerId))}propagatePointerExit(e,t,n){this.propagate(e,e=>{if(!e.gameObject||e.destroyed)return;let r=e;if(r.onPointerExit||r.onPointerEnter){if(n&&this.isChild(n,e.gameObject))return;this.handlePointerExit(r,t)}})}invokeOnPointerUp(e,t){t.onPointerUp?.call(t,e),this.releasePointerCapture(e,t)}handlePointerEnter(e,t){e.onPointerEnter&&this.updatePointerState(e,t.pointerId,this.pointerEnterSymbol,!0)&&e.onPointerEnter(t),this.updatePointerState(e,t.pointerId,this.pointerExitSymbol,!1)}handlePointerExit(e,t){e.onPointerExit&&this.updatePointerState(e,t.pointerId,this.pointerExitSymbol,!0)&&e.onPointerExit(t),this.updatePointerState(e,t.pointerId,this.pointerEnterSymbol,!1)}updatePointerState(e,t,n,r){let i=e[n];if(r)return i&&i.includes(t)?!1:(i||=[],i.push(t),e[n]=i,!0);{if(!i||!i.includes(t))return!1;let e=i.indexOf(t);return e!==-1&&i.splice(e,1),!0}}_capturedPointer={};handlePointerCapture(e,t){if(e.z__pointer_ctured){e.z__pointer_ctured=!1;let n=e.pointerId;if(t.onPointerMove){let e=this._capturedPointer[n]||[];e.push(t),this._capturedPointer[n]=e}else M()&&!t.z__warned_no_pointermove&&(t.z__warned_no_pointermove=!0,console.warn(`PointerCapture was requested but the component doesn't implement onPointerMove. It will not receive any pointer events`))}else e.z__pointer_cture_rleased&&(e.z__pointer_cture_rleased=!1,this.releasePointerCapture(e,t))}releasePointerCapture(e,t){let n=e.pointerId;if(this._capturedPointer[n]){let e=this._capturedPointer[n].indexOf(t);e!==-1&&(this._capturedPointer[n].splice(e,1),mh&&console.log(`released pointer capture`,n,t,this._capturedPointer))}}invokePointerCapture(e){if(e.event.type===L.PointerMove){let t=e.pointerId,n=this._capturedPointer[t];if(n){mh&&console.log(`Captured`,t,n);for(let t=0;t0&&_h.resetLastSelected(),!(!this.currentActiveMeshUIComponents||this.currentActiveMeshUIComponents.length<=0)){for(let e=0;e=0;s--)(o=e[s])&&(a=(i<3?o(a):i>3?o(t,n,a):o(t,n))||a);return i>3&&a&&Object.defineProperty(t,n,a),a},vh=A(`debugorbit`),yh=A(`freecam`),bh=A(`debugcamerafit`),xh=A(`smoothcam`),Sh={LEFT:``,UP:``,RIGHT:``,BOTTOM:``},Ch=void 0,wh;(function(e){e.CameraTargetReached=`target-reached`})(wh||={});var Th=class extends CustomEvent{constructor(e,t){super(wh.CameraTargetReached,{detail:{controls:e,type:t}})}},X=class extends K{get isCameraController(){return!0}get controls(){return this._controls}get controllerObject(){return this._cameraObject}onStartInteraction(e){this.controls?.addEventListener(`start`,e)}autoTarget=!0;autoFit=!1;enableRotate=!0;autoRotate=!1;autoRotateSpeed=1;minAzimuthAngle=1/0;maxAzimuthAngle=1/0;minPolarAngle=0;maxPolarAngle=Math.PI;enableKeys=!1;enableDamping=!0;dampingFactor=.1;enableZoom=!0;minZoom=0;maxZoom=1/0;zoomSpeed=1;zoomToCursor=!1;enablePan=!0;lookAtTarget=null;lockLookAtTarget=!0;lookAtConstraint01=1;lookAtConstraint;allowInterrupt=!0;middleClickToFocus=!0;doubleClickToFocus=!0;clickBackgroundToFitScene=2;get targetElement(){return this._controls?.domElement??this._targetElement}set targetElement(e){this._targetElement=e,this._controls&&this._controls.domElement!==e&&(this._controls.disconnect(),this._controls.domElement=e,this._controls.connect())}_targetElement=null;debugLog=!1;get targetLerpSpeed(){return 5}set targetLerpSpeed(e){this.targetLerpDuration=1/e}get targetLerpDuration(){return this._lookTargetLerpDuration}set targetLerpDuration(e){this._lookTargetLerpDuration=e}_lookTargetLerpDuration=1;targetBounds=null;rotateLeft(e){this._controls?._rotateLeft(e)}rotateUp(e){this._controls?._rotateUp(e)}pan(e,t){this._controls?._pan(e,t)}zoomIn(e){e>0?this._controls?._dollyIn(1-e):e<0&&this._controls?._dollyOut(1+e)}_controls=null;_cameraObject=null;_lookTargetLerpActive=!1;_lookTargetStartPosition=new o;_lookTargetEndPosition=new o;_lookTargetLerp01=0;_cameraLerpActive=!1;_cameraStartPosition=new o;_cameraEndPosition=new o;_cameraLerp01=0;_cameraLerpDuration=0;_fovLerpActive=!1;_fovLerpStartValue=0;_fovLerpEndValue=0;_fovLerp01=0;_fovLerpDuration=0;_inputs=0;_enableTime=0;_startedListeningToKeyEvents=!1;_eventSystem;_afterHandleInputFn;_camera=null;_syncedTransform;_didSetTarget=0;_didApplyLookAtTarget=!1;awake(){vh&&console.debug(`OrbitControls`,this),this.lookAtConstraint&&(console.warn(`[OrbitControls] lookAtConstraint is deprecated, use lookTarget and lockLookAtTarget instead. This will be removed in a future version.`),!this.lookAtTarget&&this.lookAtConstraint.sources?.[0]&&(this.lookAtTarget=this.lookAtConstraint.sources[0],this.lockLookAtTarget=this.lookAtConstraint.locked)),this._didSetTarget=0,this._didApplyLookAtTarget=!1,this._startedListeningToKeyEvents=!1,this.context.domElement.cameraControls===!1&&(this.enabled=!1)}start(){this._eventSystem=gh.get(this.context)??void 0,this._eventSystem&&(this._afterHandleInputFn=this.afterHandleInput.bind(this),this._eventSystem.addEventListener(hh.AfterHandleInput,this._afterHandleInputFn))}onDestroy(){this._controls?.dispose(),this._eventSystem?.removeEventListener(hh.AfterHandleInput,this._afterHandleInputFn)}onEnable(){this._didSetTarget=0,this._didApplyLookAtTarget=!1,this._enableTime=this.context.time.time;let e=G.getComponent(this.gameObject,Z);this._camera=e;let t=e?.threeCamera;if(!t&&this.gameObject instanceof C&&(t=this.gameObject),t&&sr(t,this,!0),!this._controls&&t instanceof S){this._cameraObject=t;let e=this.targetElement??this.context.renderer.domElement,n=t?.quaternion.clone();this._controls=new pt(t,e),t?.quaternion.copy(n),Ch===void 0&&(Ch={...this._controls.keys});let r=Or(t),i=this.gameObject.worldForward,a=r.clone().sub(i.multiplyScalar(2.5));this._controls.target.copy(a)}if(this._controls)if(yh&&(this.enablePan=!0,this.enableZoom=!0,this.middleClickToFocus=!0,j.isMobileDevice()&&(this.doubleClickToFocus=!0)),this._controls.addEventListener(`start`,this.onControlsChangeStarted),this._controls.addEventListener(`endMovement`,this.onControlsChangeEnded),!this._startedListeningToKeyEvents&&this.enableKeys)this._startedListeningToKeyEvents=!0,this._controls.listenToKeyEvents(this.context.domElement);else try{this._controls.stopListenToKeyEvents()}catch{}this._syncedTransform=G.getComponent(this.gameObject,$m)??void 0,this.context.pre_render_callbacks.push(this.__onPreRender),this._activePointerEvents=[],this.context.input.addEventListener(`pointerdown`,this._onPointerDown,{queue:sc.Early}),this.context.input.addEventListener(`pointerdown`,this._onPointerDownLate,{queue:sc.Late}),this.context.input.addEventListener(`pointerup`,this._onPointerUp,{queue:sc.Early}),this.context.input.addEventListener(`pointerup`,this._onPointerUpLate,{queue:sc.Late})}onDisable(){if(this._camera?.threeCamera&&sr(this._camera.threeCamera,this,!1),this._controls){this._controls.enabled=!1,this._controls.autoRotate=!1,this._controls.removeEventListener(`start`,this.onControlsChangeStarted),this._controls.removeEventListener(`endMovement`,this.onControlsChangeEnded);try{this._controls.stopListenToKeyEvents()}catch{}this._startedListeningToKeyEvents=!1}this._activePointerEvents.length=0,this.context.input.removeEventListener(`pointerdown`,this._onPointerDown),this.context.input.removeEventListener(`pointerdown`,this._onPointerDownLate),this.context.input.removeEventListener(`pointerup`,this._onPointerUp),this.context.input.removeEventListener(`pointerup`,this._onPointerUpLate)}_activePointerEvents;_lastTimeClickOnBackground=-1;_clickOnBackgroundCount=0;_onPointerDown=e=>{this._activePointerEvents.push(e)};_onPointerDownLate=e=>{e.used&&this._controls&&(this._controls.enabled=!1)};_onPointerUp=e=>{for(let t=this._activePointerEvents.length-1;t>=0;t--){let n=this._activePointerEvents[t];if(n.pointerId===e.pointerId&&n.button===e.button){this._activePointerEvents.splice(t,1);break}}if(this.clickBackgroundToFitScene>0&&e.isClick&&e.button===0){if(e.hasRay||e.intersections.push(...this.context.physics.raycast()),e.intersections.length<=0){let e=this.context.time.time-this._lastTimeClickOnBackground;this._lastTimeClickOnBackground=this.context.time.time,this.clickBackgroundToFitScene<=1||e=this.clickBackgroundToFitScene-1&&(this.autoRotate=!1,this.fitCamera({objects:this.context.scene,immediate:!1}))):this._clickOnBackgroundCount=0}vh&&console.log(this.clickBackgroundToFitScene,e.intersections.length,this._clickOnBackgroundCount)}};_onPointerUpLate=e=>{this.doubleClickToFocus&&e.isDoubleClick&&!e.used&&this.setTargetFromRaycast()};updateTargetNow(e){vh&&console.warn(`OrbitControls: updateTargetNow is using raycasting to update the target immediately. This can be expensive and should be used with caution.`,e);let t=new p(this._cameraObject?.worldPosition,this._cameraObject?.worldForward.multiplyScalar(-1)),n=this.context.physics.raycastFromRay(t,e),r=n.length>0?n[0]:void 0;r&&r.distance>this.minZoom&&r.distance{vh&&console.debug(`OrbitControls: Change started`),this._controls&&(this._orbitStartAngle=this._controls.getAzimuthalAngle()+this._controls.getPolarAngle(),this._zoomStartDistance=this._controls.getDistance()),this._syncedTransform&&this._syncedTransform.requestOwnership()};onControlsChangeEnded=()=>{if(vh&&console.debug(`OrbitControls: Change ended`,{autoTarget:this.autoTarget}),this._controls&&this.autoTarget){let e=this._controls.getAzimuthalAngle()+this._controls.getPolarAngle()-this._orbitStartAngle;Math.abs(e)<.01?(vh&&console.debug(`OrbitControls: Update target`,{deltaAngle:e}),this.updateTargetNow({allowSlowRaycastFallback:!1})):vh&&console.debug(`OrbitControls: No target update`,{deltaAngle:e})}};_shouldDisable=!1;afterHandleInput(e){e.detail.args.pointerId===0&&(e.detail.args.isDown?this._controls&&this._eventSystem&&(this._shouldDisable=this._eventSystem.hasActiveUI):(!e.detail.args.isPressed||e.detail.args.isUp)&&(this._shouldDisable=!1))}onPausedChanged(e){this._controls&&e&&(this._controls.enabled=!1)}onBeforeRender(){if(this._controls){if(this._cameraObject!==this.context.mainCamera){this._controls.enabled=!1;return}if(this._controls.enabled=!0,(this.context.input.getPointerDown(1)||this.context.input.getPointerDown(2)||this.context.input.mouseWheelChanged||this.context.input.getPointerPressed(0)&&this.context.input.getPointerPositionDelta(0)?.length())&&(this._inputs+=1),this._inputs>0&&this.allowInterrupt&&(this.enableRotate&&(this.autoRotate=!1),this._cameraLerpActive=!1,this._lookTargetLerpActive=!1),this._inputs=0,this.autoTarget&&this._didSetTarget++===0){let e=G.getComponent(this.gameObject,Z);if(e&&!this.setLookTargetFromConstraint()){this.debugLog&&console.log(`NO TARGET`);let t=Or(e.threeCamera),n=new o(0,0,-Math.max(.01,t.length())).applyMatrix4(e.threeCamera.matrixWorld);vh&&H.DrawLine(t,n,5592575,10),this.setLookTargetPosition(n,!0)}if(!this.setLookTargetFromConstraint()){let e=new kd;e.screenPoint=new w(0,0),e.lineThreshold=.1;let t=this.context.physics.raycast(e);t.length>0&&this.setLookTargetPosition(t[0].point,!0),bh&&console.log(`OrbitControls hits`,...t)}}if(this.middleClickToFocus&&this.context.input.getPointerClicked(1)&&this.setTargetFromRaycast(),this._lookTargetLerpActive||this._cameraLerpActive||this._fovLerpActive){if(this._cameraLerpActive&&this._cameraObject)if(this._cameraLerp01+=this.context.time.deltaTime/this._cameraLerpDuration,this._cameraLerp01>=1)this._cameraObject.position.copy(this._cameraEndPosition),this._cameraLerpActive=!1,this.dispatchEvent(new Th(this,`camera`));else{let e=N.easeInOutCubic(this._cameraLerp01);this._cameraObject.position.lerpVectors(this._cameraStartPosition,this._cameraEndPosition,e)}if(this._lookTargetLerpActive)if(this._lookTargetLerp01+=this.context.time.deltaTime/this._lookTargetLerpDuration,this._lookTargetLerp01>=1)this.lerpLookTarget(this._lookTargetEndPosition,this._lookTargetEndPosition,1),this._lookTargetLerpActive=!1,this.dispatchEvent(new Th(this,`lookat`));else{let e=N.easeInOutCubic(this._lookTargetLerp01);this.lerpLookTarget(this._lookTargetStartPosition,this._lookTargetEndPosition,e)}if(this._fovLerpActive&&this._cameraObject){let e=this._cameraObject;if(this._fovLerp01+=this.context.time.deltaTime/this._fovLerpDuration,this._fovLerp01>=1)e.fov=this._fovLerpEndValue,this._fovLerpActive=!1;else{let t=N.easeInOutCubic(this._fovLerp01);e.fov=N.lerp(this._fovLerpStartValue,this._fovLerpEndValue,t)}e.updateProjectionMatrix()}}if(this.targetBounds){let e=this._controls.target,t=this.targetBounds.worldPosition,n=P(this.targetBounds.worldScale).multiplyScalar(.5),r=P(t).sub(n),i=P(t).add(n),a=P(this._controls.target).clamp(r,i),o=.1;o<=0?e.copy(a):e.lerp(a,this.context.time.deltaTime/o),this._lookTargetLerpActive&&(o<=0?this._lookTargetEndPosition.copy(a):this._lookTargetEndPosition.lerp(a,this.context.time.deltaTime/(o*5))),vh&&H.DrawWireBox(t,n.multiplyScalar(2),16755200)}if(this._controls){this.debugLog&&(this._controls.domElement=this.context.renderer.domElement);let e=1/(this.context.focusRectSettings?.zoom||1);if(this._controls.enabled=!this._shouldDisable&&this._camera===this.context.mainCameraComponent&&!this.context.isInXR&&!this._activePointerEvents.some(e=>e.used),this._controls.keys=this.enableKeys?Ch:Sh,this._controls.autoRotate=this.autoRotate,this._controls.autoRotateSpeed=this.autoRotateSpeed,this._controls.enableZoom=this.enableZoom,this._controls.zoomSpeed=this.zoomSpeed,this._controls.zoomToCursor=this.zoomToCursor,this._controls.enableDamping=this.enableDamping,this._controls.dampingFactor=this.dampingFactor,this._controls.enablePan=this.enablePan,this._controls.panSpeed=e,this._controls.enableRotate=this.enableRotate,this._controls.minAzimuthAngle=this.minAzimuthAngle,this._controls.maxAzimuthAngle=this.maxAzimuthAngle,this._controls.minPolarAngle=this.minPolarAngle,this._controls.maxPolarAngle=this.maxPolarAngle,yh||(this._camera?.threeCamera?.type===`PerspectiveCamera`?(this._controls.minDistance=this.minZoom,this._controls.maxDistance=this.maxZoom,this._controls.minZoom=0,this._controls.maxZoom=1/0):(this._controls.minDistance=0,this._controls.maxDistance=1/0,this._controls.minZoom=this.minZoom,this._controls.maxZoom=this.maxZoom)),typeof xh==`number`||xh===!0){this._controls.enableDamping=!0;let e=typeof xh==`number`?xh:.99;this._controls.dampingFactor=Math.max(.001,1-Math.min(1,e))}this.allowInterrupt||(this._lookTargetLerpActive&&(this._controls.enablePan=!1),this._cameraLerpActive&&(this._controls.enableRotate=!1,this._controls.autoRotate=!1),(this._lookTargetLerpActive||this._cameraLerpActive)&&(this._controls.enableZoom=!1)),this.context.isInXR||(!yh&&this.lookAtTarget&&!this._lookTargetLerpActive&&(this.lockLookAtTarget?this.setLookTargetFromConstraint(this.lookAtConstraint01):this._didApplyLookAtTarget||(this._didApplyLookAtTarget=!0,this.setLookTargetFromConstraint(1))),this._controls.update(this.context.time.deltaTime),vh&&H.DrawWireSphere(this._controls.target,.1,65280))}}}__onPreRender=()=>{let e=this.context.pre_render_callbacks.indexOf(this.__onPreRender);e>=0&&this.context.pre_render_callbacks.splice(e,1),this.autoFit&&(this.autoFit=!1,this.fitCamera({centerCamera:`y`,immediate:!0,objects:this.scene.children}))};setCameraAndLookTarget(e,t=!1){if(!e)return(M()||vh)&&console.warn(`[OrbitControls] setCameraAndLookTarget target is null`),!1;if(!(e instanceof S)&&!(e instanceof Z))return(M()||vh)&&console.warn(`[OrbitControls] setCameraAndLookTarget target is not an Object3D or Camera`),!1;e instanceof Z&&(e=e.gameObject);let n=e.worldPosition,r=e.worldForward;e instanceof qe&&(vh&&console.debug(`[OrbitControls] setCameraAndLookTarget flip forward direction for camera`),r.multiplyScalar(-1));let i=new p(n,r);return vh&&H.DrawRay(i.origin,i.direction,16711680,10),this.setTargetFromRaycast(i,t)||this.setLookTargetPosition(i.at(2,P()),t),this.setCameraTargetPosition(n,t),!0}setCameraTargetPosition(e,t=!1){e&&(e instanceof S&&(e=Or(e)),this._cameraEndPosition||=new o,this._cameraEndPosition.copy(e),t===!0?(this._cameraLerpActive=!1,this._cameraObject&&this._cameraObject.position.copy(this._cameraEndPosition)):this._cameraObject&&(this._cameraLerpActive=!0,this._cameraLerp01=0,this._cameraStartPosition.copy(this._cameraObject?.position),typeof t==`number`?this._cameraLerpDuration=t:this._cameraLerpDuration=this.targetLerpDuration))}get cameraLerpActive(){return this._cameraLerpActive}stopCameraLerp(){this._cameraLerpActive=!1}setFieldOfView(e,t=!1){if(!this._controls||typeof e!=`number`)return;let n=this._camera?.threeCamera;n&&(t===!0?n.fov=e:(this._fovLerpActive=!0,this._fovLerp01=0,this._fovLerpStartValue=n.fov,this._fovLerpEndValue=e,typeof t==`number`?this._fovLerpDuration=t:this._fovLerpDuration=this.targetLerpDuration))}setLookTargetPosition(e=null,t=!1){this._controls&&e&&(e instanceof S&&(e=Or(e)),this._lookTargetEndPosition.copy(e),this._didSetTarget++,vh&&(console.warn(`OrbitControls: setLookTargetPosition`,e,t),H.DrawWireSphere(this._lookTargetEndPosition,.2,16711680,2)),t===!0?this.lerpLookTarget(this._lookTargetEndPosition,this._lookTargetEndPosition,1):(this._lookTargetLerpActive=!0,this._lookTargetLerp01=0,this._lookTargetStartPosition.copy(this._controls.target),typeof t==`number`?this._lookTargetLerpDuration=t:this._lookTargetLerpDuration=this.targetLerpDuration))}get lookTargetLerpActive(){return this._lookTargetLerpActive}stopLookTargetLerp(){this._lookTargetLerpActive=!1}setLookTargetFromConstraint(e=1){return!this._controls||!this.lookAtTarget?!1:(this.lookAtTarget.getWorldPosition(this._lookTargetEndPosition),this.lerpLookTarget(this._controls.target,this._lookTargetEndPosition,e),!0)}lerpLookTarget(e,t,n){this._controls&&(n>=1?this._controls.target.copy(t):this._controls.target.lerpVectors(e,t,n),this.lookAtTarget&&this.lockLookAtTarget&&(this.lookAtTarget.worldPosition=this._controls.target))}setTargetFromRaycast(e,t=!1){if(!this.controls)return!1;let n=e?this.context.physics.raycastFromRay(e):this.context.physics.raycast();for(let e of n)if(e.distance>0&&G.isActiveInHierarchy(e.object)){let n=ch(e.object);if(n&&n.canvas?.screenspace)break;return this.setLookTargetPosition(e.point,t),!0}return!1}fitCamera(e,t){let n;if(Array.isArray(e)||e&&`type`in e?n=e:e&&typeof e==`object`&&!(e instanceof S)&&!Array.isArray(e)&&(t=e,n=t.objects),n&&!Array.isArray(n)&&(n=[n]),(!Array.isArray(n)||n&&n.length<=0)&&(n=this.context.scene.children),!Array.isArray(n)||n.length<=0){console.warn(`No objects to fit camera to...`);return}let r=Mm({objects:[...n],...t,autoApply:!1,context:this.context,camera:this._cameraObject,currentZoom:this._controls?.getDistance()||void 0,minZoom:this.minZoom,maxZoom:this.maxZoom});r&&(this.setLookTargetPosition(r.lookAt,t?.immediate||!1),this.setCameraTargetPosition(r.position,t?.immediate||!1),this.setFieldOfView(t?.fov,t?.immediate||!1),this.onBeforeRender())}_haveAttachedKeyboardEvents=!1};Y([F()],X.prototype,`autoTarget`,void 0),Y([F()],X.prototype,`autoFit`,void 0),Y([F()],X.prototype,`enableRotate`,void 0),Y([F()],X.prototype,`autoRotate`,void 0),Y([F()],X.prototype,`autoRotateSpeed`,void 0),Y([F()],X.prototype,`minAzimuthAngle`,void 0),Y([F()],X.prototype,`maxAzimuthAngle`,void 0),Y([F()],X.prototype,`minPolarAngle`,void 0),Y([F()],X.prototype,`maxPolarAngle`,void 0),Y([F()],X.prototype,`enableKeys`,void 0),Y([F()],X.prototype,`enableDamping`,void 0),Y([F()],X.prototype,`dampingFactor`,void 0),Y([F()],X.prototype,`enableZoom`,void 0),Y([F()],X.prototype,`minZoom`,void 0),Y([F()],X.prototype,`maxZoom`,void 0),Y([F()],X.prototype,`zoomSpeed`,void 0),Y([F()],X.prototype,`enablePan`,void 0),Y([F(S)],X.prototype,`lookAtTarget`,void 0),Y([F()],X.prototype,`lockLookAtTarget`,void 0),Y([F()],X.prototype,`lookAtConstraint01`,void 0),Y([F(Pm)],X.prototype,`lookAtConstraint`,void 0),Y([F()],X.prototype,`allowInterrupt`,void 0),Y([F()],X.prototype,`middleClickToFocus`,void 0),Y([F()],X.prototype,`doubleClickToFocus`,void 0),Y([F()],X.prototype,`clickBackgroundToFitScene`,void 0),Y([F()],X.prototype,`targetLerpDuration`,null),Y([F(S)],X.prototype,`targetBounds`,void 0);var Eh=function(e,t,n,r){var i=arguments.length,a=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r,o;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)a=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(o=e[s])&&(a=(i<3?o(a):i>3?o(t,n,a):o(t,n))||a);return i>3&&a&&Object.defineProperty(t,n,a),a},Dh;(function(e){e[e.None=0]=`None`,e[e.Skybox=1]=`Skybox`,e[e.SolidColor=2]=`SolidColor`,e[e.Uninitialized=4]=`Uninitialized`})(Dh||={});var Oh=A(`debugcam`),kh=A(`debugscreenpointtoray`),Z=class e extends K{get isCamera(){return!0}get aspect(){return this._cam instanceof C?this._cam.aspect:this.context.domWidth/this.context.domHeight}set aspect(e){this._cam instanceof C&&this._cam.aspect!==e&&(this._cam.aspect=e,this._cam.updateProjectionMatrix())}get fieldOfView(){return this._cam instanceof C?this._cam.fov:this._fov}set fieldOfView(e){let t=this.fieldOfView!=e;if(this._fov=e,t&&this._cam&&this._cam instanceof C){if(this._fov===void 0){console.warn(`Can not set undefined fov on PerspectiveCamera`);return}this._cam.fov=this._fov,this._cam.updateProjectionMatrix()}}get nearClipPlane(){return this._nearClipPlane}set nearClipPlane(e){let t=this._nearClipPlane!=e;this._nearClipPlane=e,this._cam&&(t||this._cam.near!=e)&&(this._cam.near=e,this._cam.updateProjectionMatrix())}_nearClipPlane=.1;get farClipPlane(){return this._farClipPlane}set farClipPlane(e){let t=this._farClipPlane!=e;this._farClipPlane=e,this._cam&&(t||this._cam.far!=e)&&(this._cam.far=e,this._cam.updateProjectionMatrix())}_farClipPlane=1e3;applyClippingPlane(){this._cam&&(this._cam.near=this._nearClipPlane,this._cam.far=this._farClipPlane,this._cam.updateProjectionMatrix())}get clearFlags(){return this._clearFlags}set clearFlags(e){if(typeof e==`string`)switch(e){case`skybox`:e=Dh.Skybox;break;case`solidcolor`:e=Dh.SolidColor;break;default:e=Dh.None;break}e!==this._clearFlags&&(this._clearFlags=e,this.applyClearFlagsIfIsActiveCamera())}orthographic=!1;orthographicSize=5;ARBackgroundAlpha=0;set cullingMask(e){this._cullingMask=e,this._cam&&(this._cam.layers.mask=e)}get cullingMask(){return this._cam?this._cam.layers.mask:this._cullingMask}_cullingMask=4294967295;set cullingLayer(e){this.cullingMask=(1<>>0}set backgroundBlurriness(e){e!==this._backgroundBlurriness&&(e===void 0?this._backgroundBlurriness=void 0:this._backgroundBlurriness=Math.min(Math.max(e,0),1),this.applyClearFlagsIfIsActiveCamera())}get backgroundBlurriness(){return this._backgroundBlurriness}_backgroundBlurriness=void 0;set backgroundIntensity(e){e!==this._backgroundIntensity&&(e===void 0?this._backgroundIntensity=void 0:this._backgroundIntensity=Math.min(Math.max(e,0),10),this.applyClearFlagsIfIsActiveCamera())}get backgroundIntensity(){return this._backgroundIntensity}_backgroundIntensity=void 0;set backgroundRotation(e){e!==this._backgroundRotation&&(e===void 0?this._backgroundRotation=void 0:this._backgroundRotation=e,this.applyClearFlagsIfIsActiveCamera())}get backgroundRotation(){return this._backgroundRotation}_backgroundRotation=void 0;set environmentIntensity(e){this._environmentIntensity=e}get environmentIntensity(){return this._environmentIntensity}_environmentIntensity=void 0;get backgroundColor(){return this._backgroundColor??null}set backgroundColor(e){e&&(this._backgroundColor||=new md(1,1,1,1),this._backgroundColor.copy(e),(!(`alpha`in e)||e.alpha===void 0)&&(this._backgroundColor.alpha=1),this.applyClearFlagsIfIsActiveCamera())}set targetTexture(e){this._targetTexture=e}get targetTexture(){return this._targetTexture}_targetTexture=null;_backgroundColor;_fov;_cam=null;_clearFlags=Dh.SolidColor;_skybox;get cam(){return this.threeCamera}get threeCamera(){return this.activeAndEnabled&&this.buildCamera(),this._cam}static _origin=new o;static _direction=new o;screenPointToRay(t,n,r){let i=this.threeCamera,a=e._origin;a.set(t,n,-1),this.context.input.convertScreenspaceToRaycastSpace(a),kh&&console.log(`screenPointToRay`,t.toFixed(2),n.toFixed(2),`now:`,a.x.toFixed(2),a.y.toFixed(2),`isInXR:`+this.context.isInXR),a.z=-1,a.unproject(i);let o=e._direction.set(a.x,a.y,a.z),s=Or(i);return o.sub(s),o.normalize(),r?(r.set(s,o),r):new p(s.clone(),o.clone())}_frustum;getFrustum(){return this._frustum||(this._frustum=new ge,this.updateFrustum()),this._frustum}updateFrustum(){this._frustum||=new ge,this._frustum.setFromProjectionMatrix(this.getProjectionScreenMatrix(this._projScreenMatrix,!0),this.context.renderer.coordinateSystem)}getProjectionScreenMatrix(e,t){return t&&this._projScreenMatrix.multiplyMatrices(this.threeCamera.projectionMatrix,this.threeCamera.matrixWorldInverse),e===this._projScreenMatrix?e:e.copy(this._projScreenMatrix)}_projScreenMatrix=new ce;awake(){kh&&window.addEventListener(`pointerdown`,e=>{let t=e.clientX,n=e.clientY;console.log(`touch`,t.toFixed(2),n.toFixed(2));let r=this.screenPointToRay(t,n),i=`#`+Math.floor(Math.random()*16777215).toString(16);H.DrawRay(r.origin,r.direction,i,10)})}onEnable(){Oh&&console.log(`Camera enabled: \"${this.name}\". ClearFlags=${Dh[this._clearFlags]}`,this),this.buildCamera(),(this.tag==`MainCamera`||!this.context.mainCameraComponent)&&(this.context.setCurrentCamera(this),jh(this)),this.applyClearFlagsIfIsActiveCamera({applySkybox:!0})}onDisable(){this.context.removeCamera(this)}onLeaveXR(e){this.fieldOfView=this._fov}onBeforeRender(){if(this._cam&&(this._frustum&&this.updateFrustum(),this._clearFlags===Dh.SolidColor&&this.applyClearFlagsIfIsActiveCamera(),this._targetTexture)){this.context.isManagedExternally&&(this._warnedAboutExternalRenderer||(this._warnedAboutExternalRenderer=!0,console.warn(`Rendering with external renderer is not supported yet. This may not work or throw errors. Please remove the the target texture from your camera: `+this.name,this.targetTexture))),this.context.composer;let e=this.context.renderer;if(e){let t=this.context.mainCameraComponent;this.applyClearFlags(),this._targetTexture.render(this.context.scene,this._cam,e),t?.applyClearFlags()}}}buildCamera(){if(this._cam)return;let e=this.gameObject.isCamera,t=null;if(e?(t=this.gameObject,t?.layers.enableAll(),t instanceof C&&(this._fov=t.fov)):t=this.gameObject.children[0],t&&t.isCamera)t instanceof C&&(this._fov&&(t.fov=this._fov),t.near=this._nearClipPlane,t.far=this._farClipPlane,t.updateProjectionMatrix());else if(!this.orthographic)t=new C(this.fieldOfView,window.innerWidth/window.innerHeight,this._nearClipPlane,this._farClipPlane),this.fieldOfView&&(t.fov=this.fieldOfView),this.gameObject.add(t);else{let e=this.orthographicSize*100;t=new ke(window.innerWidth/-e,window.innerWidth/e,window.innerHeight/e,window.innerHeight/-e,this._nearClipPlane,this._farClipPlane),this.gameObject.add(t)}this._cam=t,this._cam.layers.mask=this._cullingMask,this.tag==`MainCamera`&&this.context.setCurrentCamera(this)}applyClearFlagsIfIsActiveCamera(e){this.context.mainCameraComponent===this&&this.applyClearFlags(e)}applyClearFlags(t){if(!this._cam){Oh&&console.log(`Camera does not exist (apply clear flags)`);return}if(this.fieldOfView=this.fieldOfView,Oh){let e=`[Camera] Apply ClearFlags: ${Dh[this._clearFlags]} - \"${this.name}\"`;console.debug(e)}let n=this.context.domElement.getAttribute(`background-image`)||this.context.domElement.getAttribute(`background-color`);switch(this._clearFlags){case Dh.None:return;case Dh.Skybox:if(e.backgroundShouldBeTransparent(this.context)&&(!this.ARBackgroundAlpha||this.ARBackgroundAlpha<.001)){this.context.scene.background=null,this.context.renderer.setClearColor(0,0);return}(!this.scene.background||!this._skybox||t?.applySkybox===!0)&&this.applySceneSkybox(),this._backgroundBlurriness!==void 0&&!this.context.domElement.getAttribute(`background-blurriness`)?this.context.scene.backgroundBlurriness=this._backgroundBlurriness:Oh&&console.warn(`Camera \"${this.name}\" has no background blurriness`),this._backgroundIntensity!==void 0&&!this.context.domElement.getAttribute(`background-intensity`)&&(this.context.scene.backgroundIntensity=this._backgroundIntensity),this._backgroundRotation!==void 0&&!this.context.domElement.getAttribute(`background-rotation`)?this.context.scene.backgroundRotation=this._backgroundRotation:Oh&&console.warn(`Camera \"${this.name}\" has no background intensity`);break;case Dh.SolidColor:if(this._backgroundColor&&!n){let t=this._backgroundColor.alpha;e.backgroundShouldBeTransparent(this.context)&&(t=this.ARBackgroundAlpha??0),this.context.scene.background=null,this.context.xr?.isVR?this.context.renderer.setClearColor(Cr(this._backgroundColor).convertLinearToSRGB()):this.context.renderer.setClearColor(this._backgroundColor,t)}else this._backgroundColor||Oh&&console.warn(`[Camera] has no background color \"${this.name}\" `);break;case Dh.Uninitialized:n||(this.context.scene.background=null,this.context.renderer.setClearColor(0,0));break}}applySceneSkybox(){this._skybox||=new Ah(this),this._skybox.apply()}static backgroundShouldBeTransparent(e){let t=e.renderer.xr?.getSession();if(!t)return!1;if(typeof t._transparent==`boolean`)return t._transparent;let n=t.environmentBlendMode;Oh&&Ti(`Environment blend mode: `+n+` on `+navigator.userAgent);let r=n===`additive`||n===`alpha-blend`;if(e.isInAR&&n===`opaque`){if(navigator.userAgent?.includes(`OculusBrowser`))r=!0;else if(navigator.userAgent?.includes(`Mozilla`)&&navigator.userAgent?.includes(`Mobile WebXRViewer/v2`))r=!0;else if(j.isNeedleAppClip())return!0}return t._transparent=r,r}};Eh([F()],Z.prototype,`aspect`,null),Eh([F()],Z.prototype,`fieldOfView`,null),Eh([F()],Z.prototype,`nearClipPlane`,null),Eh([F()],Z.prototype,`farClipPlane`,null),Eh([F()],Z.prototype,`clearFlags`,null),Eh([F()],Z.prototype,`orthographic`,void 0),Eh([F()],Z.prototype,`orthographicSize`,void 0),Eh([F()],Z.prototype,`ARBackgroundAlpha`,void 0),Eh([F()],Z.prototype,`cullingMask`,null),Eh([F()],Z.prototype,`backgroundBlurriness`,null),Eh([F()],Z.prototype,`backgroundIntensity`,null),Eh([F(He)],Z.prototype,`backgroundRotation`,null),Eh([F()],Z.prototype,`environmentIntensity`,null),Eh([F(md)],Z.prototype,`backgroundColor`,null),Eh([F(ym)],Z.prototype,`targetTexture`,null);var Ah=class{_camera;_skybox;get context(){return this._camera?.context}constructor(e){this._camera=e}apply(){if(this._skybox=this.context.lightmaps.tryGetSkybox(this._camera.sourceId),!this._skybox)this._did_log_failed_to_find_skybox||(this._did_log_failed_to_find_skybox=!0,console.warn(`Camera \"${this._camera.name}\" has no skybox texture. ${this._camera.sourceId}`));else if(this.context.scene.background!==this._skybox){let e=this.context.domElement.getAttribute(`background-image`)||this.context.domElement.getAttribute(`background-color`);Oh&&console.debug(`[Camera] Apply Skybox ${this._skybox?.name} ${e} - \"${this._camera.name}\"`),e?.length||(this._skybox.mapping!==306&&(this._skybox.mapping=303),this.context.scene.background=this._skybox)}}};function jh(e){A(`freecam`)&&e.context.mainCameraComponent===e&&G.getOrAddComponent(e.gameObject,X)}var Mh=A(`debugshadowcomponents`);tt.prototype.interactable={get(){return this.interactive},set(e){this.interactable=e}};var Nh=class e extends K{isRoot(){return this.Root?.gameObject===this.gameObject}get canvas(){let e=this.Root;return e?.isCanvas?e:null}get Canvas(){return this.canvas}markDirty(){gh.markUIDirty(this.context)}get shadowComponent(){return this._shadowComponent}set shadowComponent(e){this._shadowComponent=e}_shadowComponent=null;_controlsChildLayout=!0;get controlsChildLayout(){return this._controlsChildLayout}set controlsChildLayout(e){this._controlsChildLayout=e,this.shadowComponent&&(this.shadowComponent.autoLayout=e)}_root=void 0;get Root(){return this._root===void 0&&(this._root=G.getComponentInParent(this.gameObject,Ph)),this._root}_parentComponent=void 0;__internalNewInstanceCreated(e){return super.__internalNewInstanceCreated(e),this.shadowComponent=null,this._root=void 0,this._parentComponent=void 0,this}onEnable(){super.onEnable()}addShadowComponent(t,n){if(!t)return;this.removeShadowComponent();let r=this.isRoot()?this.gameObject:this.gameObject.parent;if(this._parentComponent=G.getComponentInParent(r,e),!this._parentComponent){console.warn(`Component \"${this.name}\" doesn't have a UI parent anywhere. Do you have an UI element outside a Canvas? UI components must be a child of a Canvas component`,this);return}t.name=this.name+` (`+(this.constructor.name??`UI`)+`)`,t.autoLayout=this._parentComponent.controlsChildLayout,t[Yi]=this,this.setShadowComponentOwner(t);let i=!1;if(this.Root?.gameObject===this.gameObject)this.gameObject.add(t);else{let e=this._parentComponent.shadowComponent;e&&(e?.add(t),i=!0)}this.shadowComponent=t,n&&n.shadowComponent&&this.shadowComponent&&n.shadowComponent.add(this.shadowComponent),Jo&&t.add(new _e(.5)),this.onAfterAddedToScene(),i&&rt(),Mh&&console.warn(`Added shadow component`,this.shadowComponent)}setShadowComponentOwner(e){if(e&&(e[Yi]===void 0||e[Yi]===this)&&(e[Yi]=this,e.children))for(let t of e.children)this.setShadowComponentOwner(t)}traverseOwnedShadowComponents(e,t,n){if(e&&e[Yi]===t){n(e);for(let r of e.children)this.traverseOwnedShadowComponents(r,t,n)}}removeShadowComponent(){this.shadowComponent&&this.shadowComponent.removeFromParent()}onAfterAddedToScene(){}setInteractable(e){this.shadowComponent&&(this.shadowComponent.interactable=e)}},Ph=class extends Nh{awake(){super.awake()}},Fh=function(e,t,n,r){var i=arguments.length,a=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r,o;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)a=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(o=e[s])&&(a=(i<3?o(a):i>3?o(t,n,a):o(t,n))||a);return i>3&&a&&Object.defineProperty(t,n,a),a},Ih=A(`debugui`),Lh=A(`debuguilayout`),Rh=class{width;height},zh=class{x;y;width;height},Bh=new o,Vh=new ce,Hh=new E,Uh=class e extends Nh{get parent(){return this._parentRectTransform}get translation(){return this.gameObject.position}get rotation(){return this.gameObject.quaternion}get scale(){return this.gameObject.scale}_anchoredPosition;get anchoredPosition(){return this._anchoredPosition||=new w,this._anchoredPosition}set anchoredPosition(e){this._anchoredPosition=e}sizeDelta=new w(100,100);pivot=new w(.5,.5);anchorMin=new w(0,0);anchorMax=new w(1,1);minWidth;minHeight;get width(){let e=this.sizeDelta.x;return this.anchorMin.x!==this.anchorMax.x&&this._parentRectTransform&&(e=this._parentRectTransform.width*(this.anchorMax.x-this.anchorMin.x),e+=this.sizeDelta.x),this.minWidth!==void 0&&e{this.markDirty()}),dh(this,`sizeDelta`,()=>{this.markDirty()}),dh(this,`pivot`,()=>{this.markDirty()}),dh(this,`anchorMin`,()=>{this.markDirty()}),dh(this,`anchorMax`,()=>{this.markDirty()})}onEnable(){super.onEnable(),this.rectBlock||=new S,this.lastMatrix||=new ce,this._lastAnchoring||=new w,this._initialPosition||=new o,this._anchoredPosition||=new w,this.addShadowComponent(this.rectBlock),this._transformNeedsUpdate=!0,this.canvas?.registerTransform(this)}onDisable(){super.onDisable(),this.removeShadowComponent(),this.canvas?.unregisterTransform(this)}onParentRectTransformChanged(e){this._transformNeedsUpdate||this.onApplyTransform(Lh?`${e.name} changed`:void 0)}get isDirty(){return this._transformNeedsUpdate||=!this.lastMatrix.equals(this.gameObject.matrix),this._transformNeedsUpdate}markDirty(){this._transformNeedsUpdate||(Lh&&console.warn(`RectTransform markDirty()`,this.name),this._transformNeedsUpdate=!0,this._lastUpdateFrame=-1)}updateTransform(){(this._transformNeedsUpdate||!this.lastMatrix.equals(this.gameObject.matrix))&&this.canUpdate()&&this.onApplyTransform(this._transformNeedsUpdate?`Marked dirty`:`Matrix changed`)}canUpdate(){return this._transformNeedsUpdate&&this.activeAndEnabled&&this._lastUpdateFrame!==this.context.time.frame}onApplyTransform(t){if(this.context.time.frameCount===this._lastUpdateFrame)return;this._lastUpdateFrame=this.context.time.frameCount;let n=this.shadowComponent;if(n){this.gameObject.parent?this._parentRectTransform=G.getComponentInParent(this.gameObject.parent,e):this._parentRectTransform=void 0,this._transformNeedsUpdate=!1,Lh&&console.warn(`RectTransform → ApplyTransform`,this.name+` because `+t),this.isRoot()?this.Root.screenspace||(n.rotation.y=Math.PI):(n.matrix.identity(),n.matrixAutoUpdate=!1,Bh.set(0,0,0),this.applyPivot(Bh),n.matrix.setPosition(Bh.x,Bh.y,0),(this.gameObject.quaternion.x||this.gameObject.quaternion.y||this.gameObject.quaternion.z)&&(Hh.copy(this.gameObject.quaternion),Hh.x*=-1,Hh.z*=-1,Vh.makeRotationFromQuaternion(Hh),n.matrix.premultiply(Vh)),Bh.set(0,0,0),this.applyAnchoring(Bh),this.canvas?.screenspace?Bh.z+=.1:Bh.z+=.01,Vh.identity(),Vh.setPosition(Bh.x,Bh.y,Bh.z),n.matrix.premultiply(Vh),n.matrix.scale(this.gameObject.scale)),this.lastMatrix.copy(this.gameObject.matrix);for(let e of Hf(this.gameObject,Nh,!0,1)){if(e===this||!e.activeAndEnabled)continue;let t=e;t.onParentRectTransformChanged&&t.onParentRectTransformChanged(this)}}}_lastAnchoring;applyAnchoring(e){this._lastAnchoring||=new w;let t=this._lastAnchoring.sub(this._anchoredPosition);this.gameObject.position.x+=t.x,this.gameObject.position.y+=t.y,this._lastAnchoring.copy(this._anchoredPosition),e.x+=this._initialPosition.x-this.gameObject.position.x,e.y+=this._initialPosition.y-this.gameObject.position.y,e.z+=this._initialPosition.z-this.gameObject.position.z;let n=this._parentRectTransform;if(n){let t=0,r=1-this.anchorMax.y-this.anchorMin.y;t-=n.height*.5*r,e.y+=t;let i=0,a=1-this.anchorMax.x-this.anchorMin.x;i-=n.width*.5*a,e.x+=i}}applyPivot(e){if(this.pivot&&!this.isRoot()){let t=this.pivot.x-.5;e.x-=t*this.sizeDelta.x*this.gameObject.scale.x;let n=this.pivot.y-.5;e.y-=n*this.sizeDelta.y*this.gameObject.scale.y}}getBasicOptions(){let e={width:this.sizeDelta.x,height:this.sizeDelta.y,offset:0,backgroundOpacity:0,borderWidth:0,borderRadius:0,borderOpacity:0,letterSpacing:-.03};return this.ensureValidSize(e),e}ensureValidSize(e,t=1e-4){return e.width<=0&&(e.width=t),e.height<=0&&(e.height=1e-4),e}_createdBlocks=[];_createdTextBlocks=[];createNewBlock(e){e={...this.getBasicOptions(),...e},Ih&&console.log(this.name,e);let t=new tt(e);return this._createdBlocks.push(t),t}createNewText(e){Ih&&console.log(e),e={...this.getBasicOptions(),...e},Ih&&console.log(this.name,e);let t=new Qe(e);return this._createdTextBlocks.push(t),t}};Fh([F(w)],Uh.prototype,`anchoredPosition`,null),Fh([F(w)],Uh.prototype,`sizeDelta`,void 0),Fh([F(w)],Uh.prototype,`pivot`,void 0),Fh([F(w)],Uh.prototype,`anchorMin`,void 0),Fh([F(w)],Uh.prototype,`anchorMax`,void 0);var Wh=function(e,t,n,r){var i=arguments.length,a=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r,o;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)a=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(o=e[s])&&(a=(i<3?o(a):i>3?o(t,n,a):o(t,n))||a);return i>3&&a&&Object.defineProperty(t,n,a),a},Gh=class extends K{effectColor;effectDistance};Wh([F(md)],Gh.prototype,`effectColor`,void 0),Wh([F(w)],Gh.prototype,`effectDistance`,void 0);var Kh=function(e,t,n,r){var i=arguments.length,a=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r,o;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)a=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(o=e[s])&&(a=(i<3?o(a):i>3?o(t,n,a):o(t,n))||a);return i>3&&a&&Object.defineProperty(t,n,a),a},qh={backgroundColor:new a(1,1,1),backgroundOpacity:1,borderColor:new a(1,1,1),borderOpacity:1},Jh=class e extends Nh{get isGraphic(){return!0}get color(){return this._color||=new md(1,1,1,1),this._color}set color(e){(!this._color||this._color.r!==e.r||this._color.g!==e.g||this._color.b!==e.b||this._color.alpha!==e.alpha)&&(this._color||=new md(1,1,1,1),this._color.copy(e),this.onColorChanged())}_alphaFactor=1;setAlphaFactor(e){this._alphaFactor=e,this.onColorChanged()}get alphaFactor(){return this._alphaFactor}sRGBColor=new a(1,0,1);onColorChanged(){if(this.uiObject){this.sRGBColor.copy(this._color),this.sRGBColor.convertLinearToSRGB(),qh.backgroundColor=this.sRGBColor,qh.backgroundOpacity=this._color.alpha;let e=this.uiObject._simpleState__activeStates?.[0];if(e){let t=this.uiObject._simpleState__states?.[e];t&&(`backgroundColor`in t&&(qh.backgroundColor=t.backgroundColor),`backgroundOpacity`in t&&(qh.backgroundOpacity=t.backgroundOpacity))}qh.backgroundOpacity*=this._alphaFactor,this.applyEffects(qh,this._alphaFactor),this.uiObject.set(qh),this.markDirty()}}get m_Color(){return this._color}raycastTarget=!0;uiObject=null;_color=null;_rect=null;_stateManager=null;get rectTransform(){if(this._rect||=G.getComponent(this.gameObject,Uh),!this._rect)throw Error(`Not Supported: Make sure to add a RectTransform component before adding a UI Graphic component.`);return this._rect}onParentRectTransformChanged(){this.uiObject?.set({width:this.rectTransform.width,height:this.rectTransform.height}),this.markDirty()}__internalNewInstanceCreated(e){return super.__internalNewInstanceCreated(e),this._rect=null,this.uiObject=null,this._stateManager=null,this._color&&=this._color.clone(),this}setState(e){this.makePanel(),this.uiObject&&(this.uiObject.setState(e),this?.markDirty())}setupState(e){this.makePanel(),this.uiObject&&(this._stateManager||=new it(this.uiObject),this.uiObject.setupState(e.state,e.attributes))}setOptions(e){this.makePanel(),this.uiObject&&this.uiObject.set(e)}awake(){super.awake(),this.makePanel(),dh(this,`_color`,()=>ph(this,this.onColorChanged))}onEnable(){super.onEnable(),this.uiObject&&(this.rectTransform.shadowComponent?.add(this.uiObject),this.addShadowComponent(this.uiObject,this.rectTransform))}onDisable(){super.onDisable(),this.uiObject&&this.removeShadowComponent()}_currentlyCreatingPanel=!1;makePanel(){if(this.uiObject||this._currentlyCreatingPanel)return;this._currentlyCreatingPanel=!0;let e={backgroundColor:this.color,backgroundOpacity:this.color.alpha,offset:.015};this.onBeforeCreate(e),this.applyEffects(e),this.onCreate(e),this.controlsChildLayout=!1,this._currentlyCreatingPanel=!1,this.onAfterCreated(),this.onColorChanged()}onBeforeCreate(e){}onCreate(e){this.uiObject=this.rectTransform.createNewBlock(e),this.uiObject.name=this.name}onAfterCreated(){}applyEffects(e,t=1){let n=this.gameObject?.getComponent(Gh);n&&(n.effectDistance&&(e.borderWidth=Math.max(Math.abs(n.effectDistance.x),Math.abs(n.effectDistance.y))),n.effectColor&&(e.borderColor=n.effectColor,e.borderOpacity=n.effectColor.alpha*t))}static textureCache=new Map;async setTexture(t){if(this.setOptions({backgroundOpacity:0}),t){if(e.textureCache.has(t))t=e.textureCache.get(t);else if(!t.isRenderTargetTexture){let n=t.clone();n.colorSpace=l,e.textureCache.set(t,n),t=n}this.setOptions({backgroundImage:t,borderRadius:0,backgroundOpacity:this.color.alpha,backgroundSize:`stretch`}),vt.assignTextureLOD(t,0).then(n=>{n instanceof be&&(t&&e.textureCache.set(t,n),this.setOptions({backgroundImage:n}),this.markDirty())})}else this.setOptions({backgroundImage:void 0,borderRadius:0,backgroundOpacity:this.color.alpha});this.markDirty()}onAfterAddedToScene(){super.onAfterAddedToScene(),this.shadowComponent&&(this.shadowComponent.offset=this.shadowComponent.position.z)}};Kh([F(md)],Jh.prototype,`color`,null),Kh([F()],Jh.prototype,`raycastTarget`,void 0);var Yh=class extends Jh{_flippedObject=!1;onAfterCreated(){this.uiObject&&!this._flippedObject&&(this._flippedObject=!0,this.uiObject.scale.y*=-1)}},Xh=function(e,t,n,r){var i=arguments.length,a=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r,o;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)a=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(o=e[s])&&(a=(i<3?o(a):i>3?o(t,n,a):o(t,n))||a);return i>3&&a&&Object.defineProperty(t,n,a),a},Zh=A(`debugtext`),Q;(function(e){e[e.UpperLeft=0]=`UpperLeft`,e[e.UpperCenter=1]=`UpperCenter`,e[e.UpperRight=2]=`UpperRight`,e[e.MiddleLeft=3]=`MiddleLeft`,e[e.MiddleCenter=4]=`MiddleCenter`,e[e.MiddleRight=5]=`MiddleRight`,e[e.LowerLeft=6]=`LowerLeft`,e[e.LowerCenter=7]=`LowerCenter`,e[e.LowerRight=8]=`LowerRight`})(Q||={});var Qh;(function(e){e[e.Truncate=0]=`Truncate`,e[e.Overflow=1]=`Overflow`})(Qh||={});var $h;(function(e){e[e.Wrap=0]=`Wrap`,e[e.Overflow=1]=`Overflow`})($h||={});var eg;(function(e){e[e.Normal=0]=`Normal`,e[e.Bold=1]=`Bold`,e[e.Italic=2]=`Italic`,e[e.BoldAndItalic=3]=`BoldAndItalic`})(eg||={});var tg=class extends Jh{alignment=Q.UpperLeft;verticalOverflow=Qh.Truncate;horizontalOverflow=$h.Wrap;lineSpacing=1;supportRichText=!1;font;fontStyle=eg.Normal;setAlphaFactor(e){super.setAlphaFactor(e),this.uiObject?.set({fontOpacity:this.color.alpha*this.alphaFactor}),this.markDirty()}get text(){return this._text}set text(e){e!==this._text&&(this._text=e,this.feedText(this.text,this.supportRichText),this.markDirty(),this.context.accessibility.updateElement(this,{label:this.text}))}set_text(e){this.text=e}get fontSize(){return this._fontSize}set fontSize(e){this._fontSize=e,this.uiObject?.set({fontSize:e})}sRGBTextColor=new a(1,0,1);onColorChanged(){this.sRGBTextColor.copy(this.color),this.sRGBTextColor.convertLinearToSRGB(),this.uiObject?.set({color:this.sRGBTextColor,fontOpacity:this.color.alpha})}onParentRectTransformChanged(){super.onParentRectTransformChanged(),this.uiObject&&this.updateOverflow()}onBeforeCanvasRender(e){this.updateOverflow()}updateOverflow(){let e=this.uiObject?._overflow;e&&(e._needsUpdate=!0)}onCreate(e){Zh&&console.log(this),this.horizontalOverflow==$h.Overflow&&(e.whiteSpace=`pre`),this.verticalOverflow==Qh.Truncate&&(this.context.renderer.localClippingEnabled=!0,e.overflow=`hidden`),this.horizontalOverflow==$h.Overflow&&(this.verticalOverflow,Qh.Truncate),e.lineHeight=this.lineSpacing,delete e.backgroundOpacity,delete e.backgroundColor,Zh&&(e.backgroundColor=16750848,e.backgroundOpacity=.5);let t=this.rectTransform;e={...e,...this.getTextOpts()},this.getAlignment(e),Zh&&(e.backgroundColor=Math.random()*16777215,e.backgroundOpacity=.1),this.uiObject=t.createNewText(e),this.feedText(this.text,this.supportRichText)}onAfterAddedToScene(){super.onAfterAddedToScene(),this.handleTextRenderOnTop()}_text=``;_fontSize=12;_textMeshUi=null;getTextOpts(){let e=this.fontSize,t={color:this.color,fontOpacity:this.color.alpha,fontSize:e,fontKerning:`normal`};return this.setFont(t,this.fontStyle),t}onEnable(){super.onEnable(),this.context.accessibility.updateElement(this,{role:`text`,label:this.text,hidden:!1}),this._didHandleTextRenderOnTop=!1,this.uiObject&&this.uiObject.addAfterUpdate(()=>{this.setShadowComponentOwner(this.uiObject),this.markDirty()}),setTimeout(()=>this.markDirty(),10),this.canvas?.registerEventReceiver(this)}onDisable(){super.onDisable(),this.canvas?.unregisterEventReceiver(this),this.context.accessibility.updateElement(this,{hidden:!0})}onDestroy(){super.onDestroy(),this.context.accessibility.removeElement(this)}getAlignment(e){switch(e.flexDirection=`column`,this.alignment){case Q.UpperLeft:case Q.MiddleLeft:case Q.LowerLeft:e.textAlign=`left`;break;case Q.UpperCenter:case Q.MiddleCenter:case Q.LowerCenter:e.textAlign=`center`;break;case Q.UpperRight:case Q.MiddleRight:case Q.LowerRight:e.textAlign=`right`;break}switch(this.alignment){default:case Q.UpperLeft:case Q.UpperCenter:case Q.UpperRight:e.alignItems=`start`;break;case Q.MiddleLeft:case Q.MiddleCenter:case Q.MiddleRight:e.alignItems=`center`;break;case Q.LowerLeft:case Q.LowerCenter:case Q.LowerRight:e.alignItems=`end`;break}return e}feedText(e,t){if(Zh&&console.log(`feedText`,this.uiObject,e,t),this.uiObject)if(this._textMeshUi||=[],this.uiObject.children.length=0,!t||e.length===0)this.uiObject.textContent=e;else{let t=this.getNextTag(e);if(!t){this.uiObject.textContent=``,this.setOptions({textContent:e});return}else if(t.startIndex>0){for(let e=this.uiObject.children.length-1;e>=0;e--){let t=this.uiObject.children[e];t.isUI&&(this.uiObject.remove(t),t.clear())}let n=new et({textContent:e.substring(0,t.startIndex),color:`inherit`});this.uiObject.add(n)}let n=[];for(;t;){let r=this.getNextTag(e,t.endIndex),i={fontFamily:this.uiObject?.get(`fontFamily`),color:`inherit`,textContent:``};if(r){i.textContent=this.getText(e,t,r),this.handleTag(t,i,n);let a=new et(i);this.uiObject?.add(a)}else{i.textContent=e.substring(t.endIndex),this.handleTag(t,i,n);let r=new et(i);this.uiObject?.add(r)}t=r}}}_didHandleTextRenderOnTop=!1;handleTextRenderOnTop(){this._didHandleTextRenderOnTop||(this._didHandleTextRenderOnTop=!0,this.startCoroutine(this.renderOnTopCoroutine()))}*renderOnTopCoroutine(){if(!this.canvas)return;let e=[],t=this.canvas,n={renderOnTop:t.renderOnTop,depthWrite:t.depthWrite,doubleSided:t.doubleSided};for(;;){let t=!1;if(this._textMeshUi)for(let r=0;r6?t.color=parseInt(`0x`+e.type.substring(7)):t.color=new a(1,1,1)}else if(e.type==`b`){this.setFont(t,eg.Bold);let r=new ng(e,{fontWeight:700});n.push(r)}else if(e.type==`i`){this.setFont(t,eg.Italic);let r=new ng(e,{fontStyle:`italic`});n.push(r)}}}getText(e,t,n){return e.substring(t.endIndex,n.startIndex)}getNextTag(e,t=0){let n=e.indexOf(`<`,t),r=e.indexOf(`>`,n);if(n>=0&&r>=0){let t=e.substring(n+1,r);return{type:t,startIndex:n,endIndex:r+1,isEndTag:t.startsWith(`/`)}}return null}setFont(e,t){if(!this.font)return;let n=this.font,r=this.getFamilyNameWithCorrectSuffix(n,t);Zh&&console.log(`Selected font family:`+r);let i=nt.getFontFamily(r);switch(i||=nt.addFontFamily(r),e.fontFamily=i,t){default:case eg.Normal:e.fontWeight=400,e.fontStyle=`normal`;break;case eg.Bold:e.fontWeight=700,e.fontStyle=`normal`;break;case eg.Italic:e.fontWeight=400,e.fontStyle=`italic`;break;case eg.BoldAndItalic:e.fontStyle=`italic`,e.fontWeight=400}let a=i.getVariant(e.fontWeight,e.fontStyle);if(!a){let t=r;t?.endsWith(`-msdf.json`)||(t+=`-msdf.json`);let n=r;n?.endsWith(`.png`)||(n+=`.png`),a=i.addVariant(e.fontWeight,e.fontStyle,t,n),a?.addEventListener(`ready`,()=>{this.markDirty()})}}getFamilyNameWithCorrectSuffix(e,t){(e.startsWith(`https:`)||e.startsWith(`http:`))&&(e=new URL(e).pathname);let n=e.lastIndexOf(`-`);if(n<0)return e;let r=e.substring(n+1)?.toLowerCase();if(rg.includes(r))return Zh&&console.warn(`Unsupported font style: `+r),e;let i=e.lastIndexOf(`/`),a=e;i>=0&&(a=a.substring(i+1));let o=a[0]===a[0].toUpperCase(),s=e.substring(0,n>i?n:e.length);switch(Zh&&console.log(`Select font: `,e,eg[t],a,o,s),t){case eg.Normal:return o?s+`-Regular`:s+`-regular`;case eg.Bold:return o?s+`-Bold`:s+`-bold`;case eg.Italic:return o?s+`-Italic`:s+`-italic`;case eg.BoldAndItalic:return o?s+`-BoldItalic`:s+`-bolditalic`;default:return e}}};Xh([F()],tg.prototype,`alignment`,void 0),Xh([F()],tg.prototype,`verticalOverflow`,void 0),Xh([F()],tg.prototype,`horizontalOverflow`,void 0),Xh([F()],tg.prototype,`lineSpacing`,void 0),Xh([F()],tg.prototype,`supportRichText`,void 0),Xh([F(URL)],tg.prototype,`font`,void 0),Xh([F()],tg.prototype,`fontStyle`,void 0),Xh([F()],tg.prototype,`text`,null),Xh([F()],tg.prototype,`fontSize`,null);var ng=class{tag;previousValues;constructor(e,t){this.tag=e,this.previousValues=t}},rg=[`medium`,`mediumitalic`,`black`,`blackitalic`,`thin`,`thinitalic`,`extrabold`,`light`,`lightitalic`,`semibold`],$=function(e,t,n,r){var i=arguments.length,a=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r,o;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)a=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(o=e[s])&&(a=(i<3?o(a):i>3?o(t,n,a):o(t,n))||a);return i>3&&a&&Object.defineProperty(t,n,a),a},ig=A(`debuguilayout`),ag=class{left=0;right=0;top=0;bottom=0;get vertical(){return this.top+this.bottom}get horizontal(){return this.left+this.right}};$([F()],ag.prototype,`left`,void 0),$([F()],ag.prototype,`right`,void 0),$([F()],ag.prototype,`top`,void 0),$([F()],ag.prototype,`bottom`,void 0);var og;(function(e){e[e.UpperLeft=0]=`UpperLeft`,e[e.UpperCenter=1]=`UpperCenter`,e[e.UpperRight=2]=`UpperRight`,e[e.MiddleLeft=3]=`MiddleLeft`,e[e.MiddleCenter=4]=`MiddleCenter`,e[e.MiddleRight=5]=`MiddleRight`,e[e.LowerLeft=6]=`LowerLeft`,e[e.LowerCenter=7]=`LowerCenter`,e[e.LowerRight=8]=`LowerRight`,e[e.Custom=9]=`Custom`})(og||={});var sg;(function(e){e.Horizontal=`x`,e.Vertical=`y`})(sg||={});var cg=class extends K{_rectTransform=null;get rectTransform(){return this._rectTransform}onParentRectTransformChanged(e){this._needsUpdate=!0}_needsUpdate=!1;get isDirty(){return this._needsUpdate}get isLayoutGroup(){return!0}updateLayout(){this._rectTransform&&(ig&&console.warn(`Layout Update`,this.context.time.frame,this.name),this._needsUpdate=!1,this.onCalculateLayout(this._rectTransform))}childAlignment=og.UpperLeft;reverseArrangement=!1;spacing=0;padding;minWidth=0;minHeight=0;flexibleHeight=0;flexibleWidth=0;preferredHeight=0;preferredWidth=0;start(){this._needsUpdate=!0}onEnable(){ig&&console.log(this.name,this),this._rectTransform=this.gameObject.getComponent(Uh);let e=this.gameObject.getComponentInParent(gg);e&&e.registerLayoutGroup(this),this._needsUpdate=!0}onDisable(){let e=this.gameObject.getComponentInParent(gg);e&&e.unregisterLayoutGroup(this)}set m_Spacing(e){e!==this.spacing&&(this._needsUpdate=!0,this.spacing=e)}get m_Spacing(){return this.spacing}};$([F()],cg.prototype,`childAlignment`,void 0),$([F()],cg.prototype,`reverseArrangement`,void 0),$([F()],cg.prototype,`spacing`,void 0),$([F(ag)],cg.prototype,`padding`,void 0),$([F()],cg.prototype,`minWidth`,void 0),$([F()],cg.prototype,`minHeight`,void 0),$([F()],cg.prototype,`flexibleHeight`,void 0),$([F()],cg.prototype,`flexibleWidth`,void 0),$([F()],cg.prototype,`preferredHeight`,void 0),$([F()],cg.prototype,`preferredWidth`,void 0);var lg=class extends cg{childControlHeight=!0;childControlWidth=!0;childForceExpandHeight=!1;childForceExpandWidth=!1;childScaleHeight=!1;childScaleWidth=!1;onCalculateLayout(e){let t=this.primaryAxis,n=e.width,r=n,i=e.height,a=i;r-=this.padding.horizontal,a-=this.padding.vertical,t===sg.Horizontal?this.padding.horizontal:this.padding.vertical;let o=t===sg.Horizontal,s=o?`y`:`x`,c=o?this.childControlWidth:this.childControlHeight,l=o?this.childControlHeight:this.childControlWidth,u=o?this.childForceExpandWidth:this.childForceExpandHeight,d=o?this.childForceExpandHeight:this.childForceExpandWidth,f=o?a:r,p=o?n:i,m=.5*(o?this.childAlignment%3:Math.floor(this.childAlignment/3)),h=0;o?h+=this.padding.left:h+=this.padding.top;let g=0,_=0;for(let e=0;e0&&(v=e/_)}let y=0;y+=this.padding.left,y-=this.padding.right,m!==0&&(h=p-g,h*=m,h-=ee*m,o?(h-=this.padding.right*m,h+=this.padding.left*(1-m),hh&&(h=e-v*.5+p+this.padding.left,h-=m)}let g=h;t===sg.Vertical&&(g=-g),a.anchoredPosition[t]!==g&&(a.anchoredPosition[t]=g),h+=m,h+=this.spacing,b+=1}}}};$([F()],lg.prototype,`childControlHeight`,void 0),$([F()],lg.prototype,`childControlWidth`,void 0),$([F()],lg.prototype,`childForceExpandHeight`,void 0),$([F()],lg.prototype,`childForceExpandWidth`,void 0),$([F()],lg.prototype,`childScaleHeight`,void 0),$([F()],lg.prototype,`childScaleWidth`,void 0);var ug=class extends lg{get primaryAxis(){return sg.Vertical}},dg=class extends lg{get primaryAxis(){return sg.Horizontal}},fg=class extends cg{onCalculateLayout(){}},pg=function(e,t,n,r){var i=arguments.length,a=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r,o;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)a=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(o=e[s])&&(a=(i<3?o(a):i>3?o(t,n,a):o(t,n))||a);return i>3&&a&&Object.defineProperty(t,n,a),a},mg;(function(e){e[e.ScreenSpaceOverlay=0]=`ScreenSpaceOverlay`,e[e.ScreenSpaceCamera=1]=`ScreenSpaceCamera`,e[e.WorldSpace=2]=`WorldSpace`,e[e.Undefined=-1]=`Undefined`})(mg||={});var hg=A(`debuguilayout`),gg=class e extends Ph{get isCanvas(){return!0}get screenspace(){return this.renderMode!==mg.WorldSpace}set renderOnTop(e){e!==this._renderOnTop&&(this._renderOnTop=e,this.onRenderSettingsChanged())}get renderOnTop(){return this._renderOnTop===void 0?!!(this.screenspace&&this._renderMode===mg.ScreenSpaceOverlay):this._renderOnTop}_renderOnTop;set depthWrite(e){this._depthWrite!==e&&(this._depthWrite=e,this.onRenderSettingsChanged())}get depthWrite(){return this._depthWrite}_depthWrite=!1;set doubleSided(e){this._doubleSided!==e&&(this._doubleSided=e,this.onRenderSettingsChanged())}get doubleSided(){return this._doubleSided}_doubleSided=!0;set castShadows(e){this._castShadows!==e&&(this._castShadows=e,this.onRenderSettingsChanged())}get castShadows(){return this._castShadows}_castShadows=!1;set receiveShadows(e){this._receiveShadows!==e&&(this._receiveShadows=e,this.onRenderSettingsChanged())}get receiveShadows(){return this._receiveShadows}_receiveShadows=!1;get renderMode(){return this._renderMode}set renderMode(e){this._renderMode!==e&&(this._renderMode=e,this.onRenderSettingsChanged())}_renderMode=mg.Undefined;_rootCanvas;set rootCanvas(t){this._rootCanvas instanceof e||(this._rootCanvas=t)}get rootCanvas(){return this._rootCanvas}_scaleFactor=1;get scaleFactor(){return this._scaleFactor}set scaleFactor(e){this._scaleFactor=e}worldCamera;planeDistance=-1;awake(){this.shadowComponent=this.gameObject,this.previousParent=this.gameObject.parent,hg&&console.log(`Canvas.Awake()`,this.previousParent?.name+`/`+this.gameObject.name),super.awake()}start(){this.applyRenderSettings()}onEnable(){super.onEnable(),this._updateRenderSettingsRoutine=void 0,this._lastMatrixWorld=new ce,this.applyRenderSettings(),document.addEventListener(`resize`,this._boundRenderSettingsChanged),this.context.pre_render_callbacks.push(this.onBeforeRenderRoutine),this.context.post_render_callbacks.push(this.onAfterRenderRoutine)}onDisable(){super.onDisable(),document.removeEventListener(`resize`,this._boundRenderSettingsChanged);let e=this.context.pre_render_callbacks.indexOf(this.onBeforeRenderRoutine);e!==-1&&this.context.pre_render_callbacks.splice(e,1);let t=this.context.post_render_callbacks.indexOf(this.onAfterRenderRoutine);t!==-1&&this.context.post_render_callbacks.splice(t,1)}_boundRenderSettingsChanged=this.onRenderSettingsChanged.bind(this);previousParent=null;_lastMatrixWorld=null;_rectTransforms=[];registerTransform(e){this._rectTransforms.push(e)}unregisterTransform(e){let t=this._rectTransforms.indexOf(e);t!==-1&&this._rectTransforms.splice(t,1)}_layoutGroups=new Map;registerLayoutGroup(e){let t=e.gameObject;this._layoutGroups.set(t,e)}unregisterLayoutGroup(e){let t=e.gameObject;this._layoutGroups.delete(t)}_receivers=[];registerEventReceiver(e){this._receivers.push(e)}unregisterEventReceiver(e){let t=this._receivers.indexOf(e);t!==-1&&this._receivers.splice(t,1)}async onEnterXR(e){this.screenspace?(e.xr.isVR||e.xr.isPassThrough)&&(this.gameObject.visible=!1):(this.gameObject.visible=!1,await qt(1).then(()=>{this.gameObject.visible=!0}))}onLeaveXR(e){this.screenspace&&(e.xr.isVR||e.xr.isPassThrough)&&(this.gameObject.visible=!0)}onBeforeRenderRoutine=()=>{if(this.previousParent=this.gameObject.parent,(this.context.xr?.isVR||this.context.xr?.isPassThrough)&&this.screenspace){this.gameObject.visible=!1,this.gameObject.removeFromParent();return}this.renderOnTop||this.screenspace?this.gameObject.removeFromParent():(this.onUpdateRenderMode(),this.handleLayoutUpdates(),this.shadowComponent?.updateMatrixWorld(!0),this.shadowComponent?.updateWorldMatrix(!0,!0),this.invokeBeforeRenderEvents(),gh.ensureUpdateMeshUI($e,this.context))};onAfterRenderRoutine=()=>{if((this.context.xr?.isVR||this.context.xr?.isPassThrough)&&this.screenspace){this.previousParent?.add(this.gameObject);return}if((this.screenspace||this.renderOnTop)&&this.previousParent&&this.context.mainCamera){this.screenspace?this.context.mainCamera?.add(this.gameObject):this.previousParent.add(this.gameObject);let e=this.context.renderer.autoClear,t=this.context.renderer.autoClearColor;this.context.renderer.autoClear=!1,this.context.renderer.autoClearColor=!1,this.context.renderer.clearDepth(),this.onUpdateRenderMode(!0),this.handleLayoutUpdates(),this.shadowComponent?.updateMatrixWorld(!0),this.invokeBeforeRenderEvents(),gh.ensureUpdateMeshUI($e,this.context,!0),this.context.renderer.render(this.gameObject,this.context.mainCamera),this.context.renderer.autoClear=e,this.context.renderer.autoClearColor=t,this.previousParent.add(this.gameObject)}this._lastMatrixWorld?.copy(this.gameObject.matrixWorld)};invokeBeforeRenderEvents(){for(let e of this._receivers)e.onBeforeCanvasRender?.(this)}handleLayoutUpdates(){this._lastMatrixWorld===null&&(this._lastMatrixWorld=new ce);let e=!this._lastMatrixWorld.equals(this.gameObject.matrixWorld);hg&&e&&console.log(`Canvas Layout changed`,this.context.time.frameCount,this.name);for(let t of this._rectTransforms){e&&t.markDirty();let n=this._layoutGroups.get(t.gameObject);t.isDirty&&!n&&(n=t.gameObject.getComponentInParent(cg)),(t.isDirty||n?.isDirty)&&(hg&&console.log(`CANVAS UPDATE ### `+t.name+` ##################################### `+this.context.time.frame),n?.updateLayout(),t.updateTransform())}}applyRenderSettings(){this.onRenderSettingsChanged()}_updateRenderSettingsRoutine;onRenderSettingsChanged(){this._updateRenderSettingsRoutine||=this.startCoroutine(this._updateRenderSettingsDelayed(),z.OnBeforeRender)}*_updateRenderSettingsDelayed(){if(yield,this._updateRenderSettingsRoutine=void 0,this.shadowComponent){this.onUpdateRenderMode(),uh(this.shadowComponent,this);for(let e of G.getComponentsInChildren(this.gameObject,Nh))uh(e.shadowComponent,this)}}_activeRenderMode=-1;_lastWidth=-1;_lastHeight=-1;onUpdateRenderMode(e=!1){if(!e&&this._renderMode===this._activeRenderMode&&this._lastWidth===this.context.domWidth&&this._lastHeight===this.context.domHeight)return;this._activeRenderMode=this._renderMode;let t=this.context.mainCameraComponent,n=10;switch(t&&t.nearClipPlane>0&&t.farClipPlane>0&&(n=N.lerp(t.nearClipPlane,t.farClipPlane,.01)),this._renderMode===mg.ScreenSpaceCamera&&(this.worldCamera&&(t=this.worldCamera),this.planeDistance>0&&(n=this.planeDistance)),this._renderMode){case mg.ScreenSpaceOverlay:case mg.ScreenSpaceCamera:if(this._lastWidth=this.context.domWidth,this._lastHeight=this.context.domHeight,!t)return;let e=n+.01;this.gameObject.position.x=0,this.gameObject.position.y=0,this.gameObject.position.z=-e,this.gameObject.quaternion.identity();let r=this.gameObject.getComponent(Uh),i=!1;r.sizeDelta.x!==this.context.domWidth&&(i=!0),r.sizeDelta.y!==this.context.domHeight&&(i=!0);let a=t.fieldOfView*Math.PI/180,o=2*Math.tan(a/2)*Math.abs(e);this.gameObject.scale.x=o/this.context.domHeight,this.gameObject.scale.y=o/this.context.domHeight,this.gameObject.scale.z=.01,i&&(r.sizeDelta.x=this.context.domWidth,r.sizeDelta.y=this.context.domHeight,r?.markDirty());break;case mg.WorldSpace:this._lastWidth=-1,this._lastHeight=-1;break}}};pg([F()],gg.prototype,`renderOnTop`,null),pg([F()],gg.prototype,`depthWrite`,null),pg([F()],gg.prototype,`doubleSided`,null),pg([F()],gg.prototype,`castShadows`,null),pg([F()],gg.prototype,`receiveShadows`,null),pg([F()],gg.prototype,`renderMode`,null),pg([F(gg)],gg.prototype,`rootCanvas`,null),pg([F()],gg.prototype,`scaleFactor`,null),pg([F(Z)],gg.prototype,`worldCamera`,void 0),pg([F()],gg.prototype,`planeDistance`,void 0);var _g=function(e,t,n,r){var i=arguments.length,a=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r,o;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)a=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(o=e[s])&&(a=(i<3?o(a):i>3?o(t,n,a):o(t,n))||a);return i>3&&a&&Object.defineProperty(t,n,a),a},vg=class extends K{get alpha(){return this._alpha}set alpha(e){e!==this._alpha&&(this._alpha=e,this.markDirty())}get isCanvasGroup(){return!0}_alpha=1;interactable=!0;blocksRaycasts=!0;_isDirty=!1;markDirty(){this._isDirty||(this._isDirty=!0,this.startCoroutine(this.applyChangesDelayed(),z.OnBeforeRender))}*applyChangesDelayed(){this._isDirty=!1,this.applyChangesNow()}_buffer=[];applyChangesNow(){this._buffer.length=0;for(let e of G.getComponentsInChildren(this.gameObject,Nh,this._buffer)){let t=e;t.setAlphaFactor&&t.setAlphaFactor(this._alpha)}}};_g([F()],vg.prototype,`alpha`,null),_g([F()],vg.prototype,`interactable`,void 0),_g([F()],vg.prototype,`blocksRaycasts`,void 0);var yg=function(e,t,n,r){var i=arguments.length,a=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r,o;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)a=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(o=e[s])&&(a=(i<3?o(a):i>3?o(t,n,a):o(t,n))||a);return i>3&&a&&Object.defineProperty(t,n,a),a},bg=class{texture=null;rect};yg([F(be)],bg.prototype,`texture`,void 0);var xg=class extends Yh{set image(e){this.sprite||=new bg,this.sprite.texture=e,this.onAfterCreated()}get image(){return this.sprite?this.sprite.texture:null}get sprite(){return this._sprite}set sprite(e){this._sprite!==e&&(this._sprite=e,this.onAfterCreated())}_sprite;pixelsPerUnitMultiplier=1;isBuiltinSprite(){let e=this.sprite;switch(e?.texture?.name){case`InputFieldBackground`:case`UISprite`:case`Background`:case`Knob`:return!0}return!e?.texture?.name?.length&&e?.texture?.image?.width===32&&e?.texture?.image?.height===32}onBeforeCreate(e){super.onBeforeCreate(e),this.isBuiltinSprite()&&(e.borderRadius=5/this.pixelsPerUnitMultiplier,this.sprite?.texture?.name===`Knob`&&(e.borderRadius=999))}onAfterCreated(){this.__didAwake&&(super.onAfterCreated(),!this.isBuiltinSprite()&&this.setTexture(this.sprite?.texture))}};yg([F(bg)],xg.prototype,`sprite`,null),yg([F()],xg.prototype,`pixelsPerUnitMultiplier`,void 0);var Sg=class extends Yh{get mainTexture(){return this._mainTexture}set mainTexture(e){this._mainTexture!==e&&(this._mainTexture=e,this.onAfterCreated())}_mainTexture;onAfterCreated(){this.__didAwake&&(super.onAfterCreated(),this.setTexture(this.mainTexture))}};yg([F(be)],Sg.prototype,`mainTexture`,null);var Cg=function(e,t,n,r){var i=arguments.length,a=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r,o;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)a=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(o=e[s])&&(a=(i<3?o(a):i>3?o(t,n,a):o(t,n))||a);return i>3&&a&&Object.defineProperty(t,n,a),a},wg=A(`debugbutton`),Tg;(function(e){e[e.None=0]=`None`,e[e.ColorTint=1]=`ColorTint`,e[e.SpriteSwap=2]=`SpriteSwap`,e[e.Animation=3]=`Animation`})(Tg||={});var Eg=class{colorMultiplier;disabledColor;fadeDuration;highlightedColor;normalColor;pressedColor;selectedColor};Cg([F()],Eg.prototype,`colorMultiplier`,void 0),Cg([F(md)],Eg.prototype,`disabledColor`,void 0),Cg([F()],Eg.prototype,`fadeDuration`,void 0),Cg([F(md)],Eg.prototype,`highlightedColor`,void 0),Cg([F(md)],Eg.prototype,`normalColor`,void 0),Cg([F(md)],Eg.prototype,`pressedColor`,void 0),Cg([F(md)],Eg.prototype,`selectedColor`,void 0);var Dg=class{disabledTrigger;highlightedTrigger;normalTrigger;pressedTrigger;selectedTrigger},Og=class extends K{click(){this.onClick?.invoke()}onClick=new _m;_isHovered=0;onPointerEnter(e){let t=e.event.pointerType===`mouse`&&e.button===0;t&&(this._isHovered+=1),wg&&console.warn(`Button Enter`,t,this._isHovered,this.animationTriggers?.highlightedTrigger,this.animator),this.interactable&&(this.transition==Tg.Animation&&this.animationTriggers&&this.animator?this.animator.setTrigger(this.animationTriggers.highlightedTrigger):this.transition===Tg.ColorTint&&this.colors&&this._image?.setState(`hovered`),t&&this.context.input.setCursor(`pointer`))}onPointerExit(){--this._isHovered,this._isHovered<0&&(this._isHovered=0),wg&&console.log(`Button Exit`,this._isHovered,this.animationTriggers?.highlightedTrigger,this.animator),this.interactable&&(this._isHovered>0||(this._isHovered=0,this.transition==Tg.Animation&&this.animationTriggers&&this.animator?this.animator.setTrigger(this.animationTriggers.normalTrigger):this.transition===Tg.ColorTint&&this.colors&&this._image?.setState(`normal`),this.context.input.unsetCursor(`pointer`)))}onPointerDown(e){wg&&console.log(`Button Down`,this.animationTriggers?.highlightedTrigger,this.animator),this.interactable&&(this.transition==Tg.Animation&&this.animationTriggers&&this.animator?this.animator.setTrigger(this.animationTriggers.pressedTrigger):this.transition===Tg.ColorTint&&this.colors&&this._image?.setState(`pressed`))}onPointerUp(e){wg&&console.warn(`Button Up`,this.animationTriggers?.highlightedTrigger,this.animator,this._isHovered),this.interactable&&(this.transition==Tg.Animation&&this.animationTriggers&&this.animator?this.animator.setTrigger(this._isHovered?this.animationTriggers.highlightedTrigger:this.animationTriggers.normalTrigger):this.transition===Tg.ColorTint&&this.colors&&this._image?.setState(this._isHovered?`hovered`:`normal`))}onPointerClick(e){if(this.interactable&&!(e.button!==0&&e.event.pointerType===tc.Mouse)&&(wg&&(console.warn(`Button Click`,this.onClick),Ti(`CLICKED button `+this.name+` at `+this.context.time.frameCount)),this.onClick&&this.onClick.listenerCount>0&&(this.onClick.invoke(),e.use(),this.context.accessibility.focus(this),wg))){let e=this.gameObject.worldPosition;e.add(this.gameObject.worldUp.multiplyScalar(1+Math.random()*.5)),H.DrawLabel(e,`CLICK:`+Date.now(),.1,1+Math.random()*.5)}}colors;transition;animationTriggers;animator;set interactable(e){this._interactable=e,this._image&&(this._image.setInteractable(e),e?this._image.setState(`normal`):this._image.setState(`disabled`))}get interactable(){return this._interactable}_interactable=!0;set_interactable(e){this.interactable=e}awake(){super.awake(),wg&&console.log(this),this._isInit=!1,this.init()}start(){this._image?.setInteractable(this.interactable),this.gameObject.getComponentInParent(rh)||this.gameObject.addComponent(ah)}onEnable(){super.onEnable(),this.context.accessibility.updateElement(this,{role:`button`,label:this.gameObject.name+` button`,hidden:!1})}onDisable(){super.onDisable(),this.context.accessibility.updateElement(this,{hidden:!0})}onDestroy(){this.context.accessibility.removeElement(this),this._isHovered&&this.context.input.unsetCursor(`pointer`)}_requestedAnimatorTrigger;*setAnimatorTriggerAtEndOfFrame(e){this._requestedAnimatorTrigger=e,yield,yield,this._requestedAnimatorTrigger==e&&this.animator?.setTrigger(e)}_isInit=!1;_image;init(){this._isInit||(this._isInit=!0,this._image=G.getComponent(this.gameObject,xg),this._image&&(this.stateSetup(this._image),this.interactable?this._image.setState(`normal`):this._image.setState(`disabled`)))}stateSetup(e){e.setInteractable(this.interactable);let t=this.getFinalColor(e.color,this.colors?.normalColor),n={state:`normal`,attributes:{backgroundColor:t,backgroundOpacity:t.alpha}};e.setupState(n);let r=this.getFinalColor(e.color,this.colors?.highlightedColor),i={state:`hovered`,attributes:{backgroundColor:r,backgroundOpacity:r.alpha}};e.setupState(i);let a=this.getFinalColor(e.color,this.colors?.pressedColor),o={state:`pressed`,attributes:{backgroundColor:a,backgroundOpacity:a.alpha}};e.setupState(o);let s=this.getFinalColor(e.color,this.colors?.selectedColor),c={state:`selected`,attributes:{backgroundColor:s,backgroundOpacity:s.alpha}};e.setupState(c);let l=this.getFinalColor(e.color,this.colors?.disabledColor),u={state:`disabled`,attributes:{backgroundColor:l,backgroundOpacity:l.alpha}};e.setupState(u)}getFinalColor(e,t){return t?e.clone().multiply(t).convertLinearToSRGB():e.clone().convertLinearToSRGB()}};Cg([F(_m)],Og.prototype,`onClick`,void 0),Cg([F(Eg)],Og.prototype,`colors`,void 0),Cg([F()],Og.prototype,`transition`,void 0),Cg([F(Dg)],Og.prototype,`animationTriggers`,void 0),Cg([F(fm)],Og.prototype,`animator`,void 0),Cg([F()],Og.prototype,`interactable`,null);var kg=function(e,t,n,r){var i=arguments.length,a=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r,o;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)a=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(o=e[s])&&(a=(i<3?o(a):i>3?o(t,n,a):o(t,n))||a);return i>3&&a&&Object.defineProperty(t,n,a),a},Ag=A(`debuginputfield`),jg=class e extends K{get text(){return this.textComponent?.text??``}set text(e){this.textComponent&&(this.textComponent.text=e,this.placeholder&&(e.length>0?this.placeholder.gameObject.visible=!1:this.placeholder.gameObject.visible=!0))}get isFocused(){return e.active===this}textComponent;placeholder;onValueChanged;onEndEdit;static active=null;static activeTime=-1;static htmlField=null;static htmlFieldFocused=!1;inputEventFn;_iosEventFn;start(){Ag&&console.log(this.name,this)}onEnable(){e.htmlField||(e.htmlField=document.createElement(`input`),e.htmlField.style.width=`0px`,e.htmlField.style.height=`0px`,e.htmlField.style.padding=`0px`,e.htmlField.style.border=`none`,e.htmlField.style.overflow=`hidden`,e.htmlField.style.caretColor=`transparent`,e.htmlField.style.outline=`none`,e.htmlField.classList.add(`ar`),e.htmlField.onfocus=()=>e.htmlFieldFocused=!0,e.htmlField.onblur=()=>e.htmlFieldFocused=!1,document.body.append(e.htmlField)),this.inputEventFn||=this.onInput.bind(this),e.htmlField.addEventListener(`keyup`,this.inputEventFn),this.placeholder&&this.textComponent?.text.length&&G.setActive(this.placeholder.gameObject,!1),j.isiOS()&&(this._iosEventFn=this.processInputOniOS.bind(this),window.addEventListener(`click`,this._iosEventFn))}onDisable(){e.htmlField?.removeEventListener(`keyup`,this.inputEventFn),this.onDeselected(),this._iosEventFn&&window.removeEventListener(`click`,this._iosEventFn)}clear(){e.active===this&&e.htmlField?(e.htmlField.value=``,this.setTextFromInputField()):(this.textComponent&&(this.textComponent.text=``),this.placeholder&&G.setActive(this.placeholder.gameObject,!0))}select(){this.onSelected()}deselect(){this.onDeselected()}onPointerEnter(e){e.event.pointerType===`mouse`&&e.button===0&&this.context.input.setCursor(`text`)}onPointerExit(e){this.context.input.unsetCursor(`text`)}onPointerClick(t){Ag&&console.log(`CLICK`,t,e.active),e.activeTime=this.context.time.time,e.active!==this&&this.startCoroutine(this.activeLoop(),z.LateUpdate),this.selectInputField()}*activeLoop(){for(this.onSelected();e.active===this&&!(this.context.input.getPointerClicked(0)&&this.context.time.time-e.activeTime>.2);)this.setTextFromInputField(),yield;this.onDeselected()}onSelected(){if(e.active!==this&&(Ag&&console.log(`Select`,this.name,this,e.htmlField,this.context.isInXR,this.context.arOverlayElement,this.textComponent?.text,e.htmlField?.value),e.active?.onDeselected(),e.active=this,this.placeholder&&G.setActive(this.placeholder.gameObject,!1),e.htmlField)){if(e.htmlField.value=this.textComponent?.text||``,Ag&&console.log(`set input field value`,e.htmlField.value),this.context.isInXR){let t=this.context.arOverlayElement;t&&t.append(e.htmlField)}this.selectInputField()}}onDeselected(){e.active===this&&(e.active=null,Ag&&console.log(`Deselect`,this.name,this),e.htmlField&&(e.htmlField.blur(),document.body.append(e.htmlField)),this.placeholder&&(!this.textComponent||this.textComponent.text.length<=0)&&G.setActive(this.placeholder.gameObject,!0),e.htmlField&&this.onEndEdit?.invoke(e.htmlField.value))}update(){e.active===this&&this.textComponent?.markDirty()}onInput(t){if(e.active===this){if(Ag&&console.log(t.code,t,e.htmlField?.value,this.textComponent?.text),t.code===`Escape`||t.code===`Enter`){this.onDeselected();return}e.htmlField&&(this.textComponent&&(this.setTextFromInputField(),this.placeholder&&G.setActive(this.placeholder.gameObject,this.textComponent.text.length<=0)),this.selectInputField())}}setTextFromInputField(){if(this.textComponent&&e.htmlField){let t=this.textComponent.text,n=e.htmlField.value,r=this.textComponent.text!==e.htmlField.value;this.textComponent.text=e.htmlField.value,r&&(Ag&&console.log(`[InputField] value changed:`,n,t),this.onValueChanged?.invoke(n,t))}}selectInputField(){e.htmlField&&(Ag&&console.log(`Focus Inputfield`,e.htmlFieldFocused,e.htmlField),e.htmlField.setSelectionRange(e.htmlField.value.length,e.htmlField.value.length),j.isiOS()?(e.htmlField.style.display=`block`,e.htmlField.focus({preventScroll:!0})):setTimeout(()=>e.htmlField?.focus(),1))}processInputOniOS(){let e=this.context.physics.raycast();if(!e.length)return;let t=e[0].object,n=ch(t);(n?.gameObject===this.gameObject||n?.gameObject.parent===this.gameObject)&&this.selectInputField()}};kg([F(tg)],jg.prototype,`textComponent`,void 0),kg([F(tg)],jg.prototype,`placeholder`,void 0),kg([F(_m)],jg.prototype,`onValueChanged`,void 0),kg([F(_m)],jg.prototype,`onEndEdit`,void 0);var Mg=function(e,t,n,r){var i=arguments.length,a=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r,o;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)a=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(o=e[s])&&(a=(i<3?o(a):i>3?o(t,n,a):o(t,n))||a);return i>3&&a&&Object.defineProperty(t,n,a),a},Ng=class extends K{id=null;keepAspect=!1;_object=null;onEnable(){if(this._object){this.gameObject.add(this._object);return}if(!this.id||!this.context.mainCamera)return;let e=document.getElementById(this.id);if(!e){console.warn(`Could not find element with id "`+this.id+`"`);return}e.style.display=`block`,e.style.visibility=`hidden`;let t=new mt;t.listenToPointerEvents(this.context.renderer,this.context.mainCamera),this.gameObject.add(t);let n=new ft(e);t.add(n),n.visible=!1;let r=n.material;r.transparent=!0,setTimeout(()=>{n.visible=!0;let e=Qr(this.gameObject).clone();ei(this.gameObject,0,0,0),this.gameObject.updateMatrixWorld();let r=new fe;r.setFromObject(t),this.setWorldRotation(e.x,e.y,e.z);let i=r.max.x-r.min.x,a=r.max.y-r.min.y;if(this.keepAspect){let e=i/a;i>a?n.scale.set(1/i,1/a/e,1):n.scale.set(1/i*e,1/a,1)}else n.scale.set(1/i,1/a,1);let o=this.gameObject.scale;n.scale.multiply(o)},1)}onDisable(){this._object?.removeFromParent()}};Mg([F()],Ng.prototype,`id`,void 0),Mg([F()],Ng.prototype,`keepAspect`,void 0);export{om as $,kt as $a,ji as $i,al as $n,ts as $r,ef as $t,ih as A,kr as Aa,fa as Ai,Xl as An,vn as Ao,ic as Ar,jf as At,Bm as B,ur as Ba,Yi as Bi,Ll as Bn,nn as Bo,js as Br,Pf as Bt,Z as C,vr as Ca,La as Ci,yu as Cn,Ht as Co,mc as Cr,Fp as Ct,gh as D,hi as Da,ba as Di,ou as Dn,It as Do,L as Dr,gp as Dt,X as E,mi as Ea,ka as Ei,su as En,Et as Eo,sc as Er,Cp as Et,Jm as F,ei as Fa,da as Fi,Ul as Fn,Pt as Fo,Ws as Fr,Ef as Ft,Pm as G,ir as Ga,Bi as Gi,Tl as Gn,fs as Gr,_f as Gt,Rm as H,lr as Ha,Hi,Ml as Hn,wt as Ho,Is as Hr,bf as Ht,Xm as I,Br as Ia,ca as Ii,Hl as In,Lt as Io,Hs as Ir,Nf as It,ym as J,Tn as Ja,Ki as Ji,bl as Jn,Es as Jr,mf as Jt,Mm as K,M as Ka,Wi as Ki,Dl as Kn,ps as Kr,pf as Kt,Km as L,hr as La,ta as Li,Vl as Ln,Qt as Lo,Vs as Lr,Af as Lt,eh as M,Fr as Ma,ma as Mi,Zl as Mn,Ut as Mo,Ks as Mr,Hf as Mt,th as N,Ir as Na,la as Ni,ql as Nn,Ft as No,Gs as Nr,Wf as Nt,sh as O,ui as Oa,xa as Oi,au as On,zt as Oo,oc as Or,Tf as Ot,$m as P,$r as Pa,ga as Pi,Wl as Pn,Nt as Po,Us as Pr,Of as Pt,fm as Q,Pn as Qa,Pi as Qi,ul as Qn,es as Qr,U as Qt,Um as R,si as Ra,Zi as Ri,Rl as Rn,Wt as Ro,Ls as Rr,kf as Rt,Ph as S,ti as Sa,za as Si,vu as Sn,Rt as So,pc as Sr,Np as St,Th as T,br as Ta,Va as Ti,cu as Tn,Dt as To,cc as Tr,wp as Tt,J as U,N as Ua,Vi as Ui,Al as Un,O as Uo,Ns as Ur,Sf as Ut,zm as V,sr as Va,Ji as Vi,Fl as Vn,Tt as Vo,Fs as Vr,If as Vt,Fm as W,rr as Wa,Ui as Wi,wl as Wn,k as Wo,Ps as Wr,gf as Wt,_m as X,En as Xa,F as Xi,hl as Xn,ms as Xr,Vd as Xt,mm as Y,Un as Ya,Ri as Yi,vl as Yn,_s as Yr,uf as Yt,gm as Z,Nn as Za,Fi as Zi,dl as Zn,cs as Zr,Qd as Zt,Gh as _,Or as _a,Ja as _i,B as _n,un as _o,kc as _r,Rp as _t,Sg as a,ai as aa,jo as ai,Bd as an,Gt as ao,nl as ar,Qp as at,Rh as b,zr as ba,Ha as bi,wu as bn,fn as bo,Mc as br,Pp as bt,mg as c,Ur as ca,Ho as ci,Ad as cn,A as co,Xc as cr,G as ct,ag as d,Cr as da,Fo as di,md as dn,ln as do,qc as dr,Up as dt,Mi as ea,$o as ei,tf as en,j as eo,ol as er,rm as et,ug as f,Tr as fa,Po as fi,pd as fn,Ot as fo,Vc as fr,Gp as ft,Yh as g,Xr as ga,Xa as gi,Iu as gn,on as go,Pc as gr,kp as gt,Jh as h,Kr as ha,mo as hi,Ku as hn,dn as ho,Lc as hr,Dp as ht,xg as i,_i as ia,Mo as ii,Gd as in,_n as io,Qc as ir,nm as it,oh as j,Ar as ja,ha as ji,$l as jn,Zt as jo,tc as jr,Vf as jt,ah as k,Zr as ka,ua as ki,iu as kn,Yt as ko,ac as kr,zf as kt,fg as l,fi as la,Bo as li,Sd as ln,Xt as lo,$c as lr,Yp as lt,Q as m,di as ma,Oo as mi,Zu as mn,sn as mo,Rc as mr,Op as mt,jg as n,Ti as na,Jo as ni,Kd as nn,bn as no,Yc as nr,tm as nt,vg as o,oi as oa,Ro as oi,jd as on,Kt as oo,el as or,K as ot,tg as p,P as pa,zo as pi,ed as pn,an as po,Ic as pr,Kp as pt,km as q,$n as qa,Gi as qi,El as qn,ds as qr,ff as qt,Og as r,Ei as ra,Lo as ri,Jd as rn,en as ro,Zc as rr,em as rt,gg as s,pi as sa,Io as si,kd as sn,qt as so,tl as sr,Xp as st,Ng as t,Di as ta,Yo as ti,Xd as tn,xn as to,il as tr,im as tt,dg as u,ni as ua,Go as ui,H as un,Mt as uo,Kc as ur,Wp as ut,zh as v,Pr as va,qa as vi,Tu as vn,mn as vo,Ac as vr,zp as vt,Dh as w,yr as wa,Ba as wi,uu as wn,hn as wo,uc as wr,Lp as wt,Nh as x,ri as xa,Ra as xi,Eu as xn,cn as xo,Oc as xr,Ip as xt,Uh as y,Qr as ya,Ua as yi,z as yn,pn as yo,jc as yr,Mp as yt,Vm as z,or as za,Qi as zi,Bl as zn,rn as zo,ks as zr,Df as zt};