@needle-tools/engine 2.38.0-pre.1 → 2.38.0-pre.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -173,7 +173,7 @@ irradiance += 0.;
173
173
  irradiance += getLightProbeIrradiance( lightProbe, geometry.normal );
174
174
  #endif`);mn.UniformsLib.lightmap.lightmapScaleOffset={value:new mn.Vector4(1,1,0,0)};var Hm=I("debugplayerview");var yc=class{userId;context;viewDevice="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}},Ca=class{context;playerViews=new Map;constructor(e){this.context=e}setPlayerView(e,t,n){let i=this.playerViews.get(e);i||(i=new yc(e,this.context),this.playerViews.set(e,i)),i.viewDevice=n,i.currentObject=t,i.removed=!1}getPlayerView(e){if(!e)return;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&&(Hm&&console.log("REMOVE",e),n.removed=!0,this.playerViews.delete(e))}};var Vm=I("debugSetup"),zm=I("stats"),Ta={};var St=(a=>(a[a.EarlyUpdate=0]="EarlyUpdate",a[a.Update=1]="Update",a[a.LateUpdate=2]="LateUpdate",a[a.OnBeforeRender=3]="OnBeforeRender",a[a.OnAfterRender=4]="OnAfterRender",a[a.PrePhysicsStep=9]="PrePhysicsStep",a[a.PostPhysicsStep=10]="PostPhysicsStep",a))(St||{});function Js(o,e){if(!o)return;let t=e?.new_scripts??z.Current.new_scripts;t.includes(o)||t.push(o)}var lt=class{static get Current(){return this._current}static set Current(e){this._current=e}name;alias;isManagedExternally=!1;hash;domElement;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;get domWidth(){return this.domElement.clientWidth}get domHeight(){return this.domElement.clientHeight}get domX(){return this.domElement.offsetLeft}get domY(){return this.domElement.offsetTop}get isInXR(){return this.renderer.xr?.isPresenting||!1}xrSessionMode=void 0;get isInVR(){return this.xrSessionMode==="immersive-vr"}get isInAR(){return this.xrSessionMode==="immersive-ar"}get xrSession(){return this.renderer.xr?.getSession()}get arOverlayElement(){let e=this.domElement;return typeof e.getAROverlayContainer=="function"?e.getAROverlayContainer():this.domElement}scene;renderer;composer=null;scripts=[];scripts_earlyUpdate=[];scripts_update=[];scripts_lateUpdate=[];scripts_onBeforeRender=[];scripts_onAfterRender=[];scripts_WithCorroutines=[];coroutines={};get mainCamera(){if(this.mainCameraComponent){let e=this.mainCameraComponent;return e.cam||e.buildCamera(),e.cam}return null}mainCameraComponent;post_setup_callbacks=[];pre_update_callbacks=[];pre_render_callbacks=[];post_render_callbacks=[];new_scripts=[];new_script_start=[];new_scripts_pre_setup_callbacks=[];new_scripts_post_setup_callbacks=[];application;time;input;physics;connection;assets;mainLight=null;rendererData;addressables;lightmaps;players;_sizeChanged=!1;_isCreated=!1;_stats=zm?Lh.default():null;constructor(e){if(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;else{let n=I("postfx");this.renderer=new Bm({antialias:!0}),this.renderer.toneMappingExposure=1,this.renderer.toneMapping=Ee.NoToneMapping,this.renderer.setClearColor(new Ee.Color("lightgrey"),0),this.renderer.antialias=!0,this.renderer.alpha=!1,this.renderer.shadowMap.enabled=!0,this.renderer.shadowMap.type=Ee.PCFSoftShadowMap,this.renderer.setSize(this.domWidth,this.domHeight),this.renderer.outputEncoding=Ee.sRGBEncoding,this.renderer.physicallyCorrectLights=!0,this.composer=n?new Um(this.renderer):null}this.scene=new Ee.Scene,this.application=new Ea(this),this.time=new ia,this.input=new Bs(this),this.physics=new Ci(this),this.connection=new ua(this),this.assets=new ga,this.rendererData=new ya(this),this.addressables=new _a(this),this.lightmaps=new xa(this),this.players=new Ca(this),window.addEventListener("resize",()=>this._sizeChanged=!0),new ResizeObserver(n=>this._sizeChanged=!0).observe(this.domElement)}updateSize(){if(!this.isManagedExternally&&!this.renderer.xr.isPresenting){this._sizeChanged=!1;let e=this.resolutionScaleFactor,t=this.domWidth*e,n=this.domHeight*e,i=this.mainCamera;this.updateAspect(i),this.renderer.setSize(t,n),this.renderer.setPixelRatio(window.devicePixelRatio),this.renderer.domElement.style.width="100%",this.renderer.domElement.style.height="100%",this.composer&&(this.composer.setSize(t,n),this.composer.setPixelRatio(window.devicePixelRatio))}}updateAspect(e){if(!e)return;let t=this.domWidth,n=this.domHeight,i=e.aspect;e.aspect=t/n,i!==e.aspect&&e.updateProjectionMatrix()}onCreate(e,t){return this._isCreated?(console.warn("Context already created"),null):(this._isCreated=!0,this.internalOnCreate(e,t))}onDestroy(){!this._isCreated||(this._isCreated=!1,Ut(this.scene,!0),this.renderer?.setAnimationLoop(null),this.isManagedExternally||this.renderer?.dispose())}registerCoroutineUpdate(e,t,n){return this.coroutines[n]||(this.coroutines[n]=[]),this.coroutines[n].push({comp:e,main:t}),t}unregisterCoroutineUpdate(e,t){if(!this.coroutines[t])return;let n=this.coroutines[t].findIndex(i=>i.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 i=n.length-1;i>=0;i--)n[i].comp===e&&n.splice(i,1)}}_cameraStack=[];setCurrentCamera(e){if(!e)return;if(e.cam||e.buildCamera(),!e.cam){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.cam;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 n=this._cameraStack[this._cameraStack.length-1];this.setCurrentCamera(n)}}_onBeforeRenderListeners={};addBeforeRenderListener(e,t){if(!this._onBeforeRenderListeners[e.uuid]){this._onBeforeRenderListeners[e.uuid]=[];let n=(i,r,s,a,c,d)=>{let l=this._onBeforeRenderListeners[e.uuid];if(!!l)for(let u=0;u<l.length;u++){let h=l[u];h(i,r,s,a,c,d)}};e.onBeforeRender=n}this._onBeforeRenderListeners[e.uuid].push(t)}removeBeforeRenderListener(e,t){if(this._onBeforeRenderListeners[e.uuid]){let n=this._onBeforeRenderListeners[e.uuid],i=n.indexOf(t);i>=0&&n.splice(i,1)}}_requireDepthTexture=!1;_requireColorTexture=!1;_renderTarget;_isRendering=!1;get isRendering(){return this._isRendering}setRequireDepth(e){this._requireDepthTexture=e}setRequireColor(e){this._requireColorTexture=e}get depthTexture(){return this._renderTarget?.depthTexture||null}get opaqueColorTexture(){return this._renderTarget?.texture||null}async internalOnCreate(e,t){await this.physics.createWorld();let n=!0;try{lt.Current=this,e&&await e(this,t)}catch(i){console.error(i),n=!1}if(!!n){this.isManagedExternally||this.domElement.prepend(this.renderer.domElement),Bu(this),Fu(this),Ch(this),lt._current=this;for(let i=0;i<this.new_scripts.length;i++){let r=this.new_scripts[i];if(r.gameObject!==void 0&&r.gameObject!==null){r.gameObject.userData===void 0&&(r.gameObject.userData={}),r.gameObject.userData.components===void 0&&(r.gameObject.userData.components=[]);let s=r.gameObject.userData.components;s.includes(r)||s.push(r)}}if(this.post_setup_callbacks)for(let i=0;i<this.post_setup_callbacks.length;i++)lt._current=this,await this.post_setup_callbacks[i](this);if(!this.mainCamera){lt._current=this;let i=null;Gt(this.scene,r=>{let s=r;if(s?.isCamera){if(s.tag==="MainCamera")return i=s,!0;i=s}}),i?this.setCurrentCamera(i):console.error("MISSING camera",this)}if(lt._current=this,Jn(this),!this.isManagedExternally&&this.composer&&this.mainCamera){let i=new Gm(this.scene,this.mainCamera);this.renderer.setSize(this.domWidth,this.domHeight),this.composer.addPass(i),this.composer.setSize(this.domWidth,this.domHeight)}this._sizeChanged=!0,this._stats&&(this._stats.showPanel(1),this.domElement.appendChild(this._stats.dom)),this.renderer.setAnimationLoop(this.render.bind(this)),Vm&&Ko(this.scene,!0)}}render(e,t){for(this._stats?.begin(),lt._current=this,this.time.update(),Jn(this),oo(),Ns(this);this._cameraStack.length>0&&(!this.mainCameraComponent||this.mainCameraComponent.destroyed);){this._cameraStack.splice(this._cameraStack.length-1,1);let n=this._cameraStack[this._cameraStack.length-1];this.setCurrentCamera(n)}if(this.pre_update_callbacks)for(let n in this.pre_update_callbacks)this.pre_update_callbacks[n]();for(let n=0;n<this.scripts_earlyUpdate.length;n++){let i=this.scripts_earlyUpdate[n];!i.activeAndEnabled||i.earlyUpdate!==void 0&&(lt._current=this,i.earlyUpdate())}this.executeCoroutines(0);for(let n=0;n<this.scripts_update.length;n++){let i=this.scripts_update[n];!i.activeAndEnabled||i.update!==void 0&&(lt._current=this,i.update())}this.executeCoroutines(1);for(let n=0;n<this.scripts_lateUpdate.length;n++){let i=this.scripts_lateUpdate[n];!i.activeAndEnabled||i.lateUpdate!==void 0&&(lt._current=this,i.lateUpdate())}this.executeCoroutines(2);try{let i=this.time.deltaTime/1;for(let r=0;r<1;r++)this.executeCoroutines(9),this.physics.step(i),this.executeCoroutines(10)}catch(n){console.error(n)}this.physics.postStep();for(let n=0;n<this.scripts_onBeforeRender.length;n++){let i=this.scripts_onBeforeRender[n];!i.activeAndEnabled||i.onBeforeRender!==void 0&&(lt._current=this,i.onBeforeRender(t))}if(this.executeCoroutines(3),this._sizeChanged&&this.updateSize(),this.pre_render_callbacks)for(let n in this.pre_render_callbacks)this.pre_render_callbacks[n]();this._isRendering=!0,this.renderRequiredTextures(),this.isManagedExternally||(this.composer&&!this.isInXR?this.composer.render():this.mainCamera&&this.renderer.render(this.scene,this.mainCamera)),this._isRendering=!1;for(let n=0;n<this.scripts_onAfterRender.length;n++){let i=this.scripts_onAfterRender[n];!i.activeAndEnabled||i.onAfterRender!==void 0&&(lt._current=this,i.onAfterRender())}if(this.executeCoroutines(4),this.post_render_callbacks)for(let n in this.post_render_callbacks)this.post_render_callbacks[n]();this.connection.sendBufferedMessagesNow(),this._stats?.end()}renderRequiredTextures(){if(!this.mainCamera||!this._requireDepthTexture&&!this._requireColorTexture)return;if(!this._renderTarget){if(this._renderTarget=new Ee.WebGLRenderTarget(this.domWidth,this.domHeight),this._requireDepthTexture){let n=new Fm(this.domWidth,this.domHeight);this._renderTarget.depthTexture=n}this._requireColorTexture&&(this._renderTarget.texture=new Ee.Texture,this._renderTarget.texture.generateMipmaps=!1,this._renderTarget.texture.minFilter=Ee.NearestFilter,this._renderTarget.texture.magFilter=Ee.NearestFilter,this._renderTarget.texture.format=Ee.RGBAFormat)}let e=this._renderTarget;e.texture&&(e.texture.encoding=this.renderer.outputEncoding);let t=this.renderer.getRenderTarget();this.renderer.setRenderTarget(e),this.renderer.render(this.scene,this.mainCamera),this.renderer.setRenderTarget(t)}executeCoroutines(e){if(this.coroutines[e]){let n=this.coroutines[e];for(let i=0;i<n.length;i++){let r=n[i];if(!r.comp||r.comp.destroyed||!r.main||r.comp.enabled===!1){n.splice(i,1),--i;continue}let a=r.chained;if(a&&a.length>0){let u=a[a.length-1].next();if(u.done&&a.pop(),t(u)&&(r.chained||(r.chained=[]),r.chained.push(u.value)),!u.done)continue}let c=r.main.next();if(c.done===!0){n.splice(i,1),--i;continue}let d=c.value;if(t(d)){if(d.next().done)continue;r.chained||(r.chained=[]),r.chained.push(d)}}}function t(n){return!!(n&&n.next&&n.return)}}},z=lt;j(z,"_current");var _c={};uu(_c,{Behaviour:()=>O,Component:()=>ct,GameObject:()=>R});import*as Ge from"three";var R=class extends Ge.Object3D{guid;static setActive(e,t,n=!0,i=!0){!e||(ea(e,t,i),oo(e),t&&n&&Ns(z.Current,e))}static isActiveSelf(e){return dr(e)}static isActiveInHierarchy(e){return $u(e)}static markAsInstancedRendered(e,t){eh(e,t)}static isUsingInstancing(e){return ta(e)}static foreachComponent(e,t,n=!0){return Gt(e,t,n)}static instantiateSynced(e,t){return e?Qs(e,t):null}static instantiate(e,t=null){return hr(e,t)}static destroySynced(e,t,n=!0){if(!e)return;let i=e;t=t??z.Current,so(i,t.connection,n)}static destroy(e,t=!0,n=!0){return Ut(e,t,n)}static add(e,t,n){if(!(!e||!t)){if(e===t){console.warn("Can not add object to self",e);return}n||(n=z.Current),t.add(e),ea(e,!0),oo(e),n?R.foreachComponent(e,i=>{Gl(i,n),!i.__internalDidAwakeAndStart&&n.new_script_start.includes(i)===!1&&n.new_script_start.push(i)},!0):console.warn("Missing context")}}static remove(e){!e||(e.parent?.remove(e),ea(e,!1),oo(e),R.foreachComponent(e,t=>{Ou(t)},!0))}static invokeOnChildren(e,t,...n){this.invoke(e,t,!0,n)}static invoke(e,t,n=!1,...i){!e||this.foreachComponent(e,r=>{let s=r[t];s&&typeof s=="function"&&s.bind(r)(...i)},n)}static addNewComponent(e,t,n=!0){let i=new t;return xi(e,i,n),i}static addComponent(e,t){if(t.gameObject==null)throw new Error("Did you mean to create a new component? Use addNewComponent");Qu(e,t)}static removeComponent(e){return Ys(e.gameObject,e),e}static getOrAddComponent(e,t){return Ks(e,t)}static getComponent(e,t){return e===null?null:pr(e,t)}static getComponents(e,t,n=null){return e===null?n??[]:lo(e,t,n)}static findByGuid(e,t){return ur(e,t)}static findObjectOfType(e,t,n=!0){return Ku(e,t??z.Current,n)}static findObjectsOfType(e,t){let n=[];return Ju(e,n,t),n}static getComponentInChildren(e,t){return fr(e,t)}static getComponentsInChildren(e,t,n=null){return co(e,t,n??void 0)}static getComponentInParent(e,t){return ao(e,t)}static getComponentsInParent(e,t,n=null){return es(e,t,n)}static getAllComponents(e){return[...e.userData?.components]}static*iterateComponents(e){let t=e?.userData?.components;if(t&&Array.isArray(t))for(let n=0;n<t.length;n++)yield t[n]}},zt=class{get isComponent(){return!0}__context;get context(){return this.__context??z.Current}set context(e){this.__context=e}get scene(){return this.context.scene}get layer(){return this.gameObject?.userData?.layer}get name(){return this.gameObject?.userData.name}__name;set name(e){this.gameObject?(this.gameObject.userData||(this.gameObject.userData={}),this.gameObject.userData.name=e,this.__name=e):this.__name=e}get tag(){return this.gameObject?.userData.tag}set tag(e){this.gameObject&&(this.gameObject.userData.tag=e)}get static(){return this.gameObject?.userData.static}get hideFlags(){return this.gameObject?.userData.hideFlags}get activeAndEnabled(){return!(this.destroyed||this.__isEnabled===!1||!this.__isActiveInHierarchy)}get __isActive(){return this.gameObject.visible}get __isActiveInHierarchy(){if(!this.gameObject)return!1;let e=this.gameObject[un];return e===void 0?!0:e}set __isActiveInHierarchy(e){!this.gameObject||(this.gameObject[un]=e)}gameObject;guid="invalid";sourceId;awake(){}onEnable(){}onDisable(){}onDestroy(){this.__destroyed=!0}startCoroutine(e,t=1){return this.context.registerCoroutineUpdate(this,e,t)}stopCoroutine(e,t=1){this.context.unregisterCoroutineUpdate(e,t)}get destroyed(){return this.__destroyed}destroy(){this.__destroyed||this.__internalDestroy()}__didAwake=!1;__didStart=!1;__didEnable=!1;__isEnabled=void 0;__destroyed=!1;get __internalDidAwakeAndStart(){return this.__didAwake&&this.__didStart}constructor(){this.__internalNewInstanceCreated()}__internalNewInstanceCreated(){this.__didAwake=!1,this.__didStart=!1,this.__didEnable=!1,this.__isEnabled=void 0,this.__destroyed=!1}__internalAwake(){this.__didAwake||(this.__didAwake=!0,this.awake())}__internalStart(){this.__didStart||(this.__didStart=!0,this.start&&this.start())}__internalEnable(){return this.__didEnable?!1:(this.__didEnable=!0,this.onEnable(),this.__isEnabled=!0,!0)}__internalDisable(){!this.__didEnable||(this.__didEnable=!1,this.onDisable(),this.__isEnabled=!1)}__internalDestroy(){this.__destroyed||(this.__destroyed=!0,this.destroy?.call(this),qu(this))}get enabled(){return this.__isEnabled??!0}set enabled(e){if(typeof e=="number"&&(e>=.5?e=!0:e=!1),!this.__didAwake){this.__isEnabled=e;return}e?this.__internalEnable():this.__internalDisable()}_worldPosition=void 0;_worldQuaternion=void 0;_worldEuler=void 0;_worldRotation=void 0;get worldPosition(){return this._worldPosition||(this._worldPosition=new Ge.Vector3),B(this.gameObject,this._worldPosition),this._worldPosition}set worldPosition(e){J(this.gameObject,e)}setWorldPosition(e,t,n){zt._worldPositionBuffer.set(e,t,n),this.worldPosition=zt._worldPositionBuffer}get worldQuaternion(){return this._worldQuaternion||(this._worldQuaternion=new Ge.Quaternion),ge(this.gameObject,this._worldQuaternion)}set worldQuaternion(e){Ue(this.gameObject,e)}setWorldQuaternion(e,t,n,i){zt._worldQuaternionBuffer.set(e,t,n,i),this.worldQuaternion=zt._worldQuaternionBuffer}get worldEuler(){return this._worldEuler||(this._worldEuler=new Ge.Euler),this._worldEuler.setFromQuaternion(this.worldQuaternion),this._worldEuler}set worldEuler(e){this._worldQuaternion||(this._worldQuaternion=new Ge.Quaternion),this._worldQuaternion?.setFromEuler(e),this.worldQuaternion=this._worldQuaternion}get worldRotation(){let e=this.worldEuler;this._worldRotation||(this._worldRotation=new Ge.Vector3);let t=this._worldRotation;return t.set(e.x,e.y,e.z),t.x=U.toDegrees(t.x),t.y=U.toDegrees(t.y),t.z=U.toDegrees(t.z),t}set worldRotation(e){this.setWorldRotation(e.x,e.y,e.z,!0)}setWorldRotation(e,t,n,i=!0){i&&(e=U.toRadians(e),t=U.toRadians(t),n=U.toRadians(n)),zt._worldEulerBuffer.set(e,t,n),zt._worldQuaternionBuffer.setFromEuler(zt._worldEulerBuffer),this.worldQuaternion=zt._worldQuaternionBuffer}get forward(){return zt._forward.set(0,0,-1).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(!this._eventListeners[e.type])return!1;let t=this._eventListeners[e.type];for(let n=0;n<t.length;n++)t[n](e);return!1}},ct=zt;j(ct,"_worldPositionBuffer",new Ge.Vector3),j(ct,"_worldQuaternionBuffer",new Ge.Quaternion),j(ct,"_worldEulerBuffer",new Ge.Euler),j(ct,"_tempQuaternionBuffer2",new Ge.Quaternion),j(ct,"_forward",new Ge.Vector3);var O=class extends ct{};var Nm=I("debugloadingbar");function Ec(o){return o.index/o.count+o.progress.loaded/o.progress.total/o.count}var Ra=class{loadingProgress=0;container;_progress=0;_allowCustomLoadingElement=!1;_loadingElement;_loadingTextContainer=null;_loadingBar=null;_messageContainer=null;_loadingElementOptions;constructor(e,t){this.container=e,this._loadingElementOptions=t}onLoadingBegin(e){if(!this._loadingElement){for(let t=0;t<this.container.children.length;t++){let n=this.container.children[t];if(n.classList.contains("loading")){if(!this._allowCustomLoadingElement){console.warn("Custom loading container is not allowed"),this.container.removeChild(n);continue}this._loadingElement=this.createLoadingElement(n);return}}this._loadingElement=this.createLoadingElement()}this._progress=0,this.loadingProgress=0,this._loadingElement.style.display="flex",this.container.appendChild(this._loadingElement),this.smoothProgressLoop(),this.setMessage(e??"")}onLoadingUpdate(e,t){this._loadingElement?.parentElement||this.onLoadingBegin(t);let n=0;typeof e=="number"?n=e:("index"in e&&(n=Ec(e)),!t&&"name"in e&&this.setMessage(e.name)),this.loadingProgress=n,t&&this.setMessage(t),this.updateDisplay()}onLoadingFinished(e){this.loadingProgress=1,this.setMessage(e??"")}setMessage(e){this._messageContainer&&(this._messageContainer.innerText=e)}_progressLoop;smoothProgressLoop(){if(this._progressLoop)return;let e=1/12;Nm&&(e=.001);let t=1-.05;this._progressLoop=setInterval(()=>{if(this.loadingProgress>=1&&this._progress>=t){this._loadingElement&&(this._loadingElement.style.display="none",this._loadingElement.remove()),clearInterval(this._progressLoop),this._progressLoop=null;return}this._progress=U.lerp(this._progress,this.loadingProgress,e*this.loadingProgress),this.updateDisplay()},e)}updateDisplay(){let e=this._progress,t=(e*100).toFixed(0)+"%";this._loadingBar&&(this._loadingBar.style.width=e*100+"%"),this._loadingTextContainer&&(this._loadingTextContainer.textContent=t)}createLoadingElement(e){this._loadingElement=e||document.createElement("div"),e||(this._loadingElement.style.position="fixed",this._loadingElement.style.width="100%",this._loadingElement.style.height="100%",this._loadingElement.style.left="0",this._loadingElement.style.top="0",this._loadingElement.style.backgroundColor="#000000",this._loadingElement.style.display="flex",this._loadingElement.style.alignItems="center",this._loadingElement.style.justifyContent="center",this._loadingElement.style.zIndex="1000",this._loadingElement.style.flexDirection="column",this._loadingElement.style.pointerEvents="none",this._loadingElement.style.color="white");let t=this._loadingElementOptions?.className??"loading";if(this._loadingElement.classList.add(t),this._loadingElementOptions?.additionalClasses)for(let a of this._loadingElementOptions.additionalClasses)this._loadingElement.classList.add(a);let n=document.createElement("div"),i=30;n.style.display="flex",n.style.width=i+"%",n.style.height="2px",n.style.background="rgba(255,255,255,.1)",this._loadingElement.appendChild(n),this._loadingBar=document.createElement("div"),n.appendChild(this._loadingBar);let r=function(a){return U.lerp(i*.5,100-i*.5,a)+"%"};this._loadingBar.style.background=`linear-gradient(90deg, #02022B ${r(0)}, #0BA398 ${r(.4)}, #99CC33 ${r(.5)}, #D7DB0A ${r(1)})`,this._loadingBar.style.backgroundAttachment="fixed",this._loadingBar.style.width="0%",this._loadingBar.style.height="100%",this._loadingTextContainer=document.createElement("div"),this._loadingTextContainer.style.display="flex",this._loadingTextContainer.style.justifyContent="center",this._loadingTextContainer.style.marginTop=".9em",this._loadingElement.appendChild(this._loadingTextContainer);let s=document.createElement("div");return this._messageContainer=s,s.style.display="flex",s.style.fontSize=".8em",s.style.paddingTop=".5em",s.style.color="rgba(255,255,255,.5)",s.style.justifyContent="center",this._loadingElement.appendChild(s),this._loadingElement}};import{DRACOLoader as wc}from"three/examples/jsm/loaders/DRACOLoader.js";import{KTX2Loader as jh}from"three/examples/jsm/loaders/KTX2Loader.js";var as=I("debugdecoders"),Nt,Oi;function xc(o){o!==void 0&&typeof o=="string"&&(Nt||(Nt=new wc),as&&console.log("Setting draco decoder path to",o),Nt.setDecoderPath(o))}function Cc(o){o!==void 0&&typeof o=="string"&&(Nt||(Nt=new wc),as&&console.log("Setting draco decoder type to",o),Nt.setDecoderConfig({type:o}))}function Tc(o){o!==void 0&&typeof o=="string"&&(Oi||(Oi=new jh),as&&console.log("Setting ktx2 transcoder path to",o),Oi.setTranscoderPath(o))}function Zn(o,e){Nt||(Nt=new wc,Nt.setDecoderPath("./include/draco/"),Nt.setDecoderConfig({type:"js"}),as&&console.log("Setting draco decoder path to","./include/draco/")),Oi||(Oi=new jh,Oi.setTranscoderPath("./include/ktx2/"),as&&console.log("Setting ktx2 transcoder path to","./include/ktx2/"),e.renderer&&Oi.detectSupport(e.renderer)),o.setDRACOLoader(Nt),o.setKTX2Loader(Oi)}import{AnimationClip as Wm,MathUtils as Xm}from"three";var mo=class{_name;get name(){return this._name}_nameHash;get nameHash(){return this._nameHash}_normalizedTime;get normalizedTime(){return this._normalizedTime}_length;get length(){return this._length}_speed;get speed(){return this._speed}constructor(e,t,n,i){this._name=e.name,this._nameHash=e.hash,this._normalizedTime=t,this._length=n,this._speed=i}};function Fh(o,e){return{name:"",isLooping:!1,guid:e?.generateUUID()??Xm.generateUUID(),index:-1,clip:new Wm(o,1,[])}}import{AnimationClip as Qm,AnimationMixer as qm,AxesHelper as Ym,Euler as Bh,LoopOnce as Km,Quaternion as Wt,Vector3 as ls}from"three";import*as Pa from"three";var ki=I("debuganimatorcontroller"),Rc=I("debugrootmotion"),Pt=class{Play(e,t=-1,n=Number.NEGATIVE_INFINITY,i=0){if(t<0)t=0;else if(t>=this.model.layers.length){console.warn("invalid layer");return}let s=this.model.layers[t].stateMachine;for(let a of s.states)if(a.name===e||a.hash===e){ki&&console.log("transition to ",a),this.transitionTo(a,i,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(i=>i[n]===e).forEach(i=>i.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";return this.model?.parameters.filter(i=>i[n]===e).forEach(i=>i.value=t)}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(i=>i[n]===e).forEach(i=>i.value=t)}GetInteger(e){let t=typeof e=="string"?"name":"hash";return this.model?.parameters.find(n=>n[t]===e)?.value??0}SetTrigger(e){ki&&console.log("SET TRIGGER",e);let t=typeof e=="string"?"name":"hash";return this.model?.parameters.filter(n=>n[t]===e).forEach(n=>n.value=!0)}ResetTrigger(e){let t=typeof e=="string"?"name":"hash";return this.model?.parameters.filter(n=>n[t]===e).forEach(n=>n.value=!1)}IsInTransition(){return this._activeStates.length>1}SetSpeed(e){this._speed=e}FindState(e){if(!e)return null;for(let t of this.model.layers)for(let n of t.stateMachine.states)if(n.name===e)return n;return null}normalizedStartOffset=0;_speed=1;animator;model;get context(){return this.animator?.context}bind(e){this.animator=e,this._mixer=new qm(this.animator.gameObject),this.createActions(this.animator)}clone(){let e=Wo(this.model,(n,i,r)=>r==null?!0:!(r.type==="Object3D"||r.isObject3D===!0||r?.constructor?.name==="AnimationAction"||r.tracks!==void 0));return console.assert(e!==this.model),new Pt(e)}update(){if(!this.animator)return;this.evaluateTransitions(),this.updateActiveStates();let e=this.animator.context.time.deltaTime;this.animator.applyRootMotion&&this.rootMotionHandler?.onBeforeUpdate(),this._mixer.update(e),this.animator.applyRootMotion&&this.rootMotionHandler?.onAfterUpdate()}_mixer;_activeState;constructor(e){this.model=e,ki&&console.log(this)}_activeStates=[];updateActiveStates(){for(let e=0;e<this._activeStates.length;e++){let t=this._activeStates[e],n=t.motion;if(!n.action)this._activeStates.splice(e,1),e--;else{let i=n.action;i.getEffectiveWeight()<=0&&!i.isRunning()&&(ki&&console.debug("REMOVE",t.name,i.getEffectiveWeight(),i.isRunning(),i.isScheduled()),this._activeStates.splice(e,1),e--)}}}setStartTransition(){for(let e of this.model.layers){let t=e.stateMachine,n=t.states[t.defaultState];this.transitionTo(n,0,this.normalizedStartOffset)}}evaluateTransitions(){let t=!1;if(!this._activeState){if(this.setStartTransition(),!this._activeState)return;t=!0}let n=this._activeState,i=n.motion.action,r=0;for(let a of n.transitions){if(++r,!a.hasExitTime&&a.conditions.length<=0)continue;let c=!0;for(let d of a.conditions)if(!this.evaluateCondition(d)){c=!1;break}if(!!c){for(let d of a.conditions){let l=this.model.parameters.find(u=>u.name===d.parameter);l?.type===9&&(l.value=!1)}if(i){let d=n.motion.clip.duration,l=d<=0?1:i.time/d;if(a.hasExitTime?l>=a.exitTime:!0){i.clampWhenFinished=!0,ki&&console.log("transition to "+a.destinationState,a,l,a.exitTime,a.hasExitTime),this.transitionTo(a.destinationState,a.duration,a.offset);return}}else{this.transitionTo(a.destinationState,a.duration,a.offset);return}}}let s=!1;if(n.motion.isLooping&&i&&i.time>=i.getClip().duration&&(s=!0,i.reset(),i.time=0,i.play()),!s&&n&&!t&&i&&this.animator&&n.behaviours){let a=i?.getClip().duration,c=i.time/a,d=new mo(this._activeState,c,a,this._speed);for(let l of n.behaviours)l.instance&&l.instance.onStateUpdate?.call(l.instance,this.animator,d,0)}}getState(e,t){return typeof e=="number"&&(e==-1&&(e=this.model.layers[t].stateMachine.defaultState),e=this.model.layers[t].stateMachine.states[e]),e}transitionTo(e,t,n){if(!this.animator)return;let i=0;if(e=this.getState(e,i),!e?.motion||!e.motion.clip)return;let r=this._activeState===e;if(r){let d=e.motion;!d.action_loopback&&d.clip&&(this._mixer.uncacheAction(d.clip,this.animator.gameObject),d.action_loopback=this.createAction(d.clip))}if(this._activeState?.behaviours&&this._activeState.motion.action){let d=this._activeState?.motion.clip.duration,l=this._activeState.motion.action.time/d,u=new mo(this._activeState,l,d,this._speed);for(let h of this._activeState.behaviours)h.instance?.onStateExit?.call(h.instance,this.animator,u,i)}let s=this._activeState?.motion.action;s&&s.fadeOut(t),r&&(e.motion.action=e.motion.action_loopback,e.motion.action_loopback=s);let a=this._activeState;this._activeState=e;let c=e.motion?.action;if(c){n=Math.max(0,Math.min(1,n)),c.isRunning()&&c.stop(),c.reset(),c.timeScale=this._speed,c.enabled=!0;let d=e.motion.clip.duration;if(c.time=n*d,c.clampWhenFinished=!0,c.setLoop(Km,0),t>0?c.fadeIn(t):c.setEffectiveWeight(1),c.play(),this.rootMotionHandler&&this.rootMotionHandler.onStart(c),this._activeStates.includes(e)||this._activeStates.push(e),this._activeState.behaviours){let l=new mo(e,n,d,this._speed);for(let u of this._activeState.behaviours)u.instance?.onStateEnter?.call(u.instance,this.animator,l,i)}}else console.warn("No action",e.motion,this);ki&&console.log("TRANSITION FROM "+a?.name+" TO "+e.name,t,s,c,c?.getEffectiveTimeScale(),c?.getEffectiveWeight(),c?.isRunning(),c?.isScheduled(),c?.paused)}createAction(e){if(this._mixer.existingAction(e)&&this._mixer.uncacheAction(e,this.animator?.gameObject),this.animator?.applyRootMotion){this.rootMotionHandler||(this.rootMotionHandler=new Sc(this));let n=this.animator.gameObject;return this.rootMotionHandler.createClip(this._mixer,n,e)}else return this._mixer.clipAction(e)}evaluateCondition(e){let t=this.model.parameters.find(n=>n.name===e.parameter);if(!t)return!1;switch(e.mode){case 1:return t.value===!0;case 2:return t.value===!1;case 3:return t.value>e.threshold;case 4:return t.value<e.threshold;case 6:return t.value===e.threshold;case 7:return t.value!==e.threshold}return!1}createActions(e){for(let t of this.model.layers){let n=t.stateMachine;for(let i=0;i<n.states.length;i++){let r=n.states[i];if(r.motion||(r.motion=Fh(r.name)),this.animator&&r.motion.clips){let s=r.motion.clips?.find(a=>a.node.name===this.animator?.gameObject?.name);r.motion.clip=s?.clip}if(!r.motion.clip){let s=new Qm;r.motion.clip=s}if(r.motion?.clip){let s=r.motion.clip,a=this.createAction(s);r.motion.action=a}if(r.behaviours&&Array.isArray(r.behaviours))for(let s of r.behaviours){if(!s?.typeName)continue;let a=M.get(s.typeName),c=new a;c.isStateMachineBehaviour&&(c._context=this.context??void 0,Yn(c,s.properties),s.instance=c),ki&&console.log("Created animator controller behaviour",r.name,s.typeName,s.properties,c)}}}}*enumerateActions(){for(let e of this.model.layers){let t=e.stateMachine;for(let n=0;n<t.states.length;n++){let i=t.states[n];i?.motion&&(i.motion.action&&(yield i.motion.action),i.motion.action_loopback&&(yield i.motion.action_loopback))}}}rootMotionHandler},Sa=class{track;createdInterpolant;originalEvaluate;customEvaluate;constructor(e,t){this.track=e;let n=e,i=n.createInterpolant.bind(e);n.createInterpolant=()=>(n.createInterpolant=i,this.createdInterpolant=i(),this.originalEvaluate=this.createdInterpolant.evaluate.bind(this.createdInterpolant),this.customEvaluate=r=>{if(!this.originalEvaluate)return;let s=this.originalEvaluate(r);return t(r,s)},this.createdInterpolant.evaluate=this.customEvaluate,this.createdInterpolant)}evaluate(e){this.customEvaluate&&this.customEvaluate(e)}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}},be=class{set action(e){this._action=e}get action(){return this._action}_action;root;clip;positionWrapper=null;rotationWrapper=null;context;positionChange=new ls;rotationChange=new Wt;constructor(e,t,n,i,r){if(this.context=e,this.root=t,this.clip=n,be.firstKeyframeRotation[n.uuid]||(be.firstKeyframeRotation[n.uuid]=new Pa.Quaternion),r){let s=r.values;be.firstKeyframeRotation[n.uuid].set(s[0],s[1],s[2],s[3])}be.spaceRotation[n.uuid]||(be.spaceRotation[n.uuid]=new Wt),be.effectiveSpaceRotation[n.uuid]||(be.effectiveSpaceRotation[n.uuid]=new Wt),be.clipOffsetRotation[n.uuid]=new Wt,r&&be.clipOffsetRotation[n.uuid].set(r.values[0],r.values[1],r.values[2],r.values[3]).invert(),this.handlePosition(n,i),this.handleRotation(n,r)}onStart(e){if(e.getClip()!==this.clip)return;let t=be.lastObjRotation[this.root.uuid];be.spaceRotation[this.clip.uuid].copy(t);{let n=new Pa.Euler().setFromQuaternion(t);console.log("START",this.clip.name,U.toDegrees(n.y))}}getClipRotationOffset(){return be.clipOffsetRotation[this.clip.uuid]}handlePosition(e,t){if(t){let n=this.root;Rc&&n.add(new Ym),be.lastObjPosition[n.uuid]||(be.lastObjPosition[n.uuid]=new ls);let i=new ls,r=new ls,s=0;this.positionWrapper=new Sa(t,(a,c)=>{let d=this.action.getEffectiveWeight();if(Rc&&n.position.length()>8&&n.position.set(0,n.position.y,0),a>s){i.set(c[0],c[1],c[2]),i.sub(r),i.multiplyScalar(d),i.applyQuaternion(this.getClipRotationOffset());let l=this.clip.uuid;i.applyQuaternion(be.spaceRotation[l]),this.positionChange.copy(i)}return r.fromArray(c),s=a,c[0]=0,c[1]=0,c[2]=0,c})}}handleRotation(e,t){if(t){if(Rc){let a=t.values,c=new Bh().setFromQuaternion(new Wt(a[0],a[1],a[2],a[3]));console.log(e.name,t.name,"FIRST ROTATION IN TRACK",U.toDegrees(c.y));let d=t.values.length-4,l=new Wt().set(a[d],a[d+1],a[d+2],a[d+3]),u=new Bh().setFromQuaternion(l);console.log(e.name,t.name,"LAST ROTATION IN TRACK",U.toDegrees(u.y))}let n=this.root;be.lastObjRotation[n.uuid]||(be.lastObjRotation[n.uuid]=new Wt);let i=0,r=new Wt,s=new Wt;this.rotationWrapper=new Sa(t,(a,c)=>(a>i&&(s.set(c[0],c[1],c[2],c[3]),r.invert(),s.multiply(r),this.rotationChange.copy(s)),r.fromArray(c),i=a,c[0]=0,c[1]=0,c[2]=0,c[3]=1,c))}}onBeforeUpdate(){this.positionChange.set(0,0,0),this.rotationChange.set(0,0,0,1)}onAfterUpdate(){let e=this.action.getEffectiveWeight();this.positionChange.multiplyScalar(e),this.rotationChange.slerp(be.identityQuaternion,1-e)}},Xt=be;j(Xt,"lastObjPosition",{}),j(Xt,"lastObjRotation",{}),j(Xt,"firstKeyframeRotation",{}),j(Xt,"spaceRotation",{}),j(Xt,"effectiveSpaceRotation",{}),j(Xt,"clipOffsetRotation",{}),j(Xt,"identityQuaternion",new Wt);var Sc=class{controller;handler=[];root;constructor(e){this.controller=e}createClip(e,t,n){this.root=t;let i="";t&&"name"in t&&(i=t.name);let r=this.findRootTrack(n,".position"),s=this.findRootTrack(n,".quaternion"),a=new Xt(this.controller.context,t,n,r,s);this.handler.push(a);let c=e.clipAction(n);return a.action=c,c}onStart(e){for(let t of this.handler)t.onStart(e)}onBeforeUpdate(){for(let e of this.handler)e.onBeforeUpdate()}summedPosition=new ls;summedRotation=new Wt;onAfterUpdate(){this.summedPosition.set(0,0,0),this.summedRotation.set(0,0,0,1);for(let e of this.handler)e.onAfterUpdate(),this.summedPosition.add(e.positionChange),this.summedRotation.multiply(e.rotationChange);this.root.position.add(this.summedPosition),this.root.quaternion.multiply(this.summedRotation),Xt.lastObjRotation[this.root.uuid].copy(this.root.quaternion)}findRootTrack(e,t){let n=e.tracks;for(let i of n)if(i.name.endsWith(t))return i;return null}};var w=function(o){if(o===void 0&&(o=null),!Array.isArray(o))o=Uh(o);else for(let e=0;e<o.length;e++){let t=o[e];o[e]=Uh(t)}return function(e,t){Object.getOwnPropertyDescriptor(e,"$serializedTypes")||(e.$serializedTypes={});let n=e.$serializedTypes=e.$serializedTypes||{};n[t]=o}};function Uh(o){switch(o?.prototype?.constructor?.name){case"Number":case"String":case"Boolean":return null}return o}var Jm=I("debuganimator"),He=class extends O{applyRootMotion=!1;hasRootMotion=!1;keepAnimatorControllerStateOnDisable=!1;set runtimeAnimatorController(e){this._animatorController&&this._animatorController.model===e||(e?e instanceof Pt?this._animatorController=e:this._animatorController=new Pt(e):this._animatorController=null)}get runtimeAnimatorController(){return this._animatorController}Play(e,t=-1,n=Number.NEGATIVE_INFINITY,i=0){this.runtimeAnimatorController?.Play(e,t,n,i)}Reset(){this._animatorController?.Reset()}SetBool(e,t){this.runtimeAnimatorController?.SetBool(e,t)}GetBool(e){return this.runtimeAnimatorController?.GetBool(e)??!1}SetFloat(e,t){this.runtimeAnimatorController?.SetFloat(e,t)}GetFloat(e){return this.runtimeAnimatorController?.GetFloat(e)??-1}SetInteger(e,t){this.runtimeAnimatorController?.SetInteger(e,t)}GetInteger(e){return this.runtimeAnimatorController?.GetInteger(e)??-1}SetTrigger(e){this.runtimeAnimatorController?.SetTrigger(e)}ResetTrigger(e){this.runtimeAnimatorController?.ResetTrigger(e)}IsInTransition(){return this.runtimeAnimatorController?.IsInTransition()??!1}SetSpeed(e){e!==this.speed&&(this.speed=e,this._animatorController?.SetSpeed(e))}set minMaxSpeed(e){this.speed=U.lerp(e.x,e.y,Math.random())}set minMaxOffsetNormalized(e){this.normalizedStartOffset=U.lerp(e.x,e.y,Math.random()),this.runtimeAnimatorController&&(this.runtimeAnimatorController.normalizedStartOffset=this.normalizedStartOffset)}speed=1;normalizedStartOffset=0;_animatorController=null;awake(){if(!!this.gameObject){if(this.runtimeAnimatorController){let e=this.runtimeAnimatorController.clone();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}Jm&&console.log("ANIMATOR",this.name,this)}}onDisable(){this.keepAnimatorControllerStateOnDisable||this._animatorController?.Reset()}onBeforeRender(){this._animatorController&&this._animatorController.update()}};x([w()],He.prototype,"applyRootMotion",2),x([w()],He.prototype,"hasRootMotion",2),x([w()],He.prototype,"keepAnimatorControllerStateOnDisable",2),x([w()],He.prototype,"runtimeAnimatorController",1);import*as go from"three";var gn=class extends O{playAutomatically=!0;randomStartTime=!0;minMaxSpeed;minMaxOffsetNormalized;_tempAnimationClipBeforeGameObjectExisted=null;get clip(){return this.animations?.length?this.animations[0]:null}set clip(e){if(!this.gameObject){this._tempAnimationClipBeforeGameObjectExisted=e;return}!e||(this.gameObject.animations||(this.gameObject.animations=[]),this.gameObject.animations.push(e))}set animations(e){this.gameObject.animations=e}get animations(){return this.gameObject.animations}get currentAction(){return this._currentActions[0]}get currentActions(){return this._currentActions}mixer=void 0;get actions(){return this._actions}set actions(e){this._actions=e}_actions=[];_currentActions=[];_handles=[];awake(){this._tempAnimationClipBeforeGameObjectExisted&&(this.clip=this._tempAnimationClipBeforeGameObjectExisted,this._tempAnimationClipBeforeGameObjectExisted=null),this.playAutomatically&&this.init()}onEnable(){if(this.playAutomatically&&this.actions.length>0&&this.currentActions.length<=0){let e=Math.floor(Math.random()*this.actions.length);this.play(e)}}start(){this.randomStartTime&&this.currentAction&&(this.currentAction.time=Math.random()*this.currentAction.getClip().duration)}update(){if(!!this.mixer){this.mixer.update(this.context.time.deltaTime);for(let e of this._handles)e._update();this._handles?.length>0&&ne.markDirty(this.gameObject)}}getAction(e){return this.actions?.find(t=>t.getClip().name===e)}get isPlaying(){for(let e=0;e<this._currentActions.length;e++)if(this._currentActions[e].isRunning())return!0;return!1}play(e,t){if(this.init(),!this.mixer)return;let n=e;if(typeof e=="number"){if(e>=this.animations.length)return;n=this.animations[e]}else typeof e=="string"&&(n=this.animations.find(r=>r.name===e));if(!n){console.error("Could not find clip",e);return}t||(t={}),t.minMaxOffsetNormalized||(t.minMaxOffsetNormalized=this.minMaxOffsetNormalized),t.minMaxSpeed||(t.minMaxSpeed=this.minMaxSpeed);for(let r of this.actions)if(r.getClip()===n)return this.internalOnPlay(r,t);let i=this.mixer.clipAction(n);return this.actions.push(i),this.internalOnPlay(i,t)}internalOnPlay(e,t){var n=this.currentAction;if(n===e&&n.isRunning()&&n.time<n.getClip().duration){let a=this.tryFindHandle(e);if(a)return a.getPromise()}let i=t?.exclusive??!0;t?.fadeDuration?(i&&n?.fadeOut(t.fadeDuration),e.fadeIn(t.fadeDuration)):i&&n?.stop(),e.reset(),e.enabled=!0,e.time=0,e.timeScale=1;let r=e.getClip();t?.minMaxOffsetNormalized&&(e.time=U.lerp(t.minMaxOffsetNormalized.x,t.minMaxOffsetNormalized.y,Math.random())*r.duration),t?.minMaxSpeed&&(e.timeScale=U.lerp(t.minMaxSpeed.x,t.minMaxSpeed.y,Math.random())),t?.clampWhenFinished&&(e.clampWhenFinished=!0),t?.startTime!==void 0&&(e.time=t.startTime),t?.loop!==void 0&&(e.loop=t.loop?go.LoopRepeat:go.LoopOnce),e.play();let s=new Pc(e,this.mixer,t,a=>{this._handles.splice(this._handles.indexOf(s),1)});return this._handles.push(s),s.getPromise()}tryFindHandle(e){for(let t of this._handles)if(t.action===e)return t}_didInit=!1;init(){if(!this._didInit&&(this._didInit=!0,!!this.gameObject)){this.actions=[],this.mixer=new go.AnimationMixer(this.gameObject);for(let e=0;e<this.animations.length;e++){let t=this.mixer.clipAction(this.animations[e]);this.actions.push(t)}}}};x([w()],gn.prototype,"playAutomatically",2),x([w()],gn.prototype,"randomStartTime",2);var Pc=class{mixer;action;promise=null;resolve=null;reject=null;_options;_resolveCallback=null;_rejectCallback=null;_loopCallback;_finishedCallback;_resolvedOrRejectedCallback;constructor(e,t,n,i){this.action=e,this.mixer=t,this._resolvedOrRejectedCallback=i,this._options=n}getPromise(){return this.promise?this.promise:(this.promise=new Promise((e,t)=>{this._resolveCallback=e,this._rejectCallback=t,this.resolve=this.onResolve.bind(this),this.reject=this.onReject.bind(this)}),this._loopCallback=this.onLoop.bind(this),this._finishedCallback=this.onFinished.bind(this),this.mixer.addEventListener("loop",this._loopCallback),this.mixer.addEventListener("finished",this._finishedCallback),this.promise)}_update(){!this._options||this._options.endTime!==void 0&&this.action.time>this._options.endTime&&(this._options.loop===!0?this.action.time=this._options.startTime??0:(this.action.time=this._options.endTime,this.action.timeScale=0,this.onResolve()))}onResolve(){this.dispose(),this._resolvedOrRejectedCallback?.call(this,this),this._resolveCallback?.call(this,this.action)}onReject(e){this.dispose(),this._resolvedOrRejectedCallback?.call(this,this),this._rejectCallback?.call(this,e)}onLoop(e){}onFinished(e){e.action===this.action&&this.onResolve()}dispose(){this._loopCallback&&this.mixer.removeEventListener("loop",this._loopCallback),this._finishedCallback&&this.mixer.removeEventListener("finished",this._finishedCallback),this._loopCallback=void 0,this._finishedCallback=void 0}};import{GLTFLoader as Jp}from"three/examples/jsm/loaders/GLTFLoader.js";import*as oe from"three";import{RawShaderMaterial as $m}from"three";var $n=I("debugshaders"),bo="NEEDLE_techniques_webgl";var Oc=class{objectToWorldMatrix=new oe.Matrix4;worldToObjectMatrix=new oe.Matrix4;objectToWorld=new Array;worldToObject=new Array;updateFrom(e){this.objectToWorldMatrix.copy(e.matrixWorld),os(this.objectToWorldMatrix,this.objectToWorld),this.worldToObjectMatrix.copy(e.matrixWorld).invert(),os(this.worldToObjectMatrix,this.worldToObject)}};var re=class extends $m{identifier;onBeforeRenderSceneCallback=this.onBeforeRenderScene.bind(this);clone(){let e=super.clone();return Gh(e),e}constructor(e,...t){super(...t),this.identifier=e,$n&&console.log(this),this.type="NEEDLE_CUSTOM_SHADER",this.uniforms[this._objToWorldName]||(this.uniforms[this._objToWorldName]={value:[]}),this.uniforms[this._worldToObjectName]||(this.uniforms[this._worldToObjectName]={value:[]}),this.uniforms[this._viewProjectionName]||(this.uniforms[this._viewProjectionName]={value:[]}),this.uniforms[this._sphericalHarmonicsName]&&this.waitForLighting(),(this.depthTextureUniform||this.opaqueTextureUniform)&&z.Current.pre_render_callbacks.push(this.onBeforeRenderSceneCallback)}dispose(){super.dispose();let e=z.Current.pre_render_callbacks.indexOf(this.onBeforeRenderSceneCallback);e>=0&&z.Current.pre_render_callbacks.splice(e,1)}async waitForLighting(){let e=z.Current;if(!e){console.error("Missing context");return}let t=await e.rendererData.getSceneLightingData(this.identifier);if(!t||!t.array){console.warn("Missing lighting data for custom shader, getSceneLightingData did not return anything");return}$n&&console.log(t);let n=t.array,i=t.texture;this.uniforms.unity_SpecCube0={value:i},fc(this.uniforms,n);let r=Math.sqrt(Math.PI*.5);this.uniforms.unity_SpecCube0_HDR={value:new oe.Vector4(r,r,r,r)},$n&&console.log("Set environment lighting",this.uniforms)}_sphericalHarmonicsName="unity_SpecCube0";_objToWorldName="hlslcc_mtx4x4unity_ObjectToWorld";_worldToObjectName="hlslcc_mtx4x4unity_WorldToObject";_viewProjectionName="hlslcc_mtx4x4unity_MatrixVP";_viewMatrixName="hlslcc_mtx4x4unity_MatrixV";_rendererData=new Oc;get depthTextureUniform(){if(!!this.uniforms)return this.uniforms._CameraDepthTexture}get opaqueTextureUniform(){if(!!this.uniforms)return this.uniforms._CameraOpaqueTexture}onBeforeRenderScene(){this.opaqueTextureUniform&&z.Current.setRequireColor(!0),this.depthTextureUniform&&z.Current.setRequireDepth(!0)}onBeforeRender(e,t,n,i,r,s){i.attributes.tangent||i.computeTangents(),this.onUpdateUniforms(n,r)}onUpdateUniforms(e,t){let n=z.Current;e&&(re.viewProjection&&this.uniforms[this._viewProjectionName]&&(re.viewProjection.copy(e.projectionMatrix).multiply(e.matrixWorldInverse),os(re.viewProjection,re._viewProjectionValues)),re.viewMatrix&&this.uniforms[this._viewMatrixName]&&(re.viewMatrix.copy(e.matrixWorldInverse),os(re.viewMatrix,re._viewMatrixValues)),this.uniforms[re._worldSpaceCameraPosName]&&re._worldSpaceCameraPos.setFromMatrixPosition(e.matrixWorld)),this.uniforms._TimeParameters?this.uniforms._TimeParameters.value=n.rendererData.timeVec4:this.uniforms._Time&&(this.uniforms._Time.value=n.rendererData.timeVec4);let i=n.mainLight;if(i){let a=B(i.gameObject,re._mainLightPosition);this.uniforms._MainLightPosition={value:a.normalize()},re._mainLightColor.set(i.color.r,i.color.g,i.color.b,0),this.uniforms._MainLightColor={value:re._mainLightColor};let c=i.intensity;re._lightData.z=c,this.uniforms.unity_LightData={value:re._lightData}}if(e&&(re.viewProjection&&this.uniforms[this._viewProjectionName]&&(this.uniforms[this._viewProjectionName].value=re._viewProjectionValues),re.viewMatrix&&this.uniforms[this._viewMatrixName]&&(this.uniforms[this._viewMatrixName].value=re._viewMatrixValues),this.uniforms[re._worldSpaceCameraPosName]&&(this.uniforms[re._worldSpaceCameraPosName]={value:re._worldSpaceCameraPos}),n.mainCameraComponent)){if(this.uniforms._ProjectionParams){let a=this.uniforms._ProjectionParams.value;a.x=1,a.y=n.mainCameraComponent.nearClipPlane,a.z=n.mainCameraComponent.farClipPlane,a.w=1/a.z,this.uniforms._ProjectionParams.value=a}if(this.uniforms._ZBufferParams){let a=this.uniforms._ZBufferParams.value,c=n.mainCameraComponent;a.x=1-c.farClipPlane/c.nearClipPlane,a.y=c.farClipPlane/c.nearClipPlane,a.z=a.x/c.farClipPlane,a.w=a.y/c.farClipPlane,this.uniforms._ZBufferParams.value=a}if(this.uniforms._ScreenParams){let a=this.uniforms._ScreenParams.value;a.x=n.domWidth,a.y=n.domHeight,a.z=1+1/a.x,a.w=1+1/a.y,this.uniforms._ScreenParams.value=a}}let r=this.depthTextureUniform;r&&(r.value=n.depthTexture);let s=this.opaqueTextureUniform;if(s&&(s.value=n.opaqueColorTexture),t){let a=this._rendererData;a.updateFrom(t),this.uniforms[this._worldToObjectName].value=a.worldToObject,this.uniforms[this._objToWorldName].value=a.objectToWorld}this.uniformsNeedUpdate=!0}},Ot=re;j(Ot,"viewProjection",new oe.Matrix4),j(Ot,"_viewProjectionValues",[]),j(Ot,"viewMatrix",new oe.Matrix4),j(Ot,"_viewMatrixValues",[]),j(Ot,"_worldSpaceCameraPosName","_WorldSpaceCameraPos"),j(Ot,"_worldSpaceCameraPos",new oe.Vector3),j(Ot,"_mainLightColor",new oe.Vector4),j(Ot,"_mainLightPosition",new oe.Vector3),j(Ot,"_lightData",new oe.Vector4);var Oa=class{get name(){return bo}parser;identifier;constructor(e,t){this.parser=e,this.identifier=t}loadMaterial(e){let t=this.parser.json.materials[e];if(!t)return $n&&console.log(e,this.parser.json.materials),null;if(!t.extensions||!t.extensions[bo])return $n&&console.log("material "+e+" does not use NEEDLE_techniques_webgl"),null;let n=t.extensions[bo].technique;if(n<0)return null;let i=this.parser.json.extensions[bo];if(!i)return null;$n&&console.log(i);let r=i.techniques[n];return r?new Promise(async(s,a)=>{let c=await Mh(i,r.program),d=c?.fragmentShader,l=c?.vertexShader;if(!d||!l)return a();$n&&console.log("loadMaterial",t,c);let u={},h=r.uniforms;l.includes("_Time")&&(u._Time={value:new oe.Vector4(0,0,0,0)});for(let y in h){let m=y;switch(m){case"_TimeParameters":let f=new oe.Vector4;u[m]={value:f};break;case"hlslcc_mtx4x4unity_MatrixV":case"hlslcc_mtx4x4unity_MatrixVP":u[m]={value:[]};break;case"_MainLightPosition":case"_MainLightColor":case"_WorldSpaceCameraPos":u[m]={value:[0,0,0,1]};break;case"unity_OrthoParams":break;case"unity_SpecCube0":u[m]={value:null};break;default:case"_ScreenParams":case"_ZBufferParams":case"_ProjectionParams":u[m]={value:[0,0,0,0]};break;case"_CameraOpaqueTexture":case"_CameraDepthTexture":u[m]={value:null};break}}let b=!1;if(t.extensions&&t.extensions[bo]){let y=t.extensions[bo];if(y.technique===n){$n&&console.log(t.name,"Material Properties",y);for(let m in y.values){let f=y.values[m];if(typeof f=="string"){if(f.startsWith("/textures/")){let p=f.substring(10),g=Number.parseInt(p);if(g>=0){let E=await this.parser.getDependency("texture",g);E&&(E.encoding=oe.LinearEncoding,E.needsUpdate=!0),u[m]={value:E};continue}}switch(m){case"alphaMode":f==="BLEND"&&(b=!0);continue}}if(Array.isArray(f)&&f.length===4){u[m]={value:new oe.Vector4(f[0],f[1],f[2],f[3])};continue}u[m]={value:f}}}}let _=new Ot(this.identifier,{name:t.name??"",uniforms:u,vertexShader:l,fragmentShader:d,lights:!1});switch(u._Cull?.value){case 0:_.side=oe.DoubleSide;break;case 1:_.side=oe.BackSide;break;case 2:_.side=oe.FrontSide;break;default:_.side=oe.FrontSide;break}_.transparent=b,b&&(_.depthWrite=!1),fc(u),_.onUpdateUniforms();for(let y in h){let m=y,f=h[y].type;if(u[m]?.value===void 0)switch(f){case 35678:u[m]={value:Oh},console.warn("Missing/unassigned texture, fallback to white: "+m);break;default:console.warn("TODO: EXPECTED UNIFORM / fallback NOT SET: "+m,h[y]);break}}$n&&console.log(_.uuid,u),Gh(_),s(_)}):null}};function Gh(o){if(o.uniforms)for(let e in o.uniforms)Object.getOwnPropertyDescriptor(o,e)||Object.defineProperty(o,e,{get:()=>o.uniforms[e].value,set:t=>{o.uniforms[e].value=t,o.needsUpdate=!0}})}var Ii=_e,ka="$___Export_Components",eg="NEEDLE_components",kc=class{[cr]},Ic=class{node;nodeIndex;nodeDef;constructor(e,t,n){this.node=e,this.nodeIndex=t,this.nodeDef=n}},vo=class{get name(){return eg}parser;nodeToObjectMap={};exportContext;objectToNodeMap={};context;writer;registerExport(e){e.register(t=>{let n=t.serializeUserData.bind(t);return this.writer=t,t.serializeUserData=(i,r)=>{try{this.serializeUserData(i,r),n(i,r)}finally{this.afterSerializeUserData(i,r)}},this})}beforeParse(){this.exportContext={},this.objectToNodeMap={}}serializeUserData(e,t){let n=e.userData?.components;!n||n.length<=0||(delete e.userData.components,e[ka]=n)}afterSerializeUserData(e,t){if(e.type==="Scene"&&Ii&&console.log("DONE",JSON.stringify(t)),e[ka]===void 0)return;let n=e[ka];delete e[ka],n!==null&&(e.userData.components=n)}writeNode(e,t){let n=this.writer.json.nodes.length;console.log(e.name,n,e.uuid);let i=new Ic(e,n,t);this.exportContext[n]=i,this.objectToNodeMap[e.uuid]=n}afterParse(e){Ii&&console.log("AFTER",e);for(let t in this.exportContext){let n=this.exportContext[t],i=n.node,r=n.nodeDef,s=n.nodeIndex,a=i.userData?.components;if(!a||a.length<=0)continue;let c=new kc;r.extensions=r.extensions||{},r.extensions[this.name]=c,this.context.object=i,this.context.nodeId=s,this.context.objectToNode=this.objectToNodeMap;let d=[];for(let l of a){this.context.target=l;let u=Le().writeBuiltinComponentData(l,this.context);u!==null&&d.push(u)}d.length>0&&(c[cr]=d,Ii&&console.log("DID WRITE",i,"nodeIndex",s,d))}}beforeRoot(){return Ii&&console.log("BEGIN LOAD"),this.nodeToObjectMap={},null}async afterRoot(e){let t=e.parser,n=t?.extensions;if(!n)return;let i=n[this.name];Ii&&console.log("After root",e,this.parser,n);let r=[];if(i===!0){let s=t.json.nodes;for(let a=0;a<s.length;a++){let c=await t.getDependency("node",a);this.nodeToObjectMap[a]=c}for(let a=0;a<s.length;a++){let c=s[a],d=a,l=c.extensions;if(!l)continue;let u=l[this.name];if(!u)continue;Ii&&console.log("NODE",c);let h=this.nodeToObjectMap[d];if(!h){console.error("Could not find object for node index: "+d,c,t);continue}uo(h),r.push(this.createComponents(h,u))}}await Promise.all(r)}async createComponents(e,t){if(!t)return;let n=t[cr];if(n){Ii&&console.log(e.name,n);for(let i in n){let r=n[i];Ii&&console.log("Serialized data",JSON.parse(JSON.stringify(r))),r&&this.parser&&await no(this.parser,r),e.userData=e.userData||{},e.userData[cr]=e.userData[cr]||[],e.userData[cr].push(r)}}}};import{EXRLoader as tg}from"three/examples/jsm/loaders/EXRLoader";var Mc=I("debugexr"),Ia=class{constructor(e){this.parser=e,this.name="EXT_texture_exr",Mc&&console.log(e)}loadTexture(e){let t=this.name,n=this.parser,r=n.json.textures[e];if(Mc&&console.log("EXT_texture_exr.loadTexture",e,r),!r.extensions||!r.extensions[t])return null;let s=r.extensions[t],a=new tg(n.options.manager);return Mc&&console.log("EXT_texture_exr.loadTexture",s,a),n.loadTextureImage(e,s.source,a)}};var Vh="NEEDLE_gameobject_data",Ma=class{get name(){return Vh}parser;constructor(e){this.parser=e}afterRoot(e){let t=[];for(let n=0;n<this.parser.json.nodes.length;n++){let i=this.parser.json.nodes[n];if(i&&i.extensions){let r=i.extensions[Vh];if(r){let s=this.findAndApplyExtensionData(n,r);t.push(s)}}}return Promise.all(t).then(()=>{})}async findAndApplyExtensionData(e,t){let n=await this.parser.getDependency("node",e);n&&this.applyExtensionData(n,t)}applyExtensionData(e,t){e.userData.layer=t.layers,e.layers.disableAll(),e.layers.set(t.layers),e.userData.tag=t.tag,e.userData.hideFlags=t.hideFlags,e.userData.static=t.static,e.visible=t.activeSelf,e.guid=t.guid}};import{AmbientLight as ng,Color as zh,HemisphereLight as ig}from"three";var Nh="NEEDLE_lighting_settings",yo=I("debugenvlight"),Da=class{get name(){return Nh}parser;sourceId;context;constructor(e,t,n){this.parser=e,this.sourceId=t,this.context=n}afterRoot(e){let t=this.parser.json.extensions;if(t){let n=t[Nh];if(n){yo&&console.log(n);let i=R.addNewComponent(e.scene,Dc,!1);i.sourceId=this.sourceId,i.ambientIntensity=n.ambientIntensity,i.ambientLight=new zh().fromArray(n.ambientLight),Array.isArray(n.ambientTrilight)&&(i.ambientTrilight=n.ambientTrilight.map(r=>new zh().fromArray(r))),i.ambientMode=n.ambientMode,i.environmentReflectionSource=n.environmentReflectionSource,this.context&&this.context.rendererData.registerSceneLightSettings(i)}}return null}},Dc=class extends O{ambientMode=0;ambientLight;ambientTrilight;ambientIntensity=1;environmentReflectionSource=0;_hasReflection=!1;_ambientLightObj;_lightProbeObj;awake(){if(this.sourceId){let e=this.environmentReflectionSource===0?1:2,t=this.context.lightmaps.tryGet(this.sourceId,e,0);this._hasReflection=t!=null,t&&this.context.rendererData.registerReflection(this.sourceId,t)}yo&&window.addEventListener("keydown",e=>{switch(e.key){case"l":this.enabled=!this.enabled;break}})}onEnable(){let e=this.context.mainCameraComponent?.sourceId===this.sourceId;if(yo&&console.log("Enable scene lighting",this.sourceId,e,this,this.context.mainCameraComponent?.sourceId),e||yo&&console.warn("This is no active?!",this.context.mainCameraComponent?.sourceId),this.ambientMode==3)this.ambientLight&&!this._ambientLightObj&&(this._ambientLightObj=new ng(this.ambientLight,Math.PI*this.ambientIntensity)),this._ambientLightObj&&this.gameObject.add(this._ambientLightObj),this._lightProbeObj&&this._lightProbeObj.removeFromParent();else if(this.ambientMode===1){if(this.ambientTrilight){let t=this.ambientTrilight[0],n=this.ambientTrilight[this.ambientTrilight.length-1],i=new ig(n,t,this.ambientIntensity);this.gameObject.add(i)}}else this._ambientLightObj&&this._ambientLightObj.removeFromParent(),this._lightProbeObj?this.enabled&&this.destroyed&&this._lightProbeObj&&this.scene.add(this._lightProbeObj):this.sourceId&&this.context.rendererData.getSceneLightingData(this.sourceId).then(t=>{yo&&console.log(t),t&&(this._lightProbeObj=t.lightProbe,this.enabled&&!this.destroyed&&this._lightProbeObj&&this.scene.add(this._lightProbeObj))});this.sourceId&&this.context.rendererData.enableReflection(this.sourceId)}onDisable(){yo&&console.log("disable",this.sourceId,this),this._lightProbeObj&&this._lightProbeObj.removeFromParent(),this._ambientLightObj&&this._ambientLightObj.removeFromParent(),this.sourceId&&this.context.rendererData.disableReflection()}};import{NeverStencilFunc as rg,LessStencilFunc as og,EqualStencilFunc as sg,LessEqualStencilFunc as ag,GreaterStencilFunc as lg,NotEqualStencilFunc as cg,GreaterEqualStencilFunc as dg,AlwaysStencilFunc as ug,ZeroStencilOp as hg,KeepStencilOp as pg,ReplaceStencilOp as fg,IncrementStencilOp as mg,DecrementStencilOp as gg,IncrementWrapStencilOp as bg,DecrementWrapStencilOp as vg,InvertStencilOp as yg}from"three";var Ac=I("debugstencil");function _g(o,e){return(o&1<<e.layer)!=0}var yr=class{static applyStencil(e){if(!e)return;let t=e.sourceId;if(Ac&&console.log(t,yr.stencils),!t)return;let n=yr.stencils[t];if(!!n)for(let i=n.length-1;i>=0;i--){let r=n[i];if(_g(r.layer,e)){Ac&&console.log(r);let s=e.sharedMaterial?.clone();s&&(e.sharedMaterial=s,e.gameObject.renderOrder=r.event*1e3+r.index*50,s.stencilWrite=!0,s.stencilWriteMask=255,s.stencilFuncMask=255,s.stencilRef=r.value,s.stencilFunc=r.compareFunc,s.stencilZPass=r.passOp,s.stencilFail=r.failOp,s.stencilZFail=r.zFailOp);break}}}parser;source;constructor(e,t){this.parser=e,this.source=t}afterRoot(e){let t=this.parser.json.extensions;if(t){let n=t[wg];if(n){Ac&&console.log(n);let i=n.stencil;if(i&&Array.isArray(i))for(let r of i){let s={...r};s.compareFunc=Eg(s.compareFunc),s.passOp=Lc(s.passOp),s.failOp=Lc(s.failOp),s.zFailOp=Lc(s.zFailOp),yr.stencils[this.source]||(yr.stencils[this.source]=[]),yr.stencils[this.source].push(s)}}}return null}},_r=yr;j(_r,"stencils",{});function Lc(o){switch(o){case 0:return pg;case 1:return hg;case 2:return fg;case 3:return mg;case 4:return gg;case 6:return bg;case 7:return vg;case 5:return yg}return 0}function Eg(o){switch(o){case 1:return rg;case 2:return og;case 3:return sg;case 4:return ag;case 5:return lg;case 6:return cg;case 7:return dg;case 8:return ug}return 0}var wg="NEEDLE_render_objects";import{TextureLoader as xg}from"three";import{GLTFLoader as Cg}from"three/examples/jsm/loaders/GLTFLoader";var jc="NEEDLE_deferred_texture",Ye=I("debugprogressive"),Fc=new Map,Hc=!1;Ye&&window.addEventListener("keyup",o=>{o.key==="p"&&(Fc.forEach((e,t)=>{Object.entries(e).forEach(([n,i])=>{Hc?t[n]=i.lod0:t[n]=i.original,t.needsUpdate=!0})}),Hc=!Hc)});var cs=class{static assignTextureLOD(e,t,n,i=0){if(!!n)for(let r of Object.keys(n)){let s=n[r];s?.isTexture===!0&&(Ye&&console.log(`-----------
175
175
  `,"FIND",n.name,r,s?.name,s?.userData,s),cs.getOrLoadTexture(e,t,n,r,s,i).then(a=>{if(a?.isTexture===!0&&(a.needsUpdate=!0,Ye&&console.log("Assign LOD",n.name,r,a.name,a.guid,n,"Prev:",s,"Now:",a,`
176
- --------------`),n[r]=a,n.needsUpdate=!0,Ye)){let c=Fc.get(n);c||(c={},Fc.set(n,c));let d=c[r];d||(d=c[r]={original:s,lod0:a}),d.lod0=a}}))}}get name(){return jc}parser;sourceId;context;constructor(e,t,n){this.parser=e,this.sourceId=t,this.context=n}_loading=[];afterRoot(e){return Ye&&console.log("AFTER",this.sourceId,e),this.parser.json.textures?.forEach((t,n)=>{if(t?.extensions){let i=t?.extensions[jc];if(i){let r=this.parser.getDependency("texture",n);this._loading.splice(this._loading.indexOf(n),1),r.then(s=>{Ye&&console.log("register texture",s.name,s.uuid,i),s.userData.deferred=i,cs.cache.set(s.uuid,i)})}}}),null}static async getOrLoadTexture(e,t,n,i,r,s){let a=r.uuid,c=cs.cache.get(a);if(c){Ye&&console.log(a,c.uri,c.guid);let d=cn(t,c.uri);if(d.endsWith(".glb")||d.endsWith(".gltf")){if(!c.guid)return console.warn("missing pointer for glb/gltf texture",c),null;let l=d+"_"+c.guid;if(this.resolved[l])return Ye&&console.log("Texture has already been loaded: "+l,n.name,i,r.name),this.resolved[l];let u=new Cg;Zn(u,e),Ye&&console.log("Load "+d,n.name,i,c.guid);let h=await u.loadAsync(d),b=h.parser;Ye&&console.log("Loading finished "+d,n.name,i,c.guid);let _=-1,v=!1;for(let m of h.parser.json.textures)if(_++,m?.extensions){let f=m?.extensions[jc];if(f?.guid&&f.guid===c.guid){v=!0;break}}if(!v)return null;let y=await b.getDependency("texture",_);return y&&(y.guid=c.guid),this.resolved[l]=y,Ye&&console.log(n.name,i,'change "'+r.name+'" \u2192 "'+y.name+'"',d,_,y,n,l),y}else{Ye&&console.log("Load texture from uri: "+d);let u=await new xg().loadAsync(d);return u&&Ye?console.log(c,u):console.warn("failed loading",d),u}}else Ye&&console.warn("unknown uuid",r.name,r.uuid,r);return null}},ei=cs;j(ei,"cache",new Map),j(ei,"resolved",{});function Uc(o){let e=new vo;return o.register(t=>(e.parser=t,e)),e}var Bc=class{resolvePath(e){return e.includes("/extensions/builtin_components/")?e.replace("/extensions/builtin_components/","/userData/components/"):e.includes("extensions/builtin_components/")?e.replace("extensions/builtin_components/","/userData/components/"):e}};function Gc(o,e,t){o.register(i=>new Ma(i)),o.register(i=>new Ds(i)),o.register(i=>new wa(i,e.lightmaps,t)),o.register(i=>new Da(i,t,e)),o.register(i=>new Oa(i,t)),o.register(i=>new _r(i,t)),o.register(i=>new ei(i,t,e)),o.register(i=>new Ia(i));let n=o.setAnimationPointerResolver;typeof n=="function"&&n.bind(o)(new Bc)}import{Vector3 as Tg}from"three";var ti=class extends O{from;to;width=0;centered=!0;_centerPos;awake(){this._centerPos=new Tg}update(){if(!this.from||!this.to)return;let e=B(this.from).clone(),t=B(this.to).clone(),n=e.distanceTo(t);this._centerPos.copy(e),this._centerPos.add(t),this._centerPos.multiplyScalar(.5),J(this.gameObject,this.centered?this._centerPos:e),this.gameObject.lookAt(B(this.to).clone()),this.gameObject.scale.set(this.width,this.width,n)}};x([w(R)],ti.prototype,"from",2),x([w(R)],ti.prototype,"to",2);var bn=class{time;value;inTangent;inWeight;outTangent;outWeight;weightedMode};x([w()],bn.prototype,"time",2),x([w()],bn.prototype,"value",2),x([w()],bn.prototype,"inTangent",2),x([w()],bn.prototype,"inWeight",2),x([w()],bn.prototype,"outTangent",2),x([w()],bn.prototype,"outWeight",2),x([w()],bn.prototype,"weightedMode",2);var Mi=class{keys;get duration(){return!this.keys||this.keys.length==0?0:this.keys[this.keys.length-1].time}evaluate(e){if(!this.keys||this.keys.length==0)return 0;let t=null;for(let n of this.keys){if(t&&n.time>e&&e>t.time)return U.lerp(t.value,n.value,(e-t.time)/(n.time-t.time));t=n}return this.keys[this.keys.length-1].value}};x([w(bn)],Mi.prototype,"keys",2);import*as Wh from"three";import*as ds from"three";import{PositionalAudioHelper as Rg}from"three/examples/jsm/helpers/PositionalAudioHelper.js";var Ke=I("debugaudio");var xe=class extends O{static get userInteractionRegistered(){return xe._didCallBeginWaitForUserInteraction||(xe._didCallBeginWaitForUserInteraction=!0,xe._beginWaitForUserInteraction()),xe._userInteractionRegistered}static registerWaitForAllowAudio(e){if(e!==null){if(this._userInteractionRegistered){e();return}this.callbacks.indexOf(e)===-1&&this.callbacks.push(e),xe._didCallBeginWaitForUserInteraction||(xe._didCallBeginWaitForUserInteraction=!0,xe._beginWaitForUserInteraction())}}static _beginWaitForUserInteraction(e=null){if(this._userInteractionRegistered){e&&e();return}e!==null&&this.registerWaitForAllowAudio(e);let n=(()=>{if(n!=null&&!xe._userInteractionRegistered){xe._userInteractionRegistered=!0,console.log("registered interaction, can play audio now"),document.removeEventListener("pointerdown",n),document.removeEventListener("click",n),document.removeEventListener("dragstart",n),document.removeEventListener("touchstart",n);for(let i of this.callbacks)i();this.callbacks.length=0}}).bind(this);document.addEventListener("pointerdown",n),document.addEventListener("click",n),document.addEventListener("dragstart",n),document.addEventListener("touchstart",n)}clip="";playOnAwake=!1;get loop(){return this.sound&&(this._loop=this.sound.getLoop()),this._loop}set loop(e){this._loop=e,this.sound&&this.sound.setLoop(e)}get spatialBlend(){return this._spatialBlend}set spatialBlend(e){e!==this._spatialBlend&&(this._spatialBlend=e,this._needUpdateSpatialDistanceSettings=!0)}get minDistance(){return this._minDistance}set minDistance(e){this._minDistance!==e&&(this._minDistance=e,this._needUpdateSpatialDistanceSettings=!0)}get maxDistance(){return this._maxDistance}set maxDistance(e){this._maxDistance!==e&&(this._maxDistance=e,this._needUpdateSpatialDistanceSettings=!0)}_spatialBlend=0;_minDistance=1;_maxDistance=100;get volume(){return this._volume}set volume(e){this._volume=e,this.sound&&(Ke&&console.log(this.name,"audio set volume",e),this.sound.setVolume(e))}_volume=1;rollOffMode=0;_loop=!1;sound=null;helper=null;wasPlaying=!1;audioLoader=null;shouldPlay=!1;_lastClipStartedLoading=null;get Sound(){if(!this.sound&&xe._userInteractionRegistered){let e=R.getComponent(this.context.mainCamera,kt)??R.findObjectOfType(kt,this.context);e?.listener&&(this.sound=new ds.PositionalAudio(e.listener),this.gameObject.add(this.sound))}return this.sound}get ShouldPlay(){return this.shouldPlay}_focusCallback;awake(){this.audioLoader=new ds.AudioLoader,this.playOnAwake&&(this.shouldPlay=!0),window.addEventListener("visibilitychange",e=>{switch(document.visibilityState){case"hidden":this.wasPlaying=this.isPlaying,this.pause();break;case"visible":this.wasPlaying&&this.play();break}}),this._focusCallback=()=>{this.enabled&&this.playOnAwake&&!this.isPlaying&&xe._userInteractionRegistered&&this.play()},this.context.application.addEventListener("application-visible",this._focusCallback)}onDestroy(){this.context.application.removeEventListener("application-visible",this._focusCallback)}onEnable(){xe._userInteractionRegistered?this.playOnAwake&&this.context.application.isVisible&&this.play():xe._beginWaitForUserInteraction(()=>{this.enabled&&!this.destroyed&&this.shouldPlay&&this.loadAndPlay(this.clip)})}onDisable(){this.stop()}lerp=(e,t,n)=>e*(1-n)+t*n;onLoaded(e){Ke&&console.log("audio buffer loaded"),xe.registerWaitForAllowAudio(()=>{Ke&&console.log("finished loading",e);let t=this.Sound;if(!t){console.warn("Failed getting sound",this.name);return}t.isPlaying&&t.stop(),t.setBuffer(e),t.loop=this.loop,t.setVolume(this.volume),t.autoplay=this.shouldPlay,this.applySpatialDistanceSettings(),t.isPlaying&&t.stop(),Ke&&console.log(this.name,this.shouldPlay,xe.userInteractionRegistered,this),this.shouldPlay&&xe._userInteractionRegistered&&this.play()})}applySpatialDistanceSettings(){let e=this.sound;if(!e)return;this._needUpdateSpatialDistanceSettings=!1;let t=this.lerp(10*this._maxDistance/Math.max(1e-4,this.spatialBlend),this._minDistance,this.spatialBlend);switch(Ke&&console.log(this.name,this._minDistance,this._maxDistance,this.spatialBlend,"Ref distance="+t),e.setRefDistance(t),e.setMaxDistance(Math.max(.01,this._maxDistance)),this.rollOffMode){case 0:e.setDistanceModel("exponential");break;case 1:e.setDistanceModel("linear");break;case 2:break}this.spatialBlend>0?Ke&&!this.helper&&(this.helper=new Rg(e,e.getRefDistance()),e.add(this.helper)):this.helper&&this.helper.parent&&this.helper.removeFromParent()}loadAndPlay(e){if(e&&(this.clip=e),this.clip&&(Ke&&console.log(this.clip),this.clip.endsWith(".mp3")||this.clip.endsWith(".wav"))){if(this.audioLoader||(this.audioLoader=new ds.AudioLoader),this.shouldPlay=!0,this._lastClipStartedLoading===this.clip){Ke&&console.log("Is currently loading:",this._lastClipStartedLoading,this);return}this._lastClipStartedLoading=this.clip,Ke&&console.log("load audio",this.clip),this.audioLoader.load(this.clip,this.onLoaded.bind(this),()=>{},console.error)}}play(e=void 0){if(!this.audioLoader||!this.sound||e&&e!==this.clip){this.loadAndPlay(e);return}this.shouldPlay=!0,this._hasEnded=!1,Ke&&console.log("play",this.sound?.getVolume(),this.sound),this.sound&&!this.sound.isPlaying&&this.sound.play()}pause(){Ke&&console.log("Pause",this),this._hasEnded=!0,this.shouldPlay=!1,this.sound&&this.sound.isPlaying&&this.sound.source&&(this._lastContextTime=this.sound?.context.currentTime,this.sound.pause())}stop(){Ke&&console.log("Pause",this),this._hasEnded=!0,this.shouldPlay=!1,this.sound&&this.sound.source&&(this._lastContextTime=this.sound?.context.currentTime,Ke&&console.log(this._lastContextTime),this.sound.stop())}_lastContextTime=0;get isPlaying(){return this.sound?.isPlaying??!1}set isPlaying(e){}get time(){return this.sound?.source?this.sound.source?.context.currentTime-this._lastContextTime+this.sound.offset:0}set time(e){if(this.sound){if(e===this.sound.offset)return;let t=this.isPlaying;this.stop(),this.sound.offset=e,t&&this.play()}}_hasEnded=!0;_needUpdateSpatialDistanceSettings=!1;update(){this.helper&&(this.isPlaying&&this.helper.update(),this.helper.visible=this.isPlaying),this._needUpdateSpatialDistanceSettings&&this.applySpatialDistanceSettings(),this.sound&&!this.sound.isPlaying&&this.shouldPlay&&!this._hasEnded&&(this._hasEnded=!0,Ke&&console.log("Audio clip ended",this.clip),this.sound.dispatchEvent({type:"ended",target:this}))}},Z=xe;j(Z,"_didCallBeginWaitForUserInteraction",!1),j(Z,"callbacks",[]),j(Z,"_userInteractionRegistered",!1),x([w()],Z.prototype,"clip",2),x([w()],Z.prototype,"playOnAwake",2),x([w()],Z.prototype,"loop",1),x([w()],Z.prototype,"spatialBlend",1),x([w()],Z.prototype,"minDistance",1),x([w()],Z.prototype,"maxDistance",1),x([w()],Z.prototype,"volume",1),x([w()],Z.prototype,"rollOffMode",2);import*as ni from"three";import{Color as Sg}from"three";var de=class extends Sg{alpha=1;get isRGBAColor(){return!0}constructor(e,t,n,i){super(e,t,n),this.alpha=i}clone(){let e=super.clone();return e.alpha=this.alpha,e}copy(e){return super.copy(e),"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&&(this.alpha=U.lerp(this.alpha,n.alpha,t)),super.lerp(e,t)}multiply(e){let t=e;return t.alpha&&(this.alpha=this.alpha*t.alpha),super.multiply(e)}};import{PerspectiveCamera as Og}from"three";var Aa=I("debugcam"),se=class extends O{get isCamera(){return!0}get aspect(){return this._cam instanceof Og?this._cam.aspect:this.context.domWidth/this.context.domHeight}get fieldOfView(){return this._fov}set fieldOfView(e){let t=this._fov!=e;this._fov=e,t&&this._cam&&this._cam instanceof ni.PerspectiveCamera&&(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.updateProjectionMatrix())}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.updateProjectionMatrix())}get clearFlags(){return this._clearFlags}set clearFlags(e){e!==this._clearFlags&&(this._clearFlags=e,this.applyClearFlagsIfIsActiveCamera())}orthographic=!1;orthographicSize=5;ARBackgroundAlpha=0;_nearClipPlane=.1;_farClipPlane=1e3;get backgroundColor(){return this._backgroundColor??null}set backgroundColor(e){if(!!e){if(this._backgroundColor)this._backgroundColor.copy(e);else{if(!e.clone)return;this._backgroundColor=e.clone()}this.applyClearFlagsIfIsActiveCamera()}}_backgroundColor;_fov=60;_cam=null;_clearFlags=2;_skybox;get cam(){return this.activeAndEnabled&&this.buildCamera(),this._cam}awake(){this.sourceId||console.warn("Camera has no source - the camera should be exported inside a gltf",this.name)}onEnable(){Aa&&console.log(this),this.buildCamera(),(this.tag=="MainCamera"||!this.context.mainCameraComponent)&&this.context.setCurrentCamera(this),this.applyClearFlagsIfIsActiveCamera()}onDisable(){this.context.removeCamera(this)}buildCamera(){if(this._cam)return;let e=this.gameObject.isCamera,t=null;if(e?t=this.gameObject:t=this.gameObject.children[0],t&&t.isCamera)t.type==="PerspectiveCamera"&&(t.fov=this._fov,t.near=this._nearClipPlane,t.far=this._farClipPlane,t.updateProjectionMatrix());else if(!this.orthographic)t=new ni.PerspectiveCamera(this.fieldOfView,window.innerWidth/window.innerHeight,this._nearClipPlane,this._farClipPlane),t.fov=this.fieldOfView;else{let n=this.orthographicSize*100;t=new ni.OrthographicCamera(window.innerWidth/-n,window.innerWidth/n,window.innerHeight/n,window.innerHeight/-n,this._nearClipPlane,this._farClipPlane)}this._cam=t,this.layer===0&&this._cam.layers.enableAll(),this.tag=="MainCamera"&&this.context.setCurrentCamera(this)}applyClearFlagsIfIsActiveCamera(){if(Aa&&Ft("apply Camera clear flags"),this._cam&&this.context.mainCameraComponent===this)switch(this._clearFlags){case 1:if(this.environmentIsTransparent()&&(!this.ARBackgroundAlpha||this.ARBackgroundAlpha<.001)){this.context.scene.background=null,this.context.renderer.setClearColor(0,0);return}this.enableSkybox();break;case 2:if(this._backgroundColor){let e=this._backgroundColor.alpha;this.environmentIsTransparent()&&(e=this.ARBackgroundAlpha??0),this.context.scene.background=null,this.context.renderer.setClearColor(this._backgroundColor,e)}break;case 4:this.context.scene.background=null,this.context.renderer.setClearColor(0,0);break}}environmentIsTransparent(){let e=this.context.renderer.xr?.getSession();if(!e)return!1;let t=e.environmentBlendMode;Aa&&Ft("Environment blend mode: "+t+" on "+navigator.userAgent);let n=t==="additive"||t==="alpha-blend";if(this.context.xrSessionMode==="immersive-ar"&&t==="opaque"){if(navigator.userAgent?.includes("OculusBrowser"))return!0;if(navigator.userAgent?.includes("Mozilla")&&navigator.userAgent?.includes("Mobile WebXRViewer/v2"))return!0}return n}enableSkybox(){this._skybox||(this._skybox=new Vc(this)),this._skybox.enable()}};x([w()],se.prototype,"fieldOfView",1),x([w()],se.prototype,"nearClipPlane",1),x([w()],se.prototype,"farClipPlane",1),x([w()],se.prototype,"clearFlags",1),x([w()],se.prototype,"orthographic",2),x([w()],se.prototype,"orthographicSize",2),x([w()],se.prototype,"ARBackgroundAlpha",2),x([w(de)],se.prototype,"backgroundColor",1);var Vc=class{_camera;_skybox;get context(){return this._camera?.context}constructor(e){this._camera=e}enable(){this._skybox=this.context.lightmaps.tryGetSkybox(this._camera.sourceId),this._skybox?(Aa&&console.log("Set skybox",this._camera,this._skybox),this._skybox.encoding=ni.sRGBEncoding,this._skybox.mapping=ni.EquirectangularReflectionMapping,this.context.scene.background=this._skybox):console.warn("Failed to load/find skybox texture",this)}};var kt=class extends O{get listener(){return this._listener==null&&(this._listener=new Wh.AudioListener),this._listener}_listener=null;awake(){Z.registerWaitForAllowAudio(()=>{let e=this.listener;if(e==null||e.parent)return;let t=R.getComponentInParent(this.gameObject,se);t?t.cam.add(e):this.gameObject.add(e)})}};import{GLTFLoader as kg}from"three/examples/jsm/loaders/GLTFLoader";import*as La from"three";var us=I("debugavatar"),Di=class{root;head;leftHand;rigthHand;get isValid(){return this.head!==null&&this.head!==void 0}constructor(e,t,n,i){this.root=e,this.head=t,this.leftHand=n,this.rigthHand=i,this.root?.traverse(r=>r.layers.set(2))}},ii=class{avatarRegistryUrl=null;async getOrCreateNewAvatarInstance(e,t){if(!t)return console.error("Can not create avatar: failed to provide id or root object"),null;let n=null;if(typeof t=="string"){if(n=await this.loadAvatar(e,t),!n){let r=new Ie;n=R.instantiate(Ei(t,e.scene),r)}}else n=t;if(!n)return null;let i=this.findAvatar(n);return i.isValid?(us&&console.log("[Custom Avatar] valid config",t,us?i:""),i):(console.warn("[Custom Avatar] config isn't valid",t,us?i:""),null)}async loadAvatar(e,t){if(console.assert(t!=null&&typeof t=="string","Avatar id must not be null"),t.length<=0||!t)return null;if(us&&console.log("[Custom Avatar] "+t+", loading..."),t.endsWith(".glb")||(t+=".glb"),this.avatarRegistryUrl===null){let i=await fetch("./"+t),r=null;if(i.ok){let a=await i.blob();a&&(r=await a.arrayBuffer())}return!r&&(r=await pa(t,t,0,"no url here go away",!0),!r)?null:(await Le().parseSync(e,r,null,0))?.scene??null}let n=new kg;return Zn(n,e),new Promise((i,r)=>{let s=this.avatarRegistryUrl+"/"+t;n.load(s,async a=>{await Le().createBuiltinComponents(e,s,a,null,void 0),i(a.scene)},a=>{us&&console.log("[Custom Avatar] "+a.loaded/a.total*100+"% loaded of "+a.total/1024+"kB")},a=>{console.error("[Custom Avatar] Error when loading: "+a),i(null)})})}cacheModel(e,t){}findAvatar(e){let t=e,n=t;n.children.length==1&&(n=e.children[0]);let i=this.findAvatarPart(n,["head"]),r=this.findAvatarPart(n,["left","hand"]),s=this.findAvatarPart(n,["right","hand"]);if(!i){i=t;let c=new La.Vector3;new La.Box3().setFromObject(i).getSize(c);let d=Math.max(c.x,c.y,c.z);console.warn("[Custom Avatar] Normalizing head scale, it's too big: "+d+" meters! Should be < 0.3m"),d>.3&&i.scale.multiplyScalar(1/d*.3)}return new Di(t,i,r,s)}findAvatarPart(e,t){let n=e.name.toLowerCase(),i=!0;for(let r of t){if(!i)break;n.indexOf(r)===-1&&(i=!1)}if(i)return e;if(e.children)for(let r of e.children){let s=this.findAvatarPart(r,t);if(s)return s}return null}handleCustomAvatarErrors(e){if(!e.ok)throw Error(e.statusText);return e}};import{AxesHelper as Ig}from"three";var vn=class extends O{length=1;depthTest=!0;isGizmo=!0;_axes=null;onEnable(){if(this.isGizmo&&!dn)return;this._axes||(this._axes=new Ig(this.length)),this.gameObject.add(this._axes);let e=this._axes.material;e&&e.depthTest!==void 0&&(e.depthTest=this.depthTest)}onDisable(){!this._axes||this.gameObject.remove(this._axes)}};x([w()],vn.prototype,"length",2),x([w()],vn.prototype,"depthTest",2),x([w()],vn.prototype,"isGizmo",2);import*as Xh from"three";var Er=class extends O{from;to;hint;desiredDistance=1;onEnable(){}update(){if(!this.from||!this.to||!this.hint)return;let e=B(this.to).clone(),t=B(this.from).clone(),n=e.distanceTo(t),i=e.clone();i.sub(t);let r=t.clone();r.add(e),r.multiplyScalar(.5);let s=B(this.hint).clone();s.sub(r);let a=new Xh.Vector3;a.crossVectors(s,i),a.crossVectors(i,a),a.normalize();let c=n*.5,d=Math.max(this.desiredDistance,c),l=Math.sqrt(d*d-c*c),u=a.clone();u.multiplyScalar(l),u.add(r),J(this.gameObject,u);let h=r.clone();h.sub(a),this.gameObject.lookAt(h)}};import*as wr from"three";import*as yn from"three";var Mg=new yn.BoxGeometry(1,1,1);function ja(o=null){let e=new yn.Color(o??14540253),t=new yn.EdgesGeometry(Mg);return new yn.LineSegments(t,new yn.LineBasicMaterial({color:e}))}var Ag=I("gizmos"),dt=class extends O{box=null;_lastMatrixUpdateFrame=-1;isInBox(e,t){if(!!e){if(this.box||(this.box=new wr.Box3),e.type==="Mesh")dt.testBox.setFromObject(e);else if(e.type==="Group"){if(e.children.length>0){dt.testBox.setFromCenterAndSize(dt._position.set(0,0,0),dt._size.set(0,0,0));for(let n=0;n<e.children.length;n++)e.children[n].type==="Mesh"&&dt.testBox.expandByObject(e)}}else{let n=B(e,dt._position),i=ot(e,dt._size);t!==void 0&&i.multiplyScalar(t),dt.testBox.setFromCenterAndSize(n,i)}return this.updateBox(),this.box?.intersectsBox(dt.testBox)}}intersects(e){return e?this.updateBox(!1).intersectsBox(e):!1}updateBox(e=!1){if(this.box||(this.box=new wr.Box3),e||this.context.time.frameCount!=this._lastMatrixUpdateFrame){let t=this._lastMatrixUpdateFrame<0;this._lastMatrixUpdateFrame=this.context.time.frameCount;let n=t,i=B(this.gameObject,dt._position,n),r=ot(this.gameObject,dt._size);this.box.setFromCenterAndSize(i,r)}return this.box}_helper=null;_color=null;awake(){this._helper=null,this._color=null,this.box=null}showHelper(e=null,t=!1){if(!(!Ag&&!t)){if(this._helper){e&&this._color?.set(e),this.gameObject.add(this._helper);return}this._helper=ja(e),this.gameObject.add(this._helper)}}},Ce=dt;j(Ce,"testBox",new wr.Box3),j(Ce,"_position",new wr.Vector3),j(Ce,"_size",new wr.Vector3(.01,.01,.01));import{Quaternion as Vg,Ray as zg,Vector3 as xr}from"three";import*as Qh from"three";var Qt=class{method;enabled;constructor(e,t){this.method=e,this.enabled=t!==void 0?t:!0}invoke(...e){if(this.enabled!==!1){if(!this.method){console.warn("No function. Please check you assigned a method to invoke on export",this);return}this.method(...e)}}},Lg=o=>/^[A-Z]*$/.test(o),Ai=class extends Event{args},he=class{target;key;setEventTarget(e,t){if(this.key=e,this.target=t,this.key!==void 0){let n="",i=!1;for(let r of this.key)i&&Lg(r)&&(n+="-"),i=!0,n+=r.toLowerCase();this.key=n}}_isInvoking=!1;methods=[];constructor(e){this.methods=e??[]}invoke(...e){if(this._isInvoking){console.warn("Circular event invocation detected. Please check your event listeners for circular references.",this);return}this._isInvoking=!0;try{for(let t of this.methods)t.invoke(...e);if(typeof this.target=="object"&&typeof this.key=="string"){let t=this.target.dispatchEvent;if(typeof t=="function"){let n=new Ai(this.key);n.args=e,t.call(this.target,n)}}}finally{this._isInvoking=!1}}addEventListener(e){return this.methods.push(new Qt(e,!0)),e}removeEventListener(e){if(!!e)for(let t=this.methods.length-1;t>=0;t--)this.methods[t].method===e&&(this.methods[t].enabled=!1,this.methods.splice(t,1))}removeAllEventListeners(){this.methods.length=0}};import{Color as jg,Object3D as Hg}from"three";var Nc=class extends qn{constructor(){super([jg,de])}onDeserialize(e){if(e!=null)return e.a!==void 0?new de(e.r,e.g,e.b,e.a):e.alpha!==void 0?new de(e.r,e.g,e.b,e.alpha):new Qh.Color(e.r,e.g,e.b)}onSerialize(e){if(e!=null)return e.a!==void 0?{r:e.r,g:e.g,b:e.b,a:e.a}:{r:e.r,g:e.g,b:e.b}}},E0=new Nc,Wc=class extends qn{constructor(){super(Hg)}onSerialize(e,t){if(t.objectToNode!==void 0&&e.uuid){let n=t.objectToNode[e.uuid];return _e&&console.log(n,e.name,e.uuid),{node:n}}}onDeserialize(e,t){if(e){if(e.node!==void 0&&t.nodeToObject){let n=t.nodeToObject[e.node];return _e&&console.log("Deserialized object reference?",e,n,t?.nodeToObject),n||console.warn("Did not find node: "+e.node,t.nodeToObject,t.object),n}else if(e.guid){if(!t.context){console.error("Missing context");return}let n,i=t.gltf?.scene;return i&&(n=R.findByGuid(e.guid,i)),n||(n=R.findByGuid(e.guid,t.context.scene)),n?_e&&console.log("Deserialized object reference?",e,n,t?.nodeToObject):console.warn("could not resolve reference",e,t.target,t.path,t.context.scene),n}}}},Fg=new Wc,Xc=class extends qn{constructor(){super([ct,O])}onSerialize(e,t){if(e?.guid)return{guid:e.guid}}onDeserialize(e,t){if(e?.guid){_e&&console.log(e.guid,t.root,t.object,t.target);let n=this.findObjectForGuid(e.guid,t.root);if(n)return n;if(t.context)return this.findObjectForGuid(e.guid,t.context?.scene)}}findObjectForGuid(e,t){if(t.guid===e)return t;let n=R.foreachComponent(t,i=>{if(i.guid===e)return i},!1);if(n!==void 0)return n;for(let i=0;i<t.children.length;i++){let r=t.children[i],s=this.findObjectForGuid(e,r);if(s)return s}}},zc=new Xc,Qc=class extends qn{constructor(){super([he])}onSerialize(e,t){console.log("TODO: SERIALIZE EVENT")}onDeserialize(e,t){if(e&&e.type==="EventList"){_e&&console.log("DESERIALIZE EVENT",e);let n=new Array;for(let s of e.calls){_e&&console.log(s);let a=zc.findObjectForGuid(s.target,t.root);!a&&t.context?.scene&&(a=zc.findObjectForGuid(s.target,t.context?.scene));let c=s.method?.length>0;if(a&&c){let h=()=>console.warn(`Could not find method ${s.method} on object ${a.name}`,a,typeof a[s.method]);if(typeof a[s.method]!="function"){let b=!1;s.method.startsWith("set_")&&s.method.length>4&&(s.method=s.method.substring(4),a[s.method]!==void 0&&(b=!0)),b||h()}}let d,l=s.argument;s.argument!==void 0?(typeof l=="object"&&(l=Fg.onDeserialize(s.argument,t),l||(l=zc.onDeserialize(s.argument,t))),d=new Qt(c?(...h)=>u(...h):void 0,s.enabled)):d=new Qt(c?(...h)=>u(...h):void 0,s.enabled);let u=(...h)=>{let b=a[s.method];typeof b=="function"?l!==void 0?b?.call(a,l):b?.call(a,...h):a[s.method]=l};if(d.method||(d.__debuginfo=t.object?.name),!a||!d.method){let h=t.object?"Current object: "+t.object.name+", "+t.object.guid:null;a?console.warn('EventList method not found: "'+s.method+'" on',a):console.warn("EventList is missing target - will be ignored",s.target,h,e)}else n.push(d)}let i=new he(n);_e&&console.log(i);let r=t.target;return r!==void 0&&t.path!==void 0&&i.setEventTarget(t.path,r),i}}},w0=new Qc;import*as _o from"three";import{Vector3 as qh}from"three";var qt=function(o,e){return function(t,n,i){Ug(t,n,i,o,e)}};function Ug(o,e,t,n,i){if(!(!i&&!n&&!o.onValidate)){if(t!==void 0){console.error("Invalid usage of validate decorator. Only fields can be validated.",o,e,t),Ft("Invalid usage of validate decorator. Only fields can be validated. Property: "+e,2);return}if(o.__internalAwake){let r=Symbol(e),s=o.__internalAwake;o.__internalAwake=function(){this[r]===void 0&&(this[r]=this[e],Object.defineProperty(this,e,{set:function(a){if(this[Fs]===!0)this[r]=a;else{n?.call(this,a);let c=this[r];this[r]=a,this.onValidate?.call(this,e,c)}},get:function(){return i?.call(this),this[r]}})),s.call(this)}}}}var qc=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 t of this._positionKeys)delete this.position[t];if(this.quaternion)for(let t of this._quaternionKeys)delete this.quaternion[t]}}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||(this._positionWatch=new Xn(this.obj.position,["x","y","z"])),this._positionWatch.apply(),this.position={},this._positionWatch.subscribeWrite((n,i)=>{if(this.context.physics.isUpdating||this.mute)return;let r=this.position[i];Math.abs(r-n)<1e-5||(this.position[i]=n,this.positionChanged=!0)})),t&&(this._rotationWatch||(this._rotationWatch=new Xn(this.obj.quaternion,["_x","_y","_z","_w"])),this._rotationWatch.apply(),this.quaternion={},this._rotationWatch.subscribeWrite((n,i)=>{if(this.context.physics.isUpdating||this.mute)return;let r=this.quaternion[i];Math.abs(r-n)<1e-5||(this.quaternion[i]=n,this.rotationChanged=!0)}))}stop(){this._positionWatch?.revoke(),this._rotationWatch?.revoke()}},Ha=class extends O{mass=1;useGravity=!0;constraints=0;isKinematic=!1;drag=0;angularDrag=1;detectCollisions=!0;sleepThreshold=.01;collisionDetectionMode=0;get lockPositionX(){return(this.constraints&2)!==0}get lockPositionY(){return(this.constraints&4)!==0}get lockPositionZ(){return(this.constraints&8)!==0}get lockRotationX(){return(this.constraints&16)!==0}get lockRotationY(){return(this.constraints&32)!==0}get lockRotationZ(){return(this.constraints&64)!==0}set lockPositionX(e){e?this.constraints|=2:this.constraints&=-3}set lockPositionY(e){e?this.constraints|=4:this.constraints&=-5}set lockPositionZ(e){e?this.constraints|=8:this.constraints&=-9}set lockRotationX(e){e?this.constraints|=16:this.constraints&=-17}set lockRotationY(e){e?this.constraints|=32:this.constraints&=-33}set lockRotationZ(e){e?this.constraints|=64:this.constraints&=-65}_propertiesChanged=!1;_currentVelocity;_smoothedVelocity;_smoothedVelocityGetter;_lastPosition;_watch;awake(){this._watch=void 0,this._currentVelocity=new _o.Vector3,this._smoothedVelocity=new _o.Vector3,this._smoothedVelocityGetter=new _o.Vector3,this._lastPosition=new _o.Vector3}onEnable(){this._watch||(this._watch=new qc(this.gameObject,this.context)),this._watch.start(!0,!0),this.startCoroutine(this.beforePhysics(),2)}onDisable(){this._watch?.stop(),this.context.physics.removeBody(this)}onDestroy(){this.context.physics.removeBody(this)}onValidate(){this._propertiesChanged=!0}*beforePhysics(){for(;;)this._propertiesChanged&&(this._propertiesChanged=!1,this.context.physics.updateProperties(this)),this._watch?.isDirty&&(this._watch.mute=!0,this._watch.applyValues(),this.context.physics.updateBody(this,this._watch.positionChanged,this._watch.rotationChanged),this._watch.reset()),this.captureVelocity(),yield}get body(){return this.context.physics.internal_getRigidbody(this)}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(){this.body?.resetForces(!0)}resetTorques(){this.body?.resetTorques(!0)}resetVelocities(){this.setVelocity(0,0,0),this.setAngularVelocity(0,0,0)}resetForcesAndTorques(){this.resetForces(),this.resetTorques()}wakeUp(){this.body?.wakeUp()}applyForce(e,t){this.body?.addForce(e,!0)}applyImpulse(e){this.body?.applyImpulse(e,!0)}setForce(e,t,n){this.body?.resetForces(!0),this.body?.addForce({x:e,y:t,z:n},!0)}getVelocity(){let e=this.body?.linvel();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){if(e instanceof qh){let i=e;this.body?.setLinvel(i,!0);return}t===void 0||n===void 0||this.body?.setLinvel({x:e,y:t,z:n},!0)}setAngularVelocity(e,t,n){if(e instanceof qh){let i=e;this.body?.setAngvel(i,!0);return}t===void 0||n===void 0||this.body?.setAngvel({x:e,y:t,z:n},!0)}setTorque(e,t,n){this.setAngularVelocity(e,t,n)}get smoothedVelocity(){return this._smoothedVelocityGetter.copy(this._smoothedVelocity),this._smoothedVelocityGetter.multiplyScalar(1/this.context.time.deltaTime)}setBodyFromGameObject(e=null){this.gameObject&&this.destroyed}captureVelocity(){if(this.body){let e=B(this.gameObject);Ha.tempPosition.copy(e);let t=e.sub(this._lastPosition);this._lastPosition.copy(Ha.tempPosition),this._smoothedVelocity.lerp(t,this.context.time.deltaTime/.1)}}},q=Ha;j(q,"tempPosition",new _o.Vector3),x([qt(),w()],q.prototype,"mass",2),x([qt(),w()],q.prototype,"useGravity",2),x([qt(),w()],q.prototype,"constraints",2),x([qt(),w()],q.prototype,"isKinematic",2),x([qt(),w()],q.prototype,"drag",2),x([qt(),w()],q.prototype,"angularDrag",2),x([qt(),w()],q.prototype,"detectCollisions",2),x([qt(),w()],q.prototype,"sleepThreshold",2),x([qt(),w()],q.prototype,"collisionDetectionMode",2);import{Mesh as Gg,Vector3 as Li}from"three";var ht=class extends O{get isCollider(){return!0}attachedRigidbody=null;isTrigger=!1;awake(){super.awake(),this.attachedRigidbody||(this.attachedRigidbody=this.gameObject.getComponentInParent(q))}start(){this.attachedRigidbody||(this.attachedRigidbody=this.gameObject.getComponentInParent(q))}onEnable(){this.attachedRigidbody||(this.attachedRigidbody=this.gameObject.getComponentInParent(q))}onDisable(){this.context.physics.removeBody(this)}};x([w(q)],ht.prototype,"attachedRigidbody",2),x([w()],ht.prototype,"isTrigger",2);var ri=class extends ht{radius=.5;center=new Li(0,0,0);onEnable(){super.onEnable(),this.context.physics.addSphereCollider(this,this.center,this.radius)}};x([w()],ri.prototype,"radius",2),x([w(Li)],ri.prototype,"center",2);var oi=class extends ht{size=new Li(1,1,1);center=new Li(0,0,0);onEnable(){super.onEnable(),this.context.physics.addBoxCollider(this,this.center,this.size)}};x([w(Li)],oi.prototype,"size",2),x([w(Li)],oi.prototype,"center",2);var ji=class extends ht{sharedMesh;convex=!1;onEnable(){super.onEnable(),this.sharedMesh?.isMesh||this.gameObject instanceof Gg&&(this.sharedMesh=this.gameObject),this.sharedMesh?.isMesh&&this.context.physics.addMeshCollider(this,this.sharedMesh,this.convex)}};x([w()],ji.prototype,"convex",2);var ut=class extends ht{center=new Li(0,0,0);radius=.5;height=2;onEnable(){super.onEnable(),this.context.physics.addCapsuleCollider(this,this.center,this.height,this.radius)}};x([w(Li)],ut.prototype,"center",2),x([w()],ut.prototype,"radius",2),x([w()],ut.prototype,"height",2);var Yt=class extends O{center=new xr(0,0,0);radius=.5;height=2;_rigidbody=null;get rigidbody(){return this._rigidbody?this._rigidbody:(this._rigidbody=this.gameObject.getComponent(q),this._rigidbody||(this._rigidbody=this.gameObject.addNewComponent(q)),this.rigidbody)}onEnable(){let e=this.rigidbody,t=this.gameObject.getComponent(ut);t||(t=this.gameObject.addNewComponent(ut)),t.center.copy(this.center),t.radius=this.radius,t.height=this.height,this.gameObject.rotation.x=0,this.gameObject.rotation.z=0,e.lockRotationX=!0,e.lockRotationY=!0,e.lockRotationZ=!0}move(e){this.gameObject.position.add(e)}_activeGroundCollisions=new Set;onCollisionEnter(e){for(let t of e.contacts)if(t.normal.y>.1){this._activeGroundCollisions.add(e);break}}onCollisionExit(e){this._activeGroundCollisions.delete(e)}get isGrounded(){return this._activeGroundCollisions.size>0}};x([w(xr)],Yt.prototype,"center",2),x([w()],Yt.prototype,"radius",2),x([w()],Yt.prototype,"height",2);var It=class extends O{controller;movementSpeed=2;rotationSpeed=2;jumpForce=1;animator;lookForward=!0;_currentSpeed=new xr(0,0,0);_currentAngularSpeed=new xr(0,0,0);_temp=new xr(0,0,0);_jumpCount=0;_currentRotation;awake(){this._currentRotation=new Vg}update(){this.controller?.isGrounded&&(this._jumpCount=0,this.animator?.SetBool("doubleJump",!1));let e=this.context.input.isKeyPressed("w"),t=this.context.input.isKeyPressed("s"),n=this.context.input.isKeyPressed("a"),i=this.context.input.isKeyPressed("d"),r=this.context.input.isKeyDown(" "),s=e?1:0+t?-1:0;this._currentSpeed.z+=s*this.movementSpeed*this.context.time.deltaTime,this.animator?.SetBool("running",s!=0),this.animator?.SetBool("jumping",this.controller?.isGrounded===!0&&r),this._temp.copy(this._currentSpeed),this._temp.applyQuaternion(this.gameObject.quaternion),this.controller?this.controller.move(this._temp):this.gameObject.position.add(this._temp);let a=n?1:0+i?-1:0;if(this._currentAngularSpeed.y+=U.toRadians(a*this.rotationSpeed)*this.context.time.deltaTime,this.lookForward&&Math.abs(this._currentAngularSpeed.y)<.01){let c=this.context.mainCameraComponent.forward;c.y=0,c.normalize(),this._currentRotation.setFromUnitVectors(new xr(0,0,1),c),this.gameObject.quaternion.slerp(this._currentRotation,this.context.time.deltaTime*10)}if(this.gameObject.rotateY(this._currentAngularSpeed.y),this._currentSpeed.multiplyScalar(1-this.context.time.deltaTime*10),this._currentAngularSpeed.y*=1-this.context.time.deltaTime*10,this.controller&&r&&this.jumpForce>0){let c=this.controller?.isGrounded;if(!this.controller?.isGrounded&&this._jumpCount===1&&(c=!0,this.animator?.SetBool("doubleJump",!0)),c){this._jumpCount+=1;let d=this.controller.rigidbody,l=this._jumpCount===2?2:1;d.applyImpulse(new xr(0,1,0).multiplyScalar(this.jumpForce*l))}}if(this.controller){let c=this.controller?.rigidbody.getVelocity().y;if(c<-1){this._raycastOptions.ray||(this._raycastOptions.ray=new zg),this._raycastOptions.ray.origin.copy(B(this.gameObject)),this._raycastOptions.ray.direction.set(0,-1,0);let d=this.layer;this.gameObject.layers.disableAll(),this.gameObject.layers.set(2);let l=this.context.physics.raycast(this._raycastOptions);this.gameObject.layers.set(d),(l.length&&l[0].distance>2||c<-10)&&this.animator?.SetBool("falling",!0)}else this.animator?.SetBool("falling",!1)}}_raycastOptions=new ce};x([w(Yt)],It.prototype,"controller",2),x([w()],It.prototype,"movementSpeed",2),x([w()],It.prototype,"rotationSpeed",2),x([w()],It.prototype,"jumpForce",2),x([w(He)],It.prototype,"animator",2);var pt=class extends O{canGrab=!0;onPointerClick(e){}},ft=class extends O{isUsed=!0;usedBy=null};var Hi=class extends Ce{},Cr=class extends O{deleteBoxes=[];awake(){this.deleteBoxes=R.findObjectsOfType(Hi,this.context)}update(){for(let e of this.deleteBoxes){let t=this.gameObject;e.isInBox(t)===!0&&(R.getComponentInParent(this.gameObject,ft)||so(this.gameObject,this.context.connection))}}};var Fi=class extends O{visibleOn;onEnable(){this.apply()}apply(){this.test()||R.setActive(this.gameObject,!1)}test(){return this.visibleOn<0?!0:Ng()?(this.visibleOn&2)!==0:(this.visibleOn&1)!==0}};x([w()],Fi.prototype,"visibleOn",2);var Fa;function Ng(){if(Fa===!0||Fa===!1)return Fa;let o=!1;return function(e){(/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(e)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(e.substr(0,4)))&&(o=!0)}(navigator.userAgent||navigator.vendor||window.opera),Fa=o,o}import*as si from"three";var ve=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,i){return e.prep(4,12),e.writeFloat32(i),e.writeFloat32(n),e.writeFloat32(t),e.offset()}};var Eo=class{bb=null;bb_pos=0;__init(e,t){return this.bb_pos=e,this.bb=t,this}position(e){return(e||new ve).__init(this.bb_pos,this.bb)}rotation(e){return(e||new ve).__init(this.bb_pos+12,this.bb)}scale(e){return(e||new ve).__init(this.bb_pos+24,this.bb)}static sizeOf(){return 36}static createTransform(e,t,n,i,r,s,a,c,d,l){return e.prep(4,36),e.prep(4,12),e.writeFloat32(l),e.writeFloat32(d),e.writeFloat32(c),e.prep(4,12),e.writeFloat32(a),e.writeFloat32(s),e.writeFloat32(r),e.prep(4,12),e.writeFloat32(i),e.writeFloat32(n),e.writeFloat32(t),e.offset()}};var Mt=class{bb=null;bb_pos=0;__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsSyncedTransformModel(e,t){return(t||new Mt).__init(e.readInt32(e.position())+e.position(),e)}static getSizePrefixedRootAsSyncedTransformModel(e,t){return e.setPosition(e.position()+4),(t||new Mt).__init(e.readInt32(e.position())+e.position(),e)}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 Eo).__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)}};var Bi=I("debugsync"),wo="STRS";fo(wo,Mt.getRootAsSyncedTransformModel);var _n=new st;function Yc(o,e,t=!0){_n.clear();let n=_n.createString(o);Mt.startSyncedTransformModel(_n),Mt.addGuid(_n,n),Mt.addFast(_n,t);let i=e.worldPosition,r=e.worldEuler,s=e.gameObject.scale;Mt.addTransform(_n,Eo.createTransform(_n,i.x,i.y,i.z,r.x,r.y,r.z,s.x,s.y,s.z));let a=Mt.endSyncedTransformModel(_n);return _n.finish(a,wo),_n.asUint8Array()}var Je=class extends O{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(){Bi&&console.log("Request ownership"),this._model?this._model.requestOwnership():(this._shouldRequestOwnership=!0,this._needsUpdate=!0)}hasOwnership(){return this._model?.hasOwnership??void 0}isOwned(){return this._model?.isOwned}joinedRoomCallback=null;receivedDataCallback=null;awake(){Bi&&console.log("new instance",this.guid,this),this._receivedDataBefore=!1,this._targetPosition=new si.Vector3,this._targetRotation=new si.Quaternion,this.lastWorldPos=new si.Vector3,this.lastWorldRotation=new si.Quaternion,this.rb=R.getComponentInChildren(this.gameObject,q),this.rb&&(this._wasKinematic=this.rb.isKinematic),this.receivedUpdate=!0,this._model=new Ri(this.context.connection,this.guid),this.context.connection.isConnected&&this.tryGetLastState(),this.joinedRoomCallback=this.tryGetLastState.bind(this),this.context.connection.beginListen("joined-room",this.joinedRoomCallback),this.receivedDataCallback=this.onReceivedData.bind(this),this.context.connection.beginListenBinrary(wo,this.receivedDataCallback)}onDestroy(){this.syncDestroy&&Hu(this.guid,this.context.connection),this._model=null,this.context.connection.stopListening("joined-room",this.joinedRoomCallback),this.context.connection.stopListenBinary(wo,this.receivedDataCallback)}tryGetLastState(){let e=this.context.connection.tryGetState(this.guid);e&&this.onReceivedData(e)}tempEuler=new si.Euler;onReceivedData(e){if(!this.destroyed&&typeof e.guid=="function"&&e.guid()===this.guid){Bi&&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){ne.markDirty(this.gameObject,!0);let n=t.position();n&&(this.interpolatePosition&&this._targetPosition?.set(n.x(),n.y(),n.z()),(!this.interpolatePosition||!this._receivedDataBefore)&&this.setWorldPosition(n.x(),n.y(),n.z()));let i=t.rotation();i&&(this.tempEuler.set(i.x(),i.y(),i.z()),this.interpolateRotation&&this._targetRotation.setFromEuler(this.tempEuler),(!this.interpolateRotation||!this._receivedDataBefore)&&Pu(this.gameObject,this.tempEuler))}this._receivedDataBefore=!0}}onEnable(){this.lastWorldPos.copy(this.worldPosition),this.lastWorldRotation.copy(this.worldQuaternion),this._needsUpdate=!0,this._model&&this._model.updateIsOwned()}onDisable(){this._model&&this._model.freeOwnership()}receivedUpdate=!1;lastWorldPos;lastWorldRotation;onBeforeRender(){if(!this.activeAndEnabled||!this.context.connection.isConnected)return;if(!this.context.connection.isInRoom||!this._model){Bi&&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;if(this._model.isOwned&&!this.receivedUpdate){let r=e.distanceTo(this.lastWorldPos),s=t.angleTo(this.lastWorldRotation),a=this._model.hasOwnership||this.fastMode?1e-4:.001;(r>a||s>a)&&(this._model.hasOwnership?this._needsUpdate=!0:(Bi&&console.log(this.guid,"reset because not owned but",this.gameObject.name,this.lastWorldPos),this.worldPosition=this.lastWorldPos,e.copy(this.lastWorldPos),this.worldQuaternion=this.lastWorldRotation,t.copy(this.lastWorldRotation),ne.markDirty(this.gameObject,!0),this._needsUpdate=!1))}if(this._model&&!this._model.hasOwnership&&this._model.isOwned&&this._receivedDataBefore){let s=this._receivedFastUpdate||this.fastMode?.5:.3,a=!1;if(this.interpolatePosition&&this._targetPosition){let c=this.worldPosition;c.lerp(this._targetPosition,s),this.worldPosition=c,a=!0}if(this.interpolateRotation&&this._targetRotation){let c=this.worldQuaternion;c.slerp(this._targetRotation,s),this.worldQuaternion=c,a=!0}a&&ne.markDirty(this.gameObject,!0)}if(this.receivedUpdate=!1,this.lastWorldPos.copy(e),this.lastWorldRotation.copy(t),!this._model)return;if(!this._model||this._model.hasOwnership===void 0||!this._model.hasOwnership){this.rb&&(this.rb.isKinematic=this._model.isOwned??!1,this.rb.setVelocity(0,0,0),this.rb.setBodyFromGameObject());return}this.rb&&(this._wasKinematic!==void 0&&(Bi&&console.log("reset kinematic",this.rb.name,this._wasKinematic),this.rb.isKinematic=this._wasKinematic),this.gameObject.position.distanceTo(new si.Vector3(0,0,0))>1e3&&(Bi&&console.log("RESET",this.name),this.gameObject.position.set(0,1,0),this.rb.setVelocity(0,0,0),this.rb.setBodyFromGameObject()));let n=10,i=this.rb||this.fastMode;if(this._needsUpdate&&(n<=0||n>0&&this.context.time.frameCount%n===0||i)){Bi&&console.log("send update",this.context.connection.connectionId,this.guid,this.gameObject.name,this.gameObject.guid),this.overridePhysics&&this.rb&&this.rb.setBodyFromGameObject(),this._needsUpdate=!1;let r=Yc(this.guid,this,!!i);this.context.connection.sendBinary(r)}}};import*as Q from"three";import{Euler as gb,EventDispatcher as bb,Group as vb,Matrix4 as op,Mesh as yb,MeshBasicMaterial as _b,Object3D as rp,Quaternion as od,RingGeometry as Eb,Vector3 as sp}from"three";var Ba=class{static createButton(e,t={}){let n=document.createElement("button");function i(){if(t.domOverlay===void 0){var c=document.createElement("div");c.style.display="none",document.body.appendChild(c);var d=document.createElementNS("http://www.w3.org/2000/svg","svg");d.setAttribute("width",38),d.setAttribute("height",38),d.style.position="absolute",d.style.right="20px",d.style.top="20px",d.addEventListener("click",function(){u.end()}),c.appendChild(d);var l=document.createElementNS("http://www.w3.org/2000/svg","path");l.setAttribute("d","M 12,12 L 28,28 M 28,12 12,28"),l.setAttribute("stroke","#fff"),l.setAttribute("stroke-width",2),d.appendChild(l),t.optionalFeatures===void 0&&(t.optionalFeatures=[]),t.optionalFeatures.push("dom-overlay"),t.domOverlay={root:c}}t.optionalFeatures===void 0&&(t.optionalFeatures=[]),t.optionalFeatures.push("local-floor"),t.optionalFeatures.push("hand-tracking"),t.optionalFeatures.push("layers");let u=null;async function h(_){_.addEventListener("end",b),await e.xr.setSession(_),n.textContent="STOP AR",t.domOverlay.root.style.display="",u=_}function b(){u.removeEventListener("end",b),n.textContent="START AR",t.domOverlay.root.style.display="none",u=null}n.style.display="",n.style.cursor="pointer",n.style.left="calc(50% - 50px)",n.style.width="100px",n.textContent="START AR",n.onmouseenter=function(){n.style.opacity="1.0"},n.onmouseleave=function(){n.style.opacity="0.5"},n.onclick=function(){u===null?navigator.xr.requestSession("immersive-ar",t).then(h):u.end()}}function r(){n.disabled=!0,n.style.display="",n.style.cursor="auto",n.style.left="calc(50% - 75px)",n.style.width="150px",n.onmouseenter=null,n.onmouseleave=null,n.onclick=null}function s(){r(),n.textContent="AR NOT SUPPORTED"}function a(c){c.style.position="absolute",c.style.bottom="20px",c.style.padding="12px 6px",c.style.border="1px solid #fff",c.style.borderRadius="4px",c.style.background="rgba(0,0,0,0.1)",c.style.color="#fff",c.style.font="normal 13px sans-serif",c.style.textAlign="center",c.style.opacity="0.5",c.style.outline="none",c.style.zIndex="999"}if("xr"in navigator)return n.id="ARButton",n.style.display="none",a(n),navigator.xr.isSessionSupported("immersive-ar").then(function(c){c?i():s()}).catch(s),n;{let c=document.createElement("a");return window.isSecureContext===!1?(c.href=document.location.href.replace(/^http:/,"https:"),c.innerHTML="WEBXR NEEDS HTTPS"):(c.href="https://immersiveweb.dev/",c.innerHTML="WEBXR NOT AVAILABLE"),c.style.left="calc(50% - 90px)",c.style.width="180px",c.style.textDecoration="none",a(c),c}}};var Ua=class{static createButton(e,t){t&&console.error('THREE.VRButton: The "options" parameter has been removed. Please set the reference space type via renderer.xr.setReferenceSpaceType() instead.');let n=document.createElement("button");function i(){let c=null;async function d(u){u.addEventListener("end",l),await e.xr.setSession(u),n.textContent="EXIT VR",c=u}function l(){c.removeEventListener("end",l),n.textContent="ENTER VR",c=null}n.style.display="",n.style.cursor="pointer",n.style.left="calc(50% - 50px)",n.style.width="100px",n.textContent="ENTER VR",n.onmouseenter=function(){n.style.opacity="1.0"},n.onmouseleave=function(){n.style.opacity="0.5"},n.onclick=function(){if(c===null){let u={optionalFeatures:["local-floor","bounded-floor","hand-tracking","high-fixed-foveation-level","layers"]};navigator.xr.requestSession("immersive-vr",u).then(d)}else c.end()}}function r(){n.disabled=!0,n.style.display="",n.style.cursor="auto",n.style.left="calc(50% - 75px)",n.style.width="150px",n.onmouseenter=null,n.onmouseleave=null,n.onclick=null}function s(){r(),n.textContent="VR NOT SUPPORTED"}function a(c){c.style.position="absolute",c.style.bottom="20px",c.style.padding="12px 6px",c.style.border="1px solid #fff",c.style.borderRadius="4px",c.style.background="rgba(0,0,0,0.1)",c.style.color="#fff",c.style.font="normal 13px sans-serif",c.style.textAlign="center",c.style.opacity="0.5",c.style.outline="none",c.style.zIndex="999"}if("xr"in navigator)return n.id="VRButton",n.style.display="none",a(n),navigator.xr.isSessionSupported("immersive-vr").then(function(c){c?i():s(),Ua.xrSessionIsGranted&&(console.log("XR session is granted - will enter immersive web now"),n.click())}),n;{let c=document.createElement("a");return window.isSecureContext===!1?(c.href=document.location.href.replace(/^http:/,"https:"),c.innerHTML="WEBXR NEEDS HTTPS"):(c.href="https://immersiveweb.dev/",c.innerHTML="WEBXR NOT AVAILABLE"),c.style.left="calc(50% - 90px)",c.style.width="180px",c.style.textDecoration="none",a(c),c}}static registerSessionGrantedListener(){if("xr"in navigator)try{navigator.xr.addEventListener("sessiongranted",()=>{console.log("Received session granted event"),Ua.xrSessionIsGranted=!0})}catch(e){console.error(e)}}},Co=Ua;j(Co,"xrSessionIsGranted",!1);Co.registerSessionGrantedListener();import*as Ga from"three";var Yh=ks(aa(),1);import{AudioAnalyser as Wg}from"three";var To="noVoip",Ze=I("debugvoip"),Xg=I("voip");var Kc=class{id;constructor(e){this.id=e}};var Jc=class{peer;voip;userId;peerId;call=null;callErrorListener=null;stream=null;constructor(e,t,n,i){this.voip=e,this.peer=t,this.userId=n,this.peerId=i}close(){Ze&&console.log("close voip call"),this.callErrorListener&&this.peer.off("error",this.callErrorListener),this.call&&this.call.open&&this.call.close(),this.stream?.getTracks().forEach(function(e){e.stop()})}updateMute(e){if(!this.stream)return;let t=this.stream?.getAudioTracks();for(let n of t)n.enabled=!e}async startVoipCall(){if(!await Fe.HasMicrophonePermissions()){console.warn("no permission to use microphone, can not start call");return}Ze&&console.log("start voip call"),this.stream=await navigator.mediaDevices.getUserMedia({audio:!0,video:!1}),this.updateMute(this.voip.muteOutput),Ze&&console.log(this.stream),this.call=this.peer.call(this.peerId,this.stream,{metadata:{userId:this.userId}}),this.call.on("error",t=>{console.error(t)}),this.call.on("stream",t=>{Ze&&console.log("received stream from remote again",t)}),this.peer.on("close",this.onCallClose.bind(this)),this.callErrorListener=t=>{t.message.includes(this.peerId)?(console.log("Could not connect to "+this.peerId),this.callErrorListener&&this.peer.off("error",this.callErrorListener),this.call&&this.call.close(),this.stream?.getTracks().forEach(function(n){n.stop()}),this.stream=null):console.error(t)},this.peer.on("error",this.callErrorListener)}onCallClose(e){Ze&&console.log("call closed",e)}},Zc=class{get currentStream(){return this.stream}get currentAudio(){return this.audio}get currentAnalyzer(){return this.analyzer}voip;call;audio=null;stream=null;obj;analyzer=null;waitingForStart=!1;closed=!1;audioElement=null;constructor(e,t,n){this.voip=e,this.obj=t,this.call=n}openAudioStream(e){let t=e.getAudioTracks();for(let n of t)if(n.kind==="audio"&&n.readyState==="live"){this.open(n);return}console.warn("failed finding valid audio stream to begin call")}open(e){console.assert(e.kind==="audio","invalid track kind, expected audio but received "+e.kind),!this.waitingForStart&&(this.waitingForStart=!0,Z.userInteractionRegistered||Ze&&console.log("Incoming call, waiting for user interaction before opening audio"),Z.registerWaitForAllowAudio(async()=>{if(this.call.open&&!this.closed){Ze&&console.log("Setup audio and begin listening"),this.stream=new MediaStream([e]);let t=new Ga.AudioListener;this.audio=new Ga.Audio(t),this.audio.setVolume(this.voip.muteInput?0:1),this.audio.setMediaStreamSource(this.stream);let n=document.createElement("audio");this.audioElement=n,n.style.display="none",document.body.appendChild(n),n.srcObject=this.stream,n.sinkId!==void 0&&navigator.mediaDevices.enumerateDevices().then(i=>{if(!!n){console.log(i);for(let r of i)if(r.label==="Speakerphone"){n.sinkId=r.deviceId;break}}}),Ze&&console.log("call is setup, you should hear something now"),this.analyzer=new Wg(this.audio,32)}}))}close(){this.closed=!0,this.call?.open&&this.call.close(),this.audio?.disconnect(),this.stream?.getTracks().forEach(e=>{e.stop()}),this.stream=null,this.audioElement&&this.audioElement.remove()}},Fe=class extends O{requireParam=!1;set muteInput(e){if(e===this._inputMuted||(this._inputMuted=e,!this.currentIncomingCalls))return;let t=this._inputMuted?0:1;for(let n in this.currentIncomingCalls)this.currentIncomingCalls[n]?.currentAudio?.setVolume(t)}get muteInput(){return this._inputMuted}set muteOutput(e){if(e!==this._outputMuted&&(this._outputMuted=e,!!this.connections))for(let t in this.connections)this.connections[t]?.updateMute(e)}get muteOutput(){return this._outputMuted}getFrequency(e){if(e===null){for(let n in this.currentIncomingCalls){let i=this.currentIncomingCalls[n];if(i&&i.currentAnalyzer)return i.currentAnalyzer.getAverageFrequency()}return null}let t=this.currentIncomingCalls[e];return t&&t.currentAnalyzer?t.currentAnalyzer.getAverageFrequency():null}peer=null;model=null;connections={};currentIncomingCalls={};_inputMuted=!1;_outputMuted=!1;awake(){if(I(To)){console.log("VOIP is disabled by url parameter: "+To);return}if(this.requireParam&&!Xg){console.debug("VOIP must be enabled explicitly by url parameter");return}this.peer=new Yh.default,navigator.getUserMedia=navigator.getUserMedia||navigator.webkitGetUserMedia||navigator.mozGetUserMedia||navigator.msGetUserMedia,this.context.connection.beginListen("joined-room",e=>{navigator.mediaDevices.getUserMedia({audio:!0,video:!1})}),this.context.connection.beginListen("peer-update-id",e=>{if(e.id!==this.context.connection.connectionId){let t=this.connections[e.id];if(t&&t.close(),this.peer&&this.context.connection.connectionId){let n=new Jc(this,this.peer,this.context.connection.connectionId,e.peerId);this.connections[e.id]=n,n.startVoipCall()}}}),this.context.connection.beginListen("user-left-room",e=>{let{userId:t}=e,n=this.connections[t];this.connections[t]=null,n&&n.close();let i=this.currentIncomingCalls[t];Ze&&console.log("UserLeftRoom",e,t,i),i&&(i.close(),this.currentIncomingCalls[t]=null)}),this.peer.on("open",this.onOpenPeerConnection.bind(this))}onEnable(){}onDisable(){console.log("TODO: close all");for(let e in this.currentIncomingCalls)this.currentIncomingCalls[e]?.close(),this.connections[e]?.close()}async onOpenPeerConnection(e){Ze&&console.log("Peer connection established and received id"),this.model=new Kc(e),this.context.connection.send("peer-update-id",this.model,1),this.peer&&(this.peer.on("call",this.onReceiveCall.bind(this)),this.peer.on("connection",function(t){Ze&&console.log("CONNECTION",t),t.on("data",function(n){Ze&&console.log("Received",n)})}))}async onReceiveCall(e){let{metadata:t}=e;console.assert(t.userId);let{userId:n}=t,{peer:i}=e,r=this.currentIncomingCalls[n];if(r&&r.close(),Ze&&console.log("received call"),await Fe.HasMicrophonePermissions()){let s=await navigator.mediaDevices.getUserMedia({audio:!0,video:!1});e.answer(s)}else e.answer(null);this.currentIncomingCalls[n]=new Zc(this,this.gameObject,e),e.on("stream",s=>{Ze&&console.log("receive caller stream, will setup audio now"),this.currentIncomingCalls[n]?.openAudioStream(s)}),e.on("error",console.error)}static async HasMicrophonePermissions(){return(await navigator.permissions.query({name:"microphone"})).state!=="denied"}};import{Matrix4 as hs}from"three";var mt=class extends O{webAR=null;get rig(){return this.webAR?.webxr.Rig}invertForward=!1;get arScale(){return this._arScale}set arScale(e){e!==this._arScale&&(this._arScale=e,this.setScale(e))}_initalMatrix=new hs;_selectStartFn=this.onSelectStart.bind(this);_selectEndFn=this.onSelectEnd.bind(this);start(){let e=R.findObjectOfType(G);e&&(e.Rig.updateMatrix(),this._initalMatrix.copy(e.Rig.matrix))}_arScale=5;_rig=null;_startPose=null;_placementPose=null;_isTouching=!1;_rigStartPose=null;onBegin(e){this._placementPose=null,this.gameObject.visible=!1,this.gameObject.matrixAutoUpdate=!1,this._startPose=this.gameObject.matrix.clone(),this._rigStartPose=this.rig?.matrix.clone(),e.addEventListener("selectstart",this._selectStartFn),e.addEventListener("selectend",this._selectEndFn),this.gameObject.visible=!1,this.rig&&(this.rig.matrixAutoUpdate=!0,this._initalMatrix.decompose(this.rig.position,this.rig.quaternion,this.rig.scale))}onUpdate(e,t,n){return n&&!this._placementPose&&this._isTouching?(this.webAR&&this.webAR.setReticleActive(!1),this.placeAt(e,new hs().fromArray(n.transform.matrix).invert()),!0):!1}placeAt(e,t){if(this._placementPose||(this._placementPose=new hs),this._placementPose.copy(t),e){if(this.invertForward){let n=new hs().makeRotationY(Math.PI);this._placementPose.premultiply(n)}this._rig=e,this.setScale(this.arScale)}else this._rig=null;this.gameObject.visible=!0}onEnd(e,t){this._placementPose=null,this.gameObject.visible=!1,this.gameObject.matrixAutoUpdate=!1,this._startPose&&this.gameObject.matrix.copy(this._startPose),e&&(e.matrixAutoUpdate=!0,this._rigStartPose&&this._rigStartPose.decompose(e.position,e.quaternion,e.scale)),ne.markDirty(this.gameObject,!0),setTimeout(()=>{this.gameObject.matrixAutoUpdate=!0,this.gameObject.visible=!0},100)}onSelectStart(){this._isTouching=!0}onSelectEnd(){this._isTouching=!1}setScale(e){let t=this._rig;!t||!this._placementPose||(this._rigStartPose||(this._rigStartPose=t.matrix.clone()),t.matrixAutoUpdate=!1,t.matrix.multiplyMatrices(new hs().makeScale(e,e,e),this._placementPose),t.matrix.decompose(t.position,t.quaternion,t.scale),t.updateMatrixWorld(),console.log("Place",t.position))}};x([w()],mt.prototype,"invertForward",2),x([w()],mt.prototype,"arScale",1);import{BoxHelper as eb,BufferGeometry as tb,Color as tp,Euler as nb,Layers as ib,Line as rb,Mesh as ob,MeshBasicMaterial as sb,Quaternion as Na,Ray as ab,SphereGeometry as lb,Vector2 as cb,Vector3 as Zt}from"three";import{OculusHandModel as db}from"three/examples/jsm/webxr/OculusHandModel.js";import{OculusHandPointerModel as ub}from"three/examples/jsm/webxr/OculusHandPointerModel.js";import{XRControllerModelFactory as hb}from"three/examples/jsm/webxr/XRControllerModelFactory.js";import{GLTFLoader as pb}from"three/examples/jsm/loaders/GLTFLoader.js";import*as Zh from"three";import{Quaternion as Qg,Vector3 as Va}from"three";var Ro=I("debugflags");var $c=class{Mask=17;Has(e){let t=this.Mask&e;return Ro&&console.log("HAS",e,this.Mask,"Result="+t),t!==0}Set(e){this.Mask=e,pe.Apply()}Enable(e){this.Mask|=e,pe.Apply()}Disable(e){this.Mask&=~e,pe.Apply()}Toggle(e){this.Mask^=e,pe.Apply()}EnableAll(){this.Mask=-1,pe.Apply()}DisableAll(){this.Mask=0,pe.Apply()}},$e=$c;j($e,"Global",new $c);var En=class extends O{static Apply(){for(let e of this.registry)e.UpdateVisible($e.Global)}awake(){En.registry.push(this)}onEnable(){En.firstApply||(En.firstApply=!0,En.Apply())}onDestroy(){let e=En.registry.indexOf(this);e>=0&&En.registry.splice(e,1)}visibleIn;get isOn(){return this.gameObject.visible}UpdateVisible(e=null){if(!this.enabled)return;let t,n=e;n&&typeof n=="number"&&(console.assert(typeof n=="number","XRFlag.UpdateVisible: state must be a number",n),Ro&&console.log(n),En.buffer.Mask=n,e=En.buffer);let i=e;if(i?(Ro&&console.log("use passed in mask"),t=i.Has(this.visibleIn)):(Ro&&console.log("use global mask"),$e.Global.Has(this.visibleIn)),t!==void 0)if(t)Ro&&console.trace("is visible",this.name,this.gameObject.uuid),R.setActive(this.gameObject,!0);else{if(Ro&&console.trace("is not visible",this.name,this.gameObject.uuid),!this.gameObject.visible)return;this.gameObject.visible=!1}}},pe=En;j(pe,"registry",[]),j(pe,"firstApply"),j(pe,"buffer",new $e);import{Object3D as ed}from"three";var Ui=I("debugavatar"),Kt=class extends O{static getAvatar(e){return e>=0&&e<Kt.instances.length?Kt.instances[e]:null}static onAvatarMarkerCreated(e){return Kt._onNewAvatarMarkerAdded.push(e),e}static onAvatarMarkerDestroyed(e){return Kt._onAvatarMarkerDestroyed.push(e),e}connectionId;avatar;awake(){Kt.instances.push(this),Ui&&console.log(this);for(let e of Kt._onNewAvatarMarkerAdded)e({avatarMarker:this,gameObject:this.gameObject})}onDestroy(){Kt.instances.splice(Kt.instances.indexOf(this),1);for(let e of Kt._onAvatarMarkerDestroyed)e({avatarMarker:this,gameObject:this.gameObject})}isLocalAvatar(){return this.connectionId===this.context.connection.connectionId}setVisible(e){this.avatar&&("setVisible"in this.avatar?this.avatar.setVisible(e):R.setActive(this.avatar,e))}},ie=Kt;j(ie,"instances",[]),j(ie,"_onNewAvatarMarkerAdded",[]),j(ie,"_onAvatarMarkerDestroyed",[]);var ps=class{_isVisible=!0;setVisible(e){this._isVisible=e,this.updateVisibility()}get isWebXRAvatar(){return!0}guid;root=null;head=null;handLeft=null;handRight=null;lastUpdate=-1;isLocalAvatar=!1;flags=null;headScale=new Va(1,1,1);handLeftScale=new Va(1,1,1);handRightScale=new Va(1,1,1);webxr;lastAvatarId=null;hasAvatarOverride=!1;context;avatarMarker=null;constructor(e,t,n){this.context=e,this.guid=t,this.webxr=n,this.setupCustomAvatar(this.webxr.defaultAvatar)}updateFlags(){if(!this.flags)return;let e=this.isLocalAvatar?8:16;for(let t of this.flags)t.gameObject.visible=!0,t.UpdateVisible(e)}async setAvatarOverride(e){return this.hasAvatarOverride=e!==null,this.hasAvatarOverride&&this.lastAvatarId!==e&&(this.lastAvatarId=e,e!=null&&e.length>0)?await this.setupCustomAvatar(e):null}_headTarget=new ed;_handLeftTarget=new ed;_handRightTarget=new ed;_canInterpolate=!1;tryUpdate(e,t){if(e.guid===this.guid&&(this.lastAvatarId!==e.avatarId&&e.avatarId&&e.avatarId.length>0&&(this.lastAvatarId=e.avatarId,this.setupCustomAvatar(e.avatarId)),this.lastUpdate=e.time,this.head)){let n=this.webxr.IsInAR?"handheld":"headset",i=this.head;this.context.players.setPlayerView(e.guid,i,n),ne.markDirty(this.head),this._canInterpolate=!0;let r=this.isLocalAvatar?this.head:this._headTarget;if(r.position.set(e.position.x,e.position.y,e.position.z),r.quaternion.set(e.rotation.x,e.rotation.y,e.rotation.z,e.rotation.w),r.scale.set(e.scale,e.scale,e.scale),r.scale.multiply(this.headScale),this.handLeft){let s=this.isLocalAvatar?this.handLeft:this._handLeftTarget;s.position.set(e.posLeftHand.x,e.posLeftHand.y,e.posLeftHand.z),s.quaternion.set(e.rotLeftHand._x,e.rotLeftHand._y,e.rotLeftHand._z,e.rotLeftHand._w),s.quaternion.multiply(ps.invertRotation),s.scale.set(e.scale,e.scale,e.scale),s.scale.multiply(this.handLeftScale),ne.markDirty(this.handLeft)}if(this.handRight){let s=this.isLocalAvatar?this.handRight:this._handRightTarget;s.position.set(e.posRightHand.x,e.posRightHand.y,e.posRightHand.z),s.quaternion.set(e.rotRightHand._x,e.rotRightHand._y,e.rotRightHand._z,e.rotRightHand._w),s.quaternion.multiply(ps.invertRotation),s.scale.set(e.scale,e.scale,e.scale),s.scale.multiply(this.handRightScale),ne.markDirty(this.handRight)}}}update(){if(this.isLocalAvatar||!this._canInterpolate)return;let e=this.context.time.deltaTime/.1;this.head&&(this.head.position.lerp(this._headTarget.position,e),this.head.quaternion.slerp(this._headTarget.quaternion,e),this.head.scale.lerp(this._headTarget.scale,e)),this.handLeft&&this._handLeftTarget&&(this.handLeft.position.lerp(this._handLeftTarget.position,e),this.handLeft.quaternion.slerp(this._handLeftTarget.quaternion,e),this.handLeft.scale.lerp(this._handLeftTarget.scale,e)),this.handRight&&this._handRightTarget&&(this.handRight.position.lerp(this._handRightTarget.position,e),this.handRight.quaternion.slerp(this._handRightTarget.quaternion,e),this.handRight.scale.lerp(this._handRightTarget.scale,e))}destroy(){Ui&&console.log("Destroy avatar",this.guid),this.root?.removeFromParent(),this.avatarMarker?.destroy(),this.lastAvatarId=null,this.head&&ue.Remove(this.context,this.head)}updateVisibility(){let e=this.root;e&&R.setActive(e,this._isVisible)}async setupCustomAvatar(e){if(Ui&&console.log("LOAD",e,this),!e||typeof e=="string"&&e.length<=0)return!1;this.head&&ue.Remove(this.context,this.head);let t=e;if(t?.loadAssetAsync!==void 0){await t.loadAssetAsync();let i=t.asset;R.setActive(i,!1),e=R.instantiate(i),R.setActive(e,!0)}Ui&&console.log(e);let n=await ps.loader.getOrCreateNewAvatarInstance(this.context,e);if(Ui&&console.log(n,n?.isValid,this.lastAvatarId,e),n?.isValid){if(this.root=n.root,this.root.position.set(0,0,0),this.root.quaternion.set(0,0,0,1),this.root.scale.set(1,1,1),this.avatarMarker=R.addNewComponent(this.root,ie),this.avatarMarker.connectionId=this.guid,this.avatarMarker.avatar=this,this.head&&this.head!==n.head&&this.head?.removeFromParent(),this.head=n.head,this.headScale.copy(this.head.scale),this.head&&!this.isLocalAvatar&&ue.Add(this.context,this.head,this.avatarMarker),n.leftHand&&this.handLeft?.removeFromParent(),this.handLeft=n.leftHand??this.handLeft,this.handLeft?this.handLeftScale.copy(this.handLeft.scale):this.handLeftScale.set(1,1,1),n.rigthHand&&this.handRight?.removeFromParent(),this.handRight=n.rigthHand??this.handRight,this.handRight?this.handRightScale.copy(this.handRight.scale):this.handRightScale.set(1,1,1),this.context.scene.add(this.root),this.flags==null&&(this.flags=[]),this.flags.length=0,this.flags.push(...R.getComponentsInChildren(this.root,pe)),this.flags.length<=0&&this.head){let i=R.addNewComponent(this.head,pe);i.visibleIn=20,this.flags.push(i),Ui&&console.log("Added flag to head: "+i.visibleIn,this.head.name)}return Ui&&console.log("[Avatar], is Local? ",this.isLocalAvatar,this.root),this.updateFlags(),this.updateVisibility(),!0}else return Ui&&console.warn("build avatar failed"),!1}},gt=ps;j(gt,"loader",new ii),j(gt,"invertRotation",new Qg().setFromAxisAngle(new Va(0,1,0),Math.PI));var ue=class{static Add(e,t,n=null){if(!!t){for(let i of this.Pois)if(i.obj===t)return;this.Pois.push({obj:t,avatar:n}),this.LastChangeTime=e.time.time}}static Remove(e,t){if(!!t){for(let n of this.Pois)if(n.obj===t){this.Pois.splice(this.Pois.indexOf(n),1),this.LastChangeTime=e?.time.time??z.Current?.time.time;return}}}};j(ue,"Pois",[]),j(ue,"LastChangeTime",0);var td=class{guid;position=new Zh.Vector3},wn=class extends O{set controlledTarget(e){this.target=e;let t=M.get("MoveRandom");if(t&&this.target){let n=R.getComponent(this.target,t);n&&n.destroy()}}target=null;avatar=null;_model=null;_targetModel=new td;_currentTargetObject=null;_lastUpdateTime=0;_lookDuration=0;_lastPoiChangedTime=0;awake(){if(this.avatar=R.getComponentInParent(this.gameObject,ie),this.avatar){let e=R.getComponentInParent(this.gameObject,ie);this._model=new Ri(this.context.connection,this.guid),e?.isLocalAvatar&&this._model.requestOwnership()}this.context.connection.beginListen("avatar-look-target-changed",e=>{this.target&&e&&e.guid===this.avatar?.guid&&J(this.target,e.position)})}update(){if((!this.context.connection.isConnected||this._model?.hasOwnership)&&(ue.LastChangeTime!==this._lastPoiChangedTime&&(this._lastPoiChangedTime=ue.LastChangeTime,this._lookDuration=0),this.selectTarget(),this._currentTargetObject&&this.context.time.frameCount%10===0&&this.target)){let t=B(this._currentTargetObject);J(this.target,t),this.context.connection.isConnected&&this.avatar&&(this.context.connection.send("avatar-look-target-changed",this._targetModel),this._targetModel.guid=this.avatar.guid,this._targetModel.position.copy(t))}}selectTarget(){if(this.context.time.time-this._lastUpdateTime>this._lookDuration){this._lastUpdateTime=this.context.time.time,this._lookDuration=Math.random()*.5+.2;let t=ue.Pois;if(t.length>0){let n=t[Math.floor(Math.random()*t.length)];if(n&&n.obj){if(n.avatar&&n.avatar===this.avatar)return;this._currentTargetObject=n.obj}}}}};import*as za from"three-mesh-ui";import{OrbitControls as Yg}from"three/examples/jsm/controls/OrbitControls";import{Object3D as qg}from"three";var xn=class extends O{constraintActive=!0;locked=!1;sources=[]};x([w(qg)],xn.prototype,"sources",2);import*as fs from"three";var $h=I("nocamlimits"),Be=class extends O{get controls(){return this._controls}get controllerObject(){return this._cameraObject}onStartInteraction(e){this.controls?.addEventListener("start",e)}autoRotate=!1;autoRotateSpeed=1;enableKeys=!0;enableDamping=!0;dampingFactor=.1;enableZoom=!0;minZoom=0;maxZoom=1/0;enablePan=!0;lookAtConstraint=null;lookAtConstraint01=1;middleClickToFocus=!0;doubleClickToFocus=!0;useSlerp=!1;debugLog=!1;targetLerpSpeed=5;_lookTargetPosition;_controls=null;_cameraObject=null;_lerpToTargetPosition=!1;_lerpCameraToTarget=!1;_cameraTargetPosition=null;_inputs=0;_enableTime=0;_startedListeningToKeyEvents=!1;awake(){this._lookTargetPosition=new fs.Vector3,this._startedListeningToKeyEvents=!1}onEnable(){this._enableTime=this.context.time.time;let t=R.getComponent(this.gameObject,se)?.cam;this._controls||(console.assert(t!=null,"Missing camera",this),t&&(this._cameraObject=t),this._controls=new Yg(t,this.context.renderer.domElement)),this._controls&&(this._controls.enableDamping=this.enableDamping,this._controls.enableKeys=this.enableKeys,this._controls.autoRotate=this.autoRotate,this._controls.autoRotateSpeed=this.autoRotateSpeed,this._controls.enableZoom=this.enableZoom,t?.type==="PerspectiveCamera"?$h||(this._controls.minDistance=this.minZoom,this._controls.maxDistance=this.maxZoom):$h||(this._controls.minZoom=this.minZoom,this._controls.maxZoom=this.maxZoom),this._controls.dampingFactor=this.dampingFactor,this._controls.enablePan=this.enablePan,this._startedListeningToKeyEvents||(this._startedListeningToKeyEvents=!0,this._controls.listenToKeyEvents(window.document.body)))}onDisable(){this._controls&&(this._controls.enabled=!1,this._controls.autoRotate=!1)}onDestroy(){this._controls?.dispose()}start(){if(this._controls){let e=R.getComponent(this.gameObject,se);if(e&&!this.setFromTargetPosition()){this.debugLog&&console.log("NO TARGET");let t=new fs.Vector3(0,0,-1).applyMatrix4(e.cam.matrixWorld);this.setTarget(t,!0)}}this.startCoroutine(this.startRaycastDelayed())}*startRaycastDelayed(){if(yield,!this.setFromTargetPosition()){let e=new ce;e.screenPoint=new fs.Vector2(0,0),e.lineThreshold=.1;let t=this.context.physics.raycast(e);t.length>0&&this.setTarget(t[0].point,!0)}}onBeforeRender(){if(!this._controls)return;(this.context.input.getPointerDown(0)||this.context.input.getPointerDown(1)||this.context.input.getPointerDown(2))&&(this._inputs+=1),this._inputs>0&&(this._controls.autoRotate=!1,this._lerpCameraToTarget=!1,this._lerpToTargetPosition=!1),this._inputs=0;let e=this.middleClickToFocus&&this.context.input.getPointerClicked(1);if(e||=this.doubleClickToFocus&&this.context.input.getPointerDoubleClicked(0)&&this.context.time.time-this._enableTime>.3,e?this.setTargetFromRaycast():(this.context.input.getPointerDown(0)||this.context.input.mouseWheelChanged)&&(this._lerpToTargetPosition=!1,this._lerpCameraToTarget=!1),this._lerpToTargetPosition||this._lerpCameraToTarget){let t=this.context.time.deltaTime*this.targetLerpSpeed;this._lerpCameraToTarget&&this._cameraTargetPosition&&this._cameraObject&&(this.useSlerp&&typeof this._cameraObject?.position.slerp=="function"?(this._cameraObject?.position).slerp(this._cameraTargetPosition,t):this._cameraObject?.position.lerp(this._cameraTargetPosition,t),this._cameraObject.position.distanceTo(this._cameraTargetPosition)<.01&&(this._lerpCameraToTarget=!1)),this._lerpToTargetPosition&&(this.lerpTarget(this._lookTargetPosition,t),this._lookTargetPosition.distanceTo(this._controls.target)<.005&&(this._lerpToTargetPosition=!1))}this.lookAtConstraint?.locked&&this.setFromTargetPosition(0,this.lookAtConstraint01),this._controls&&!this.context.isInXR&&(this.debugLog&&(this._controls.domElement=this.context.renderer.domElement),this._controls.enabled=!0,this._controls.update())}setCameraTarget(e,t=!1){e?(this._lerpCameraToTarget=!0,this._cameraTargetPosition=e.clone(),t&&this._cameraTargetPosition&&this.controllerObject?.position.copy(this._cameraTargetPosition)):this._lerpCameraToTarget=!1}setFromTargetPosition(e=0,t=1){if(!this._controls)return!1;let n=this.lookAtConstraint?.sources;if(n&&n.length>0){let i=n[e];if(i)return i.getWorldPosition(this._lookTargetPosition),this.lerpTarget(this._lookTargetPosition,t),!0}return!1}setTarget(e=null,t=!1){!this._controls||(e!==null&&this._lookTargetPosition.copy(e),t?this._controls.target.copy(this._lookTargetPosition):this._lerpToTargetPosition=!0)}lerpTarget(e,t){!this._controls||this._controls.target.lerp(e,t)}distanceToTarget(e){return this._controls?this._controls.target.distanceTo(e):-1}setTargetFromRaycast(){if(!this.controls)return;let e=this.context.physics.raycast();for(let t of e)if(t.distance>0&&R.isActiveInHierarchy(t.object)){if(this._lookTargetPosition.copy(t.point),this._lerpToTargetPosition=!0,this._cameraTargetPosition=null,this.context.mainCamera){this._lerpCameraToTarget=!0;let n=B(this.context.mainCamera);this._cameraTargetPosition=n.clone().sub(this.controls.target).add(this._lookTargetPosition)}break}}};x([w(xn)],Be.prototype,"lookAtConstraint",2);var Dt=class{used=!1;Use(){this.used=!0}StopPropagation(){this.event?.stopImmediatePropagation()}inputSource;object;isDown;isUp;isPressed;isClicked;event;constructor(e){this.event=e}};import{Object3D as Jg}from"three";var Zg=I("debugeventsystem"),Cn=class extends O{static createIfNoneExists(e){this.didSearchEventSystem||(this.didSearchEventSystem=!0,Cn.systems.length<=0&&Cn.systems.push(...R.findObjectsOfType(Cn,e)));for(let n of Cn.systems)if(n.context===e)return;let t=new Jg;R.addNewComponent(t,Cn),e.scene.add(t)}static ensureUpdateMeshUI(e,t){Jt.update(e,t)}static markUIDirty(e){Jt.markDirty()}static get instance(){return this.systems[0]}orbitControl=null;orbitControlWasEnabled=!1;raycaster=[];constructor(){super(),Cn.systems.push(this)}onDestroy(){Cn.systems.splice(Cn.systems.indexOf(this),1)}start(){}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)}_selectStartFn;_selectEndFn;_selectUpdateFn;onEnable(){let e=new Map;this._selectStartFn??=(n,i)=>{if(!i.grab)return;Jt.resetLastSelected();let r=new Dt;r.inputSource=n,r.isDown=n.selectionDown,r.isUp=n.selectionUp,r.isPressed=n.selectionPressed,r.isClicked=!1,e.set(n,i.grab),i.grab&&!this.handleEvents(i.grab,r)&&(i.grab=null)},this._selectEndFn??=(n,i)=>{if(!i.grab)return;let r=new Dt;r.inputSource=n,r.isDown=n.selectionDown,r.isUp=n.selectionUp,r.isPressed=n.selectionPressed,r.isClicked=n.selectionClick,this.handleEvents(i.grab,r);let s=e.get(n);if(e.set(n,null),s)for(let a=0;a<this.raisedPointerDownEvents.length;a++){let c=this.raisedPointerDownEvents[a];this.raisedPointerDownObjects[a]===s&&c&&(c.onPointerUp?.call(c,r),this.raisedPointerDownEvents.splice(a,1),this.raisedPointerDownObjects.splice(a,1),a--)}};let t=new ce;this._selectUpdateFn??=n=>{t.ray=n.getRay();let i=this.performRaycast(t);if(!i)return;let r=new Dt;r.inputSource=n,this.handleIntersections(i,r)},Y.addEventListener("select-start",this._selectStartFn),Y.addEventListener("select-end",this._selectEndFn),Y.addEventListener("update",this._selectUpdateFn),this.context.pre_update_callbacks.push(this.onBeforeUpdate.bind(this)),this.context.input.addEventListener("pointerdown",this.onPointerDown.bind(this))}onDisable(){Y.removeEventListener("select-start",this._selectStartFn),Y.removeEventListener("select-end",this._selectEndFn),Y.removeEventListener("update",this._selectUpdateFn)}onPointerDown(){this.onBeforeUpdate()}lastPointerEvent=null;objectsHoveredThisFrame=[];objectsHoveredLastFrame=[];raisedPointerDownEvents=[];raisedPointerDownObjects=[];_didMove=!1;onBeforeUpdate(){if(this.objectsHoveredThisFrame.length=0,this.resetMeshUIStates(),G.IsInWebXR||this.context.input.isKeyPressed("Alt"))return;if(!this._didMove){let r=this.context.input.getPointerPositionRC(0);if(r&&r.x===0&&r.y===0)return;this._didMove=!0}let e=this.performRaycast(null),t=new Dt(this.context.input.getPointerEvent(0));if(t.inputSource=this.context.input,t.isClicked=this.context.input.mouseClick,t.isDown=this.context.input.mouseDown,t.isUp=this.context.input.mouseUp,t.isPressed=this.context.input.mousePressed,this.lastPointerEvent=t,!e)return;let n=null,i=null;this.context.input.mouseDown&&this.currentActiveMeshUIComponents.length>0&&this.context.mainCameraComponent&&(n=R.getComponent(this.context.mainCameraComponent.gameObject,Be)??null,n&&(i=n.enabled,n.enabled=!1)),this.handleIntersections(e,t),n&&(this.orbitControl=n,this.orbitControl?.enabled?(this.orbitControlWasEnabled=this.orbitControl.enabled,this.orbitControl.enabled=!1):this.orbitControl&&!this.context.input.mousePressed&&(this.orbitControl.enabled=this.orbitControlWasEnabled,this.orbitControl=null))}_tempComponentsArray=[];onBeforeRender(){if(this.lastPointerEvent)this.lastPointerEvent.used=!1;else return;if(this.lastPointerEvent.isUp){for(let t of this.raisedPointerDownEvents)t.onPointerUp&&t.onPointerUp(this.lastPointerEvent);this.raisedPointerDownEvents.length=0,this.raisedPointerDownObjects.length=0}for(let t of this.objectsHoveredLastFrame)if(this.objectsHoveredThisFrame.indexOf(t)<0){this._tempComponentsArray.length=0;let n=R.getComponentsInParent(t,O,this._tempComponentsArray);this.lastPointerEvent.object=t;for(let i=0;i<n.length;i++){let r=n[i];if(!r.gameObject||r.destroyed)continue;let s=r;s.onPointerExit&&s.onPointerExit(this.lastPointerEvent)}}let e=this.objectsHoveredLastFrame;this.objectsHoveredLastFrame=this.objectsHoveredThisFrame,this.objectsHoveredThisFrame=e}_sortedHits=[];performRaycast(e){if(!this.raycaster)return null;this._sortedHits.length=0;for(let t of this.raycaster){if(!t.activeAndEnabled)continue;let n=t.performRaycast(e);n&&n.length>0&&this._sortedHits.push(...n)}return this._sortedHits.sort((t,n)=>t.distance-n.distance),this._sortedHits}handleIntersections(e,t){if(!e||e.length<=0)return!1;e=this.sortCandidates(e);for(let n of e){let{object:i}=n;if(this.handleEvents(i,t))return!0}return!1}_sortingBuffer=[];_noDepthTestingResults=[];sortCandidates(e){this._sortingBuffer.length=0,this._noDepthTestingResults.length=0;for(let t=0;t<e.length;t++){let n=e[t],i=n.object;if(i.material&&i.material.depthTest===!1){this._noDepthTestingResults.push(n);continue}this._sortingBuffer.push(n)}for(let t of this._sortingBuffer)this._noDepthTestingResults.push(t);return this._noDepthTestingResults}handleEventsArray=[];out={};handleEvents(e,t){if(!this.testIsVisible(e))return t.isClicked&&Zg&&console.log("not allowed",e),!1;let n=e;t.object=e,this.lastPointerEvent=t;let i=e.parent,r=!1,s=t.isClicked??!1,a=null;if(i&&i.isUI){let c=(t.isPressed||t.isClicked)??!1;if(i[bt]){let d=i[bt].gameObject;if(d){if(!At.isInteractable(d,this.out))return this.out.canvasGroup?.interactable??!1;a=this.out.canvasGroup??null;let u=this.handleMeshUIIntersection(e,c);e=d,r=!0}}if(!r&&this.handleMeshUiObjectWithoutShadowDom(i,c))return!0}if(this.objectsHoveredThisFrame.push(e),a===null||a.interactable){let c=this.objectsHoveredLastFrame.indexOf(e)>=0;this.handleEventsArray.length=0;let d=R.getComponentsInParent(e,O,this.handleEventsArray);for(let l=0;l<d.length;l++){if(t.used)return!0;if(d[l].destroyed)continue;let u=d[l];u.interactable!==!1&&(u.onPointerEnter&&(c||u.onPointerEnter(t)),t.isDown&&u.onPointerDown&&!this.raisedPointerDownEvents.includes(u)&&(u.onPointerDown(t),this.raisedPointerDownEvents.push(u),this.raisedPointerDownObjects.push(n)),t.isUp&&u.onPointerUp&&u.onPointerUp(t),t.isClicked&&u.onPointerClick&&u.onPointerClick(t))}}return!0}handleMeshUiObjectWithoutShadowDom(e,t){return!e||!e.isUI?!0:this.handleMeshUIIntersection(e,t)}currentActiveMeshUIComponents=[];handleMeshUIIntersection(e,t){let n=Jt.updateState(e,t);return n&&this.currentActiveMeshUIComponents.push(n),n!==null}resetMeshUIStates(){if(this.context.input.getPointerPressedCount()>0&&Jt.resetLastSelected(),!(!this.currentActiveMeshUIComponents||this.currentActiveMeshUIComponents.length<=0)){for(let e=0;e<this.currentActiveMeshUIComponents.length;e++){let t=this.currentActiveMeshUIComponents[e];Jt.resetState(t)}this.currentActiveMeshUIComponents.length=0}}testIsVisible(e){return e?R.isActiveSelf(e)?this.testIsVisible(e.parent):!1:!0}},Me=Cn;j(Me,"didSearchEventSystem",!1),j(Me,"systems",[]);var Jt=class{static markDirty(){this.needsUpdate=!0}static update(e,t){for(let n of this.lastUpdateFrame)if(n.context===t){if(t.time.frameCount===n.frame)return;n.frame=t.time.frameCount,(this.needsUpdate||t.time.frameCount<30)&&(this.needsUpdate=!1,e.update());return}this.lastUpdateFrame=[{context:t,frame:t.time.frameCount}],e.update()}static updateState(e,t){let n=null;if(e&&(n=this.findBlockInParent(e),n&&n!==this.lastSelected)){if(n.interactable===!1)return null;t?(this.lastSelected=n,n.states.pressed&&n.setState("pressed")):n.states.hovered&&n.setState("hovered"),this.needsUpdate=!0}return n}static resetLastSelected(){let e=this.lastSelected;!e||(this.lastSelected=null,this.resetState(e))}static resetState(e){if(!e)return;e.interactable===!1?e.states.disabled&&e.setState("disabled"):e===this.lastSelected&&e.states.selected?e.setState("selected"):e.setState("normal"),this.needsUpdate=!0}static findBlockInParent(e){return e?e.isBlock&&Object.keys(e.states).length>0?e:this.findBlockInParent(e.parent):null}};j(Jt,"lastSelected",null),j(Jt,"lastUpdateFrame",[]),j(Jt,"needsUpdate",!1);import{AxesHelper as $g}from"three";var So="./include";za.Block.prototype.interactable={get(){return this.interactive},set(o){this.interactable=o}};var bt=Symbol("shadowDomOwner"),Te=class extends O{isRoot(){return this.Root?.gameObject===this.gameObject}markDirty(){Me.markUIDirty(this.context)}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=R.getComponentInParent(this.gameObject,Tn)),this._root}_parentComponent=void 0;onEnable(){super.onEnable()}addShadowComponent(e,t){this.removeShadowComponent();let n=this.isRoot()?this.gameObject:this.gameObject.parent;if(this._parentComponent=R.getComponentInParent(n,Te),!this._parentComponent){console.warn(`Component "${this.name}" doesn't have a UI parent anywhere. Do you have a UI element outside a Canvas?`,this);return}e.name=this.name+" ("+(this.constructor.name??"UI")+")",e.autoLayout=this._parentComponent.controlsChildLayout,e[bt]=this,e.traverse(r=>{r[bt]===void 0&&(r[bt]=this)});let i=!1;if(this.Root?.gameObject===this.gameObject)this.gameObject.add(e);else{let r=this._parentComponent.shadowComponent;r&&(r?.add(e),i=!0)}this.shadowComponent=e,t&&t.shadowComponent&&this.shadowComponent&&t.shadowComponent.add(this.shadowComponent),dn&&e.add(new $g(.5)),this.onAfterAddedToScene(),i&&za.update()}set(e){}traverseOwnedShadowComponents(e,t,n){if(!!e&&e[bt]===t){n(e);for(let i of e.children)this.traverseOwnedShadowComponents(i,t,n)}}removeShadowComponent(){this.shadowComponent&&this.shadowComponent.removeFromParent()}onAfterAddedToScene(){}setInteractable(e){this.shadowComponent&&(this.shadowComponent.interactable=e)}},Tn=class extends Te{awake(){super.awake()}};var At=class{static getObject(e){let t=e[bt];return t&&(t.isComponent===!0?e=t.gameObject:e=t),e}static isInteractable(e,t){if(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 i=Gt(e,r=>{if(r.isGraphic===!0)return r},!1);return t&&i?.isGraphic===!0&&(t.graphic=i),i?.raycastTarget!==!1}static tryFindCanvasGroup(e){if(!e)return null;let t=Gt(e,n=>{let i=n;if(i.blocksRaycasts!==void 0&&i.interactable!==void 0)return i},!1);return t!==void 0?t:this.tryFindCanvasGroup(e.parent)}};var ms=I("debugwebxrcontroller");var Gi=class extends O{},Re=class extends O{static CreateRaycastLine(){let e=new rb(this.geometry),t=e.material;return t.color=this.raycastColor,e.layers.set(2),e.name="line",e.scale.z=1,e}static CreateRaycastHitPoint(){let e=new lb(.5,22,22),t=new sb({color:this.raycastColor}),n=new ob(e,t);return n.visible=!1,n.layers.set(2),n}static Create(e,t,n,i){let r=n?R.addNewComponent(n,Re,!1):new Re;r.webXR=e,r.index=t,r.type=i;let s=e.context;r.controller=s.renderer.xr.getController(t),r.controllerGrip=s.renderer.xr.getControllerGrip(t),r.controllerModel=this.Factory.createControllerModel(r.controller),r.controllerGrip.add(r.controllerModel),r.hand=s.renderer.xr.getHand(t);let a=new pb;Zn(a,s),r.webXR.handModelPath&&r.webXR.handModelPath!==""&&a.setPath("/"+cn(e.sourceId,r.webXR.handModelPath));let c=new db(r.hand,a);return r.hand.add(c),r.hand.traverse(d=>d.layers.set(2)),r.handPointerModel=new ub(r.hand,r.controller),r.controller.addEventListener("connected",d=>{r.setControllerLayers(r.controllerModel,2),r.setControllerLayers(r.controllerGrip,2),r.setControllerLayers(r.hand,2),setTimeout(()=>{r.setControllerLayers(r.controllerModel,2),r.setControllerLayers(r.controllerGrip,2),r.setControllerLayers(r.hand,2)},1e3)}),r.hand.addEventListener("connected",d=>{if(d.data.hand){e.Rig&&e.Rig.add(r.hand),r.type=0,r.handPointerModel.traverse(h=>h.layers.set(2)),r.handPointerModel.pointerObject?.traverse(h=>h.layers.set(2));let u=r.hand.joints;if(u)for(let h of Object.keys(u)){let b=u[h];b.parent||r.hand.add(b)}}}),r}static addEventListener(e,t){let n=this.eventSubs[e]??[];n.push(t),this.eventSubs[e]=n}static removeEventListener(e,t){if(!t)return;let n=this.eventSubs[e]??[],i=n.indexOf(t);i>=0&&n.splice(i,1),this.eventSubs[e]=n}webXR;index=-1;controllerModel;controller;controllerGrip;hand;handPointerModel;grabbed=null;input=null;type=0;get isUsingHands(){let e=this.input?.hand;return e!=null}get wrist(){if(!this.hand)return null;let e=this.hand.joints;return e?e.wrist:null}_wristQuaternion=null;getWristQuaternion(){let e=this.wrist;return e?(this._wristQuaternion||(this._wristQuaternion=new Na),ge(e).multiply(this._wristQuaternion.setFromEuler(new nb(-Math.PI/4,0,0)))):null}movementVector=new Zt;worldRot=new Na;joystick=new cb;didRotate=!1;didTeleport=!1;didChangeScale=!1;lastHit=null;raycastLine=null;_raycastHitPoint=null;_connnectedCallback=null;_disconnectedCallback=null;_selectStartEvt=null;_selectEndEvt=null;get selectionDown(){return this._selectionPressed&&!this._selectionPressedLastFrame}get selectionUp(){return!this._selectionPressed&&this._selectionPressedLastFrame}get selectionPressed(){return this._selectionPressed}get selectionClick(){return this._selectionEndTime-this._selectionStartTime<.3}get raycastHitPoint(){return this._raycastHitPoint}_selectionPressed=!1;_selectionPressedLastFrame=!1;_selectionStartTime=0;_selectionEndTime=0;get useSmoothing(){return this._useSmoothing}_useSmoothing=!0;awake(){if(!this.controller){console.warn("Missing Controller!!!",this);return}this._connnectedCallback=this.onSourceConnected.bind(this),this._disconnectedCallback=this.onSourceDisconnected.bind(this),this._selectStartEvt=this.onSelectStart.bind(this),this._selectEndEvt=this.onSelectEnd.bind(this),this.type===1&&(this.controllerGrip.addEventListener("connected",this._connnectedCallback),this.controllerGrip.addEventListener("disconnected",this._disconnectedCallback),this.controller.addEventListener("selectstart",this._selectStartEvt),this.controller.addEventListener("selectend",this._selectEndEvt)),this.type===0&&(this.controller.addEventListener("selectstart",this._selectStartEvt),this.controller.addEventListener("selectend",this._selectEndEvt))}onDestroy(){this.type===1&&(this.controllerGrip.removeEventListener("connected",this._connnectedCallback),this.controllerGrip.removeEventListener("disconnected",this._disconnectedCallback),this.controller.removeEventListener("selectstart",this._selectStartEvt),this.controller.removeEventListener("selectend",this._selectEndEvt)),this.type===0&&(this.controller.removeEventListener("selectstart",this._selectStartEvt),this.controller.removeEventListener("selectend",this._selectEndEvt)),this.hand?.clear(),this.controllerGrip?.clear(),this.controller?.clear()}onEnable(){this.hand&&(this.hand.name="Hand"),this.controllerGrip&&(this.controllerGrip.name="ControllerGrip"),this.controller&&(this.controller.name="Controller"),this.raycastLine&&(this.raycastLine.name="RaycastLine;"),this.webXR.Controllers.indexOf(this)<0&&this.webXR.Controllers.push(this),this.raycastLine||(this.raycastLine=Re.CreateRaycastLine()),this._raycastHitPoint||(this._raycastHitPoint=Re.CreateRaycastHitPoint()),this.webXR.Rig?.add(this.hand),this.webXR.Rig?.add(this.controllerGrip),this.webXR.Rig?.add(this.controller),this.webXR.Rig?.add(this.raycastLine),this.raycastLine?.add(this._raycastHitPoint),this._raycastHitPoint.visible=!1,this.hand.add(this.handPointerModel),ms&&console.log("ADDED TO RIG",this.webXR.Rig)}onDisable(){this.hand?.removeFromParent(),this.controllerGrip?.removeFromParent(),this.controller?.removeFromParent(),this.raycastLine?.removeFromParent(),this._raycastHitPoint?.removeFromParent();let e=this.webXR.Controllers.indexOf(this);e>=0&&this.webXR.Controllers.splice(e,1)}_isConnected=!1;onSourceConnected(e){if(this._isConnected){console.warn("Received connected event for controller that is already connected",this.index,e);return}this._isConnected=!0,this.input=e.data,this.type===1&&(this.onSelectStart(),this.createPointerEvent("down"))}onSourceDisconnected(e){if(!this._isConnected){console.warn("Received discnnected event for controller that is not connected",e);return}this._isConnected=!1,this.type===1&&(this.onSelectEnd(),this.createPointerEvent("up")),this.input=null}createPointerEvent(e){switch(e){case"down":this.context.input.createPointerDown({pointerId:this.index,clientX:0,clientY:0,button:this.index,pointerType:"touch"});break;case"move":break;case"up":this.context.input.createPointerUp({pointerId:this.index,clientX:0,clientY:0,button:this.index,pointerType:"touch"});break}}rayRotation=new Na;update(){this.context.time.frameCount%60===0&&(this.setControllerLayers(this.controller,2),this.setControllerLayers(this.controllerGrip,2),this.setControllerLayers(this.hand,2));let e=Re.eventSubs["update"];if(e&&e.length>0)for(let i of e)i(this);let t=1;this.type===0?t=this.context.time.deltaTime/.1:this.isUsingHands&&this.handPointerModel.pinched&&(t=this.context.time.deltaTime/.3),this.rayRotation.slerp(ge(this.controller),this.useSmoothing?t:1);let n=B(this.controller);if(this.isUsingHands&&this.handPointerModel.cursorObject&&(this.handPointerModel.cursorObject.visible=!1),this.raycastLine)if(this.type===1)this.raycastLine.visible=!1;else if(this.isUsingHands){this.raycastLine.visible=!this.grabbed,J(this.raycastLine,n);let i=this.hand.joints;if(i&&i.wrist&&this.grabbed&&this.grabbed.isCloseGrab){let s=this.getWristQuaternion();s&&this.rayRotation.copy(s)}Ue(this.raycastLine,this.rayRotation)}else this.raycastLine.visible=!0,Ue(this.raycastLine,this.rayRotation),J(this.raycastLine,n);this.lastHit=this.updateLastHit(),this.grabbed&&this.grabbed.update(),this._selectionPressedLastFrame=this._selectionPressed,this.selectStartCallback&&this.selectStartCallback()}_pinchStartTime=void 0;onUpdate(e){if(this.lastHit=null,!e||e.inputSources.length<=this.index){this.input=null;return}if(this.type===0&&(this.input=e.inputSources[this.index]),!this.input)return;let t=this.webXR.Rig;if(!t)return;this._didNotEndSelection&&!this.handPointerModel.pinched&&(this._didNotEndSelection=!1,this.onSelectEnd()),this.updateStick(this.input);let n=this.input?.gamepad?.buttons;switch(this.input.handedness){case"left":let i=3*Re.MovementSpeedFactor,r=2,s=U.clamp01(this.joystick.length()*2),a=this.joystick.x>0?1:-1,c=Math.pow(this.joystick.x,r);c*=a,c*=s;let d=this.joystick.y>0?1:-1,l=Math.pow(this.joystick.y,r);l*=d,c*=s,t.getWorldQuaternion(this.worldRot),this.movementVector.set(c,0,l),this.movementVector.applyQuaternion(this.webXR.TransformOrientation),this.movementVector.y=0,this.movementVector.applyQuaternion(this.worldRot),this.movementVector.multiplyScalar(i*this.context.time.deltaTime),t.position.add(this.movementVector),this.isUsingHands&&this.runTeleport(t,n);break;case"right":let u=this.joystick.x,h=Math.abs(u);if(h<.4)this.didRotate=!1;else if(h>.5&&!this.didRotate){let b=u>0?-1:1;t.rotateY(U.toRadians(30*b)),this.didRotate=!0}this.runTeleport(t,n);break}}runTeleport(e,t){let n=-this.joystick.y;if(this.hand?.visible&&!this.grabbed){let a=this.handPointerModel.isPinched();a&&this._pinchStartTime===void 0&&(this._pinchStartTime=this.context.time.time),a&&this._pinchStartTime&&this.context.time.time-this._pinchStartTime>.8&&(n=this.handPointerModel.isPinched()?1:0),a||(this._pinchStartTime=void 0)}else this._pinchStartTime=void 0;let i=n>.5&&this.webXR.IsInVR,r=this.webXR.Rig?this.webXR.Rig?.scale?.x<.999:!1,s=null;if(t&&this.input&&!this.input.hand)for(let a=0;a<t.length;a++){let c=t[a];if(a===4)if(c.pressed&&!this.didChangeScale&&this.webXR.IsInVR){this.didChangeScale=!0;let d=this.webXR.Rig;if(d)if(r){r=!1,d.scale.set(1,1,1),s=1,Re.MovementSpeedFactor=1;let l=this.context.mainCamera;Re.PreviousCameraFarDistance&&(l.far=Re.PreviousCameraFarDistance)}else{r=!0,i=!0,s=.1,Re.MovementSpeedFactor=s*2;let l=this.context.mainCamera;Re.PreviousCameraFarDistance=l.far,l.far/=s}}else c.pressed||(this.didChangeScale=!1)}if(i){if(!this.didTeleport){let a=this.raycast();if(this.didTeleport=!0,a&&a.length>0){let c=a[0];if(r||this.isValidTeleportTarget(c.object)){let d=c.point;J(e,d)}}}}else n<.1&&(this.didTeleport=!1);s!==null&&(e.scale.set(s,s,s),e.updateMatrixWorld())}isValidTeleportTarget(e){return R.getComponentInParent(e,Gi)!=null}updateStick(e){!e||!e.gamepad||e.gamepad.axes?.length<4||(this.joystick.x=e.gamepad.axes[2],this.joystick.y=e.gamepad.axes[3])}updateLastHit(){let e=this.raycast(),t=e?e[0]:null;this.lastHit=t;let n=1;if(this.webXR.Rig&&(n/=this.webXR.Rig.scale.x),this.raycastLine){this.raycastLine.scale.z=n*(this.lastHit?.distance??9999);let i=this.raycastLine.material;t!=null?i.color=Re.raycastColor:i.color=Re.raycastNoHitColor}if(this._raycastHitPoint){if(this.lastHit!=null){this._raycastHitPoint.position.z=-1;let i=U.clamp(this.lastHit.distance*.01*n,.015,.1);this._raycastHitPoint.scale.set(i,i,i)}this._raycastHitPoint.visible=this.lastHit!==null&&this.lastHit!==void 0}return t}onSelectStart(){!this.context.connection.allowEditing||(this.selectStartCallback=()=>this.onHandleSelectStart())}selectStartCallback=null;lastSelectStartObject=null;onHandleSelectStart(){this.selectStartCallback=null,this._selectionPressed=!0,this._selectionStartTime=this.context.time.time,this._selectionEndTime=1e3;let e=null,t=!1;if(this.isUsingHands?(e=this.overlap(),e.length<=0?(e=this.raycast(),t=!1):t=!0):e=this.raycast(),ms&&console.log("onHandleSelectStart","close grab? "+t,"intersections",e),e&&e.length>0)for(let n of e){let i=n.object;this.lastSelectStartObject=i;let r={selected:i,grab:i},s=Re.eventSubs["select-start"];if(s&&s.length>0)for(let a of s)a(this,r);r.grab!==i&&ms&&console.log("Grabbed object changed","original",i,"new",r.grab),r.grab&&(this.grabbed=ze.TryTake(this,r.grab,n,t));break}else{let n=Re.eventSubs["select-start"],i={selected:null,grab:null};if(n&&n.length>0)for(let r of n)r(this,i)}}_didNotEndSelection=!1;onSelectEnd(){if(this.isUsingHands&&this.handPointerModel.pinched){this._didNotEndSelection=!0;return}if(!this._selectionPressed)return;this.selectStartCallback=null,this._selectionPressed=!1,this._selectionEndTime=this.context.time.time;let e={grab:this.grabbed?.selected??this.lastSelectStartObject},t=Re.eventSubs["select-end"];if(t&&t.length>0)for(let n of t)n(this,e);this.grabbed&&(this.grabbed.free(),this.grabbed=null)}testIsVisible(e){return!(!e||R.isActiveInHierarchy(e)===!1||At.isInteractable(e)===!1)}setControllerLayers(e,t){if(!!e&&(e.layers.set(t),e.children))for(let n of e.children)this.grabbed?.selected===n||this.grabbed?.selectedMesh===n||this.setControllerLayers(n,t)}getRay(){let e=new ab;return e.origin.copy(B(this.controller)),e.direction.set(0,0,-1).applyQuaternion(this.rayRotation),e}closeGrabBoundingBoxHelper;overlap(){let e=this.isUsingHands&&this.handPointerModel?this.handPointerModel.pointerObject:this.controllerGrip;if(ms&&(!this.closeGrabBoundingBoxHelper&&e&&(this.closeGrabBoundingBoxHelper=new eb(e,16776960),this.scene.add(this.closeGrabBoundingBoxHelper)),this.closeGrabBoundingBoxHelper&&e&&this.closeGrabBoundingBoxHelper.setFromObject(e)),!e)return new Array;let t=B(e).clone();return this.context.physics.sphereOverlap(t,.02)}raycast(){let e=new ce;e.layerMask=new ib,e.layerMask.set(0),e.layerMask.disable(2),e.ray=this.getRay();let t=this.context.physics.raycast(e);for(let n=0;n<t.length;n++){let i=t[n],r=i.object;if(!this.testIsVisible(r)){t.splice(n,1),n--;continue}i.object=At.getObject(r);break}return t}},Y=Re;j(Y,"Factory",new hb),j(Y,"raycastColor",new tp(.9,.3,.3)),j(Y,"raycastNoHitColor",new tp(.6,.6,.6)),j(Y,"geometry",new tb().setFromPoints([new Zt(0,0,0),new Zt(0,0,-1)])),j(Y,"handModels",{}),j(Y,"eventSubs",{}),j(Y,"PreviousCameraFarDistance"),j(Y,"MovementSpeedFactor",1);var Ve=class{static AddEventListener(e,t){return Ve.Events[e]||(Ve.Events[e]=[]),Ve.Events[e].push(t),t}static RemoveEventListener(e,t){if(!t||!Ve.Events[e])return;let n=Ve.Events[e].indexOf(t);n>=0&&Ve.Events[e].splice(n,1)}static Register(e){this.Current.find(t=>t===e)||this.Current.push(e)}static Remove(e){let t=this.Current.indexOf(e);t>=0&&this.Current.splice(t,1)}static TryTake(e,t,n,i){let r=R.getComponentInParent(t,pt);if(r)t=r.gameObject;else return ms&&console.warn("Prevented taking object that is not interactable",t),null;let s=t,a=R.getComponentInParent(t,Je);a&&(a.requestOwnership(),s=a.gameObject);for(let d of this.Current)if(d.selected===s)return d.controller===e||(d.free(),d.Take(e,s,t,a,r,n,i)),d;let c=new Ve;return c.Take(e,s,t,a,r,n,i),c}sync=null;selected=null;selectedParent=null;selectedMesh=null;controller=null;grabTime=0;grabUUID="";isCloseGrab=!1;originalMaterial=null;usageMarker=null;rigidbodies=null;didReparent=!1;grabDistance=0;interactable=null;positionSource=null;Take(e,t,n,i,r,s,a){if(console.assert(t!==null,"Expected object to be taken but was",t),e.isUsingHands?this.positionSource=a?e.wrist:e.controller:this.positionSource=e.controller,!this.positionSource)return console.warn("No position source"),this;let c={controller:e,take:t,hit:n,sync:i,interactable:r};Ve.Events.WillTake?.forEach(b=>b(this,c));let d=n;d?.material&&(this.originalMaterial=d.material,Array.isArray(d.material)||(d.material=d.material.clone(),d.material&&d.material.emissive&&(d.material.emissive.b=.2))),this.selected=t,this.selectedParent||(this.selectedParent=t.parent),this.selectedMesh=d,this.controller=e,this.interactable=r,this.isCloseGrab=a,this.didReparent=!1,this.sync=i,this.grabTime=e.context.time.time,this.grabUUID=Date.now().toString(),this.usageMarker=R.addNewComponent(this.selected,ft),this.rigidbodies=R.getComponentsInChildren(this.selected,q),B(this.positionSource,this.lastControllerWorldPos);let l=()=>a?this.lastControllerWorldPos.clone():s.point.clone();this.grabDistance=l().distanceTo(this.lastControllerWorldPos),this.totalChangeAlongDirection=0,this.localPositionOffsetToGrab=this.selected.worldToLocal(l());let u=e.isUsingHands&&a?this.controller.getWristQuaternion().clone():e.rayRotation.clone();ge(this.selected,this.localQuaternionToGrab).premultiply(u.invert());let h=this.controller.webXR.Rig;return h&&this.rigPositionLastFrame.copy(B(h)),ue.Add(e.context,this.selected),Ve.Register(this),this.sync&&(this.sync.fastMode=!0),Ve.Events.DidTake?.forEach(b=>b(this,c)),this}free(){if(!this.selected)return;let e={controller:this.controller,take:this.selected,hit:this.selected,sync:this.sync,interactable:null};Ve.Events.WillFree?.forEach(i=>i(this,e)),ue.Remove(this.controller.context,this.selected),Ve.Remove(this),this.sync&&(this.sync.fastMode=!1);let t=this.selectedMesh;t&&this.originalMaterial&&t.material&&(t.material=this.originalMaterial);let n=this.selected;if(this.didReparent&&n.parent){let i=this.selectedParent;i?i.attach(n):this.controller?.context.scene.attach(n)}if(this.usageMarker?.destroy(),this.controller&&(this.controller.grabbed=null),this.selected=null,this.selectedParent=null,this.selectedMesh=null,this.sync=null,this.rigidbodies)for(let i of this.rigidbodies)i.wakeUp(),i.setVelocity(i.smoothedVelocity);this.rigidbodies=null,this.localPositionOffsetToGrab=null,this.quaternionLerp=null,Ve.Events.DidFree?.forEach(i=>i(this,e))}grabPoint=new Zt;localPositionOffsetToGrab=null;localPositionOffsetToGrab_worldSpace=new Zt;localQuaternionToGrab=new Na(0,0,0,1);targetDir=null;quaternionLerp=null;controllerDir=new Zt;controllerWorldPos=new Zt;lastControllerWorldPos=new Zt;controllerPosDelta=new Zt;totalChangeAlongDirection=0;rigPositionLastFrame=new Zt;controllerMovementSinceLastFrame(){if(!this.positionSource||!this.controller)return 0;this.controllerDir.set(0,0,-1),this.controllerDir.applyQuaternion(this.controller.rayRotation),B(this.positionSource,this.controllerWorldPos),this.controllerPosDelta.copy(this.controllerWorldPos),this.controllerPosDelta.sub(this.lastControllerWorldPos),this.lastControllerWorldPos.copy(this.controllerWorldPos);let e=this.controller.webXR.Rig;if(e){let n=B(e),i=this.rigPositionLastFrame.sub(n);this.controllerPosDelta.add(i),this.rigPositionLastFrame.copy(n)}return this.controllerDir.dot(this.controllerPosDelta)}update(){if(this.rigidbodies)for(let e of this.rigidbodies)e.resetVelocities();if(this.sync&&this.controller&&this.controller.context.connection.isInRoom&&this.controller.context.time.time-this.grabTime>3&&this.sync.hasOwnership()===!1&&(console.log("no ownership, will leave",this.sync.guid),this.free()),!(this.interactable&&!this.interactable.canGrab)){if(!this.didReparent&&this.selected&&this.controller){let e=this.controller.webXR.Rig?.scale.x??1;this.totalChangeAlongDirection+=this.controllerMovementSinceLastFrame();let t=1;this.controller.type===0&&(t=Math.max(0,1+this.totalChangeAlongDirection*2/e),t=t*t*t),this.grabDistance/e<.8&&(t=1),this.targetDir||(this.targetDir=new Zt),this.targetDir.set(0,0,-this.grabDistance*t);let n=this.targetDir.applyQuaternion(this.controller.rayRotation).add(this.controllerWorldPos),i=this.controller.rayRotation.clone().multiplyQuaternions(this.controller.rayRotation,this.localQuaternionToGrab);this.quaternionLerp||(this.quaternionLerp=i.clone()),this.quaternionLerp.slerp(i,this.controller.useSmoothing?this.controller.context.time.deltaTime/.03:1),Ue(this.selected,this.quaternionLerp),this.selected.updateWorldMatrix(!1,!1),this.grabPoint.copy(n),this.localPositionOffsetToGrab&&(this.localPositionOffsetToGrab_worldSpace.copy(this.localPositionOffsetToGrab),this.selected.localToWorld(this.localPositionOffsetToGrab_worldSpace).sub(B(this.selected)),n.sub(this.localPositionOffsetToGrab_worldSpace)),J(this.selected,n)}if(this.rigidbodies!=null)for(let e of this.rigidbodies)e.wakeUp(),e.setBodyFromGameObject({x:0,y:0,z:0});ne.markDirty(this.selected,!0)}}},ze=Ve;j(ze,"Events",{}),j(ze,"Current",[]);var ai=class extends O{awake(){}};import{Quaternion as gs,Vector3 as Wa,Vector4 as fb}from"three";var Rn=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)}w(){return this.bb.readFloat32(this.bb_pos+12)}static sizeOf(){return 16}static createVec4(e,t,n,i,r){return e.prep(4,16),e.writeFloat32(r),e.writeFloat32(i),e.writeFloat32(n),e.writeFloat32(t),e.offset()}};var we=class{bb=null;bb_pos=0;__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsVrUserStateBuffer(e,t){return(t||new we).__init(e.readInt32(e.position())+e.position(),e)}static getSizePrefixedRootAsVrUserStateBuffer(e,t){return e.setPosition(e.position()+4),(t||new we).__init(e.readInt32(e.position())+e.position(),e)}guid(e){let t=this.bb.__offset(this.bb_pos,4);return t?this.bb.__string(this.bb_pos+t,e):null}time(){let e=this.bb.__offset(this.bb_pos,6);return e?this.bb.readInt64(this.bb_pos+e):this.bb.createLong(0,0)}avatarId(e){let t=this.bb.__offset(this.bb_pos,8);return t?this.bb.__string(this.bb_pos+t,e):null}position(e){let t=this.bb.__offset(this.bb_pos,10);return t?(e||new ve).__init(this.bb_pos+t,this.bb):null}rotation(e){let t=this.bb.__offset(this.bb_pos,12);return t?(e||new Rn).__init(this.bb_pos+t,this.bb):null}scale(){let e=this.bb.__offset(this.bb_pos,14);return e?this.bb.readFloat32(this.bb_pos+e):0}posLeftHand(e){let t=this.bb.__offset(this.bb_pos,16);return t?(e||new ve).__init(this.bb_pos+t,this.bb):null}posRightHand(e){let t=this.bb.__offset(this.bb_pos,18);return t?(e||new ve).__init(this.bb_pos+t,this.bb):null}rotLeftHand(e){let t=this.bb.__offset(this.bb_pos,20);return t?(e||new Rn).__init(this.bb_pos+t,this.bb):null}rotRightHand(e){let t=this.bb.__offset(this.bb_pos,22);return t?(e||new Rn).__init(this.bb_pos+t,this.bb):null}static startVrUserStateBuffer(e){e.startObject(10)}static addGuid(e,t){e.addFieldOffset(0,t,0)}static addTime(e,t){e.addFieldInt64(1,t,e.createLong(0,0))}static addAvatarId(e,t){e.addFieldOffset(2,t,0)}static addPosition(e,t){e.addFieldStruct(3,t,0)}static addRotation(e,t){e.addFieldStruct(4,t,0)}static addScale(e,t){e.addFieldFloat32(5,t,0)}static addPosLeftHand(e,t){e.addFieldStruct(6,t,0)}static addPosRightHand(e,t){e.addFieldStruct(7,t,0)}static addRotLeftHand(e,t){e.addFieldStruct(8,t,0)}static addRotRightHand(e,t){e.addFieldStruct(9,t,0)}static endVrUserStateBuffer(e){return e.endObject()}static finishVrUserStateBufferBuffer(e,t){e.finish(t)}static finishSizePrefixedVrUserStateBufferBuffer(e,t){e.finish(t,void 0,!0)}};var np=I("debugxr"),bs=I("debugavatar");var rd="VRUS";fo(rd,we.getRootAsVrUserStateBuffer);function id(){return new Date().getTime()}function mb(o){let e=o&4294967295,t=o/Math.pow(2,32)&1048575;return Ae.create(e,t)}var vs=class{guid;time;avatarId;position=new Wa;rotation=new fb;scale=1;posLeftHand=new Wa;posRightHand=new Wa;rotLeftHand=new gs;rotRightHand=new gs;constructor(e){this.guid=e}update(e,t,n,i,r){this.time=id(),this.avatarId=r,this.position.set(t.x,t.y,t.z),e&&this.position.applyMatrix4(e.matrixWorld);let s=vs.quat0,a=vs.quat1;s.set(n.x,n.y,n.z,n.w),s=s.multiplyQuaternions(s,vs.invertRotation),e&&(e.getWorldQuaternion(a),s.multiplyQuaternions(a,s)),this.rotation.set(s.x,s.y,s.z,s.w),this.scale=e.scale.x;let c=i.LeftController?.controllerGrip;c&&(c.getWorldPosition(this.posLeftHand),c.getWorldQuaternion(this.rotLeftHand));let d=i.RightController?.controllerGrip;if(d&&(d.getWorldPosition(this.posRightHand),d.getWorldQuaternion(this.rotRightHand)),i.LeftController?.hand?.visible){let l=i.LeftController.wrist;l&&(l.getWorldPosition(this.posLeftHand),l.getWorldQuaternion(this.rotLeftHand))}if(i.RightController?.hand?.visible){let l=i.RightController.wrist;l&&(l.getWorldPosition(this.posRightHand),l.getWorldQuaternion(this.rotRightHand))}}sendAsBuffer(e,t){e.clear();let n=e.createString(this.guid),i=e.createString(this.avatarId);we.startVrUserStateBuffer(e),we.addGuid(e,n),we.addTime(e,mb(this.time)),we.addAvatarId(e,i),we.addPosition(e,ve.createVec3(e,this.position.x,this.position.y,this.position.z)),we.addRotation(e,Rn.createVec4(e,this.rotation.x,this.rotation.y,this.rotation.z,this.rotation.w)),we.addScale(e,this.scale),we.addPosLeftHand(e,ve.createVec3(e,this.posLeftHand.x,this.posLeftHand.y,this.posLeftHand.z)),we.addPosRightHand(e,ve.createVec3(e,this.posRightHand.x,this.posRightHand.y,this.posRightHand.z)),we.addRotLeftHand(e,Rn.createVec4(e,this.rotLeftHand.x,this.rotLeftHand.y,this.rotLeftHand.z,this.rotLeftHand.w)),we.addRotRightHand(e,Rn.createVec4(e,this.rotRightHand.x,this.rotRightHand.y,this.rotRightHand.z,this.rotRightHand.w));let r=we.endVrUserStateBuffer(e);e.finish(r,rd);let s=e.asUint8Array();t.sendBinary(s)}setFromBuffer(e,t){if(!e)return;this.guid=e,this.time=t.time().toFloat64();let n=t.avatarId();n&&(this.avatarId=n);let i=t.position();i&&this.position.set(i.x(),i.y(),i.z());let r=t.rotation();r&&this.rotation.set(r.x(),r.y(),r.z(),r.w());let s=t.posLeftHand();s&&this.posLeftHand.set(s.x(),s.y(),s.z());let a=t.posRightHand();a&&this.posRightHand.set(a.x(),a.y(),a.z());let c=t.rotLeftHand();c&&this.rotLeftHand.set(c.x(),c.y(),c.z(),c.w());let d=t.rotRightHand();d&&this.rotRightHand.set(d.x(),d.y(),d.z(),d.w()),this.scale=t.scale()}},vt=vs;j(vt,"invertRotation",new gs().setFromAxisAngle(new Wa(0,1,0),Math.PI)),j(vt,"quat0",new gs),j(vt,"quat1",new gs);var Sn=class extends O{webXR=null;debugAvatarUser=null;voip=null;async awake(){if(this.webXR||(this.webXR=R.getComponent(this.gameObject,G)),this.webXR||(this.webXR=R.findObjectOfType(G,this.context)),!this.webXR&&(console.log("Missing webxr component"),this.webXR=R.findObjectOfType(G,this.context),!this.webXR)){console.error("Could not find webxr component");return}if(this.voip||(this.voip=R.findObjectOfType(Fe,this.context)),bs){let e="debug-avatar-"+bs,t=new gt(this.context,e,this.webXR);if(this.debugAvatarUser=t,typeof bs=="string"&&bs.length>0)if(await t.setAvatarOverride(bs)){let n=new vt(e);n.position.y+=1;let i=.5;n.posLeftHand.y+=i,n.posLeftHand.x+=i,n.posRightHand.y+=i,n.posRightHand.x-=i,t.tryUpdate(n,0)}else t.destroy()}}onEnable(){if(!this.webXR&&(this.webXR=R.getComponent(this.gameObject,G),!this.webXR)){console.warn("Missing webxr component on "+this.gameObject.name);return}this.eventSub_WebXRStartEvent=this.onXRSessionStart.bind(this),G.addEventListener("xrStarted",this.eventSub_WebXRStartEvent),this.eventSub_WebXRUpdateEvent=this.onXRSessionUpdate.bind(this),G.addEventListener("xrUpdate",this.eventSub_WebXRUpdateEvent),this.eventSub_WebXREndEvent=this.onXRSessionEnded.bind(this),G.addEventListener("xrStopped",this.eventSub_WebXREndEvent),this.eventSub_ConnectionEvent=this.onConnected.bind(this),this.context.connection.beginListen("joined-room",this.eventSub_ConnectionEvent),this.context.connection.beginListen("webxr-user-joined",e=>{console.log("webxr user joined evt")}),this.context.connection.beginListen("webxr-user-left",e=>{let t=e.id!==null&&e.id!==void 0;!t||(console.log("webxr user left evt"),t&&(this.avatars[e.id]?.destroy(),this.avatars[e.id]=void 0))}),this.context.connection.beginListenBinrary(rd,e=>{let t=e.guid();if(!t)return;let n=e.time().toFloat64(),i=this.tempState;i.setFromBuffer(t,e),this.onTryGetAvatar(t,n)?.tryUpdate(i,n)}),this.context.connection.beginListen("vr-session-update",e=>{let t=e.guid,n=e.time;this.onTryGetAvatar(t,n)?.tryUpdate(e,n)})}tempState=new vt("");onTryGetAvatar(e,t){if(e===this.context.connection.connectionId)return null;let n=new Date().getTime()-t;if(n>5e3)return np&&console.log("old data",n,e),null;let i=this.avatars[e];if(i===void 0)try{console.log("create new avatar");let r=new gt(this.context,e,this.webXR);i=r,this.avatars[e]=r}catch(r){this.avatars[e]=null,console.error(r)}return i}onDisable(){this.eventSub_ConnectionEvent&&this.context.connection.stopListening("joined-room",this.eventSub_ConnectionEvent),G.removeEventListener("xrStarted",this.eventSub_WebXRStartEvent),G.removeEventListener("xrUpdate",this.eventSub_WebXRUpdateEvent),G.removeEventListener("xrStopped",this.eventSub_WebXREndEvent)}update(){let e=id();this.debugAvatarUser&&(this.debugAvatarUser.lastUpdate=e),this.detectPotentiallyDisconnectedAvatarsAndRemove();for(let t in this.avatars){let n=this.avatars[t];!n||n.update()}}_removeAvatarsList=[];detectPotentiallyDisconnectedAvatarsAndRemove(){let e=id();for(let t in this.avatars){let n=this.avatars[t];if(!n){this._removeAvatarsList.push(t);continue}e-n.lastUpdate>1e4&&(console.log("avatar timed out (didnt receive any updates in a while) - destroying it now"),n.destroy(),this.avatars[t]=void 0)}for(let t of this._removeAvatarsList)delete this.avatars[t];this._removeAvatarsList.length=0}buildLocalAvatar(){if(this.localAvatar)return;let e=this.context.connection?.connectionId??this.k_LocalAvatarNoNetworkingGuid;this.localAvatar=new gt(this.context,e,this.webXR),this.localAvatar.isLocalAvatar=!0,this.localAvatar.setAvatarOverride(this.getAvatarId()),this.avatars[this.localAvatar.guid]=this.localAvatar}eventSub_ConnectionEvent=null;eventSub_WebXRStartEvent=null;eventSub_WebXREndEvent=null;eventSub_WebXRUpdateEvent=null;avatars={};localAvatar=null;k_LocalAvatarNoNetworkingGuid="local";onConnected(){np&&console.log("Hey you are connected as "+this.context.connection.connectionId),this.localAvatar?.guid===this.k_LocalAvatarNoNetworkingGuid&&(this.localAvatar&&(this.localAvatar?.destroy(),this.avatars[this.localAvatar.guid]=void 0),this.localAvatar=null,this.xrState=null,this.ownership?.freeOwnership(),this.ownership=null)}onXRSessionStart(e){if(console.log("XR session started"),this.context.connection.send("webxr-user-joined",{id:this.context.connection.connectionId,mode:"vr"}),this.localAvatar&&(this.localAvatar?.destroy(),this.avatars[this.localAvatar.guid]=void 0,this.localAvatar=null),this.xrState=null,this.ownership?.freeOwnership(),this.ownership=null,this.avatars)for(let t in this.avatars)this.avatars[t]?.updateFlags()}onXRSessionEnded(e){console.log("XR session ended"),this.context.connection.send("webxr-user-left",{id:this.context.connection.connectionId,mode:"vr"})}ownership=null;xrState=null;builder=new st(1024);onXRSessionUpdate(e){this.xrState??=new vt(this.context.connection.connectionId??this.k_LocalAvatarNoNetworkingGuid),this.ownership??=new Ri(this.context.connection,this.context.connection.connectionId??this.k_LocalAvatarNoNetworkingGuid),this.ownership.guid=this.context.connection.connectionId??this.k_LocalAvatarNoNetworkingGuid,this.buildLocalAvatar();let{frame:t,xr:n,rig:i}=e,r=t.getViewerPose(n.getReferenceSpace());if(!r)return;let s=r?.transform,a=s.position,c=s.orientation;this.xrState.update(i,a,c,this.webXR,this.getAvatarId()),this.localAvatar&&(this.context.connection.connectionId&&(this.localAvatar.guid=this.context.connection.connectionId),this.localAvatar.tryUpdate(this.xrState,0)),!(this.ownership&&!this.ownership.hasOwnership&&this.context.connection.isConnected&&(this.context.time.frameCount%120===0&&this.ownership.requestOwnership(),!this.ownership.hasOwnership))&&(!this.context.connection.isConnected||!this.context.connection.connectionId||this.xrState.sendAsBuffer(this.builder,this.context.connection))}getAvatarId(){return I("avatar")??null}};async function wb(){return"xr"in navigator?await navigator.xr.isSessionSupported("immersive-ar")===!0:!1}async function xb(){return"xr"in navigator?await navigator.xr.isSessionSupported("immersive-vr")===!0:!1}var sd=!1,ad=!1;wb().then(o=>sd=o);xb().then(o=>ad=o);var Se=class extends O{enableVR=!0;enableAR=!0;defaultAvatar;handModelPath="";createVRButton=!0;createARButton=!0;static get IsInWebXR(){return this._isInXr}static get XRSupported(){return"xr"in navigator&&(sd||ad)}static get IsARSupported(){return sd}static get IsVRSupported(){return ad}static addEventListener(e,t){return this.events.addEventListener(e,t),t}static removeEventListener(e,t){return this.events.removeEventListener(e,t),t}static createVRButton(e,t){Se.XRSupported||console.warn("WebXR is not supported on this device");let n=Co.createButton(e.context.renderer);return n.classList.add("webxr-ar-button"),n.classList.add("webxr-button"),this.resetButtonStyles(n),(t?.registerClick??!0)&&n.addEventListener("click",e.onClickedVRButton.bind(e)),n}static createARButton(e,t){let n=e.webAR?.getAROverlayContainer(),i={};n&&(i.domOverlay={root:n},i.optionalFeatures=["hit-test","dom-overlay"]);let r=Ba.createButton(e.context.renderer,i);return r.classList.add("webxr-ar-button"),r.classList.add("webxr-button"),Se.resetButtonStyles(r),(t?.registerClick??!0)&&r.addEventListener("click",e.onClickedARButton.bind(e)),r}static resetButtonStyles(e){!e||(e.style.position="",e.style.bottom="",e.style.left="")}endSession(){let e=this.context.renderer.xr.getSession();e&&e.end()}get Rig(){return this.rig||this.ensureRig(),this.rig}controllers=[];get Controllers(){return this.controllers}get LeftController(){return this.controllers.length>0&&this.controllers[0].input?.handedness==="left"?this.controllers[0]:this.controllers.length>1&&this.controllers[1].input?.handedness==="left"?this.controllers[1]:null}get RightController(){return this.controllers.length>0&&this.controllers[0].input?.handedness==="right"?this.controllers[0]:this.controllers.length>1&&this.controllers[1].input?.handedness==="right"?this.controllers[1]:null}get ARButton(){return this._arButton}get VRButton(){return this._vrButton}get IsInVR(){return this._isInVR}get IsInAR(){return this._isInAR}rig;isInit=!1;_requestedAR=!1;_requestedVR=!1;_isInAR=!1;_isInVR=!1;_arButton;_vrButton;webAR=null;awake(){if(this.defaultAvatar&&typeof this.defaultAvatar=="string"&&(this.defaultAvatar=je.getOrCreate(this.sourceId??"/",this.defaultAvatar,this.context)),!R.findObjectOfType(Sn,this.context)){let e=R.addNewComponent(this.gameObject,Sn,!1);e.webXR=this}}onEnable(){if(this.isInit||!this.enableAR&&!this.enableVR)return;this.isInit=!0,this.context.renderer.xr.enabled=!0,this.webAR=new li(this);let e=Se.XRSupported,t,n,i=document.createElement("div");i.classList.add("webxr-buttons"),this.context.domElement.append(i),this.enableAR&&this.createARButton&&(t=Se.createARButton(this),this._arButton=t,i.appendChild(t)),this.createVRButton&&this.enableVR&&(n=Se.createVRButton(this),this._vrButton=n,i.appendChild(n)),setTimeout(()=>{Se.resetButtonStyles(n),Se.resetButtonStyles(t)},1e3)}_transformOrientation=new od;get TransformOrientation(){return this._transformOrientation}_currentHeadPose=null;get HeadPose(){return this._currentHeadPose}onBeforeRender(e){if(!e)return;let t=this.context.renderer.xr.getSession();if(t){let n=e.getViewerPose(this.context.renderer.xr.getReferenceSpace());if(this._currentHeadPose=n,!n)return;let i=n?.transform;i&&this._transformOrientation.set(i.orientation.x,i.orientation.y,i.orientation.z,i.orientation.w);for(let r of this.controllers)r.onUpdate(t);this._isInAR&&this.webAR?.onUpdate(t,e)}Se._isInXr===!1&&t&&this.onEnterXR(t,e),Se.events.dispatchEvent({type:"xrUpdate",frame:e,xr:this.context.renderer.xr,rig:this.rig})}onClickedARButton(){this._isInAR||(this._requestedAR=!0,this._requestedVR=!1,this.captureCameraState())}onClickedVRButton(){if(!this._isInVR){if(this._requestedVR){this.onExitXR(null);return}this._requestedAR=!1,this._requestedVR=!0,this.captureCameraState(),this.ensureRig();for(let e=0;e<2;e++)Y.Create(this,e,this.gameObject,0);Se.events.dispatchEvent({type:"requestVRSession"})}}captureCameraState(){this.context.mainCamera&&(this._originalCameraPosition.copy(B(this.context.mainCamera)),this._originalCameraRotation.copy(ge(this.context.mainCamera)),this._originalCameraParent=this.context.mainCamera.parent)}ensureRig(){if(!this.rig){let e=R.findObjectOfType(ai,this.context);e?(this.rig=e.gameObject,this.rig.rotateY(Math.PI)):(this.rig=new vb,this.rig.rotateY(Math.PI),this.rig.name="XRRig",this.context.scene.add(this.rig))}}_originalCameraParent=null;_originalCameraPosition=new sp;_originalCameraRotation=new od;onEnterXR(e,t){console.log("[XR] session begin",e),Se._isInXr=!0,this.ensureRig();let n=this.context.renderer.xr.getReferenceSpace();if(n&&this.rig){let a=t.getViewerPose(n)?.transform.orientation;if(a){let c=new od(a.x,a.y,a.z,a.w),d=new gb().setFromQuaternion(c);this.rig.rotateY(d.y)}}let i=this.context.renderer.xr;if(this.context.mainCamera){let s=i.getCamera(this.context.mainCamera);for(let a of s.cameras)a.layers.enableAll();this.rig.add(this.context.mainCamera)}let r=this._requestedAR?2:4;switch($e.Global.Set(r),r){case 2:this.context.xrSessionMode="immersive-ar",this._isInAR=!0,this.webAR?.onBegin(e);break;case 4:this.context.xrSessionMode="immersive-vr",this._isInVR=!0,this.onEnterVR(e);break}e.addEventListener("end",()=>{console.log("[XR] session end"),Se._isInXr=!1,this.onExitXR(e)}),this.onEnterXR_HandleMirrorWindow(e),Se.events.dispatchEvent({type:"xrStarted",session:e})}onExitXR(e){this._isInAR&&e&&this.webAR?.onEnd(e),this._isInAR=!1,this._isInVR=!1,this._requestedAR=!1,this._requestedVR=!1,this.context.xrSessionMode=void 0,this.xrMirrorWindow&&(this.xrMirrorWindow.close(),this.xrMirrorWindow=null),this.destroyControllers(),this.context.mainCamera&&(this._originalCameraParent?.add(this.context.mainCamera),J(this.context.mainCamera,this._originalCameraPosition),Ue(this.context.mainCamera,this._originalCameraRotation),this.context.mainCamera.scale.set(1,1,1)),$e.Global.Set(17),Se.events.dispatchEvent({type:"xrStopped",session:e})}onEnterVR(e){}destroyControllers(){for(let e=this.controllers.length-1;e>=0;e-=1)this.controllers[e]?.destroy();this.controllers.length=0}xrMirrorWindow=null;onEnterXR_HandleMirrorWindow(e){!I("mirror")||setTimeout(()=>{if(!Se.IsInWebXR)return;let t=new URL(window.location.href);to(t.searchParams,To,1),to(t.searchParams,"isMirror",1);let n=t.toString();this.xrMirrorWindow=window.open(n,"webxr sync","popup=yes"),this.xrMirrorWindow&&(this.xrMirrorWindow.onload=()=>{this.xrMirrorWindow&&(this.xrMirrorWindow.onbeforeunload=()=>{Se.IsInWebXR&&e.end()})})},1e3)}},G=Se;j(G,"_isInXr",!1),j(G,"events",new bb),x([w()],G.prototype,"enableVR",2),x([w()],G.prototype,"enableAR",2),x([w(je)],G.prototype,"defaultAvatar",2),x([w()],G.prototype,"handModelPath",2),x([w()],G.prototype,"createVRButton",2),x([w()],G.prototype,"createARButton",2);var Po=class{get webxr(){return this._webxr}_webxr;reticle=null;reticleParent=null;hitTestSource=null;reticleActive=!0;previousBackground=null;previousEnvironment=null;sessionRoot=null;_previousParent=null;get context(){return this.webxr.context}constructor(e){this._webxr=e}arDomOverlay=null;arOverlayElement=null;noHitTestAvailable=!1;didPlaceARSessionRoot=!1;getAROverlayContainer(){this.arDomOverlay=this.webxr.context.domElement;let e=this.arDomOverlay;return e.getAROverlayContainer?this.arOverlayElement=e.getAROverlayContainer():this.arOverlayElement=this.arDomOverlay,this.arOverlayElement}setReticleActive(e){this.reticleActive=e}async onBegin(e){let t=this.webxr.context;this.reticleActive=!0,this.didPlaceARSessionRoot=!1,this.getAROverlayContainer();let n=navigator.userAgent?.includes("OculusBrowser")?0:1,i=n===1?4:2;for(let s=0;s<i;s++)Y.Create(this.webxr,s,this.webxr.gameObject,n);(!this.sessionRoot||this.sessionRoot.destroyed||!this.sessionRoot.activeAndEnabled)&&(this.sessionRoot=R.findObjectOfType(mt,t)),this.previousBackground=t.scene.background,this.previousEnvironment=t.scene.environment,t.scene.background=null,e.requestReferenceSpace("viewer").then(s=>{e.requestHitTestSource({space:s}).then(a=>{this.hitTestSource=a}).catch(a=>{this.noHitTestAvailable=!0,console.warn("WebXR: Hit test not supported")})}),!this.reticle&&this.sessionRoot&&(this.reticle=new yb(new Eb(.07,.09,32).rotateX(-Math.PI/2),new _b),this.reticle.name="AR Placement reticle",this.reticle.matrixAutoUpdate=!1,this.reticle.visible=!1,this.reticleParent=new rp,this.reticleParent.name="AR Reticle Parent",this.reticleParent.matrixAutoUpdate=!1,this.reticleParent.add(this.reticle),this.reticleParent.matrix.copy(this.sessionRoot.gameObject.matrixWorld),this.webxr.scene?(this.context.scene.add(this.reticleParent),this.context.scene.visible=!0):console.warn("Could not found WebXR Rig")),this._previousParent=this.webxr.gameObject,Po.tempWebXRObject||(Po.tempWebXRObject=new rp),this.context.scene.add(Po.tempWebXRObject),R.addComponent(Po.tempWebXRObject,this.webxr),this.sessionRoot?(this.sessionRoot.webAR=this,this.sessionRoot?.onBegin(e)):console.warn("No WebARSessionRoot found in scene");let r=this.context.domElement;r?.onEnterAR?.call(r,e,this.arOverlayElement),this.context.mainCameraComponent?.applyClearFlagsIfIsActiveCamera()}onEnd(e){this._previousParent&&(console.log("ADD",this._previousParent),R.addComponent(this._previousParent,this.webxr),this._previousParent=null),this.hitTestSource=null;let t=this.webxr.context;if(t.scene.background=this.previousBackground,t.scene.environment=this.previousEnvironment,this.sessionRoot&&this.sessionRoot.onEnd(this.webxr.Rig,e),this.arDomOverlay){let n=this.arOverlayElement;n.onExitAR?.call(n,e)}this.context.mainCameraComponent?.applyClearFlagsIfIsActiveCamera()}onUpdate(e,t){if(this.noHitTestAvailable===!0){if(this.reticle&&(this.reticle.visible=!1),!this.didPlaceARSessionRoot){this.didPlaceARSessionRoot=!0;let i=this.webxr.Rig,r=Cb.clone();if(i){let s=new sp(0,0,0).add(i.position).divideScalar(this.sessionRoot?.arScale??1);r.multiply(new op().makeTranslation(s.x,s.y,s.z))}this.sessionRoot?.placeAt(i,r)}return}if(!this.hitTestSource)return;let n=t.getHitTestResults(this.hitTestSource);if(n.length){let i=n[0],r=this.webxr.context.renderer.xr.getReferenceSpace();if(r){let s=i.getPose(r);if(this.sessionRoot){let a=this.sessionRoot.onUpdate(this.webxr.Rig,e,s);this.didPlaceARSessionRoot=a}if(this.reticle&&(this.reticle.visible=this.reticleActive,this.reticleActive&&s)){let a=s.transform.matrix;this.reticle.matrix.fromArray(a),this.webxr.Rig&&this.reticle.matrix.premultiply(this.webxr.Rig.matrix)}}}else this.sessionRoot?.onUpdate(this.webxr.Rig,e,null),this.reticle&&(this.reticle.visible=!1)}},li=Po;j(li,"tempWebXRObject");var Cb=new op().identity().makeTranslation(0,-.5,0);var ld=!1;var Oo=class extends pt{static get HasAnySelected(){return this._active!==null}transformSelf=!0;orbit=null;selectStartEventListener=[];selectEndEventListener=[];constructor(){super(),this.selectStartEventListener=[],this.selectEndEventListener=[],this._dragDelta=new Q.Vector2}addDragEventListener(e,t){switch(e){case"selectstart":this.selectStartEventListener.push(t);break;case"selectend":this.selectEndEventListener.push(t);break}}_dragHelper=null;start(){this.orbit=R.findObjectOfType(Be,this.context)}_draggingRigidbodies=[];allowEdit(e=null){return this.context.connection.allowEditing}onPointerEnter(e){if(!this.allowEdit(this.gameObject)||G.IsInWebXR)return;let t=R.getComponentInParent(e.object,Oo);!t||t!==this||(Oo.lastHovered=e.object,this.context.domElement.style.cursor="pointer")}onPointerExit(e){!this.allowEdit(this.gameObject)||G.IsInWebXR||Oo.lastHovered===e.object&&(this.context.domElement.style.cursor="auto")}_waitingForDragStart=null;onPointerDown(e){!this.allowEdit(this.gameObject)||G.IsInWebXR||(this._dragDelta.set(0,0),this._didDrag=!1,this._waitingForDragStart=e,e.StopPropagation())}onPointerUp(e){this._waitingForDragStart=null,this.allowEdit(this.gameObject)&&(G.IsInWebXR||(this.onDragEnd(e),e.StopPropagation()))}update(){if(!G.IsInWebXR){if(this._waitingForDragStart){if(!this._didDrag){let t=this.context.input.getPointerPositionDelta(0);if(t&&this._dragDelta.add(t),this._dragDelta.length()>2)this._didDrag=!0;else return}let e=this._waitingForDragStart;this._waitingForDragStart=null,this.onDragStart(e)}this._dragHelper&&this._dragHelper.hasSelected&&this.onUpdateDrag(),this._isDragging&&this._dragHelper?.hasSelected===!1&&this.onDragEnd(null)}}_isDragging=!1;_marker=null;_dragDelta;_didDrag=!1;onDragStart(e){if(!this._dragHelper)if(this.context.mainCamera)this._dragHelper=new Xa(this.context.mainCamera);else return;if(!e||!e.object)return;let t=R.getComponentInParent(e.object,Oo);if(!t||t!==this)return;let n=e.object;this.transformSelf&&(n=this.gameObject);let i={selected:n,attached:n};for(let c of this.selectStartEventListener)c(this,i);if(!i.attached)return;i.attached,n=i.attached,this._isDragging=!0,this._dragHelper.setSelected(n,this.context),this.orbit&&(this.orbit.enabled=!1);let r=R.getComponentInChildren(n,Je);ld&&console.log("DRAG START",r,n),r&&(r.fastMode=!0,r?.requestOwnership()),this._marker=R.addNewComponent(n,ft),this._draggingRigidbodies.length=0;let s=R.getComponentsInChildren(n,q);s&&this._draggingRigidbodies.push(...s);let a=Cl();R.invokeOnChildren(this._dragHelper.selected,a("onDragStart"))}onUpdateDrag(){if(!!this._dragHelper){this._dragHelper.onUpdate(this.context);for(let e of this._draggingRigidbodies)e.wakeUp(),e.resetVelocities()}}onDragEnd(e){if(!this||!this._isDragging||(this._isDragging=!1,!this._dragHelper))return;for(let i of this._draggingRigidbodies)i.setVelocity(i.smoothedVelocity);this._draggingRigidbodies.length=0;let t=this._dragHelper.selected;if(ld&&console.log("DRAG END",t,t?.visible),this._dragHelper.setSelected(null,this.context),this.orbit&&(this.orbit.enabled=!0),e?.object){let i=R.getComponentInChildren(e.object,Je);i&&(i.fastMode=!1),this._marker&&this._marker.destroy()}for(let i of this.selectEndEventListener)i(this);let n=Cl();R.invokeOnChildren(t,n("onDragEnd"))}},$t=Oo;j($t,"_active",null),j($t,"lastHovered");var cd=class{get hasSelected(){return this._selected!==null&&this._selected!==void 0}get selected(){return this._selected}_selected=null;_context=null;_camera;_cameraPlane=new Q.Plane;_hasGroundPlane=!1;_groundPlane=new Q.Plane;_groundOffset=new Q.Vector3;_groundOffsetFactor=0;_groundDistance=0;_groundPlanePoint=new Q.Vector3;_raycaster=new Q.Raycaster;_cameraPlaneOffset=new Q.Vector3;_intersection=new Q.Vector3;_worldPosition=new Q.Vector3;_inverseMatrix=new Q.Matrix4;_rbs=[];_groundLine;_groundMarker;constructor(e){this._camera=e;let t=new Q.Line(cd.geometry),n=t.material;n.color=new Q.Color(.4,.4,.4),t.layers.set(2),t.name="line",t.scale.y=1,this._groundLine=t;let i=new Q.SphereGeometry(.5,22,22),r=new Q.MeshBasicMaterial({color:n.color}),s=new Q.Mesh(i,r);s.visible=!1,s.layers.set(2),this._groundMarker=s}setSelected(e,t){if(this._selected&&t)for(let n of this._rbs)n.wakeUp(),n.setVelocity(0,0,0);if(this._selected&&ue.Remove(t,this._selected),this._selected=e,this._context=t,this._rbs.length=0,e?(t.scene.add(this._groundLine),t.scene.add(this._groundMarker)):(this._groundLine.removeFromParent(),this._groundMarker.removeFromParent()),this._selected){if(!t){console.error("DragHelper: no context");return}ue.Add(t,this._selected,null),this._groundOffsetFactor=0,this._hasGroundPlane=!0,this._groundOffset.set(0,0,0),this._requireUpdateGroundPlane=!0,this.onUpdateScreenSpacePlane()}}_groundOffsetVector=new Q.Vector3(0,1,0);_requireUpdateGroundPlane=!0;_didDragOnGroundPlaneLastFrame=!1;onUpdate(e){if(!this._context)return;let t=" ",n="d",i="s",r=this._context?.input.isKeyPressed(t)||this._context?.input.isKeyPressed(n),s=this._context.input.getTouchesPressedCount()>=2||r;if(s){let c=this._context.input.getPointerPositionDelta(0);c&&(this._groundOffsetVector.set(0,1,0),this._selected?.rotateOnWorldAxis(this._groundOffsetVector,c.x*this._context.time.deltaTime))}let a=this._context.input.getPointerPositionRC(0);if(!!a&&(this._raycaster.setFromCamera(a,this._camera),this._selected)){ld&&console.log("UPDATE DRAG",this._selected),this._groundOffsetVector.set(0,1,0);let c=B(this._camera).clone().sub(B(this._selected)).normalize(),d=Math.abs(c.dot(this._groundOffsetVector)),l=this._context?.input.isKeyPressed(t)||this._context?.input.isKeyPressed(n),u=!s&&d>.2&&!l&&this._context.input.getPointerPressedCount()<=1,h=this._didDragOnGroundPlaneLastFrame!==u;if(this._didDragOnGroundPlaneLastFrame=u,this._hasGroundPlane||(this._requireUpdateGroundPlane=!0),(this._requireUpdateGroundPlane||!u||h)&&this.onUpdateGroundPlane(),this._requireUpdateGroundPlane=!1,this._hasGroundPlane)if(this._raycaster.ray.intersectPlane(this._groundPlane,this._intersection)){let b=this._intersection.y;if(this._groundPlanePoint.copy(this._intersection).sub(this._groundOffset),this._groundPlanePoint.y=b,u){this._groundOffsetVector.set(0,1,0);let _=this._intersection.sub(this._groundOffset).add(this._groundOffsetVector.multiplyScalar(this._groundOffsetFactor));this.onUpdateWorldPosition(_,this._groundPlanePoint,!1),this.onDidUpdate();return}}else this._groundPlanePoint.set(0,99999,0);h&&this.onUpdateScreenSpacePlane(),this._requireUpdateGroundPlane=!0,this._raycaster.ray.intersectPlane(this._cameraPlane,this._intersection)&&(this.onUpdateWorldPosition(this._intersection.sub(this._cameraPlaneOffset),this._groundPlanePoint,!0),this.onDidUpdate())}}onUpdateWorldPosition(e,t,n){if(!!this._selected){if(n){let i=B(this._selected);i.y=e.y,e=i}if(J(this._selected,e),J(this._groundLine,e),this._hasGroundPlane?this._groundLine.scale.y=this._groundDistance:this._groundLine.scale.y=1e3,this._groundMarker.visible=t!==null,t){let i=B(this._camera).distanceTo(t)*.01;this._groundMarker.scale.set(i,i,i),J(this._groundMarker,t)}}}onUpdateScreenSpacePlane(){if(!this._selected||!this._context)return;let e=this._context.input.getPointerPositionRC(0);!e||(this._raycaster.setFromCamera(e,this._camera),this._cameraPlane.setFromNormalAndCoplanarPoint(this._camera.getWorldDirection(this._cameraPlane.normal),this._worldPosition.setFromMatrixPosition(this._selected.matrixWorld)),this._raycaster.ray.intersectPlane(this._cameraPlane,this._intersection)&&this._selected.parent&&(this._inverseMatrix.copy(this._selected.parent.matrixWorld).invert(),this._cameraPlaneOffset.copy(this._intersection).sub(this._worldPosition.setFromMatrixPosition(this._selected.matrixWorld))))}onUpdateGroundPlane(){if(!this._selected||!this._context)return;let e=B(this._selected),t=new Q.Ray(new Q.Vector3(0,.1,0).add(e),new Q.Vector3(0,-1,0)),n=new ce;n.ignore=[this._selected];let i=this._context.physics.raycastFromRay(t,n);for(let r=0;r<i.length;r++){let s=i[r];if(!s.face||this.contains(this._selected,s.object))continue;let a=new Q.Vector3(0,1,0);this._groundPlane.setFromNormalAndCoplanarPoint(a,s.point);break}this._hasGroundPlane=!0,this._groundPlane.setFromNormalAndCoplanarPoint(t.direction.multiplyScalar(-1),t.origin),this._raycaster.ray.intersectPlane(this._groundPlane,this._intersection),this._groundDistance=this._intersection.distanceTo(e),this._groundOffset.copy(this._intersection).sub(e)}onDidUpdate(){ne.markDirty(this._selected);for(let e of this._rbs)e.wakeUp(),e.resetForcesAndTorques(),e.setAngularVelocity(0,0,0)}contains(e,t){if(e===t)return!0;if(e.children){for(let n of e.children)if(this.contains(n,t))return!0}return!1}},Xa=cd;j(Xa,"geometry",new Q.BufferGeometry().setFromPoints([new Q.Vector3(0,0,0),new Q.Vector3(0,-1,0)]));var Lt=class extends O{url=null;urlParameterName=null;localhost=null;awake(){this.context.connection.registerProvider(this)}getWebsocketUrl(){let e=this.url?Lt.GetUrl(this.url,this.localhost):null;if(this.urlParameterName){let r=I(this.urlParameterName);r&&typeof r=="string"&&(e=r)}if(!e)return null;let n=new RegExp("(((https?)|(?<socket_prefix>wss?))://)?(www.)?(?<url>.+)","gm").exec(e);return n?.groups?n?.groups.socket_prefix?e:"wss://"+n?.groups.url:null}static GetUrl(e,t){let n=e,i=Lt.IsLocalNetwork()&&t;return i&&(n=t),e?.startsWith("/")&&(n=(i?n:window.location.origin)+e),n}static IsLocalNetwork(e=window.location.hostname){return rr(e)}};var ci=class extends O{filesBackendUrl;localhost;_dragOver;_drop;onEnable(){this.filesBackendUrl=this.filesBackendUrl?Lt.GetUrl(this.filesBackendUrl,this.localhost):void 0,this._dragOver=this.onDrag.bind(this),this._drop=this.onDrop.bind(this),this.context.domElement.addEventListener("dragover",this._dragOver),this.context.domElement.addEventListener("drop",this._drop)}onDisable(){this.context.domElement.removeEventListener("dragover",this._dragOver),this.context.domElement.removeEventListener("drop",this._drop)}onDrag(e){e.preventDefault()}async onDrop(e){if(console.log(e),!e.dataTransfer)return;e.preventDefault();let t=e.dataTransfer.items;if(!!t)for(let n in t){let i=t[n];if(i.kind==="file"){let r=i.getAsFile();if(!r)continue;console.log("Register file "+r.name+" to",this.filesBackendUrl,r);let s=await wh(r,this.context,this.filesBackendUrl);s&&this.addObject(e,s)}else i.kind==="string"&&i.type=="text/plain"&&i.getAsString(async r=>{console.log("dropped url",r);try{let s=new URL(r);if(!s)return;let a=await xh(s,this.context);a&&this.addObject(e,a)}catch{console.log("dropped string is not a valid URL!",r)}})}}async addObject(e,t){console.log("Dropped",t);let n=new ce;n.setMask(16777215),n.screenPointFromOffset(e.offsetX,e.offsetY);let i=this.context.physics.raycast(n),r=t.scene;if(i&&i.length>0)for(let s of i){r.position.copy(s.point);break}this.gameObject.add(r),this.dispatchEvent(new CustomEvent("object-added",{detail:t}))}};x([w()],ci.prototype,"filesBackendUrl",2),x([w()],ci.prototype,"localhost",2);import{Vector3 as Tb,Quaternion as Rb,Object3D as ap}from"three";var en=class extends pt{parent=null;object=null;limitCount=10;limitInterval=60;_currentCount=0;_startPosition=null;_startQuaternion=null;awake(){if(this.object){if(this.object===this.gameObject){console.error("Can not duplicate self");return}this.object.visible=!1,this._startPosition=this.object.position?.clone()??new Tb(0,0,0),this._startQuaternion=this.object.quaternion?.clone()??new Rb(0,0,0,1)}let e=R.getComponentInParent(this.gameObject,$t);e?e.addDragEventListener("selectstart",(t,n)=>{if(this._currentCount>=this.limitCount){n.attached=null;return}let i=this.handleDuplication(n.selected);i&&(console.assert(i!==n.selected,"Duplicated object is original"),n.attached=i)}):console.warn("Could no find drag controls in parent",this.name),Y.addEventListener("select-start",(t,n)=>{if(this._currentCount>=this.limitCount){n.grab=null;return}let i=this.handleDuplication(n.selected);i&&(n.grab=i)}),this.cloneLimitIntervalFn()}cloneLimitIntervalFn(){this.destroyed||(this._currentCount>0&&(this._currentCount-=1),setTimeout(()=>{this.cloneLimitIntervalFn()},this.limitInterval/this.limitCount*1e3))}handleDuplication(e){if(this._currentCount>=this.limitCount||!this.object)return null;if(e===this.gameObject||this.handleMultiObject(e)){if(this.object===this.gameObject)return null;this.object.visible=!0,this._startPosition&&this.object.position.copy(this._startPosition),this._startQuaternion&&this.object.quaternion.copy(this._startQuaternion);let t=new Ie;this.parent||(this.parent=this.gameObject.parent),this.parent&&(t.parent=this.parent.guid??this.parent.userData?.guid,t.keepWorldPosition=!0),t.position=this.worldPosition,t.rotation=this.worldQuaternion,t.context=this.context,this._currentCount+=1;let n=R.instantiateSynced(this.object,t);return console.assert(n!==this.object,"Duplicated object is original"),this.object.visible=!1,this._startPosition&&this.object.position.clone().copy(this._startPosition),this._startQuaternion&&this.object.quaternion.clone().copy(this._startQuaternion),n}return null}handleMultiObject(e){return this.gameObject.type==="Group"||this.gameObject.type==="Object3D"?this.isInChildren(this.gameObject,e):!1}isInChildren(e,t){if(!e)return!1;if(e===t)return!0;if(e.children){for(let n of e.children)if(this.isInChildren(n,t))return!0}return!1}};x([w(ap)],en.prototype,"parent",2),x([w(ap)],en.prototype,"object",2),x([w()],en.prototype,"limitCount",2),x([w()],en.prototype,"limitInterval",2);var Tr=class extends O{};import{FlyControls as Sb}from"three/examples/jsm/controls/FlyControls";var Rr=class extends O{_controls=null;onEnable(){let e=R.getComponent(this.gameObject,se)?.cam;this._controls=new Sb(e,this.context.renderer.domElement),this._controls.rollSpeed=.5,this._controls.movementSpeed=3,this._controls.dragToLook=!0}onDisable(){this._controls?.dispose(),this._controls=null}update(){this._controls&&this._controls.update(this.context.time.deltaTime)}};import*as lp from"three";import{Color as Pb}from"three";var Pn=class extends O{objectBounds=!1;color;isGizmo=!0;_gizmoObject=null;_boxHelper=null;onEnable(){this.isGizmo&&!dn||(this._gizmoObject||(this.objectBounds&&this.gameObject.isMesh===!0?this._gizmoObject=new lp.BoxHelper(this.gameObject,this.color??16776960):(this.objectBounds=!1,this._gizmoObject=ja(this.color??16776960))),this.objectBounds?(this.scene.add(this._gizmoObject),this._boxHelper=this._gizmoObject,this.startCoroutine(this.syncObjectBounds(),3)):this.gameObject.add(this._gizmoObject))}onDisable(){this._gizmoObject&&this.gameObject.remove(this._gizmoObject)}*syncObjectBounds(){for(;this._boxHelper;)this._boxHelper?.update(),yield}};x([w()],Pn.prototype,"objectBounds",2),x([w(Pb)],Pn.prototype,"color",2),x([w()],Pn.prototype,"isGizmo",2);import{GLTFExporter as Ub}from"three/examples/jsm/exporters/GLTFExporter.js";import{BufferAttribute as dd,Matrix4 as Ob,Vector3 as cp,Quaternion as kb}from"three";var ys=class{constructor(e){this.writer=e,this.name="EXT_mesh_gpu_instancing"}writeNode(e,t){if(e.constructor.name!=="InstancedMesh")return;let n=this.writer,i=n.extensionsUsed,r={};t.extensions=t.extensions||{},t.extensions[this.name]=r;let s=new Ob,a=new Array,c=new Array,d=new Array;for(let b=0;b<e.count;b++){e.getMatrixAt(b,s);let _=new cp,v=new kb,y=new cp;s.decompose(_,v,y),a.push(_.x,_.y,_.z),c.push(v.x,v.y,v.z,v.w),d.push(y.x,y.y,y.z)}let l=new Float32Array(a),u=new Float32Array(c),h=new Float32Array(d);r.attributes={TRANSLATION:n.processAccessor(new dd(l,3)),ROTATION:n.processAccessor(new dd(u,4)),SCALE:n.processAccessor(new dd(h,3))},i[this.name]=!0}};import*as In from"three";import*as _s from"three";var On=class{get lightmap(){return this.lightmapTexture}set lightmap(e){e!==this.lightmapTexture&&(this.lightmapTexture=e,this.setupLightmap())}lightmapIndex=-1;lightmapScaleOffset=new _s.Vector4(1,1,0,0);context;gameObject;lightmapTexture=null;lightmapScaleOffsetUniform={value:new _s.Vector4(1,1,0,0)};lightmapUniform={value:null};beforeRenderCallback;constructor(e,t){this.gameObject=e,this.context=t}init(e,t,n,i=!1){if(console.assert(this.gameObject!==void 0&&this.gameObject!==null,"Missing gameobject",this),this.lightmapIndex=e,this.lightmapIndex<0)return;this.lightmapScaleOffset=t,this.lightmapTexture=n,i&&this.setLightmapDebugMaterial(),this.setupLightmap()}bindOnBeforeRender(){this.beforeRenderCallback=this.onBeforeRenderThreeComplete.bind(this),this.context.addBeforeRenderListener(this.gameObject,this.beforeRenderCallback)}onBeforeRenderThreeComplete(e,t,n,i,r,s){this.onBeforeRenderThree(r)}setupLightmap(){if(this.gameObject.type==="Object3D")return;if(this.gameObject.type==="Group"){console.warn("Lightmap on multimaterial object is not supported yet... please ask kindly for implementation.");return}console.assert(this.gameObject.type==="Mesh","Lightmap only works on meshes",this);let e=this.gameObject;e.geometry.getAttribute("uv2")||e.geometry.setAttribute("uv2",e.geometry.getAttribute("uv"));let t=this.gameObject.material.clone();if(this.gameObject.material=t,this.gameObject.material.onBeforeCompile=(n,i)=>{n.uniforms.lightmap=this.lightmapUniform,n.uniforms.lightmapScaleOffset=this.lightmapScaleOffsetUniform},this.lightmapIndex>=0){let n=this.lightmapTexture,i=this.gameObject.material;i&&n&&(i.uniforms||(i.uniforms={}),i.lightMap=n,i.uniforms.lightmap={value:n})}}onBeforeRenderThree(e){let t=e.uniforms;t&&t.lightmap&&(this.lightmapScaleOffsetUniform.value=this.lightmapScaleOffset,this.lightmapUniform.value=this.lightmapTexture,t.lightmap=this.lightmapUniform,t.lightmapScaleOffset=this.lightmapScaleOffsetUniform)}setLightmapDebugMaterial(){this.gameObject.material=new _s.ShaderMaterial({vertexShader:`
176
+ --------------`),n[r]=a,n.needsUpdate=!0,Ye)){let c=Fc.get(n);c||(c={},Fc.set(n,c));let d=c[r];d||(d=c[r]={original:s,lod0:a}),d.lod0=a}}))}}get name(){return jc}parser;sourceId;context;constructor(e,t,n){this.parser=e,this.sourceId=t,this.context=n}_loading=[];afterRoot(e){return Ye&&console.log("AFTER",this.sourceId,e),this.parser.json.textures?.forEach((t,n)=>{if(t?.extensions){let i=t?.extensions[jc];if(i){let r=this.parser.getDependency("texture",n);this._loading.splice(this._loading.indexOf(n),1),r.then(s=>{Ye&&console.log("register texture",s.name,s.uuid,i),s.userData.deferred=i,cs.cache.set(s.uuid,i)})}}}),null}static async getOrLoadTexture(e,t,n,i,r,s){let a=r.uuid,c=cs.cache.get(a);if(c){Ye&&console.log(a,c.uri,c.guid);let d=cn(t,c.uri);if(d.endsWith(".glb")||d.endsWith(".gltf")){if(!c.guid)return console.warn("missing pointer for glb/gltf texture",c),null;let l=d+"_"+c.guid;if(this.resolved[l])return Ye&&console.log("Texture has already been loaded: "+l,n.name,i,r.name),this.resolved[l];let u=new Cg;Zn(u,e),Ye&&console.log("Load "+d,n.name,i,c.guid);let h=await u.loadAsync(d),b=h.parser;Ye&&console.log("Loading finished "+d,n.name,i,c.guid);let _=-1,v=!1;for(let m of h.parser.json.textures)if(_++,m?.extensions){let f=m?.extensions[jc];if(f?.guid&&f.guid===c.guid){v=!0;break}}if(!v)return null;let y=await b.getDependency("texture",_);return y&&(y.guid=c.guid),this.resolved[l]=y,Ye&&console.log(n.name,i,'change "'+r.name+'" \u2192 "'+y.name+'"',d,_,y,n,l),y}else{Ye&&console.log("Load texture from uri: "+d);let u=await new xg().loadAsync(d);return u&&Ye?console.log(c,u):console.warn("failed loading",d),u}}else Ye&&console.warn("unknown uuid",r.name,r.uuid,r);return null}},ei=cs;j(ei,"cache",new Map),j(ei,"resolved",{});function Uc(o){let e=new vo;return o.register(t=>(e.parser=t,e)),e}var Bc=class{resolvePath(e){return e.includes("/extensions/builtin_components/")?e.replace("/extensions/builtin_components/","/userData/components/"):e.includes("extensions/builtin_components/")?e.replace("extensions/builtin_components/","/userData/components/"):e}};function Gc(o,e,t){o.register(i=>new Ma(i)),o.register(i=>new Ds(i)),o.register(i=>new wa(i,e.lightmaps,t)),o.register(i=>new Da(i,t,e)),o.register(i=>new Oa(i,t)),o.register(i=>new _r(i,t)),o.register(i=>new ei(i,t,e)),o.register(i=>new Ia(i));let n=o.setAnimationPointerResolver;typeof n=="function"&&n.bind(o)(new Bc)}import{Vector3 as Tg}from"three";var ti=class extends O{from;to;width=0;centered=!0;_centerPos;awake(){this._centerPos=new Tg}update(){if(!this.from||!this.to)return;let e=B(this.from).clone(),t=B(this.to).clone(),n=e.distanceTo(t);this._centerPos.copy(e),this._centerPos.add(t),this._centerPos.multiplyScalar(.5),J(this.gameObject,this.centered?this._centerPos:e),this.gameObject.lookAt(B(this.to).clone()),this.gameObject.scale.set(this.width,this.width,n)}};x([w(R)],ti.prototype,"from",2),x([w(R)],ti.prototype,"to",2);var bn=class{time;value;inTangent;inWeight;outTangent;outWeight;weightedMode};x([w()],bn.prototype,"time",2),x([w()],bn.prototype,"value",2),x([w()],bn.prototype,"inTangent",2),x([w()],bn.prototype,"inWeight",2),x([w()],bn.prototype,"outTangent",2),x([w()],bn.prototype,"outWeight",2),x([w()],bn.prototype,"weightedMode",2);var Mi=class{keys;get duration(){return!this.keys||this.keys.length==0?0:this.keys[this.keys.length-1].time}evaluate(e){if(!this.keys||this.keys.length==0)return 0;let t=null;for(let n of this.keys){if(t&&n.time>e&&e>t.time)return U.lerp(t.value,n.value,(e-t.time)/(n.time-t.time));t=n}return this.keys[this.keys.length-1].value}};x([w(bn)],Mi.prototype,"keys",2);import*as Wh from"three";import*as ds from"three";import{PositionalAudioHelper as Rg}from"three/examples/jsm/helpers/PositionalAudioHelper.js";var Ke=I("debugaudio");var xe=class extends O{static get userInteractionRegistered(){return xe._didCallBeginWaitForUserInteraction||(xe._didCallBeginWaitForUserInteraction=!0,xe._beginWaitForUserInteraction()),xe._userInteractionRegistered}static registerWaitForAllowAudio(e){if(e!==null){if(this._userInteractionRegistered){e();return}this.callbacks.indexOf(e)===-1&&this.callbacks.push(e),xe._didCallBeginWaitForUserInteraction||(xe._didCallBeginWaitForUserInteraction=!0,xe._beginWaitForUserInteraction())}}static _beginWaitForUserInteraction(e=null){if(this._userInteractionRegistered){e&&e();return}e!==null&&this.registerWaitForAllowAudio(e);let n=(()=>{if(n!=null&&!xe._userInteractionRegistered){xe._userInteractionRegistered=!0,console.log("registered interaction, can play audio now"),document.removeEventListener("pointerdown",n),document.removeEventListener("click",n),document.removeEventListener("dragstart",n),document.removeEventListener("touchstart",n);for(let i of this.callbacks)i();this.callbacks.length=0}}).bind(this);document.addEventListener("pointerdown",n),document.addEventListener("click",n),document.addEventListener("dragstart",n),document.addEventListener("touchstart",n)}clip="";playOnAwake=!1;get loop(){return this.sound&&(this._loop=this.sound.getLoop()),this._loop}set loop(e){this._loop=e,this.sound&&this.sound.setLoop(e)}get spatialBlend(){return this._spatialBlend}set spatialBlend(e){e!==this._spatialBlend&&(this._spatialBlend=e,this._needUpdateSpatialDistanceSettings=!0)}get minDistance(){return this._minDistance}set minDistance(e){this._minDistance!==e&&(this._minDistance=e,this._needUpdateSpatialDistanceSettings=!0)}get maxDistance(){return this._maxDistance}set maxDistance(e){this._maxDistance!==e&&(this._maxDistance=e,this._needUpdateSpatialDistanceSettings=!0)}_spatialBlend=0;_minDistance=1;_maxDistance=100;get volume(){return this._volume}set volume(e){this._volume=e,this.sound&&(Ke&&console.log(this.name,"audio set volume",e),this.sound.setVolume(e))}_volume=1;rollOffMode=0;_loop=!1;sound=null;helper=null;wasPlaying=!1;audioLoader=null;shouldPlay=!1;_lastClipStartedLoading=null;get Sound(){if(!this.sound&&xe._userInteractionRegistered){let e=R.getComponent(this.context.mainCamera,kt)??R.findObjectOfType(kt,this.context);e?.listener&&(this.sound=new ds.PositionalAudio(e.listener),this.gameObject.add(this.sound))}return this.sound}get ShouldPlay(){return this.shouldPlay}_focusCallback;awake(){this.audioLoader=new ds.AudioLoader,this.playOnAwake&&(this.shouldPlay=!0),window.addEventListener("visibilitychange",e=>{switch(document.visibilityState){case"hidden":this.wasPlaying=this.isPlaying,this.pause();break;case"visible":this.wasPlaying&&this.play();break}}),this._focusCallback=()=>{this.enabled&&this.playOnAwake&&!this.isPlaying&&xe._userInteractionRegistered&&this.play()},this.context.application.addEventListener("application-visible",this._focusCallback)}onDestroy(){this.context.application.removeEventListener("application-visible",this._focusCallback)}onEnable(){xe._userInteractionRegistered?this.playOnAwake&&this.context.application.isVisible&&this.play():xe._beginWaitForUserInteraction(()=>{this.enabled&&!this.destroyed&&this.shouldPlay&&this.loadAndPlay(this.clip)})}onDisable(){this.stop()}lerp=(e,t,n)=>e*(1-n)+t*n;onLoaded(e){Ke&&console.log("audio buffer loaded"),xe.registerWaitForAllowAudio(()=>{Ke&&console.log("finished loading",e);let t=this.Sound;if(!t){console.warn("Failed getting sound",this.name);return}t.isPlaying&&t.stop(),t.setBuffer(e),t.loop=this.loop,t.setVolume(this.volume),t.autoplay=this.shouldPlay,this.applySpatialDistanceSettings(),t.isPlaying&&t.stop(),Ke&&console.log(this.name,this.shouldPlay,xe.userInteractionRegistered,this),this.shouldPlay&&xe._userInteractionRegistered&&this.play()})}applySpatialDistanceSettings(){let e=this.sound;if(!e)return;this._needUpdateSpatialDistanceSettings=!1;let t=this.lerp(10*this._maxDistance/Math.max(1e-4,this.spatialBlend),this._minDistance,this.spatialBlend);switch(Ke&&console.log(this.name,this._minDistance,this._maxDistance,this.spatialBlend,"Ref distance="+t),e.setRefDistance(t),e.setMaxDistance(Math.max(.01,this._maxDistance)),this.rollOffMode){case 0:e.setDistanceModel("exponential");break;case 1:e.setDistanceModel("linear");break;case 2:break}this.spatialBlend>0?Ke&&!this.helper&&(this.helper=new Rg(e,e.getRefDistance()),e.add(this.helper)):this.helper&&this.helper.parent&&this.helper.removeFromParent()}loadAndPlay(e){if(e&&(this.clip=e),this.clip&&(Ke&&console.log(this.clip),this.clip.endsWith(".mp3")||this.clip.endsWith(".wav"))){if(this.audioLoader||(this.audioLoader=new ds.AudioLoader),this.shouldPlay=!0,this._lastClipStartedLoading===this.clip){Ke&&console.log("Is currently loading:",this._lastClipStartedLoading,this);return}this._lastClipStartedLoading=this.clip,Ke&&console.log("load audio",this.clip),this.audioLoader.load(this.clip,this.onLoaded.bind(this),()=>{},console.error)}}play(e=void 0){if(!this.audioLoader||!this.sound||e&&e!==this.clip){this.loadAndPlay(e);return}this.shouldPlay=!0,this._hasEnded=!1,Ke&&console.log("play",this.sound?.getVolume(),this.sound),this.sound&&!this.sound.isPlaying&&this.sound.play()}pause(){Ke&&console.log("Pause",this),this._hasEnded=!0,this.shouldPlay=!1,this.sound&&this.sound.isPlaying&&this.sound.source&&(this._lastContextTime=this.sound?.context.currentTime,this.sound.pause())}stop(){Ke&&console.log("Pause",this),this._hasEnded=!0,this.shouldPlay=!1,this.sound&&this.sound.source&&(this._lastContextTime=this.sound?.context.currentTime,Ke&&console.log(this._lastContextTime),this.sound.stop())}_lastContextTime=0;get isPlaying(){return this.sound?.isPlaying??!1}set isPlaying(e){}get time(){return this.sound?.source?this.sound.source?.context.currentTime-this._lastContextTime+this.sound.offset:0}set time(e){if(this.sound){if(e===this.sound.offset)return;let t=this.isPlaying;this.stop(),this.sound.offset=e,t&&this.play()}}_hasEnded=!0;_needUpdateSpatialDistanceSettings=!1;update(){this.helper&&(this.isPlaying&&this.helper.update(),this.helper.visible=this.isPlaying),this._needUpdateSpatialDistanceSettings&&this.applySpatialDistanceSettings(),this.sound&&!this.sound.isPlaying&&this.shouldPlay&&!this._hasEnded&&(this._hasEnded=!0,Ke&&console.log("Audio clip ended",this.clip),this.sound.dispatchEvent({type:"ended",target:this}))}},Z=xe;j(Z,"_didCallBeginWaitForUserInteraction",!1),j(Z,"callbacks",[]),j(Z,"_userInteractionRegistered",!1),x([w()],Z.prototype,"clip",2),x([w()],Z.prototype,"playOnAwake",2),x([w()],Z.prototype,"loop",1),x([w()],Z.prototype,"spatialBlend",1),x([w()],Z.prototype,"minDistance",1),x([w()],Z.prototype,"maxDistance",1),x([w()],Z.prototype,"volume",1),x([w()],Z.prototype,"rollOffMode",2);import*as ni from"three";import{Color as Sg}from"three";var de=class extends Sg{alpha=1;get isRGBAColor(){return!0}constructor(e,t,n,i){super(e,t,n),this.alpha=i}clone(){let e=super.clone();return e.alpha=this.alpha,e}copy(e){return super.copy(e),"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&&(this.alpha=U.lerp(this.alpha,n.alpha,t)),super.lerp(e,t)}multiply(e){let t=e;return t.alpha&&(this.alpha=this.alpha*t.alpha),super.multiply(e)}};import{PerspectiveCamera as Og}from"three";var Aa=I("debugcam"),se=class extends O{get isCamera(){return!0}get aspect(){return this._cam instanceof Og?this._cam.aspect:this.context.domWidth/this.context.domHeight}get fieldOfView(){return this._fov}set fieldOfView(e){let t=this._fov!=e;this._fov=e,t&&this._cam&&this._cam instanceof ni.PerspectiveCamera&&(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.updateProjectionMatrix())}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.updateProjectionMatrix())}get clearFlags(){return this._clearFlags}set clearFlags(e){e!==this._clearFlags&&(this._clearFlags=e,this.applyClearFlagsIfIsActiveCamera())}orthographic=!1;orthographicSize=5;ARBackgroundAlpha=0;_nearClipPlane=.1;_farClipPlane=1e3;get backgroundColor(){return this._backgroundColor??null}set backgroundColor(e){if(!!e){if(this._backgroundColor)this._backgroundColor.copy(e);else{if(!e.clone)return;this._backgroundColor=e.clone()}e.alpha===void 0&&(this._backgroundColor.alpha=1),this.applyClearFlagsIfIsActiveCamera()}}_backgroundColor;_fov=60;_cam=null;_clearFlags=2;_skybox;get cam(){return this.activeAndEnabled&&this.buildCamera(),this._cam}awake(){this.sourceId||console.warn("Camera has no source - the camera should be exported inside a gltf",this.name)}onEnable(){Aa&&console.log(this),this.buildCamera(),(this.tag=="MainCamera"||!this.context.mainCameraComponent)&&this.context.setCurrentCamera(this),this.applyClearFlagsIfIsActiveCamera()}onDisable(){this.context.removeCamera(this)}buildCamera(){if(this._cam)return;let e=this.gameObject.isCamera,t=null;if(e?t=this.gameObject:t=this.gameObject.children[0],t&&t.isCamera)t.type==="PerspectiveCamera"&&(t.fov=this._fov,t.near=this._nearClipPlane,t.far=this._farClipPlane,t.updateProjectionMatrix());else if(!this.orthographic)t=new ni.PerspectiveCamera(this.fieldOfView,window.innerWidth/window.innerHeight,this._nearClipPlane,this._farClipPlane),t.fov=this.fieldOfView;else{let n=this.orthographicSize*100;t=new ni.OrthographicCamera(window.innerWidth/-n,window.innerWidth/n,window.innerHeight/n,window.innerHeight/-n,this._nearClipPlane,this._farClipPlane)}this._cam=t,this.layer===0&&this._cam.layers.enableAll(),this.tag=="MainCamera"&&this.context.setCurrentCamera(this)}applyClearFlagsIfIsActiveCamera(){if(Aa&&Ft("apply Camera clear flags"),this._cam&&this.context.mainCameraComponent===this)switch(this._clearFlags){case 1:if(this.environmentIsTransparent()&&(!this.ARBackgroundAlpha||this.ARBackgroundAlpha<.001)){this.context.scene.background=null,this.context.renderer.setClearColor(0,0);return}this.enableSkybox();break;case 2:if(this._backgroundColor){let e=this._backgroundColor.alpha;this.environmentIsTransparent()&&(e=this.ARBackgroundAlpha??0),this.context.scene.background=null,this.context.renderer.setClearColor(this._backgroundColor,e)}break;case 4:this.context.scene.background=null,this.context.renderer.setClearColor(0,0);break}}environmentIsTransparent(){let e=this.context.renderer.xr?.getSession();if(!e)return!1;let t=e.environmentBlendMode;Aa&&Ft("Environment blend mode: "+t+" on "+navigator.userAgent);let n=t==="additive"||t==="alpha-blend";if(this.context.xrSessionMode==="immersive-ar"&&t==="opaque"){if(navigator.userAgent?.includes("OculusBrowser"))return!0;if(navigator.userAgent?.includes("Mozilla")&&navigator.userAgent?.includes("Mobile WebXRViewer/v2"))return!0}return n}enableSkybox(){this._skybox||(this._skybox=new Vc(this)),this._skybox.enable()}};x([w()],se.prototype,"fieldOfView",1),x([w()],se.prototype,"nearClipPlane",1),x([w()],se.prototype,"farClipPlane",1),x([w()],se.prototype,"clearFlags",1),x([w()],se.prototype,"orthographic",2),x([w()],se.prototype,"orthographicSize",2),x([w()],se.prototype,"ARBackgroundAlpha",2),x([w(de)],se.prototype,"backgroundColor",1);var Vc=class{_camera;_skybox;get context(){return this._camera?.context}constructor(e){this._camera=e}enable(){this._skybox=this.context.lightmaps.tryGetSkybox(this._camera.sourceId),this._skybox?(Aa&&console.log("Set skybox",this._camera,this._skybox),this._skybox.encoding=ni.sRGBEncoding,this._skybox.mapping=ni.EquirectangularReflectionMapping,this.context.scene.background=this._skybox):console.warn("Failed to load/find skybox texture",this)}};var kt=class extends O{get listener(){return this._listener==null&&(this._listener=new Wh.AudioListener),this._listener}_listener=null;awake(){Z.registerWaitForAllowAudio(()=>{let e=this.listener;if(e==null||e.parent)return;let t=R.getComponentInParent(this.gameObject,se);t?t.cam.add(e):this.gameObject.add(e)})}};import{GLTFLoader as kg}from"three/examples/jsm/loaders/GLTFLoader";import*as La from"three";var us=I("debugavatar"),Di=class{root;head;leftHand;rigthHand;get isValid(){return this.head!==null&&this.head!==void 0}constructor(e,t,n,i){this.root=e,this.head=t,this.leftHand=n,this.rigthHand=i,this.root?.traverse(r=>r.layers.set(2))}},ii=class{avatarRegistryUrl=null;async getOrCreateNewAvatarInstance(e,t){if(!t)return console.error("Can not create avatar: failed to provide id or root object"),null;let n=null;if(typeof t=="string"){if(n=await this.loadAvatar(e,t),!n){let r=new Ie;n=R.instantiate(Ei(t,e.scene),r)}}else n=t;if(!n)return null;let i=this.findAvatar(n);return i.isValid?(us&&console.log("[Custom Avatar] valid config",t,us?i:""),i):(console.warn("[Custom Avatar] config isn't valid",t,us?i:""),null)}async loadAvatar(e,t){if(console.assert(t!=null&&typeof t=="string","Avatar id must not be null"),t.length<=0||!t)return null;if(us&&console.log("[Custom Avatar] "+t+", loading..."),t.endsWith(".glb")||(t+=".glb"),this.avatarRegistryUrl===null){let i=await fetch("./"+t),r=null;if(i.ok){let a=await i.blob();a&&(r=await a.arrayBuffer())}return!r&&(r=await pa(t,t,0,"no url here go away",!0),!r)?null:(await Le().parseSync(e,r,null,0))?.scene??null}let n=new kg;return Zn(n,e),new Promise((i,r)=>{let s=this.avatarRegistryUrl+"/"+t;n.load(s,async a=>{await Le().createBuiltinComponents(e,s,a,null,void 0),i(a.scene)},a=>{us&&console.log("[Custom Avatar] "+a.loaded/a.total*100+"% loaded of "+a.total/1024+"kB")},a=>{console.error("[Custom Avatar] Error when loading: "+a),i(null)})})}cacheModel(e,t){}findAvatar(e){let t=e,n=t;n.children.length==1&&(n=e.children[0]);let i=this.findAvatarPart(n,["head"]),r=this.findAvatarPart(n,["left","hand"]),s=this.findAvatarPart(n,["right","hand"]);if(!i){i=t;let c=new La.Vector3;new La.Box3().setFromObject(i).getSize(c);let d=Math.max(c.x,c.y,c.z);console.warn("[Custom Avatar] Normalizing head scale, it's too big: "+d+" meters! Should be < 0.3m"),d>.3&&i.scale.multiplyScalar(1/d*.3)}return new Di(t,i,r,s)}findAvatarPart(e,t){let n=e.name.toLowerCase(),i=!0;for(let r of t){if(!i)break;n.indexOf(r)===-1&&(i=!1)}if(i)return e;if(e.children)for(let r of e.children){let s=this.findAvatarPart(r,t);if(s)return s}return null}handleCustomAvatarErrors(e){if(!e.ok)throw Error(e.statusText);return e}};import{AxesHelper as Ig}from"three";var vn=class extends O{length=1;depthTest=!0;isGizmo=!0;_axes=null;onEnable(){if(this.isGizmo&&!dn)return;this._axes||(this._axes=new Ig(this.length)),this.gameObject.add(this._axes);let e=this._axes.material;e&&e.depthTest!==void 0&&(e.depthTest=this.depthTest)}onDisable(){!this._axes||this.gameObject.remove(this._axes)}};x([w()],vn.prototype,"length",2),x([w()],vn.prototype,"depthTest",2),x([w()],vn.prototype,"isGizmo",2);import*as Xh from"three";var Er=class extends O{from;to;hint;desiredDistance=1;onEnable(){}update(){if(!this.from||!this.to||!this.hint)return;let e=B(this.to).clone(),t=B(this.from).clone(),n=e.distanceTo(t),i=e.clone();i.sub(t);let r=t.clone();r.add(e),r.multiplyScalar(.5);let s=B(this.hint).clone();s.sub(r);let a=new Xh.Vector3;a.crossVectors(s,i),a.crossVectors(i,a),a.normalize();let c=n*.5,d=Math.max(this.desiredDistance,c),l=Math.sqrt(d*d-c*c),u=a.clone();u.multiplyScalar(l),u.add(r),J(this.gameObject,u);let h=r.clone();h.sub(a),this.gameObject.lookAt(h)}};import*as wr from"three";import*as yn from"three";var Mg=new yn.BoxGeometry(1,1,1);function ja(o=null){let e=new yn.Color(o??14540253),t=new yn.EdgesGeometry(Mg);return new yn.LineSegments(t,new yn.LineBasicMaterial({color:e}))}var Ag=I("gizmos"),dt=class extends O{box=null;_lastMatrixUpdateFrame=-1;isInBox(e,t){if(!!e){if(this.box||(this.box=new wr.Box3),e.type==="Mesh")dt.testBox.setFromObject(e);else if(e.type==="Group"){if(e.children.length>0){dt.testBox.setFromCenterAndSize(dt._position.set(0,0,0),dt._size.set(0,0,0));for(let n=0;n<e.children.length;n++)e.children[n].type==="Mesh"&&dt.testBox.expandByObject(e)}}else{let n=B(e,dt._position),i=ot(e,dt._size);t!==void 0&&i.multiplyScalar(t),dt.testBox.setFromCenterAndSize(n,i)}return this.updateBox(),this.box?.intersectsBox(dt.testBox)}}intersects(e){return e?this.updateBox(!1).intersectsBox(e):!1}updateBox(e=!1){if(this.box||(this.box=new wr.Box3),e||this.context.time.frameCount!=this._lastMatrixUpdateFrame){let t=this._lastMatrixUpdateFrame<0;this._lastMatrixUpdateFrame=this.context.time.frameCount;let n=t,i=B(this.gameObject,dt._position,n),r=ot(this.gameObject,dt._size);this.box.setFromCenterAndSize(i,r)}return this.box}_helper=null;_color=null;awake(){this._helper=null,this._color=null,this.box=null}showHelper(e=null,t=!1){if(!(!Ag&&!t)){if(this._helper){e&&this._color?.set(e),this.gameObject.add(this._helper);return}this._helper=ja(e),this.gameObject.add(this._helper)}}},Ce=dt;j(Ce,"testBox",new wr.Box3),j(Ce,"_position",new wr.Vector3),j(Ce,"_size",new wr.Vector3(.01,.01,.01));import{Quaternion as Vg,Ray as zg,Vector3 as xr}from"three";import*as Qh from"three";var Qt=class{method;enabled;constructor(e,t){this.method=e,this.enabled=t!==void 0?t:!0}invoke(...e){if(this.enabled!==!1){if(!this.method){console.warn("No function. Please check you assigned a method to invoke on export",this);return}this.method(...e)}}},Lg=o=>/^[A-Z]*$/.test(o),Ai=class extends Event{args},he=class{target;key;setEventTarget(e,t){if(this.key=e,this.target=t,this.key!==void 0){let n="",i=!1;for(let r of this.key)i&&Lg(r)&&(n+="-"),i=!0,n+=r.toLowerCase();this.key=n}}_isInvoking=!1;methods=[];constructor(e){this.methods=e??[]}invoke(...e){if(this._isInvoking){console.warn("Circular event invocation detected. Please check your event listeners for circular references.",this);return}this._isInvoking=!0;try{for(let t of this.methods)t.invoke(...e);if(typeof this.target=="object"&&typeof this.key=="string"){let t=this.target.dispatchEvent;if(typeof t=="function"){let n=new Ai(this.key);n.args=e,t.call(this.target,n)}}}finally{this._isInvoking=!1}}addEventListener(e){return this.methods.push(new Qt(e,!0)),e}removeEventListener(e){if(!!e)for(let t=this.methods.length-1;t>=0;t--)this.methods[t].method===e&&(this.methods[t].enabled=!1,this.methods.splice(t,1))}removeAllEventListeners(){this.methods.length=0}};import{Color as jg,Object3D as Hg}from"three";var Nc=class extends qn{constructor(){super([jg,de])}onDeserialize(e){if(e!=null)return e.a!==void 0?new de(e.r,e.g,e.b,e.a):e.alpha!==void 0?new de(e.r,e.g,e.b,e.alpha):new Qh.Color(e.r,e.g,e.b)}onSerialize(e){if(e!=null)return e.a!==void 0?{r:e.r,g:e.g,b:e.b,a:e.a}:{r:e.r,g:e.g,b:e.b}}},E0=new Nc,Wc=class extends qn{constructor(){super(Hg)}onSerialize(e,t){if(t.objectToNode!==void 0&&e.uuid){let n=t.objectToNode[e.uuid];return _e&&console.log(n,e.name,e.uuid),{node:n}}}onDeserialize(e,t){if(e){if(e.node!==void 0&&t.nodeToObject){let n=t.nodeToObject[e.node];return _e&&console.log("Deserialized object reference?",e,n,t?.nodeToObject),n||console.warn("Did not find node: "+e.node,t.nodeToObject,t.object),n}else if(e.guid){if(!t.context){console.error("Missing context");return}let n,i=t.gltf?.scene;return i&&(n=R.findByGuid(e.guid,i)),n||(n=R.findByGuid(e.guid,t.context.scene)),n?_e&&console.log("Deserialized object reference?",e,n,t?.nodeToObject):console.warn("could not resolve reference",e,t.target,t.path,t.context.scene),n}}}},Fg=new Wc,Xc=class extends qn{constructor(){super([ct,O])}onSerialize(e,t){if(e?.guid)return{guid:e.guid}}onDeserialize(e,t){if(e?.guid){_e&&console.log(e.guid,t.root,t.object,t.target);let n=this.findObjectForGuid(e.guid,t.root);if(n)return n;if(t.context)return this.findObjectForGuid(e.guid,t.context?.scene)}}findObjectForGuid(e,t){if(t.guid===e)return t;let n=R.foreachComponent(t,i=>{if(i.guid===e)return i},!1);if(n!==void 0)return n;for(let i=0;i<t.children.length;i++){let r=t.children[i],s=this.findObjectForGuid(e,r);if(s)return s}}},zc=new Xc,Qc=class extends qn{constructor(){super([he])}onSerialize(e,t){console.log("TODO: SERIALIZE EVENT")}onDeserialize(e,t){if(e&&e.type==="EventList"){_e&&console.log("DESERIALIZE EVENT",e);let n=new Array;for(let s of e.calls){_e&&console.log(s);let a=zc.findObjectForGuid(s.target,t.root);!a&&t.context?.scene&&(a=zc.findObjectForGuid(s.target,t.context?.scene));let c=s.method?.length>0;if(a&&c){let h=()=>console.warn(`Could not find method ${s.method} on object ${a.name}`,a,typeof a[s.method]);if(typeof a[s.method]!="function"){let b=!1;s.method.startsWith("set_")&&s.method.length>4&&(s.method=s.method.substring(4),a[s.method]!==void 0&&(b=!0)),b||h()}}let d,l=s.argument;s.argument!==void 0?(typeof l=="object"&&(l=Fg.onDeserialize(s.argument,t),l||(l=zc.onDeserialize(s.argument,t))),d=new Qt(c?(...h)=>u(...h):void 0,s.enabled)):d=new Qt(c?(...h)=>u(...h):void 0,s.enabled);let u=(...h)=>{let b=a[s.method];typeof b=="function"?l!==void 0?b?.call(a,l):b?.call(a,...h):a[s.method]=l};if(d.method||(d.__debuginfo=t.object?.name),!a||!d.method){let h=t.object?"Current object: "+t.object.name+", "+t.object.guid:null;a?console.warn('EventList method not found: "'+s.method+'" on',a):console.warn("EventList is missing target - will be ignored",s.target,h,e)}else n.push(d)}let i=new he(n);_e&&console.log(i);let r=t.target;return r!==void 0&&t.path!==void 0&&i.setEventTarget(t.path,r),i}}},w0=new Qc;import*as _o from"three";import{Vector3 as qh}from"three";var qt=function(o,e){return function(t,n,i){Ug(t,n,i,o,e)}};function Ug(o,e,t,n,i){if(!(!i&&!n&&!o.onValidate)){if(t!==void 0){console.error("Invalid usage of validate decorator. Only fields can be validated.",o,e,t),Ft("Invalid usage of validate decorator. Only fields can be validated. Property: "+e,2);return}if(o.__internalAwake){let r=Symbol(e),s=o.__internalAwake;o.__internalAwake=function(){this[r]===void 0&&(this[r]=this[e],Object.defineProperty(this,e,{set:function(a){if(this[Fs]===!0)this[r]=a;else{n?.call(this,a);let c=this[r];this[r]=a,this.onValidate?.call(this,e,c)}},get:function(){return i?.call(this),this[r]}})),s.call(this)}}}}var qc=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 t of this._positionKeys)delete this.position[t];if(this.quaternion)for(let t of this._quaternionKeys)delete this.quaternion[t]}}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||(this._positionWatch=new Xn(this.obj.position,["x","y","z"])),this._positionWatch.apply(),this.position={},this._positionWatch.subscribeWrite((n,i)=>{if(this.context.physics.isUpdating||this.mute)return;let r=this.position[i];Math.abs(r-n)<1e-5||(this.position[i]=n,this.positionChanged=!0)})),t&&(this._rotationWatch||(this._rotationWatch=new Xn(this.obj.quaternion,["_x","_y","_z","_w"])),this._rotationWatch.apply(),this.quaternion={},this._rotationWatch.subscribeWrite((n,i)=>{if(this.context.physics.isUpdating||this.mute)return;let r=this.quaternion[i];Math.abs(r-n)<1e-5||(this.quaternion[i]=n,this.rotationChanged=!0)}))}stop(){this._positionWatch?.revoke(),this._rotationWatch?.revoke()}},Ha=class extends O{mass=1;useGravity=!0;constraints=0;isKinematic=!1;drag=0;angularDrag=1;detectCollisions=!0;sleepThreshold=.01;collisionDetectionMode=0;get lockPositionX(){return(this.constraints&2)!==0}get lockPositionY(){return(this.constraints&4)!==0}get lockPositionZ(){return(this.constraints&8)!==0}get lockRotationX(){return(this.constraints&16)!==0}get lockRotationY(){return(this.constraints&32)!==0}get lockRotationZ(){return(this.constraints&64)!==0}set lockPositionX(e){e?this.constraints|=2:this.constraints&=-3}set lockPositionY(e){e?this.constraints|=4:this.constraints&=-5}set lockPositionZ(e){e?this.constraints|=8:this.constraints&=-9}set lockRotationX(e){e?this.constraints|=16:this.constraints&=-17}set lockRotationY(e){e?this.constraints|=32:this.constraints&=-33}set lockRotationZ(e){e?this.constraints|=64:this.constraints&=-65}_propertiesChanged=!1;_currentVelocity;_smoothedVelocity;_smoothedVelocityGetter;_lastPosition;_watch;awake(){this._watch=void 0,this._currentVelocity=new _o.Vector3,this._smoothedVelocity=new _o.Vector3,this._smoothedVelocityGetter=new _o.Vector3,this._lastPosition=new _o.Vector3}onEnable(){this._watch||(this._watch=new qc(this.gameObject,this.context)),this._watch.start(!0,!0),this.startCoroutine(this.beforePhysics(),2)}onDisable(){this._watch?.stop(),this.context.physics.removeBody(this)}onDestroy(){this.context.physics.removeBody(this)}onValidate(){this._propertiesChanged=!0}*beforePhysics(){for(;;)this._propertiesChanged&&(this._propertiesChanged=!1,this.context.physics.updateProperties(this)),this._watch?.isDirty&&(this._watch.mute=!0,this._watch.applyValues(),this.context.physics.updateBody(this,this._watch.positionChanged,this._watch.rotationChanged),this._watch.reset()),this.captureVelocity(),yield}get body(){return this.context.physics.internal_getRigidbody(this)}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(){this.body?.resetForces(!0)}resetTorques(){this.body?.resetTorques(!0)}resetVelocities(){this.setVelocity(0,0,0),this.setAngularVelocity(0,0,0)}resetForcesAndTorques(){this.resetForces(),this.resetTorques()}wakeUp(){this.body?.wakeUp()}applyForce(e,t){this.body?.addForce(e,!0)}applyImpulse(e){this.body?.applyImpulse(e,!0)}setForce(e,t,n){this.body?.resetForces(!0),this.body?.addForce({x:e,y:t,z:n},!0)}getVelocity(){let e=this.body?.linvel();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){if(e instanceof qh){let i=e;this.body?.setLinvel(i,!0);return}t===void 0||n===void 0||this.body?.setLinvel({x:e,y:t,z:n},!0)}setAngularVelocity(e,t,n){if(e instanceof qh){let i=e;this.body?.setAngvel(i,!0);return}t===void 0||n===void 0||this.body?.setAngvel({x:e,y:t,z:n},!0)}setTorque(e,t,n){this.setAngularVelocity(e,t,n)}get smoothedVelocity(){return this._smoothedVelocityGetter.copy(this._smoothedVelocity),this._smoothedVelocityGetter.multiplyScalar(1/this.context.time.deltaTime)}setBodyFromGameObject(e=null){this.gameObject&&this.destroyed}captureVelocity(){if(this.body){let e=B(this.gameObject);Ha.tempPosition.copy(e);let t=e.sub(this._lastPosition);this._lastPosition.copy(Ha.tempPosition),this._smoothedVelocity.lerp(t,this.context.time.deltaTime/.1)}}},q=Ha;j(q,"tempPosition",new _o.Vector3),x([qt(),w()],q.prototype,"mass",2),x([qt(),w()],q.prototype,"useGravity",2),x([qt(),w()],q.prototype,"constraints",2),x([qt(),w()],q.prototype,"isKinematic",2),x([qt(),w()],q.prototype,"drag",2),x([qt(),w()],q.prototype,"angularDrag",2),x([qt(),w()],q.prototype,"detectCollisions",2),x([qt(),w()],q.prototype,"sleepThreshold",2),x([qt(),w()],q.prototype,"collisionDetectionMode",2);import{Mesh as Gg,Vector3 as Li}from"three";var ht=class extends O{get isCollider(){return!0}attachedRigidbody=null;isTrigger=!1;awake(){super.awake(),this.attachedRigidbody||(this.attachedRigidbody=this.gameObject.getComponentInParent(q))}start(){this.attachedRigidbody||(this.attachedRigidbody=this.gameObject.getComponentInParent(q))}onEnable(){this.attachedRigidbody||(this.attachedRigidbody=this.gameObject.getComponentInParent(q))}onDisable(){this.context.physics.removeBody(this)}};x([w(q)],ht.prototype,"attachedRigidbody",2),x([w()],ht.prototype,"isTrigger",2);var ri=class extends ht{radius=.5;center=new Li(0,0,0);onEnable(){super.onEnable(),this.context.physics.addSphereCollider(this,this.center,this.radius)}};x([w()],ri.prototype,"radius",2),x([w(Li)],ri.prototype,"center",2);var oi=class extends ht{size=new Li(1,1,1);center=new Li(0,0,0);onEnable(){super.onEnable(),this.context.physics.addBoxCollider(this,this.center,this.size)}};x([w(Li)],oi.prototype,"size",2),x([w(Li)],oi.prototype,"center",2);var ji=class extends ht{sharedMesh;convex=!1;onEnable(){super.onEnable(),this.sharedMesh?.isMesh||this.gameObject instanceof Gg&&(this.sharedMesh=this.gameObject),this.sharedMesh?.isMesh&&this.context.physics.addMeshCollider(this,this.sharedMesh,this.convex)}};x([w()],ji.prototype,"convex",2);var ut=class extends ht{center=new Li(0,0,0);radius=.5;height=2;onEnable(){super.onEnable(),this.context.physics.addCapsuleCollider(this,this.center,this.height,this.radius)}};x([w(Li)],ut.prototype,"center",2),x([w()],ut.prototype,"radius",2),x([w()],ut.prototype,"height",2);var Yt=class extends O{center=new xr(0,0,0);radius=.5;height=2;_rigidbody=null;get rigidbody(){return this._rigidbody?this._rigidbody:(this._rigidbody=this.gameObject.getComponent(q),this._rigidbody||(this._rigidbody=this.gameObject.addNewComponent(q)),this.rigidbody)}onEnable(){let e=this.rigidbody,t=this.gameObject.getComponent(ut);t||(t=this.gameObject.addNewComponent(ut)),t.center.copy(this.center),t.radius=this.radius,t.height=this.height,this.gameObject.rotation.x=0,this.gameObject.rotation.z=0,e.lockRotationX=!0,e.lockRotationY=!0,e.lockRotationZ=!0}move(e){this.gameObject.position.add(e)}_activeGroundCollisions=new Set;onCollisionEnter(e){for(let t of e.contacts)if(t.normal.y>.1){this._activeGroundCollisions.add(e);break}}onCollisionExit(e){this._activeGroundCollisions.delete(e)}get isGrounded(){return this._activeGroundCollisions.size>0}};x([w(xr)],Yt.prototype,"center",2),x([w()],Yt.prototype,"radius",2),x([w()],Yt.prototype,"height",2);var It=class extends O{controller;movementSpeed=2;rotationSpeed=2;jumpForce=1;animator;lookForward=!0;_currentSpeed=new xr(0,0,0);_currentAngularSpeed=new xr(0,0,0);_temp=new xr(0,0,0);_jumpCount=0;_currentRotation;awake(){this._currentRotation=new Vg}update(){this.controller?.isGrounded&&(this._jumpCount=0,this.animator?.SetBool("doubleJump",!1));let e=this.context.input.isKeyPressed("w"),t=this.context.input.isKeyPressed("s"),n=this.context.input.isKeyPressed("a"),i=this.context.input.isKeyPressed("d"),r=this.context.input.isKeyDown(" "),s=e?1:0+t?-1:0;this._currentSpeed.z+=s*this.movementSpeed*this.context.time.deltaTime,this.animator?.SetBool("running",s!=0),this.animator?.SetBool("jumping",this.controller?.isGrounded===!0&&r),this._temp.copy(this._currentSpeed),this._temp.applyQuaternion(this.gameObject.quaternion),this.controller?this.controller.move(this._temp):this.gameObject.position.add(this._temp);let a=n?1:0+i?-1:0;if(this._currentAngularSpeed.y+=U.toRadians(a*this.rotationSpeed)*this.context.time.deltaTime,this.lookForward&&Math.abs(this._currentAngularSpeed.y)<.01){let c=this.context.mainCameraComponent.forward;c.y=0,c.normalize(),this._currentRotation.setFromUnitVectors(new xr(0,0,1),c),this.gameObject.quaternion.slerp(this._currentRotation,this.context.time.deltaTime*10)}if(this.gameObject.rotateY(this._currentAngularSpeed.y),this._currentSpeed.multiplyScalar(1-this.context.time.deltaTime*10),this._currentAngularSpeed.y*=1-this.context.time.deltaTime*10,this.controller&&r&&this.jumpForce>0){let c=this.controller?.isGrounded;if(!this.controller?.isGrounded&&this._jumpCount===1&&(c=!0,this.animator?.SetBool("doubleJump",!0)),c){this._jumpCount+=1;let d=this.controller.rigidbody,l=this._jumpCount===2?2:1;d.applyImpulse(new xr(0,1,0).multiplyScalar(this.jumpForce*l))}}if(this.controller){let c=this.controller?.rigidbody.getVelocity().y;if(c<-1){this._raycastOptions.ray||(this._raycastOptions.ray=new zg),this._raycastOptions.ray.origin.copy(B(this.gameObject)),this._raycastOptions.ray.direction.set(0,-1,0);let d=this.layer;this.gameObject.layers.disableAll(),this.gameObject.layers.set(2);let l=this.context.physics.raycast(this._raycastOptions);this.gameObject.layers.set(d),(l.length&&l[0].distance>2||c<-10)&&this.animator?.SetBool("falling",!0)}else this.animator?.SetBool("falling",!1)}}_raycastOptions=new ce};x([w(Yt)],It.prototype,"controller",2),x([w()],It.prototype,"movementSpeed",2),x([w()],It.prototype,"rotationSpeed",2),x([w()],It.prototype,"jumpForce",2),x([w(He)],It.prototype,"animator",2);var pt=class extends O{canGrab=!0;onPointerClick(e){}},ft=class extends O{isUsed=!0;usedBy=null};var Hi=class extends Ce{},Cr=class extends O{deleteBoxes=[];awake(){this.deleteBoxes=R.findObjectsOfType(Hi,this.context)}update(){for(let e of this.deleteBoxes){let t=this.gameObject;e.isInBox(t)===!0&&(R.getComponentInParent(this.gameObject,ft)||so(this.gameObject,this.context.connection))}}};var Fi=class extends O{visibleOn;onEnable(){this.apply()}apply(){this.test()||R.setActive(this.gameObject,!1)}test(){return this.visibleOn<0?!0:Ng()?(this.visibleOn&2)!==0:(this.visibleOn&1)!==0}};x([w()],Fi.prototype,"visibleOn",2);var Fa;function Ng(){if(Fa===!0||Fa===!1)return Fa;let o=!1;return function(e){(/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(e)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(e.substr(0,4)))&&(o=!0)}(navigator.userAgent||navigator.vendor||window.opera),Fa=o,o}import*as si from"three";var ve=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,i){return e.prep(4,12),e.writeFloat32(i),e.writeFloat32(n),e.writeFloat32(t),e.offset()}};var Eo=class{bb=null;bb_pos=0;__init(e,t){return this.bb_pos=e,this.bb=t,this}position(e){return(e||new ve).__init(this.bb_pos,this.bb)}rotation(e){return(e||new ve).__init(this.bb_pos+12,this.bb)}scale(e){return(e||new ve).__init(this.bb_pos+24,this.bb)}static sizeOf(){return 36}static createTransform(e,t,n,i,r,s,a,c,d,l){return e.prep(4,36),e.prep(4,12),e.writeFloat32(l),e.writeFloat32(d),e.writeFloat32(c),e.prep(4,12),e.writeFloat32(a),e.writeFloat32(s),e.writeFloat32(r),e.prep(4,12),e.writeFloat32(i),e.writeFloat32(n),e.writeFloat32(t),e.offset()}};var Mt=class{bb=null;bb_pos=0;__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsSyncedTransformModel(e,t){return(t||new Mt).__init(e.readInt32(e.position())+e.position(),e)}static getSizePrefixedRootAsSyncedTransformModel(e,t){return e.setPosition(e.position()+4),(t||new Mt).__init(e.readInt32(e.position())+e.position(),e)}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 Eo).__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)}};var Bi=I("debugsync"),wo="STRS";fo(wo,Mt.getRootAsSyncedTransformModel);var _n=new st;function Yc(o,e,t=!0){_n.clear();let n=_n.createString(o);Mt.startSyncedTransformModel(_n),Mt.addGuid(_n,n),Mt.addFast(_n,t);let i=e.worldPosition,r=e.worldEuler,s=e.gameObject.scale;Mt.addTransform(_n,Eo.createTransform(_n,i.x,i.y,i.z,r.x,r.y,r.z,s.x,s.y,s.z));let a=Mt.endSyncedTransformModel(_n);return _n.finish(a,wo),_n.asUint8Array()}var Je=class extends O{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(){Bi&&console.log("Request ownership"),this._model?this._model.requestOwnership():(this._shouldRequestOwnership=!0,this._needsUpdate=!0)}hasOwnership(){return this._model?.hasOwnership??void 0}isOwned(){return this._model?.isOwned}joinedRoomCallback=null;receivedDataCallback=null;awake(){Bi&&console.log("new instance",this.guid,this),this._receivedDataBefore=!1,this._targetPosition=new si.Vector3,this._targetRotation=new si.Quaternion,this.lastWorldPos=new si.Vector3,this.lastWorldRotation=new si.Quaternion,this.rb=R.getComponentInChildren(this.gameObject,q),this.rb&&(this._wasKinematic=this.rb.isKinematic),this.receivedUpdate=!0,this._model=new Ri(this.context.connection,this.guid),this.context.connection.isConnected&&this.tryGetLastState(),this.joinedRoomCallback=this.tryGetLastState.bind(this),this.context.connection.beginListen("joined-room",this.joinedRoomCallback),this.receivedDataCallback=this.onReceivedData.bind(this),this.context.connection.beginListenBinrary(wo,this.receivedDataCallback)}onDestroy(){this.syncDestroy&&Hu(this.guid,this.context.connection),this._model=null,this.context.connection.stopListening("joined-room",this.joinedRoomCallback),this.context.connection.stopListenBinary(wo,this.receivedDataCallback)}tryGetLastState(){let e=this.context.connection.tryGetState(this.guid);e&&this.onReceivedData(e)}tempEuler=new si.Euler;onReceivedData(e){if(!this.destroyed&&typeof e.guid=="function"&&e.guid()===this.guid){Bi&&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){ne.markDirty(this.gameObject,!0);let n=t.position();n&&(this.interpolatePosition&&this._targetPosition?.set(n.x(),n.y(),n.z()),(!this.interpolatePosition||!this._receivedDataBefore)&&this.setWorldPosition(n.x(),n.y(),n.z()));let i=t.rotation();i&&(this.tempEuler.set(i.x(),i.y(),i.z()),this.interpolateRotation&&this._targetRotation.setFromEuler(this.tempEuler),(!this.interpolateRotation||!this._receivedDataBefore)&&Pu(this.gameObject,this.tempEuler))}this._receivedDataBefore=!0}}onEnable(){this.lastWorldPos.copy(this.worldPosition),this.lastWorldRotation.copy(this.worldQuaternion),this._needsUpdate=!0,this._model&&this._model.updateIsOwned()}onDisable(){this._model&&this._model.freeOwnership()}receivedUpdate=!1;lastWorldPos;lastWorldRotation;onBeforeRender(){if(!this.activeAndEnabled||!this.context.connection.isConnected)return;if(!this.context.connection.isInRoom||!this._model){Bi&&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;if(this._model.isOwned&&!this.receivedUpdate){let r=e.distanceTo(this.lastWorldPos),s=t.angleTo(this.lastWorldRotation),a=this._model.hasOwnership||this.fastMode?1e-4:.001;(r>a||s>a)&&(this._model.hasOwnership?this._needsUpdate=!0:(Bi&&console.log(this.guid,"reset because not owned but",this.gameObject.name,this.lastWorldPos),this.worldPosition=this.lastWorldPos,e.copy(this.lastWorldPos),this.worldQuaternion=this.lastWorldRotation,t.copy(this.lastWorldRotation),ne.markDirty(this.gameObject,!0),this._needsUpdate=!1))}if(this._model&&!this._model.hasOwnership&&this._model.isOwned&&this._receivedDataBefore){let s=this._receivedFastUpdate||this.fastMode?.5:.3,a=!1;if(this.interpolatePosition&&this._targetPosition){let c=this.worldPosition;c.lerp(this._targetPosition,s),this.worldPosition=c,a=!0}if(this.interpolateRotation&&this._targetRotation){let c=this.worldQuaternion;c.slerp(this._targetRotation,s),this.worldQuaternion=c,a=!0}a&&ne.markDirty(this.gameObject,!0)}if(this.receivedUpdate=!1,this.lastWorldPos.copy(e),this.lastWorldRotation.copy(t),!this._model)return;if(!this._model||this._model.hasOwnership===void 0||!this._model.hasOwnership){this.rb&&(this.rb.isKinematic=this._model.isOwned??!1,this.rb.setVelocity(0,0,0),this.rb.setBodyFromGameObject());return}this.rb&&(this._wasKinematic!==void 0&&(Bi&&console.log("reset kinematic",this.rb.name,this._wasKinematic),this.rb.isKinematic=this._wasKinematic),this.gameObject.position.distanceTo(new si.Vector3(0,0,0))>1e3&&(Bi&&console.log("RESET",this.name),this.gameObject.position.set(0,1,0),this.rb.setVelocity(0,0,0),this.rb.setBodyFromGameObject()));let n=10,i=this.rb||this.fastMode;if(this._needsUpdate&&(n<=0||n>0&&this.context.time.frameCount%n===0||i)){Bi&&console.log("send update",this.context.connection.connectionId,this.guid,this.gameObject.name,this.gameObject.guid),this.overridePhysics&&this.rb&&this.rb.setBodyFromGameObject(),this._needsUpdate=!1;let r=Yc(this.guid,this,!!i);this.context.connection.sendBinary(r)}}};import*as Q from"three";import{Euler as gb,EventDispatcher as bb,Group as vb,Matrix4 as op,Mesh as yb,MeshBasicMaterial as _b,Object3D as rp,Quaternion as od,RingGeometry as Eb,Vector3 as sp}from"three";var Ba=class{static createButton(e,t={}){let n=document.createElement("button");function i(){if(t.domOverlay===void 0){var c=document.createElement("div");c.style.display="none",document.body.appendChild(c);var d=document.createElementNS("http://www.w3.org/2000/svg","svg");d.setAttribute("width",38),d.setAttribute("height",38),d.style.position="absolute",d.style.right="20px",d.style.top="20px",d.addEventListener("click",function(){u.end()}),c.appendChild(d);var l=document.createElementNS("http://www.w3.org/2000/svg","path");l.setAttribute("d","M 12,12 L 28,28 M 28,12 12,28"),l.setAttribute("stroke","#fff"),l.setAttribute("stroke-width",2),d.appendChild(l),t.optionalFeatures===void 0&&(t.optionalFeatures=[]),t.optionalFeatures.push("dom-overlay"),t.domOverlay={root:c}}t.optionalFeatures===void 0&&(t.optionalFeatures=[]),t.optionalFeatures.push("local-floor"),t.optionalFeatures.push("hand-tracking"),t.optionalFeatures.push("layers");let u=null;async function h(_){_.addEventListener("end",b),await e.xr.setSession(_),n.textContent="STOP AR",t.domOverlay.root.style.display="",u=_}function b(){u.removeEventListener("end",b),n.textContent="START AR",t.domOverlay.root.style.display="none",u=null}n.style.display="",n.style.cursor="pointer",n.style.left="calc(50% - 50px)",n.style.width="100px",n.textContent="START AR",n.onmouseenter=function(){n.style.opacity="1.0"},n.onmouseleave=function(){n.style.opacity="0.5"},n.onclick=function(){u===null?navigator.xr.requestSession("immersive-ar",t).then(h):u.end()}}function r(){n.disabled=!0,n.style.display="",n.style.cursor="auto",n.style.left="calc(50% - 75px)",n.style.width="150px",n.onmouseenter=null,n.onmouseleave=null,n.onclick=null}function s(){r(),n.textContent="AR NOT SUPPORTED"}function a(c){c.style.position="absolute",c.style.bottom="20px",c.style.padding="12px 6px",c.style.border="1px solid #fff",c.style.borderRadius="4px",c.style.background="rgba(0,0,0,0.1)",c.style.color="#fff",c.style.font="normal 13px sans-serif",c.style.textAlign="center",c.style.opacity="0.5",c.style.outline="none",c.style.zIndex="999"}if("xr"in navigator)return n.id="ARButton",n.style.display="none",a(n),navigator.xr.isSessionSupported("immersive-ar").then(function(c){c?i():s()}).catch(s),n;{let c=document.createElement("a");return window.isSecureContext===!1?(c.href=document.location.href.replace(/^http:/,"https:"),c.innerHTML="WEBXR NEEDS HTTPS"):(c.href="https://immersiveweb.dev/",c.innerHTML="WEBXR NOT AVAILABLE"),c.style.left="calc(50% - 90px)",c.style.width="180px",c.style.textDecoration="none",a(c),c}}};var Ua=class{static createButton(e,t){t&&console.error('THREE.VRButton: The "options" parameter has been removed. Please set the reference space type via renderer.xr.setReferenceSpaceType() instead.');let n=document.createElement("button");function i(){let c=null;async function d(u){u.addEventListener("end",l),await e.xr.setSession(u),n.textContent="EXIT VR",c=u}function l(){c.removeEventListener("end",l),n.textContent="ENTER VR",c=null}n.style.display="",n.style.cursor="pointer",n.style.left="calc(50% - 50px)",n.style.width="100px",n.textContent="ENTER VR",n.onmouseenter=function(){n.style.opacity="1.0"},n.onmouseleave=function(){n.style.opacity="0.5"},n.onclick=function(){if(c===null){let u={optionalFeatures:["local-floor","bounded-floor","hand-tracking","high-fixed-foveation-level","layers"]};navigator.xr.requestSession("immersive-vr",u).then(d)}else c.end()}}function r(){n.disabled=!0,n.style.display="",n.style.cursor="auto",n.style.left="calc(50% - 75px)",n.style.width="150px",n.onmouseenter=null,n.onmouseleave=null,n.onclick=null}function s(){r(),n.textContent="VR NOT SUPPORTED"}function a(c){c.style.position="absolute",c.style.bottom="20px",c.style.padding="12px 6px",c.style.border="1px solid #fff",c.style.borderRadius="4px",c.style.background="rgba(0,0,0,0.1)",c.style.color="#fff",c.style.font="normal 13px sans-serif",c.style.textAlign="center",c.style.opacity="0.5",c.style.outline="none",c.style.zIndex="999"}if("xr"in navigator)return n.id="VRButton",n.style.display="none",a(n),navigator.xr.isSessionSupported("immersive-vr").then(function(c){c?i():s(),Ua.xrSessionIsGranted&&(console.log("XR session is granted - will enter immersive web now"),n.click())}),n;{let c=document.createElement("a");return window.isSecureContext===!1?(c.href=document.location.href.replace(/^http:/,"https:"),c.innerHTML="WEBXR NEEDS HTTPS"):(c.href="https://immersiveweb.dev/",c.innerHTML="WEBXR NOT AVAILABLE"),c.style.left="calc(50% - 90px)",c.style.width="180px",c.style.textDecoration="none",a(c),c}}static registerSessionGrantedListener(){if("xr"in navigator)try{navigator.xr.addEventListener("sessiongranted",()=>{console.log("Received session granted event"),Ua.xrSessionIsGranted=!0})}catch(e){console.error(e)}}},Co=Ua;j(Co,"xrSessionIsGranted",!1);Co.registerSessionGrantedListener();import*as Ga from"three";var Yh=ks(aa(),1);import{AudioAnalyser as Wg}from"three";var To="noVoip",Ze=I("debugvoip"),Xg=I("voip");var Kc=class{id;constructor(e){this.id=e}};var Jc=class{peer;voip;userId;peerId;call=null;callErrorListener=null;stream=null;constructor(e,t,n,i){this.voip=e,this.peer=t,this.userId=n,this.peerId=i}close(){Ze&&console.log("close voip call"),this.callErrorListener&&this.peer.off("error",this.callErrorListener),this.call&&this.call.open&&this.call.close(),this.stream?.getTracks().forEach(function(e){e.stop()})}updateMute(e){if(!this.stream)return;let t=this.stream?.getAudioTracks();for(let n of t)n.enabled=!e}async startVoipCall(){if(!await Fe.HasMicrophonePermissions()){console.warn("no permission to use microphone, can not start call");return}Ze&&console.log("start voip call"),this.stream=await navigator.mediaDevices.getUserMedia({audio:!0,video:!1}),this.updateMute(this.voip.muteOutput),Ze&&console.log(this.stream),this.call=this.peer.call(this.peerId,this.stream,{metadata:{userId:this.userId}}),this.call.on("error",t=>{console.error(t)}),this.call.on("stream",t=>{Ze&&console.log("received stream from remote again",t)}),this.peer.on("close",this.onCallClose.bind(this)),this.callErrorListener=t=>{t.message.includes(this.peerId)?(console.log("Could not connect to "+this.peerId),this.callErrorListener&&this.peer.off("error",this.callErrorListener),this.call&&this.call.close(),this.stream?.getTracks().forEach(function(n){n.stop()}),this.stream=null):console.error(t)},this.peer.on("error",this.callErrorListener)}onCallClose(e){Ze&&console.log("call closed",e)}},Zc=class{get currentStream(){return this.stream}get currentAudio(){return this.audio}get currentAnalyzer(){return this.analyzer}voip;call;audio=null;stream=null;obj;analyzer=null;waitingForStart=!1;closed=!1;audioElement=null;constructor(e,t,n){this.voip=e,this.obj=t,this.call=n}openAudioStream(e){let t=e.getAudioTracks();for(let n of t)if(n.kind==="audio"&&n.readyState==="live"){this.open(n);return}console.warn("failed finding valid audio stream to begin call")}open(e){console.assert(e.kind==="audio","invalid track kind, expected audio but received "+e.kind),!this.waitingForStart&&(this.waitingForStart=!0,Z.userInteractionRegistered||Ze&&console.log("Incoming call, waiting for user interaction before opening audio"),Z.registerWaitForAllowAudio(async()=>{if(this.call.open&&!this.closed){Ze&&console.log("Setup audio and begin listening"),this.stream=new MediaStream([e]);let t=new Ga.AudioListener;this.audio=new Ga.Audio(t),this.audio.setVolume(this.voip.muteInput?0:1),this.audio.setMediaStreamSource(this.stream);let n=document.createElement("audio");this.audioElement=n,n.style.display="none",document.body.appendChild(n),n.srcObject=this.stream,n.sinkId!==void 0&&navigator.mediaDevices.enumerateDevices().then(i=>{if(!!n){console.log(i);for(let r of i)if(r.label==="Speakerphone"){n.sinkId=r.deviceId;break}}}),Ze&&console.log("call is setup, you should hear something now"),this.analyzer=new Wg(this.audio,32)}}))}close(){this.closed=!0,this.call?.open&&this.call.close(),this.audio?.disconnect(),this.stream?.getTracks().forEach(e=>{e.stop()}),this.stream=null,this.audioElement&&this.audioElement.remove()}},Fe=class extends O{requireParam=!1;set muteInput(e){if(e===this._inputMuted||(this._inputMuted=e,!this.currentIncomingCalls))return;let t=this._inputMuted?0:1;for(let n in this.currentIncomingCalls)this.currentIncomingCalls[n]?.currentAudio?.setVolume(t)}get muteInput(){return this._inputMuted}set muteOutput(e){if(e!==this._outputMuted&&(this._outputMuted=e,!!this.connections))for(let t in this.connections)this.connections[t]?.updateMute(e)}get muteOutput(){return this._outputMuted}getFrequency(e){if(e===null){for(let n in this.currentIncomingCalls){let i=this.currentIncomingCalls[n];if(i&&i.currentAnalyzer)return i.currentAnalyzer.getAverageFrequency()}return null}let t=this.currentIncomingCalls[e];return t&&t.currentAnalyzer?t.currentAnalyzer.getAverageFrequency():null}peer=null;model=null;connections={};currentIncomingCalls={};_inputMuted=!1;_outputMuted=!1;awake(){if(I(To)){console.log("VOIP is disabled by url parameter: "+To);return}if(this.requireParam&&!Xg){console.debug("VOIP must be enabled explicitly by url parameter");return}this.peer=new Yh.default,navigator.getUserMedia=navigator.getUserMedia||navigator.webkitGetUserMedia||navigator.mozGetUserMedia||navigator.msGetUserMedia,this.context.connection.beginListen("joined-room",e=>{navigator.mediaDevices.getUserMedia({audio:!0,video:!1})}),this.context.connection.beginListen("peer-update-id",e=>{if(e.id!==this.context.connection.connectionId){let t=this.connections[e.id];if(t&&t.close(),this.peer&&this.context.connection.connectionId){let n=new Jc(this,this.peer,this.context.connection.connectionId,e.peerId);this.connections[e.id]=n,n.startVoipCall()}}}),this.context.connection.beginListen("user-left-room",e=>{let{userId:t}=e,n=this.connections[t];this.connections[t]=null,n&&n.close();let i=this.currentIncomingCalls[t];Ze&&console.log("UserLeftRoom",e,t,i),i&&(i.close(),this.currentIncomingCalls[t]=null)}),this.peer.on("open",this.onOpenPeerConnection.bind(this))}onEnable(){}onDisable(){console.log("TODO: close all");for(let e in this.currentIncomingCalls)this.currentIncomingCalls[e]?.close(),this.connections[e]?.close()}async onOpenPeerConnection(e){Ze&&console.log("Peer connection established and received id"),this.model=new Kc(e),this.context.connection.send("peer-update-id",this.model,1),this.peer&&(this.peer.on("call",this.onReceiveCall.bind(this)),this.peer.on("connection",function(t){Ze&&console.log("CONNECTION",t),t.on("data",function(n){Ze&&console.log("Received",n)})}))}async onReceiveCall(e){let{metadata:t}=e;console.assert(t.userId);let{userId:n}=t,{peer:i}=e,r=this.currentIncomingCalls[n];if(r&&r.close(),Ze&&console.log("received call"),await Fe.HasMicrophonePermissions()){let s=await navigator.mediaDevices.getUserMedia({audio:!0,video:!1});e.answer(s)}else e.answer(null);this.currentIncomingCalls[n]=new Zc(this,this.gameObject,e),e.on("stream",s=>{Ze&&console.log("receive caller stream, will setup audio now"),this.currentIncomingCalls[n]?.openAudioStream(s)}),e.on("error",console.error)}static async HasMicrophonePermissions(){return(await navigator.permissions.query({name:"microphone"})).state!=="denied"}};import{Matrix4 as hs}from"three";var mt=class extends O{webAR=null;get rig(){return this.webAR?.webxr.Rig}invertForward=!1;get arScale(){return this._arScale}set arScale(e){e!==this._arScale&&(this._arScale=e,this.setScale(e))}_initalMatrix=new hs;_selectStartFn=this.onSelectStart.bind(this);_selectEndFn=this.onSelectEnd.bind(this);start(){let e=R.findObjectOfType(G);e&&(e.Rig.updateMatrix(),this._initalMatrix.copy(e.Rig.matrix))}_arScale=5;_rig=null;_startPose=null;_placementPose=null;_isTouching=!1;_rigStartPose=null;onBegin(e){this._placementPose=null,this.gameObject.visible=!1,this.gameObject.matrixAutoUpdate=!1,this._startPose=this.gameObject.matrix.clone(),this._rigStartPose=this.rig?.matrix.clone(),e.addEventListener("selectstart",this._selectStartFn),e.addEventListener("selectend",this._selectEndFn),this.gameObject.visible=!1,this.rig&&(this.rig.matrixAutoUpdate=!0,this._initalMatrix.decompose(this.rig.position,this.rig.quaternion,this.rig.scale))}onUpdate(e,t,n){return n&&!this._placementPose&&this._isTouching?(this.webAR&&this.webAR.setReticleActive(!1),this.placeAt(e,new hs().fromArray(n.transform.matrix).invert()),!0):!1}placeAt(e,t){if(this._placementPose||(this._placementPose=new hs),this._placementPose.copy(t),e){if(this.invertForward){let n=new hs().makeRotationY(Math.PI);this._placementPose.premultiply(n)}this._rig=e,this.setScale(this.arScale)}else this._rig=null;this.gameObject.visible=!0}onEnd(e,t){this._placementPose=null,this.gameObject.visible=!1,this.gameObject.matrixAutoUpdate=!1,this._startPose&&this.gameObject.matrix.copy(this._startPose),e&&(e.matrixAutoUpdate=!0,this._rigStartPose&&this._rigStartPose.decompose(e.position,e.quaternion,e.scale)),ne.markDirty(this.gameObject,!0),setTimeout(()=>{this.gameObject.matrixAutoUpdate=!0,this.gameObject.visible=!0},100)}onSelectStart(){this._isTouching=!0}onSelectEnd(){this._isTouching=!1}setScale(e){let t=this._rig;!t||!this._placementPose||(this._rigStartPose||(this._rigStartPose=t.matrix.clone()),t.matrixAutoUpdate=!1,t.matrix.multiplyMatrices(new hs().makeScale(e,e,e),this._placementPose),t.matrix.decompose(t.position,t.quaternion,t.scale),t.updateMatrixWorld(),console.log("Place",t.position))}};x([w()],mt.prototype,"invertForward",2),x([w()],mt.prototype,"arScale",1);import{BoxHelper as eb,BufferGeometry as tb,Color as tp,Euler as nb,Layers as ib,Line as rb,Mesh as ob,MeshBasicMaterial as sb,Quaternion as Na,Ray as ab,SphereGeometry as lb,Vector2 as cb,Vector3 as Zt}from"three";import{OculusHandModel as db}from"three/examples/jsm/webxr/OculusHandModel.js";import{OculusHandPointerModel as ub}from"three/examples/jsm/webxr/OculusHandPointerModel.js";import{XRControllerModelFactory as hb}from"three/examples/jsm/webxr/XRControllerModelFactory.js";import{GLTFLoader as pb}from"three/examples/jsm/loaders/GLTFLoader.js";import*as Zh from"three";import{Quaternion as Qg,Vector3 as Va}from"three";var Ro=I("debugflags");var $c=class{Mask=17;Has(e){let t=this.Mask&e;return Ro&&console.log("HAS",e,this.Mask,"Result="+t),t!==0}Set(e){this.Mask=e,pe.Apply()}Enable(e){this.Mask|=e,pe.Apply()}Disable(e){this.Mask&=~e,pe.Apply()}Toggle(e){this.Mask^=e,pe.Apply()}EnableAll(){this.Mask=-1,pe.Apply()}DisableAll(){this.Mask=0,pe.Apply()}},$e=$c;j($e,"Global",new $c);var En=class extends O{static Apply(){for(let e of this.registry)e.UpdateVisible($e.Global)}awake(){En.registry.push(this)}onEnable(){En.firstApply||(En.firstApply=!0,En.Apply())}onDestroy(){let e=En.registry.indexOf(this);e>=0&&En.registry.splice(e,1)}visibleIn;get isOn(){return this.gameObject.visible}UpdateVisible(e=null){if(!this.enabled)return;let t,n=e;n&&typeof n=="number"&&(console.assert(typeof n=="number","XRFlag.UpdateVisible: state must be a number",n),Ro&&console.log(n),En.buffer.Mask=n,e=En.buffer);let i=e;if(i?(Ro&&console.log("use passed in mask"),t=i.Has(this.visibleIn)):(Ro&&console.log("use global mask"),$e.Global.Has(this.visibleIn)),t!==void 0)if(t)Ro&&console.trace("is visible",this.name,this.gameObject.uuid),R.setActive(this.gameObject,!0);else{if(Ro&&console.trace("is not visible",this.name,this.gameObject.uuid),!this.gameObject.visible)return;this.gameObject.visible=!1}}},pe=En;j(pe,"registry",[]),j(pe,"firstApply"),j(pe,"buffer",new $e);import{Object3D as ed}from"three";var Ui=I("debugavatar"),Kt=class extends O{static getAvatar(e){return e>=0&&e<Kt.instances.length?Kt.instances[e]:null}static onAvatarMarkerCreated(e){return Kt._onNewAvatarMarkerAdded.push(e),e}static onAvatarMarkerDestroyed(e){return Kt._onAvatarMarkerDestroyed.push(e),e}connectionId;avatar;awake(){Kt.instances.push(this),Ui&&console.log(this);for(let e of Kt._onNewAvatarMarkerAdded)e({avatarMarker:this,gameObject:this.gameObject})}onDestroy(){Kt.instances.splice(Kt.instances.indexOf(this),1);for(let e of Kt._onAvatarMarkerDestroyed)e({avatarMarker:this,gameObject:this.gameObject})}isLocalAvatar(){return this.connectionId===this.context.connection.connectionId}setVisible(e){this.avatar&&("setVisible"in this.avatar?this.avatar.setVisible(e):R.setActive(this.avatar,e))}},ie=Kt;j(ie,"instances",[]),j(ie,"_onNewAvatarMarkerAdded",[]),j(ie,"_onAvatarMarkerDestroyed",[]);var ps=class{_isVisible=!0;setVisible(e){this._isVisible=e,this.updateVisibility()}get isWebXRAvatar(){return!0}guid;root=null;head=null;handLeft=null;handRight=null;lastUpdate=-1;isLocalAvatar=!1;flags=null;headScale=new Va(1,1,1);handLeftScale=new Va(1,1,1);handRightScale=new Va(1,1,1);webxr;lastAvatarId=null;hasAvatarOverride=!1;context;avatarMarker=null;constructor(e,t,n){this.context=e,this.guid=t,this.webxr=n,this.setupCustomAvatar(this.webxr.defaultAvatar)}updateFlags(){if(!this.flags)return;let e=this.isLocalAvatar?8:16;for(let t of this.flags)t.gameObject.visible=!0,t.UpdateVisible(e)}async setAvatarOverride(e){return this.hasAvatarOverride=e!==null,this.hasAvatarOverride&&this.lastAvatarId!==e&&(this.lastAvatarId=e,e!=null&&e.length>0)?await this.setupCustomAvatar(e):null}_headTarget=new ed;_handLeftTarget=new ed;_handRightTarget=new ed;_canInterpolate=!1;tryUpdate(e,t){if(e.guid===this.guid&&(this.lastAvatarId!==e.avatarId&&e.avatarId&&e.avatarId.length>0&&(this.lastAvatarId=e.avatarId,this.setupCustomAvatar(e.avatarId)),this.lastUpdate=e.time,this.head)){let n=this.webxr.IsInAR?"handheld":"headset",i=this.head;this.context.players.setPlayerView(e.guid,i,n),ne.markDirty(this.head),this._canInterpolate=!0;let r=this.isLocalAvatar?this.head:this._headTarget;if(r.position.set(e.position.x,e.position.y,e.position.z),r.quaternion.set(e.rotation.x,e.rotation.y,e.rotation.z,e.rotation.w),r.scale.set(e.scale,e.scale,e.scale),r.scale.multiply(this.headScale),this.handLeft){let s=this.isLocalAvatar?this.handLeft:this._handLeftTarget;s.position.set(e.posLeftHand.x,e.posLeftHand.y,e.posLeftHand.z),s.quaternion.set(e.rotLeftHand._x,e.rotLeftHand._y,e.rotLeftHand._z,e.rotLeftHand._w),s.quaternion.multiply(ps.invertRotation),s.scale.set(e.scale,e.scale,e.scale),s.scale.multiply(this.handLeftScale),ne.markDirty(this.handLeft)}if(this.handRight){let s=this.isLocalAvatar?this.handRight:this._handRightTarget;s.position.set(e.posRightHand.x,e.posRightHand.y,e.posRightHand.z),s.quaternion.set(e.rotRightHand._x,e.rotRightHand._y,e.rotRightHand._z,e.rotRightHand._w),s.quaternion.multiply(ps.invertRotation),s.scale.set(e.scale,e.scale,e.scale),s.scale.multiply(this.handRightScale),ne.markDirty(this.handRight)}}}update(){if(this.isLocalAvatar||!this._canInterpolate)return;let e=this.context.time.deltaTime/.1;this.head&&(this.head.position.lerp(this._headTarget.position,e),this.head.quaternion.slerp(this._headTarget.quaternion,e),this.head.scale.lerp(this._headTarget.scale,e)),this.handLeft&&this._handLeftTarget&&(this.handLeft.position.lerp(this._handLeftTarget.position,e),this.handLeft.quaternion.slerp(this._handLeftTarget.quaternion,e),this.handLeft.scale.lerp(this._handLeftTarget.scale,e)),this.handRight&&this._handRightTarget&&(this.handRight.position.lerp(this._handRightTarget.position,e),this.handRight.quaternion.slerp(this._handRightTarget.quaternion,e),this.handRight.scale.lerp(this._handRightTarget.scale,e))}destroy(){Ui&&console.log("Destroy avatar",this.guid),this.root?.removeFromParent(),this.avatarMarker?.destroy(),this.lastAvatarId=null,this.head&&ue.Remove(this.context,this.head)}updateVisibility(){let e=this.root;e&&R.setActive(e,this._isVisible)}async setupCustomAvatar(e){if(Ui&&console.log("LOAD",e,this),!e||typeof e=="string"&&e.length<=0)return!1;this.head&&ue.Remove(this.context,this.head);let t=e;if(t?.loadAssetAsync!==void 0){await t.loadAssetAsync();let i=t.asset;R.setActive(i,!1),e=R.instantiate(i),R.setActive(e,!0)}Ui&&console.log(e);let n=await ps.loader.getOrCreateNewAvatarInstance(this.context,e);if(Ui&&console.log(n,n?.isValid,this.lastAvatarId,e),n?.isValid){if(this.root=n.root,this.root.position.set(0,0,0),this.root.quaternion.set(0,0,0,1),this.root.scale.set(1,1,1),this.avatarMarker=R.addNewComponent(this.root,ie),this.avatarMarker.connectionId=this.guid,this.avatarMarker.avatar=this,this.head&&this.head!==n.head&&this.head?.removeFromParent(),this.head=n.head,this.headScale.copy(this.head.scale),this.head&&!this.isLocalAvatar&&ue.Add(this.context,this.head,this.avatarMarker),n.leftHand&&this.handLeft?.removeFromParent(),this.handLeft=n.leftHand??this.handLeft,this.handLeft?this.handLeftScale.copy(this.handLeft.scale):this.handLeftScale.set(1,1,1),n.rigthHand&&this.handRight?.removeFromParent(),this.handRight=n.rigthHand??this.handRight,this.handRight?this.handRightScale.copy(this.handRight.scale):this.handRightScale.set(1,1,1),this.context.scene.add(this.root),this.flags==null&&(this.flags=[]),this.flags.length=0,this.flags.push(...R.getComponentsInChildren(this.root,pe)),this.flags.length<=0&&this.head){let i=R.addNewComponent(this.head,pe);i.visibleIn=20,this.flags.push(i),Ui&&console.log("Added flag to head: "+i.visibleIn,this.head.name)}return Ui&&console.log("[Avatar], is Local? ",this.isLocalAvatar,this.root),this.updateFlags(),this.updateVisibility(),!0}else return Ui&&console.warn("build avatar failed"),!1}},gt=ps;j(gt,"loader",new ii),j(gt,"invertRotation",new Qg().setFromAxisAngle(new Va(0,1,0),Math.PI));var ue=class{static Add(e,t,n=null){if(!!t){for(let i of this.Pois)if(i.obj===t)return;this.Pois.push({obj:t,avatar:n}),this.LastChangeTime=e.time.time}}static Remove(e,t){if(!!t){for(let n of this.Pois)if(n.obj===t){this.Pois.splice(this.Pois.indexOf(n),1),this.LastChangeTime=e?.time.time??z.Current?.time.time;return}}}};j(ue,"Pois",[]),j(ue,"LastChangeTime",0);var td=class{guid;position=new Zh.Vector3},wn=class extends O{set controlledTarget(e){this.target=e;let t=M.get("MoveRandom");if(t&&this.target){let n=R.getComponent(this.target,t);n&&n.destroy()}}target=null;avatar=null;_model=null;_targetModel=new td;_currentTargetObject=null;_lastUpdateTime=0;_lookDuration=0;_lastPoiChangedTime=0;awake(){if(this.avatar=R.getComponentInParent(this.gameObject,ie),this.avatar){let e=R.getComponentInParent(this.gameObject,ie);this._model=new Ri(this.context.connection,this.guid),e?.isLocalAvatar&&this._model.requestOwnership()}this.context.connection.beginListen("avatar-look-target-changed",e=>{this.target&&e&&e.guid===this.avatar?.guid&&J(this.target,e.position)})}update(){if((!this.context.connection.isConnected||this._model?.hasOwnership)&&(ue.LastChangeTime!==this._lastPoiChangedTime&&(this._lastPoiChangedTime=ue.LastChangeTime,this._lookDuration=0),this.selectTarget(),this._currentTargetObject&&this.context.time.frameCount%10===0&&this.target)){let t=B(this._currentTargetObject);J(this.target,t),this.context.connection.isConnected&&this.avatar&&(this.context.connection.send("avatar-look-target-changed",this._targetModel),this._targetModel.guid=this.avatar.guid,this._targetModel.position.copy(t))}}selectTarget(){if(this.context.time.time-this._lastUpdateTime>this._lookDuration){this._lastUpdateTime=this.context.time.time,this._lookDuration=Math.random()*.5+.2;let t=ue.Pois;if(t.length>0){let n=t[Math.floor(Math.random()*t.length)];if(n&&n.obj){if(n.avatar&&n.avatar===this.avatar)return;this._currentTargetObject=n.obj}}}}};import*as za from"three-mesh-ui";import{OrbitControls as Yg}from"three/examples/jsm/controls/OrbitControls";import{Object3D as qg}from"three";var xn=class extends O{constraintActive=!0;locked=!1;sources=[]};x([w(qg)],xn.prototype,"sources",2);import*as fs from"three";var $h=I("nocamlimits"),Be=class extends O{get controls(){return this._controls}get controllerObject(){return this._cameraObject}onStartInteraction(e){this.controls?.addEventListener("start",e)}autoRotate=!1;autoRotateSpeed=1;enableKeys=!0;enableDamping=!0;dampingFactor=.1;enableZoom=!0;minZoom=0;maxZoom=1/0;enablePan=!0;lookAtConstraint=null;lookAtConstraint01=1;middleClickToFocus=!0;doubleClickToFocus=!0;useSlerp=!1;debugLog=!1;targetLerpSpeed=5;_lookTargetPosition;_controls=null;_cameraObject=null;_lerpToTargetPosition=!1;_lerpCameraToTarget=!1;_cameraTargetPosition=null;_inputs=0;_enableTime=0;_startedListeningToKeyEvents=!1;awake(){this._lookTargetPosition=new fs.Vector3,this._startedListeningToKeyEvents=!1}onEnable(){this._enableTime=this.context.time.time;let t=R.getComponent(this.gameObject,se)?.cam;this._controls||(console.assert(t!=null,"Missing camera",this),t&&(this._cameraObject=t),this._controls=new Yg(t,this.context.renderer.domElement)),this._controls&&(this._controls.enableDamping=this.enableDamping,this._controls.enableKeys=this.enableKeys,this._controls.autoRotate=this.autoRotate,this._controls.autoRotateSpeed=this.autoRotateSpeed,this._controls.enableZoom=this.enableZoom,t?.type==="PerspectiveCamera"?$h||(this._controls.minDistance=this.minZoom,this._controls.maxDistance=this.maxZoom):$h||(this._controls.minZoom=this.minZoom,this._controls.maxZoom=this.maxZoom),this._controls.dampingFactor=this.dampingFactor,this._controls.enablePan=this.enablePan,this._startedListeningToKeyEvents||(this._startedListeningToKeyEvents=!0,this._controls.listenToKeyEvents(window.document.body)))}onDisable(){this._controls&&(this._controls.enabled=!1,this._controls.autoRotate=!1)}onDestroy(){this._controls?.dispose()}start(){if(this._controls){let e=R.getComponent(this.gameObject,se);if(e&&!this.setFromTargetPosition()){this.debugLog&&console.log("NO TARGET");let t=new fs.Vector3(0,0,-1).applyMatrix4(e.cam.matrixWorld);this.setTarget(t,!0)}}this.startCoroutine(this.startRaycastDelayed())}*startRaycastDelayed(){if(yield,!this.setFromTargetPosition()){let e=new ce;e.screenPoint=new fs.Vector2(0,0),e.lineThreshold=.1;let t=this.context.physics.raycast(e);t.length>0&&this.setTarget(t[0].point,!0)}}onBeforeRender(){if(!this._controls)return;(this.context.input.getPointerDown(0)||this.context.input.getPointerDown(1)||this.context.input.getPointerDown(2))&&(this._inputs+=1),this._inputs>0&&(this._controls.autoRotate=!1,this._lerpCameraToTarget=!1,this._lerpToTargetPosition=!1),this._inputs=0;let e=this.middleClickToFocus&&this.context.input.getPointerClicked(1);if(e||=this.doubleClickToFocus&&this.context.input.getPointerDoubleClicked(0)&&this.context.time.time-this._enableTime>.3,e?this.setTargetFromRaycast():(this.context.input.getPointerDown(0)||this.context.input.mouseWheelChanged)&&(this._lerpToTargetPosition=!1,this._lerpCameraToTarget=!1),this._lerpToTargetPosition||this._lerpCameraToTarget){let t=this.context.time.deltaTime*this.targetLerpSpeed;this._lerpCameraToTarget&&this._cameraTargetPosition&&this._cameraObject&&(this.useSlerp&&typeof this._cameraObject?.position.slerp=="function"?(this._cameraObject?.position).slerp(this._cameraTargetPosition,t):this._cameraObject?.position.lerp(this._cameraTargetPosition,t),this._cameraObject.position.distanceTo(this._cameraTargetPosition)<.01&&(this._lerpCameraToTarget=!1)),this._lerpToTargetPosition&&(this.lerpTarget(this._lookTargetPosition,t),this._lookTargetPosition.distanceTo(this._controls.target)<.005&&(this._lerpToTargetPosition=!1))}this.lookAtConstraint?.locked&&this.setFromTargetPosition(0,this.lookAtConstraint01),this._controls&&!this.context.isInXR&&(this.debugLog&&(this._controls.domElement=this.context.renderer.domElement),this._controls.enabled=!0,this._controls.update())}setCameraTarget(e,t=!1){e?(this._lerpCameraToTarget=!0,this._cameraTargetPosition=e.clone(),t&&this._cameraTargetPosition&&this.controllerObject?.position.copy(this._cameraTargetPosition)):this._lerpCameraToTarget=!1}setFromTargetPosition(e=0,t=1){if(!this._controls)return!1;let n=this.lookAtConstraint?.sources;if(n&&n.length>0){let i=n[e];if(i)return i.getWorldPosition(this._lookTargetPosition),this.lerpTarget(this._lookTargetPosition,t),!0}return!1}setTarget(e=null,t=!1){!this._controls||(e!==null&&this._lookTargetPosition.copy(e),t?this._controls.target.copy(this._lookTargetPosition):this._lerpToTargetPosition=!0)}lerpTarget(e,t){!this._controls||this._controls.target.lerp(e,t)}distanceToTarget(e){return this._controls?this._controls.target.distanceTo(e):-1}setTargetFromRaycast(){if(!this.controls)return;let e=this.context.physics.raycast();for(let t of e)if(t.distance>0&&R.isActiveInHierarchy(t.object)){if(this._lookTargetPosition.copy(t.point),this._lerpToTargetPosition=!0,this._cameraTargetPosition=null,this.context.mainCamera){this._lerpCameraToTarget=!0;let n=B(this.context.mainCamera);this._cameraTargetPosition=n.clone().sub(this.controls.target).add(this._lookTargetPosition)}break}}};x([w(xn)],Be.prototype,"lookAtConstraint",2);var Dt=class{used=!1;Use(){this.used=!0}StopPropagation(){this.event?.stopImmediatePropagation()}inputSource;object;isDown;isUp;isPressed;isClicked;event;constructor(e){this.event=e}};import{Object3D as Jg}from"three";var Zg=I("debugeventsystem"),Cn=class extends O{static createIfNoneExists(e){this.didSearchEventSystem||(this.didSearchEventSystem=!0,Cn.systems.length<=0&&Cn.systems.push(...R.findObjectsOfType(Cn,e)));for(let n of Cn.systems)if(n.context===e)return;let t=new Jg;R.addNewComponent(t,Cn),e.scene.add(t)}static ensureUpdateMeshUI(e,t){Jt.update(e,t)}static markUIDirty(e){Jt.markDirty()}static get instance(){return this.systems[0]}orbitControl=null;orbitControlWasEnabled=!1;raycaster=[];constructor(){super(),Cn.systems.push(this)}onDestroy(){Cn.systems.splice(Cn.systems.indexOf(this),1)}start(){}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)}_selectStartFn;_selectEndFn;_selectUpdateFn;onEnable(){let e=new Map;this._selectStartFn??=(n,i)=>{if(!i.grab)return;Jt.resetLastSelected();let r=new Dt;r.inputSource=n,r.isDown=n.selectionDown,r.isUp=n.selectionUp,r.isPressed=n.selectionPressed,r.isClicked=!1,e.set(n,i.grab),i.grab&&!this.handleEvents(i.grab,r)&&(i.grab=null)},this._selectEndFn??=(n,i)=>{if(!i.grab)return;let r=new Dt;r.inputSource=n,r.isDown=n.selectionDown,r.isUp=n.selectionUp,r.isPressed=n.selectionPressed,r.isClicked=n.selectionClick,this.handleEvents(i.grab,r);let s=e.get(n);if(e.set(n,null),s)for(let a=0;a<this.raisedPointerDownEvents.length;a++){let c=this.raisedPointerDownEvents[a];this.raisedPointerDownObjects[a]===s&&c&&(c.onPointerUp?.call(c,r),this.raisedPointerDownEvents.splice(a,1),this.raisedPointerDownObjects.splice(a,1),a--)}};let t=new ce;this._selectUpdateFn??=n=>{t.ray=n.getRay();let i=this.performRaycast(t);if(!i)return;let r=new Dt;r.inputSource=n,this.handleIntersections(i,r)},Y.addEventListener("select-start",this._selectStartFn),Y.addEventListener("select-end",this._selectEndFn),Y.addEventListener("update",this._selectUpdateFn),this.context.pre_update_callbacks.push(this.onBeforeUpdate.bind(this)),this.context.input.addEventListener("pointerdown",this.onPointerDown.bind(this))}onDisable(){Y.removeEventListener("select-start",this._selectStartFn),Y.removeEventListener("select-end",this._selectEndFn),Y.removeEventListener("update",this._selectUpdateFn)}onPointerDown(){this.onBeforeUpdate()}lastPointerEvent=null;objectsHoveredThisFrame=[];objectsHoveredLastFrame=[];raisedPointerDownEvents=[];raisedPointerDownObjects=[];_didMove=!1;onBeforeUpdate(){if(this.objectsHoveredThisFrame.length=0,this.resetMeshUIStates(),G.IsInWebXR||this.context.input.isKeyPressed("Alt"))return;if(!this._didMove){let r=this.context.input.getPointerPositionRC(0);if(r&&r.x===0&&r.y===0)return;this._didMove=!0}let e=this.performRaycast(null),t=new Dt(this.context.input.getPointerEvent(0));if(t.inputSource=this.context.input,t.isClicked=this.context.input.mouseClick,t.isDown=this.context.input.mouseDown,t.isUp=this.context.input.mouseUp,t.isPressed=this.context.input.mousePressed,this.lastPointerEvent=t,!e)return;let n=null,i=null;this.context.input.mouseDown&&this.currentActiveMeshUIComponents.length>0&&this.context.mainCameraComponent&&(n=R.getComponent(this.context.mainCameraComponent.gameObject,Be)??null,n&&(i=n.enabled,n.enabled=!1)),this.handleIntersections(e,t),n&&(this.orbitControl=n,this.orbitControl?.enabled?(this.orbitControlWasEnabled=this.orbitControl.enabled,this.orbitControl.enabled=!1):this.orbitControl&&!this.context.input.mousePressed&&(this.orbitControl.enabled=this.orbitControlWasEnabled,this.orbitControl=null))}_tempComponentsArray=[];onBeforeRender(){if(this.lastPointerEvent)this.lastPointerEvent.used=!1;else return;if(this.lastPointerEvent.isUp){for(let t of this.raisedPointerDownEvents)t.onPointerUp&&t.onPointerUp(this.lastPointerEvent);this.raisedPointerDownEvents.length=0,this.raisedPointerDownObjects.length=0}for(let t of this.objectsHoveredLastFrame)if(this.objectsHoveredThisFrame.indexOf(t)<0){this._tempComponentsArray.length=0;let n=R.getComponentsInParent(t,O,this._tempComponentsArray);this.lastPointerEvent.object=t;for(let i=0;i<n.length;i++){let r=n[i];if(!r.gameObject||r.destroyed)continue;let s=r;s.onPointerExit&&s.onPointerExit(this.lastPointerEvent)}}let e=this.objectsHoveredLastFrame;this.objectsHoveredLastFrame=this.objectsHoveredThisFrame,this.objectsHoveredThisFrame=e}_sortedHits=[];performRaycast(e){if(!this.raycaster)return null;this._sortedHits.length=0;for(let t of this.raycaster){if(!t.activeAndEnabled)continue;let n=t.performRaycast(e);n&&n.length>0&&this._sortedHits.push(...n)}return this._sortedHits.sort((t,n)=>t.distance-n.distance),this._sortedHits}handleIntersections(e,t){if(!e||e.length<=0)return!1;e=this.sortCandidates(e);for(let n of e){let{object:i}=n;if(this.handleEvents(i,t))return!0}return!1}_sortingBuffer=[];_noDepthTestingResults=[];sortCandidates(e){this._sortingBuffer.length=0,this._noDepthTestingResults.length=0;for(let t=0;t<e.length;t++){let n=e[t],i=n.object;if(i.material&&i.material.depthTest===!1){this._noDepthTestingResults.push(n);continue}this._sortingBuffer.push(n)}for(let t of this._sortingBuffer)this._noDepthTestingResults.push(t);return this._noDepthTestingResults}handleEventsArray=[];out={};handleEvents(e,t){if(!this.testIsVisible(e))return t.isClicked&&Zg&&console.log("not allowed",e),!1;let n=e;t.object=e,this.lastPointerEvent=t;let i=e.parent,r=!1,s=t.isClicked??!1,a=null;if(i&&i.isUI){let c=(t.isPressed||t.isClicked)??!1;if(i[bt]){let d=i[bt].gameObject;if(d){if(!At.isInteractable(d,this.out))return this.out.canvasGroup?.interactable??!1;a=this.out.canvasGroup??null;let u=this.handleMeshUIIntersection(e,c);e=d,r=!0}}if(!r&&this.handleMeshUiObjectWithoutShadowDom(i,c))return!0}if(this.objectsHoveredThisFrame.push(e),a===null||a.interactable){let c=this.objectsHoveredLastFrame.indexOf(e)>=0;this.handleEventsArray.length=0;let d=R.getComponentsInParent(e,O,this.handleEventsArray);for(let l=0;l<d.length;l++){if(t.used)return!0;if(d[l].destroyed)continue;let u=d[l];u.interactable!==!1&&(u.onPointerEnter&&(c||u.onPointerEnter(t)),t.isDown&&u.onPointerDown&&!this.raisedPointerDownEvents.includes(u)&&(u.onPointerDown(t),this.raisedPointerDownEvents.push(u),this.raisedPointerDownObjects.push(n)),t.isUp&&u.onPointerUp&&u.onPointerUp(t),t.isClicked&&u.onPointerClick&&u.onPointerClick(t))}}return!0}handleMeshUiObjectWithoutShadowDom(e,t){return!e||!e.isUI?!0:this.handleMeshUIIntersection(e,t)}currentActiveMeshUIComponents=[];handleMeshUIIntersection(e,t){let n=Jt.updateState(e,t);return n&&this.currentActiveMeshUIComponents.push(n),n!==null}resetMeshUIStates(){if(this.context.input.getPointerPressedCount()>0&&Jt.resetLastSelected(),!(!this.currentActiveMeshUIComponents||this.currentActiveMeshUIComponents.length<=0)){for(let e=0;e<this.currentActiveMeshUIComponents.length;e++){let t=this.currentActiveMeshUIComponents[e];Jt.resetState(t)}this.currentActiveMeshUIComponents.length=0}}testIsVisible(e){return e?R.isActiveSelf(e)?this.testIsVisible(e.parent):!1:!0}},Me=Cn;j(Me,"didSearchEventSystem",!1),j(Me,"systems",[]);var Jt=class{static markDirty(){this.needsUpdate=!0}static update(e,t){for(let n of this.lastUpdateFrame)if(n.context===t){if(t.time.frameCount===n.frame)return;n.frame=t.time.frameCount,(this.needsUpdate||t.time.frameCount<30)&&(this.needsUpdate=!1,e.update());return}this.lastUpdateFrame=[{context:t,frame:t.time.frameCount}],e.update()}static updateState(e,t){let n=null;if(e&&(n=this.findBlockInParent(e),n&&n!==this.lastSelected)){if(n.interactable===!1)return null;t?(this.lastSelected=n,n.states.pressed&&n.setState("pressed")):n.states.hovered&&n.setState("hovered"),this.needsUpdate=!0}return n}static resetLastSelected(){let e=this.lastSelected;!e||(this.lastSelected=null,this.resetState(e))}static resetState(e){if(!e)return;e.interactable===!1?e.states.disabled&&e.setState("disabled"):e===this.lastSelected&&e.states.selected?e.setState("selected"):e.setState("normal"),this.needsUpdate=!0}static findBlockInParent(e){return e?e.isBlock&&Object.keys(e.states).length>0?e:this.findBlockInParent(e.parent):null}};j(Jt,"lastSelected",null),j(Jt,"lastUpdateFrame",[]),j(Jt,"needsUpdate",!1);import{AxesHelper as $g}from"three";var So="./include";za.Block.prototype.interactable={get(){return this.interactive},set(o){this.interactable=o}};var bt=Symbol("shadowDomOwner"),Te=class extends O{isRoot(){return this.Root?.gameObject===this.gameObject}markDirty(){Me.markUIDirty(this.context)}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=R.getComponentInParent(this.gameObject,Tn)),this._root}_parentComponent=void 0;onEnable(){super.onEnable()}addShadowComponent(e,t){this.removeShadowComponent();let n=this.isRoot()?this.gameObject:this.gameObject.parent;if(this._parentComponent=R.getComponentInParent(n,Te),!this._parentComponent){console.warn(`Component "${this.name}" doesn't have a UI parent anywhere. Do you have a UI element outside a Canvas?`,this);return}e.name=this.name+" ("+(this.constructor.name??"UI")+")",e.autoLayout=this._parentComponent.controlsChildLayout,e[bt]=this,e.traverse(r=>{r[bt]===void 0&&(r[bt]=this)});let i=!1;if(this.Root?.gameObject===this.gameObject)this.gameObject.add(e);else{let r=this._parentComponent.shadowComponent;r&&(r?.add(e),i=!0)}this.shadowComponent=e,t&&t.shadowComponent&&this.shadowComponent&&t.shadowComponent.add(this.shadowComponent),dn&&e.add(new $g(.5)),this.onAfterAddedToScene(),i&&za.update()}set(e){}traverseOwnedShadowComponents(e,t,n){if(!!e&&e[bt]===t){n(e);for(let i of e.children)this.traverseOwnedShadowComponents(i,t,n)}}removeShadowComponent(){this.shadowComponent&&this.shadowComponent.removeFromParent()}onAfterAddedToScene(){}setInteractable(e){this.shadowComponent&&(this.shadowComponent.interactable=e)}},Tn=class extends Te{awake(){super.awake()}};var At=class{static getObject(e){let t=e[bt];return t&&(t.isComponent===!0?e=t.gameObject:e=t),e}static isInteractable(e,t){if(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 i=Gt(e,r=>{if(r.isGraphic===!0)return r},!1);return t&&i?.isGraphic===!0&&(t.graphic=i),i?.raycastTarget!==!1}static tryFindCanvasGroup(e){if(!e)return null;let t=Gt(e,n=>{let i=n;if(i.blocksRaycasts!==void 0&&i.interactable!==void 0)return i},!1);return t!==void 0?t:this.tryFindCanvasGroup(e.parent)}};var ms=I("debugwebxrcontroller");var Gi=class extends O{},Re=class extends O{static CreateRaycastLine(){let e=new rb(this.geometry),t=e.material;return t.color=this.raycastColor,e.layers.set(2),e.name="line",e.scale.z=1,e}static CreateRaycastHitPoint(){let e=new lb(.5,22,22),t=new sb({color:this.raycastColor}),n=new ob(e,t);return n.visible=!1,n.layers.set(2),n}static Create(e,t,n,i){let r=n?R.addNewComponent(n,Re,!1):new Re;r.webXR=e,r.index=t,r.type=i;let s=e.context;r.controller=s.renderer.xr.getController(t),r.controllerGrip=s.renderer.xr.getControllerGrip(t),r.controllerModel=this.Factory.createControllerModel(r.controller),r.controllerGrip.add(r.controllerModel),r.hand=s.renderer.xr.getHand(t);let a=new pb;Zn(a,s),r.webXR.handModelPath&&r.webXR.handModelPath!==""&&a.setPath("/"+cn(e.sourceId,r.webXR.handModelPath));let c=new db(r.hand,a);return r.hand.add(c),r.hand.traverse(d=>d.layers.set(2)),r.handPointerModel=new ub(r.hand,r.controller),r.controller.addEventListener("connected",d=>{r.setControllerLayers(r.controllerModel,2),r.setControllerLayers(r.controllerGrip,2),r.setControllerLayers(r.hand,2),setTimeout(()=>{r.setControllerLayers(r.controllerModel,2),r.setControllerLayers(r.controllerGrip,2),r.setControllerLayers(r.hand,2)},1e3)}),r.hand.addEventListener("connected",d=>{if(d.data.hand){e.Rig&&e.Rig.add(r.hand),r.type=0,r.handPointerModel.traverse(h=>h.layers.set(2)),r.handPointerModel.pointerObject?.traverse(h=>h.layers.set(2));let u=r.hand.joints;if(u)for(let h of Object.keys(u)){let b=u[h];b.parent||r.hand.add(b)}}}),r}static addEventListener(e,t){let n=this.eventSubs[e]??[];n.push(t),this.eventSubs[e]=n}static removeEventListener(e,t){if(!t)return;let n=this.eventSubs[e]??[],i=n.indexOf(t);i>=0&&n.splice(i,1),this.eventSubs[e]=n}webXR;index=-1;controllerModel;controller;controllerGrip;hand;handPointerModel;grabbed=null;input=null;type=0;get isUsingHands(){let e=this.input?.hand;return e!=null}get wrist(){if(!this.hand)return null;let e=this.hand.joints;return e?e.wrist:null}_wristQuaternion=null;getWristQuaternion(){let e=this.wrist;return e?(this._wristQuaternion||(this._wristQuaternion=new Na),ge(e).multiply(this._wristQuaternion.setFromEuler(new nb(-Math.PI/4,0,0)))):null}movementVector=new Zt;worldRot=new Na;joystick=new cb;didRotate=!1;didTeleport=!1;didChangeScale=!1;lastHit=null;raycastLine=null;_raycastHitPoint=null;_connnectedCallback=null;_disconnectedCallback=null;_selectStartEvt=null;_selectEndEvt=null;get selectionDown(){return this._selectionPressed&&!this._selectionPressedLastFrame}get selectionUp(){return!this._selectionPressed&&this._selectionPressedLastFrame}get selectionPressed(){return this._selectionPressed}get selectionClick(){return this._selectionEndTime-this._selectionStartTime<.3}get raycastHitPoint(){return this._raycastHitPoint}_selectionPressed=!1;_selectionPressedLastFrame=!1;_selectionStartTime=0;_selectionEndTime=0;get useSmoothing(){return this._useSmoothing}_useSmoothing=!0;awake(){if(!this.controller){console.warn("Missing Controller!!!",this);return}this._connnectedCallback=this.onSourceConnected.bind(this),this._disconnectedCallback=this.onSourceDisconnected.bind(this),this._selectStartEvt=this.onSelectStart.bind(this),this._selectEndEvt=this.onSelectEnd.bind(this),this.type===1&&(this.controllerGrip.addEventListener("connected",this._connnectedCallback),this.controllerGrip.addEventListener("disconnected",this._disconnectedCallback),this.controller.addEventListener("selectstart",this._selectStartEvt),this.controller.addEventListener("selectend",this._selectEndEvt)),this.type===0&&(this.controller.addEventListener("selectstart",this._selectStartEvt),this.controller.addEventListener("selectend",this._selectEndEvt))}onDestroy(){this.type===1&&(this.controllerGrip.removeEventListener("connected",this._connnectedCallback),this.controllerGrip.removeEventListener("disconnected",this._disconnectedCallback),this.controller.removeEventListener("selectstart",this._selectStartEvt),this.controller.removeEventListener("selectend",this._selectEndEvt)),this.type===0&&(this.controller.removeEventListener("selectstart",this._selectStartEvt),this.controller.removeEventListener("selectend",this._selectEndEvt)),this.hand?.clear(),this.controllerGrip?.clear(),this.controller?.clear()}onEnable(){this.hand&&(this.hand.name="Hand"),this.controllerGrip&&(this.controllerGrip.name="ControllerGrip"),this.controller&&(this.controller.name="Controller"),this.raycastLine&&(this.raycastLine.name="RaycastLine;"),this.webXR.Controllers.indexOf(this)<0&&this.webXR.Controllers.push(this),this.raycastLine||(this.raycastLine=Re.CreateRaycastLine()),this._raycastHitPoint||(this._raycastHitPoint=Re.CreateRaycastHitPoint()),this.webXR.Rig?.add(this.hand),this.webXR.Rig?.add(this.controllerGrip),this.webXR.Rig?.add(this.controller),this.webXR.Rig?.add(this.raycastLine),this.raycastLine?.add(this._raycastHitPoint),this._raycastHitPoint.visible=!1,this.hand.add(this.handPointerModel),ms&&console.log("ADDED TO RIG",this.webXR.Rig)}onDisable(){this.hand?.removeFromParent(),this.controllerGrip?.removeFromParent(),this.controller?.removeFromParent(),this.raycastLine?.removeFromParent(),this._raycastHitPoint?.removeFromParent();let e=this.webXR.Controllers.indexOf(this);e>=0&&this.webXR.Controllers.splice(e,1)}_isConnected=!1;onSourceConnected(e){if(this._isConnected){console.warn("Received connected event for controller that is already connected",this.index,e);return}this._isConnected=!0,this.input=e.data,this.type===1&&(this.onSelectStart(),this.createPointerEvent("down"))}onSourceDisconnected(e){if(!this._isConnected){console.warn("Received discnnected event for controller that is not connected",e);return}this._isConnected=!1,this.type===1&&(this.onSelectEnd(),this.createPointerEvent("up")),this.input=null}createPointerEvent(e){switch(e){case"down":this.context.input.createPointerDown({pointerId:this.index,clientX:0,clientY:0,button:this.index,pointerType:"touch"});break;case"move":break;case"up":this.context.input.createPointerUp({pointerId:this.index,clientX:0,clientY:0,button:this.index,pointerType:"touch"});break}}rayRotation=new Na;update(){this.context.time.frameCount%60===0&&(this.setControllerLayers(this.controller,2),this.setControllerLayers(this.controllerGrip,2),this.setControllerLayers(this.hand,2));let e=Re.eventSubs["update"];if(e&&e.length>0)for(let i of e)i(this);let t=1;this.type===0?t=this.context.time.deltaTime/.1:this.isUsingHands&&this.handPointerModel.pinched&&(t=this.context.time.deltaTime/.3),this.rayRotation.slerp(ge(this.controller),this.useSmoothing?t:1);let n=B(this.controller);if(this.isUsingHands&&this.handPointerModel.cursorObject&&(this.handPointerModel.cursorObject.visible=!1),this.raycastLine)if(this.type===1)this.raycastLine.visible=!1;else if(this.isUsingHands){this.raycastLine.visible=!this.grabbed,J(this.raycastLine,n);let i=this.hand.joints;if(i&&i.wrist&&this.grabbed&&this.grabbed.isCloseGrab){let s=this.getWristQuaternion();s&&this.rayRotation.copy(s)}Ue(this.raycastLine,this.rayRotation)}else this.raycastLine.visible=!0,Ue(this.raycastLine,this.rayRotation),J(this.raycastLine,n);this.lastHit=this.updateLastHit(),this.grabbed&&this.grabbed.update(),this._selectionPressedLastFrame=this._selectionPressed,this.selectStartCallback&&this.selectStartCallback()}_pinchStartTime=void 0;onUpdate(e){if(this.lastHit=null,!e||e.inputSources.length<=this.index){this.input=null;return}if(this.type===0&&(this.input=e.inputSources[this.index]),!this.input)return;let t=this.webXR.Rig;if(!t)return;this._didNotEndSelection&&!this.handPointerModel.pinched&&(this._didNotEndSelection=!1,this.onSelectEnd()),this.updateStick(this.input);let n=this.input?.gamepad?.buttons;switch(this.input.handedness){case"left":let i=3*Re.MovementSpeedFactor,r=2,s=U.clamp01(this.joystick.length()*2),a=this.joystick.x>0?1:-1,c=Math.pow(this.joystick.x,r);c*=a,c*=s;let d=this.joystick.y>0?1:-1,l=Math.pow(this.joystick.y,r);l*=d,c*=s,t.getWorldQuaternion(this.worldRot),this.movementVector.set(c,0,l),this.movementVector.applyQuaternion(this.webXR.TransformOrientation),this.movementVector.y=0,this.movementVector.applyQuaternion(this.worldRot),this.movementVector.multiplyScalar(i*this.context.time.deltaTime),t.position.add(this.movementVector),this.isUsingHands&&this.runTeleport(t,n);break;case"right":let u=this.joystick.x,h=Math.abs(u);if(h<.4)this.didRotate=!1;else if(h>.5&&!this.didRotate){let b=u>0?-1:1;t.rotateY(U.toRadians(30*b)),this.didRotate=!0}this.runTeleport(t,n);break}}runTeleport(e,t){let n=-this.joystick.y;if(this.hand?.visible&&!this.grabbed){let a=this.handPointerModel.isPinched();a&&this._pinchStartTime===void 0&&(this._pinchStartTime=this.context.time.time),a&&this._pinchStartTime&&this.context.time.time-this._pinchStartTime>.8&&(n=this.handPointerModel.isPinched()?1:0),a||(this._pinchStartTime=void 0)}else this._pinchStartTime=void 0;let i=n>.5&&this.webXR.IsInVR,r=this.webXR.Rig?this.webXR.Rig?.scale?.x<.999:!1,s=null;if(t&&this.input&&!this.input.hand)for(let a=0;a<t.length;a++){let c=t[a];if(a===4)if(c.pressed&&!this.didChangeScale&&this.webXR.IsInVR){this.didChangeScale=!0;let d=this.webXR.Rig;if(d)if(r){r=!1,d.scale.set(1,1,1),s=1,Re.MovementSpeedFactor=1;let l=this.context.mainCamera;Re.PreviousCameraFarDistance&&(l.far=Re.PreviousCameraFarDistance)}else{r=!0,i=!0,s=.1,Re.MovementSpeedFactor=s*2;let l=this.context.mainCamera;Re.PreviousCameraFarDistance=l.far,l.far/=s}}else c.pressed||(this.didChangeScale=!1)}if(i){if(!this.didTeleport){let a=this.raycast();if(this.didTeleport=!0,a&&a.length>0){let c=a[0];if(r||this.isValidTeleportTarget(c.object)){let d=c.point;J(e,d)}}}}else n<.1&&(this.didTeleport=!1);s!==null&&(e.scale.set(s,s,s),e.updateMatrixWorld())}isValidTeleportTarget(e){return R.getComponentInParent(e,Gi)!=null}updateStick(e){!e||!e.gamepad||e.gamepad.axes?.length<4||(this.joystick.x=e.gamepad.axes[2],this.joystick.y=e.gamepad.axes[3])}updateLastHit(){let e=this.raycast(),t=e?e[0]:null;this.lastHit=t;let n=1;if(this.webXR.Rig&&(n/=this.webXR.Rig.scale.x),this.raycastLine){this.raycastLine.scale.z=n*(this.lastHit?.distance??9999);let i=this.raycastLine.material;t!=null?i.color=Re.raycastColor:i.color=Re.raycastNoHitColor}if(this._raycastHitPoint){if(this.lastHit!=null){this._raycastHitPoint.position.z=-1;let i=U.clamp(this.lastHit.distance*.01*n,.015,.1);this._raycastHitPoint.scale.set(i,i,i)}this._raycastHitPoint.visible=this.lastHit!==null&&this.lastHit!==void 0}return t}onSelectStart(){!this.context.connection.allowEditing||(this.selectStartCallback=()=>this.onHandleSelectStart())}selectStartCallback=null;lastSelectStartObject=null;onHandleSelectStart(){this.selectStartCallback=null,this._selectionPressed=!0,this._selectionStartTime=this.context.time.time,this._selectionEndTime=1e3;let e=null,t=!1;if(this.isUsingHands?(e=this.overlap(),e.length<=0?(e=this.raycast(),t=!1):t=!0):e=this.raycast(),ms&&console.log("onHandleSelectStart","close grab? "+t,"intersections",e),e&&e.length>0)for(let n of e){let i=n.object;this.lastSelectStartObject=i;let r={selected:i,grab:i},s=Re.eventSubs["select-start"];if(s&&s.length>0)for(let a of s)a(this,r);r.grab!==i&&ms&&console.log("Grabbed object changed","original",i,"new",r.grab),r.grab&&(this.grabbed=ze.TryTake(this,r.grab,n,t));break}else{let n=Re.eventSubs["select-start"],i={selected:null,grab:null};if(n&&n.length>0)for(let r of n)r(this,i)}}_didNotEndSelection=!1;onSelectEnd(){if(this.isUsingHands&&this.handPointerModel.pinched){this._didNotEndSelection=!0;return}if(!this._selectionPressed)return;this.selectStartCallback=null,this._selectionPressed=!1,this._selectionEndTime=this.context.time.time;let e={grab:this.grabbed?.selected??this.lastSelectStartObject},t=Re.eventSubs["select-end"];if(t&&t.length>0)for(let n of t)n(this,e);this.grabbed&&(this.grabbed.free(),this.grabbed=null)}testIsVisible(e){return!(!e||R.isActiveInHierarchy(e)===!1||At.isInteractable(e)===!1)}setControllerLayers(e,t){if(!!e&&(e.layers.set(t),e.children))for(let n of e.children)this.grabbed?.selected===n||this.grabbed?.selectedMesh===n||this.setControllerLayers(n,t)}getRay(){let e=new ab;return e.origin.copy(B(this.controller)),e.direction.set(0,0,-1).applyQuaternion(this.rayRotation),e}closeGrabBoundingBoxHelper;overlap(){let e=this.isUsingHands&&this.handPointerModel?this.handPointerModel.pointerObject:this.controllerGrip;if(ms&&(!this.closeGrabBoundingBoxHelper&&e&&(this.closeGrabBoundingBoxHelper=new eb(e,16776960),this.scene.add(this.closeGrabBoundingBoxHelper)),this.closeGrabBoundingBoxHelper&&e&&this.closeGrabBoundingBoxHelper.setFromObject(e)),!e)return new Array;let t=B(e).clone();return this.context.physics.sphereOverlap(t,.02)}raycast(){let e=new ce;e.layerMask=new ib,e.layerMask.set(0),e.layerMask.disable(2),e.ray=this.getRay();let t=this.context.physics.raycast(e);for(let n=0;n<t.length;n++){let i=t[n],r=i.object;if(!this.testIsVisible(r)){t.splice(n,1),n--;continue}i.object=At.getObject(r);break}return t}},Y=Re;j(Y,"Factory",new hb),j(Y,"raycastColor",new tp(.9,.3,.3)),j(Y,"raycastNoHitColor",new tp(.6,.6,.6)),j(Y,"geometry",new tb().setFromPoints([new Zt(0,0,0),new Zt(0,0,-1)])),j(Y,"handModels",{}),j(Y,"eventSubs",{}),j(Y,"PreviousCameraFarDistance"),j(Y,"MovementSpeedFactor",1);var Ve=class{static AddEventListener(e,t){return Ve.Events[e]||(Ve.Events[e]=[]),Ve.Events[e].push(t),t}static RemoveEventListener(e,t){if(!t||!Ve.Events[e])return;let n=Ve.Events[e].indexOf(t);n>=0&&Ve.Events[e].splice(n,1)}static Register(e){this.Current.find(t=>t===e)||this.Current.push(e)}static Remove(e){let t=this.Current.indexOf(e);t>=0&&this.Current.splice(t,1)}static TryTake(e,t,n,i){let r=R.getComponentInParent(t,pt);if(r)t=r.gameObject;else return ms&&console.warn("Prevented taking object that is not interactable",t),null;let s=t,a=R.getComponentInParent(t,Je);a&&(a.requestOwnership(),s=a.gameObject);for(let d of this.Current)if(d.selected===s)return d.controller===e||(d.free(),d.Take(e,s,t,a,r,n,i)),d;let c=new Ve;return c.Take(e,s,t,a,r,n,i),c}sync=null;selected=null;selectedParent=null;selectedMesh=null;controller=null;grabTime=0;grabUUID="";isCloseGrab=!1;originalMaterial=null;usageMarker=null;rigidbodies=null;didReparent=!1;grabDistance=0;interactable=null;positionSource=null;Take(e,t,n,i,r,s,a){if(console.assert(t!==null,"Expected object to be taken but was",t),e.isUsingHands?this.positionSource=a?e.wrist:e.controller:this.positionSource=e.controller,!this.positionSource)return console.warn("No position source"),this;let c={controller:e,take:t,hit:n,sync:i,interactable:r};Ve.Events.WillTake?.forEach(b=>b(this,c));let d=n;d?.material&&(this.originalMaterial=d.material,Array.isArray(d.material)||(d.material=d.material.clone(),d.material&&d.material.emissive&&(d.material.emissive.b=.2))),this.selected=t,this.selectedParent||(this.selectedParent=t.parent),this.selectedMesh=d,this.controller=e,this.interactable=r,this.isCloseGrab=a,this.didReparent=!1,this.sync=i,this.grabTime=e.context.time.time,this.grabUUID=Date.now().toString(),this.usageMarker=R.addNewComponent(this.selected,ft),this.rigidbodies=R.getComponentsInChildren(this.selected,q),B(this.positionSource,this.lastControllerWorldPos);let l=()=>a?this.lastControllerWorldPos.clone():s.point.clone();this.grabDistance=l().distanceTo(this.lastControllerWorldPos),this.totalChangeAlongDirection=0,this.localPositionOffsetToGrab=this.selected.worldToLocal(l());let u=e.isUsingHands&&a?this.controller.getWristQuaternion().clone():e.rayRotation.clone();ge(this.selected,this.localQuaternionToGrab).premultiply(u.invert());let h=this.controller.webXR.Rig;return h&&this.rigPositionLastFrame.copy(B(h)),ue.Add(e.context,this.selected),Ve.Register(this),this.sync&&(this.sync.fastMode=!0),Ve.Events.DidTake?.forEach(b=>b(this,c)),this}free(){if(!this.selected)return;let e={controller:this.controller,take:this.selected,hit:this.selected,sync:this.sync,interactable:null};Ve.Events.WillFree?.forEach(i=>i(this,e)),ue.Remove(this.controller.context,this.selected),Ve.Remove(this),this.sync&&(this.sync.fastMode=!1);let t=this.selectedMesh;t&&this.originalMaterial&&t.material&&(t.material=this.originalMaterial);let n=this.selected;if(this.didReparent&&n.parent){let i=this.selectedParent;i?i.attach(n):this.controller?.context.scene.attach(n)}if(this.usageMarker?.destroy(),this.controller&&(this.controller.grabbed=null),this.selected=null,this.selectedParent=null,this.selectedMesh=null,this.sync=null,this.rigidbodies)for(let i of this.rigidbodies)i.wakeUp(),i.setVelocity(i.smoothedVelocity);this.rigidbodies=null,this.localPositionOffsetToGrab=null,this.quaternionLerp=null,Ve.Events.DidFree?.forEach(i=>i(this,e))}grabPoint=new Zt;localPositionOffsetToGrab=null;localPositionOffsetToGrab_worldSpace=new Zt;localQuaternionToGrab=new Na(0,0,0,1);targetDir=null;quaternionLerp=null;controllerDir=new Zt;controllerWorldPos=new Zt;lastControllerWorldPos=new Zt;controllerPosDelta=new Zt;totalChangeAlongDirection=0;rigPositionLastFrame=new Zt;controllerMovementSinceLastFrame(){if(!this.positionSource||!this.controller)return 0;this.controllerDir.set(0,0,-1),this.controllerDir.applyQuaternion(this.controller.rayRotation),B(this.positionSource,this.controllerWorldPos),this.controllerPosDelta.copy(this.controllerWorldPos),this.controllerPosDelta.sub(this.lastControllerWorldPos),this.lastControllerWorldPos.copy(this.controllerWorldPos);let e=this.controller.webXR.Rig;if(e){let n=B(e),i=this.rigPositionLastFrame.sub(n);this.controllerPosDelta.add(i),this.rigPositionLastFrame.copy(n)}return this.controllerDir.dot(this.controllerPosDelta)}update(){if(this.rigidbodies)for(let e of this.rigidbodies)e.resetVelocities();if(this.sync&&this.controller&&this.controller.context.connection.isInRoom&&this.controller.context.time.time-this.grabTime>3&&this.sync.hasOwnership()===!1&&(console.log("no ownership, will leave",this.sync.guid),this.free()),!(this.interactable&&!this.interactable.canGrab)){if(!this.didReparent&&this.selected&&this.controller){let e=this.controller.webXR.Rig?.scale.x??1;this.totalChangeAlongDirection+=this.controllerMovementSinceLastFrame();let t=1;this.controller.type===0&&(t=Math.max(0,1+this.totalChangeAlongDirection*2/e),t=t*t*t),this.grabDistance/e<.8&&(t=1),this.targetDir||(this.targetDir=new Zt),this.targetDir.set(0,0,-this.grabDistance*t);let n=this.targetDir.applyQuaternion(this.controller.rayRotation).add(this.controllerWorldPos),i=this.controller.rayRotation.clone().multiplyQuaternions(this.controller.rayRotation,this.localQuaternionToGrab);this.quaternionLerp||(this.quaternionLerp=i.clone()),this.quaternionLerp.slerp(i,this.controller.useSmoothing?this.controller.context.time.deltaTime/.03:1),Ue(this.selected,this.quaternionLerp),this.selected.updateWorldMatrix(!1,!1),this.grabPoint.copy(n),this.localPositionOffsetToGrab&&(this.localPositionOffsetToGrab_worldSpace.copy(this.localPositionOffsetToGrab),this.selected.localToWorld(this.localPositionOffsetToGrab_worldSpace).sub(B(this.selected)),n.sub(this.localPositionOffsetToGrab_worldSpace)),J(this.selected,n)}if(this.rigidbodies!=null)for(let e of this.rigidbodies)e.wakeUp(),e.setBodyFromGameObject({x:0,y:0,z:0});ne.markDirty(this.selected,!0)}}},ze=Ve;j(ze,"Events",{}),j(ze,"Current",[]);var ai=class extends O{awake(){}};import{Quaternion as gs,Vector3 as Wa,Vector4 as fb}from"three";var Rn=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)}w(){return this.bb.readFloat32(this.bb_pos+12)}static sizeOf(){return 16}static createVec4(e,t,n,i,r){return e.prep(4,16),e.writeFloat32(r),e.writeFloat32(i),e.writeFloat32(n),e.writeFloat32(t),e.offset()}};var we=class{bb=null;bb_pos=0;__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsVrUserStateBuffer(e,t){return(t||new we).__init(e.readInt32(e.position())+e.position(),e)}static getSizePrefixedRootAsVrUserStateBuffer(e,t){return e.setPosition(e.position()+4),(t||new we).__init(e.readInt32(e.position())+e.position(),e)}guid(e){let t=this.bb.__offset(this.bb_pos,4);return t?this.bb.__string(this.bb_pos+t,e):null}time(){let e=this.bb.__offset(this.bb_pos,6);return e?this.bb.readInt64(this.bb_pos+e):this.bb.createLong(0,0)}avatarId(e){let t=this.bb.__offset(this.bb_pos,8);return t?this.bb.__string(this.bb_pos+t,e):null}position(e){let t=this.bb.__offset(this.bb_pos,10);return t?(e||new ve).__init(this.bb_pos+t,this.bb):null}rotation(e){let t=this.bb.__offset(this.bb_pos,12);return t?(e||new Rn).__init(this.bb_pos+t,this.bb):null}scale(){let e=this.bb.__offset(this.bb_pos,14);return e?this.bb.readFloat32(this.bb_pos+e):0}posLeftHand(e){let t=this.bb.__offset(this.bb_pos,16);return t?(e||new ve).__init(this.bb_pos+t,this.bb):null}posRightHand(e){let t=this.bb.__offset(this.bb_pos,18);return t?(e||new ve).__init(this.bb_pos+t,this.bb):null}rotLeftHand(e){let t=this.bb.__offset(this.bb_pos,20);return t?(e||new Rn).__init(this.bb_pos+t,this.bb):null}rotRightHand(e){let t=this.bb.__offset(this.bb_pos,22);return t?(e||new Rn).__init(this.bb_pos+t,this.bb):null}static startVrUserStateBuffer(e){e.startObject(10)}static addGuid(e,t){e.addFieldOffset(0,t,0)}static addTime(e,t){e.addFieldInt64(1,t,e.createLong(0,0))}static addAvatarId(e,t){e.addFieldOffset(2,t,0)}static addPosition(e,t){e.addFieldStruct(3,t,0)}static addRotation(e,t){e.addFieldStruct(4,t,0)}static addScale(e,t){e.addFieldFloat32(5,t,0)}static addPosLeftHand(e,t){e.addFieldStruct(6,t,0)}static addPosRightHand(e,t){e.addFieldStruct(7,t,0)}static addRotLeftHand(e,t){e.addFieldStruct(8,t,0)}static addRotRightHand(e,t){e.addFieldStruct(9,t,0)}static endVrUserStateBuffer(e){return e.endObject()}static finishVrUserStateBufferBuffer(e,t){e.finish(t)}static finishSizePrefixedVrUserStateBufferBuffer(e,t){e.finish(t,void 0,!0)}};var np=I("debugxr"),bs=I("debugavatar");var rd="VRUS";fo(rd,we.getRootAsVrUserStateBuffer);function id(){return new Date().getTime()}function mb(o){let e=o&4294967295,t=o/Math.pow(2,32)&1048575;return Ae.create(e,t)}var vs=class{guid;time;avatarId;position=new Wa;rotation=new fb;scale=1;posLeftHand=new Wa;posRightHand=new Wa;rotLeftHand=new gs;rotRightHand=new gs;constructor(e){this.guid=e}update(e,t,n,i,r){this.time=id(),this.avatarId=r,this.position.set(t.x,t.y,t.z),e&&this.position.applyMatrix4(e.matrixWorld);let s=vs.quat0,a=vs.quat1;s.set(n.x,n.y,n.z,n.w),s=s.multiplyQuaternions(s,vs.invertRotation),e&&(e.getWorldQuaternion(a),s.multiplyQuaternions(a,s)),this.rotation.set(s.x,s.y,s.z,s.w),this.scale=e.scale.x;let c=i.LeftController?.controllerGrip;c&&(c.getWorldPosition(this.posLeftHand),c.getWorldQuaternion(this.rotLeftHand));let d=i.RightController?.controllerGrip;if(d&&(d.getWorldPosition(this.posRightHand),d.getWorldQuaternion(this.rotRightHand)),i.LeftController?.hand?.visible){let l=i.LeftController.wrist;l&&(l.getWorldPosition(this.posLeftHand),l.getWorldQuaternion(this.rotLeftHand))}if(i.RightController?.hand?.visible){let l=i.RightController.wrist;l&&(l.getWorldPosition(this.posRightHand),l.getWorldQuaternion(this.rotRightHand))}}sendAsBuffer(e,t){e.clear();let n=e.createString(this.guid),i=e.createString(this.avatarId);we.startVrUserStateBuffer(e),we.addGuid(e,n),we.addTime(e,mb(this.time)),we.addAvatarId(e,i),we.addPosition(e,ve.createVec3(e,this.position.x,this.position.y,this.position.z)),we.addRotation(e,Rn.createVec4(e,this.rotation.x,this.rotation.y,this.rotation.z,this.rotation.w)),we.addScale(e,this.scale),we.addPosLeftHand(e,ve.createVec3(e,this.posLeftHand.x,this.posLeftHand.y,this.posLeftHand.z)),we.addPosRightHand(e,ve.createVec3(e,this.posRightHand.x,this.posRightHand.y,this.posRightHand.z)),we.addRotLeftHand(e,Rn.createVec4(e,this.rotLeftHand.x,this.rotLeftHand.y,this.rotLeftHand.z,this.rotLeftHand.w)),we.addRotRightHand(e,Rn.createVec4(e,this.rotRightHand.x,this.rotRightHand.y,this.rotRightHand.z,this.rotRightHand.w));let r=we.endVrUserStateBuffer(e);e.finish(r,rd);let s=e.asUint8Array();t.sendBinary(s)}setFromBuffer(e,t){if(!e)return;this.guid=e,this.time=t.time().toFloat64();let n=t.avatarId();n&&(this.avatarId=n);let i=t.position();i&&this.position.set(i.x(),i.y(),i.z());let r=t.rotation();r&&this.rotation.set(r.x(),r.y(),r.z(),r.w());let s=t.posLeftHand();s&&this.posLeftHand.set(s.x(),s.y(),s.z());let a=t.posRightHand();a&&this.posRightHand.set(a.x(),a.y(),a.z());let c=t.rotLeftHand();c&&this.rotLeftHand.set(c.x(),c.y(),c.z(),c.w());let d=t.rotRightHand();d&&this.rotRightHand.set(d.x(),d.y(),d.z(),d.w()),this.scale=t.scale()}},vt=vs;j(vt,"invertRotation",new gs().setFromAxisAngle(new Wa(0,1,0),Math.PI)),j(vt,"quat0",new gs),j(vt,"quat1",new gs);var Sn=class extends O{webXR=null;debugAvatarUser=null;voip=null;async awake(){if(this.webXR||(this.webXR=R.getComponent(this.gameObject,G)),this.webXR||(this.webXR=R.findObjectOfType(G,this.context)),!this.webXR&&(console.log("Missing webxr component"),this.webXR=R.findObjectOfType(G,this.context),!this.webXR)){console.error("Could not find webxr component");return}if(this.voip||(this.voip=R.findObjectOfType(Fe,this.context)),bs){let e="debug-avatar-"+bs,t=new gt(this.context,e,this.webXR);if(this.debugAvatarUser=t,typeof bs=="string"&&bs.length>0)if(await t.setAvatarOverride(bs)){let n=new vt(e);n.position.y+=1;let i=.5;n.posLeftHand.y+=i,n.posLeftHand.x+=i,n.posRightHand.y+=i,n.posRightHand.x-=i,t.tryUpdate(n,0)}else t.destroy()}}onEnable(){if(!this.webXR&&(this.webXR=R.getComponent(this.gameObject,G),!this.webXR)){console.warn("Missing webxr component on "+this.gameObject.name);return}this.eventSub_WebXRStartEvent=this.onXRSessionStart.bind(this),G.addEventListener("xrStarted",this.eventSub_WebXRStartEvent),this.eventSub_WebXRUpdateEvent=this.onXRSessionUpdate.bind(this),G.addEventListener("xrUpdate",this.eventSub_WebXRUpdateEvent),this.eventSub_WebXREndEvent=this.onXRSessionEnded.bind(this),G.addEventListener("xrStopped",this.eventSub_WebXREndEvent),this.eventSub_ConnectionEvent=this.onConnected.bind(this),this.context.connection.beginListen("joined-room",this.eventSub_ConnectionEvent),this.context.connection.beginListen("webxr-user-joined",e=>{console.log("webxr user joined evt")}),this.context.connection.beginListen("webxr-user-left",e=>{let t=e.id!==null&&e.id!==void 0;!t||(console.log("webxr user left evt"),t&&(this.avatars[e.id]?.destroy(),this.avatars[e.id]=void 0))}),this.context.connection.beginListenBinrary(rd,e=>{let t=e.guid();if(!t)return;let n=e.time().toFloat64(),i=this.tempState;i.setFromBuffer(t,e),this.onTryGetAvatar(t,n)?.tryUpdate(i,n)}),this.context.connection.beginListen("vr-session-update",e=>{let t=e.guid,n=e.time;this.onTryGetAvatar(t,n)?.tryUpdate(e,n)})}tempState=new vt("");onTryGetAvatar(e,t){if(e===this.context.connection.connectionId)return null;let n=new Date().getTime()-t;if(n>5e3)return np&&console.log("old data",n,e),null;let i=this.avatars[e];if(i===void 0)try{console.log("create new avatar");let r=new gt(this.context,e,this.webXR);i=r,this.avatars[e]=r}catch(r){this.avatars[e]=null,console.error(r)}return i}onDisable(){this.eventSub_ConnectionEvent&&this.context.connection.stopListening("joined-room",this.eventSub_ConnectionEvent),G.removeEventListener("xrStarted",this.eventSub_WebXRStartEvent),G.removeEventListener("xrUpdate",this.eventSub_WebXRUpdateEvent),G.removeEventListener("xrStopped",this.eventSub_WebXREndEvent)}update(){let e=id();this.debugAvatarUser&&(this.debugAvatarUser.lastUpdate=e),this.detectPotentiallyDisconnectedAvatarsAndRemove();for(let t in this.avatars){let n=this.avatars[t];!n||n.update()}}_removeAvatarsList=[];detectPotentiallyDisconnectedAvatarsAndRemove(){let e=id();for(let t in this.avatars){let n=this.avatars[t];if(!n){this._removeAvatarsList.push(t);continue}e-n.lastUpdate>1e4&&(console.log("avatar timed out (didnt receive any updates in a while) - destroying it now"),n.destroy(),this.avatars[t]=void 0)}for(let t of this._removeAvatarsList)delete this.avatars[t];this._removeAvatarsList.length=0}buildLocalAvatar(){if(this.localAvatar)return;let e=this.context.connection?.connectionId??this.k_LocalAvatarNoNetworkingGuid;this.localAvatar=new gt(this.context,e,this.webXR),this.localAvatar.isLocalAvatar=!0,this.localAvatar.setAvatarOverride(this.getAvatarId()),this.avatars[this.localAvatar.guid]=this.localAvatar}eventSub_ConnectionEvent=null;eventSub_WebXRStartEvent=null;eventSub_WebXREndEvent=null;eventSub_WebXRUpdateEvent=null;avatars={};localAvatar=null;k_LocalAvatarNoNetworkingGuid="local";onConnected(){np&&console.log("Hey you are connected as "+this.context.connection.connectionId),this.localAvatar?.guid===this.k_LocalAvatarNoNetworkingGuid&&(this.localAvatar&&(this.localAvatar?.destroy(),this.avatars[this.localAvatar.guid]=void 0),this.localAvatar=null,this.xrState=null,this.ownership?.freeOwnership(),this.ownership=null)}onXRSessionStart(e){if(console.log("XR session started"),this.context.connection.send("webxr-user-joined",{id:this.context.connection.connectionId,mode:"vr"}),this.localAvatar&&(this.localAvatar?.destroy(),this.avatars[this.localAvatar.guid]=void 0,this.localAvatar=null),this.xrState=null,this.ownership?.freeOwnership(),this.ownership=null,this.avatars)for(let t in this.avatars)this.avatars[t]?.updateFlags()}onXRSessionEnded(e){console.log("XR session ended"),this.context.connection.send("webxr-user-left",{id:this.context.connection.connectionId,mode:"vr"})}ownership=null;xrState=null;builder=new st(1024);onXRSessionUpdate(e){this.xrState??=new vt(this.context.connection.connectionId??this.k_LocalAvatarNoNetworkingGuid),this.ownership??=new Ri(this.context.connection,this.context.connection.connectionId??this.k_LocalAvatarNoNetworkingGuid),this.ownership.guid=this.context.connection.connectionId??this.k_LocalAvatarNoNetworkingGuid,this.buildLocalAvatar();let{frame:t,xr:n,rig:i}=e,r=t.getViewerPose(n.getReferenceSpace());if(!r)return;let s=r?.transform,a=s.position,c=s.orientation;this.xrState.update(i,a,c,this.webXR,this.getAvatarId()),this.localAvatar&&(this.context.connection.connectionId&&(this.localAvatar.guid=this.context.connection.connectionId),this.localAvatar.tryUpdate(this.xrState,0)),!(this.ownership&&!this.ownership.hasOwnership&&this.context.connection.isConnected&&(this.context.time.frameCount%120===0&&this.ownership.requestOwnership(),!this.ownership.hasOwnership))&&(!this.context.connection.isConnected||!this.context.connection.connectionId||this.xrState.sendAsBuffer(this.builder,this.context.connection))}getAvatarId(){return I("avatar")??null}};async function wb(){return"xr"in navigator?await navigator.xr.isSessionSupported("immersive-ar")===!0:!1}async function xb(){return"xr"in navigator?await navigator.xr.isSessionSupported("immersive-vr")===!0:!1}var sd=!1,ad=!1;wb().then(o=>sd=o);xb().then(o=>ad=o);var Se=class extends O{enableVR=!0;enableAR=!0;defaultAvatar;handModelPath="";createVRButton=!0;createARButton=!0;static get IsInWebXR(){return this._isInXr}static get XRSupported(){return"xr"in navigator&&(sd||ad)}static get IsARSupported(){return sd}static get IsVRSupported(){return ad}static addEventListener(e,t){return this.events.addEventListener(e,t),t}static removeEventListener(e,t){return this.events.removeEventListener(e,t),t}static createVRButton(e,t){Se.XRSupported||console.warn("WebXR is not supported on this device");let n=Co.createButton(e.context.renderer);return n.classList.add("webxr-ar-button"),n.classList.add("webxr-button"),this.resetButtonStyles(n),(t?.registerClick??!0)&&n.addEventListener("click",e.onClickedVRButton.bind(e)),n}static createARButton(e,t){let n=e.webAR?.getAROverlayContainer(),i={};n&&(i.domOverlay={root:n},i.optionalFeatures=["hit-test","dom-overlay"]);let r=Ba.createButton(e.context.renderer,i);return r.classList.add("webxr-ar-button"),r.classList.add("webxr-button"),Se.resetButtonStyles(r),(t?.registerClick??!0)&&r.addEventListener("click",e.onClickedARButton.bind(e)),r}static resetButtonStyles(e){!e||(e.style.position="",e.style.bottom="",e.style.left="")}endSession(){let e=this.context.renderer.xr.getSession();e&&e.end()}get Rig(){return this.rig||this.ensureRig(),this.rig}controllers=[];get Controllers(){return this.controllers}get LeftController(){return this.controllers.length>0&&this.controllers[0].input?.handedness==="left"?this.controllers[0]:this.controllers.length>1&&this.controllers[1].input?.handedness==="left"?this.controllers[1]:null}get RightController(){return this.controllers.length>0&&this.controllers[0].input?.handedness==="right"?this.controllers[0]:this.controllers.length>1&&this.controllers[1].input?.handedness==="right"?this.controllers[1]:null}get ARButton(){return this._arButton}get VRButton(){return this._vrButton}get IsInVR(){return this._isInVR}get IsInAR(){return this._isInAR}rig;isInit=!1;_requestedAR=!1;_requestedVR=!1;_isInAR=!1;_isInVR=!1;_arButton;_vrButton;webAR=null;awake(){if(this.defaultAvatar&&typeof this.defaultAvatar=="string"&&(this.defaultAvatar=je.getOrCreate(this.sourceId??"/",this.defaultAvatar,this.context)),!R.findObjectOfType(Sn,this.context)){let e=R.addNewComponent(this.gameObject,Sn,!1);e.webXR=this}}onEnable(){if(this.isInit||!this.enableAR&&!this.enableVR)return;this.isInit=!0,this.context.renderer.xr.enabled=!0,this.webAR=new li(this);let e=Se.XRSupported,t,n,i=document.createElement("div");i.classList.add("webxr-buttons"),this.context.domElement.append(i),this.enableAR&&this.createARButton&&(t=Se.createARButton(this),this._arButton=t,i.appendChild(t)),this.createVRButton&&this.enableVR&&(n=Se.createVRButton(this),this._vrButton=n,i.appendChild(n)),setTimeout(()=>{Se.resetButtonStyles(n),Se.resetButtonStyles(t)},1e3)}_transformOrientation=new od;get TransformOrientation(){return this._transformOrientation}_currentHeadPose=null;get HeadPose(){return this._currentHeadPose}onBeforeRender(e){if(!e)return;let t=this.context.renderer.xr.getSession();if(t){let n=e.getViewerPose(this.context.renderer.xr.getReferenceSpace());if(this._currentHeadPose=n,!n)return;let i=n?.transform;i&&this._transformOrientation.set(i.orientation.x,i.orientation.y,i.orientation.z,i.orientation.w);for(let r of this.controllers)r.onUpdate(t);this._isInAR&&this.webAR?.onUpdate(t,e)}Se._isInXr===!1&&t&&this.onEnterXR(t,e),Se.events.dispatchEvent({type:"xrUpdate",frame:e,xr:this.context.renderer.xr,rig:this.rig})}onClickedARButton(){this._isInAR||(this._requestedAR=!0,this._requestedVR=!1,this.captureCameraState())}onClickedVRButton(){if(!this._isInVR){if(this._requestedVR){this.onExitXR(null);return}this._requestedAR=!1,this._requestedVR=!0,this.captureCameraState(),this.ensureRig();for(let e=0;e<2;e++)Y.Create(this,e,this.gameObject,0);Se.events.dispatchEvent({type:"requestVRSession"})}}captureCameraState(){this.context.mainCamera&&(this._originalCameraPosition.copy(B(this.context.mainCamera)),this._originalCameraRotation.copy(ge(this.context.mainCamera)),this._originalCameraParent=this.context.mainCamera.parent)}ensureRig(){if(!this.rig){let e=R.findObjectOfType(ai,this.context);e?(this.rig=e.gameObject,this.rig.rotateY(Math.PI)):(this.rig=new vb,this.rig.rotateY(Math.PI),this.rig.name="XRRig",this.context.scene.add(this.rig))}}_originalCameraParent=null;_originalCameraPosition=new sp;_originalCameraRotation=new od;onEnterXR(e,t){console.log("[XR] session begin",e),Se._isInXr=!0,this.ensureRig();let n=this.context.renderer.xr.getReferenceSpace();if(n&&this.rig){let a=t.getViewerPose(n)?.transform.orientation;if(a){let c=new od(a.x,a.y,a.z,a.w),d=new gb().setFromQuaternion(c);this.rig.rotateY(d.y)}}let i=this.context.renderer.xr;if(this.context.mainCamera){let s=i.getCamera(this.context.mainCamera);for(let a of s.cameras)a.layers.enableAll();this.rig.add(this.context.mainCamera)}let r=this._requestedAR?2:4;switch($e.Global.Set(r),r){case 2:this.context.xrSessionMode="immersive-ar",this._isInAR=!0,this.webAR?.onBegin(e);break;case 4:this.context.xrSessionMode="immersive-vr",this._isInVR=!0,this.onEnterVR(e);break}e.addEventListener("end",()=>{console.log("[XR] session end"),Se._isInXr=!1,this.onExitXR(e)}),this.onEnterXR_HandleMirrorWindow(e),Se.events.dispatchEvent({type:"xrStarted",session:e})}onExitXR(e){this._isInAR&&e&&this.webAR?.onEnd(e),this._isInAR=!1,this._isInVR=!1,this._requestedAR=!1,this._requestedVR=!1,this.context.xrSessionMode=void 0,this.xrMirrorWindow&&(this.xrMirrorWindow.close(),this.xrMirrorWindow=null),this.destroyControllers(),this.context.mainCamera&&(this._originalCameraParent?.add(this.context.mainCamera),J(this.context.mainCamera,this._originalCameraPosition),Ue(this.context.mainCamera,this._originalCameraRotation),this.context.mainCamera.scale.set(1,1,1)),$e.Global.Set(17),Se.events.dispatchEvent({type:"xrStopped",session:e})}onEnterVR(e){}destroyControllers(){for(let e=this.controllers.length-1;e>=0;e-=1)this.controllers[e]?.destroy();this.controllers.length=0}xrMirrorWindow=null;onEnterXR_HandleMirrorWindow(e){!I("mirror")||setTimeout(()=>{if(!Se.IsInWebXR)return;let t=new URL(window.location.href);to(t.searchParams,To,1),to(t.searchParams,"isMirror",1);let n=t.toString();this.xrMirrorWindow=window.open(n,"webxr sync","popup=yes"),this.xrMirrorWindow&&(this.xrMirrorWindow.onload=()=>{this.xrMirrorWindow&&(this.xrMirrorWindow.onbeforeunload=()=>{Se.IsInWebXR&&e.end()})})},1e3)}},G=Se;j(G,"_isInXr",!1),j(G,"events",new bb),x([w()],G.prototype,"enableVR",2),x([w()],G.prototype,"enableAR",2),x([w(je)],G.prototype,"defaultAvatar",2),x([w()],G.prototype,"handModelPath",2),x([w()],G.prototype,"createVRButton",2),x([w()],G.prototype,"createARButton",2);var Po=class{get webxr(){return this._webxr}_webxr;reticle=null;reticleParent=null;hitTestSource=null;reticleActive=!0;previousBackground=null;previousEnvironment=null;sessionRoot=null;_previousParent=null;get context(){return this.webxr.context}constructor(e){this._webxr=e}arDomOverlay=null;arOverlayElement=null;noHitTestAvailable=!1;didPlaceARSessionRoot=!1;getAROverlayContainer(){this.arDomOverlay=this.webxr.context.domElement;let e=this.arDomOverlay;return e.getAROverlayContainer?this.arOverlayElement=e.getAROverlayContainer():this.arOverlayElement=this.arDomOverlay,this.arOverlayElement}setReticleActive(e){this.reticleActive=e}async onBegin(e){let t=this.webxr.context;this.reticleActive=!0,this.didPlaceARSessionRoot=!1,this.getAROverlayContainer();let n=navigator.userAgent?.includes("OculusBrowser")?0:1,i=n===1?4:2;for(let s=0;s<i;s++)Y.Create(this.webxr,s,this.webxr.gameObject,n);(!this.sessionRoot||this.sessionRoot.destroyed||!this.sessionRoot.activeAndEnabled)&&(this.sessionRoot=R.findObjectOfType(mt,t)),this.previousBackground=t.scene.background,this.previousEnvironment=t.scene.environment,t.scene.background=null,e.requestReferenceSpace("viewer").then(s=>{e.requestHitTestSource({space:s}).then(a=>{this.hitTestSource=a}).catch(a=>{this.noHitTestAvailable=!0,console.warn("WebXR: Hit test not supported")})}),!this.reticle&&this.sessionRoot&&(this.reticle=new yb(new Eb(.07,.09,32).rotateX(-Math.PI/2),new _b),this.reticle.name="AR Placement reticle",this.reticle.matrixAutoUpdate=!1,this.reticle.visible=!1,this.reticleParent=new rp,this.reticleParent.name="AR Reticle Parent",this.reticleParent.matrixAutoUpdate=!1,this.reticleParent.add(this.reticle),this.reticleParent.matrix.copy(this.sessionRoot.gameObject.matrixWorld),this.webxr.scene?(this.context.scene.add(this.reticleParent),this.context.scene.visible=!0):console.warn("Could not found WebXR Rig")),this._previousParent=this.webxr.gameObject,Po.tempWebXRObject||(Po.tempWebXRObject=new rp),this.context.scene.add(Po.tempWebXRObject),R.addComponent(Po.tempWebXRObject,this.webxr),this.sessionRoot?(this.sessionRoot.webAR=this,this.sessionRoot?.onBegin(e)):console.warn("No WebARSessionRoot found in scene");let r=this.context.domElement;r?.onEnterAR?.call(r,e,this.arOverlayElement),this.context.mainCameraComponent?.applyClearFlagsIfIsActiveCamera()}onEnd(e){this._previousParent&&(console.log("ADD",this._previousParent),R.addComponent(this._previousParent,this.webxr),this._previousParent=null),this.hitTestSource=null;let t=this.webxr.context;if(t.scene.background=this.previousBackground,t.scene.environment=this.previousEnvironment,this.sessionRoot&&this.sessionRoot.onEnd(this.webxr.Rig,e),this.arDomOverlay){let n=this.arOverlayElement;n.onExitAR?.call(n,e)}this.context.mainCameraComponent?.applyClearFlagsIfIsActiveCamera()}onUpdate(e,t){if(this.noHitTestAvailable===!0){if(this.reticle&&(this.reticle.visible=!1),!this.didPlaceARSessionRoot){this.didPlaceARSessionRoot=!0;let i=this.webxr.Rig,r=Cb.clone();if(i){let s=new sp(0,0,0).add(i.position).divideScalar(this.sessionRoot?.arScale??1);r.multiply(new op().makeTranslation(s.x,s.y,s.z))}this.sessionRoot?.placeAt(i,r)}return}if(!this.hitTestSource)return;let n=t.getHitTestResults(this.hitTestSource);if(n.length){let i=n[0],r=this.webxr.context.renderer.xr.getReferenceSpace();if(r){let s=i.getPose(r);if(this.sessionRoot){let a=this.sessionRoot.onUpdate(this.webxr.Rig,e,s);this.didPlaceARSessionRoot=a}if(this.reticle&&(this.reticle.visible=this.reticleActive,this.reticleActive&&s)){let a=s.transform.matrix;this.reticle.matrix.fromArray(a),this.webxr.Rig&&this.reticle.matrix.premultiply(this.webxr.Rig.matrix)}}}else this.sessionRoot?.onUpdate(this.webxr.Rig,e,null),this.reticle&&(this.reticle.visible=!1)}},li=Po;j(li,"tempWebXRObject");var Cb=new op().identity().makeTranslation(0,-.5,0);var ld=!1;var Oo=class extends pt{static get HasAnySelected(){return this._active!==null}transformSelf=!0;orbit=null;selectStartEventListener=[];selectEndEventListener=[];constructor(){super(),this.selectStartEventListener=[],this.selectEndEventListener=[],this._dragDelta=new Q.Vector2}addDragEventListener(e,t){switch(e){case"selectstart":this.selectStartEventListener.push(t);break;case"selectend":this.selectEndEventListener.push(t);break}}_dragHelper=null;start(){this.orbit=R.findObjectOfType(Be,this.context)}_draggingRigidbodies=[];allowEdit(e=null){return this.context.connection.allowEditing}onPointerEnter(e){if(!this.allowEdit(this.gameObject)||G.IsInWebXR)return;let t=R.getComponentInParent(e.object,Oo);!t||t!==this||(Oo.lastHovered=e.object,this.context.domElement.style.cursor="pointer")}onPointerExit(e){!this.allowEdit(this.gameObject)||G.IsInWebXR||Oo.lastHovered===e.object&&(this.context.domElement.style.cursor="auto")}_waitingForDragStart=null;onPointerDown(e){!this.allowEdit(this.gameObject)||G.IsInWebXR||(this._dragDelta.set(0,0),this._didDrag=!1,this._waitingForDragStart=e,e.StopPropagation())}onPointerUp(e){this._waitingForDragStart=null,this.allowEdit(this.gameObject)&&(G.IsInWebXR||(this.onDragEnd(e),e.StopPropagation()))}update(){if(!G.IsInWebXR){if(this._waitingForDragStart){if(!this._didDrag){let t=this.context.input.getPointerPositionDelta(0);if(t&&this._dragDelta.add(t),this._dragDelta.length()>2)this._didDrag=!0;else return}let e=this._waitingForDragStart;this._waitingForDragStart=null,this.onDragStart(e)}this._dragHelper&&this._dragHelper.hasSelected&&this.onUpdateDrag(),this._isDragging&&this._dragHelper?.hasSelected===!1&&this.onDragEnd(null)}}_isDragging=!1;_marker=null;_dragDelta;_didDrag=!1;onDragStart(e){if(!this._dragHelper)if(this.context.mainCamera)this._dragHelper=new Xa(this.context.mainCamera);else return;if(!e||!e.object)return;let t=R.getComponentInParent(e.object,Oo);if(!t||t!==this)return;let n=e.object;this.transformSelf&&(n=this.gameObject);let i={selected:n,attached:n};for(let c of this.selectStartEventListener)c(this,i);if(!i.attached)return;i.attached,n=i.attached,this._isDragging=!0,this._dragHelper.setSelected(n,this.context),this.orbit&&(this.orbit.enabled=!1);let r=R.getComponentInChildren(n,Je);ld&&console.log("DRAG START",r,n),r&&(r.fastMode=!0,r?.requestOwnership()),this._marker=R.addNewComponent(n,ft),this._draggingRigidbodies.length=0;let s=R.getComponentsInChildren(n,q);s&&this._draggingRigidbodies.push(...s);let a=Cl();R.invokeOnChildren(this._dragHelper.selected,a("onDragStart"))}onUpdateDrag(){if(!!this._dragHelper){this._dragHelper.onUpdate(this.context);for(let e of this._draggingRigidbodies)e.wakeUp(),e.resetVelocities()}}onDragEnd(e){if(!this||!this._isDragging||(this._isDragging=!1,!this._dragHelper))return;for(let i of this._draggingRigidbodies)i.setVelocity(i.smoothedVelocity);this._draggingRigidbodies.length=0;let t=this._dragHelper.selected;if(ld&&console.log("DRAG END",t,t?.visible),this._dragHelper.setSelected(null,this.context),this.orbit&&(this.orbit.enabled=!0),e?.object){let i=R.getComponentInChildren(e.object,Je);i&&(i.fastMode=!1),this._marker&&this._marker.destroy()}for(let i of this.selectEndEventListener)i(this);let n=Cl();R.invokeOnChildren(t,n("onDragEnd"))}},$t=Oo;j($t,"_active",null),j($t,"lastHovered");var cd=class{get hasSelected(){return this._selected!==null&&this._selected!==void 0}get selected(){return this._selected}_selected=null;_context=null;_camera;_cameraPlane=new Q.Plane;_hasGroundPlane=!1;_groundPlane=new Q.Plane;_groundOffset=new Q.Vector3;_groundOffsetFactor=0;_groundDistance=0;_groundPlanePoint=new Q.Vector3;_raycaster=new Q.Raycaster;_cameraPlaneOffset=new Q.Vector3;_intersection=new Q.Vector3;_worldPosition=new Q.Vector3;_inverseMatrix=new Q.Matrix4;_rbs=[];_groundLine;_groundMarker;constructor(e){this._camera=e;let t=new Q.Line(cd.geometry),n=t.material;n.color=new Q.Color(.4,.4,.4),t.layers.set(2),t.name="line",t.scale.y=1,this._groundLine=t;let i=new Q.SphereGeometry(.5,22,22),r=new Q.MeshBasicMaterial({color:n.color}),s=new Q.Mesh(i,r);s.visible=!1,s.layers.set(2),this._groundMarker=s}setSelected(e,t){if(this._selected&&t)for(let n of this._rbs)n.wakeUp(),n.setVelocity(0,0,0);if(this._selected&&ue.Remove(t,this._selected),this._selected=e,this._context=t,this._rbs.length=0,e?(t.scene.add(this._groundLine),t.scene.add(this._groundMarker)):(this._groundLine.removeFromParent(),this._groundMarker.removeFromParent()),this._selected){if(!t){console.error("DragHelper: no context");return}ue.Add(t,this._selected,null),this._groundOffsetFactor=0,this._hasGroundPlane=!0,this._groundOffset.set(0,0,0),this._requireUpdateGroundPlane=!0,this.onUpdateScreenSpacePlane()}}_groundOffsetVector=new Q.Vector3(0,1,0);_requireUpdateGroundPlane=!0;_didDragOnGroundPlaneLastFrame=!1;onUpdate(e){if(!this._context)return;let t=" ",n="d",i="s",r=this._context?.input.isKeyPressed(t)||this._context?.input.isKeyPressed(n),s=this._context.input.getTouchesPressedCount()>=2||r;if(s){let c=this._context.input.getPointerPositionDelta(0);c&&(this._groundOffsetVector.set(0,1,0),this._selected?.rotateOnWorldAxis(this._groundOffsetVector,c.x*this._context.time.deltaTime))}let a=this._context.input.getPointerPositionRC(0);if(!!a&&(this._raycaster.setFromCamera(a,this._camera),this._selected)){ld&&console.log("UPDATE DRAG",this._selected),this._groundOffsetVector.set(0,1,0);let c=B(this._camera).clone().sub(B(this._selected)).normalize(),d=Math.abs(c.dot(this._groundOffsetVector)),l=this._context?.input.isKeyPressed(t)||this._context?.input.isKeyPressed(n),u=!s&&d>.2&&!l&&this._context.input.getPointerPressedCount()<=1,h=this._didDragOnGroundPlaneLastFrame!==u;if(this._didDragOnGroundPlaneLastFrame=u,this._hasGroundPlane||(this._requireUpdateGroundPlane=!0),(this._requireUpdateGroundPlane||!u||h)&&this.onUpdateGroundPlane(),this._requireUpdateGroundPlane=!1,this._hasGroundPlane)if(this._raycaster.ray.intersectPlane(this._groundPlane,this._intersection)){let b=this._intersection.y;if(this._groundPlanePoint.copy(this._intersection).sub(this._groundOffset),this._groundPlanePoint.y=b,u){this._groundOffsetVector.set(0,1,0);let _=this._intersection.sub(this._groundOffset).add(this._groundOffsetVector.multiplyScalar(this._groundOffsetFactor));this.onUpdateWorldPosition(_,this._groundPlanePoint,!1),this.onDidUpdate();return}}else this._groundPlanePoint.set(0,99999,0);h&&this.onUpdateScreenSpacePlane(),this._requireUpdateGroundPlane=!0,this._raycaster.ray.intersectPlane(this._cameraPlane,this._intersection)&&(this.onUpdateWorldPosition(this._intersection.sub(this._cameraPlaneOffset),this._groundPlanePoint,!0),this.onDidUpdate())}}onUpdateWorldPosition(e,t,n){if(!!this._selected){if(n){let i=B(this._selected);i.y=e.y,e=i}if(J(this._selected,e),J(this._groundLine,e),this._hasGroundPlane?this._groundLine.scale.y=this._groundDistance:this._groundLine.scale.y=1e3,this._groundMarker.visible=t!==null,t){let i=B(this._camera).distanceTo(t)*.01;this._groundMarker.scale.set(i,i,i),J(this._groundMarker,t)}}}onUpdateScreenSpacePlane(){if(!this._selected||!this._context)return;let e=this._context.input.getPointerPositionRC(0);!e||(this._raycaster.setFromCamera(e,this._camera),this._cameraPlane.setFromNormalAndCoplanarPoint(this._camera.getWorldDirection(this._cameraPlane.normal),this._worldPosition.setFromMatrixPosition(this._selected.matrixWorld)),this._raycaster.ray.intersectPlane(this._cameraPlane,this._intersection)&&this._selected.parent&&(this._inverseMatrix.copy(this._selected.parent.matrixWorld).invert(),this._cameraPlaneOffset.copy(this._intersection).sub(this._worldPosition.setFromMatrixPosition(this._selected.matrixWorld))))}onUpdateGroundPlane(){if(!this._selected||!this._context)return;let e=B(this._selected),t=new Q.Ray(new Q.Vector3(0,.1,0).add(e),new Q.Vector3(0,-1,0)),n=new ce;n.ignore=[this._selected];let i=this._context.physics.raycastFromRay(t,n);for(let r=0;r<i.length;r++){let s=i[r];if(!s.face||this.contains(this._selected,s.object))continue;let a=new Q.Vector3(0,1,0);this._groundPlane.setFromNormalAndCoplanarPoint(a,s.point);break}this._hasGroundPlane=!0,this._groundPlane.setFromNormalAndCoplanarPoint(t.direction.multiplyScalar(-1),t.origin),this._raycaster.ray.intersectPlane(this._groundPlane,this._intersection),this._groundDistance=this._intersection.distanceTo(e),this._groundOffset.copy(this._intersection).sub(e)}onDidUpdate(){ne.markDirty(this._selected);for(let e of this._rbs)e.wakeUp(),e.resetForcesAndTorques(),e.setAngularVelocity(0,0,0)}contains(e,t){if(e===t)return!0;if(e.children){for(let n of e.children)if(this.contains(n,t))return!0}return!1}},Xa=cd;j(Xa,"geometry",new Q.BufferGeometry().setFromPoints([new Q.Vector3(0,0,0),new Q.Vector3(0,-1,0)]));var Lt=class extends O{url=null;urlParameterName=null;localhost=null;awake(){this.context.connection.registerProvider(this)}getWebsocketUrl(){let e=this.url?Lt.GetUrl(this.url,this.localhost):null;if(this.urlParameterName){let r=I(this.urlParameterName);r&&typeof r=="string"&&(e=r)}if(!e)return null;let n=new RegExp("(((https?)|(?<socket_prefix>wss?))://)?(www.)?(?<url>.+)","gm").exec(e);return n?.groups?n?.groups.socket_prefix?e:"wss://"+n?.groups.url:null}static GetUrl(e,t){let n=e,i=Lt.IsLocalNetwork()&&t;return i&&(n=t),e?.startsWith("/")&&(n=(i?n:window.location.origin)+e),n}static IsLocalNetwork(e=window.location.hostname){return rr(e)}};var ci=class extends O{filesBackendUrl;localhost;_dragOver;_drop;onEnable(){this.filesBackendUrl=this.filesBackendUrl?Lt.GetUrl(this.filesBackendUrl,this.localhost):void 0,this._dragOver=this.onDrag.bind(this),this._drop=this.onDrop.bind(this),this.context.domElement.addEventListener("dragover",this._dragOver),this.context.domElement.addEventListener("drop",this._drop)}onDisable(){this.context.domElement.removeEventListener("dragover",this._dragOver),this.context.domElement.removeEventListener("drop",this._drop)}onDrag(e){e.preventDefault()}async onDrop(e){if(console.log(e),!e.dataTransfer)return;e.preventDefault();let t=e.dataTransfer.items;if(!!t)for(let n in t){let i=t[n];if(i.kind==="file"){let r=i.getAsFile();if(!r)continue;console.log("Register file "+r.name+" to",this.filesBackendUrl,r);let s=await wh(r,this.context,this.filesBackendUrl);s&&this.addObject(e,s)}else i.kind==="string"&&i.type=="text/plain"&&i.getAsString(async r=>{console.log("dropped url",r);try{let s=new URL(r);if(!s)return;let a=await xh(s,this.context);a&&this.addObject(e,a)}catch{console.log("dropped string is not a valid URL!",r)}})}}async addObject(e,t){console.log("Dropped",t);let n=new ce;n.setMask(16777215),n.screenPointFromOffset(e.offsetX,e.offsetY);let i=this.context.physics.raycast(n),r=t.scene;if(i&&i.length>0)for(let s of i){r.position.copy(s.point);break}this.gameObject.add(r),this.dispatchEvent(new CustomEvent("object-added",{detail:t}))}};x([w()],ci.prototype,"filesBackendUrl",2),x([w()],ci.prototype,"localhost",2);import{Vector3 as Tb,Quaternion as Rb,Object3D as ap}from"three";var en=class extends pt{parent=null;object=null;limitCount=10;limitInterval=60;_currentCount=0;_startPosition=null;_startQuaternion=null;awake(){if(this.object){if(this.object===this.gameObject){console.error("Can not duplicate self");return}this.object.visible=!1,this._startPosition=this.object.position?.clone()??new Tb(0,0,0),this._startQuaternion=this.object.quaternion?.clone()??new Rb(0,0,0,1)}let e=R.getComponentInParent(this.gameObject,$t);e?e.addDragEventListener("selectstart",(t,n)=>{if(this._currentCount>=this.limitCount){n.attached=null;return}let i=this.handleDuplication(n.selected);i&&(console.assert(i!==n.selected,"Duplicated object is original"),n.attached=i)}):console.warn("Could no find drag controls in parent",this.name),Y.addEventListener("select-start",(t,n)=>{if(this._currentCount>=this.limitCount){n.grab=null;return}let i=this.handleDuplication(n.selected);i&&(n.grab=i)}),this.cloneLimitIntervalFn()}cloneLimitIntervalFn(){this.destroyed||(this._currentCount>0&&(this._currentCount-=1),setTimeout(()=>{this.cloneLimitIntervalFn()},this.limitInterval/this.limitCount*1e3))}handleDuplication(e){if(this._currentCount>=this.limitCount||!this.object)return null;if(e===this.gameObject||this.handleMultiObject(e)){if(this.object===this.gameObject)return null;this.object.visible=!0,this._startPosition&&this.object.position.copy(this._startPosition),this._startQuaternion&&this.object.quaternion.copy(this._startQuaternion);let t=new Ie;this.parent||(this.parent=this.gameObject.parent),this.parent&&(t.parent=this.parent.guid??this.parent.userData?.guid,t.keepWorldPosition=!0),t.position=this.worldPosition,t.rotation=this.worldQuaternion,t.context=this.context,this._currentCount+=1;let n=R.instantiateSynced(this.object,t);return console.assert(n!==this.object,"Duplicated object is original"),this.object.visible=!1,this._startPosition&&this.object.position.clone().copy(this._startPosition),this._startQuaternion&&this.object.quaternion.clone().copy(this._startQuaternion),n}return null}handleMultiObject(e){return this.gameObject.type==="Group"||this.gameObject.type==="Object3D"?this.isInChildren(this.gameObject,e):!1}isInChildren(e,t){if(!e)return!1;if(e===t)return!0;if(e.children){for(let n of e.children)if(this.isInChildren(n,t))return!0}return!1}};x([w(ap)],en.prototype,"parent",2),x([w(ap)],en.prototype,"object",2),x([w()],en.prototype,"limitCount",2),x([w()],en.prototype,"limitInterval",2);var Tr=class extends O{};import{FlyControls as Sb}from"three/examples/jsm/controls/FlyControls";var Rr=class extends O{_controls=null;onEnable(){let e=R.getComponent(this.gameObject,se)?.cam;this._controls=new Sb(e,this.context.renderer.domElement),this._controls.rollSpeed=.5,this._controls.movementSpeed=3,this._controls.dragToLook=!0}onDisable(){this._controls?.dispose(),this._controls=null}update(){this._controls&&this._controls.update(this.context.time.deltaTime)}};import*as lp from"three";import{Color as Pb}from"three";var Pn=class extends O{objectBounds=!1;color;isGizmo=!0;_gizmoObject=null;_boxHelper=null;onEnable(){this.isGizmo&&!dn||(this._gizmoObject||(this.objectBounds&&this.gameObject.isMesh===!0?this._gizmoObject=new lp.BoxHelper(this.gameObject,this.color??16776960):(this.objectBounds=!1,this._gizmoObject=ja(this.color??16776960))),this.objectBounds?(this.scene.add(this._gizmoObject),this._boxHelper=this._gizmoObject,this.startCoroutine(this.syncObjectBounds(),3)):this.gameObject.add(this._gizmoObject))}onDisable(){this._gizmoObject&&this.gameObject.remove(this._gizmoObject)}*syncObjectBounds(){for(;this._boxHelper;)this._boxHelper?.update(),yield}};x([w()],Pn.prototype,"objectBounds",2),x([w(Pb)],Pn.prototype,"color",2),x([w()],Pn.prototype,"isGizmo",2);import{GLTFExporter as Ub}from"three/examples/jsm/exporters/GLTFExporter.js";import{BufferAttribute as dd,Matrix4 as Ob,Vector3 as cp,Quaternion as kb}from"three";var ys=class{constructor(e){this.writer=e,this.name="EXT_mesh_gpu_instancing"}writeNode(e,t){if(e.constructor.name!=="InstancedMesh")return;let n=this.writer,i=n.extensionsUsed,r={};t.extensions=t.extensions||{},t.extensions[this.name]=r;let s=new Ob,a=new Array,c=new Array,d=new Array;for(let b=0;b<e.count;b++){e.getMatrixAt(b,s);let _=new cp,v=new kb,y=new cp;s.decompose(_,v,y),a.push(_.x,_.y,_.z),c.push(v.x,v.y,v.z,v.w),d.push(y.x,y.y,y.z)}let l=new Float32Array(a),u=new Float32Array(c),h=new Float32Array(d);r.attributes={TRANSLATION:n.processAccessor(new dd(l,3)),ROTATION:n.processAccessor(new dd(u,4)),SCALE:n.processAccessor(new dd(h,3))},i[this.name]=!0}};import*as In from"three";import*as _s from"three";var On=class{get lightmap(){return this.lightmapTexture}set lightmap(e){e!==this.lightmapTexture&&(this.lightmapTexture=e,this.setupLightmap())}lightmapIndex=-1;lightmapScaleOffset=new _s.Vector4(1,1,0,0);context;gameObject;lightmapTexture=null;lightmapScaleOffsetUniform={value:new _s.Vector4(1,1,0,0)};lightmapUniform={value:null};beforeRenderCallback;constructor(e,t){this.gameObject=e,this.context=t}init(e,t,n,i=!1){if(console.assert(this.gameObject!==void 0&&this.gameObject!==null,"Missing gameobject",this),this.lightmapIndex=e,this.lightmapIndex<0)return;this.lightmapScaleOffset=t,this.lightmapTexture=n,i&&this.setLightmapDebugMaterial(),this.setupLightmap()}bindOnBeforeRender(){this.beforeRenderCallback=this.onBeforeRenderThreeComplete.bind(this),this.context.addBeforeRenderListener(this.gameObject,this.beforeRenderCallback)}onBeforeRenderThreeComplete(e,t,n,i,r,s){this.onBeforeRenderThree(r)}setupLightmap(){if(this.gameObject.type==="Object3D")return;if(this.gameObject.type==="Group"){console.warn("Lightmap on multimaterial object is not supported yet... please ask kindly for implementation.");return}console.assert(this.gameObject.type==="Mesh","Lightmap only works on meshes",this);let e=this.gameObject;e.geometry.getAttribute("uv2")||e.geometry.setAttribute("uv2",e.geometry.getAttribute("uv"));let t=this.gameObject.material.clone();if(this.gameObject.material=t,this.gameObject.material.onBeforeCompile=(n,i)=>{n.uniforms.lightmap=this.lightmapUniform,n.uniforms.lightmapScaleOffset=this.lightmapScaleOffsetUniform},this.lightmapIndex>=0){let n=this.lightmapTexture,i=this.gameObject.material;i&&n&&(i.uniforms||(i.uniforms={}),i.lightMap=n,i.uniforms.lightmap={value:n})}}onBeforeRenderThree(e){let t=e.uniforms;t&&t.lightmap&&(this.lightmapScaleOffsetUniform.value=this.lightmapScaleOffset,this.lightmapUniform.value=this.lightmapTexture,t.lightmap=this.lightmapUniform,t.lightmapScaleOffset=this.lightmapScaleOffsetUniform)}setLightmapDebugMaterial(){this.gameObject.material=new _s.ShaderMaterial({vertexShader:`
177
177
  attribute vec2 uv2;
178
178
  varying vec2 vUv2;
179
179
  void main()