@needle-tools/engine 2.26.1-pre → 2.28.0-pre

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. package/CHANGELOG.md +14 -0
  2. package/dist/needle-engine.d.ts +5 -1
  3. package/dist/needle-engine.js +4 -4
  4. package/dist/needle-engine.js.map +3 -3
  5. package/dist/needle-engine.min.js +4 -4
  6. package/dist/needle-engine.min.js.map +3 -3
  7. package/lib/engine/engine_networking_utils.js +1 -2
  8. package/lib/engine/engine_networking_utils.js.map +1 -1
  9. package/lib/engine/engine_serialization_builtin_serializer.js +15 -4
  10. package/lib/engine/engine_serialization_builtin_serializer.js.map +1 -1
  11. package/lib/engine/engine_setup.d.ts +5 -1
  12. package/lib/engine/engine_setup.js +21 -3
  13. package/lib/engine/engine_setup.js.map +1 -1
  14. package/lib/engine/extensions/NEEDLE_techniques_webgl.js +2 -2
  15. package/lib/engine/extensions/NEEDLE_techniques_webgl.js.map +1 -1
  16. package/lib/engine/extensions/extension_utils.js +6 -6
  17. package/lib/engine/extensions/extension_utils.js.map +1 -1
  18. package/lib/engine-components/AvatarLoader.js +1 -1
  19. package/lib/engine-components/AvatarLoader.js.map +1 -1
  20. package/lib/engine-components/ui/BaseUIComponent.js +8 -5
  21. package/lib/engine-components/ui/BaseUIComponent.js.map +1 -1
  22. package/lib/engine-components/ui/Image.js +4 -0
  23. package/lib/engine-components/ui/Image.js.map +1 -1
  24. package/lib/engine-components/ui/InputField.js +2 -2
  25. package/lib/engine-components/ui/RectTransform.js +1 -1
  26. package/lib/engine-components/ui/RectTransform.js.map +1 -1
  27. package/package.json +1 -1
  28. package/src/engine/engine_networking_utils.ts +1 -2
  29. package/src/engine/engine_serialization_builtin_serializer.ts +15 -3
  30. package/src/engine/engine_setup.ts +19 -3
  31. package/src/engine/extensions/NEEDLE_techniques_webgl.ts +2 -2
  32. package/src/engine/extensions/extension_utils.ts +6 -6
  33. package/src/engine-components/AvatarLoader.ts +1 -1
  34. package/src/engine-components/ui/BaseUIComponent.ts +12 -5
  35. package/src/engine-components/ui/Image.ts +4 -0
  36. package/src/engine-components/ui/InputField.ts +2 -2
  37. package/src/engine-components/ui/RectTransform.ts +1 -1
@@ -120,7 +120,7 @@ a=extmap-allow-mixed`)!==-1){var m=p.sdp.split(`
120
120
  // gl_FragColor = vec4(vUv2.xy, 0, 1);
121
121
  gl_FragColor = lightMapTexel;
122
122
  }
123
- `,defines:{USE_LIGHTMAP:""}})}};var A=function(l){if(l===void 0&&(l=null),!Array.isArray(l))l=ju(l);else for(let e=0;e<l.length;e++){let t=l[e];l[e]=ju(t)}return function(e,t){Object.getOwnPropertyDescriptor(e,"$serializedTypes")||(e.$serializedTypes={});let i=e.$serializedTypes=e.$serializedTypes||{};i[t]=l}};function ju(l){switch(l?.prototype?.constructor?.name){case"Number":case"String":case"Boolean":return null}return l}import{Vector4 as Jb}from"three";import{NeverStencilFunc as Ab,LessStencilFunc as kb,EqualStencilFunc as Ib,LessEqualStencilFunc as Mb,GreaterStencilFunc as Lb,NotEqualStencilFunc as Db,GreaterEqualStencilFunc as Hb,AlwaysStencilFunc as jb,ZeroStencilOp as Bb,KeepStencilOp as Fb,ReplaceStencilOp as Nb,IncrementStencilOp as zb,DecrementStencilOp as Gb,IncrementWrapStencilOp as Vb,DecrementWrapStencilOp as Wb,InvertStencilOp as Ub}from"three";var rc=N("debugstencil");function qb(l,e){return(l&1<<e.layer)!=0}var tr=class{static applyStencil(e){if(!e)return;let t=e.sourceId;if(rc&&console.log(t,tr.stencils),!t)return;let i=tr.stencils[t];if(!!i)for(let n=i.length-1;n>=0;n--){let r=i[n];if(qb(r.layer,e)){rc&&console.log(r);let o=e.material?.clone();o&&(e.material=o,e.gameObject.renderOrder=r.event*1e3+r.index*50,o.stencilWrite=!0,o.stencilWriteMask=255,o.stencilFuncMask=255,o.stencilRef=r.value,o.stencilFunc=r.compareFunc,o.stencilZPass=r.passOp,o.stencilFail=r.failOp,o.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 i=t[Qb];if(i){rc&&console.log(i);let n=i.stencil;if(n&&Array.isArray(n))for(let r of n){let o={...r};o.compareFunc=Xb(o.compareFunc),o.passOp=oc(o.passOp),o.failOp=oc(o.failOp),o.zFailOp=oc(o.zFailOp),tr.stencils[this.source]||(tr.stencils[this.source]=[]),tr.stencils[this.source].push(o)}}}return null}},ir=tr;z(ir,"stencils",{});function oc(l){switch(l){case 0:return Fb;case 1:return Bb;case 2:return Nb;case 3:return zb;case 4:return Gb;case 6:return Vb;case 7:return Wb;case 5:return Ub}return 0}function Xb(l){switch(l){case 1:return Ab;case 2:return kb;case 3:return Ib;case 4:return Mb;case 5:return Lb;case 6:return Db;case 7:return Hb;case 8:return jb}return 0}var Qb="NEEDLE_render_objects";import{TextureLoader as Yb}from"three";import{GLTFLoader as Zb}from"three/examples/jsm/loaders/GLTFLoader";import{DRACOLoader as sc}from"three/examples/jsm/loaders/DRACOLoader.js";import{KTX2Loader as Bu}from"three/examples/jsm/loaders/KTX2Loader.js";var ns=N("debugdecoders"),Ut,bn;function ac(l){l!==void 0&&typeof l=="string"&&(Ut||(Ut=new sc),ns&&console.log("Setting draco decoder path to",l),Ut.setDecoderPath(l))}function lc(l){l!==void 0&&typeof l=="string"&&(Ut||(Ut=new sc),ns&&console.log("Setting draco decoder type to",l),Ut.setDecoderConfig({type:l}))}function cc(l){l!==void 0&&typeof l=="string"&&(bn||(bn=new Bu),ns&&console.log("Setting ktx2 transcoder path to",l),bn.setTranscoderPath(l))}function nr(l,e){Ut||(Ut=new sc,Ut.setDecoderPath("./include/draco/"),Ut.setDecoderConfig({type:"js"}),ns&&console.log("Setting draco decoder path to","./include/draco/")),bn||(bn=new Bu,bn.setTranscoderPath("./include/ktx2/"),ns&&console.log("Setting ktx2 transcoder path to","./include/ktx2/"),e.renderer&&bn.detectSupport(e.renderer)),l.setDRACOLoader(Ut),l.setKTX2Loader(bn)}var dc="NEEDLE_deferred_texture",vn=N("debugdeferredtextures"),rs=class{static assignTextureLOD(e,t,i=0){if(!!t)for(let n of Object.keys(t)){let r=t[n];r?.isTexture===!0&&(vn&&console.log("FIND",n,r?.name,r?.userData,r),rs.getOrLoadTexture(e,t,n,r,i).then(o=>{o?.isTexture===!0&&(o.needsUpdate=!0,t[n]=o,t.needsUpdate=!0)}))}}get name(){return dc}parser;sourceId;context;constructor(e,t,i){this.parser=e,this.sourceId=t,this.context=i}_loading=[];afterRoot(e){return vn&&console.log("AFTER",e),this.parser.json.textures?.forEach((t,i)=>{if(t?.extensions){let n=t?.extensions[dc];if(n){let r=this.parser.getDependency("texture",i);this._loading.splice(this._loading.indexOf(i),1),r.then(o=>{vn&&console.log("register texture",o.name,o.uuid,n),o.userData.deferred=n,rs.cache.set(o.uuid,n)})}}}),null}static async getOrLoadTexture(e,t,i,n,r){let o=n.uuid,s=rs.cache.get(o)||n.userData.deferred;if(s){vn&&console.log(o,s.uri,s.guid);let c=s.uri;if(c.endsWith(".glb")||c.endsWith(".gltf")){if(!s.guid)return console.warn("missing pointer for glb/gltf texture",s),null;let d=s.uri+"_"+s.guid;if(this.resolved[d])return this.resolved[d];let a=new Zb;nr(a,e),vn&&console.log("Load "+c,t.name,i);let h=await a.loadAsync(c),u=h.parser,f=-1,E=!1;for(let y of h.parser.json.textures)if(f++,y?.extensions){let g=y?.extensions[dc];if(g?.guid&&g.guid===s.guid){E=!0;break}}if(!E)return null;let b=await u.getDependency("texture",f);return this.resolved[d]=b,vn&&console.log(t.name,i,'change "'+n.name+'" \u2192 "'+b.name+'"',c,f,b,t),b}else{let a=await new Yb().loadAsync(s.uri);return a&&vn?console.log(s,a):console.warn("failed loading",s.uri),a}}else vn&&console.warn("unknown uuid",n.name,n.uuid,n);return null}},Bi=rs;z(Bi,"cache",new Map),z(Bi,"resolved",{});var Nu=N("noInstancing"),zu=!!N("debuglightmaps"),$b=N("debuginstancing"),Kb=N("debugprogressiveload"),Fr=class{path=null;asset=null;default};var hc=class{_renderer;_targets=[];is(e){return this._renderer===e}constructor(e){this._renderer=e;let t=this.setMaterial.bind(this),i=this.getMaterial.bind(this),n=e.gameObject;if(this._targets=[],n)switch(n.type){case"Group":this._targets=[...n.children];break;case"Mesh":this._targets.push(n);break}return new Proxy(this,{get(r,o){if(typeof o=="string"){let s=parseInt(o);if(!isNaN(s))return i(s)}return r[o]},set(r,o,s){return typeof o=="string"&&t(s,Number.parseInt(o)),Reflect.set(r,o,s)}})}get length(){return this._targets.length}setMaterial(e,t){if(t<0||t>=this._targets.length)return;let i=this._targets[t];!i||(i.material=e)}getMaterial(e){if(e<0)return null;let t=this._targets;if(e>=t.length)return null;let i=t[e];return i?i.material:null}},gc=class extends M{receiveShadows=!1;shadowCastingMode=uc.Off;lightmapIndex=-1;lightmapScaleOffset=new li.Vector4(1,1,0,0);enableInstancing=void 0;renderOrder=void 0;allowOcclusionWhenDynamic=!0;_lightmaps;get material(){return this.gameObject.material}set material(e){this.gameObject.material=e}_sharedMaterials;get sharedMaterials(){return(!this._sharedMaterials||!this._sharedMaterials.is(this))&&(this._sharedMaterials=new hc(this)),this._sharedMaterials}static get shouldSuppressInstancing(){return Nu}_lightmapTextureOverride=void 0;get lightmap(){return this._lightmaps?.length?this._lightmaps[0].lightmap:null}set lightmap(e){if(this._lightmapTextureOverride=e,e===void 0&&(e=this.context.lightmaps.tryGetLightmap(this.sourceId,this.lightmapIndex)),this._lightmaps?.length)for(let t of this._lightmaps)t.lightmap=e}get hasLightmap(){let e=this.lightmap;return e!=null}awake(){let e=this.gameObject.type;if(e==="Group"){for(let t of this.gameObject.children)this.context.addBeforeRenderListener(t,this.onBeforeRenderThree.bind(this)),t.layers.mask=this.gameObject.layers.mask;if(this.renderOrder!==void 0){let t=0;for(let i=0;i<this.gameObject.children.length;i++){let n=this.gameObject.children[i];if(!(n.type!=="Mesh"||S.getComponent(n,gc))){if(this.renderOrder.length<=t){console.error("Incorrect element count",this);break}n.renderOrder=this.renderOrder[t],t+=1}}}}else(e==="Mesh"||e==="SkinnedMesh")&&(this.context.addBeforeRenderListener(this.gameObject,this.onBeforeRenderThree.bind(this)),this.renderOrder!==void 0&&this.renderOrder.length>0&&(this.gameObject.renderOrder=this.renderOrder[0]));if(this.lightmapIndex>=0){let t=this._lightmapTextureOverride!==void 0?this._lightmapTextureOverride:this.context.lightmaps.tryGetLightmap(this.sourceId,this.lightmapIndex);if(t){if(this._lightmaps=[],e==="Mesh"){if(!this.gameObject.material?.isMeshBasicMaterial){let i=new ji(this.gameObject,this.context);this._lightmaps.push(i),i.init(this.lightmapIndex,this.lightmapScaleOffset,t,zu)}}else if(e==="Group"){for(let i of this.gameObject.children)if(!i.material?.isMeshBasicMaterial){let n=new ji(i,this.context);this._lightmaps.push(n),n.init(this.lightmapIndex,this.lightmapScaleOffset,t,zu),n.bindOnBeforeRender()}}}}}_isInstancingEnabled=!1;handles=void 0;prevLayers=void 0;setInstancingEnabled(e){if(this._isInstancingEnabled===e)return e&&(this.handles===void 0||this.handles!=null&&this.handles.length>0);if(this._isInstancingEnabled=e,e){if(this.handles===void 0){if(this.handles=ev.setup(this.gameObject,this.context,null,{rend:this,foundMeshes:0}),this.handles)return S.markAsInstancedRendered(this.gameObject,!0),!0}else if(this.handles!==null){for(let t of this.handles)t.updateInstanceMatrix(!0),t.add();return S.markAsInstancedRendered(this.gameObject,!0),!0}}else{if(this.handles)for(let t of this.handles)t.remove();return!0}return!1}start(){if(this.enableInstancing&&!Nu&&this.setInstancingEnabled(!0),this.gameObject.frustumCulled=this.allowOcclusionWhenDynamic,this.gameObject.type==="Group")for(let e=0;e<this.gameObject.children.length;e++){let t=this.gameObject.children[e];t.frustumCulled=this.allowOcclusionWhenDynamic}}onEnable(){this._isInstancingEnabled?this.setInstancingEnabled(!0):this.enabled&&(this.gameObject.visible=!0,this.applyStencil())}onDisable(){this.handles&&this.handles.length>0?this.setInstancingEnabled(!1):this.enabled||(this.gameObject.visible=!1)}onDestroy(){this.handles=null}applyStencil(){ir.applyStencil(this)}onBeforeRenderThree(e,t,i,n,r,o){if(r._didRequestTextureLOD===void 0&&(r._didRequestTextureLOD=0,Kb?(console.log("Load material LOD (with delay)",r.name),setTimeout(()=>{Bi.assignTextureLOD(this.context,r)},2e3)):Bi.assignTextureLOD(this.context,r)),r.envMapIntensity!==void 0){let s=this.hasLightmap?Math.PI:1;r.envMapIntensity=Math.max(0,this.context.rendererData.environmentIntensity/s)}if(this._lightmaps)for(let s of this._lightmaps)s.onBeforeRenderThree(r)}onBeforeRender(){if(!this.gameObject)return;let e=this.gameObject[pc]===!0||this.gameObject.matrixWorldNeedsUpdate;if(this.gameObject.type==="Group"&&this.gameObject.children?.length>0)for(let t of this.gameObject.children)this.applySettings(t);else this.applySettings(this.gameObject);if(e&&(delete this.gameObject[pc],this.handles)){for(let i=this.handles.length-1;i>=0;i--)this.handles[i].updateInstanceMatrix();this.gameObject.matrixWorldNeedsUpdate=!1}if(this.handles&&this.handles.length<=0&&S.markAsInstancedRendered(this.gameObject,!1),this._isInstancingEnabled&&this.handles)for(let t=0;t<this.handles.length;t++){let i=this.handles[t];this.prevLayers||(this.prevLayers=[]);let n=i.object.layers.mask;t>=this.prevLayers.length?this.prevLayers.push(n):this.prevLayers[t]=n,i.object.layers.disableAll()}}onAfterRender(){if(this._isInstancingEnabled&&this.handles&&this.prevLayers&&this.prevLayers.length>=this.handles.length)for(let e=0;e<this.handles.length;e++){let t=this.handles[e];t.object.layers.mask=this.prevLayers[e]}}applySettings(e){e.receiveShadow=this.receiveShadows,this.shadowCastingMode==uc.On?e.castShadow=!0:e.castShadow=!1}},Te=gc;k([A()],Te.prototype,"receiveShadows",2),k([A()],Te.prototype,"shadowCastingMode",2),k([A()],Te.prototype,"lightmapIndex",2),k([A(Jb)],Te.prototype,"lightmapScaleOffset",2),k([A()],Te.prototype,"enableInstancing",2),k([A()],Te.prototype,"renderOrder",2),k([A()],Te.prototype,"allowOcclusionWhenDynamic",2);var rr=class extends Te{},Nr=class extends rr{awake(){super.awake(),this.allowOcclusionWhenDynamic=!1}},uc=(n=>(n[n.Off=0]="Off",n[n.On=1]="On",n[n.TwoSided=2]="TwoSided",n[n.ShadowsOnly=3]="ShadowsOnly",n))(uc||{}),pc="NEEDLE_NEED_UPDATE_INSTANCE",he=class{static markDirty(e,t=!0){if(!!e&&(S.isUsingInstancing(e)&&(e[pc]=!0,e.matrixWorldNeedsUpdate=!0),t))for(let i of e.children)he.markDirty(i,!0)}},fc=class{objs=[];setup(e,t,i,n,r=0){let o=this.tryCreateOrAddInstance(e,t,n);if(o)return i===null&&(i=[]),i.push(o),i;if(r<=0&&e.type!=="Mesh"){let s=r+1;for(let c of e.children)i=this.setup(c,t,i,n,s)}return i}tryCreateOrAddInstance(e,t,i){if(e.type==="Mesh"){let n=i.foundMeshes;if(i.foundMeshes+=1,!i.rend.enableInstancing||n>=i.rend.enableInstancing.length||!i.rend.enableInstancing[n])return null;let r=e,o=r.geometry,s=r.material;for(let d of this.objs)if(!d.isFull()&&d.geo===o&&d.material===s)return d.addInstance(r);let c=new oa(e.name,o,s,200,t);return this.objs.push(c),c.addInstance(r)}return null}},ev=new fc,mc=class{get name(){return this.object.name}instanceIndex=-1;object;instancer;constructor(e,t,i){this.instanceIndex=e,this.object=t,this.instancer=i,S.markAsInstancedRendered(t,!0)}updateInstanceMatrix(e=!1){this.instanceIndex<0||(this.object.updateWorldMatrix(!0,e),this.instancer.updateInstance(this.object.matrixWorld,this.instanceIndex))}add(){this.instanceIndex>=0||this.instancer.add(this)}remove(){this.instanceIndex<0||this.instancer.remove(this)}},bc=class{name="";geo;material;get currentCount(){return this.inst.count}context;inst;handles=[];maxCount;isFull(){return this.currentCount>=this.maxCount}constructor(e,t,i,n,r){this.name=e,this.geo=t,this.material=i,this.context=r,this.maxCount=n,$b&&(i=new li.MeshBasicMaterial({color:this.randomColor()})),this.inst=new li.InstancedMesh(t,i,n),this.inst.count=0,this.inst.layers.set(2),this.inst.visible=!0,this.context.scene.add(this.inst)}randomColor(){return new li.Color(Math.random(),Math.random(),Math.random())}addInstance(e){if(this.currentCount>=this.maxCount)return console.error("TOO MANY INSTANCES - resize is not yet implemented!",this.inst.count),null;let t=new mc(-1,e,this);return this.add(t),t}add(e){e.instanceIndex<0&&(e.instanceIndex=this.currentCount,e.instanceIndex>=this.handles.length?this.handles.push(e):this.handles[e.instanceIndex]=e),e.object.updateWorldMatrix(!0,!0),this.inst.setMatrixAt(e.instanceIndex,e.object.matrixWorld),this.inst.instanceMatrix.needsUpdate=!0,this.inst.count+=1,this.inst.count>0&&(this.inst.visible=!0)}remove(e){if(!e||e.instanceIndex<0||e.instanceIndex>=this.handles.length||this.inst.count<=0)return;if(this.handles[e.instanceIndex]!==e){console.error("instance handle is not part of renderer, was it removed before?",e.instanceIndex,this.name);let i=this.handles.indexOf(e);if(i<0)return;e.instanceIndex=i}if(this.handles[e.instanceIndex]=null,this.inst.setMatrixAt(e.instanceIndex,bc.nullMatrix),!(e.instanceIndex>=this.currentCount-1)&&this.currentCount>0){let i=this.handles[this.currentCount-1];i&&(i.instanceIndex=e.instanceIndex,i.updateInstanceMatrix(),this.handles[e.instanceIndex]=i,this.handles[this.currentCount-1]=null)}this.inst.count>0&&(this.inst.count-=1),e.instanceIndex=-1,this.inst.count<=0&&(this.inst.visible=!1),this.inst.instanceMatrix.needsUpdate=!0}updateInstance(e,t){this.inst.setMatrixAt(t,e),this.inst.instanceMatrix.needsUpdate=!0}},oa=bc;z(oa,"nullMatrix",new li.Matrix4);var os=N("debugphysics"),tv=N("debugcollisions"),sa=class{mass=1;kinematic=!1;physicsEvents=!1;drag=0;angularDrag=.05;sleepThreshold=.01},ss=class{obj;parent;body;shapes=[];collisonCallback=null;_hasRigidbody=!1;_didSleepLastStep=!1;constructor(e,t){this.obj=e,this.parent=e.parent,this.body=t}},vc=class{obj;contact;target;type;constructor(e,t){this.contact=e,this.type=t,this.obj=null,this.target=null}};var je=class{ray=void 0;screenPoint=void 0;raycaster=void 0;results=void 0;targets=void 0;recursive=!0;minDistance=void 0;maxDistance=void 0;lineThreshold=void 0;layerMask=void 0;ignore=void 0;screenPointFromOffset(e,t){this.screenPoint===void 0&&(this.screenPoint=new ke.Vector2),this.screenPoint.x=e/window.innerWidth*2-1,this.screenPoint.y=-(t/window.innerHeight)*2+1}setMask(e){this.layerMask||(this.layerMask=new ke.Layers);let t=this.layerMask;t?t.mask=e:this.layerMask=e}};z(je,"AllLayers",4294967295);var yc=class{distance;point;object;constructor(e,t,i){this.object=e,this.distance=t,this.point=i}},aa=class{raycaster=new ke.Raycaster;defaultRaycastOptions=new je;targetBuffer=new Array(1);defaultThresholds={Mesh:{},Line:{threshold:0},LOD:{},Points:{threshold:0},Sprite:{}};sphereResults=new Array;sphereMask=new ke.Layers;sphereOverlap(e,t){if(this.sphereResults.length=0,!this.context.scene)return this.sphereResults;let i=new ke.Sphere(e,t),n=this.sphereMask;n.enableAll(),n.disable(2);for(let r of this.context.scene.children){let o=this.onSphereOverlap(r,i,n);o&&this.sphereResults.push(o)}return this.sphereResults.sort((r,o)=>r.distance-o.distance)}tempBoundingBox=new ke.Box3;onSphereOverlap(e,t,i){if(e.type==="Mesh"){if(!e.layers.test(i))return null;let n=e,r=n.geometry;if(r.boundingBox||r.computeBoundingBox(),!r.boundingBox)return null;n.matrixWorldNeedsUpdate&&n.updateMatrixWorld();let o=this.tempBoundingBox.copy(r.boundingBox).applyMatrix4(n.matrixWorld);if(t.intersectsBox(o)){let c=q(e).distanceTo(t.center);return new yc(e,c,t.center.clone())}}else if(e.children)for(let n of e.children){let r=this.onSphereOverlap(n,t,i);if(r)return r}return null}raycastFromRay(e,t=null){let i=t??this.defaultRaycastOptions;return i.ray=e,this.raycast(i)}raycast(e=null){e||(e=this.defaultRaycastOptions);let t=e.screenPoint??this.context.input.mousePositionRC,i=e.raycaster??this.raycaster;if(i.near=e.minDistance??0,i.far=e.maxDistance??1/0,i.params=this.defaultThresholds,e.lineThreshold?i.params.Line={threshold:e.lineThreshold}:i.params.Line={threshold:0},e.ray)i.ray.copy(e.ray);else{let s=this.context.mainCamera;if(!s)return console.error("Can not perform raycast - no main camera found"),this.defaultRaycastOptions.results&&(this.defaultRaycastOptions.results.length=0),this.defaultRaycastOptions.results??[];i.setFromCamera(t,s)}let n=e.targets;n||(n=this.targetBuffer,n[0]=this.context.scene);let r=e.results;r||(this.defaultRaycastOptions.results||(this.defaultRaycastOptions.results=new Array),r=this.defaultRaycastOptions.results),e.layerMask!==void 0?e.layerMask instanceof ke.Layers?i.layers.mask=e.layerMask.mask:i.layers.mask=e.layerMask:(i.layers.enableAll(),i.layers.disable(2)),r.length=0,i.intersectObjects(n,e.recursive,r);let o=e.ignore;return o!==void 0&&o.length>0&&(r=r.filter(s=>!o.includes(s.object))),r}get isUpdating(){return this._isUpdatingPhysicsWorld}_isUpdatingPhysicsWorld=!1;context;world=new ra;objects=[];tempPosition=new ke.Vector3;tempQuaternion=new ke.Quaternion;constructor(e){if(this.context=e,this.world.gravity.set(0,-9.82,0),os){let t={};t.onInit=(i,n,r)=>{n.layers.set(-1)},Hu(e.scene,this.world.bodies,t)}}addPreStepListener(e){this.world.addEventListener("preStep",e)}addPostStepListener(e){this.world.addEventListener("postStep",e)}addConstraint(e){this.world.addConstraint(e)}setGravity(e){this.world.gravity.set(e.x,e.y,e.z)}multiplyGravity(e){this.world.gravity.x*=e.x,this.world.gravity.y*=e.y,this.world.gravity.z*=e.z}addBody(e,t){for(let i=0;i<this.objects.length;i++){let n=this.objects[i];if(n.obj===e){n._hasRigidbody=!0;break}}this.world.addBody(t)}removeBody(e,t,i=!0){this.world.removeBody(t);for(let n=0;n<this.objects.length;n++){let r=this.objects[n];if(r.obj===e){r._hasRigidbody=!1,i&&this.objects.splice(n,1);break}}}removeShape(e,t){for(let i of this.objects)if(i.obj===e){i.body&&(i.body.removeShape(t),i.body.updateMassProperties());return}}createBody(e,t){let i=this.internalCreateBody(e,null);t.mass&&(i.mass=t.mass),t.kinematic?i.type=G.KINEMATIC:i.type=G.DYNAMIC,t.drag&&(i.linearDamping=t.drag),t.angularDrag&&(i.angularDamping=t.angularDrag),t.sleepThreshold&&(i.sleepSpeedLimit=t.sleepThreshold),this.world.addBody(i);let n=new ss(e,i);return n._hasRigidbody=!0,this.objects.push(n),os&&console.log("created new body",e.name,i,i.sleepState,this.world.gravity),t.physicsEvents&&this.registerCollisionEvents(n),i}addBoxCollider(e,t,i,n,r){let o=this.tempPosition;e.getWorldScale(o);let s=new _(.5*o.x*n.x,.5*o.y*n.y,.5*o.z*n.z),c=new Kn(s);c.collisionResponse=!t,i=i.clone(),i.multiply(o);let d=this.addShape(e,c,i,r);if(d!==null){if(this.isAlreadyRegistered(d))return c;let a=new ss(e,d);this.objects.push(a)}return c}addSphereCollider(e,t,i,n){let r=this.tempPosition;e.getWorldScale(r);let o=Math.max(r.x,r.y,r.z),s=new ia(i*o);t=t.clone(),t.multiply(r);let c=this.addShape(e,s,t,n);if(c!==null){if(this.isAlreadyRegistered(c))return s;let d=new ss(e,c);this.objects.push(d)}return s}addMeshCollider(e){os&&console.warn("TODO mesh collider not yet supported")}isAlreadyRegistered(e){for(let t of this.objects)if(t.body===e)return!0;return!1}addShape(e,t,i,n){let r=null;if(n?(n.initialize(),console.assert(!!n.body,"rigidbody didn't initialize / produce a physics body",n),r=n.body):(r=this.internalCreateBody(e,null),r.type=G.KINEMATIC,this.world.addBody(r)),r){i.x*=-1;let o=ve(e),s=q(e);s.add(i);let c=new ke.Quaternion(r.quaternion.x,r.quaternion.y,r.quaternion.z,r.quaternion.w);o.multiply(c.invert());let d=r.position,a=new _(s.x-d.x,s.y-d.y,s.z-d.z),h=new le(o.x,o.y,o.z,o.w);r.addShape(t,a,h),r.updateMassProperties()}return r}step(e){this._isUpdatingPhysicsWorld=!0,e=Math.min(e,1/30),this.world.step(e),this._isUpdatingPhysicsWorld=!1,os&&this.context.time.frameCount%60===0&&console.log("physics world has "+this.world.bodies.length+" bodies",this.world)}temp=new ke.Vector3;tempQuat=new ke.Quaternion;postStep(){this._isUpdatingPhysicsWorld=!0;for(let e=0;e<this.objects.length;e++){let t=this.objects[e],i=t.body;if(!i||!i.world)continue;i.sleepTick(this.context.time.time),os&&(!t._didSleepLastStep&&i.sleepState===G.SLEEPING?console.log("BODY SLEEPING",i):t._didSleepLastStep&&i.sleepState!==G.SLEEPING&&console.log("BODY WOKE UP",i)),t._didSleepLastStep=i.sleepState===G.SLEEPING;let n=t.obj;if(i.type===G.KINEMATIC){let r=q(n,this.temp);i.position.set(r.x,r.y,r.z);let o=ve(n,this.tempQuat);i.quaternion.set(o.x,o.y,o.z,o.w);continue}if(t.parent&&n.parent===t.parent){Rh(n,i.quaternion.x,i.quaternion.y,i.quaternion.z,i.quaternion.w);let r=i.position;Mr(n,r.x,r.y,r.z),i.velocity.length()>i.sleepSpeedLimit&&he.markDirty(n)}}this._isUpdatingPhysicsWorld=!1}internalCreateBody(e,t){let i=new G;i._owner=e,i._name=e.name,e.getWorldPosition(this.tempPosition);let n=this.tempPosition;i.position=new _(n.x,n.y,n.z);let r=this.tempQuaternion;return e.getWorldQuaternion(r),i.quaternion=new le(r.x,r.y,r.z,r.w),i.type=G.KINEMATIC,t&&(i.addShape(t),i.updateMassProperties()),i}registerCollisionEvents(e){if(e.collisonCallback&&this.unregisterCollisionEvents(e),!e.body)return;let t=i=>this.raiseCollisionEvents(e.obj,i);e.collisonCallback=t.bind(this),e.body.addEventListener("collide",e.collisonCallback)}unregisterCollisionEvents(e){!e.collisonCallback||!e.body||e.body.removeEventListener("collide",e.collisonCallback)}raiseCollisionEvents(e,t){let i=new vc(t.contact,t.type),n=0,r=this.objects;function o(){if(!(n>0))for(let s=0;s<r.length;s++){if(n==2)return;let c=r[s];c.body==t.body?(i.obj=c.obj,++n):c.body==t.target&&(i.target=c.obj,++n)}}tv&&console.log("collision between",t.contact.bi,t.contact.bj,e,t);for(let s=0;s<e.userData?.components?.length;s++){let c=e.userData.components[s];c.onCollision&&(o(),c.onCollision(i))}}};import{Clock as iv}from"three";var la=class{deltaTime=0;time=0;frame=0;get realtimeSinceStartup(){return this.clock.elapsedTime}get frameCount(){return this.frame}get smoothedFps(){return this._smoothedFps}clock=new iv;_smoothedFps=0;_fpsSamples=[];_fpsSampleIndex=0;update(){this.deltaTime=this.clock.getDelta(),this.deltaTime=Math.min(.1,this.deltaTime),this.frame+=1,this.time+=this.deltaTime,this._fpsSamples.length<30?this._fpsSamples.push(this.deltaTime):this._fpsSamples[this._fpsSampleIndex++%30]=this.deltaTime;let e=0;for(let t=0;t<this._fpsSamples.length;t++)e+=this._fpsSamples[t];this._smoothedFps=1/(e/this._fpsSamples.length)}};import{WebsocketBuilder as rv}from"websocket-ts";function Gu(l=window.location.hostname){return new RegExp("[0-9]{3}.[0-9]{2,3}.[0-9]{2,3}.[0-9]{2,3}|localhost","gm").test(l)===!0}var pt=class extends M{url=null;urlParameterName=null;localhost=null;getWebsocketUrl(){let e=this.url?pt.GetUrl(this.url,this.localhost):null;if(this.urlParameterName){let r=N(this.urlParameterName);r&&typeof r=="string"&&(e=r)}if(!e)return null;let i=new RegExp("(((https?)|(?<socket_prefix>wss?))://)?(www.)?(?<url>.+)","gm").exec(e);return i?.groups?i?.groups.socket_prefix?e:"wss://"+i?.groups.url:null}static GetUrl(e,t){let i=e,n=pt.IsLocalNetwork()&&t;return n&&(i=t),e?.startsWith("/")&&(i=(n?i:window.location.origin)+e),i}static IsLocalNetwork(e=window.location.hostname){return Gu(e)}};var ci=new Int32Array(2),ca=new Float32Array(ci.buffer),da=new Float64Array(ci.buffer),zr=new Uint16Array(new Uint8Array([1,0]).buffer)[0]===1;var Xe=class{constructor(e,t){this.low=e|0,this.high=t|0}static create(e,t){return e==0&&t==0?Xe.ZERO:new Xe(e,t)}toFloat64(){return(this.low>>>0)+this.high*4294967296}equals(e){return this.low==e.low&&this.high==e.high}};Xe.ZERO=new Xe(0,0);var as;(function(l){l[l.UTF8_BYTES=1]="UTF8_BYTES",l[l.UTF16_STRING=2]="UTF16_STRING"})(as||(as={}));var di=class{constructor(e){this.bytes_=e,this.position_=0}static allocate(e){return new di(new Uint8Array(e))}clear(){this.position_=0}bytes(){return this.bytes_}position(){return this.position_}setPosition(e){this.position_=e}capacity(){return this.bytes_.length}readInt8(e){return this.readUint8(e)<<24>>24}readUint8(e){return this.bytes_[e]}readInt16(e){return this.readUint16(e)<<16>>16}readUint16(e){return this.bytes_[e]|this.bytes_[e+1]<<8}readInt32(e){return this.bytes_[e]|this.bytes_[e+1]<<8|this.bytes_[e+2]<<16|this.bytes_[e+3]<<24}readUint32(e){return this.readInt32(e)>>>0}readInt64(e){return new Xe(this.readInt32(e),this.readInt32(e+4))}readUint64(e){return new Xe(this.readUint32(e),this.readUint32(e+4))}readFloat32(e){return ci[0]=this.readInt32(e),ca[0]}readFloat64(e){return ci[zr?0:1]=this.readInt32(e),ci[zr?1:0]=this.readInt32(e+4),da[0]}writeInt8(e,t){this.bytes_[e]=t}writeUint8(e,t){this.bytes_[e]=t}writeInt16(e,t){this.bytes_[e]=t,this.bytes_[e+1]=t>>8}writeUint16(e,t){this.bytes_[e]=t,this.bytes_[e+1]=t>>8}writeInt32(e,t){this.bytes_[e]=t,this.bytes_[e+1]=t>>8,this.bytes_[e+2]=t>>16,this.bytes_[e+3]=t>>24}writeUint32(e,t){this.bytes_[e]=t,this.bytes_[e+1]=t>>8,this.bytes_[e+2]=t>>16,this.bytes_[e+3]=t>>24}writeInt64(e,t){this.writeInt32(e,t.low),this.writeInt32(e+4,t.high)}writeUint64(e,t){this.writeUint32(e,t.low),this.writeUint32(e+4,t.high)}writeFloat32(e,t){ca[0]=t,this.writeInt32(e,ci[0])}writeFloat64(e,t){da[0]=t,this.writeInt32(e,ci[zr?0:1]),this.writeInt32(e+4,ci[zr?1:0])}getBufferIdentifier(){if(this.bytes_.length<this.position_+4+4)throw new Error("FlatBuffers: ByteBuffer is too short to contain an identifier.");let e="";for(let t=0;t<4;t++)e+=String.fromCharCode(this.readInt8(this.position_+4+t));return e}__offset(e,t){let i=e-this.readInt32(e);return t<this.readInt16(i)?this.readInt16(i+t):0}__union(e,t){return e.bb_pos=t+this.readInt32(t),e.bb=this,e}__string(e,t){e+=this.readInt32(e);let i=this.readInt32(e),n="",r=0;if(e+=4,t===as.UTF8_BYTES)return this.bytes_.subarray(e,e+i);for(;r<i;){let o,s=this.readUint8(e+r++);if(s<192)o=s;else{let c=this.readUint8(e+r++);if(s<224)o=(s&31)<<6|c&63;else{let d=this.readUint8(e+r++);if(s<240)o=(s&15)<<12|(c&63)<<6|d&63;else{let a=this.readUint8(e+r++);o=(s&7)<<18|(c&63)<<12|(d&63)<<6|a&63}}}o<65536?n+=String.fromCharCode(o):(o-=65536,n+=String.fromCharCode((o>>10)+55296,(o&(1<<10)-1)+56320))}return n}__union_with_string(e,t){return typeof e=="string"?this.__string(t):this.__union(e,t)}__indirect(e){return e+this.readInt32(e)}__vector(e){return e+this.readInt32(e)+4}__vector_len(e){return this.readInt32(e+this.readInt32(e))}__has_identifier(e){if(e.length!=4)throw new Error("FlatBuffers: file identifier must be length "+4);for(let t=0;t<4;t++)if(e.charCodeAt(t)!=this.readInt8(this.position()+4+t))return!1;return!0}createLong(e,t){return Xe.create(e,t)}createScalarList(e,t){let i=[];for(let n=0;n<t;++n)e(n)!==null&&i.push(e(n));return i}createObjList(e,t){let i=[];for(let n=0;n<t;++n){let r=e(n);r!==null&&i.push(r.unpack())}return i}};var ft=class{constructor(e){this.minalign=1,this.vtable=null,this.vtable_in_use=0,this.isNested=!1,this.object_start=0,this.vtables=[],this.vector_num_elems=0,this.force_defaults=!1,this.string_maps=null;let t;e?t=e:t=1024,this.bb=di.allocate(t),this.space=t}clear(){this.bb.clear(),this.space=this.bb.capacity(),this.minalign=1,this.vtable=null,this.vtable_in_use=0,this.isNested=!1,this.object_start=0,this.vtables=[],this.vector_num_elems=0,this.force_defaults=!1,this.string_maps=null}forceDefaults(e){this.force_defaults=e}dataBuffer(){return this.bb}asUint8Array(){return this.bb.bytes().subarray(this.bb.position(),this.bb.position()+this.offset())}prep(e,t){e>this.minalign&&(this.minalign=e);let i=~(this.bb.capacity()-this.space+t)+1&e-1;for(;this.space<i+e+t;){let n=this.bb.capacity();this.bb=ft.growByteBuffer(this.bb),this.space+=this.bb.capacity()-n}this.pad(i)}pad(e){for(let t=0;t<e;t++)this.bb.writeInt8(--this.space,0)}writeInt8(e){this.bb.writeInt8(this.space-=1,e)}writeInt16(e){this.bb.writeInt16(this.space-=2,e)}writeInt32(e){this.bb.writeInt32(this.space-=4,e)}writeInt64(e){this.bb.writeInt64(this.space-=8,e)}writeFloat32(e){this.bb.writeFloat32(this.space-=4,e)}writeFloat64(e){this.bb.writeFloat64(this.space-=8,e)}addInt8(e){this.prep(1,0),this.writeInt8(e)}addInt16(e){this.prep(2,0),this.writeInt16(e)}addInt32(e){this.prep(4,0),this.writeInt32(e)}addInt64(e){this.prep(8,0),this.writeInt64(e)}addFloat32(e){this.prep(4,0),this.writeFloat32(e)}addFloat64(e){this.prep(8,0),this.writeFloat64(e)}addFieldInt8(e,t,i){(this.force_defaults||t!=i)&&(this.addInt8(t),this.slot(e))}addFieldInt16(e,t,i){(this.force_defaults||t!=i)&&(this.addInt16(t),this.slot(e))}addFieldInt32(e,t,i){(this.force_defaults||t!=i)&&(this.addInt32(t),this.slot(e))}addFieldInt64(e,t,i){(this.force_defaults||!t.equals(i))&&(this.addInt64(t),this.slot(e))}addFieldFloat32(e,t,i){(this.force_defaults||t!=i)&&(this.addFloat32(t),this.slot(e))}addFieldFloat64(e,t,i){(this.force_defaults||t!=i)&&(this.addFloat64(t),this.slot(e))}addFieldOffset(e,t,i){(this.force_defaults||t!=i)&&(this.addOffset(t),this.slot(e))}addFieldStruct(e,t,i){t!=i&&(this.nested(t),this.slot(e))}nested(e){if(e!=this.offset())throw new Error("FlatBuffers: struct must be serialized inline.")}notNested(){if(this.isNested)throw new Error("FlatBuffers: object serialization must not be nested.")}slot(e){this.vtable!==null&&(this.vtable[e]=this.offset())}offset(){return this.bb.capacity()-this.space}static growByteBuffer(e){let t=e.capacity();if(t&3221225472)throw new Error("FlatBuffers: cannot grow buffer beyond 2 gigabytes.");let i=t<<1,n=di.allocate(i);return n.setPosition(i-t),n.bytes().set(e.bytes(),i-t),n}addOffset(e){this.prep(4,0),this.writeInt32(this.offset()-e+4)}startObject(e){this.notNested(),this.vtable==null&&(this.vtable=[]),this.vtable_in_use=e;for(let t=0;t<e;t++)this.vtable[t]=0;this.isNested=!0,this.object_start=this.offset()}endObject(){if(this.vtable==null||!this.isNested)throw new Error("FlatBuffers: endObject called without startObject");this.addInt32(0);let e=this.offset(),t=this.vtable_in_use-1;for(;t>=0&&this.vtable[t]==0;t--);let i=t+1;for(;t>=0;t--)this.addInt16(this.vtable[t]!=0?e-this.vtable[t]:0);let n=2;this.addInt16(e-this.object_start);let r=(i+n)*2;this.addInt16(r);let o=0,s=this.space;e:for(t=0;t<this.vtables.length;t++){let c=this.bb.capacity()-this.vtables[t];if(r==this.bb.readInt16(c)){for(let d=2;d<r;d+=2)if(this.bb.readInt16(s+d)!=this.bb.readInt16(c+d))continue e;o=this.vtables[t];break}}return o?(this.space=this.bb.capacity()-e,this.bb.writeInt32(this.space,o-e)):(this.vtables.push(this.offset()),this.bb.writeInt32(this.bb.capacity()-e,this.offset()-e)),this.isNested=!1,e}finish(e,t,i){let n=i?4:0;if(t){let r=t;if(this.prep(this.minalign,4+4+n),r.length!=4)throw new Error("FlatBuffers: file identifier must be length "+4);for(let o=4-1;o>=0;o--)this.writeInt8(r.charCodeAt(o))}this.prep(this.minalign,4+n),this.addOffset(e),n&&this.addInt32(this.bb.capacity()-this.space),this.bb.setPosition(this.space)}finishSizePrefixed(e,t){this.finish(e,t,!0)}requiredField(e,t){let i=this.bb.capacity()-e,n=i-this.bb.readInt32(i);if(!(this.bb.readInt16(n+t)!=0))throw new Error("FlatBuffers: field "+t+" must be set")}startVector(e,t,i){this.notNested(),this.vector_num_elems=t,this.prep(4,e*t),this.prep(i,e*t)}endVector(){return this.writeInt32(this.vector_num_elems),this.offset()}createSharedString(e){if(!e)return 0;if(this.string_maps||(this.string_maps=new Map),this.string_maps.has(e))return this.string_maps.get(e);let t=this.createString(e);return this.string_maps.set(e,t),t}createString(e){if(!e)return 0;let t;if(e instanceof Uint8Array)t=e;else{t=[];let i=0;for(;i<e.length;){let n,r=e.charCodeAt(i++);if(r<55296||r>=56320)n=r;else{let o=e.charCodeAt(i++);n=(r<<10)+o+(65536-(55296<<10)-56320)}n<128?t.push(n):(n<2048?t.push(n>>6&31|192):(n<65536?t.push(n>>12&15|224):t.push(n>>18&7|240,n>>12&63|128),t.push(n>>6&63|128)),t.push(n&63|128))}}this.addInt8(0),this.startVector(1,t.length,1),this.bb.setPosition(this.space-=t.length);for(let i=0,n=this.space,r=this.bb.bytes();i<t.length;i++)r[n++]=t[i];return this.endVector()}createLong(e,t){return Xe.create(e,t)}createObjectOffset(e){return e===null?0:typeof e=="string"?this.createString(e):e.pack(this)}createObjectOffsetList(e){let t=[];for(let i=0;i<e.length;++i){let n=e[i];if(n!==null)t.push(this.createObjectOffset(n));else throw new Error("FlatBuffers: Argument for createObjectOffsetList cannot contain null.")}return t}createStructOffsetList(e,t){return t(this,e.length),this.createObjectOffsetList(e),this.endVector()}};var Vu={};function Vr(l,e){Vu[l]=e}function Wu(l){let e=l.getBufferIdentifier(),t=Vu[e];return t(l)}function Uu(l){return typeof l.guid=="function"?l.guid():null}var _c=vl(wc(),1);var ua=class{get isHost(){return this._host!==void 0}_host;_client;_clientData;constructor(){this.onEnable()}onEnable(){let e="HOST-5980e65c-8438-453e-8b35-f13c736dcd81";this.trySetupHost(e)}trySetupHost(e){let t=new _c.default(e);t.on("error",i=>{console.error(i),this._host=void 0,this.trySetupClient(e)}),t.on("open",i=>{this._host=new Tc(t)})}trySetupClient(e){this._client=new _c.default,this._client.on("error",t=>{console.error("Client error",t)}),this._client.on("open",t=>{console.log("client connected",t),this._clientData=this._client.connect(e,{metadata:{id:t}}),this._clientData.on("open",()=>{console.log("Connected to host")}),this._clientData.on("data",i=>{console.log("<<",i)})})}},xc=class{_peer;constructor(e){this._peer=e}};var Tc=class extends xc{get isHost(){return!0}_connections=[];constructor(e){super(e),console.log("I AM THE HOST"),this._peer?.on("connection",this.onConnection.bind(this)),this._peer.on("close",()=>{this.broadcast("BYE")}),setInterval(()=>{this.broadcast("HELLO")},2e3)}onConnection(e){console.log("host connection",e),e.on("open",()=>{this._connections.push(e),this.broadcastConnection(e)})}broadcastConnection(e){let t=this._connections.map(i=>i.metadata?.id).filter(i=>i!==void 0);this.broadcast({type:"connection-list",connections:t})}broadcast(e){if(e!=null){console.log(">>",e);for(let t in this._peer.connections){let i=this._peer.connections[t];if(!!i)if(Array.isArray(i))for(let n of i)!n||n.send(e);else console.warn(i)}}}};var Rc="wss://needle-tiny-starter.glitch.me/socket",mt=!!N("debugnet"),pa=!!(mt||N("debugowner"));var En=class{guid;connection;get hasOwnership(){return this._hasOwnership}get isOwned(){return this._isOwned}get isConnected(){return this.connection.isConnected}_hasOwnership=!1;_isOwned=void 0;_gainSubscription;_lostSubscription;_hasOwnerResponse;constructor(e,t){this.connection=e,this.guid=t,this._gainSubscription=this.onGainedOwnership.bind(this),this._lostSubscription=this.onLostOwnership.bind(this),e.beginListen("lost-ownership",this._lostSubscription),e.beginListen("gained-ownership-broadcast",this._gainSubscription),this._hasOwnerResponse=this.onHasOwnerResponse.bind(this),e.beginListen("response-has-owner",this._hasOwnerResponse)}_isWaitingForOwnershipResponseCallback=null;updateIsOwned(){this.connection.send("request-has-owner",{guid:this.guid})}onHasOwnerResponse(e){e.guid===this.guid&&(this._isOwned=e.value)}requestOwnershipIfNotOwned(){return this._isWaitingForOwnershipResponseCallback!==null?this:(this._isWaitingForOwnershipResponseCallback=this.waitForHasOwnershipRequestResponse.bind(this),this.connection.beginListen("response-has-owner",this._isWaitingForOwnershipResponseCallback),this.connection.send("request-has-owner",{guid:this.guid}),this)}waitForHasOwnershipRequestResponse(e){e.guid===this.guid&&(this._isWaitingForOwnershipResponseCallback&&(this.connection.stopListening("response-has-owner",this._isWaitingForOwnershipResponseCallback),this._isWaitingForOwnershipResponseCallback=null),this._isOwned=e.value,e.value||(pa&&console.log("request ownership",this.guid),this.requestOwnership()))}requestOwnershipAsync(){return new Promise((e,t)=>{this.requestOwnership();let i=0,n=()=>{if(i++>10)return t("Timeout");setTimeout(()=>{this.hasOwnership?e(this):n()},100)};n()})}requestOwnership(){return pa&&console.log("Request ownership",this.guid),this.connection.send("request-ownership",{guid:this.guid}),this}freeOwnership(){return this.connection.send("remove-ownership",{guid:this.guid}),this._isWaitingForOwnershipResponseCallback&&(this.connection.stopListening("response-has-owner",this._isWaitingForOwnershipResponseCallback),this._isWaitingForOwnershipResponseCallback=null),this}destroy(){this.connection.stopListening("gained-ownership",this._gainSubscription),this.connection.stopListening("lost-ownership",this._lostSubscription),this.connection.stopListening("response-has-owner",this._hasOwnerResponse),this._isWaitingForOwnershipResponseCallback&&(this.connection.stopListening("response-has-owner",this._isWaitingForOwnershipResponseCallback),this._isWaitingForOwnershipResponseCallback=null)}onGainedOwnership(e){e.guid===this.guid&&(this._isOwned=!0,this.connection.connectionId===e.owner?(pa&&console.log("GAINED OWNERSHIP",this.guid),this._hasOwnership=!0):this._hasOwnership=!1)}onLostOwnership(e){e===this.guid&&(pa&&console.log("LOST OWNERSHIP",this.guid),this._hasOwnership=!1,this._isOwned=!1)}};var fa=class{context;_peer=null;constructor(e){this.context=e}get peer(){return this._peer||(this._peer=new ua),this._peer}tryGetState(e){return e==="invalid"?null:this._state[e]}get connectionId(){return this._connectionId}get isDebugEnabled(){return mt}get isConnected(){return this.connected}get currentRoomName(){return this._currentRoomName}get allowEditing(){return this._currentRoomAllowEditing}get currentRoomViewId(){return this._currentRoomViewId}get isInRoom(){return this._isInRoom}get currentLatency(){return this._currentDelay}userIsInRoom(e){return this._currentInRoom.indexOf(e)!==-1}_usersInRoomCopy=[];usersInRoom(e=null){e||(e=this._usersInRoomCopy),e.length=0;for(let t of this._currentInRoom)e.push(t);return e}joinRoom(e,t=!1){this.connect(),mt&&console.log("join: "+e),this.send("join-room",{room:e,viewOnly:t},0)}leaveRoom(e=null){if(e||(e=this.currentRoomName),!e){console.error("Can not leave unknown room");return}this.send("leave-room",{room:e})}send(e,t=null,i=2){if(t===null&&(t={}),i===2){this._defaultMessagesBuffer.push({key:e,value:t});return}return this.sendWithWebsocket(e,t,i)}sendDeleteRemoteState(e){this.send("delete-state",{guid:e,dontSave:!0}),delete this._state[e]}sendBinary(e){mt&&console.log("<< bin",e.length),this._ws?.send(e)}_defaultMessagesBuffer=[];_defaultMessagesBufferArray=[];sendBufferedMessagesNow(){if(!this._ws)return;this._defaultMessagesBufferArray.length=0;let e=Object.keys(this._defaultMessagesBuffer).length;for(let i in this._defaultMessagesBuffer){let n=this._defaultMessagesBuffer[i];if(e<=1){this.sendWithWebsocket(n.key,n.value,3);break}let r=this.toMessage(n.key,n.value);this._defaultMessagesBufferArray.push(r)}if(this._defaultMessagesBuffer.length=0,this._defaultMessagesBufferArray.length>0&&mt&&console.log("SEND BUFFERED",this._defaultMessagesBufferArray.length),this._defaultMessagesBufferArray.length<=0)return;let t=JSON.stringify(this._defaultMessagesBufferArray);this._ws?.send(t)}beginListen(e,t){return this._listeners[e]||(this._listeners[e]=[]),this._listeners[e].push(t),t}stopListening(e,t){if(!t||!this._listeners[e])return;let i=this._listeners[e].indexOf(t);i>=0&&this._listeners[e].splice(i,1)}beginListenBinrary(e,t){return this._listenersBinary[e]||(this._listenersBinary[e]=[]),this._listenersBinary[e].push(t),t}stopListenBinary(e,t){if(!this._listenersBinary[e])return;let i=this._listenersBinary[e].indexOf(t);i>=0&&this._listenersBinary[e].splice(i,1)}connect(){if(this.connected)return;mt&&console.log("connecting");let t=S.findObjectOfType(pt,this.context,!1)?.getWebsocketUrl();t&&(Rc=t),this.connectWebsocket()}_listeners={};_listenersBinary={};connected=!1;channelId;_connectionId=null;_isConnectingToWebsocket=!1;_ws;_waitingForSocket={};_isInRoom=!1;_currentRoomName=null;_currentRoomViewId=null;_currentRoomAllowEditing=!0;_currentInRoom=[];_state={};_currentDelay=-1;connectWebsocket(){if(this._isConnectingToWebsocket)return;this._isConnectingToWebsocket=!0,console.log("Connecting to "+Rc);let e=new rv(Rc).onOpen(()=>{this._ws=e,this._isConnectingToWebsocket=!1,this.connected=!0,console.log("Connected to websocket"),this.onSendQueued(0)}).onClose(t=>{this.connected=!1,this._isInRoom=!1}).onError((t,i)=>{console.error(t,i)}).onMessage(this.onMessage.bind(this)).onRetry(()=>{console.log("websocket connection retry")}).build()}onMessage(e,t){let i=t.data;try{if(typeof i!="string"){i.size&&this.handleIncomingBinaryMessage(i);return}let n=JSON.parse(i);if(Array.isArray(n))for(let r of n)this.handleIncomingStringMessage(r);else this.handleIncomingStringMessage(n);return}catch{mt&&i==="pong"&&console.log("<<",i)}}async handleIncomingBinaryMessage(e){let t=await e.arrayBuffer();var i=new Uint8Array(t);let n=new di(i),r=n.getBufferIdentifier(),o=this._listenersBinary[r],s=Wu(n),c=Uu(s);if(c&&typeof c=="string"&&(this._state[c]=s),!o)return;let d=s??n;for(let a of o)a(d)}handleIncomingStringMessage(e){if(mt&&console.log("<<",e.key??e),e.key)switch(e.key){case"connection-start-info":if(e.data){let o=e.data;o&&(console.assert(o.id!==void 0&&o.id!==null&&o.id.length>0,"server did not send connection id",o.id),console.log("Your id is: "+o.id,this.context.alias??""),this._connectionId=o.id)}else console.warn("Expected connection id in "+e.key);break;case"joined-room":if(mt&&console.log(e),e){this._isInRoom=!0;let o=e;this._currentRoomName=o.room,this._currentRoomViewId=o.viewId,this._currentRoomAllowEditing=o.allowEditing??!0,console.log("Room view id",this._currentRoomViewId),this._currentInRoom.length=0,this._currentInRoom.push(...o.inRoom),mt&&console.log("joined room with",this._currentInRoom,this.context.alias??"")}this.onSendQueued(1);break;case"left-room":e.room===this.currentRoomName&&(this._isInRoom=!1,this._currentRoomName=null,this._currentInRoom.length=0);break;case"user-joined-room":if(e.data){let o=e.data;this._currentInRoom.push(o.userId),mt&&console.log(o.userId+" joined","now in room:",this._currentInRoom)}break;case"user-left-room":if(e.data){let o=e.data,s=this._currentInRoom.indexOf(o.userId);s>=0&&(console.log(o.userId+" left",this.context.alias??""),this._currentInRoom.splice(s,1)),o.userId===this.connectionId&&console.log("you left the room")}break;case"ping":case"pong":let r=e.data?.time;r&&(this._currentDelay=this.context.time.time-r),mt&&console.log("Current latency: "+this._currentDelay.toFixed(1)+" sec","Clients in room: "+this._currentInRoom?.length);break}let t=this._listeners[e.key];if(t)for(let n of t)n(e.data);let i=e.data;i&&(this._state[i.guid]=i)}toMessage(e,t){return{key:e,data:t}}sendWithWebsocket(e,t,i=1){if(!this._ws){let r=this._waitingForSocket[i]||[];r.push(()=>this.sendWithWebsocket(e,t,i)),this._waitingForSocket[i]=r;return}let n=JSON.stringify(this.toMessage(e,t));mt&&console.log(">>",e),this._ws.send(n)}onSendQueued(e){let t=this._waitingForSocket[e];if(t){for(let i of t)i();t.length=0}}};import*as Xt from"three";import{OrbitControls as sv}from"three/examples/jsm/controls/OrbitControls";import{Object3D as ov}from"three";var Fi=class extends M{constraintActive=!0;locked=!1;sources=[]};k([A(ov)],Fi.prototype,"sources",2);import*as ls from"three";var gt=class extends M{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;awake(){this._lookTargetPosition=new ls.Vector3}onEnable(){this._enableTime=this.context.time.time;let t=S.getComponent(this.gameObject,ne)?.cam;this._controls||(console.assert(t!=null,"Missing camera",this),t&&(this._cameraObject=t),this._controls=new sv(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"?(this._controls.minDistance=this.minZoom,this._controls.maxDistance=this.maxZoom):(this._controls.minZoom=this.minZoom,this._controls.maxZoom=this.maxZoom),this._controls.dampingFactor=this.dampingFactor,this._controls.enablePan=this.enablePan)}onDisable(){this._controls&&(this._controls.enabled=!1,this._controls.autoRotate=!1)}start(){if(this._controls){let e=S.getComponent(this.gameObject,ne);if(e&&!this.setFromTargetPosition()){console.log("NO TARGET");let t=new ls.Vector3(0,0,-1).applyMatrix4(e.cam.matrixWorld);this.setTarget(t,!0)}}this.startCoroutine(this.startRaycastDelayed())}*startRaycastDelayed(){if(yield,!this.setFromTargetPosition()){let e=new je;e.screenPoint=new ls.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.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 i=this.lookAtConstraint?.sources;if(i&&i.length>0){let n=i[e];if(n)return n.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&&S.isActiveInHierarchy(t.object)){if(this._lookTargetPosition.copy(t.point),this._lerpToTargetPosition=!0,this._cameraTargetPosition=null,this.context.mainCamera){this._lerpCameraToTarget=!0;let i=q(this.context.mainCamera);this._cameraTargetPosition=i.clone().sub(this.controls.target).add(this._lookTargetPosition)}break}}};k([A(Fi)],gt.prototype,"lookAtConstraint",2);import{Color as av}from"three";var we=class extends av{alpha=1;get isRGBAColor(){return!0}constructor(e,t,i,n){super(e,t,i),this.alpha=n}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 i=e;return i.alpha&&(this.alpha=Q.lerp(this.alpha,i.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 lv}from"three";var Xu=N("debugcam"),ne=class extends M{get aspect(){return this._cam instanceof lv?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 Xt.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(){Xu&&console.log(this),this.buildCamera(),this.tag=="MainCamera"&&this.context.setCurrentCamera(this),this.applyClearFlagsIfIsActiveCamera()}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 Xt.PerspectiveCamera(this.fieldOfView,window.innerWidth/window.innerHeight,this._nearClipPlane,this._farClipPlane),t.fov=this.fieldOfView;else{let i=this.orthographicSize*100;t=new Xt.OrthographicCamera(window.innerWidth/-i,window.innerWidth/i,window.innerHeight/i,window.innerHeight/-i,this._nearClipPlane,this._farClipPlane)}this._cam=t,this.layer===0&&this._cam.layers.enableAll(),this.tag=="MainCamera"&&this.context.setCurrentCamera(this)}applyClearFlagsIfIsActiveCamera(){if(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;return t==="additive"||t==="alpha-blend"}enableSkybox(){this._skybox||(this._skybox=new Cc(this)),this._skybox.enable()}};k([A()],ne.prototype,"fieldOfView",1),k([A()],ne.prototype,"nearClipPlane",1),k([A()],ne.prototype,"farClipPlane",1),k([A()],ne.prototype,"clearFlags",1),k([A()],ne.prototype,"orthographic",2),k([A()],ne.prototype,"orthographicSize",2),k([A()],ne.prototype,"ARBackgroundAlpha",2),k([A(we)],ne.prototype,"backgroundColor",1);var Cc=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?(Xu&&console.log("Set skybox",this._camera,this._skybox),this._skybox.encoding=Xt.sRGBEncoding,this._skybox.mapping=Xt.EquirectangularReflectionMapping,this.context.scene.background=this._skybox):console.warn("Failed to load/find skybox texture",this)}};function Qu(l){let e="created/implictly",t=new Xt.Object3D;l.add(t);let i=S.addNewComponent(t,ne,!1);i.sourceId=e;let n=S.addNewComponent(t,gt,!1);return n.sourceId=e,i}import{EffectComposer as OE}from"three/examples/jsm/postprocessing/EffectComposer.js";import{RenderPass as AE}from"three/examples/jsm/postprocessing/RenderPass";import{AnimationClip as cv,MathUtils as dv}from"three";var Wr=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,i,n){this._name=e.name,this._nameHash=e.hash,this._normalizedTime=t,this._length=i,this._speed=n}};function Yu(l,e){return{name:"",isLooping:!1,guid:e?.generateUUID()??dv.generateUUID(),index:-1,clip:new cv(l,1,[])}}import{AnimationClip as gv,AnimationMixer as bv,AxesHelper as vv,Euler as Ku,LoopOnce as yv,Quaternion as Qt,Vector3 as hs}from"three";import*as wa from"three";var Sc=class{_types={};add(e,t){let i=this._types[e];i===void 0?this._types[e]=t:i!==t&&console.warn("Type name exists multiple times in your project and may lead to runtime errors:",e)}get(e){return this._types[e]}},D=new Sc;var hi=N("gizmos"),Ie=N("debugextension");var ga=N("debugresolvedependencies"),hv=[{prefix:"nodes/",dependencyName:"node"},{prefix:"meshes/",dependencyName:"mesh"},{prefix:"materials/",dependencyName:"material"},{prefix:"textures/",dependencyName:"texture"},{prefix:"animations/",dependencyName:"animation"}];async function Ur(l,e){ga&&console.log(l,e);let t=[];Oc(hv,l,e,t);let i=await Promise.all(t);return typeof e=="string"&&i.length===1?i[0]:i}function Oc(l,e,t,i){if(typeof t=="object"&&t!==void 0&&t!==null)for(let n of Object.keys(t)){let r=t[n];if(typeof r=="string"){let o=Zu(e,r);if(o!==null)typeof o.then=="function"?i.push(o.then(s=>t[n]=s)):t[n]=o;else for(let s of l){let c=Ac(s.prefix,r);if(c>=0){ga&&console.log(s,c,s.dependencyName),i.push(e?.getDependency(s.dependencyName,c).then(d=>(t[n]=d,d)));break}}}else if(Array.isArray(r))for(let o=0;o<r.length;o++){let s=r[o],c=Zu(e,s);if(c!==null){typeof c.then=="function"?i.push(c.then(d=>r[o]=d)):r[o]=c;continue}for(let d of l){let a=Ac(d.prefix,s);if(a>=0){ga&&console.log(d,a,d.dependencyName),i.push(e?.getDependency(d.dependencyName,a).then(h=>r[o]=h));break}}typeof s=="object"&&Oc(l,e,s,i)}else typeof r=="object"&&Oc(l,e,r,i)}else typeof t=="string"&&uv(l,e,t,i)}var Pc="extensions/";function Zu(l,e){if(l&&l.plugins&&typeof e=="string"&&e.startsWith(Pc)){let t=e.substring(Pc.length),i=t.indexOf("/");i>=0&&(t=t.substring(0,i));let n=l.plugins[t];if(Ie&&console.log(t,n),typeof n?.resolve=="function"){let r=e.substring(Pc.length+t.length+1);return n.resolve(l,r)}}return null}function uv(l,e,t,i){for(let n of l){let r=Ac(n.prefix,t);if(r>=0)return ga&&console.log(n,r,n.dependencyName),i.push(e?.getDependency(n.dependencyName,r).then(o=>o)),!0}return!1}function Ac(l,e){if(typeof e=="string"&&e.startsWith(l)){let t=e.substring(l.length),i=Number.parseInt(t);if(i>=0)return i}return-1}var kc="NEEDLE_persistent_assets";function Ju(l){return l?.___persistentAsset===!0}var ba=class{get name(){return kc}parser;constructor(e){this.parser=e}async afterRoot(e){if(!this.parser?.json?.extensions)return;let t=this.parser.json.extensions[kc];if(!t)return;Ie&&console.log(t);let i=new Array;for(let n of t?.assets){let r=Ur(this.parser,n);r&&i.push(r)}await Promise.all(i)}resolve(e,t){let i=Number.parseInt(t);if(i>=0){Ie&&console.log(t);let n=e.json.extensions[kc];if(n){let r=n?.assets[i];if(r&&typeof r=="object"){r.___persistentAsset=!0;let o=r.__type;if(o){let s=D.get(o)}}return r}}return null}};var or=N("debugserializer"),Ic=class{register(e,t){if(this.typeMap[e]!==void 0){if(this.typeMap[e]===t)return;console.warn("Type "+e+" is already registered",t,this.typeMap[e])}or&&console.log("Register type serializer for "+e,t),this.typeMap[e]=t}typeMap={};getSerializer(e){if(!!e)return this.typeMap[e]}getSerializerForConstructor(e,t=0){if(t>20)return;if(!e||!e.constructor){or&&console.log("invalid type");return}let i=e.name??e.constructor?.name;if(!i){or&&console.log("invalid name",i);return}let n=this.getSerializer(i);if(n!==void 0)return or&&console.log("FOUND "+i,e.name,e.constructor.name,n,this.typeMap),n;let r=Object.getPrototypeOf(e);if(!(r.prototype||r.constructor)){or&&console.warn("No prototype for "+i,e,e.name,e.prototype,e.constructor.name);return}let s=r.prototype??r.constructor;if(s!==e){let c=this.getSerializerForConstructor(s,++t);if(c){or&&console.log("FOUND "+s.constructor.name,s.name,s,c);let d=s.name??s.constructor.name;d==="Function"?console.error("Registering Function is not allowed, something went wrong",e,s,c):this.register(d,c)}return c}}},ya=new Ic,Ni=class{constructor(e){if(Array.isArray(e))for(let t of e)ya.register(t.name,this);else ya.register(e.name,this)}},qr=class{root;gltf;gltfId;object;target;nodeId;nodeToObject;objectToNode;context;path;constructor(e){this.root=e}};function Lc(l,e){let t=l.$serializedTypes;if(t===void 0)return null;let i={};for(let n in t){let r=l[n];if(r!=null&&typeof r=="object"){let o=ya.getSerializerForConstructor(r);if(o){i[n]=o.onSerialize(r,e);continue}}i[n]=r}return i.name=l.constructor.name,typeof l.guid=="string"&&(i.guid=l.guid),i}var va=[];function $u(l,e){if(!l)return e;typeof l.$serializedTypes=="object"&&(e||(e={}),Object.assign(e,l.$serializedTypes));let t=Object.getPrototypeOf(l);return $u(t,e)}function cs(l,e,t){if(!l)return!1;if(t.target=l,l.onBeforeDeserialize!==void 0){let r=l.onBeforeDeserialize(e,t);if(typeof r=="boolean")return r}let i=$u(l);if(e){if(typeof e.guid=="string"&&(l.guid=e.guid),i)for(let r in i){let o=i[r],s=e[r];if(t.path=r,o===null)l[r]=s;else{let c=function(d){let h=d.type;return h?Mc(s,h,t,void 0,l[r]):Mc(s,d,t,void 0,l[r])};var n=c;if(l.onBeforeDeserializeMember!==void 0&&l.onBeforeDeserializeMember(r,s,t)===!0)continue;if(Array.isArray(o))for(let d=0;d<o.length;d++){let a=o[d],h=c(a);if(h!==void 0||d===o.length-1){l[r]=h;break}}else l[r]=c(o);va.length=0,l.onAfterDeserializeMember!==void 0&&l.onAfterDeserializeMember(r,s,t)}}pv(l,e)}return l.onAfterDeserialize!==void 0&&l.onAfterDeserialize(e,t),t.path=void 0,!0}function pv(l,e){for(let i of Object.keys(e)){let n=e[i];if(typeof n=="object"&&n!==null&&n!==void 0){let r=l[i];if(!r){or&&console.log(i,"is undefined on",l);continue}for(let o of Object.keys(n))r[o]===void 0&&t(n[o])&&!t(r)&&(r[o]=n[o])}}function t(i){switch(typeof i){case"number":case"string":case"boolean":return!0}return!1}}function Mc(l,e,t,i,n){let r=typeof e=="function"&&e.prototype===void 0,o=e;if(r)try{if(o=e?.call(e,n),r=!1,o==null)return}catch(a){console.error("Error in callback",a,l)}if(!r&&n instanceof o)return n;if(n&&typeof n=="object"&&Ju(n)){if(n.__concreteInstance)return n.__concreteInstance;let a=n;if(!a.$serializedTypes&&o.prototype.$serializedTypes&&(a.$serializedTypes=o.prototype.$serializedTypes),a.$serializedTypes&&cs(a,l,t),n&&o!==void 0)try{let h=new o;Ie&&console.log("Create concrete instance for persistent asset",n,"instance:",h),ds(h,n),n.__concreteInstance=h,n=h}catch(h){console.error("Error creating instance or creating values on instance",h,n,o)}return n}if(i||(i={serializer:ya.getSerializerForConstructor(o)}),Array.isArray(l)){let a=[];for(let h=0;h<l.length;h++){let u=l[h],f=Mc(u,e,t,i,u);a.push(f)}return a}let s=i.serializer;if(s)return s.onDeserialize(l,t);let c;l&&(l.isMaterial||l.isTexture||l.isObject3D)?c=l:c=new o(...fv(l));let d=c;return d.$serializedTypes&&cs(d,l,t),c}function fv(l){if(va.length=0,typeof l=="object"&&l!==null&&l!==void 0)for(let e of Object.keys(l))va.push(l[e]);return va}function ds(l,e){if(e==null||l==null)return;let t=!1;for(let i of Object.keys(e)){let n=mv(l,i);t&&n===void 0||(!n||n.writable===!0||n?.set!==void 0)&&(l[i]=e[i])}}function mv(l,e){let t;do t=Object.getOwnPropertyDescriptor(l,e);while(!t&&(l=Object.getPrototypeOf(l)));return t}var wn=N("debuganimatorcontroller"),Dc=N("debugrootmotion"),Zt=class{Play(e,t=-1,i=Number.NEGATIVE_INFINITY,n=0){if(t<0)t=0;else if(t>=this.model.layers.length){console.warn("invalid layer");return}let o=this.model.layers[t].stateMachine;for(let s of o.states)if(s.name===e||s.hash===e){wn&&console.log("transition to ",s),this.transitionTo(s,n,i);return}console.warn("Could not find "+e+" to play")}Reset(){this.setStartTransition()}SetBool(e,t){let i=typeof e=="string"?"name":"hash";return this.model?.parameters.filter(n=>n[i]===e).forEach(n=>n.value=t)}GetBool(e){let t=typeof e=="string"?"name":"hash";return this.model?.parameters.find(i=>i[t]===e)?.value??!1}SetFloat(e,t){let i=typeof e=="string"?"name":"hash";return this.model?.parameters.filter(n=>n[i]===e).forEach(n=>n.value=t)}GetFloat(e){let t=typeof e=="string"?"name":"hash";return this.model?.parameters.find(i=>i[t]===e)?.value??0}SetInteger(e,t){let i=typeof e=="string"?"name":"hash";return this.model?.parameters.filter(n=>n[i]===e).forEach(n=>n.value=t)}GetInteger(e){let t=typeof e=="string"?"name":"hash";return this.model?.parameters.find(i=>i[t]===e)?.value??0}SetTrigger(e){wn&&console.log("SET TRIGGER",e);let t=typeof e=="string"?"name":"hash";return this.model?.parameters.filter(i=>i[t]===e).forEach(i=>i.value=!0)}ResetTrigger(e){let t=typeof e=="string"?"name":"hash";return this.model?.parameters.filter(i=>i[t]===e).forEach(i=>i.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 i of t.stateMachine.states)if(i.name===e)return i;return null}normalizedStartOffset=0;_speed=1;animator;model;get context(){return this.animator?.context}bind(e){this.animator=e,this._mixer=new bv(this.animator.gameObject),this.createActions(this.animator)}clone(){let e=qo(this.model,(i,n,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 Zt(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,wn&&console.log(this)}_activeStates=[];updateActiveStates(){for(let e=0;e<this._activeStates.length;e++){let t=this._activeStates[e],i=t.motion;if(!i.action)this._activeStates.splice(e,1),e--;else{let n=i.action;n.getEffectiveWeight()<=0&&!n.isRunning()&&(wn&&console.debug("REMOVE",t.name,n.getEffectiveWeight(),n.isRunning(),n.isScheduled()),this._activeStates.splice(e,1),e--)}}}setStartTransition(){for(let e of this.model.layers){let t=e.stateMachine,i=t.states[t.defaultState];this.transitionTo(i,0,this.normalizedStartOffset)}}evaluateTransitions(){let e=!1;if(!this._activeState){if(this.setStartTransition(),!this._activeState)return;e=!0}let t=this._activeState,i=t.motion.action,n=0;for(let o of t.transitions){if(++n,!o.hasExitTime&&o.conditions.length<=0)continue;let s=!0;for(let c of o.conditions)if(!this.evaluateCondition(c)){s=!1;break}if(!!s){wn&&s&&console.log("All conditions are met",o.conditions,i);for(let c of o.conditions){let d=this.model.parameters.find(a=>a.name===c.parameter);d?.type===9&&(d.value=!1)}if(i){let c=t.motion.clip.duration,d=c<=0?1:i.time/c;if(!o.hasExitTime||d>=o.exitTime&&i.time>=i.getClip().duration){i.clampWhenFinished=!0,wn&&(console.log("transition to "+o.destinationState,o),console.log(i.time,o.exitTime)),this.transitionTo(o.destinationState,o.duration,o.offset);return}}else{this.transitionTo(o.destinationState,o.duration,o.offset);return}break}}let r=!1;if(t.motion.isLooping&&i&&i.time>=i.getClip().duration&&(r=!0,i.reset(),i.time=0,i.play()),!r&&t&&!e&&i&&this.animator&&t.behaviours){let o=i?.getClip().duration,s=i.time/o,c=new Wr(this._activeState,s,o,this._speed);for(let d of t.behaviours)d.instance&&d.instance.onStateUpdate?.call(d.instance,this.animator,c,0)}}transitionTo(e,t,i){if(!this.animator)return;let n=0;if(typeof e=="number"&&(e==-1&&(e=this.model.layers[n].stateMachine.defaultState),e=this.model.layers[n].stateMachine.states[e]),!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,a=this._activeState.motion.action.time/d,h=new Wr(this._activeState,a,d,this._speed);for(let u of this._activeState.behaviours)u.instance?.onStateExit?.call(u.instance,this.animator,h,n)}let o=this._activeState?.motion.action;o&&o.fadeOut(t),r&&(e.motion.action=e.motion.action_loopback,e.motion.action_loopback=o);let s=this._activeState;this._activeState=e;let c=e.motion?.action;if(c){i=Math.max(0,Math.min(1,i)),c.isRunning()&&c.stop(),c.reset(),c.timeScale=this._speed,c.enabled=!0;let d=e.motion.clip.duration;if(c.time=i*d,c.clampWhenFinished=!0,c.setLoop(yv,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 a=new Wr(e,i,d,this._speed);for(let h of this._activeState.behaviours)h.instance?.onStateEnter?.call(h.instance,this.animator,a,n)}}else console.warn("No action",e.motion,this);wn&&console.log("TRANSITION FROM "+s?.name+" TO "+e.name,t,o,c,c?.getEffectiveTimeScale(),c?.getEffectiveWeight(),c?.isRunning(),c?.isScheduled(),c?.paused)}createAction(e){if(this._mixer.uncacheClip(e),this.animator?.applyRootMotion){this.rootMotionHandler||(this.rootMotionHandler=new Hc(this));let t=this.animator.gameObject;return this.rootMotionHandler.createClip(this._mixer,t,e)}else return this._mixer.clipAction(e)}evaluateCondition(e){let t=this.model.parameters.find(i=>i.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 i=t.stateMachine;for(let n=0;n<i.states.length;n++){let r=i.states[n];if(r.motion||(r.motion=Yu(r.name)),this.animator&&r.motion.clips){let o=r.motion.clips?.find(s=>s.node.name===this.animator?.gameObject?.name);r.motion.clip=o?.clip}if(!r.motion.clip){let o=new gv;r.motion.clip=o}if(r.motion?.clip){let o=r.motion.clip,s=this.createAction(o);r.motion.action=s}if(r.behaviours&&Array.isArray(r.behaviours))for(let o of r.behaviours){if(!o?.typeName)continue;let s=D.get(o.typeName),c=new s;c.isStateMachineBehaviour&&(c._context=this.context??void 0,ds(c,o.properties),o.instance=c),wn&&console.log("Created animator controller behaviour",r.name,o.typeName,o.properties,c)}}}}*enumerateActions(){for(let e of this.model.layers){let t=e.stateMachine;for(let i=0;i<t.states.length;i++){let n=t.states[i];n?.motion&&(n.motion.action&&(yield n.motion.action),n.motion.action_loopback&&(yield n.motion.action_loopback))}}}rootMotionHandler},Ea=class{track;createdInterpolant;originalEvaluate;customEvaluate;constructor(e,t){this.track=e;let i=e,n=i.createInterpolant.bind(e);i.createInterpolant=()=>(i.createInterpolant=n,this.createdInterpolant=n(),this.originalEvaluate=this.createdInterpolant.evaluate.bind(this.createdInterpolant),this.customEvaluate=r=>{if(!this.originalEvaluate)return;let o=this.originalEvaluate(r);return t(r,o)},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}},Re=class{set action(e){this._action=e}get action(){return this._action}_action;root;clip;positionWrapper=null;rotationWrapper=null;context;positionChange=new hs;rotationChange=new Qt;constructor(e,t,i,n,r){if(this.context=e,this.root=t,this.clip=i,Re.firstKeyframeRotation[i.uuid]||(Re.firstKeyframeRotation[i.uuid]=new wa.Quaternion),r){let o=r.values;Re.firstKeyframeRotation[i.uuid].set(o[0],o[1],o[2],o[3])}Re.spaceRotation[i.uuid]||(Re.spaceRotation[i.uuid]=new Qt),Re.effectiveSpaceRotation[i.uuid]||(Re.effectiveSpaceRotation[i.uuid]=new Qt),Re.clipOffsetRotation[i.uuid]=new Qt,r&&Re.clipOffsetRotation[i.uuid].set(r.values[0],r.values[1],r.values[2],r.values[3]).invert(),this.handlePosition(i,n),this.handleRotation(i,r)}onStart(e){if(e.getClip()!==this.clip)return;let t=Re.lastObjRotation[this.root.uuid];Re.spaceRotation[this.clip.uuid].copy(t);{let i=new wa.Euler().setFromQuaternion(t);console.log("START",this.clip.name,Q.toDegrees(i.y))}}getClipRotationOffset(){return Re.clipOffsetRotation[this.clip.uuid]}handlePosition(e,t){if(t){let i=this.root;Dc&&i.add(new vv),Re.lastObjPosition[i.uuid]||(Re.lastObjPosition[i.uuid]=new hs);let n=new hs,r=new hs,o=0;this.positionWrapper=new Ea(t,(s,c)=>{let d=this.action.getEffectiveWeight();if(Dc&&i.position.length()>8&&i.position.set(0,i.position.y,0),s>o){n.set(c[0],c[1],c[2]),n.sub(r),n.multiplyScalar(d),n.applyQuaternion(this.getClipRotationOffset());let a=this.clip.uuid;n.applyQuaternion(Re.spaceRotation[a]),this.positionChange.copy(n)}return r.fromArray(c),o=s,c[0]=0,c[1]=0,c[2]=0,c})}}handleRotation(e,t){if(t){if(Dc){let s=t.values,c=new Ku().setFromQuaternion(new Qt(s[0],s[1],s[2],s[3]));console.log(e.name,t.name,"FIRST ROTATION IN TRACK",Q.toDegrees(c.y));let d=t.values.length-4,a=new Qt().set(s[d],s[d+1],s[d+2],s[d+3]),h=new Ku().setFromQuaternion(a);console.log(e.name,t.name,"LAST ROTATION IN TRACK",Q.toDegrees(h.y))}let i=this.root;Re.lastObjRotation[i.uuid]||(Re.lastObjRotation[i.uuid]=new Qt);let n=0,r=new Qt,o=new Qt;this.rotationWrapper=new Ea(t,(s,c)=>(s>n&&(o.set(c[0],c[1],c[2],c[3]),r.invert(),o.multiply(r),this.rotationChange.copy(o)),r.fromArray(c),n=s,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(Re.identityQuaternion,1-e)}},Yt=Re;z(Yt,"lastObjPosition",{}),z(Yt,"lastObjRotation",{}),z(Yt,"firstKeyframeRotation",{}),z(Yt,"spaceRotation",{}),z(Yt,"effectiveSpaceRotation",{}),z(Yt,"clipOffsetRotation",{}),z(Yt,"identityQuaternion",new Qt);var Hc=class{controller;handler=[];root;constructor(e){this.controller=e}createClip(e,t,i){this.root=t;let n="";t&&"name"in t&&(n=t.name);let r=this.findRootTrack(i,".position"),o=this.findRootTrack(i,".quaternion"),s=new Yt(this.controller.context,t,i,r,o);this.handler.push(s);let c=e.clipAction(i);return s.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 hs;summedRotation=new Qt;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),Yt.lastObjRotation[this.root.uuid].copy(this.root.quaternion)}findRootTrack(e,t){let i=e.tracks;for(let n of i)if(n.name.endsWith(t))return n;return null}};var Ev=N("debuganimator"),bt=class extends M{applyRootMotion=!1;hasRootMotion=!1;keepAnimatorControllerStateOnDisable=!1;set runtimeAnimatorController(e){this._animatorController&&this._animatorController.model===e||(e?e instanceof Zt?this._animatorController=e:this._animatorController=new Zt(e):this._animatorController=null)}get runtimeAnimatorController(){return this._animatorController}Play(e,t=-1,i=Number.NEGATIVE_INFINITY,n=0){this.runtimeAnimatorController?.Play(e,t,i,n)}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=Q.lerp(e.x,e.y,Math.random())}set minMaxOffsetNormalized(e){this.normalizedStartOffset=Q.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}Ev&&console.log("ANIMATOR",this.name,this)}}onDisable(){this.keepAnimatorControllerStateOnDisable||this._animatorController?.Reset()}onBeforeRender(){this._animatorController&&this._animatorController.update()}};k([A()],bt.prototype,"applyRootMotion",2),k([A()],bt.prototype,"hasRootMotion",2),k([A()],bt.prototype,"keepAnimatorControllerStateOnDisable",2),k([A()],bt.prototype,"runtimeAnimatorController",1);import*as Xr from"three";var Jt=class extends M{playAutomatically=!0;randomStartTime=!0;_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&&he.markDirty(this.gameObject)}}getAction(e){return this.actions?.find(t=>t.getClip().name===e)}play(e,t){if(this.init(),!this.mixer)return;let i=e;if(typeof e=="number"){if(e>=this.animations.length)return;i=this.animations[e]}else typeof e=="string"&&(i=this.animations.find(r=>r.name===e));if(!i){console.error("Could not find clip",e);return}for(let r of this.actions)if(r.getClip()===i)return this.internalOnPlay(r,t);let n=this.mixer.clipAction(i);return this.actions.push(n),this.internalOnPlay(n,t)}internalOnPlay(e,t){var i=this.currentAction;if(i===e&&i.isRunning()&&i.time<i.getClip().duration){let o=this.tryFindHandle(e);if(o)return o.getPromise()}let n=t?.exclusive??!0;t?.fadeDuration?(n&&i?.fadeOut(t.fadeDuration),e.fadeIn(t.fadeDuration)):n&&i?.stop(),e.reset(),e.enabled=!0,e.time=0,e.timeScale=1,t?.clampWhenFinished&&(e.clampWhenFinished=!0),t?.startTime!==void 0&&(e.time=t.startTime),t?.loop!==void 0&&(e.loop=t.loop?Xr.LoopRepeat:Xr.LoopOnce),e.play();let r=new jc(e,this.mixer,t,o=>{this._handles.splice(this._handles.indexOf(r),1)});return this._handles.push(r),r.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 Xr.AnimationMixer(this.gameObject);for(let e=0;e<this.animations.length;e++){let t=this.mixer.clipAction(this.animations[e]);this.actions.push(t)}}}};k([A()],Jt.prototype,"playAutomatically",2),k([A()],Jt.prototype,"randomStartTime",2);var jc=class{mixer;action;promise=null;resolve=null;reject=null;_options;_resolveCallback=null;_rejectCallback=null;_loopCallback;_finishedCallback;_resolvedOrRejectedCallback;constructor(e,t,i,n){this.action=e,this.mixer=t,this._resolvedOrRejectedCallback=n,this._options=i}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 yf}from"three/examples/jsm/loaders/GLTFLoader.js";import{Vector3 as wv}from"three";var _n=class extends M{from;to;width=0;centered=!0;_centerPos;awake(){this._centerPos=new wv}update(){if(!this.from||!this.to)return;let e=q(this.from).clone(),t=q(this.to).clone(),i=e.distanceTo(t);this._centerPos.copy(e),this._centerPos.add(t),this._centerPos.multiplyScalar(.5),ie(this.gameObject,this.centered?this._centerPos:e),this.gameObject.lookAt(q(this.to).clone()),this.gameObject.scale.set(this.width,this.width,i)}};k([A(S)],_n.prototype,"from",2),k([A(S)],_n.prototype,"to",2);var ui=class{time;value;inTangent;inWeight;outTangent;outWeight;weightedMode};k([A()],ui.prototype,"time",2),k([A()],ui.prototype,"value",2),k([A()],ui.prototype,"inTangent",2),k([A()],ui.prototype,"inWeight",2),k([A()],ui.prototype,"outTangent",2),k([A()],ui.prototype,"outWeight",2),k([A()],ui.prototype,"weightedMode",2);var sr=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 i of this.keys){if(t&&i.time>e&&e>t.time)return Q.lerp(t.value,i.value,(e-t.time)/(i.time-t.time));t=i}return this.keys[this.keys.length-1].value}};k([A(ui)],sr.prototype,"keys",2);import*as ep from"three";import*as us from"three";import{PositionalAudioHelper as _v}from"three/examples/jsm/helpers/PositionalAudioHelper.js";var _a=class extends EventTarget{context;get hasFocus(){return document.hasFocus()}get isVisible(){return this._isVisible}_isVisible=!0;constructor(e){super(),this.context=e,window.addEventListener("visibilitychange",this.onVisiblityChanged.bind(this),!1)}onVisiblityChanged(e){switch(e.target.visibilityState){case"hidden":this._isVisible=!1,this.dispatchEvent(new Event("application-hidden"));break;case"visible":this._isVisible=!0,this.dispatchEvent(new Event("application-visible"));break}}};var at=N("debugaudio");var Be=class extends M{static get userInteractionRegistered(){return Be._didCallBeginWaitForUserInteraction||(Be._didCallBeginWaitForUserInteraction=!0,Be._beginWaitForUserInteraction()),Be._userInteractionRegistered}static registerWaitForAllowAudio(e){if(e!==null){if(this._userInteractionRegistered){e();return}this.callbacks.indexOf(e)===-1&&this.callbacks.push(e),Be._didCallBeginWaitForUserInteraction||(Be._didCallBeginWaitForUserInteraction=!0,Be._beginWaitForUserInteraction())}}static _beginWaitForUserInteraction(e=null){if(this._userInteractionRegistered){e&&e();return}e!==null&&this.registerWaitForAllowAudio(e);let i=(()=>{if(i!=null&&!Be._userInteractionRegistered){Be._userInteractionRegistered=!0,console.log("registered interaction, can play audio now"),document.removeEventListener("pointerdown",i),document.removeEventListener("click",i),document.removeEventListener("dragstart",i),document.removeEventListener("touchstart",i);for(let n of this.callbacks)n();this.callbacks.length=0}}).bind(this);document.addEventListener("pointerdown",i),document.addEventListener("click",i),document.addEventListener("dragstart",i),document.addEventListener("touchstart",i)}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&&(at&&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&&Be._userInteractionRegistered){let e=S.getComponent(this.context.mainCamera,$t)??S.findObjectOfType($t,this.context);e?.listener&&(this.sound=new us.PositionalAudio(e.listener),this.gameObject.add(this.sound))}return this.sound}get ShouldPlay(){return this.shouldPlay}_focusCallback;awake(){this.audioLoader=new us.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&&Be._userInteractionRegistered&&this.play()},this.context.application.addEventListener("application-visible",this._focusCallback)}onDestroy(){this.context.application.removeEventListener("application-visible",this._focusCallback)}onEnable(){Be._userInteractionRegistered?this.playOnAwake&&this.context.application.isVisible&&this.play():Be._beginWaitForUserInteraction(()=>{this.enabled&&!this.destroyed&&this.shouldPlay&&this.loadAndPlay(this.clip)})}onDisable(){this.stop()}lerp=(e,t,i)=>e*(1-i)+t*i;onLoaded(e){at&&console.log("audio buffer loaded"),Be.registerWaitForAllowAudio(()=>{at&&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(),at&&console.log(this.name,this.shouldPlay,Be.userInteractionRegistered,this),this.shouldPlay&&Be._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(at&&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?at&&!this.helper&&(this.helper=new _v(e,e.getRefDistance()),e.add(this.helper)):this.helper&&this.helper.parent&&this.helper.removeFromParent()}loadAndPlay(e){if(e&&(this.clip=e),this.clip&&(at&&console.log(this.clip),this.clip.endsWith(".mp3")||this.clip.endsWith(".wav"))){if(this.audioLoader||(this.audioLoader=new us.AudioLoader),this.shouldPlay=!0,this._lastClipStartedLoading===this.clip){at&&console.log("Is currently loading:",this._lastClipStartedLoading,this);return}this._lastClipStartedLoading=this.clip,at&&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,at&&console.log("play",this.sound?.getVolume(),this.sound),this.sound&&!this.sound.isPlaying&&this.sound.play()}pause(){at&&console.log("Pause",this),this._hasEnded=!0,this.shouldPlay=!1,this.sound&&this.sound.isPlaying&&(this._lastContextTime=this.sound?.context.currentTime,this.sound.pause())}stop(){at&&console.log("Pause",this),this._hasEnded=!0,this.shouldPlay=!1,this.sound&&(this._lastContextTime=this.sound?.context.currentTime,at&&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,at&&console.log("Audio clip ended",this.clip),this.sound.dispatchEvent({type:"ended",target:this}))}},ue=Be;z(ue,"_didCallBeginWaitForUserInteraction",!1),z(ue,"callbacks",[]),z(ue,"_userInteractionRegistered",!1),k([A()],ue.prototype,"clip",2),k([A()],ue.prototype,"playOnAwake",2),k([A()],ue.prototype,"loop",1),k([A()],ue.prototype,"spatialBlend",1),k([A()],ue.prototype,"minDistance",1),k([A()],ue.prototype,"maxDistance",1),k([A()],ue.prototype,"volume",1),k([A()],ue.prototype,"rollOffMode",2);var $t=class extends M{get listener(){return this._listener==null&&(this._listener=new ep.AudioListener),this._listener}_listener=null;awake(){ue.registerWaitForAllowAudio(()=>{let e=this.listener;if(e==null||e.parent)return;let t=S.getComponentInParent(this.gameObject,ne);t?t.cam.add(e):this.gameObject.add(e)})}};import{GLTFLoader as Rv}from"three/examples/jsm/loaders/GLTFLoader";import*as Ra from"three";var cp=vl(lp(),1),xa=class{success;filename;hash;size;url;constructor(e,t,i,n){this.success=e,this.filename=t,this.hash=i,this.size=n}};async function dp(l,e){let t=await l.arrayBuffer(),i=hp(t),n=l.name.split(".").pop(),r=i+"."+n,o=l.name.split(".").shift();console.assert(o!==void 0);let s={alias:o,filename:r},d=await(await fetch(e+"/exists",{method:"POST",body:JSON.stringify(s)})).json();if(d.success||console.warn("exists check did fail"),d.exists)return console.log("file already exists",i),new xa(!0,r,i,l.size);console.log("begin uploading file",o,l.size);let a=new FormData;a.append("file",l);let h={};h.filesize=l.size,o&&(h.alias=o);let f=await(await fetch(e+"/upload/file",{method:"POST",body:a,headers:h})).json();if(f?.success===!1)return f.message!==void 0?console.error("Upload failed:",f.message):console.error("Upload failed"),null;console.assert(f.hash_sum===i,"hash sum did not match","received:",f.hash_sum,"expected:",i),f.success&&console.log("successfully uploaded",i,f.id);let E=new xa(f.success,r,i,l.size);return E.url=e,E}function hp(l){return(0,cp.default)(new Uint8Array(l))}async function Ta(l,e,t,i,n=!1){try{let r=await fetch(i+"/download/file",{method:"POST",body:l});if(r.status!==200)return console.error("download failed",r),null;let o=await r.blob(),s=await o.arrayBuffer();n||console.assert(o.size===t,"size mismatch","expected:",t,"got:",o.size);let c=hp(s);return n||console.assert(c===e,"hash mismatch, downloaded file is invalid"),o.arrayBuffer()}catch(r){console.error(r)}return null}async function up(l,e){let t=await fetch(l),i=t.body?.getReader(),n=t.headers.get("Content-Length"),r=n?parseInt(n):0;if(!i)return null;let o=0,s=[];for(;;){let{done:a,value:h}=await i.read();if(h&&(s.push(h),o+=h.length,e.call(null,new ProgressEvent("progress",{loaded:o,total:r}))),a)break}let c=new Uint8Array(o),d=0;for(let a of s)c.set(a,d),d+=a.length;return c}var ps=N("debugavatar"),ar=class{root;head;leftHand;rigthHand;get isValid(){return this.head!==null&&this.head!==void 0}constructor(e,t,i,n){this.root=e,this.head=t,this.leftHand=i,this.rigthHand=n,this.root?.traverse(r=>r.layers.set(2))}},xn=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 i=null;if(typeof t=="string"){if(i=await this.loadAvatar(e,t),!i){let r=new ye;i=S.instantiate(hn(t,e.scene),r)}}else i=t;if(!i)return null;let n=this.findAvatar(i);return n.isValid?(ps&&console.log("[Custom Avatar] valid config",t,ps?n:""),n):(console.warn("[Custom Avatar] config isn't valid",t,ps?n:""),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(ps&&console.log("[Custom Avatar] "+t+", loading..."),t.endsWith(".glb")||(t+=".glb"),this.avatarRegistryUrl===null){let n=await fetch("./"+t),r=null;if(n.ok){let s=await n.blob();s&&(r=await s.arrayBuffer())}return!r&&(r=await Ta(t,t,0,"no url here go away",!0),!r)?null:(await Qr(e,r,null,0))?.scene??null}let i=new Rv;return nr(i,e),new Promise((n,r)=>{let o=this.avatarRegistryUrl+"/"+t;i.load(o,async s=>{await Ca(e,o,s),n(s.scene)},s=>{ps&&console.log("[Custom Avatar] "+s.loaded/s.total*100+"% loaded of "+s.total/1024+"kB")},s=>{console.error("[Custom Avatar] Error when loading: "+s),n(null)})})}cacheModel(e,t){}findAvatar(e){let t=e,i=t;i.children.length==1&&(i=e.children[0]);let n=this.findAvatarPart(i,["head"]),r=this.findAvatarPart(i,["left","hand"]),o=this.findAvatarPart(i,["right","hand"]);if(!n){n=t;let c=new Ra.Vector3;new Ra.Box3().setFromObject(n).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&&n.scale.multiplyScalar(1/d*.3)}return new ar(t,n,r,o)}findAvatarPart(e,t){let i=e.name.toLowerCase(),n=!0;for(let r of t){if(!n)break;i.indexOf(r)===-1&&(n=!1)}if(n)return e;if(e.children)for(let r of e.children){let o=this.findAvatarPart(r,t);if(o)return o}return null}handleCustomAvatarErrors(e){if(!e.ok)throw Error(e.statusText);return e}};import{AxesHelper as Cv}from"three";var zi=class extends M{length=1;depthTest=!0;isGizmo=!0;_axes=null;onEnable(){if(this.isGizmo&&!hi)return;this._axes||(this._axes=new Cv(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)}};k([A()],zi.prototype,"length",2),k([A()],zi.prototype,"depthTest",2),k([A()],zi.prototype,"isGizmo",2);import*as fp from"three";var Yr=class extends M{from;to;hint;desiredDistance=1;onEnable(){}update(){if(!this.from||!this.to||!this.hint)return;let e=q(this.to).clone(),t=q(this.from).clone(),i=e.distanceTo(t),n=e.clone();n.sub(t);let r=t.clone();r.add(e),r.multiplyScalar(.5);let o=q(this.hint).clone();o.sub(r);let s=new fp.Vector3;s.crossVectors(o,n),s.crossVectors(n,s),s.normalize();let c=i*.5,d=Math.max(this.desiredDistance,c),a=Math.sqrt(d*d-c*c),h=s.clone();h.multiplyScalar(a),h.add(r),ie(this.gameObject,h);let u=r.clone();u.sub(s),this.gameObject.lookAt(u)}};import*as Gi from"three";import*as pi from"three";var Sv=new pi.BoxGeometry(1,1,1);function Sa(l=null){let e=new pi.Color(l??14540253),t=new pi.EdgesGeometry(Sv);return new pi.LineSegments(t,new pi.LineBasicMaterial({color:e}))}var Ov=N("gizmos"),Pa=class extends M{box=null;testBox=new Gi.Box3;_lastMatrixUpdateFrame=-1;isInBox(e){if(!!e){if(this.box||(this.box=new Gi.Box3),this.updateBox(!1),e.type==="Mesh")this.testBox.setFromObject(e);else{let t=q(e,Pa._position),i=Ch(e,Pa._size);this.testBox.setFromCenterAndSize(t,i)}return this.box?.intersectsBox(this.testBox)}}intersects(e){return e?this.updateBox(!1).intersectsBox(e):!1}updateBox(e=!1){return this.box||(this.box=new Gi.Box3),(e||this.context.time.frameCount!=this._lastMatrixUpdateFrame)&&(this._lastMatrixUpdateFrame=this.context.time.frameCount,this.box.setFromCenterAndSize(new Gi.Vector3(0,0,0),new Gi.Vector3(1,1,1)),this.box.applyMatrix4(this.gameObject.matrixWorld)),this.box}_helper=null;_color=null;awake(){this._helper=null,this._color=null,this.box=null}showHelper(e=null,t=!1){if(!(!Ov&&!t)){if(this._helper){e&&this._color?.set(e),this.gameObject.add(this._helper);return}this._helper=Sa(e),this.gameObject.add(this._helper)}}},lt=Pa;z(lt,"_position",new Gi.Vector3),z(lt,"_size",new Gi.Vector3(.01,.01,.01));import*as fs from"three";import{FrontSide as mp,DoubleSide as gp}from"three";function Zr(l,e){if(!l)return;let t=l.material;t?.isMaterial===!0&&(t.depthTest=!e.renderOnTop,t.side=e.doubleSided??!0?gp:mp,t.depthWrite=e.depthWrite??!1,t.shadowSide=e.doubleSided?gp:mp,l.castShadow=e.castShadows?e.castShadows:!1,l.receiveShadow=e.receiveShadows?e.receiveShadows:!1);for(let i of l.children)Zr(i,e)}function Jr(l,e,t){l[e]===void 0&&console.warn("Field",e,"is undefined on",l);let i=Proxy.revocable(l[e],{set(o,s,c,d){let a=o[s],h=Reflect.set(o,s,c,d);return t(c,a),h}}),n=i.revoke,r=l[e];return i.revoke=()=>{l[e]=r,n()},l[e]=i.proxy,i}function bp(l,e,t=3){let i=l.__scheduledActions;i||(i=l.__scheduledActions={});let n=e.name;i[t]||(i[t]={});let r=i[t];if(r[n])return;function*s(){e?.call(l),r[n]=null}let c=l.startCoroutine(s(),t);r[n]=c}var $r=class extends M{mass=1;set isKinematic(e){this._isKinematic=e,this._body&&(this._body.type=e?G.KINEMATIC:G.DYNAMIC)}get isKinematic(){return this._isKinematic}_isKinematic=!1;drag=0;angularDrag=1;detectCollision=!0;sleepThreshold=.01;get body(){return this._body===null&&this.initialize(),this._body}_body=null;currentVelocity;_smoothedVelocity;lastWorldPosition;dirty=!0;transformProxy;awake(){this._body=null,this.currentVelocity=new fs.Vector3,this._smoothedVelocity=new fs.Vector3,this.lastWorldPosition=q(this.gameObject).clone()}start(){this.setBodyFromGameObject()}onEnable(){this._body?this.context.physics.addBody(this.gameObject,this._body):this.initialize(),this.body&&(this.body.wakeUp(),this.gameObject.updateWorldMatrix(!0,!1),this.setBodyFromGameObject()),this.transformProxy=Jr(this.gameObject.matrix,"elements",()=>{this.context.physics.isUpdating||(this.dirty=!0)})}onDisable(){this.transformProxy?.revoke(),this._body&&this.context.physics.removeBody(this.gameObject,this._body,!1)}onDestroy(){this._body&&this.context.physics.removeBody(this.gameObject,this._body)}earlyUpdate(){this.dirty&&this.setBodyFromGameObject()}onBeforeRender(){this.updateVelocity()}initialize(){if(this._body)return;let e=new sa;e.drag=this.drag,e.angularDrag=this.angularDrag,e.mass=this.mass,e.kinematic=this.isKinematic,e.physicsEvents=this.detectCollision,e.sleepThreshold=this.sleepThreshold,this._body=this.context.physics.createBody(this.gameObject,e)}wakeUp(){this.body?.wakeUp()}applyForce(e,t){this.body?.applyForce(new _(e.x,e.y,e.z),t?new _(t.x,t.y,t.z):void 0)}getVelocity(){return this.body?$r.tempPosition.set(this.body?.velocity.x,this.body?.velocity.y,this.body?.velocity.z):$r.tempPosition.set(0,0,0)}setVelocity(e,t,i){!this.body||(this.body.velocity.x=e/this.context.time.deltaTime,this.body.velocity.y=t/this.context.time.deltaTime,this.body.velocity.z=i/this.context.time.deltaTime)}get smoothedVelocity(){return this._smoothedVelocity}setAngularVelocity(e,t,i){!this.body||(this.body.angularVelocity.x=e/this.context.time.deltaTime,this.body.angularVelocity.y=t/this.context.time.deltaTime,this.body.angularVelocity.z=i/this.context.time.deltaTime)}setBodyFromGameObject(e=null){if(this.dirty=!1,this.body&&this.gameObject&&!this.destroyed){let t=this.worldPosition;this.body.position.set(t.x,t.y,t.z);let i=this.worldQuaternion;if(this.body.quaternion.set(i.x,i.y,i.z,i.w),e){$r.copyVector3.set(e.x,e.y,e.z),this._smoothedVelocity.lerp($r.copyVector3,this.context.time.deltaTime/.1);let n=this._smoothedVelocity;this.body.velocity.x=n.x,this.body.velocity.y=n.y,this.body.velocity.z=n.z}}}updateVelocity(){if(!!this.currentVelocity&&this.body&&this.gameObject){let e=q(this.gameObject);this.currentVelocity.subVectors(e,this.lastWorldPosition),this.lastWorldPosition.copy(e),this._smoothedVelocity.lerp(this.currentVelocity,this.context.time.deltaTime/.1)}}},ce=$r;z(ce,"tempPosition",new fs.Vector3),z(ce,"copyVector3",new fs.Vector3),k([A()],ce.prototype,"mass",2),k([A()],ce.prototype,"isKinematic",1),k([A()],ce.prototype,"drag",2),k([A()],ce.prototype,"angularDrag",2),k([A()],ce.prototype,"detectCollision",2),k([A()],ce.prototype,"sleepThreshold",2);import{Vector3 as Oa}from"three";var fi=class extends M{attachedRigidbody=null;isTrigger=!1;_shape=null;awake(){super.awake(),this._shape=null}onEnable(){this.attachedRigidbody||(this.attachedRigidbody=this.gameObject.getComponentInParent(ce))}onDisable(){this._shape}};k([A(ce)],fi.prototype,"attachedRigidbody",2),k([A()],fi.prototype,"isTrigger",2);var Tn=class extends fi{radius=.5;center=new Oa(0,0,0);onEnable(){super.onEnable(),this._shape||(this._shape=this.context.physics.addSphereCollider(this.gameObject,this.center,this.radius,this.attachedRigidbody))}};k([A()],Tn.prototype,"radius",2),k([A(Oa)],Tn.prototype,"center",2);var Rn=class extends fi{size;center;onEnable(){super.onEnable(),this._shape||(this._shape=this.context.physics.addBoxCollider(this.gameObject,this.isTrigger,this.center,this.size,this.attachedRigidbody))}};k([A(Oa)],Rn.prototype,"size",2),k([A(Oa)],Rn.prototype,"center",2);var Kr=class{};var kt=class extends M{canGrab=!0;onPointerClick(e){}},It=class extends M{isUsed=!0;usedBy=null};var lr=class extends lt{},eo=class extends M{deleteBoxes=[];awake(){this.deleteBoxes=S.findObjectsOfType(lr,this.context)}update(){for(let e of this.deleteBoxes){let t=this.gameObject;e.isInBox(t)===!0&&(S.getComponentInParent(this.gameObject,It)||Lr(this.gameObject,this.context.connection))}}};var cr=class extends M{visibleOn;onEnable(){this.apply()}apply(){this.test()||S.setActive(this.gameObject,!1)}test(){return this.visibleOn<0?!0:Av()?(this.visibleOn&2)!==0:(this.visibleOn&1)!==0}};k([A()],cr.prototype,"visibleOn",2);var Aa;function Av(){if(Aa===!0||Aa===!1)return Aa;let l=!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)))&&(l=!0)}(navigator.userAgent||navigator.vendor||window.opera),Aa=l,l}import*as Vi from"three";var Ce=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,i,n){return e.prep(4,12),e.writeFloat32(n),e.writeFloat32(i),e.writeFloat32(t),e.offset()}};var to=class{bb=null;bb_pos=0;__init(e,t){return this.bb_pos=e,this.bb=t,this}position(e){return(e||new Ce).__init(this.bb_pos,this.bb)}rotation(e){return(e||new Ce).__init(this.bb_pos+12,this.bb)}scale(e){return(e||new Ce).__init(this.bb_pos+24,this.bb)}static sizeOf(){return 36}static createTransform(e,t,i,n,r,o,s,c,d,a){return e.prep(4,36),e.prep(4,12),e.writeFloat32(a),e.writeFloat32(d),e.writeFloat32(c),e.prep(4,12),e.writeFloat32(s),e.writeFloat32(o),e.writeFloat32(r),e.prep(4,12),e.writeFloat32(n),e.writeFloat32(i),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 to).__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 Cn=N("debugsync"),io="STRS";Vr(io,Mt.getRootAsSyncedTransformModel);var mi=new ft;function Nc(l,e,t=!0){mi.clear();let i=mi.createString(l);Mt.startSyncedTransformModel(mi),Mt.addGuid(mi,i),Mt.addFast(mi,t);let n=e.worldPosition,r=e.worldEuler,o=e.gameObject.scale;Mt.addTransform(mi,to.createTransform(mi,n.x,n.y,n.z,r.x,r.y,r.z,o.x,o.y,o.z));let s=Mt.endSyncedTransformModel(mi);return mi.finish(s,io),mi.asUint8Array()}var Qe=class extends M{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(){Cn&&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(){Cn&&console.log("new instance",this.guid,this),this._receivedDataBefore=!1,this._targetPosition=new Vi.Vector3,this._targetRotation=new Vi.Quaternion,this.lastWorldPos=new Vi.Vector3,this.lastWorldRotation=new Vi.Quaternion,this.rb=S.getComponentInChildren(this.gameObject,ce),this.rb&&(this._wasKinematic=this.rb.isKinematic),this.receivedUpdate=!0,this._model=new En(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(io,this.receivedDataCallback)}onDestroy(){this.syncDestroy&&Mh(this.guid,this.context.connection),this._model=null,this.context.connection.stopListening("joined-room",this.joinedRoomCallback),this.context.connection.stopListenBinary(io,this.receivedDataCallback)}tryGetLastState(){let e=this.context.connection.tryGetState(this.guid);e&&this.onReceivedData(e)}tempEuler=new Vi.Euler;onReceivedData(e){if(!this.destroyed&&typeof e.guid=="function"&&e.guid()===this.guid){Cn&&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){he.markDirty(this.gameObject,!0);let i=t.position();i&&(this.interpolatePosition&&this._targetPosition?.set(i.x(),i.y(),i.z()),(!this.interpolatePosition||!this._receivedDataBefore)&&this.setWorldPosition(i.x(),i.y(),i.z()));let n=t.rotation();n&&(this.tempEuler.set(n.x(),n.y(),n.z()),this.interpolateRotation&&this._targetRotation.setFromEuler(this.tempEuler),(!this.interpolateRotation||!this._receivedDataBefore)&&Sh(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){Cn&&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),o=t.angleTo(this.lastWorldRotation),s=this._model.hasOwnership||this.fastMode?1e-4:.001;(r>s||o>s)&&(this._model.hasOwnership?this._needsUpdate=!0:(Cn&&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),he.markDirty(this.gameObject,!0),this._needsUpdate=!1))}if(this._model&&!this._model.hasOwnership&&this._model.isOwned&&this._receivedDataBefore){let o=this._receivedFastUpdate||this.fastMode?.5:.3,s=!1;if(this.interpolatePosition&&this._targetPosition){let c=this.worldPosition;c.lerp(this._targetPosition,o),this.worldPosition=c,s=!0}if(this.interpolateRotation&&this._targetRotation){let c=this.worldQuaternion;c.slerp(this._targetRotation,o),this.worldQuaternion=c,s=!0}s&&he.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&&(Cn&&console.log("reset kinematic",this.rb.name,this._wasKinematic),this.rb.isKinematic=this._wasKinematic),this.gameObject.position.distanceTo(new Vi.Vector3(0,0,0))>1e3&&(Cn&&console.log("RESET",this.name),this.gameObject.position.set(0,1,0),this.rb.setVelocity(0,0,0),this.rb.setBodyFromGameObject()));let i=10,n=this.rb||this.fastMode;if(this._needsUpdate&&(i<=0||i>0&&this.context.time.frameCount%i===0||n)){Cn&&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=Nc(this.guid,this,!!n);this.context.connection.sendBinary(r)}}};import*as ee from"three";var Ia=class{static createButton(e,t={}){let i=document.createElement("button");function n(){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(){h.end()}),c.appendChild(d);var a=document.createElementNS("http://www.w3.org/2000/svg","path");a.setAttribute("d","M 12,12 L 28,28 M 28,12 12,28"),a.setAttribute("stroke","#fff"),a.setAttribute("stroke-width",2),d.appendChild(a),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 h=null;async function u(E){E.addEventListener("end",f),await e.xr.setSession(E),i.textContent="STOP AR",t.domOverlay.root.style.display="",h=E}function f(){h.removeEventListener("end",f),i.textContent="START AR",t.domOverlay.root.style.display="none",h=null}i.style.display="",i.style.cursor="pointer",i.style.left="calc(50% - 50px)",i.style.width="100px",i.textContent="START AR",i.onmouseenter=function(){i.style.opacity="1.0"},i.onmouseleave=function(){i.style.opacity="0.5"},i.onclick=function(){h===null?navigator.xr.requestSession("immersive-ar",t).then(u):h.end()}}function r(){i.disabled=!0,i.style.display="",i.style.cursor="auto",i.style.left="calc(50% - 75px)",i.style.width="150px",i.onmouseenter=null,i.onmouseleave=null,i.onclick=null}function o(){r(),i.textContent="AR NOT SUPPORTED"}function s(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 i.id="ARButton",i.style.display="none",s(i),navigator.xr.isSessionSupported("immersive-ar").then(function(c){c?n():o()}).catch(o),i;{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",s(c),c}}};var Ma=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 i=document.createElement("button");function n(){let c=null;async function d(h){h.addEventListener("end",a),await e.xr.setSession(h),i.textContent="EXIT VR",c=h}function a(){c.removeEventListener("end",a),i.textContent="ENTER VR",c=null}i.style.display="",i.style.cursor="pointer",i.style.left="calc(50% - 50px)",i.style.width="100px",i.textContent="ENTER VR",i.onmouseenter=function(){i.style.opacity="1.0"},i.onmouseleave=function(){i.style.opacity="0.5"},i.onclick=function(){if(c===null){let h={optionalFeatures:["local-floor","bounded-floor","hand-tracking","high-fixed-foveation-level","layers"]};navigator.xr.requestSession("immersive-vr",h).then(d)}else c.end()}}function r(){i.disabled=!0,i.style.display="",i.style.cursor="auto",i.style.left="calc(50% - 75px)",i.style.width="150px",i.onmouseenter=null,i.onmouseleave=null,i.onclick=null}function o(){r(),i.textContent="VR NOT SUPPORTED"}function s(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 i.id="VRButton",i.style.display="none",s(i),navigator.xr.isSessionSupported("immersive-vr").then(function(c){c?n():o(),Ma.xrSessionIsGranted&&(console.log("XR session is granted - will enter immersive web now"),i.click())}),i;{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",s(c),c}}static registerSessionGrantedListener(){if("xr"in navigator)try{navigator.xr.addEventListener("sessiongranted",()=>{console.log("Received session granted event"),Ma.xrSessionIsGranted=!0})}catch(e){console.error(e)}}},no=Ma;z(no,"xrSessionIsGranted",!1);no.registerSessionGrantedListener();import*as Pe from"three";import*as La from"three";var vp=vl(wc(),1);import{AudioAnalyser as Iv}from"three";var ro="noVoip",ct=N("debugvoip"),Mv=N("voip");var zc=class{id;constructor(e){this.id=e}};var Gc=class{peer;voip;userId;peerId;call=null;callErrorListener=null;stream=null;constructor(e,t,i,n){this.voip=e,this.peer=t,this.userId=i,this.peerId=n}close(){ct&&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 i of t)i.enabled=!e}async startVoipCall(){if(!await Ke.HasMicrophonePermissions()){console.warn("no permission to use microphone, can not start call");return}ct&&console.log("start voip call"),this.stream=await navigator.mediaDevices.getUserMedia({audio:!0,video:!1}),this.updateMute(this.voip.muteOutput),ct&&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=>{ct&&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(i){i.stop()}),this.stream=null):console.error(t)},this.peer.on("error",this.callErrorListener)}onCallClose(e){ct&&console.log("call closed",e)}},Vc=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,i){this.voip=e,this.obj=t,this.call=i}openAudioStream(e){let t=e.getAudioTracks();for(let i of t)if(i.kind==="audio"&&i.readyState==="live"){this.open(i);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,ue.userInteractionRegistered||ct&&console.log("Incoming call, waiting for user interaction before opening audio"),ue.registerWaitForAllowAudio(async()=>{if(this.call.open&&!this.closed){ct&&console.log("Setup audio and begin listening"),this.stream=new MediaStream([e]);let t=new La.AudioListener;this.audio=new La.Audio(t),this.audio.setVolume(this.voip.muteInput?0:1),this.audio.setMediaStreamSource(this.stream);let i=document.createElement("audio");this.audioElement=i,i.style.display="none",document.body.appendChild(i),i.srcObject=this.stream,i.sinkId!==void 0&&navigator.mediaDevices.enumerateDevices().then(n=>{if(!!i){console.log(n);for(let r of n)if(r.label==="Speakerphone"){i.sinkId=r.deviceId;break}}}),ct&&console.log("call is setup, you should hear something now"),this.analyzer=new Iv(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()}},Ke=class extends M{requireParam=!1;set muteInput(e){if(e===this._inputMuted||(this._inputMuted=e,!this.currentIncomingCalls))return;let t=this._inputMuted?0:1;for(let i in this.currentIncomingCalls)this.currentIncomingCalls[i]?.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 i in this.currentIncomingCalls){let n=this.currentIncomingCalls[i];if(n&&n.currentAnalyzer)return n.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(N(ro)){console.log("VOIP is disabled by url parameter: "+ro);return}if(this.requireParam&&!Mv){console.debug("VOIP must be enabled explicitly by url parameter");return}this.peer=new vp.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 i=new Gc(this,this.peer,this.context.connection.connectionId,e.peerId);this.connections[e.id]=i,i.startVoipCall()}}}),this.context.connection.beginListen("user-left-room",e=>{let{userId:t}=e,i=this.connections[t];this.connections[t]=null,i&&i.close();let n=this.currentIncomingCalls[t];ct&&console.log("UserLeftRoom",e,t,n),n&&(n.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){ct&&console.log("Peer connection established and received id"),this.model=new zc(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){ct&&console.log("CONNECTION",t),t.on("data",function(i){ct&&console.log("Received",i)})}))}async onReceiveCall(e){let{metadata:t}=e;console.assert(t.userId);let{userId:i}=t,{peer:n}=e,r=this.currentIncomingCalls[i];if(r&&r.close(),ct&&console.log("received call"),await Ke.HasMicrophonePermissions()){let o=await navigator.mediaDevices.getUserMedia({audio:!0,video:!1});e.answer(o)}else e.answer(null);this.currentIncomingCalls[i]=new Vc(this,this.gameObject,e),e.on("stream",o=>{ct&&console.log("receive caller stream, will setup audio now"),this.currentIncomingCalls[i]?.openAudioStream(o)}),e.on("error",console.error)}static async HasMicrophonePermissions(){return(await navigator.permissions.query({name:"microphone"})).state!=="denied"}};var oo=N("debugflags");var Wc=class{Mask=17;Has(e){let t=this.Mask&e;return oo&&console.log("HAS",e,this.Mask,"Result="+t),t!==0}Set(e){this.Mask=e,Se.Apply()}Enable(e){this.Mask|=e,Se.Apply()}Disable(e){this.Mask&=~e,Se.Apply()}Toggle(e){this.Mask^=e,Se.Apply()}EnableAll(){this.Mask=-1,Se.Apply()}DisableAll(){this.Mask=0,Se.Apply()}},vt=Wc;z(vt,"Global",new Wc);var gi=class extends M{static Apply(){for(let e of this.registry)e.UpdateVisible(vt.Global)}awake(){gi.registry.push(this)}onEnable(){gi.firstApply||(gi.firstApply=!0,gi.Apply())}onDestroy(){let e=gi.registry.indexOf(this);e>=0&&gi.registry.splice(e,1)}visibleIn;get isOn(){return this.gameObject.visible}UpdateVisible(e=null){if(!this.enabled)return;let t,i=e;i&&typeof i=="number"&&(console.assert(typeof i=="number","XRFlag.UpdateVisible: state must be a number",i),oo&&console.log(i),gi.buffer.Mask=i,e=gi.buffer);let n=e;if(n?(oo&&console.log("use passed in mask"),t=n.Has(this.visibleIn)):(oo&&console.log("use global mask"),vt.Global.Has(this.visibleIn)),t!==void 0)if(t)oo&&console.trace("is visible",this.name,this.gameObject.uuid),S.setActive(this.gameObject,!0);else{if(oo&&console.trace("is not visible",this.name,this.gameObject.uuid),!this.gameObject.visible)return;this.gameObject.visible=!1}}},Se=gi;z(Se,"registry",[]),z(Se,"firstApply"),z(Se,"buffer",new vt);import*as K from"three";import{XRControllerModelFactory as Lv}from"three/examples/jsm/webxr/XRControllerModelFactory.js";import{OculusHandModel as Dv}from"three/examples/jsm/webxr/OculusHandModel.js";import{OculusHandPointerModel as Hv}from"three/examples/jsm/webxr/OculusHandPointerModel.js";import*as Ep from"three";import*as Kt from"three";var Sn=N("debugavatar"),Wi=class extends M{static onAvatarMarkerCreated(e){return Wi._onNewAvatarMarkerAdded.push(e),e}static onAvatarMarkerDestroyed(e){return Wi._onAvatarMarkerDestroyed.push(e),e}connectionId;avatar;awake(){Wi.instances.push(this),Sn&&console.log(this);for(let e of Wi._onNewAvatarMarkerAdded)e({avatarMarker:this,gameObject:this.gameObject})}onDestroy(){Wi.instances.splice(Wi.instances.indexOf(this),1);for(let e of Wi._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):S.setActive(this.avatar,e))}},pe=Wi;z(pe,"instances",[]),z(pe,"_onNewAvatarMarkerAdded",[]),z(pe,"_onAvatarMarkerDestroyed",[]);var ms=class{_isVisible=!0;setVisible(e){this._isVisible=e,this.updateVisibility()}guid;root=null;head=null;handLeft=null;handRight=null;lastUpdate=-1;isLocalAvatar=!1;flags=null;headScale=new Kt.Vector3(1,1,1);handLeftScale=new Kt.Vector3(1,1,1);handRightScale=new Kt.Vector3(1,1,1);webxr;lastAvatarId=null;hasAvatarOverride=!1;context;avatarMarker=null;constructor(e,t,i){this.context=e,this.guid=t,this.webxr=i,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 Kt.Object3D;_handLeftTarget=new Kt.Object3D;_handRightTarget=new Kt.Object3D;_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)){this._canInterpolate=!0;let i=this.isLocalAvatar?this.head:this._headTarget;if(i.position.set(e.position.x,e.position.y,e.position.z),i.quaternion.set(e.rotation.x,e.rotation.y,e.rotation.z,e.rotation.w),i.scale.set(e.scale,e.scale,e.scale),i.scale.multiply(this.headScale),this.handLeft){let n=this.isLocalAvatar?this.handLeft:this._handLeftTarget;n.position.set(e.posLeftHand.x,e.posLeftHand.y,e.posLeftHand.z),n.quaternion.set(e.rotLeftHand._x,e.rotLeftHand._y,e.rotLeftHand._z,e.rotLeftHand._w),n.quaternion.multiply(ms.invertRotation),n.scale.set(e.scale,e.scale,e.scale),n.scale.multiply(this.handLeftScale)}if(this.handRight){let n=this.isLocalAvatar?this.handRight:this._handRightTarget;n.position.set(e.posRightHand.x,e.posRightHand.y,e.posRightHand.z),n.quaternion.set(e.rotRightHand._x,e.rotRightHand._y,e.rotRightHand._z,e.rotRightHand._w),n.quaternion.multiply(ms.invertRotation),n.scale.set(e.scale,e.scale,e.scale),n.scale.multiply(this.handRightScale)}}}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(){Sn&&console.log("Destroy avatar",this.guid),this.root?.removeFromParent(),this.avatarMarker?.destroy(),this.lastAvatarId=null,this.head&&_e.Remove(this.context,this.head)}updateVisibility(){let e=this.root;e&&S.setActive(e,this._isVisible)}async setupCustomAvatar(e){if(Sn&&console.log("LOAD",e,this),!e||typeof e=="string"&&e.length<=0)return!1;this.head&&_e.Remove(this.context,this.head);let t=e;if(t?.loadAssetAsync!==void 0){await t.loadAssetAsync();let n=t.asset;S.setActive(n,!1),e=S.instantiate(n),S.setActive(e,!0)}Sn&&console.log(e);let i=await ms.loader.getOrCreateNewAvatarInstance(this.context,e);if(Sn&&console.log(i,i?.isValid,this.lastAvatarId,e),i?.isValid){if(this.root=i.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=S.addNewComponent(this.root,pe),this.avatarMarker.connectionId=this.guid,this.avatarMarker.avatar=this,this.head&&this.head!==i.head&&this.head?.removeFromParent(),this.head=i.head,this.headScale.copy(this.head.scale),this.head&&!this.isLocalAvatar&&_e.Add(this.context,this.head,this.avatarMarker),i.leftHand&&this.handLeft?.removeFromParent(),this.handLeft=i.leftHand??this.handLeft,this.handLeft?this.handLeftScale.copy(this.handLeft.scale):this.handLeftScale.set(1,1,1),i.rigthHand&&this.handRight?.removeFromParent(),this.handRight=i.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(...S.getComponentsInChildren(this.root,Se)),this.flags.length<=0&&this.head){let n=S.addNewComponent(this.head,Se);n.visibleIn=20,this.flags.push(n),Sn&&console.log("Added flag to head: "+n.visibleIn,this.head.name)}return Sn&&console.log("[Avatar], is Local? ",this.isLocalAvatar,this.root),this.updateFlags(),this.updateVisibility(),!0}else return Sn&&console.warn("build avatar failed"),!1}},Lt=ms;z(Lt,"loader",new xn),z(Lt,"invertRotation",new Kt.Quaternion().setFromAxisAngle(new Kt.Vector3(0,1,0),Math.PI));var _e=class{static Add(e,t,i=null){if(!!t){for(let n of this.Pois)if(n.obj===t)return;this.Pois.push({obj:t,avatar:i}),this.LastChangeTime=e.time.time}}static Remove(e,t){if(!!t){for(let i of this.Pois)if(i.obj===t){this.Pois.splice(this.Pois.indexOf(i),1),this.LastChangeTime=e?.time.time??Z.Current?.time.time;return}}}};z(_e,"Pois",[]),z(_e,"LastChangeTime",0);var Uc=class{guid;position=new Ep.Vector3},Ui=class extends M{set controlledTarget(e){this.target=e;let t=D.get("MoveRandom");if(t&&this.target){let i=S.getComponent(this.target,t);i&&i.destroy()}}target=null;avatar=null;_model=null;_targetModel=new Uc;_currentTargetObject=null;_lastUpdateTime=0;_lookDuration=0;_lastPoiChangedTime=0;awake(){if(this.avatar=S.getComponentInParent(this.gameObject,pe),this.avatar){let e=S.getComponentInParent(this.gameObject,pe);this._model=new En(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&&ie(this.target,e.position)})}update(){if((!this.context.connection.isConnected||this._model?.hasOwnership)&&(_e.LastChangeTime!==this._lastPoiChangedTime&&(this._lastPoiChangedTime=_e.LastChangeTime,this._lookDuration=0),this.selectTarget(),this._currentTargetObject&&this.context.time.frameCount%10===0&&this.target)){let t=q(this._currentTargetObject);ie(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=_e.Pois;if(t.length>0){let i=t[Math.floor(Math.random()*t.length)];if(i&&i.obj){if(i.avatar&&i.avatar===this.avatar)return;this._currentTargetObject=i.obj}}}}};var dr=class extends M{},Fe=class extends M{static CreateRaycastLine(){let e=new K.Line(this.geometry),t=e.material;return t.color=this.raycastColor,e.layers.set(1),e.name="line",e.scale.z=1,e}static CreateRaycastHitPoint(){let e=new K.SphereGeometry(.5,22,22),t=new K.MeshBasicMaterial({color:this.raycastColor}),i=new K.Mesh(e,t);return i.visible=!1,i.layers.set(1),i}static Create(e,t,i,n){let r=i?S.addNewComponent(i,Fe,!1):new Fe;r.webXR=e,r.index=t,r.type=n;let o=e.context;return r.controller=o.renderer.xr.getController(t),r.controllerGrip=o.renderer.xr.getControllerGrip(t),r.controllerModel=this.Factory.createControllerModel(r.controller),r.controllerGrip.add(r.controllerModel),r.hand=o.renderer.xr.getHand(t),r.hand.add(new Dv(r.hand)),r.hand.traverse(s=>s.layers.set(2)),r.handPointerModel=new Hv(r.hand,r.controller),r.controller.addEventListener("connected",s=>{r.setControllerLayers(r.controllerModel,2),r.setControllerLayers(r.controllerGrip,2),setTimeout(()=>{r.setControllerLayers(r.controllerGrip,2)},1e3)}),r.hand.addEventListener("connected",s=>{if(s.data.hand){e.Rig&&e.Rig.add(r.hand),r.type=0,r.handPointerModel.traverse(a=>a.layers.set(2)),r.handPointerModel.pointerObject?.traverse(a=>a.layers.set(2));let d=r.hand.joints;if(d)for(let a of Object.keys(d)){let h=d[a];h.parent||r.hand.add(h)}}}),r}static addEventListener(e,t){let i=this.eventSubs[e]??[];i.push(t),this.eventSubs[e]=i}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 K.Quaternion),ve(e).multiply(this._wristQuaternion.setFromEuler(new K.Euler(-Math.PI/4,0,0)))):null}movementVector=new K.Vector3;worldRot=new K.Quaternion;joystick=new K.Vector2;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=Fe.CreateRaycastLine()),this._raycastHitPoint||(this._raycastHitPoint=Fe.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),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 K.Quaternion;update(){this.context.time.frameCount%60===0&&(this.setControllerLayers(this.controller,2),this.setControllerLayers(this.controllerGrip,2),this.setControllerLayers(this.hand,2));let e=Fe.eventSubs["update"];if(e&&e.length>0)for(let n of e)n(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(ve(this.controller),this.useSmoothing?t:1);let i=q(this.controller);if(this.raycastLine)if(this.type===1)this.raycastLine.visible=!1;else if(this.isUsingHands){this.raycastLine.visible=!this.grabbed,ie(this.raycastLine,i);let n=this.hand.joints;if(n&&n.wrist&&this.grabbed&&this.grabbed.isCloseGrab){let o=this.getWristQuaternion();o&&this.rayRotation.copy(o)}Ae(this.raycastLine,this.rayRotation)}else this.raycastLine.visible=!0,Ae(this.raycastLine,this.rayRotation),ie(this.raycastLine,i);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 i=this.input?.gamepad?.buttons;switch(this.input.handedness){case"left":let n=3*Fe.MovementSpeedFactor,r=2,o=Q.clamp01(this.joystick.length()*2),s=this.joystick.x>0?1:-1,c=Math.pow(this.joystick.x,r);c*=s,c*=o;let d=this.joystick.y>0?1:-1,a=Math.pow(this.joystick.y,r);a*=d,c*=o,t.getWorldQuaternion(this.worldRot),this.movementVector.set(c,0,a),this.movementVector.applyQuaternion(this.webXR.TransformOrientation),this.movementVector.y=0,this.movementVector.applyQuaternion(this.worldRot),t.position.add(this.movementVector.multiplyScalar(n*this.context.time.deltaTime)),this.isUsingHands&&this.runTeleport(t,i);break;case"right":let h=this.joystick.x,u=Math.abs(h);if(u<.4)this.didRotate=!1;else if(u>.5&&!this.didRotate){let f=h>0?-1:1;t.rotateY(Q.toRadians(30*f)),this.didRotate=!0}this.runTeleport(t,i);break}}runTeleport(e,t){let i=-this.joystick.y;if(this.hand?.visible&&!this.grabbed){let s=this.handPointerModel.isPinched();s&&this._pinchStartTime===void 0&&(this._pinchStartTime=this.context.time.time),s&&this._pinchStartTime&&this.context.time.time-this._pinchStartTime>.8&&(i=this.handPointerModel.isPinched()?1:0),s||(this._pinchStartTime=void 0)}else this._pinchStartTime=void 0;let n=i>.5,r=this.webXR.Rig?this.webXR.Rig?.scale?.x<.999:!1,o=null;if(t&&this.input&&!this.input.hand)for(let s=0;s<t.length;s++){let c=t[s];if(s===4)if(c.pressed&&!this.didChangeScale){this.didChangeScale=!0;let d=this.webXR.Rig;if(d)if(r){r=!1,d.scale.set(1,1,1),o=1,Fe.MovementSpeedFactor=1;let a=this.context.mainCamera;Fe.PreviousCameraFarDistance&&(a.far=Fe.PreviousCameraFarDistance)}else{r=!0,n=!0,o=.1,Fe.MovementSpeedFactor=o*2;let a=this.context.mainCamera;Fe.PreviousCameraFarDistance=a.far,a.far/=o}}else c.pressed||(this.didChangeScale=!1)}if(n){if(!this.didTeleport){let s=this.raycast();if(this.didTeleport=!0,s&&s.length>0){let c=s[0];if(r||this.isValidTeleportTarget(c.object)){let d=c.point;ie(e,d)}}}}else i<.1&&(this.didTeleport=!1);o!==null&&(e.scale.set(o,o,o),e.updateMatrixWorld())}isValidTeleportTarget(e){return S.getComponentInParent(e,dr)!=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 i=1;if(this.webXR.Rig&&(i/=this.webXR.Rig.scale.x),this.raycastLine){this.raycastLine.scale.z=i*(this.lastHit?.distance??9999);let n=this.raycastLine.material;t!=null?n.color=Fe.raycastColor:n.color=Fe.raycastNoHitColor}if(this._raycastHitPoint){if(this.lastHit!=null){this._raycastHitPoint.position.z=-1;let n=Q.clamp(this.lastHit.distance*.01*i,.015,.1);this._raycastHitPoint.scale.set(n,n,n)}this._raycastHitPoint.visible=this.lastHit!==null}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(),e&&e.length>0)for(let i of e){let n=i.object;if(!this.testIsVisible(n)){console.log("not visible");continue}this.lastSelectStartObject=n;let r={selected:n,grab:n},o=Fe.eventSubs["select-start"];if(o&&o.length>0)for(let s of o)s(this,r);r.grab!==n&&console.log("Grabbed object changed","original",n,"new",r.grab),r.grab&&(this.grabbed=dt.TryTake(this,r.grab,i,t));break}else{let i=Fe.eventSubs["select-start"],n={selected:null,grab:null};if(i&&i.length>0)for(let r of i)r(this,n)}}_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=Fe.eventSubs["select-end"];if(t&&t.length>0)for(let i of t)i(this,e);this.grabbed&&(this.grabbed.free(),this.grabbed=null)}testIsVisible(e){return e?S.isActiveInHierarchy(e):!0}setControllerLayers(e,t){if(!!e&&(e.layers.set(t),e.children))for(let i of e.children)this.grabbed?.selected===i||this.grabbed?.selectedMesh===i||this.setControllerLayers(i,t)}getRay(){let e=new K.Ray;return e.origin.copy(q(this.controller)),e.direction.set(0,0,-1).applyQuaternion(this.rayRotation),e}overlap(){let e=this.isUsingHands&&this.handPointerModel?this.handPointerModel.pointerObject:this.controllerGrip;if(!e)return new Array;let t=q(e).clone();return this.context.physics.sphereOverlap(t,.02)}raycast(){let e=new je;return e.layerMask=new K.Layers,e.layerMask.set(0),e.ray=this.getRay(),this.context.physics.raycast(e)}},ae=Fe;z(ae,"Factory",new Lv),z(ae,"raycastColor",new K.Color(.9,.3,.3)),z(ae,"raycastNoHitColor",new K.Color(.6,.6,.6)),z(ae,"geometry",new K.BufferGeometry().setFromPoints([new K.Vector3(0,0,0),new K.Vector3(0,0,-1)])),z(ae,"handModels",{}),z(ae,"eventSubs",{}),z(ae,"PreviousCameraFarDistance"),z(ae,"MovementSpeedFactor",1);var et=class{static AddEventListener(e,t){return et.Events[e]||(et.Events[e]=[]),et.Events[e].push(t),t}static RemoveEventListener(e,t){if(!t||!et.Events[e])return;let i=et.Events[e].indexOf(t);i>=0&&et.Events[e].splice(i,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,i,n){let r=S.getComponentInParent(t,kt);if(!r)return console.warn("Prevented taking object that is not interactable",t),null;let o=t,s=S.getComponentInParent(t,Qe);s&&(s.requestOwnership(),o=s.gameObject);for(let d of this.Current)if(d.selected===o)return d.controller===e||(d.free(),d.Take(e,o,t,s,r,i,n)),d;let c=new et;return c.Take(e,o,t,s,r,i,n),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,i,n,r,o,s){if(console.assert(t!==null,"Expected object to be taken but was",t),e.isUsingHands?this.positionSource=s?e.wrist:e.controller:this.positionSource=e.controller,!this.positionSource)return console.warn("No position source"),this;let c={controller:e,take:t,hit:i,sync:n,interactable:r};et.Events.WillTake?.forEach(f=>f(this,c));let d=i;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=s,this.didReparent=!1,this.sync=n,this.grabTime=e.context.time.time,this.grabUUID=Date.now().toString(),this.usageMarker=S.addNewComponent(this.selected,It),this.rigidbodies=S.getComponentsInChildren(this.selected,ce),q(this.positionSource,this.lastControllerWorldPos);let a=()=>s?this.lastControllerWorldPos.clone():o.point.clone();this.grabDistance=a().distanceTo(this.lastControllerWorldPos),this.totalChangeAlongDirection=0,this.localPositionOffsetToGrab=this.selected.worldToLocal(a());let h=e.isUsingHands&&s?this.controller.getWristQuaternion().clone():e.rayRotation.clone();ve(this.selected,this.localQuaternionToGrab).premultiply(h.invert());let u=this.controller.webXR.Rig;return u&&this.rigPositionLastFrame.copy(q(u)),_e.Add(e.context,this.selected),et.Register(this),this.sync&&(this.sync.fastMode=!0),et.Events.DidTake?.forEach(f=>f(this,c)),this}free(){if(!this.selected)return;let e={controller:this.controller,take:this.selected,hit:this.selected,sync:this.sync,interactable:null};et.Events.WillFree?.forEach(n=>n(this,e)),_e.Remove(this.controller.context,this.selected),et.Remove(this),this.sync&&(this.sync.fastMode=!1);let t=this.selectedMesh;t&&this.originalMaterial&&t.material&&(t.material=this.originalMaterial);let i=this.selected;if(this.didReparent&&i.parent){let n=this.selectedParent;n?n.attach(i):this.controller?.context.scene.attach(i)}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 n of this.rigidbodies)n.wakeUp(),n.smoothedVelocity&&n.setVelocity(n.smoothedVelocity.x,n.smoothedVelocity.y,n.smoothedVelocity.z);this.rigidbodies=null,this.localPositionOffsetToGrab=null,this.quaternionLerp=null,et.Events.DidFree?.forEach(n=>n(this,e))}grabPoint=new K.Vector3;localPositionOffsetToGrab=null;localPositionOffsetToGrab_worldSpace=new K.Vector3;localQuaternionToGrab=new K.Quaternion(0,0,0,1);targetDir=null;quaternionLerp=null;controllerDir=new K.Vector3;controllerWorldPos=new K.Vector3;lastControllerWorldPos=new K.Vector3;controllerPosDelta=new K.Vector3;totalChangeAlongDirection=0;rigPositionLastFrame=new K.Vector3;controllerMovementSinceLastFrame(){if(!this.positionSource||!this.controller)return 0;this.controllerDir.set(0,0,-1),this.controllerDir.applyQuaternion(this.controller.rayRotation),q(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 i=q(e),n=this.rigPositionLastFrame.sub(i);this.controllerPosDelta.add(n),this.rigPositionLastFrame.copy(i)}return this.controllerDir.dot(this.controllerPosDelta)}update(){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 K.Vector3),this.targetDir.set(0,0,-this.grabDistance*t);let i=this.targetDir.applyQuaternion(this.controller.rayRotation).add(this.controllerWorldPos),n=this.controller.rayRotation.clone().multiplyQuaternions(this.controller.rayRotation,this.localQuaternionToGrab);this.quaternionLerp||(this.quaternionLerp=n.clone()),this.quaternionLerp.slerp(n,this.controller.useSmoothing?this.controller.context.time.deltaTime/.03:1),Ae(this.selected,this.quaternionLerp),this.selected.updateWorldMatrix(!1,!1),this.grabPoint.copy(i),this.localPositionOffsetToGrab&&(this.localPositionOffsetToGrab_worldSpace.copy(this.localPositionOffsetToGrab),this.selected.localToWorld(this.localPositionOffsetToGrab_worldSpace).sub(q(this.selected)),i.sub(this.localPositionOffsetToGrab_worldSpace)),ie(this.selected,i)}if(this.rigidbodies!=null)for(let e of this.rigidbodies)e.wakeUp(),e.setBodyFromGameObject({x:0,y:0,z:0});he.markDirty(this.selected,!0)}}},dt=et;z(dt,"Events",{}),z(dt,"Current",[]);import*as Da from"three";var Dt=class extends M{webAR=null;invertForward=!1;get arScale(){return this._arScale}set arScale(e){e!==this._arScale&&(this._arScale=e,this.setScale(e))}_arScale=5;_rig=null;_startPose=null;_placementPose=null;_isTouching=!1;onBegin(e){this._placementPose=null,this.gameObject.visible=!1,this.gameObject.matrixAutoUpdate=!1,this._startPose=this.gameObject.matrix.clone(),e.addEventListener("selectstart",this.onSelectStart.bind(this)),e.addEventListener("selectend",this.onSelectEnd.bind(this)),setTimeout(()=>this.gameObject.visible=!1,1e3)}onUpdate(e,t,i){if(i&&!this._placementPose&&this._isTouching){if(this.webAR&&this.webAR.setReticleActive(!1),this._placementPose=new Da.Matrix4().fromArray(i.transform.matrix).invert(),e){if(this.invertForward){let n=new Da.Matrix4().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._startPose&&this.gameObject.matrix.copy(this._startPose),this.gameObject.matrixAutoUpdate=!0,e&&(e.matrixAutoUpdate=!0),he.markDirty(this.gameObject,!0),setTimeout(()=>this.gameObject.visible=!0,100)}onSelectStart(){this._isTouching=!0}onSelectEnd(){this._isTouching=!1}setScale(e){let t=this._rig;!t||!this._placementPose||(t.matrixAutoUpdate=!1,t.matrix.multiplyMatrices(new Da.Matrix4().makeScale(e,e,e),this._placementPose),t.matrix.decompose(t.position,t.quaternion,t.scale),t.updateMatrixWorld())}};k([A()],Dt.prototype,"invertForward",2),k([A()],Dt.prototype,"arScale",1);var Pn=class extends M{awake(){}};import{Object3D as jv}from"three";var hr=N("debugaddressables"),Ha=class{_context;constructor(e){this._context=e,this._context.pre_update_callbacks.push(this.preUpdate.bind(this))}preUpdate(){}_assetReferences={};findAssetReference(e){return this._assetReferences[e]||null}registerAssetReference(e){return e.uri&&(this._assetReferences[e.uri]?console.warn("Asset reference already registered",e):this._assetReferences[e.uri]=e),e}},tt=class{static getOrCreate(e,t,i){let n=ks(e,t);hr&&console.log("GetOrCreate Addressable from",e,t,"FinalPath=",n);let r=i.addressables,o=r.findAssetReference(n);if(o)return o;let s=new tt(n);return r.registerAssetReference(s),s}get asset(){return this._glbRoot??this._asset}set asset(e){this._asset=e}_loading;get uri(){return this._uri}get rawAsset(){return this._asset}_asset;_glbRoot;_uri;_progressListeners=[];_isLoadingRawBinary=!1;_rawBinary;constructor(e){this._uri=e,jh(this._uri,this.onResolvePrefab.bind(this))}async onResolvePrefab(e){return e===this.uri&&(this.mustLoad&&await this.loadAssetAsync(),this.asset)?this.asset:null}get mustLoad(){return!this.asset||this.asset.__destroyed===!0}isLoaded(){return this._rawBinary||this.asset!==void 0}unload(){this.asset&&(hr&&console.log("Unload",this.asset),this.asset.scene?S.destroy(this.asset.scene):S.destroy(this.asset)),this.asset=null}async preload(){if(!this.mustLoad||this._isLoadingRawBinary)return null;if(this._rawBinary!==void 0)return this._rawBinary;this._isLoadingRawBinary=!0,hr&&console.log("Preload",this.uri);let e=await up(this.uri,t=>{this.raiseProgressEvent(t)});return this._rawBinary=e?.buffer??null,this._isLoadingRawBinary=!1,this._rawBinary}async loadAssetAsync(e){if(!this.mustLoad)return;if(e&&this._progressListeners.push(e),this._loading!==void 0)return this._loading;let t=Z.Current;this._rawBinary?(this._loading=Qr(t,this._rawBinary,this.uri,null),this.raiseProgressEvent(new ProgressEvent("progress",{loaded:this._rawBinary.byteLength,total:this._rawBinary.byteLength}))):(hr&&console.log("Load async",this.uri),this._loading=ur(t,this.uri,null,!0,n=>{this.raiseProgressEvent(n)}));let i=await this._loading;if(this._progressListeners.length=0,this._glbRoot=this.tryGetActualGameObjectRoot(i),this._loading=void 0,i)return Ii(t),i.scene!==void 0&&(this.asset=i),this.asset}async instantiate(e){return this.onInstantiate(e,!1)}async instantiateSynced(e,t=!0){return this.onInstantiate(e,!0,t)}beginListenDownload(e){this._progressListeners.indexOf(e)<0&&this._progressListeners.push(e)}endListenDownload(e){let t=this._progressListeners.indexOf(e);t>=0&&this._progressListeners.splice(t,1)}raiseProgressEvent(e){for(let t of this._progressListeners)t(this,e)}async onInstantiate(e,t=!1,i){let n=Z.Current;if(e||(e=n.scene),this.mustLoad&&await this.loadAssetAsync(),hr&&console.log("Instantiate",this.uri,"parent:",e),this.asset){hr&&console.log("Add to scene",this.asset);let r=e instanceof ye?e:null;if(r||(r=new ye),typeof e=="object"&&(e instanceof jv?r.parent=e:Object.assign(r,e)),t){r.context=n;let o=this.asset;o.guid=this.uri;let s=Gs(o,r,void 0,i);if(s)return s}else{let o=S.instantiate(this.asset,r);if(o)return o}}else hr&&console.warn("Failed to load asset",this.uri);return null}tryGetActualGameObjectRoot(e){if(e&&e.scene){let t=e.scene;return t.isGroup&&t.children.length===1&&t.children[0].name+"glb"===t.name?t.children[0]:t}return null}},qc=class extends Ni{constructor(){super([tt])}onSerialize(e,t){if(e&&e.uri!==void 0&&typeof e.uri=="string")return e.uri}onDeserialize(e,t){return typeof e=="string"?t.context?t.gltfId?tt.getOrCreate(t.gltfId,e,t.context):(console.error("Missing spurce id"),null):(console.error("Missing context"),null):null}};new qc;import*as yt from"three";var bi=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,i,n,r){return e.prep(4,16),e.writeFloat32(r),e.writeFloat32(n),e.writeFloat32(i),e.writeFloat32(t),e.offset()}};var Me=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 Me).__init(e.readInt32(e.position())+e.position(),e)}static getSizePrefixedRootAsVrUserStateBuffer(e,t){return e.setPosition(e.position()+4),(t||new Me).__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 Ce).__init(this.bb_pos+t,this.bb):null}rotation(e){let t=this.bb.__offset(this.bb_pos,12);return t?(e||new bi).__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 Ce).__init(this.bb_pos+t,this.bb):null}posRightHand(e){let t=this.bb.__offset(this.bb_pos,18);return t?(e||new Ce).__init(this.bb_pos+t,this.bb):null}rotLeftHand(e){let t=this.bb.__offset(this.bb_pos,20);return t?(e||new bi).__init(this.bb_pos+t,this.bb):null}rotRightHand(e){let t=this.bb.__offset(this.bb_pos,22);return t?(e||new bi).__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 wp=N("debugxr"),gs=N("debugavatar");var Qc="VRUS";Vr(Qc,Me.getRootAsVrUserStateBuffer);function Xc(){return new Date().getTime()}function Bv(l){let e=l&4294967295,t=l/Math.pow(2,32)&1048575;return Xe.create(e,t)}var bs=class{guid;time;avatarId;position=new yt.Vector3;rotation=new yt.Vector4;scale=1;posLeftHand=new yt.Vector3;posRightHand=new yt.Vector3;rotLeftHand=new yt.Quaternion;rotRightHand=new yt.Quaternion;constructor(e){this.guid=e}update(e,t,i,n,r){this.time=Xc(),this.avatarId=r,this.position.set(t.x,t.y,t.z),e&&this.position.applyMatrix4(e.matrixWorld);let o=bs.quat0,s=bs.quat1;o.set(i.x,i.y,i.z,i.w),o=o.multiplyQuaternions(o,bs.invertRotation),e&&(e.getWorldQuaternion(s),o.multiplyQuaternions(s,o)),this.rotation.set(o.x,o.y,o.z,o.w),this.scale=e.scale.x;let c=n.LeftController?.controllerGrip;c&&(c.getWorldPosition(this.posLeftHand),c.getWorldQuaternion(this.rotLeftHand));let d=n.RightController?.controllerGrip;if(d&&(d.getWorldPosition(this.posRightHand),d.getWorldQuaternion(this.rotRightHand)),n.LeftController?.hand?.visible){let a=n.LeftController.wrist;a&&(a.getWorldPosition(this.posLeftHand),a.getWorldQuaternion(this.rotLeftHand))}if(n.RightController?.hand?.visible){let a=n.RightController.wrist;a&&(a.getWorldPosition(this.posRightHand),a.getWorldQuaternion(this.rotRightHand))}}sendAsBuffer(e,t){e.clear();let i=e.createString(this.guid),n=e.createString(this.avatarId);Me.startVrUserStateBuffer(e),Me.addGuid(e,i),Me.addTime(e,Bv(this.time)),Me.addAvatarId(e,n),Me.addPosition(e,Ce.createVec3(e,this.position.x,this.position.y,this.position.z)),Me.addRotation(e,bi.createVec4(e,this.rotation.x,this.rotation.y,this.rotation.z,this.rotation.w)),Me.addScale(e,this.scale),Me.addPosLeftHand(e,Ce.createVec3(e,this.posLeftHand.x,this.posLeftHand.y,this.posLeftHand.z)),Me.addPosRightHand(e,Ce.createVec3(e,this.posRightHand.x,this.posRightHand.y,this.posRightHand.z)),Me.addRotLeftHand(e,bi.createVec4(e,this.rotLeftHand.x,this.rotLeftHand.y,this.rotLeftHand.z,this.rotLeftHand.w)),Me.addRotRightHand(e,bi.createVec4(e,this.rotRightHand.x,this.rotRightHand.y,this.rotRightHand.z,this.rotRightHand.w));let r=Me.endVrUserStateBuffer(e);e.finish(r,Qc);let o=e.asUint8Array();t.sendBinary(o)}setFromBuffer(e,t){if(!e)return;this.guid=e,this.time=t.time().toFloat64();let i=t.avatarId();i&&(this.avatarId=i);let n=t.position();n&&this.position.set(n.x(),n.y(),n.z());let r=t.rotation();r&&this.rotation.set(r.x(),r.y(),r.z(),r.w());let o=t.posLeftHand();o&&this.posLeftHand.set(o.x(),o.y(),o.z());let s=t.posRightHand();s&&this.posRightHand.set(s.x(),s.y(),s.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()}},Ht=bs;z(Ht,"invertRotation",new yt.Quaternion().setFromAxisAngle(new yt.Vector3(0,1,0),Math.PI)),z(Ht,"quat0",new yt.Quaternion),z(Ht,"quat1",new yt.Quaternion);var qi=class extends M{webXR=null;debugAvatarUser=null;voip=null;async awake(){if(this.webXR||(this.webXR=this.gameObject.getComponent($)),this.webXR||(this.webXR=S.findObjectOfType($,this.context)),!this.webXR&&(console.log("Missing webxr component"),this.webXR=S.findObjectOfType($,this.context),!this.webXR)){console.error("Could not find webxr component");return}if(this.voip||(this.voip=S.findObjectOfType(Ke,this.context)),gs){let e="debug-avatar-"+gs,t=new Lt(this.context,e,this.webXR);if(this.debugAvatarUser=t,typeof gs=="string"&&gs.length>0)if(await t.setAvatarOverride(gs)){let i=new Ht(e);i.position.y+=1;let n=.5;i.posLeftHand.y+=n,i.posLeftHand.x+=n,i.posRightHand.y+=n,i.posRightHand.x-=n,t.tryUpdate(i,0)}else t.destroy()}}onEnable(){if(!this.webXR&&(this.webXR=S.getComponent(this.gameObject,$),!this.webXR)){console.warn("Missing webxr component on "+this.gameObject.name);return}this.eventSub_WebXRStartEvent=this.onXRSessionStart.bind(this),$.addEventListener("xrStarted",this.eventSub_WebXRStartEvent),this.eventSub_WebXRUpdateEvent=this.onXRSessionUpdate.bind(this),$.addEventListener("xrUpdate",this.eventSub_WebXRUpdateEvent),this.eventSub_WebXREndEvent=this.onXRSessionEnded.bind(this),$.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(Qc,e=>{let t=e.guid();if(!t)return;let i=e.time().toFloat64(),n=this.tempState;n.setFromBuffer(t,e),this.onTryGetAvatar(t,i)?.tryUpdate(n,i)}),this.context.connection.beginListen("vr-session-update",e=>{let t=e.guid,i=e.time;this.onTryGetAvatar(t,i)?.tryUpdate(e,i)})}tempState=new Ht("");onTryGetAvatar(e,t){if(e===this.context.connection.connectionId)return null;let i=new Date().getTime()-t;if(i>5e3)return wp&&console.log("old data",i,e),null;let n=this.avatars[e];if(n===void 0)try{console.log("create new avatar");let r=new Lt(this.context,e,this.webXR);n=r,this.avatars[e]=r}catch(r){this.avatars[e]=null,console.error(r)}return n}onDisable(){this.eventSub_ConnectionEvent&&this.context.connection.stopListening("joined-room",this.eventSub_ConnectionEvent),$.removeEventListener("xrStarted",this.eventSub_WebXRStartEvent),$.removeEventListener("xrUpdate",this.eventSub_WebXRUpdateEvent),$.removeEventListener("xrStopped",this.eventSub_WebXREndEvent)}update(){let e=Xc();this.debugAvatarUser&&(this.debugAvatarUser.lastUpdate=e),this.detectPotentiallyDisconnectedAvatarsAndRemove();for(let t in this.avatars){let i=this.avatars[t];!i||i.update()}}_removeAvatarsList=[];detectPotentiallyDisconnectedAvatarsAndRemove(){let e=Xc();for(let t in this.avatars){let i=this.avatars[t];if(!i){this._removeAvatarsList.push(t);continue}e-i.lastUpdate>1e4&&(console.log("avatar timed out (didnt receive any updates in a while) - destroying it now"),i.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 Lt(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(){wp&&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 ft(1024);onXRSessionUpdate(e){this.xrState??=new Ht(this.context.connection.connectionId??this.k_LocalAvatarNoNetworkingGuid),this.ownership??=new En(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:i,rig:n}=e,r=t.getViewerPose(i.getReferenceSpace());if(!r)return;let o=r?.transform,s=o.position,c=o.orientation;this.xrState.update(n,s,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 N("avatar")}};async function Fv(){return"xr"in navigator?await navigator.xr.isSessionSupported("immersive-ar")===!0:!1}async function Nv(){return"xr"in navigator?await navigator.xr.isSessionSupported("immersive-vr")===!0:!1}var Yc=!1,Zc=!1;Fv().then(l=>Yc=l);Nv().then(l=>Zc=l);var Ne=class extends M{enableVR=!0;enableAR=!0;defaultAvatar;createVRButton=!0;createARButton=!0;static get IsInWebXR(){return this._isInXr}static get XRSupported(){return"xr"in navigator&&(Yc||Zc)}static get IsARSupported(){return Yc}static get IsVRSupported(){return Zc}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){Ne.XRSupported||console.warn("WebXR is not supported on this device");let i=no.createButton(e.context.renderer);return i.classList.add("webxr-ar-button"),i.classList.add("webxr-button"),this.resetButtonStyles(i),(t?.registerClick??!0)&&i.addEventListener("click",e.onClickedVRButton.bind(e)),i}static createARButton(e,t){let i=e.webAR?.getAROverlayContainer(),n={requiredFeatures:["hit-test"]};i&&(n.domOverlay={root:i},n.optionalFeatures=["dom-overlay"]);let r=Ia.createButton(e.context.renderer,n);return r.classList.add("webxr-ar-button"),r.classList.add("webxr-button"),Ne.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}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=tt.getOrCreate(this.sourceId??"/",this.defaultAvatar,this.context)),!S.findObjectOfType(qi,this.context)){let e=S.addNewComponent(this.gameObject,qi,!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 On(this);let e=Ne.XRSupported,t,i,n=document.createElement("div");n.classList.add("webxr-buttons"),this.context.domElement.append(n),this.enableAR&&this.createARButton&&(t=Ne.createARButton(this),this._arButton=t,n.appendChild(t)),this.createVRButton&&this.enableVR&&(e||!this.enableAR)&&(i=Ne.createVRButton(this),this._vrButton=i,n.appendChild(i)),setTimeout(()=>{Ne.resetButtonStyles(i),Ne.resetButtonStyles(t)},1e3)}_transformOrientation=new Pe.Quaternion;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 i=e.getViewerPose(this.context.renderer.xr.getReferenceSpace());if(this._currentHeadPose=i,!i)return;let n=i?.transform;n&&this._transformOrientation.set(n.orientation.x,n.orientation.y,n.orientation.z,n.orientation.w);for(let r of this.controllers)r.onUpdate(t);this._isInAR&&this.webAR?.onUpdate(t,e)}Ne._isInXr===!1&&t&&this.onEnterXR(t,e),Ne.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++)ae.Create(this,e,this.gameObject,0);Ne.events.dispatchEvent({type:"requestVRSession"})}}captureCameraState(){this.context.mainCamera&&(this._originalCameraPosition.copy(q(this.context.mainCamera)),this._originalCameraRotation.copy(ve(this.context.mainCamera)),this._originalCameraParent=this.context.mainCamera.parent)}ensureRig(){if(!this.rig){let e=S.findObjectOfType(Pn,this.context);e?(this.rig=e.gameObject,this.rig.rotateY(Math.PI)):(this.rig=new Pe.Group,this.rig.name="XRRig",this.context.scene.add(this.rig))}}_originalCameraParent=null;_originalCameraPosition=new Pe.Vector3;_originalCameraRotation=new Pe.Quaternion;onEnterXR(e,t){console.log("[XR] session begin",e),Ne._isInXr=!0,this.ensureRig();let i=this.context.renderer.xr.getReferenceSpace();if(i&&this.rig){let s=t.getViewerPose(i)?.transform.orientation;if(s){let c=new Pe.Quaternion(s.x,s.y,s.z,s.w),d=new Pe.Euler().setFromQuaternion(c);this.rig.rotateY(d.y)}}let n=this.context.renderer.xr;if(this.context.mainCamera){let o=n.getCamera(this.context.mainCamera);for(let s of o.cameras)s.layers.enableAll();this.rig.add(this.context.mainCamera)}let r=this._requestedAR?2:4;switch(vt.Global.Set(r),r){case 2:this._isInAR=!0,this.webAR?.onBegin(e);break;case 4:this._isInVR=!0,this.onEnterVR(e);break}e.addEventListener("end",()=>{console.log("[XR] session end"),Ne._isInXr=!1,this.onExitXR(e)}),this.onEnterXR_HandleMirrorWindow(e),Ne.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.xrMirrorWindow&&(this.xrMirrorWindow.close(),this.xrMirrorWindow=null),this.destroyControllers(),this.context.mainCamera&&(this._originalCameraParent?.add(this.context.mainCamera),ie(this.context.mainCamera,this._originalCameraPosition),Ae(this.context.mainCamera,this._originalCameraRotation),this.context.mainCamera.scale.set(1,1,1)),vt.Global.Set(17),Ne.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){!N("mirror")||setTimeout(()=>{if(!Ne.IsInWebXR)return;let t=new URL(window.location.href);Ir(t.searchParams,ro,1),Ir(t.searchParams,"isMirror",1);let i=t.toString();this.xrMirrorWindow=window.open(i,"webxr sync","popup=yes"),this.xrMirrorWindow&&(this.xrMirrorWindow.onload=()=>{this.xrMirrorWindow&&(this.xrMirrorWindow.onbeforeunload=()=>{Ne.IsInWebXR&&e.end()})})},1e3)}},$=Ne;z($,"_isInXr",!1),z($,"events",new Pe.EventDispatcher),k([A(tt)],$.prototype,"defaultAvatar",2);var so=class{webxr;reticle=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;getAROverlayContainer(){return this.arDomOverlay=this.webxr.context.domElement,this.arOverlayElement=this.arDomOverlay.getAROverlayContainer(),this.arOverlayElement}setReticleActive(e){this.reticleActive=e}onBegin(e){let t=this.webxr.context;this.reticleActive=!0;for(let i=0;i<4;i++)ae.Create(this.webxr,i,this.webxr.gameObject,1);(!this.sessionRoot||this.sessionRoot.destroyed||!this.sessionRoot.activeAndEnabled)&&(this.sessionRoot=S.findObjectOfType(Dt,t)),this.previousBackground=t.scene.background,this.previousEnvironment=t.scene.environment,t.scene.background=null,e.requestReferenceSpace("viewer").then(i=>{e.requestHitTestSource({space:i}).then(n=>{this.hitTestSource=n})}),!this.reticle&&this.sessionRoot&&(this.reticle=new Pe.Mesh(new Pe.RingGeometry(.07,.09,32).rotateX(-Math.PI/2),new Pe.MeshBasicMaterial),this.reticle.name="AR Placement reticle",this.reticle.matrixAutoUpdate=!1,this.reticle.visible=!1,this.webxr.scene?(this.webxr.scene.add(this.reticle),this.webxr.scene.visible=!0):console.warn("Could not found WebXR Rig")),this._previousParent=this.webxr.gameObject,so.tempWebXRObject||(so.tempWebXRObject=new Pe.Object3D),this.context.scene.add(so.tempWebXRObject),S.addComponent(so.tempWebXRObject,this.webxr),this.sessionRoot?(this.sessionRoot.webAR=this,this.sessionRoot?.onBegin(e)):console.warn("No WebARSessionRoot found in scene"),this.arDomOverlay&&this.arOverlayElement&&this.arDomOverlay.onEnterAR(e,this.arOverlayElement),this.context.mainCameraComponent?.applyClearFlagsIfIsActiveCamera()}onEnd(e){this._previousParent&&(console.log("ADD",this._previousParent),S.addComponent(this._previousParent,this.webxr),this._previousParent=null),this.hitTestSource=null;let t=this.webxr.context;t.scene.background=this.previousBackground,t.scene.environment=this.previousEnvironment,this.sessionRoot&&this.sessionRoot.onEnd(this.webxr.Rig,e),this.arDomOverlay&&this.arDomOverlay.onExitAR(e),this.context.mainCameraComponent?.applyClearFlagsIfIsActiveCamera()}onUpdate(e,t){if(!this.hitTestSource)return;let i=t.getHitTestResults(this.hitTestSource);if(i.length){let n=i[0],r=this.webxr.context.renderer.xr.getReferenceSpace();if(r){let o=n.getPose(r);if(this.sessionRoot?.onUpdate(this.webxr.Rig,e,o),this.reticle&&(this.reticle.visible=this.reticleActive,this.reticleActive&&o)){let s=o.transform.matrix;this.reticle.matrix.fromArray(s),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)}},On=so;z(On,"tempWebXRObject");var Jc=!1;var ao=class extends kt{static get HasAnySelected(){return this._active!==null}transformSelf=!0;selectStartEventListener=[];selectEndEventListener=[];constructor(){super(),this.selectStartEventListener=[],this.selectEndEventListener=[],this._dragDelta=new ee.Vector2}addDragEventListener(e,t){switch(e){case"selectstart":this.selectStartEventListener.push(t);break;case"selectend":this.selectEndEventListener.push(t);break}}_dragHelper=null;start(){}_draggingRigidbodies=[];allowEdit(e=null){return this.context.connection.allowEditing}onPointerEnter(e){if(!this.allowEdit(this.gameObject)||$.IsInWebXR)return;let t=S.getComponentInParent(e.object,ao);!t||t!==this||(ao.lastHovered=e.object,this.context.domElement.style.cursor="pointer")}onPointerExit(e){!this.allowEdit(this.gameObject)||$.IsInWebXR||ao.lastHovered===e.object&&(this.context.domElement.style.cursor="auto")}_waitingForDragStart=null;onPointerDown(e){!this.allowEdit(this.gameObject)||$.IsInWebXR||(this._dragDelta.set(0,0),this._didDrag=!1,this._waitingForDragStart=e,e.StopPropagation())}onPointerUp(e){this._waitingForDragStart=null,this.allowEdit(this.gameObject)&&($.IsInWebXR||(this.onDragEnd(e),e.StopPropagation()))}update(){if(!$.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&&this.onDragEnd(null)}}_isDragging=!1;_marker=null;_dragDelta;_didDrag=!1;onDragStart(e){if(!this._dragHelper)if(this.context.mainCamera)this._dragHelper=new ja(this.context.mainCamera);else return;if(!e||!e.object)return;let t=S.getComponentInParent(e.object,ao);if(!t||t!==this)return;let i=e.object;this.transformSelf&&(i=this.gameObject);let n={selected:i,attached:i};for(let c of this.selectStartEventListener)c(this,n);if(!n.attached)return;n.attached,i=n.attached,this._isDragging=!0,this._dragHelper.setSelected(i,this.context);let r=S.getComponentInChildren(i,Qe);Jc&&console.log("DRAG START",r,i),r&&(r.fastMode=!0,r?.requestOwnership()),this._marker=S.addNewComponent(i,It),this._draggingRigidbodies.length=0;let o=S.getComponentsInChildren(i,ce);o&&this._draggingRigidbodies.push(...o);let s=El();S.invokeOnChildren(this._dragHelper.selected,s("onDragStart"))}onUpdateDrag(){if(!!this._dragHelper){this._dragHelper.onUpdate(this.context);for(let e of this._draggingRigidbodies)e.wakeUp(),e.setBodyFromGameObject()}}onDragEnd(e){if(!this||!this._isDragging||(this._isDragging=!1,!this._dragHelper))return;this._draggingRigidbodies.length=0;let t=this._dragHelper.selected;if(Jc&&console.log("DRAG END",t,t?.visible),this._dragHelper.setSelected(null,this.context),e?.object){let n=S.getComponentInChildren(e.object,Qe);n&&(n.fastMode=!1),this._marker&&this._marker.destroy()}for(let n of this.selectEndEventListener)n(this);let i=El();S.invokeOnChildren(t,i("onDragEnd"))}},Et=ao;z(Et,"_active",null),z(Et,"lastHovered");var $c=class{get hasSelected(){return this._selected!==null&&this._selected!==void 0}get selected(){return this._selected}_selected=null;_context=null;_camera;_cameraPlane=new ee.Plane;_hasGroundPlane=!1;_groundPlane=new ee.Plane;_groundOffset=new ee.Vector3;_groundOffsetFactor=0;_groundDistance=0;_groundPlanePoint=new ee.Vector3;_raycaster=new ee.Raycaster;_cameraPlaneOffset=new ee.Vector3;_intersection=new ee.Vector3;_worldPosition=new ee.Vector3;_inverseMatrix=new ee.Matrix4;_rbs=[];_groundLine;_groundMarker;constructor(e){this._camera=e;let t=new ee.Line($c.geometry),i=t.material;i.color=new ee.Color(.4,.4,.4),t.layers.set(2),t.name="line",t.scale.y=1,this._groundLine=t;let n=new ee.SphereGeometry(.5,22,22),r=new ee.MeshBasicMaterial({color:i.color}),o=new ee.Mesh(n,r);o.visible=!1,o.layers.set(2),this._groundMarker=o}setSelected(e,t){if(this._selected&&t)for(let i of this._rbs)i.wakeUp(),i.smoothedVelocity&&i.setVelocity(i.smoothedVelocity.x,i.smoothedVelocity.y,i.smoothedVelocity.z);if(this._selected&&_e.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}_e.Add(t,this._selected,null),this._groundOffsetFactor=0,this._hasGroundPlane=!0,this._groundOffset.set(0,0,0),this._requireUpdateGroundPlane=!0,this._rbs=S.getComponentsInChildren(this._selected,ce),this.onUpdateScreenSpacePlane()}}_groundOffsetVector=new ee.Vector3(0,1,0);_requireUpdateGroundPlane=!0;_didDragOnGroundPlaneLastFrame=!1;onUpdate(e){if(!this._context)return;let t=32,i=68,n=83,r=this._context?.input.isKeyPressed(t)||this._context?.input.isKeyPressed(i),o=this._context.input.getTouchesPressedCount()>=2||r;if(o){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 s=this._context.input.getPointerPositionRC(0);if(!!s&&(this._raycaster.setFromCamera(s,this._camera),this._selected)){Jc&&console.log("UPDATE DRAG",this._selected),this._groundOffsetVector.set(0,1,0);let c=q(this._camera).clone().sub(q(this._selected)).normalize(),d=Math.abs(c.dot(this._groundOffsetVector)),a=this._context?.input.isKeyPressed(t)||this._context?.input.isKeyPressed(i),h=!o&&d>.2&&!a&&this._context.input.getPointerPressedCount()<=1,u=this._didDragOnGroundPlaneLastFrame!==h;if(this._didDragOnGroundPlaneLastFrame=h,this._hasGroundPlane||(this._requireUpdateGroundPlane=!0),(this._requireUpdateGroundPlane||!h||u)&&this.onUpdateGroundPlane(),this._requireUpdateGroundPlane=!1,this._hasGroundPlane)if(this._raycaster.ray.intersectPlane(this._groundPlane,this._intersection)){let f=this._intersection.y;if(this._groundPlanePoint.copy(this._intersection).sub(this._groundOffset),this._groundPlanePoint.y=f,h){this._groundOffsetVector.set(0,1,0);let E=this._intersection.sub(this._groundOffset).add(this._groundOffsetVector.multiplyScalar(this._groundOffsetFactor));this.onUpdateWorldPosition(E,this._groundPlanePoint,!1),this.onDidUpdate();return}}else this._groundPlanePoint.set(0,99999,0);u&&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,i){if(!!this._selected){if(i){let n=q(this._selected);n.y=e.y,e=n}if(ie(this._selected,e),ie(this._groundLine,e),this._hasGroundPlane?this._groundLine.scale.y=this._groundDistance:this._groundLine.scale.y=1e3,this._groundMarker.visible=t!==null,t){let n=q(this._camera).distanceTo(t)*.01;this._groundMarker.scale.set(n,n,n),ie(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=q(this._selected),t=new ee.Ray(new ee.Vector3(0,.1,0).add(e),new ee.Vector3(0,-1,0)),i=new je;i.ignore=[this._selected];let n=this._context.physics.raycastFromRay(t,i);for(let r=0;r<n.length;r++){let o=n[r];if(!o.face||this.contains(this._selected,o.object))continue;let s=new ee.Vector3(0,1,0);this._groundPlane.setFromNormalAndCoplanarPoint(s,o.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(){he.markDirty(this._selected);for(let e of this._rbs)e.wakeUp(),e.setBodyFromGameObject({x:0,y:0,z:0}),e.setAngularVelocity(0,0,0)}contains(e,t){if(e===t)return!0;if(e.children){for(let i of e.children)if(this.contains(i,t))return!0}return!1}},ja=$c;z(ja,"geometry",new ee.BufferGeometry().setFromPoints([new ee.Vector3(0,0,0),new ee.Vector3(0,-1,0)]));var An=class extends M{filesBackendUrl;localhost;_dragOver;_drop;onEnable(){this.filesBackendUrl=this.filesBackendUrl?pt.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 i in t){let n=t[i];if(n.kind==="file"){let r=n.getAsFile();if(!r)continue;console.log("Register file "+r.name+" to",this.filesBackendUrl,r);let o=await xp(r,this.context,this.filesBackendUrl);o&&this.addObject(e,o)}else n.kind==="string"&&n.type=="text/plain"&&n.getAsString(async r=>{console.log("dropped url",r);try{let o=new URL(r);if(!o)return;let s=await Tp(o,this.context);s&&this.addObject(e,s)}catch{console.log("dropped string is not a valid URL!",r)}})}}async addObject(e,t){console.log("Dropped",t);let i=new je;i.setMask(16777215),i.screenPointFromOffset(e.offsetX,e.offsetY);let n=this.context.physics.raycast(i),r=t.scene;if(n&&n.length>0)for(let o of n){r.position.copy(o.point);break}this.gameObject.add(r),this.dispatchEvent(new CustomEvent("object-added",{detail:t}))}};k([A()],An.prototype,"filesBackendUrl",2),k([A()],An.prototype,"localhost",2);import{Vector3 as Gv,Quaternion as Vv,Object3D as Rp}from"three";var vi=class extends kt{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 Gv(0,0,0),this._startQuaternion=this.object.quaternion?.clone()??new Vv(0,0,0,1)}let e=S.getComponentInParent(this.gameObject,Et);e?e.addDragEventListener("selectstart",(t,i)=>{if(this._currentCount>=this.limitCount){i.attached=null;return}let n=this.handleDuplication(i.selected);n&&(console.assert(n!==i.selected,"Duplicated object is original"),i.attached=n)}):console.warn("Could no find drag controls in parent",this.name),ae.addEventListener("select-start",(t,i)=>{if(this._currentCount>=this.limitCount){i.grab=null;return}let n=this.handleDuplication(i.selected);n&&(i.grab=n)}),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 ye;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 i=S.instantiateSynced(this.object,t);return console.assert(i!==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),i}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 i of e.children)if(this.isInChildren(i,t))return!0}return!1}};k([A(Rp)],vi.prototype,"parent",2),k([A(Rp)],vi.prototype,"object",2),k([A()],vi.prototype,"limitCount",2),k([A()],vi.prototype,"limitInterval",2);var yi=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)}}},Wv=l=>/^[A-Z]*$/.test(l),pr=class extends Event{args},Oe=class{target;key;setEventTarget(e,t){if(this.key=e,this.target=t,this.key!==void 0){let i="",n=!1;for(let r of this.key)n&&Wv(r)&&(i+="-"),n=!0,i+=r.toLowerCase();this.key=i}}_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 i=new pr(this.key);i.args=e,t.call(this.target,i)}}}finally{this._isInvoking=!1}}addEventListener(e){return this.methods.push(new yi(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}};var lo=class extends M{};import{FlyControls as Uv}from"three/examples/jsm/controls/FlyControls";var co=class extends M{_controls=null;onEnable(){let e=S.getComponent(this.gameObject,ne)?.cam;this._controls=new Uv(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 Sp from"three";import{Color as qv}from"three";var Xi=class extends M{objectBounds=!1;color;isGizmo=!0;_gizmoObject=null;_boxHelper=null;onEnable(){this.isGizmo&&!hi||(this._gizmoObject||(this.objectBounds&&this.gameObject.isMesh===!0?this._gizmoObject=new Sp.BoxHelper(this.gameObject,this.color??16776960):(this.objectBounds=!1,this._gizmoObject=Sa(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}};k([A()],Xi.prototype,"objectBounds",2),k([A(qv)],Xi.prototype,"color",2),k([A()],Xi.prototype,"isGizmo",2);import{GLTFExporter as Zv}from"three/examples/jsm/exporters/GLTFExporter.js";import{BufferAttribute as Kc,Matrix4 as Xv,Vector3 as Pp,Quaternion as Qv}from"three";var vs=class{constructor(e){this.writer=e,this.name="EXT_mesh_gpu_instancing"}writeNode(e,t){if(e.constructor.name!=="InstancedMesh")return;let i=this.writer,n=i.extensionsUsed,r={};t.extensions=t.extensions||{},t.extensions[this.name]=r;let o=new Xv,s=new Array,c=new Array,d=new Array;for(let f=0;f<e.count;f++){e.getMatrixAt(f,o);let E=new Pp,b=new Qv,y=new Pp;o.decompose(E,b,y),s.push(E.x,E.y,E.z),c.push(b.x,b.y,b.z,b.w),d.push(y.x,y.y,y.z)}let a=new Float32Array(s),h=new Float32Array(c),u=new Float32Array(d);r.attributes={TRANSLATION:i.processAccessor(new Kc(a,3)),ROTATION:i.processAccessor(new Kc(h,4)),SCALE:i.processAccessor(new Kc(u,3))},n[this.name]=!0}};import{Object3D as Jv,Vector3 as $v}from"three";var kn=Ie,Fa="$___Export_Components",Yv="NEEDLE_components",ed=class{[qn]},td=class{node;nodeIndex;nodeDef;constructor(e,t,i){this.node=e,this.nodeIndex=t,this.nodeDef=i}},ho=class{get name(){return Yv}parser;nodeToObjectMap={};exportContext;objectToNodeMap={};context;writer;registerExport(e){e.register(t=>{let i=t.serializeUserData.bind(t);return this.writer=t,t.serializeUserData=(n,r)=>{try{this.serializeUserData(n,r),i(n,r)}finally{this.afterSerializeUserData(n,r)}},this})}beforeParse(){this.exportContext={},this.objectToNodeMap={}}serializeUserData(e,t){let i=e.userData?.components;!i||i.length<=0||(delete e.userData.components,e[Fa]=i)}afterSerializeUserData(e,t){if(e.type==="Scene"&&kn&&console.log("DONE",JSON.stringify(t)),e[Fa]===void 0)return;let i=e[Fa];delete e[Fa],i!==null&&(e.userData.components=i)}writeNode(e,t){let i=this.writer.json.nodes.length;console.log(e.name,i,e.uuid);let n=new td(e,i,t);this.exportContext[i]=n,this.objectToNodeMap[e.uuid]=i}afterParse(e){kn&&console.log("AFTER",e);for(let t in this.exportContext){let i=this.exportContext[t],n=i.node,r=i.nodeDef,o=i.nodeIndex,s=n.userData?.components;if(!s||s.length<=0)continue;let c=new ed;r.extensions=r.extensions||{},r.extensions[this.name]=c,this.context.object=n,this.context.nodeId=o,this.context.objectToNode=this.objectToNodeMap;let d=[];for(let a of s){this.context.target=a;let h=Op(a,this.context);h!==null&&d.push(h)}d.length>0&&(c[qn]=d,kn&&console.log("DID WRITE",n,"nodeIndex",o,d))}}beforeRoot(){return kn&&console.log("BEGIN LOAD"),this.nodeToObjectMap={},null}async afterRoot(e){let t=e.parser,i=t?.extensions;if(!i)return;let n=i[this.name];kn&&console.log("After root",e,this.parser,i);let r=[];if(n===!0){let o=t.json.nodes;for(let s=0;s<o.length;s++){let c=await t.getDependency("node",s);this.nodeToObjectMap[s]=c}for(let s=0;s<o.length;s++){let c=o[s],d=s,a=c.extensions;if(!a)continue;let h=a[this.name];if(!h)continue;kn&&console.log("NODE",c);let u=this.nodeToObjectMap[d];if(!u){console.error("Could not find object for node index: "+d,c,t);continue}r.push(this.createComponents(u,h))}}await Promise.all(r)}async createComponents(e,t){if(!t)return;let i=t[qn];if(i){kn&&console.log(e.name,i);for(let n in i){let r=i[n];kn&&console.log("Serialized data",JSON.parse(JSON.stringify(r))),r&&this.parser&&await Ur(this.parser,r),e.userData=e.userData||{},e.userData[qn]=e.userData[qn]||[],e.userData[qn].push(r)}}}};var uo=class extends lt{sceneRoot;start(){this.startCoroutine(this.updateGltfBox())}*updateGltfBox(){for(;;)for(let e=0;e<10;e++)yield}},jt=class extends M{binary=!0;objects=[];exporter;ext;async exportNow(e){console.log("DO EXPORT",this.objects);let t={binary:this.binary,pivot:jt.calculateCenter(this.objects)},i=await this.export(this.objects,t);this.binary?e.endsWith(".glb")||(e+=".glb"):e.endsWith(".gltf")||(e+=".gltf"),this.binary?jt.saveArrayBuffer(i,e):jt.saveJson(i,e)}async export(e,t){if(e===null||e.length<=0){console.log("no objects set to export");return}this.exporter||(this.exporter=new Zv,this.exporter.register(s=>new vs(s)),this.ext=new ho,this.ext.registerExport(this.exporter)),jt.filterTopmostParent(e);let i={trs:!1,onlyVisible:!0,truncateDrawRange:!1,binary:t?.binary??!0,maxTextureSize:1/0,embedImages:!0,includeCustomExtensions:!0,animations:jt.collectAnimations(e)},n=new Jv;t?.pivot&&n.position.sub(t.pivot),console.log("EXPORT",e),e.forEach(s=>{s&&(n.children.push(s),s.matrixAutoUpdate=!1,s.matrix.copy(s.matrixWorld),S.getComponentsInChildren(s,Te).forEach(c=>{S.isActiveInHierarchy(c.gameObject)&&c.setInstancingEnabled(!1)}))});let r=new qr(n);return this.ext.context=r,new Promise((s,c)=>{try{this.exporter?.parse(n,d=>{o(),s(d)},d=>{o(),c(d)},i)}catch(d){console.error(d),c(d)}finally{console.log("FINALLY")}});function o(){e.forEach(s=>{!s||(s.matrixAutoUpdate=!0,S.getComponentsInChildren(s,Te).forEach(c=>{S.isActiveInHierarchy(c.gameObject)&&c.setInstancingEnabled(!1)}))})}}static saveArrayBuffer(e,t){this.save(new Blob([e],{type:"application/octet-stream"}),t)}static saveJson(e,t){this.save("data: text/json;charset=utf-8,"+encodeURIComponent(JSON.stringify(e)),t)}static save(e,t){let i=document.createElement("a");i.style.display="none",document.body.appendChild(i),typeof e=="string"?i.href=e:i.href=URL.createObjectURL(e),i.download=t,i.click(),i.remove()}static collectAnimations(e,t){t=t||[];for(let i of e)!i||i.traverseVisible(n=>{n.animations&&n.animations.length>0&&t.push(...n.animations)});return t}static calculateCenter(e,t){let i=t||new $v;return i.set(0,0,0),e.forEach(n=>{i.add(q(n))}),console.log(i),i.divideScalar(e.length),i}static filterTopmostParent(e){if(!(e.length<=0))for(let t=0;t<e.length;t++){let i=e[t];if(!i){e.splice(t,1),t--;continue}for(;i.parent;){if(e.includes(i.parent)){e.splice(t,1),t--;break}i=i.parent}}}};import{Color as Na,GridHelper as Kv}from"three";var Qi=class extends M{isGizmo=!1;color0;color1;gridHelper;size;divisions;offset;onEnable(){if(this.isGizmo&&!hi)return;let e=this.size,t=this.divisions;this.gridHelper||(this.gridHelper=new Kv(e,t,this.color0??new Na(.4,.4,.4),this.color1??new Na(.6,.6,.6)),this.offset!==void 0&&(this.gridHelper.position.y+=this.offset),this.gameObject.add(this.gridHelper))}};k([A()],Qi.prototype,"isGizmo",2),k([A(Na)],Qi.prototype,"color0",2),k([A(Na)],Qi.prototype,"color1",2);import{GroundProjectedEnv as ey}from"three/examples/jsm/objects/GroundProjectedEnv.js";var Yi=class extends M{set scale(e){this._scale=e,this.env?.scale.setScalar(e)}get scale(){return this._scale}_scale=20;set radius(e){this._radius=e,this.env&&(this.env.height=e)}get radius(){return this._radius}_radius=100;set height(e){this._height=e,this.env&&(this.env.height=e)}get height(){return this._height}_height=100;_lastEnvironment;env;_watcher;onEnable(){this.updateProjection(),this._watcher||(this._watcher=new As(this.context.scene,"environment"),this._watcher.subscribeWrite(this.updateProjection.bind(this))),this._watcher.apply()}onDisable(){this._watcher?.revoke(),this.env?.removeFromParent()}updateProjection(){!this.context.scene.environment||((!this.env||this.context.scene.environment!==this._lastEnvironment)&&(console.log("Create/Update Ground Projection",this.context.scene.environment.name),this.env=new ey(this.context.scene.environment)),this._lastEnvironment=this.context.scene.environment,this.env.parent||this.gameObject.add(this.env),this.env.scale.setScalar(this._scale),this.env.radius=this._radius,this.env.height=this._height,this.env.isObject3D===!0&&this.env.layers.set(2))}};k([A()],Yi.prototype,"scale",1),k([A()],Yi.prototype,"radius",1),k([A()],Yi.prototype,"height",1);import*as it from"three";import{Color as ty}from"three";function id(l){return l*Math.PI/180}var Ap=300,kp=N("debuglights");var Ye=class extends M{type=0;range=1;spotAngle=1;innerSpotAngle=1;color=new it.Color(16777215);set shadowNearPlane(e){if(e!==this._shadowNearPlane&&(this._shadowNearPlane=e,this.light?.shadow?.camera!==void 0)){let t=this.light.shadow.camera;t.near=e}}get shadowNearPlane(){return this._shadowNearPlane}_shadowNearPlane=.1;set shadowBias(e){e!==this._shadowBias&&(this._shadowBias=e,this.light?.shadow?.bias!==void 0&&(this.light.shadow.bias=e,this.light.shadow.needsUpdate=!0))}get shadowBias(){return this._shadowBias}_shadowBias=0;set shadowNormalBias(e){e!==this._shadowNormalBias&&(this._shadowNormalBias=e,this.light?.shadow?.normalBias!==void 0&&(this.light.shadow.normalBias=e,this.light.shadow.needsUpdate=!0))}get shadowNormalBias(){return this._shadowNormalBias}_shadowNormalBias=1;set shadows(e){this._shadows=e,this.light&&(this.light.castShadow=e===1||e===2)}get shadows(){return this._shadows}_shadows=1;lightmapBakeType=4;set intensity(e){if(this._intensity=e,this.light){let t=1;if(this.context.isInXR&&this._webARRoot){let i=this._webARRoot?.arScale;typeof i=="number"&&i>0&&(t/=i)}this.light.intensity=e*t}}get intensity(){return this._intensity}_intensity=1;get shadowDistance(){let e=this.light;return e?e.shadow.camera.far:-1}set shadowDistance(e){this._shadowDistance=e;let t=this.light;if(t){let i=t.shadow.camera;i.far=e,i.updateProjectionMatrix()}}_shadowDistance;shadowWidth;shadowHeight;get shadowResolution(){let e=this.light;return e?e.shadow.mapSize.x:-1}set shadowResolution(e){if(e===this._shadowResolution)return;this._shadowResolution=e;let t=this.light;t&&(t.shadow.mapSize.set(e,e),t.shadow.needsUpdate=!0)}_shadowResolution=void 0;get isBaked(){return this.lightmapBakeType===2}get selfIsLight(){if(this.gameObject.isLight===!0)return!0;switch(this.gameObject.type){case"SpotLight":case"PointLight":case"DirectionalLight":return!0}return!1}light=void 0;getWorldPosition(e){return this.light?this.type===1?this.light.getWorldPosition(e).multiplyScalar(1):this.light.getWorldPosition(e):e}updateIntensity(){this.intensity=this._intensity}awake(){this.color=new it.Color(this.color??16777215)}onEnable(){this.createLight(),!this.isBaked&&(this.light&&(this.selfIsLight||this.light.parent!==this.gameObject&&this.gameObject.add(this.light)),this.type===1&&this.startCoroutine(this.updateMainLightRoutine(),2),this._webXRStartedListener=$.addEventListener("xrStarted",this.onWebXRStarted.bind(this)),this._webXREndedListener=$.addEventListener("xrStopped",this.onWebXREnded.bind(this)))}onDisable(){$.removeEventListener("xrStarted",this._webXRStartedListener),$.removeEventListener("xrStopped",this._webXREndedListener)}_webXRStartedListener;_webXREndedListener;_webARRoot;onWebXRStarted(){this._webARRoot=this.gameObject.getComponentInParent(Dt)??void 0,this.startCoroutine(this._updateLightIntensityInARRoutine())}*_updateLightIntensityInARRoutine(){for(;this.context.isInXR;){yield,this.updateIntensity();for(let e=0;e<30;e++)yield}}onWebXREnded(){this.updateIntensity()}createLight(){if(this.light)return;let e=this.selfIsLight;if(e)switch(this.light=this.gameObject,this.type){case 1:this.setDirectionalLight(this.light);break}else switch(this.type){case 1:let t=new it.DirectionalLight(this.color,this.intensity*Math.PI);if(t.position.set(0,0,-Ap*.5).applyQuaternion(this.gameObject.quaternion),this.gameObject.add(t.target),Mr(t.target,0,0,0),this.light=t,this.gameObject.position.set(0,0,0),this.gameObject.rotation.set(0,0,0),kp){let o=new it.DirectionalLightHelper(this.light,.2,this.color);this.context.scene.add(o)}break;case 0:let i=new it.SpotLight(this.color,this.intensity*Math.PI,this.range,id(this.spotAngle/2),1-id(this.innerSpotAngle/2)/id(this.spotAngle/2),2);i.position.set(0,0,0),i.rotation.set(0,0,0),this.light=i;let n=i.target;i.add(n),n.position.set(0,0,this.range),n.rotation.set(0,0,0);break;case 2:let r=new it.PointLight(this.color,this.intensity*Math.PI,this.range);this.light=r;break}if(this.light!==void 0){this.shadows!==0?this.light.castShadow=!0:this.light.castShadow=!1,this._shadowResolution!==void 0&&this._shadowResolution>4?(this.light.shadow.mapSize.width=this._shadowResolution,this.light.shadow.mapSize.height=this._shadowResolution):(this.light.shadow.mapSize.width=2048,this.light.shadow.mapSize.height=2048),this.light.shadow.bias=this.shadowBias*1e-5,this.light.shadow.normalBias=this.shadowNormalBias*1e-4;let t=this.light.shadow.camera;if(t.near=this.shadowNearPlane,this._shadowDistance!==void 0&&typeof this._shadowDistance=="number"?t.far=this._shadowDistance:t.far=Ap*Math.abs(this.gameObject.scale.z),this.gameObject.scale.set(1,1,1),this.shadowWidth!==void 0)t.left=-this.shadowWidth/2,t.right=this.shadowWidth/2;else{let i=this.gameObject.scale.x;t.left*=i,t.right*=i}if(this.shadowHeight!==void 0)t.top=this.shadowHeight/2,t.bottom=-this.shadowHeight/2;else{let i=this.gameObject.scale.y;t.top*=i,t.bottom*=i}this.light.shadow.needsUpdate=!0,kp&&this.context.scene.add(new it.CameraHelper(t)),this.isBaked?this.light.removeFromParent():e||this.gameObject.add(this.light)}}*updateMainLightRoutine(){for(;;){this.type===1&&((!this.context.mainLight||this.intensity>this.context.mainLight.intensity)&&(this.context.mainLight=this),yield);break}}setDirectionalLight(e){e.add(e.target),e.target.position.set(0,0,-1)}};k([A()],Ye.prototype,"type",2),k([A(ty)],Ye.prototype,"color",2),k([A()],Ye.prototype,"shadowNearPlane",1),k([A()],Ye.prototype,"shadowBias",1),k([A()],Ye.prototype,"shadowNormalBias",1),k([A()],Ye.prototype,"shadows",1),k([A()],Ye.prototype,"lightmapBakeType",2),k([A()],Ye.prototype,"intensity",1),k([A()],Ye.prototype,"shadowDistance",1),k([A()],Ye.prototype,"shadowResolution",1);var XO=new it.Vector3(0,0,0);import*as za from"three";import{Vector3 as iy}from"three";var po=N("debugLODs"),ny=N("noLODs");var Ei=class{screenRelativeTransitionHeight;distance;renderers};k([A()],Ei.prototype,"screenRelativeTransitionHeight",2),k([A()],Ei.prototype,"distance",2),k([A()],Ei.prototype,"renderers",2);var nd=class{model;renderers;constructor(e,t){this.model=t,this.renderers=[];for(let i of t.renderers){let n=this.findRenderer(i,e.gameObject);n&&n.gameObject?this.renderers.push(n):po&&console.warn("Renderer not found: "+i,e.gameObject)}}findRenderer(e,t){let i=S.foreachComponent(t,n=>n.guid===e||Object.getPrototypeOf(n)?.guid===e?n:null);if(i)return i;for(let n of t.children){let r=this.findRenderer(e,n);if(r)return r}return null}},In=class extends M{fadeMode=0;localReferencePoint=void 0;lodCount=0;size=0;animateCrossFading=!1;lodModels;_lods=[];_settings=[];_lodsHandler;start(){if(!ny&&!this._lodsHandler&&!!this.gameObject&&(po&&console.log(this),this.lodModels&&Array.isArray(this.lodModels))){let e=0,t=[];for(let n of this.lodModels){e=Math.max(n.distance,e);let r=new nd(this,n);this._lods.push(r);for(let o of r.renderers)t.includes(o)||t.push(o)}this._lodsHandler=new Array;for(let n=0;n<t.length;n++){let r=new za.LOD;this._lodsHandler.push(r),this.gameObject.add(r)}let i=new za.Object3D;po&&console.log(t);for(let n=0;n<t.length;n++){let r=t[n],o=this._lodsHandler[n],s=r.gameObject,c=0,d=0;po&&console.log(n,s.name);for(let h of this._lods){let u=null;h.renderers.includes(r)?u=s:u=i,po&&console.log("add",h.model.distance,u.name);let f=h.model.distance;d=f-c,c=Math.max(f,c),this.onAddLodLevel(o,u,f)}let a=c+d;po&&console.log("cull",a),this.onAddLodLevel(o,i,a)}}}update(){if(!this.gameObject||!this._lodsHandler)return;let e=this.context.mainCamera;if(!!e)for(let t of this._lodsHandler)t.update(e)}onAddLodLevel(e,t,i){e.addLevel(t,i*this._distanceFactor);let n={lod:e,levelIndex:e.levels.length-1,distance:i};this._settings.push(n)}_distanceFactor=1;distanceFactor(e){if(e!==this._distanceFactor){this._distanceFactor=e;for(let t of this._settings){let i=t.lod.levels[t.levelIndex];i.distance=t.distance*e}}}};k([A(iy)],In.prototype,"localReferencePoint",2),k([A(Ei)],In.prototype,"lodModels",2);var fo=class extends M{},mo=class extends M{};var rd=N("debugnestedgltf"),fr=class extends M{filePath;_isLoadingOrDoneLoading=!1;listenToProgress(e){this.filePath?.beginListenDownload(e)}preload(){this.filePath?.preload()}async start(){if(this._isLoadingOrDoneLoading)return;rd&&console.log(this,this.guid);let e=this.gameObject.parent;if(e){this._isLoadingOrDoneLoading=!0;let t=new ye;t.idProvider=new We(this.hash(this.guid)),t.parent=e,this.gameObject.updateMatrix();let i=this.gameObject.matrix;rd&&console.log("Load nested:",this.filePath?.uri??this.filePath,this.gameObject.position);let n=await this.filePath?.instantiate?.call(this.filePath,t);n&&(n.matrixAutoUpdate=!1,n.matrix.identity(),n.applyMatrix4(i),n.matrixAutoUpdate=!0),this.destroy(),rd&&console.log("Nested loading done:",this.filePath?.uri??this.filePath,n)}}hash(e){let t=0;for(let i=0;i<e.length;i++)t=e.charCodeAt(i)+((t<<5)-t);return t}};k([A(tt)],fr.prototype,"filePath",2);import{Quaternion as ry,Euler as oy,Vector3 as mr,Plane as sy}from"three";var wi=class extends M{referenceSpace;from;affectPosition=!1;affectRotation=!1;alignLookDirection=!1;levelLookDirection=!1;levelPosition=!1;positionOffset=new mr(0,0,0);rotationOffset=new mr(0,0,0);offset=new mr(0,0,0);update(){if(!this.from)return;var e=q(this.from),t=ve(this.from);this.offset.copy(this.positionOffset);let i=this.offset.length();if(this.referenceSpace&&this.offset.transformDirection(this.referenceSpace.matrixWorld).multiplyScalar(i),e.add(this.offset),this.levelPosition&&this.referenceSpace){let s=new sy(this.gameObject.up,0),c=q(this.referenceSpace);s.setFromNormalAndCoplanarPoint(this.gameObject.up,c);let d=new mr(0,0,0);s.projectPoint(e,d),e.copy(d)}this.affectPosition&&ie(this.gameObject,e);let n=new oy(this.rotationOffset.x,this.rotationOffset.y,this.rotationOffset.z),r=new ry().setFromEuler(n);this.affectRotation&&Ae(this.gameObject,t.multiply(r));let o=new mr;this.from.getWorldDirection(o).multiplyScalar(50),this.levelLookDirection&&(o.y=0),this.alignLookDirection&&this.gameObject.lookAt(o)}};k([A(S)],wi.prototype,"referenceSpace",2),k([A(S)],wi.prototype,"from",2),k([A(mr)],wi.prototype,"positionOffset",2),k([A(mr)],wi.prototype,"rotationOffset",2);import*as xe from"three";import*as ei from"three";var go=class{randomizeRotationDirection=0;duration=5;loop=!0;prewarm=!1;startDelay=void 0;startDelayMultiplier=0;startLifetime=void 0;startLifetimeMultiplier=5;startSpeed=void 0;startSpeedMultiplier=5;startSize3D=!1;startSize=void 0;startSizeMultiplier=1;startSizeX=void 0;startSizeXMultiplier=1;startSizeY=void 0;startSizeYMultiplier=1;startSizeZ=void 0;startSizeZMultiplier=1;startRotation3D=!1;startRotation=void 0;startRotationMultiplier=0;startRotationX=void 0;startRotationXMultiplier=0;startRotationY=void 0;startRotationYMultiplier=0;startRotationZ=void 0;startRotationZMultiplier=0;flipRotation=0;startColor=new ei.Color(1,1,1);startColor1=new ei.Color(0,0,0);gravityModifier=void 0;gravityModifierMultiplier=0;simulationSpace=0;customSimulationSpace=null;simulationSpeed=1;useUnscaledTime=!1;scalingMode=1;playOnAwake=!0;maxParticles=1e3;emitterVelocityMode=1;stopAction=0;ringBufferMode=0;ringBufferLoopRange=new ei.Vector2(0,1);cullingMode=0},bo=class{burstCount=0;enabled=!0;rate=10;rateMutliplier=1;rateOverDistance=0;rateOverDistanceMultiplier=0;rateOverTime=0;rateOverTimeMultiplier=0},vo=class{shapeType=od.Box;enabled=!0;alignToDirection=!1;angle=0;arc=360;arcmode=0;box=new ei.Vector3(1,1,1);boxThickness=new ei.Vector3(0,0,0);position=new ei.Vector3(0,0,0);rotation=new ei.Vector3(0,0,0);scale=new ei.Vector3(1,1,1);radius=1;sphericalDirectionAmount=0},od=(p=>(p[p.Sphere=0]="Sphere",p[p.SphereShell=1]="SphereShell",p[p.Hemisphere=2]="Hemisphere",p[p.HemisphereShell=3]="HemisphereShell",p[p.Cone=4]="Cone",p[p.Box=5]="Box",p[p.Mesh=6]="Mesh",p[p.ConeVolume=7]="ConeVolume",p[p.Circle=10]="Circle",p[p.SingleSidedEdge=11]="SingleSidedEdge",p[p.MeshRenderer=12]="MeshRenderer",p[p.SkinnedMeshRenderer=13]="SkinnedMeshRenderer",p[p.BoxShell=14]="BoxShell",p[p.BoxEdge=15]="BoxEdge",p[p.Donut=16]="Donut",p[p.Rectangle=17]="Rectangle",p[p.Sprite=18]="Sprite",p[p.SpriteRenderer=19]="SpriteRenderer",p))(od||{});var Ip=N("debugparticles"),sd=class{age=0;lifetime=0;position;velocity;color},gr=class extends M{get mainTexture(){if(this.sharedMaterial){let e=this.context.assets.findTexture(this.sharedMaterial);if(e)return e}return null}getMesh(e){return this.mesh?this.context.assets.findMesh(this.mesh):null}sharedMaterial;mesh;awake(){Ip&&console.log(this)}},yo=class extends M{main;emission;shape;renderer;geometry;material;particlesMesh;positions;positionsArray;particleStates=[];activeCount=0;shapeRotation=new xe.Quaternion;tempVec3=new xe.Vector3;tempQuat=new xe.Quaternion;awake(){this.renderer=S.getComponent(this.gameObject,gr),Ip&&console.log(this)}onEnable(){if(this.geometry)return;this.particleStates=[],this.shapeRotation.setFromEuler(new xe.Euler(this.shape.rotation.x,this.shape.rotation.y,this.shape.rotation.z)),this.geometry=new xe.BufferGeometry,this.positionsArray=new Float32Array(this.main.maxParticles*3),this.positions=new xe.Float32BufferAttribute(this.positionsArray,3),this.geometry.setAttribute("position",this.positions);let e=new Float32Array(this.main.maxParticles*3);for(let i=0;i<e.length;i++)e[i*3]=1,e[i*3+1]=1,e[i*3+2]=1;let t=new xe.Float32BufferAttribute(e,3);this.geometry.setAttribute("color",t),this.material=new xe.PointsMaterial({size:this.main.startSize,color:16777215,vertexColors:!0}),this.material.map=this.renderer.mainTexture,this.particlesMesh=new xe.Points(this.geometry,this.material),this.particlesMesh.layers.enable(2),this.gameObject.add(this.particlesMesh),this.activeCount=this.main.prewarm?this.main.maxParticles:0}update(){if(!this.geometry)return;let e=this.context.time.deltaTime;this.emit(e);for(let t=0;t<this.activeCount;t+=1){let i=this.particleStates[t];if(!i)continue;let n=i.velocity.x*e,r=i.velocity.y*e,o=i.velocity.z*e;i.position.x+=n,i.position.y+=r,i.position.z+=o,this.updateOverLifetime(t,i),this.geometry.attributes.position.setXYZ(t,i.position.x,i.position.y,i.position.z),this.geometry.attributes.color.setXYZ(t,i.color.r,i.color.g,i.color.b)}this.geometry&&(this.geometry.attributes.position.needsUpdate=!0,this.geometry.setDrawRange(0,this.activeCount))}emit(e){let t=this.activeCount;for(let i=0;i<t;i+=1){if(i>=this.particleStates.length){let r=new sd;r.lifetime=this.main.startLifetime??1,r.position=new xe.Vector3,r.velocity=new xe.Vector3,r.color=new xe.Color(1,0,0),this.particleStates.push(r),this.initializeParticle(i,r),r.age=r.lifetime*Math.random()}let n=this.particleStates[i];if(n.age>n.lifetime){this.activeCount-=1,this.activeCount=Math.max(0,this.activeCount),this.initializeParticle(i,n);continue}n.age+=e,this.particleStates[i]=n}this.activeCount+=e*this.emission.rate,this.activeCount=Math.min(this.main.maxParticles,this.activeCount)}initializeParticle(e,t){if(!this.geometry)return;t.age=0,t.color.set(this.main.startColor),this.main.startColor1&&t.color.lerp(this.main.startColor1,Math.random()),this.geometry.attributes.color.needsUpdate=!0,this.assignPosition(t.position),this.assignVelocity(t.position,t.velocity);let i=t.position;i.multiply(this.shape.scale),i.applyQuaternion(this.shapeRotation),i.add(this.shape.position),this.particleStates.splice(e,1),this.particleStates.push(t)}updateOverLifetime(e,t){}assignPosition(e){switch(this.shape.shapeType){case 0:e.set(Math.random()-.5,Math.random()-.5,Math.random()-.5).multiplyScalar(this.shape.radius);break;case 5:e.set(Math.random()-.5,Math.random()-.5,Math.random()-.5);break;default:e.set(0,0,0);break}}assignVelocity(e,t){switch(this.shape.shapeType){case 0:t.set(e.x,e.y,e.z);break;case 5:t.set(0,0,1),this.shape.sphericalDirectionAmount>0&&(this.tempVec3.set(e.x,e.y,e.z).multiply(this.shape.scale).normalize(),t.lerp(this.tempVec3,this.shape.sphericalDirectionAmount));break;case 4:let i=new xe.Vector3(0,1,0);t.copy(i);break;case 10:this.tempQuat.setFromAxisAngle(this.tempVec3.set(0,0,1),Math.random()*Q.toRadians(this.shape.arc)),t.copy(this.tempVec3.set(1,0,0).applyQuaternion(this.tempQuat));break;default:t.set(Math.random()*2-1,Math.random()*2-1,Math.random()*2-1);break}switch(t.normalize(),this.shape.shapeType){case 10:e.add(t).multiplyScalar(this.shape.radius);break}t.multiplyScalar(this.main.startSpeedMultiplier)}};import*as Lp from"three";function*Mp(l,e=null){let t=e?e.time:Z.Current.time,i=t.time;for(;t.time-i<l;)yield}var ht=class extends M{awake(){this.context.connection.beginListen("joined-room",this.tryAssignColor.bind(this))}_didAssignPlayerColor=!1;onEnable(){this._didAssignPlayerColor||this.startCoroutine(this.waitForConnection())}*waitForConnection(){for(;!this.destroyed&&this.enabled&&(yield Mp(.2),!this.tryAssignColor()););}tryAssignColor(){let e=S.getComponentInParent(this.gameObject,pe);return e&&e.connectionId?(this._didAssignPlayerColor=!0,this.assignUserColor(e.connectionId),!0):!1}assignUserColor(e){let t=ht.hashCode(e),i=ht.colorFromHashCode(t);if(this.gameObject.type==="Mesh"){let n=this.gameObject;this.assignColor(i,e,n)}else if(this.gameObject.children)for(let n of this.gameObject.children){let r=n;r.material&&r.material.color&&this.assignColor(i,e,r)}}assignColor(e,t,i){let n=i.material;!n||(n._playerMaterial!==t?(n=n.clone(),n._playerMaterial=t,i.material=n):console.log("DONT CLONE",n),n.color=e)}static hashCode(e){var t=0,i,n;if(e.length===0)return t;for(i=0;i<e.length;i++)n=e.charCodeAt(i),t=(t<<5)-t+n,t|=0;return t}static colorFromHashCode(e){let t=(e&16711680)>>16,i=(e&65280)>>8,n=e&255;return new Lp.Color(t/255,i/255,n/255)}};import*as Ga from"three";import{Object3D as cy}from"three";function ly(){return new Promise((l,e)=>{let i=()=>{i!=null&&(document.removeEventListener("pointerdown",i),document.removeEventListener("click",i),document.removeEventListener("dragstart",i),document.removeEventListener("touchstart",i),l())};document.addEventListener("pointerdown",i),document.addEventListener("click",i),document.addEventListener("dragstart",i),document.addEventListener("touchstart",i)})}async function Dp(l){await ly(),l()}var ad=N("debugvideo");var nt=class extends M{renderer=null;playOnAwake=!0;playOnEnable;targetMaterialProperty;time=0;_playbackSpeed=1;get playbackSpeed(){return this.videoElement?.playbackRate??this._playbackSpeed}set playbackSpeed(e){this._playbackSpeed=e,this.videoElement&&(this.videoElement.playbackRate=e)}_isLooping=!1;get isLooping(){return this.videoElement?.loop??this._isLooping}set isLooping(e){this._isLooping=e,this.videoElement&&(this.videoElement.loop=e)}get currentTime(){return this.videoElement?.currentTime??this.time}set currentTime(e){this.videoElement?this.videoElement.currentTime=e:this.time=e}get isPlaying(){let e=this.videoElement;return e?e.currentTime>0&&!e.paused&&!e.ended&&e.readyState>e.HAVE_CURRENT_DATA:!1}get crossOrigin(){return this.videoElement?.crossOrigin??this._crossOrigin}set crossOrigin(e){this._crossOrigin=e,this.videoElement&&(e!==null?this.videoElement.setAttribute("crossorigin",e):this.videoElement.removeAttribute("crossorigin"))}_crossOrigin="anonymous";audioOutputMode=1;source;clip=null;url=null;videoElement=null;videoTexture=null;videoMaterial=null;_isPlaying=!1;wasPlaying=!1;setClipURL(e){this.url!==e&&(this.url=e,this.source=1,ad&&console.log("set url",e),this.videoElement&&(this.videoElement.src=e,this._isPlaying&&this.videoElement.play()))}awake(){this.create(this.playOnAwake),window.addEventListener("visibilitychange",e=>{switch(document.visibilityState){case"hidden":this.wasPlaying=this._isPlaying,this.pause();break;case"visible":this.wasPlaying&&this.play();break}})}onEnable(){this.playOnEnable===!0&&this.handleBeginPlaying(!0)}onDisable(){this.pause()}onDestroy(){this.videoElement&&(this.videoElement.parentElement?.removeChild(this.videoElement),this.videoElement=null),this.videoTexture&&(this.videoTexture.dispose(),this.videoTexture=null)}_receivedInput=!1;constructor(){super(),Dp(()=>{this._receivedInput=!0,this.updateVideoElementSettings()})}play(){!this.videoElement||this._isPlaying&&!this.videoElement?.ended&&!this.videoElement?.paused||(this._isPlaying=!0,this._receivedInput||(this.videoElement.muted=!0),this.updateVideoElementSettings(),this.videoElement?.play().catch(e=>{console.warn(e)}),ad&&console.log("play",this.videoElement))}stop(){this._isPlaying=!1,this.videoElement&&(this.videoElement.currentTime=0,this.videoElement.pause())}pause(){this._isPlaying=!1,this.videoElement?.pause()}create(e){let t;switch(this.source){case 0:t=this.clip;break;case 1:t=this.url;break}!t||(this.videoElement||(this.videoElement=this.createVideoElement(),this.context.domElement?.prepend(this.videoElement),this.updateVideoElementStyles()),typeof t=="string"?this.videoElement.src=t:this.videoElement.srcObject=t,this.videoTexture||(this.videoTexture=new Ga.VideoTexture(this.videoElement)),this.videoTexture.flipY=!1,this.videoTexture.encoding=Ga.sRGBEncoding,this.handleBeginPlaying(e))}createVideoElement(){let e=document.createElement("video");return this._crossOrigin&&e.setAttribute("crossorigin",this._crossOrigin),ad&&console.log("create video elment",e),e}handleBeginPlaying(e){if(!this.enabled||!this.videoElement)return;let t=this.gameObject.material;if(t)if(t!==this.videoMaterial&&(this.videoMaterial=t.clone(),this.gameObject.material=this.videoMaterial),!this.targetMaterialProperty)this.videoMaterial.map=this.videoTexture;else switch(this.targetMaterialProperty){default:this.videoMaterial.map=this.videoTexture;break}else{console.warn("Can not play video, no material found, this might be a multimaterial case which is not supported yet");return}this.updateVideoElementSettings(),this.updateVideoElementStyles(),e&&this.play()}updateVideoElementSettings(){!this.videoElement||(this.videoElement.loop=this._isLooping,this.videoElement.currentTime=this.currentTime,this.videoElement.playbackRate=this._playbackSpeed,this.videoElement.playsInline=!0,this.videoElement.muted=!this._receivedInput&&this.audioOutputMode!==0,(this.playOnAwake||this.playOnEnable)&&(this.videoElement.autoplay=!0))}updateVideoElementStyles(){!this.videoElement||(this.videoElement.style.userSelect="none",this.videoElement.style.visibility="hidden",this.videoElement.style.display="none")}};k([A(cy)],nt.prototype,"renderer",2),k([A()],nt.prototype,"playOnAwake",2),k([A()],nt.prototype,"playOnEnable",2),k([A()],nt.prototype,"targetMaterialProperty",2),k([A()],nt.prototype,"time",2),k([A()],nt.prototype,"playbackSpeed",1),k([A()],nt.prototype,"isLooping",1);var Eo=class extends M{streamOnAwake=!0;start(){this.streamOnAwake&&this.open()}requestOpen=!1;captureStream=null;async open(e=!1){if(!(this.captureStream&&!e)){this.close(),this.requestOpen=!0;try{let t=S.getComponentInChildren(this.gameObject,nt);if(t){let i={video:!0,audio:!1};this.captureStream=await navigator.mediaDevices.getDisplayMedia(i),this.captureStream&&this.requestOpen&&(t.clip=this.captureStream,t.create(!0))}}catch(t){console.error("Error: "+t)}}}close(){if(this.requestOpen=!1,this.captureStream){for(let e of this.captureStream.getTracks())e.stop();this.captureStream=null}}};import{ShadowMaterial as dy,AdditiveBlending as hy}from"three";var Mn=class extends M{mode=0;shadowColor=new we(0,0,0,1);awake(){switch(this.mode){case 0:this.applyShadowMaterial();break;case 1:this.applyLightBlendMaterial();break}}applyLightBlendMaterial(){let e=S.getComponent(this.gameObject,Te);if(e){let t=e.material;t.blending=hy,this.applyMaterialOptions(t),t.onBeforeCompile=i=>{i.fragmentShader=i.fragmentShader.replace("vec3 outgoingLight = totalDiffuse + totalSpecular + totalEmissiveRadiance;",`vec3 outgoingLight = totalDiffuse + totalSpecular + totalEmissiveRadiance;
123
+ `,defines:{USE_LIGHTMAP:""}})}};var A=function(l){if(l===void 0&&(l=null),!Array.isArray(l))l=ju(l);else for(let e=0;e<l.length;e++){let t=l[e];l[e]=ju(t)}return function(e,t){Object.getOwnPropertyDescriptor(e,"$serializedTypes")||(e.$serializedTypes={});let i=e.$serializedTypes=e.$serializedTypes||{};i[t]=l}};function ju(l){switch(l?.prototype?.constructor?.name){case"Number":case"String":case"Boolean":return null}return l}import{Vector4 as Jb}from"three";import{NeverStencilFunc as Ab,LessStencilFunc as kb,EqualStencilFunc as Ib,LessEqualStencilFunc as Mb,GreaterStencilFunc as Lb,NotEqualStencilFunc as Db,GreaterEqualStencilFunc as Hb,AlwaysStencilFunc as jb,ZeroStencilOp as Bb,KeepStencilOp as Fb,ReplaceStencilOp as Nb,IncrementStencilOp as zb,DecrementStencilOp as Gb,IncrementWrapStencilOp as Vb,DecrementWrapStencilOp as Wb,InvertStencilOp as Ub}from"three";var rc=N("debugstencil");function qb(l,e){return(l&1<<e.layer)!=0}var tr=class{static applyStencil(e){if(!e)return;let t=e.sourceId;if(rc&&console.log(t,tr.stencils),!t)return;let i=tr.stencils[t];if(!!i)for(let n=i.length-1;n>=0;n--){let r=i[n];if(qb(r.layer,e)){rc&&console.log(r);let o=e.material?.clone();o&&(e.material=o,e.gameObject.renderOrder=r.event*1e3+r.index*50,o.stencilWrite=!0,o.stencilWriteMask=255,o.stencilFuncMask=255,o.stencilRef=r.value,o.stencilFunc=r.compareFunc,o.stencilZPass=r.passOp,o.stencilFail=r.failOp,o.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 i=t[Qb];if(i){rc&&console.log(i);let n=i.stencil;if(n&&Array.isArray(n))for(let r of n){let o={...r};o.compareFunc=Xb(o.compareFunc),o.passOp=oc(o.passOp),o.failOp=oc(o.failOp),o.zFailOp=oc(o.zFailOp),tr.stencils[this.source]||(tr.stencils[this.source]=[]),tr.stencils[this.source].push(o)}}}return null}},ir=tr;z(ir,"stencils",{});function oc(l){switch(l){case 0:return Fb;case 1:return Bb;case 2:return Nb;case 3:return zb;case 4:return Gb;case 6:return Vb;case 7:return Wb;case 5:return Ub}return 0}function Xb(l){switch(l){case 1:return Ab;case 2:return kb;case 3:return Ib;case 4:return Mb;case 5:return Lb;case 6:return Db;case 7:return Hb;case 8:return jb}return 0}var Qb="NEEDLE_render_objects";import{TextureLoader as Yb}from"three";import{GLTFLoader as Zb}from"three/examples/jsm/loaders/GLTFLoader";import{DRACOLoader as sc}from"three/examples/jsm/loaders/DRACOLoader.js";import{KTX2Loader as Bu}from"three/examples/jsm/loaders/KTX2Loader.js";var ns=N("debugdecoders"),Ut,bn;function ac(l){l!==void 0&&typeof l=="string"&&(Ut||(Ut=new sc),ns&&console.log("Setting draco decoder path to",l),Ut.setDecoderPath(l))}function lc(l){l!==void 0&&typeof l=="string"&&(Ut||(Ut=new sc),ns&&console.log("Setting draco decoder type to",l),Ut.setDecoderConfig({type:l}))}function cc(l){l!==void 0&&typeof l=="string"&&(bn||(bn=new Bu),ns&&console.log("Setting ktx2 transcoder path to",l),bn.setTranscoderPath(l))}function nr(l,e){Ut||(Ut=new sc,Ut.setDecoderPath("./include/draco/"),Ut.setDecoderConfig({type:"js"}),ns&&console.log("Setting draco decoder path to","./include/draco/")),bn||(bn=new Bu,bn.setTranscoderPath("./include/ktx2/"),ns&&console.log("Setting ktx2 transcoder path to","./include/ktx2/"),e.renderer&&bn.detectSupport(e.renderer)),l.setDRACOLoader(Ut),l.setKTX2Loader(bn)}var dc="NEEDLE_deferred_texture",vn=N("debugdeferredtextures"),rs=class{static assignTextureLOD(e,t,i=0){if(!!t)for(let n of Object.keys(t)){let r=t[n];r?.isTexture===!0&&(vn&&console.log("FIND",n,r?.name,r?.userData,r),rs.getOrLoadTexture(e,t,n,r,i).then(o=>{o?.isTexture===!0&&(o.needsUpdate=!0,t[n]=o,t.needsUpdate=!0)}))}}get name(){return dc}parser;sourceId;context;constructor(e,t,i){this.parser=e,this.sourceId=t,this.context=i}_loading=[];afterRoot(e){return vn&&console.log("AFTER",e),this.parser.json.textures?.forEach((t,i)=>{if(t?.extensions){let n=t?.extensions[dc];if(n){let r=this.parser.getDependency("texture",i);this._loading.splice(this._loading.indexOf(i),1),r.then(o=>{vn&&console.log("register texture",o.name,o.uuid,n),o.userData.deferred=n,rs.cache.set(o.uuid,n)})}}}),null}static async getOrLoadTexture(e,t,i,n,r){let o=n.uuid,s=rs.cache.get(o)||n.userData.deferred;if(s){vn&&console.log(o,s.uri,s.guid);let c=s.uri;if(c.endsWith(".glb")||c.endsWith(".gltf")){if(!s.guid)return console.warn("missing pointer for glb/gltf texture",s),null;let d=s.uri+"_"+s.guid;if(this.resolved[d])return this.resolved[d];let a=new Zb;nr(a,e),vn&&console.log("Load "+c,t.name,i);let h=await a.loadAsync(c),u=h.parser,f=-1,E=!1;for(let y of h.parser.json.textures)if(f++,y?.extensions){let g=y?.extensions[dc];if(g?.guid&&g.guid===s.guid){E=!0;break}}if(!E)return null;let b=await u.getDependency("texture",f);return this.resolved[d]=b,vn&&console.log(t.name,i,'change "'+n.name+'" \u2192 "'+b.name+'"',c,f,b,t),b}else{let a=await new Yb().loadAsync(s.uri);return a&&vn?console.log(s,a):console.warn("failed loading",s.uri),a}}else vn&&console.warn("unknown uuid",n.name,n.uuid,n);return null}},Bi=rs;z(Bi,"cache",new Map),z(Bi,"resolved",{});var Nu=N("noInstancing"),zu=!!N("debuglightmaps"),$b=N("debuginstancing"),Kb=N("debugprogressiveload"),Fr=class{path=null;asset=null;default};var hc=class{_renderer;_targets=[];is(e){return this._renderer===e}constructor(e){this._renderer=e;let t=this.setMaterial.bind(this),i=this.getMaterial.bind(this),n=e.gameObject;if(this._targets=[],n)switch(n.type){case"Group":this._targets=[...n.children];break;case"Mesh":this._targets.push(n);break}return new Proxy(this,{get(r,o){if(typeof o=="string"){let s=parseInt(o);if(!isNaN(s))return i(s)}return r[o]},set(r,o,s){return typeof o=="string"&&t(s,Number.parseInt(o)),Reflect.set(r,o,s)}})}get length(){return this._targets.length}setMaterial(e,t){if(t<0||t>=this._targets.length)return;let i=this._targets[t];!i||(i.material=e)}getMaterial(e){if(e<0)return null;let t=this._targets;if(e>=t.length)return null;let i=t[e];return i?i.material:null}},gc=class extends M{receiveShadows=!1;shadowCastingMode=uc.Off;lightmapIndex=-1;lightmapScaleOffset=new li.Vector4(1,1,0,0);enableInstancing=void 0;renderOrder=void 0;allowOcclusionWhenDynamic=!0;_lightmaps;get material(){return this.gameObject.material}set material(e){this.gameObject.material=e}_sharedMaterials;get sharedMaterials(){return(!this._sharedMaterials||!this._sharedMaterials.is(this))&&(this._sharedMaterials=new hc(this)),this._sharedMaterials}static get shouldSuppressInstancing(){return Nu}_lightmapTextureOverride=void 0;get lightmap(){return this._lightmaps?.length?this._lightmaps[0].lightmap:null}set lightmap(e){if(this._lightmapTextureOverride=e,e===void 0&&(e=this.context.lightmaps.tryGetLightmap(this.sourceId,this.lightmapIndex)),this._lightmaps?.length)for(let t of this._lightmaps)t.lightmap=e}get hasLightmap(){let e=this.lightmap;return e!=null}awake(){let e=this.gameObject.type;if(e==="Group"){for(let t of this.gameObject.children)this.context.addBeforeRenderListener(t,this.onBeforeRenderThree.bind(this)),t.layers.mask=this.gameObject.layers.mask;if(this.renderOrder!==void 0){let t=0;for(let i=0;i<this.gameObject.children.length;i++){let n=this.gameObject.children[i];if(!(n.type!=="Mesh"||S.getComponent(n,gc))){if(this.renderOrder.length<=t){console.error("Incorrect element count",this);break}n.renderOrder=this.renderOrder[t],t+=1}}}}else(e==="Mesh"||e==="SkinnedMesh")&&(this.context.addBeforeRenderListener(this.gameObject,this.onBeforeRenderThree.bind(this)),this.renderOrder!==void 0&&this.renderOrder.length>0&&(this.gameObject.renderOrder=this.renderOrder[0]));if(this.lightmapIndex>=0){let t=this._lightmapTextureOverride!==void 0?this._lightmapTextureOverride:this.context.lightmaps.tryGetLightmap(this.sourceId,this.lightmapIndex);if(t){if(this._lightmaps=[],e==="Mesh"){if(!this.gameObject.material?.isMeshBasicMaterial){let i=new ji(this.gameObject,this.context);this._lightmaps.push(i),i.init(this.lightmapIndex,this.lightmapScaleOffset,t,zu)}}else if(e==="Group"){for(let i of this.gameObject.children)if(!i.material?.isMeshBasicMaterial){let n=new ji(i,this.context);this._lightmaps.push(n),n.init(this.lightmapIndex,this.lightmapScaleOffset,t,zu),n.bindOnBeforeRender()}}}}}_isInstancingEnabled=!1;handles=void 0;prevLayers=void 0;setInstancingEnabled(e){if(this._isInstancingEnabled===e)return e&&(this.handles===void 0||this.handles!=null&&this.handles.length>0);if(this._isInstancingEnabled=e,e){if(this.handles===void 0){if(this.handles=ev.setup(this.gameObject,this.context,null,{rend:this,foundMeshes:0}),this.handles)return S.markAsInstancedRendered(this.gameObject,!0),!0}else if(this.handles!==null){for(let t of this.handles)t.updateInstanceMatrix(!0),t.add();return S.markAsInstancedRendered(this.gameObject,!0),!0}}else{if(this.handles)for(let t of this.handles)t.remove();return!0}return!1}start(){if(this.enableInstancing&&!Nu&&this.setInstancingEnabled(!0),this.gameObject.frustumCulled=this.allowOcclusionWhenDynamic,this.gameObject.type==="Group")for(let e=0;e<this.gameObject.children.length;e++){let t=this.gameObject.children[e];t.frustumCulled=this.allowOcclusionWhenDynamic}}onEnable(){this._isInstancingEnabled?this.setInstancingEnabled(!0):this.enabled&&(this.gameObject.visible=!0,this.applyStencil())}onDisable(){this.handles&&this.handles.length>0?this.setInstancingEnabled(!1):this.enabled||(this.gameObject.visible=!1)}onDestroy(){this.handles=null}applyStencil(){ir.applyStencil(this)}onBeforeRenderThree(e,t,i,n,r,o){if(r._didRequestTextureLOD===void 0&&(r._didRequestTextureLOD=0,Kb?(console.log("Load material LOD (with delay)",r.name),setTimeout(()=>{Bi.assignTextureLOD(this.context,r)},2e3)):Bi.assignTextureLOD(this.context,r)),r.envMapIntensity!==void 0){let s=this.hasLightmap?Math.PI:1;r.envMapIntensity=Math.max(0,this.context.rendererData.environmentIntensity/s)}if(this._lightmaps)for(let s of this._lightmaps)s.onBeforeRenderThree(r)}onBeforeRender(){if(!this.gameObject)return;let e=this.gameObject[pc]===!0||this.gameObject.matrixWorldNeedsUpdate;if(this.gameObject.type==="Group"&&this.gameObject.children?.length>0)for(let t of this.gameObject.children)this.applySettings(t);else this.applySettings(this.gameObject);if(e&&(delete this.gameObject[pc],this.handles)){for(let i=this.handles.length-1;i>=0;i--)this.handles[i].updateInstanceMatrix();this.gameObject.matrixWorldNeedsUpdate=!1}if(this.handles&&this.handles.length<=0&&S.markAsInstancedRendered(this.gameObject,!1),this._isInstancingEnabled&&this.handles)for(let t=0;t<this.handles.length;t++){let i=this.handles[t];this.prevLayers||(this.prevLayers=[]);let n=i.object.layers.mask;t>=this.prevLayers.length?this.prevLayers.push(n):this.prevLayers[t]=n,i.object.layers.disableAll()}}onAfterRender(){if(this._isInstancingEnabled&&this.handles&&this.prevLayers&&this.prevLayers.length>=this.handles.length)for(let e=0;e<this.handles.length;e++){let t=this.handles[e];t.object.layers.mask=this.prevLayers[e]}}applySettings(e){e.receiveShadow=this.receiveShadows,this.shadowCastingMode==uc.On?e.castShadow=!0:e.castShadow=!1}},Te=gc;k([A()],Te.prototype,"receiveShadows",2),k([A()],Te.prototype,"shadowCastingMode",2),k([A()],Te.prototype,"lightmapIndex",2),k([A(Jb)],Te.prototype,"lightmapScaleOffset",2),k([A()],Te.prototype,"enableInstancing",2),k([A()],Te.prototype,"renderOrder",2),k([A()],Te.prototype,"allowOcclusionWhenDynamic",2);var rr=class extends Te{},Nr=class extends rr{awake(){super.awake(),this.allowOcclusionWhenDynamic=!1}},uc=(n=>(n[n.Off=0]="Off",n[n.On=1]="On",n[n.TwoSided=2]="TwoSided",n[n.ShadowsOnly=3]="ShadowsOnly",n))(uc||{}),pc="NEEDLE_NEED_UPDATE_INSTANCE",he=class{static markDirty(e,t=!0){if(!!e&&(S.isUsingInstancing(e)&&(e[pc]=!0,e.matrixWorldNeedsUpdate=!0),t))for(let i of e.children)he.markDirty(i,!0)}},fc=class{objs=[];setup(e,t,i,n,r=0){let o=this.tryCreateOrAddInstance(e,t,n);if(o)return i===null&&(i=[]),i.push(o),i;if(r<=0&&e.type!=="Mesh"){let s=r+1;for(let c of e.children)i=this.setup(c,t,i,n,s)}return i}tryCreateOrAddInstance(e,t,i){if(e.type==="Mesh"){let n=i.foundMeshes;if(i.foundMeshes+=1,!i.rend.enableInstancing||n>=i.rend.enableInstancing.length||!i.rend.enableInstancing[n])return null;let r=e,o=r.geometry,s=r.material;for(let d of this.objs)if(!d.isFull()&&d.geo===o&&d.material===s)return d.addInstance(r);let c=new oa(e.name,o,s,200,t);return this.objs.push(c),c.addInstance(r)}return null}},ev=new fc,mc=class{get name(){return this.object.name}instanceIndex=-1;object;instancer;constructor(e,t,i){this.instanceIndex=e,this.object=t,this.instancer=i,S.markAsInstancedRendered(t,!0)}updateInstanceMatrix(e=!1){this.instanceIndex<0||(this.object.updateWorldMatrix(!0,e),this.instancer.updateInstance(this.object.matrixWorld,this.instanceIndex))}add(){this.instanceIndex>=0||this.instancer.add(this)}remove(){this.instanceIndex<0||this.instancer.remove(this)}},bc=class{name="";geo;material;get currentCount(){return this.inst.count}context;inst;handles=[];maxCount;isFull(){return this.currentCount>=this.maxCount}constructor(e,t,i,n,r){this.name=e,this.geo=t,this.material=i,this.context=r,this.maxCount=n,$b&&(i=new li.MeshBasicMaterial({color:this.randomColor()})),this.inst=new li.InstancedMesh(t,i,n),this.inst.count=0,this.inst.layers.set(2),this.inst.visible=!0,this.context.scene.add(this.inst)}randomColor(){return new li.Color(Math.random(),Math.random(),Math.random())}addInstance(e){if(this.currentCount>=this.maxCount)return console.error("TOO MANY INSTANCES - resize is not yet implemented!",this.inst.count),null;let t=new mc(-1,e,this);return this.add(t),t}add(e){e.instanceIndex<0&&(e.instanceIndex=this.currentCount,e.instanceIndex>=this.handles.length?this.handles.push(e):this.handles[e.instanceIndex]=e),e.object.updateWorldMatrix(!0,!0),this.inst.setMatrixAt(e.instanceIndex,e.object.matrixWorld),this.inst.instanceMatrix.needsUpdate=!0,this.inst.count+=1,this.inst.count>0&&(this.inst.visible=!0)}remove(e){if(!e||e.instanceIndex<0||e.instanceIndex>=this.handles.length||this.inst.count<=0)return;if(this.handles[e.instanceIndex]!==e){console.error("instance handle is not part of renderer, was it removed before?",e.instanceIndex,this.name);let i=this.handles.indexOf(e);if(i<0)return;e.instanceIndex=i}if(this.handles[e.instanceIndex]=null,this.inst.setMatrixAt(e.instanceIndex,bc.nullMatrix),!(e.instanceIndex>=this.currentCount-1)&&this.currentCount>0){let i=this.handles[this.currentCount-1];i&&(i.instanceIndex=e.instanceIndex,i.updateInstanceMatrix(),this.handles[e.instanceIndex]=i,this.handles[this.currentCount-1]=null)}this.inst.count>0&&(this.inst.count-=1),e.instanceIndex=-1,this.inst.count<=0&&(this.inst.visible=!1),this.inst.instanceMatrix.needsUpdate=!0}updateInstance(e,t){this.inst.setMatrixAt(t,e),this.inst.instanceMatrix.needsUpdate=!0}},oa=bc;z(oa,"nullMatrix",new li.Matrix4);var os=N("debugphysics"),tv=N("debugcollisions"),sa=class{mass=1;kinematic=!1;physicsEvents=!1;drag=0;angularDrag=.05;sleepThreshold=.01},ss=class{obj;parent;body;shapes=[];collisonCallback=null;_hasRigidbody=!1;_didSleepLastStep=!1;constructor(e,t){this.obj=e,this.parent=e.parent,this.body=t}},vc=class{obj;contact;target;type;constructor(e,t){this.contact=e,this.type=t,this.obj=null,this.target=null}};var je=class{ray=void 0;screenPoint=void 0;raycaster=void 0;results=void 0;targets=void 0;recursive=!0;minDistance=void 0;maxDistance=void 0;lineThreshold=void 0;layerMask=void 0;ignore=void 0;screenPointFromOffset(e,t){this.screenPoint===void 0&&(this.screenPoint=new ke.Vector2),this.screenPoint.x=e/window.innerWidth*2-1,this.screenPoint.y=-(t/window.innerHeight)*2+1}setMask(e){this.layerMask||(this.layerMask=new ke.Layers);let t=this.layerMask;t?t.mask=e:this.layerMask=e}};z(je,"AllLayers",4294967295);var yc=class{distance;point;object;constructor(e,t,i){this.object=e,this.distance=t,this.point=i}},aa=class{raycaster=new ke.Raycaster;defaultRaycastOptions=new je;targetBuffer=new Array(1);defaultThresholds={Mesh:{},Line:{threshold:0},LOD:{},Points:{threshold:0},Sprite:{}};sphereResults=new Array;sphereMask=new ke.Layers;sphereOverlap(e,t){if(this.sphereResults.length=0,!this.context.scene)return this.sphereResults;let i=new ke.Sphere(e,t),n=this.sphereMask;n.enableAll(),n.disable(2);for(let r of this.context.scene.children){let o=this.onSphereOverlap(r,i,n);o&&this.sphereResults.push(o)}return this.sphereResults.sort((r,o)=>r.distance-o.distance)}tempBoundingBox=new ke.Box3;onSphereOverlap(e,t,i){if(e.type==="Mesh"){if(!e.layers.test(i))return null;let n=e,r=n.geometry;if(r.boundingBox||r.computeBoundingBox(),!r.boundingBox)return null;n.matrixWorldNeedsUpdate&&n.updateMatrixWorld();let o=this.tempBoundingBox.copy(r.boundingBox).applyMatrix4(n.matrixWorld);if(t.intersectsBox(o)){let c=q(e).distanceTo(t.center);return new yc(e,c,t.center.clone())}}else if(e.children)for(let n of e.children){let r=this.onSphereOverlap(n,t,i);if(r)return r}return null}raycastFromRay(e,t=null){let i=t??this.defaultRaycastOptions;return i.ray=e,this.raycast(i)}raycast(e=null){e||(e=this.defaultRaycastOptions);let t=e.screenPoint??this.context.input.mousePositionRC,i=e.raycaster??this.raycaster;if(i.near=e.minDistance??0,i.far=e.maxDistance??1/0,i.params=this.defaultThresholds,e.lineThreshold?i.params.Line={threshold:e.lineThreshold}:i.params.Line={threshold:0},e.ray)i.ray.copy(e.ray);else{let s=this.context.mainCamera;if(!s)return console.error("Can not perform raycast - no main camera found"),this.defaultRaycastOptions.results&&(this.defaultRaycastOptions.results.length=0),this.defaultRaycastOptions.results??[];i.setFromCamera(t,s)}let n=e.targets;n||(n=this.targetBuffer,n[0]=this.context.scene);let r=e.results;r||(this.defaultRaycastOptions.results||(this.defaultRaycastOptions.results=new Array),r=this.defaultRaycastOptions.results),e.layerMask!==void 0?e.layerMask instanceof ke.Layers?i.layers.mask=e.layerMask.mask:i.layers.mask=e.layerMask:(i.layers.enableAll(),i.layers.disable(2)),r.length=0,i.intersectObjects(n,e.recursive,r);let o=e.ignore;return o!==void 0&&o.length>0&&(r=r.filter(s=>!o.includes(s.object))),r}get isUpdating(){return this._isUpdatingPhysicsWorld}_isUpdatingPhysicsWorld=!1;context;world=new ra;objects=[];tempPosition=new ke.Vector3;tempQuaternion=new ke.Quaternion;constructor(e){if(this.context=e,this.world.gravity.set(0,-9.82,0),os){let t={};t.onInit=(i,n,r)=>{n.layers.set(-1)},Hu(e.scene,this.world.bodies,t)}}addPreStepListener(e){this.world.addEventListener("preStep",e)}addPostStepListener(e){this.world.addEventListener("postStep",e)}addConstraint(e){this.world.addConstraint(e)}setGravity(e){this.world.gravity.set(e.x,e.y,e.z)}multiplyGravity(e){this.world.gravity.x*=e.x,this.world.gravity.y*=e.y,this.world.gravity.z*=e.z}addBody(e,t){for(let i=0;i<this.objects.length;i++){let n=this.objects[i];if(n.obj===e){n._hasRigidbody=!0;break}}this.world.addBody(t)}removeBody(e,t,i=!0){this.world.removeBody(t);for(let n=0;n<this.objects.length;n++){let r=this.objects[n];if(r.obj===e){r._hasRigidbody=!1,i&&this.objects.splice(n,1);break}}}removeShape(e,t){for(let i of this.objects)if(i.obj===e){i.body&&(i.body.removeShape(t),i.body.updateMassProperties());return}}createBody(e,t){let i=this.internalCreateBody(e,null);t.mass&&(i.mass=t.mass),t.kinematic?i.type=G.KINEMATIC:i.type=G.DYNAMIC,t.drag&&(i.linearDamping=t.drag),t.angularDrag&&(i.angularDamping=t.angularDrag),t.sleepThreshold&&(i.sleepSpeedLimit=t.sleepThreshold),this.world.addBody(i);let n=new ss(e,i);return n._hasRigidbody=!0,this.objects.push(n),os&&console.log("created new body",e.name,i,i.sleepState,this.world.gravity),t.physicsEvents&&this.registerCollisionEvents(n),i}addBoxCollider(e,t,i,n,r){let o=this.tempPosition;e.getWorldScale(o);let s=new _(.5*o.x*n.x,.5*o.y*n.y,.5*o.z*n.z),c=new Kn(s);c.collisionResponse=!t,i=i.clone(),i.multiply(o);let d=this.addShape(e,c,i,r);if(d!==null){if(this.isAlreadyRegistered(d))return c;let a=new ss(e,d);this.objects.push(a)}return c}addSphereCollider(e,t,i,n){let r=this.tempPosition;e.getWorldScale(r);let o=Math.max(r.x,r.y,r.z),s=new ia(i*o);t=t.clone(),t.multiply(r);let c=this.addShape(e,s,t,n);if(c!==null){if(this.isAlreadyRegistered(c))return s;let d=new ss(e,c);this.objects.push(d)}return s}addMeshCollider(e){os&&console.warn("TODO mesh collider not yet supported")}isAlreadyRegistered(e){for(let t of this.objects)if(t.body===e)return!0;return!1}addShape(e,t,i,n){let r=null;if(n?(n.initialize(),console.assert(!!n.body,"rigidbody didn't initialize / produce a physics body",n),r=n.body):(r=this.internalCreateBody(e,null),r.type=G.KINEMATIC,this.world.addBody(r)),r){i.x*=-1;let o=ve(e),s=q(e);s.add(i);let c=new ke.Quaternion(r.quaternion.x,r.quaternion.y,r.quaternion.z,r.quaternion.w);o.multiply(c.invert());let d=r.position,a=new _(s.x-d.x,s.y-d.y,s.z-d.z),h=new le(o.x,o.y,o.z,o.w);r.addShape(t,a,h),r.updateMassProperties()}return r}step(e){this._isUpdatingPhysicsWorld=!0,e=Math.min(e,1/30),this.world.step(e),this._isUpdatingPhysicsWorld=!1,os&&this.context.time.frameCount%60===0&&console.log("physics world has "+this.world.bodies.length+" bodies",this.world)}temp=new ke.Vector3;tempQuat=new ke.Quaternion;postStep(){this._isUpdatingPhysicsWorld=!0;for(let e=0;e<this.objects.length;e++){let t=this.objects[e],i=t.body;if(!i||!i.world)continue;i.sleepTick(this.context.time.time),os&&(!t._didSleepLastStep&&i.sleepState===G.SLEEPING?console.log("BODY SLEEPING",i):t._didSleepLastStep&&i.sleepState!==G.SLEEPING&&console.log("BODY WOKE UP",i)),t._didSleepLastStep=i.sleepState===G.SLEEPING;let n=t.obj;if(i.type===G.KINEMATIC){let r=q(n,this.temp);i.position.set(r.x,r.y,r.z);let o=ve(n,this.tempQuat);i.quaternion.set(o.x,o.y,o.z,o.w);continue}if(t.parent&&n.parent===t.parent){Rh(n,i.quaternion.x,i.quaternion.y,i.quaternion.z,i.quaternion.w);let r=i.position;Mr(n,r.x,r.y,r.z),i.velocity.length()>i.sleepSpeedLimit&&he.markDirty(n)}}this._isUpdatingPhysicsWorld=!1}internalCreateBody(e,t){let i=new G;i._owner=e,i._name=e.name,e.getWorldPosition(this.tempPosition);let n=this.tempPosition;i.position=new _(n.x,n.y,n.z);let r=this.tempQuaternion;return e.getWorldQuaternion(r),i.quaternion=new le(r.x,r.y,r.z,r.w),i.type=G.KINEMATIC,t&&(i.addShape(t),i.updateMassProperties()),i}registerCollisionEvents(e){if(e.collisonCallback&&this.unregisterCollisionEvents(e),!e.body)return;let t=i=>this.raiseCollisionEvents(e.obj,i);e.collisonCallback=t.bind(this),e.body.addEventListener("collide",e.collisonCallback)}unregisterCollisionEvents(e){!e.collisonCallback||!e.body||e.body.removeEventListener("collide",e.collisonCallback)}raiseCollisionEvents(e,t){let i=new vc(t.contact,t.type),n=0,r=this.objects;function o(){if(!(n>0))for(let s=0;s<r.length;s++){if(n==2)return;let c=r[s];c.body==t.body?(i.obj=c.obj,++n):c.body==t.target&&(i.target=c.obj,++n)}}tv&&console.log("collision between",t.contact.bi,t.contact.bj,e,t);for(let s=0;s<e.userData?.components?.length;s++){let c=e.userData.components[s];c.onCollision&&(o(),c.onCollision(i))}}};import{Clock as iv}from"three";var la=class{deltaTime=0;time=0;frame=0;get realtimeSinceStartup(){return this.clock.elapsedTime}get frameCount(){return this.frame}get smoothedFps(){return this._smoothedFps}clock=new iv;_smoothedFps=0;_fpsSamples=[];_fpsSampleIndex=0;update(){this.deltaTime=this.clock.getDelta(),this.deltaTime=Math.min(.1,this.deltaTime),this.frame+=1,this.time+=this.deltaTime,this._fpsSamples.length<30?this._fpsSamples.push(this.deltaTime):this._fpsSamples[this._fpsSampleIndex++%30]=this.deltaTime;let e=0;for(let t=0;t<this._fpsSamples.length;t++)e+=this._fpsSamples[t];this._smoothedFps=1/(e/this._fpsSamples.length)}};import{WebsocketBuilder as rv}from"websocket-ts";function Gu(l=window.location.hostname){return new RegExp("[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}|localhost","gm").test(l)===!0}var pt=class extends M{url=null;urlParameterName=null;localhost=null;getWebsocketUrl(){let e=this.url?pt.GetUrl(this.url,this.localhost):null;if(this.urlParameterName){let r=N(this.urlParameterName);r&&typeof r=="string"&&(e=r)}if(!e)return null;let i=new RegExp("(((https?)|(?<socket_prefix>wss?))://)?(www.)?(?<url>.+)","gm").exec(e);return i?.groups?i?.groups.socket_prefix?e:"wss://"+i?.groups.url:null}static GetUrl(e,t){let i=e,n=pt.IsLocalNetwork()&&t;return n&&(i=t),e?.startsWith("/")&&(i=(n?i:window.location.origin)+e),i}static IsLocalNetwork(e=window.location.hostname){return Gu(e)}};var ci=new Int32Array(2),ca=new Float32Array(ci.buffer),da=new Float64Array(ci.buffer),zr=new Uint16Array(new Uint8Array([1,0]).buffer)[0]===1;var Xe=class{constructor(e,t){this.low=e|0,this.high=t|0}static create(e,t){return e==0&&t==0?Xe.ZERO:new Xe(e,t)}toFloat64(){return(this.low>>>0)+this.high*4294967296}equals(e){return this.low==e.low&&this.high==e.high}};Xe.ZERO=new Xe(0,0);var as;(function(l){l[l.UTF8_BYTES=1]="UTF8_BYTES",l[l.UTF16_STRING=2]="UTF16_STRING"})(as||(as={}));var di=class{constructor(e){this.bytes_=e,this.position_=0}static allocate(e){return new di(new Uint8Array(e))}clear(){this.position_=0}bytes(){return this.bytes_}position(){return this.position_}setPosition(e){this.position_=e}capacity(){return this.bytes_.length}readInt8(e){return this.readUint8(e)<<24>>24}readUint8(e){return this.bytes_[e]}readInt16(e){return this.readUint16(e)<<16>>16}readUint16(e){return this.bytes_[e]|this.bytes_[e+1]<<8}readInt32(e){return this.bytes_[e]|this.bytes_[e+1]<<8|this.bytes_[e+2]<<16|this.bytes_[e+3]<<24}readUint32(e){return this.readInt32(e)>>>0}readInt64(e){return new Xe(this.readInt32(e),this.readInt32(e+4))}readUint64(e){return new Xe(this.readUint32(e),this.readUint32(e+4))}readFloat32(e){return ci[0]=this.readInt32(e),ca[0]}readFloat64(e){return ci[zr?0:1]=this.readInt32(e),ci[zr?1:0]=this.readInt32(e+4),da[0]}writeInt8(e,t){this.bytes_[e]=t}writeUint8(e,t){this.bytes_[e]=t}writeInt16(e,t){this.bytes_[e]=t,this.bytes_[e+1]=t>>8}writeUint16(e,t){this.bytes_[e]=t,this.bytes_[e+1]=t>>8}writeInt32(e,t){this.bytes_[e]=t,this.bytes_[e+1]=t>>8,this.bytes_[e+2]=t>>16,this.bytes_[e+3]=t>>24}writeUint32(e,t){this.bytes_[e]=t,this.bytes_[e+1]=t>>8,this.bytes_[e+2]=t>>16,this.bytes_[e+3]=t>>24}writeInt64(e,t){this.writeInt32(e,t.low),this.writeInt32(e+4,t.high)}writeUint64(e,t){this.writeUint32(e,t.low),this.writeUint32(e+4,t.high)}writeFloat32(e,t){ca[0]=t,this.writeInt32(e,ci[0])}writeFloat64(e,t){da[0]=t,this.writeInt32(e,ci[zr?0:1]),this.writeInt32(e+4,ci[zr?1:0])}getBufferIdentifier(){if(this.bytes_.length<this.position_+4+4)throw new Error("FlatBuffers: ByteBuffer is too short to contain an identifier.");let e="";for(let t=0;t<4;t++)e+=String.fromCharCode(this.readInt8(this.position_+4+t));return e}__offset(e,t){let i=e-this.readInt32(e);return t<this.readInt16(i)?this.readInt16(i+t):0}__union(e,t){return e.bb_pos=t+this.readInt32(t),e.bb=this,e}__string(e,t){e+=this.readInt32(e);let i=this.readInt32(e),n="",r=0;if(e+=4,t===as.UTF8_BYTES)return this.bytes_.subarray(e,e+i);for(;r<i;){let o,s=this.readUint8(e+r++);if(s<192)o=s;else{let c=this.readUint8(e+r++);if(s<224)o=(s&31)<<6|c&63;else{let d=this.readUint8(e+r++);if(s<240)o=(s&15)<<12|(c&63)<<6|d&63;else{let a=this.readUint8(e+r++);o=(s&7)<<18|(c&63)<<12|(d&63)<<6|a&63}}}o<65536?n+=String.fromCharCode(o):(o-=65536,n+=String.fromCharCode((o>>10)+55296,(o&(1<<10)-1)+56320))}return n}__union_with_string(e,t){return typeof e=="string"?this.__string(t):this.__union(e,t)}__indirect(e){return e+this.readInt32(e)}__vector(e){return e+this.readInt32(e)+4}__vector_len(e){return this.readInt32(e+this.readInt32(e))}__has_identifier(e){if(e.length!=4)throw new Error("FlatBuffers: file identifier must be length "+4);for(let t=0;t<4;t++)if(e.charCodeAt(t)!=this.readInt8(this.position()+4+t))return!1;return!0}createLong(e,t){return Xe.create(e,t)}createScalarList(e,t){let i=[];for(let n=0;n<t;++n)e(n)!==null&&i.push(e(n));return i}createObjList(e,t){let i=[];for(let n=0;n<t;++n){let r=e(n);r!==null&&i.push(r.unpack())}return i}};var ft=class{constructor(e){this.minalign=1,this.vtable=null,this.vtable_in_use=0,this.isNested=!1,this.object_start=0,this.vtables=[],this.vector_num_elems=0,this.force_defaults=!1,this.string_maps=null;let t;e?t=e:t=1024,this.bb=di.allocate(t),this.space=t}clear(){this.bb.clear(),this.space=this.bb.capacity(),this.minalign=1,this.vtable=null,this.vtable_in_use=0,this.isNested=!1,this.object_start=0,this.vtables=[],this.vector_num_elems=0,this.force_defaults=!1,this.string_maps=null}forceDefaults(e){this.force_defaults=e}dataBuffer(){return this.bb}asUint8Array(){return this.bb.bytes().subarray(this.bb.position(),this.bb.position()+this.offset())}prep(e,t){e>this.minalign&&(this.minalign=e);let i=~(this.bb.capacity()-this.space+t)+1&e-1;for(;this.space<i+e+t;){let n=this.bb.capacity();this.bb=ft.growByteBuffer(this.bb),this.space+=this.bb.capacity()-n}this.pad(i)}pad(e){for(let t=0;t<e;t++)this.bb.writeInt8(--this.space,0)}writeInt8(e){this.bb.writeInt8(this.space-=1,e)}writeInt16(e){this.bb.writeInt16(this.space-=2,e)}writeInt32(e){this.bb.writeInt32(this.space-=4,e)}writeInt64(e){this.bb.writeInt64(this.space-=8,e)}writeFloat32(e){this.bb.writeFloat32(this.space-=4,e)}writeFloat64(e){this.bb.writeFloat64(this.space-=8,e)}addInt8(e){this.prep(1,0),this.writeInt8(e)}addInt16(e){this.prep(2,0),this.writeInt16(e)}addInt32(e){this.prep(4,0),this.writeInt32(e)}addInt64(e){this.prep(8,0),this.writeInt64(e)}addFloat32(e){this.prep(4,0),this.writeFloat32(e)}addFloat64(e){this.prep(8,0),this.writeFloat64(e)}addFieldInt8(e,t,i){(this.force_defaults||t!=i)&&(this.addInt8(t),this.slot(e))}addFieldInt16(e,t,i){(this.force_defaults||t!=i)&&(this.addInt16(t),this.slot(e))}addFieldInt32(e,t,i){(this.force_defaults||t!=i)&&(this.addInt32(t),this.slot(e))}addFieldInt64(e,t,i){(this.force_defaults||!t.equals(i))&&(this.addInt64(t),this.slot(e))}addFieldFloat32(e,t,i){(this.force_defaults||t!=i)&&(this.addFloat32(t),this.slot(e))}addFieldFloat64(e,t,i){(this.force_defaults||t!=i)&&(this.addFloat64(t),this.slot(e))}addFieldOffset(e,t,i){(this.force_defaults||t!=i)&&(this.addOffset(t),this.slot(e))}addFieldStruct(e,t,i){t!=i&&(this.nested(t),this.slot(e))}nested(e){if(e!=this.offset())throw new Error("FlatBuffers: struct must be serialized inline.")}notNested(){if(this.isNested)throw new Error("FlatBuffers: object serialization must not be nested.")}slot(e){this.vtable!==null&&(this.vtable[e]=this.offset())}offset(){return this.bb.capacity()-this.space}static growByteBuffer(e){let t=e.capacity();if(t&3221225472)throw new Error("FlatBuffers: cannot grow buffer beyond 2 gigabytes.");let i=t<<1,n=di.allocate(i);return n.setPosition(i-t),n.bytes().set(e.bytes(),i-t),n}addOffset(e){this.prep(4,0),this.writeInt32(this.offset()-e+4)}startObject(e){this.notNested(),this.vtable==null&&(this.vtable=[]),this.vtable_in_use=e;for(let t=0;t<e;t++)this.vtable[t]=0;this.isNested=!0,this.object_start=this.offset()}endObject(){if(this.vtable==null||!this.isNested)throw new Error("FlatBuffers: endObject called without startObject");this.addInt32(0);let e=this.offset(),t=this.vtable_in_use-1;for(;t>=0&&this.vtable[t]==0;t--);let i=t+1;for(;t>=0;t--)this.addInt16(this.vtable[t]!=0?e-this.vtable[t]:0);let n=2;this.addInt16(e-this.object_start);let r=(i+n)*2;this.addInt16(r);let o=0,s=this.space;e:for(t=0;t<this.vtables.length;t++){let c=this.bb.capacity()-this.vtables[t];if(r==this.bb.readInt16(c)){for(let d=2;d<r;d+=2)if(this.bb.readInt16(s+d)!=this.bb.readInt16(c+d))continue e;o=this.vtables[t];break}}return o?(this.space=this.bb.capacity()-e,this.bb.writeInt32(this.space,o-e)):(this.vtables.push(this.offset()),this.bb.writeInt32(this.bb.capacity()-e,this.offset()-e)),this.isNested=!1,e}finish(e,t,i){let n=i?4:0;if(t){let r=t;if(this.prep(this.minalign,4+4+n),r.length!=4)throw new Error("FlatBuffers: file identifier must be length "+4);for(let o=4-1;o>=0;o--)this.writeInt8(r.charCodeAt(o))}this.prep(this.minalign,4+n),this.addOffset(e),n&&this.addInt32(this.bb.capacity()-this.space),this.bb.setPosition(this.space)}finishSizePrefixed(e,t){this.finish(e,t,!0)}requiredField(e,t){let i=this.bb.capacity()-e,n=i-this.bb.readInt32(i);if(!(this.bb.readInt16(n+t)!=0))throw new Error("FlatBuffers: field "+t+" must be set")}startVector(e,t,i){this.notNested(),this.vector_num_elems=t,this.prep(4,e*t),this.prep(i,e*t)}endVector(){return this.writeInt32(this.vector_num_elems),this.offset()}createSharedString(e){if(!e)return 0;if(this.string_maps||(this.string_maps=new Map),this.string_maps.has(e))return this.string_maps.get(e);let t=this.createString(e);return this.string_maps.set(e,t),t}createString(e){if(!e)return 0;let t;if(e instanceof Uint8Array)t=e;else{t=[];let i=0;for(;i<e.length;){let n,r=e.charCodeAt(i++);if(r<55296||r>=56320)n=r;else{let o=e.charCodeAt(i++);n=(r<<10)+o+(65536-(55296<<10)-56320)}n<128?t.push(n):(n<2048?t.push(n>>6&31|192):(n<65536?t.push(n>>12&15|224):t.push(n>>18&7|240,n>>12&63|128),t.push(n>>6&63|128)),t.push(n&63|128))}}this.addInt8(0),this.startVector(1,t.length,1),this.bb.setPosition(this.space-=t.length);for(let i=0,n=this.space,r=this.bb.bytes();i<t.length;i++)r[n++]=t[i];return this.endVector()}createLong(e,t){return Xe.create(e,t)}createObjectOffset(e){return e===null?0:typeof e=="string"?this.createString(e):e.pack(this)}createObjectOffsetList(e){let t=[];for(let i=0;i<e.length;++i){let n=e[i];if(n!==null)t.push(this.createObjectOffset(n));else throw new Error("FlatBuffers: Argument for createObjectOffsetList cannot contain null.")}return t}createStructOffsetList(e,t){return t(this,e.length),this.createObjectOffsetList(e),this.endVector()}};var Vu={};function Vr(l,e){Vu[l]=e}function Wu(l){let e=l.getBufferIdentifier(),t=Vu[e];return t(l)}function Uu(l){return typeof l.guid=="function"?l.guid():null}var _c=vl(wc(),1);var ua=class{get isHost(){return this._host!==void 0}_host;_client;_clientData;constructor(){this.onEnable()}onEnable(){let e="HOST-5980e65c-8438-453e-8b35-f13c736dcd81";this.trySetupHost(e)}trySetupHost(e){let t=new _c.default(e);t.on("error",i=>{console.error(i),this._host=void 0,this.trySetupClient(e)}),t.on("open",i=>{this._host=new Tc(t)})}trySetupClient(e){this._client=new _c.default,this._client.on("error",t=>{console.error("Client error",t)}),this._client.on("open",t=>{console.log("client connected",t),this._clientData=this._client.connect(e,{metadata:{id:t}}),this._clientData.on("open",()=>{console.log("Connected to host")}),this._clientData.on("data",i=>{console.log("<<",i)})})}},xc=class{_peer;constructor(e){this._peer=e}};var Tc=class extends xc{get isHost(){return!0}_connections=[];constructor(e){super(e),console.log("I AM THE HOST"),this._peer?.on("connection",this.onConnection.bind(this)),this._peer.on("close",()=>{this.broadcast("BYE")}),setInterval(()=>{this.broadcast("HELLO")},2e3)}onConnection(e){console.log("host connection",e),e.on("open",()=>{this._connections.push(e),this.broadcastConnection(e)})}broadcastConnection(e){let t=this._connections.map(i=>i.metadata?.id).filter(i=>i!==void 0);this.broadcast({type:"connection-list",connections:t})}broadcast(e){if(e!=null){console.log(">>",e);for(let t in this._peer.connections){let i=this._peer.connections[t];if(!!i)if(Array.isArray(i))for(let n of i)!n||n.send(e);else console.warn(i)}}}};var Rc="wss://needle-tiny-starter.glitch.me/socket",mt=!!N("debugnet"),pa=!!(mt||N("debugowner"));var En=class{guid;connection;get hasOwnership(){return this._hasOwnership}get isOwned(){return this._isOwned}get isConnected(){return this.connection.isConnected}_hasOwnership=!1;_isOwned=void 0;_gainSubscription;_lostSubscription;_hasOwnerResponse;constructor(e,t){this.connection=e,this.guid=t,this._gainSubscription=this.onGainedOwnership.bind(this),this._lostSubscription=this.onLostOwnership.bind(this),e.beginListen("lost-ownership",this._lostSubscription),e.beginListen("gained-ownership-broadcast",this._gainSubscription),this._hasOwnerResponse=this.onHasOwnerResponse.bind(this),e.beginListen("response-has-owner",this._hasOwnerResponse)}_isWaitingForOwnershipResponseCallback=null;updateIsOwned(){this.connection.send("request-has-owner",{guid:this.guid})}onHasOwnerResponse(e){e.guid===this.guid&&(this._isOwned=e.value)}requestOwnershipIfNotOwned(){return this._isWaitingForOwnershipResponseCallback!==null?this:(this._isWaitingForOwnershipResponseCallback=this.waitForHasOwnershipRequestResponse.bind(this),this.connection.beginListen("response-has-owner",this._isWaitingForOwnershipResponseCallback),this.connection.send("request-has-owner",{guid:this.guid}),this)}waitForHasOwnershipRequestResponse(e){e.guid===this.guid&&(this._isWaitingForOwnershipResponseCallback&&(this.connection.stopListening("response-has-owner",this._isWaitingForOwnershipResponseCallback),this._isWaitingForOwnershipResponseCallback=null),this._isOwned=e.value,e.value||(pa&&console.log("request ownership",this.guid),this.requestOwnership()))}requestOwnershipAsync(){return new Promise((e,t)=>{this.requestOwnership();let i=0,n=()=>{if(i++>10)return t("Timeout");setTimeout(()=>{this.hasOwnership?e(this):n()},100)};n()})}requestOwnership(){return pa&&console.log("Request ownership",this.guid),this.connection.send("request-ownership",{guid:this.guid}),this}freeOwnership(){return this.connection.send("remove-ownership",{guid:this.guid}),this._isWaitingForOwnershipResponseCallback&&(this.connection.stopListening("response-has-owner",this._isWaitingForOwnershipResponseCallback),this._isWaitingForOwnershipResponseCallback=null),this}destroy(){this.connection.stopListening("gained-ownership",this._gainSubscription),this.connection.stopListening("lost-ownership",this._lostSubscription),this.connection.stopListening("response-has-owner",this._hasOwnerResponse),this._isWaitingForOwnershipResponseCallback&&(this.connection.stopListening("response-has-owner",this._isWaitingForOwnershipResponseCallback),this._isWaitingForOwnershipResponseCallback=null)}onGainedOwnership(e){e.guid===this.guid&&(this._isOwned=!0,this.connection.connectionId===e.owner?(pa&&console.log("GAINED OWNERSHIP",this.guid),this._hasOwnership=!0):this._hasOwnership=!1)}onLostOwnership(e){e===this.guid&&(pa&&console.log("LOST OWNERSHIP",this.guid),this._hasOwnership=!1,this._isOwned=!1)}};var fa=class{context;_peer=null;constructor(e){this.context=e}get peer(){return this._peer||(this._peer=new ua),this._peer}tryGetState(e){return e==="invalid"?null:this._state[e]}get connectionId(){return this._connectionId}get isDebugEnabled(){return mt}get isConnected(){return this.connected}get currentRoomName(){return this._currentRoomName}get allowEditing(){return this._currentRoomAllowEditing}get currentRoomViewId(){return this._currentRoomViewId}get isInRoom(){return this._isInRoom}get currentLatency(){return this._currentDelay}userIsInRoom(e){return this._currentInRoom.indexOf(e)!==-1}_usersInRoomCopy=[];usersInRoom(e=null){e||(e=this._usersInRoomCopy),e.length=0;for(let t of this._currentInRoom)e.push(t);return e}joinRoom(e,t=!1){this.connect(),mt&&console.log("join: "+e),this.send("join-room",{room:e,viewOnly:t},0)}leaveRoom(e=null){if(e||(e=this.currentRoomName),!e){console.error("Can not leave unknown room");return}this.send("leave-room",{room:e})}send(e,t=null,i=2){if(t===null&&(t={}),i===2){this._defaultMessagesBuffer.push({key:e,value:t});return}return this.sendWithWebsocket(e,t,i)}sendDeleteRemoteState(e){this.send("delete-state",{guid:e,dontSave:!0}),delete this._state[e]}sendBinary(e){mt&&console.log("<< bin",e.length),this._ws?.send(e)}_defaultMessagesBuffer=[];_defaultMessagesBufferArray=[];sendBufferedMessagesNow(){if(!this._ws)return;this._defaultMessagesBufferArray.length=0;let e=Object.keys(this._defaultMessagesBuffer).length;for(let i in this._defaultMessagesBuffer){let n=this._defaultMessagesBuffer[i];if(e<=1){this.sendWithWebsocket(n.key,n.value,3);break}let r=this.toMessage(n.key,n.value);this._defaultMessagesBufferArray.push(r)}if(this._defaultMessagesBuffer.length=0,this._defaultMessagesBufferArray.length>0&&mt&&console.log("SEND BUFFERED",this._defaultMessagesBufferArray.length),this._defaultMessagesBufferArray.length<=0)return;let t=JSON.stringify(this._defaultMessagesBufferArray);this._ws?.send(t)}beginListen(e,t){return this._listeners[e]||(this._listeners[e]=[]),this._listeners[e].push(t),t}stopListening(e,t){if(!t||!this._listeners[e])return;let i=this._listeners[e].indexOf(t);i>=0&&this._listeners[e].splice(i,1)}beginListenBinrary(e,t){return this._listenersBinary[e]||(this._listenersBinary[e]=[]),this._listenersBinary[e].push(t),t}stopListenBinary(e,t){if(!this._listenersBinary[e])return;let i=this._listenersBinary[e].indexOf(t);i>=0&&this._listenersBinary[e].splice(i,1)}connect(){if(this.connected)return;mt&&console.log("connecting");let t=S.findObjectOfType(pt,this.context,!1)?.getWebsocketUrl();t&&(Rc=t),this.connectWebsocket()}_listeners={};_listenersBinary={};connected=!1;channelId;_connectionId=null;_isConnectingToWebsocket=!1;_ws;_waitingForSocket={};_isInRoom=!1;_currentRoomName=null;_currentRoomViewId=null;_currentRoomAllowEditing=!0;_currentInRoom=[];_state={};_currentDelay=-1;connectWebsocket(){if(this._isConnectingToWebsocket)return;this._isConnectingToWebsocket=!0,console.log("Connecting to "+Rc);let e=new rv(Rc).onOpen(()=>{this._ws=e,this._isConnectingToWebsocket=!1,this.connected=!0,console.log("Connected to websocket"),this.onSendQueued(0)}).onClose(t=>{this.connected=!1,this._isInRoom=!1}).onError((t,i)=>{console.error(t,i)}).onMessage(this.onMessage.bind(this)).onRetry(()=>{console.log("websocket connection retry")}).build()}onMessage(e,t){let i=t.data;try{if(typeof i!="string"){i.size&&this.handleIncomingBinaryMessage(i);return}let n=JSON.parse(i);if(Array.isArray(n))for(let r of n)this.handleIncomingStringMessage(r);else this.handleIncomingStringMessage(n);return}catch{mt&&i==="pong"&&console.log("<<",i)}}async handleIncomingBinaryMessage(e){let t=await e.arrayBuffer();var i=new Uint8Array(t);let n=new di(i),r=n.getBufferIdentifier(),o=this._listenersBinary[r],s=Wu(n),c=Uu(s);if(c&&typeof c=="string"&&(this._state[c]=s),!o)return;let d=s??n;for(let a of o)a(d)}handleIncomingStringMessage(e){if(mt&&console.log("<<",e.key??e),e.key)switch(e.key){case"connection-start-info":if(e.data){let o=e.data;o&&(console.assert(o.id!==void 0&&o.id!==null&&o.id.length>0,"server did not send connection id",o.id),console.log("Your id is: "+o.id,this.context.alias??""),this._connectionId=o.id)}else console.warn("Expected connection id in "+e.key);break;case"joined-room":if(mt&&console.log(e),e){this._isInRoom=!0;let o=e;this._currentRoomName=o.room,this._currentRoomViewId=o.viewId,this._currentRoomAllowEditing=o.allowEditing??!0,console.log("Room view id",this._currentRoomViewId),this._currentInRoom.length=0,this._currentInRoom.push(...o.inRoom),mt&&console.log("joined room with",this._currentInRoom,this.context.alias??"")}this.onSendQueued(1);break;case"left-room":e.room===this.currentRoomName&&(this._isInRoom=!1,this._currentRoomName=null,this._currentInRoom.length=0);break;case"user-joined-room":if(e.data){let o=e.data;this._currentInRoom.push(o.userId),mt&&console.log(o.userId+" joined","now in room:",this._currentInRoom)}break;case"user-left-room":if(e.data){let o=e.data,s=this._currentInRoom.indexOf(o.userId);s>=0&&(console.log(o.userId+" left",this.context.alias??""),this._currentInRoom.splice(s,1)),o.userId===this.connectionId&&console.log("you left the room")}break;case"ping":case"pong":let r=e.data?.time;r&&(this._currentDelay=this.context.time.time-r),mt&&console.log("Current latency: "+this._currentDelay.toFixed(1)+" sec","Clients in room: "+this._currentInRoom?.length);break}let t=this._listeners[e.key];if(t)for(let n of t)n(e.data);let i=e.data;i&&(this._state[i.guid]=i)}toMessage(e,t){return{key:e,data:t}}sendWithWebsocket(e,t,i=1){if(!this._ws){let r=this._waitingForSocket[i]||[];r.push(()=>this.sendWithWebsocket(e,t,i)),this._waitingForSocket[i]=r;return}let n=JSON.stringify(this.toMessage(e,t));mt&&console.log(">>",e),this._ws.send(n)}onSendQueued(e){let t=this._waitingForSocket[e];if(t){for(let i of t)i();t.length=0}}};import*as Xt from"three";import{OrbitControls as sv}from"three/examples/jsm/controls/OrbitControls";import{Object3D as ov}from"three";var Fi=class extends M{constraintActive=!0;locked=!1;sources=[]};k([A(ov)],Fi.prototype,"sources",2);import*as ls from"three";var gt=class extends M{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;awake(){this._lookTargetPosition=new ls.Vector3}onEnable(){this._enableTime=this.context.time.time;let t=S.getComponent(this.gameObject,ne)?.cam;this._controls||(console.assert(t!=null,"Missing camera",this),t&&(this._cameraObject=t),this._controls=new sv(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"?(this._controls.minDistance=this.minZoom,this._controls.maxDistance=this.maxZoom):(this._controls.minZoom=this.minZoom,this._controls.maxZoom=this.maxZoom),this._controls.dampingFactor=this.dampingFactor,this._controls.enablePan=this.enablePan)}onDisable(){this._controls&&(this._controls.enabled=!1,this._controls.autoRotate=!1)}start(){if(this._controls){let e=S.getComponent(this.gameObject,ne);if(e&&!this.setFromTargetPosition()){console.log("NO TARGET");let t=new ls.Vector3(0,0,-1).applyMatrix4(e.cam.matrixWorld);this.setTarget(t,!0)}}this.startCoroutine(this.startRaycastDelayed())}*startRaycastDelayed(){if(yield,!this.setFromTargetPosition()){let e=new je;e.screenPoint=new ls.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.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 i=this.lookAtConstraint?.sources;if(i&&i.length>0){let n=i[e];if(n)return n.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&&S.isActiveInHierarchy(t.object)){if(this._lookTargetPosition.copy(t.point),this._lerpToTargetPosition=!0,this._cameraTargetPosition=null,this.context.mainCamera){this._lerpCameraToTarget=!0;let i=q(this.context.mainCamera);this._cameraTargetPosition=i.clone().sub(this.controls.target).add(this._lookTargetPosition)}break}}};k([A(Fi)],gt.prototype,"lookAtConstraint",2);import{Color as av}from"three";var we=class extends av{alpha=1;get isRGBAColor(){return!0}constructor(e,t,i,n){super(e,t,i),this.alpha=n}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 i=e;return i.alpha&&(this.alpha=Q.lerp(this.alpha,i.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 lv}from"three";var Xu=N("debugcam"),ne=class extends M{get aspect(){return this._cam instanceof lv?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 Xt.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(){Xu&&console.log(this),this.buildCamera(),this.tag=="MainCamera"&&this.context.setCurrentCamera(this),this.applyClearFlagsIfIsActiveCamera()}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 Xt.PerspectiveCamera(this.fieldOfView,window.innerWidth/window.innerHeight,this._nearClipPlane,this._farClipPlane),t.fov=this.fieldOfView;else{let i=this.orthographicSize*100;t=new Xt.OrthographicCamera(window.innerWidth/-i,window.innerWidth/i,window.innerHeight/i,window.innerHeight/-i,this._nearClipPlane,this._farClipPlane)}this._cam=t,this.layer===0&&this._cam.layers.enableAll(),this.tag=="MainCamera"&&this.context.setCurrentCamera(this)}applyClearFlagsIfIsActiveCamera(){if(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;return t==="additive"||t==="alpha-blend"}enableSkybox(){this._skybox||(this._skybox=new Cc(this)),this._skybox.enable()}};k([A()],ne.prototype,"fieldOfView",1),k([A()],ne.prototype,"nearClipPlane",1),k([A()],ne.prototype,"farClipPlane",1),k([A()],ne.prototype,"clearFlags",1),k([A()],ne.prototype,"orthographic",2),k([A()],ne.prototype,"orthographicSize",2),k([A()],ne.prototype,"ARBackgroundAlpha",2),k([A(we)],ne.prototype,"backgroundColor",1);var Cc=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?(Xu&&console.log("Set skybox",this._camera,this._skybox),this._skybox.encoding=Xt.sRGBEncoding,this._skybox.mapping=Xt.EquirectangularReflectionMapping,this.context.scene.background=this._skybox):console.warn("Failed to load/find skybox texture",this)}};function Qu(l){let e="created/implictly",t=new Xt.Object3D;l.add(t);let i=S.addNewComponent(t,ne,!1);i.sourceId=e;let n=S.addNewComponent(t,gt,!1);return n.sourceId=e,i}import{EffectComposer as OE}from"three/examples/jsm/postprocessing/EffectComposer.js";import{RenderPass as AE}from"three/examples/jsm/postprocessing/RenderPass";import{AnimationClip as cv,MathUtils as dv}from"three";var Wr=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,i,n){this._name=e.name,this._nameHash=e.hash,this._normalizedTime=t,this._length=i,this._speed=n}};function Yu(l,e){return{name:"",isLooping:!1,guid:e?.generateUUID()??dv.generateUUID(),index:-1,clip:new cv(l,1,[])}}import{AnimationClip as gv,AnimationMixer as bv,AxesHelper as vv,Euler as Ku,LoopOnce as yv,Quaternion as Qt,Vector3 as hs}from"three";import*as wa from"three";var Sc=class{_types={};add(e,t){let i=this._types[e];i===void 0?this._types[e]=t:i!==t&&console.warn("Type name exists multiple times in your project and may lead to runtime errors:",e)}get(e){return this._types[e]}},D=new Sc;var hi=N("gizmos"),Ie=N("debugextension");var ga=N("debugresolvedependencies"),Pc="/extensions/",hv=[{prefix:"/nodes/",dependencyName:"node"},{prefix:"/meshes/",dependencyName:"mesh"},{prefix:"/materials/",dependencyName:"material"},{prefix:"/textures/",dependencyName:"texture"},{prefix:"/animations/",dependencyName:"animation"}];async function Ur(l,e){ga&&console.log(l,e);let t=[];Oc(hv,l,e,t);let i=await Promise.all(t);return typeof e=="string"&&i.length===1?i[0]:i}function Oc(l,e,t,i){if(typeof t=="object"&&t!==void 0&&t!==null)for(let n of Object.keys(t)){let r=t[n];if(typeof r=="string"){let o=Zu(e,r);if(o!==null)typeof o.then=="function"?i.push(o.then(s=>t[n]=s)):t[n]=o;else for(let s of l){let c=Ac(s.prefix,r);if(c>=0){ga&&console.log(s,c,s.dependencyName),i.push(e?.getDependency(s.dependencyName,c).then(d=>(t[n]=d,d)));break}}}else if(Array.isArray(r))for(let o=0;o<r.length;o++){let s=r[o],c=Zu(e,s);if(c!==null){typeof c.then=="function"?i.push(c.then(d=>r[o]=d)):r[o]=c;continue}for(let d of l){let a=Ac(d.prefix,s);if(a>=0){ga&&console.log(d,a,d.dependencyName),i.push(e?.getDependency(d.dependencyName,a).then(h=>r[o]=h));break}}typeof s=="object"&&Oc(l,e,s,i)}else typeof r=="object"&&Oc(l,e,r,i)}else typeof t=="string"&&uv(l,e,t,i)}function Zu(l,e){if(l&&l.plugins&&typeof e=="string"&&e.startsWith(Pc)){let t=e.substring(Pc.length),i=t.indexOf("/");i>=0&&(t=t.substring(0,i));let n=l.plugins[t];if(Ie&&console.log(t,n),typeof n?.resolve=="function"){let r=e.substring(Pc.length+t.length+1);return n.resolve(l,r)}}return null}function uv(l,e,t,i){for(let n of l){let r=Ac(n.prefix,t);if(r>=0)return ga&&console.log(n,r,n.dependencyName),i.push(e?.getDependency(n.dependencyName,r).then(o=>o)),!0}return!1}function Ac(l,e){if(typeof e=="string"&&e.startsWith(l)){let t=e.substring(l.length),i=Number.parseInt(t);if(i>=0)return i}return-1}var kc="NEEDLE_persistent_assets";function Ju(l){return l?.___persistentAsset===!0}var ba=class{get name(){return kc}parser;constructor(e){this.parser=e}async afterRoot(e){if(!this.parser?.json?.extensions)return;let t=this.parser.json.extensions[kc];if(!t)return;Ie&&console.log(t);let i=new Array;for(let n of t?.assets){let r=Ur(this.parser,n);r&&i.push(r)}await Promise.all(i)}resolve(e,t){let i=Number.parseInt(t);if(i>=0){Ie&&console.log(t);let n=e.json.extensions[kc];if(n){let r=n?.assets[i];if(r&&typeof r=="object"){r.___persistentAsset=!0;let o=r.__type;if(o){let s=D.get(o)}}return r}}return null}};var or=N("debugserializer"),Ic=class{register(e,t){if(this.typeMap[e]!==void 0){if(this.typeMap[e]===t)return;console.warn("Type "+e+" is already registered",t,this.typeMap[e])}or&&console.log("Register type serializer for "+e,t),this.typeMap[e]=t}typeMap={};getSerializer(e){if(!!e)return this.typeMap[e]}getSerializerForConstructor(e,t=0){if(t>20)return;if(!e||!e.constructor){or&&console.log("invalid type");return}let i=e.name??e.constructor?.name;if(!i){or&&console.log("invalid name",i);return}let n=this.getSerializer(i);if(n!==void 0)return or&&console.log("FOUND "+i,e.name,e.constructor.name,n,this.typeMap),n;let r=Object.getPrototypeOf(e);if(!(r.prototype||r.constructor)){or&&console.warn("No prototype for "+i,e,e.name,e.prototype,e.constructor.name);return}let s=r.prototype??r.constructor;if(s!==e){let c=this.getSerializerForConstructor(s,++t);if(c){or&&console.log("FOUND "+s.constructor.name,s.name,s,c);let d=s.name??s.constructor.name;d==="Function"?console.error("Registering Function is not allowed, something went wrong",e,s,c):this.register(d,c)}return c}}},ya=new Ic,Ni=class{constructor(e){if(Array.isArray(e))for(let t of e)ya.register(t.name,this);else ya.register(e.name,this)}},qr=class{root;gltf;gltfId;object;target;nodeId;nodeToObject;objectToNode;context;path;constructor(e){this.root=e}};function Lc(l,e){let t=l.$serializedTypes;if(t===void 0)return null;let i={};for(let n in t){let r=l[n];if(r!=null&&typeof r=="object"){let o=ya.getSerializerForConstructor(r);if(o){i[n]=o.onSerialize(r,e);continue}}i[n]=r}return i.name=l.constructor.name,typeof l.guid=="string"&&(i.guid=l.guid),i}var va=[];function $u(l,e){if(!l)return e;typeof l.$serializedTypes=="object"&&(e||(e={}),Object.assign(e,l.$serializedTypes));let t=Object.getPrototypeOf(l);return $u(t,e)}function cs(l,e,t){if(!l)return!1;if(t.target=l,l.onBeforeDeserialize!==void 0){let r=l.onBeforeDeserialize(e,t);if(typeof r=="boolean")return r}let i=$u(l);if(e){if(typeof e.guid=="string"&&(l.guid=e.guid),i)for(let r in i){let o=i[r],s=e[r];if(t.path=r,o===null)l[r]=s;else{let c=function(d){let h=d.type;return h?Mc(s,h,t,void 0,l[r]):Mc(s,d,t,void 0,l[r])};var n=c;if(l.onBeforeDeserializeMember!==void 0&&l.onBeforeDeserializeMember(r,s,t)===!0)continue;if(Array.isArray(o))for(let d=0;d<o.length;d++){let a=o[d],h=c(a);if(h!==void 0||d===o.length-1){l[r]=h;break}}else l[r]=c(o);va.length=0,l.onAfterDeserializeMember!==void 0&&l.onAfterDeserializeMember(r,s,t)}}pv(l,e)}return l.onAfterDeserialize!==void 0&&l.onAfterDeserialize(e,t),t.path=void 0,!0}function pv(l,e){for(let i of Object.keys(e)){let n=e[i];if(typeof n=="object"&&n!==null&&n!==void 0){let r=l[i];if(!r){or&&console.log(i,"is undefined on",l);continue}for(let o of Object.keys(n))r[o]===void 0&&t(n[o])&&!t(r)&&(r[o]=n[o])}}function t(i){switch(typeof i){case"number":case"string":case"boolean":return!0}return!1}}function Mc(l,e,t,i,n){let r=typeof e=="function"&&e.prototype===void 0,o=e;if(r)try{if(o=e?.call(e,n),r=!1,o==null)return}catch(a){console.error("Error in callback",a,l)}if(!r&&n instanceof o)return n;if(n&&typeof n=="object"&&Ju(n)){if(n.__concreteInstance)return n.__concreteInstance;let a=n;if(!a.$serializedTypes&&o.prototype.$serializedTypes&&(a.$serializedTypes=o.prototype.$serializedTypes),a.$serializedTypes&&cs(a,l,t),n&&o!==void 0)try{let h=new o;Ie&&console.log("Create concrete instance for persistent asset",n,"instance:",h),ds(h,n),n.__concreteInstance=h,n=h}catch(h){console.error("Error creating instance or creating values on instance",h,n,o)}return n}if(i||(i={serializer:ya.getSerializerForConstructor(o)}),Array.isArray(l)){let a=[];for(let h=0;h<l.length;h++){let u=l[h],f=Mc(u,e,t,i,u);a.push(f)}return a}let s=i.serializer;if(s)return s.onDeserialize(l,t);let c;l&&(l.isMaterial||l.isTexture||l.isObject3D)?c=l:c=new o(...fv(l));let d=c;return d.$serializedTypes&&cs(d,l,t),c}function fv(l){if(va.length=0,typeof l=="object"&&l!==null&&l!==void 0)for(let e of Object.keys(l))va.push(l[e]);return va}function ds(l,e){if(e==null||l==null)return;let t=!1;for(let i of Object.keys(e)){let n=mv(l,i);t&&n===void 0||(!n||n.writable===!0||n?.set!==void 0)&&(l[i]=e[i])}}function mv(l,e){let t;do t=Object.getOwnPropertyDescriptor(l,e);while(!t&&(l=Object.getPrototypeOf(l)));return t}var wn=N("debuganimatorcontroller"),Dc=N("debugrootmotion"),Zt=class{Play(e,t=-1,i=Number.NEGATIVE_INFINITY,n=0){if(t<0)t=0;else if(t>=this.model.layers.length){console.warn("invalid layer");return}let o=this.model.layers[t].stateMachine;for(let s of o.states)if(s.name===e||s.hash===e){wn&&console.log("transition to ",s),this.transitionTo(s,n,i);return}console.warn("Could not find "+e+" to play")}Reset(){this.setStartTransition()}SetBool(e,t){let i=typeof e=="string"?"name":"hash";return this.model?.parameters.filter(n=>n[i]===e).forEach(n=>n.value=t)}GetBool(e){let t=typeof e=="string"?"name":"hash";return this.model?.parameters.find(i=>i[t]===e)?.value??!1}SetFloat(e,t){let i=typeof e=="string"?"name":"hash";return this.model?.parameters.filter(n=>n[i]===e).forEach(n=>n.value=t)}GetFloat(e){let t=typeof e=="string"?"name":"hash";return this.model?.parameters.find(i=>i[t]===e)?.value??0}SetInteger(e,t){let i=typeof e=="string"?"name":"hash";return this.model?.parameters.filter(n=>n[i]===e).forEach(n=>n.value=t)}GetInteger(e){let t=typeof e=="string"?"name":"hash";return this.model?.parameters.find(i=>i[t]===e)?.value??0}SetTrigger(e){wn&&console.log("SET TRIGGER",e);let t=typeof e=="string"?"name":"hash";return this.model?.parameters.filter(i=>i[t]===e).forEach(i=>i.value=!0)}ResetTrigger(e){let t=typeof e=="string"?"name":"hash";return this.model?.parameters.filter(i=>i[t]===e).forEach(i=>i.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 i of t.stateMachine.states)if(i.name===e)return i;return null}normalizedStartOffset=0;_speed=1;animator;model;get context(){return this.animator?.context}bind(e){this.animator=e,this._mixer=new bv(this.animator.gameObject),this.createActions(this.animator)}clone(){let e=qo(this.model,(i,n,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 Zt(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,wn&&console.log(this)}_activeStates=[];updateActiveStates(){for(let e=0;e<this._activeStates.length;e++){let t=this._activeStates[e],i=t.motion;if(!i.action)this._activeStates.splice(e,1),e--;else{let n=i.action;n.getEffectiveWeight()<=0&&!n.isRunning()&&(wn&&console.debug("REMOVE",t.name,n.getEffectiveWeight(),n.isRunning(),n.isScheduled()),this._activeStates.splice(e,1),e--)}}}setStartTransition(){for(let e of this.model.layers){let t=e.stateMachine,i=t.states[t.defaultState];this.transitionTo(i,0,this.normalizedStartOffset)}}evaluateTransitions(){let e=!1;if(!this._activeState){if(this.setStartTransition(),!this._activeState)return;e=!0}let t=this._activeState,i=t.motion.action,n=0;for(let o of t.transitions){if(++n,!o.hasExitTime&&o.conditions.length<=0)continue;let s=!0;for(let c of o.conditions)if(!this.evaluateCondition(c)){s=!1;break}if(!!s){wn&&s&&console.log("All conditions are met",o.conditions,i);for(let c of o.conditions){let d=this.model.parameters.find(a=>a.name===c.parameter);d?.type===9&&(d.value=!1)}if(i){let c=t.motion.clip.duration,d=c<=0?1:i.time/c;if(!o.hasExitTime||d>=o.exitTime&&i.time>=i.getClip().duration){i.clampWhenFinished=!0,wn&&(console.log("transition to "+o.destinationState,o),console.log(i.time,o.exitTime)),this.transitionTo(o.destinationState,o.duration,o.offset);return}}else{this.transitionTo(o.destinationState,o.duration,o.offset);return}break}}let r=!1;if(t.motion.isLooping&&i&&i.time>=i.getClip().duration&&(r=!0,i.reset(),i.time=0,i.play()),!r&&t&&!e&&i&&this.animator&&t.behaviours){let o=i?.getClip().duration,s=i.time/o,c=new Wr(this._activeState,s,o,this._speed);for(let d of t.behaviours)d.instance&&d.instance.onStateUpdate?.call(d.instance,this.animator,c,0)}}transitionTo(e,t,i){if(!this.animator)return;let n=0;if(typeof e=="number"&&(e==-1&&(e=this.model.layers[n].stateMachine.defaultState),e=this.model.layers[n].stateMachine.states[e]),!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,a=this._activeState.motion.action.time/d,h=new Wr(this._activeState,a,d,this._speed);for(let u of this._activeState.behaviours)u.instance?.onStateExit?.call(u.instance,this.animator,h,n)}let o=this._activeState?.motion.action;o&&o.fadeOut(t),r&&(e.motion.action=e.motion.action_loopback,e.motion.action_loopback=o);let s=this._activeState;this._activeState=e;let c=e.motion?.action;if(c){i=Math.max(0,Math.min(1,i)),c.isRunning()&&c.stop(),c.reset(),c.timeScale=this._speed,c.enabled=!0;let d=e.motion.clip.duration;if(c.time=i*d,c.clampWhenFinished=!0,c.setLoop(yv,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 a=new Wr(e,i,d,this._speed);for(let h of this._activeState.behaviours)h.instance?.onStateEnter?.call(h.instance,this.animator,a,n)}}else console.warn("No action",e.motion,this);wn&&console.log("TRANSITION FROM "+s?.name+" TO "+e.name,t,o,c,c?.getEffectiveTimeScale(),c?.getEffectiveWeight(),c?.isRunning(),c?.isScheduled(),c?.paused)}createAction(e){if(this._mixer.uncacheClip(e),this.animator?.applyRootMotion){this.rootMotionHandler||(this.rootMotionHandler=new Hc(this));let t=this.animator.gameObject;return this.rootMotionHandler.createClip(this._mixer,t,e)}else return this._mixer.clipAction(e)}evaluateCondition(e){let t=this.model.parameters.find(i=>i.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 i=t.stateMachine;for(let n=0;n<i.states.length;n++){let r=i.states[n];if(r.motion||(r.motion=Yu(r.name)),this.animator&&r.motion.clips){let o=r.motion.clips?.find(s=>s.node.name===this.animator?.gameObject?.name);r.motion.clip=o?.clip}if(!r.motion.clip){let o=new gv;r.motion.clip=o}if(r.motion?.clip){let o=r.motion.clip,s=this.createAction(o);r.motion.action=s}if(r.behaviours&&Array.isArray(r.behaviours))for(let o of r.behaviours){if(!o?.typeName)continue;let s=D.get(o.typeName),c=new s;c.isStateMachineBehaviour&&(c._context=this.context??void 0,ds(c,o.properties),o.instance=c),wn&&console.log("Created animator controller behaviour",r.name,o.typeName,o.properties,c)}}}}*enumerateActions(){for(let e of this.model.layers){let t=e.stateMachine;for(let i=0;i<t.states.length;i++){let n=t.states[i];n?.motion&&(n.motion.action&&(yield n.motion.action),n.motion.action_loopback&&(yield n.motion.action_loopback))}}}rootMotionHandler},Ea=class{track;createdInterpolant;originalEvaluate;customEvaluate;constructor(e,t){this.track=e;let i=e,n=i.createInterpolant.bind(e);i.createInterpolant=()=>(i.createInterpolant=n,this.createdInterpolant=n(),this.originalEvaluate=this.createdInterpolant.evaluate.bind(this.createdInterpolant),this.customEvaluate=r=>{if(!this.originalEvaluate)return;let o=this.originalEvaluate(r);return t(r,o)},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}},Re=class{set action(e){this._action=e}get action(){return this._action}_action;root;clip;positionWrapper=null;rotationWrapper=null;context;positionChange=new hs;rotationChange=new Qt;constructor(e,t,i,n,r){if(this.context=e,this.root=t,this.clip=i,Re.firstKeyframeRotation[i.uuid]||(Re.firstKeyframeRotation[i.uuid]=new wa.Quaternion),r){let o=r.values;Re.firstKeyframeRotation[i.uuid].set(o[0],o[1],o[2],o[3])}Re.spaceRotation[i.uuid]||(Re.spaceRotation[i.uuid]=new Qt),Re.effectiveSpaceRotation[i.uuid]||(Re.effectiveSpaceRotation[i.uuid]=new Qt),Re.clipOffsetRotation[i.uuid]=new Qt,r&&Re.clipOffsetRotation[i.uuid].set(r.values[0],r.values[1],r.values[2],r.values[3]).invert(),this.handlePosition(i,n),this.handleRotation(i,r)}onStart(e){if(e.getClip()!==this.clip)return;let t=Re.lastObjRotation[this.root.uuid];Re.spaceRotation[this.clip.uuid].copy(t);{let i=new wa.Euler().setFromQuaternion(t);console.log("START",this.clip.name,Q.toDegrees(i.y))}}getClipRotationOffset(){return Re.clipOffsetRotation[this.clip.uuid]}handlePosition(e,t){if(t){let i=this.root;Dc&&i.add(new vv),Re.lastObjPosition[i.uuid]||(Re.lastObjPosition[i.uuid]=new hs);let n=new hs,r=new hs,o=0;this.positionWrapper=new Ea(t,(s,c)=>{let d=this.action.getEffectiveWeight();if(Dc&&i.position.length()>8&&i.position.set(0,i.position.y,0),s>o){n.set(c[0],c[1],c[2]),n.sub(r),n.multiplyScalar(d),n.applyQuaternion(this.getClipRotationOffset());let a=this.clip.uuid;n.applyQuaternion(Re.spaceRotation[a]),this.positionChange.copy(n)}return r.fromArray(c),o=s,c[0]=0,c[1]=0,c[2]=0,c})}}handleRotation(e,t){if(t){if(Dc){let s=t.values,c=new Ku().setFromQuaternion(new Qt(s[0],s[1],s[2],s[3]));console.log(e.name,t.name,"FIRST ROTATION IN TRACK",Q.toDegrees(c.y));let d=t.values.length-4,a=new Qt().set(s[d],s[d+1],s[d+2],s[d+3]),h=new Ku().setFromQuaternion(a);console.log(e.name,t.name,"LAST ROTATION IN TRACK",Q.toDegrees(h.y))}let i=this.root;Re.lastObjRotation[i.uuid]||(Re.lastObjRotation[i.uuid]=new Qt);let n=0,r=new Qt,o=new Qt;this.rotationWrapper=new Ea(t,(s,c)=>(s>n&&(o.set(c[0],c[1],c[2],c[3]),r.invert(),o.multiply(r),this.rotationChange.copy(o)),r.fromArray(c),n=s,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(Re.identityQuaternion,1-e)}},Yt=Re;z(Yt,"lastObjPosition",{}),z(Yt,"lastObjRotation",{}),z(Yt,"firstKeyframeRotation",{}),z(Yt,"spaceRotation",{}),z(Yt,"effectiveSpaceRotation",{}),z(Yt,"clipOffsetRotation",{}),z(Yt,"identityQuaternion",new Qt);var Hc=class{controller;handler=[];root;constructor(e){this.controller=e}createClip(e,t,i){this.root=t;let n="";t&&"name"in t&&(n=t.name);let r=this.findRootTrack(i,".position"),o=this.findRootTrack(i,".quaternion"),s=new Yt(this.controller.context,t,i,r,o);this.handler.push(s);let c=e.clipAction(i);return s.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 hs;summedRotation=new Qt;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),Yt.lastObjRotation[this.root.uuid].copy(this.root.quaternion)}findRootTrack(e,t){let i=e.tracks;for(let n of i)if(n.name.endsWith(t))return n;return null}};var Ev=N("debuganimator"),bt=class extends M{applyRootMotion=!1;hasRootMotion=!1;keepAnimatorControllerStateOnDisable=!1;set runtimeAnimatorController(e){this._animatorController&&this._animatorController.model===e||(e?e instanceof Zt?this._animatorController=e:this._animatorController=new Zt(e):this._animatorController=null)}get runtimeAnimatorController(){return this._animatorController}Play(e,t=-1,i=Number.NEGATIVE_INFINITY,n=0){this.runtimeAnimatorController?.Play(e,t,i,n)}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=Q.lerp(e.x,e.y,Math.random())}set minMaxOffsetNormalized(e){this.normalizedStartOffset=Q.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}Ev&&console.log("ANIMATOR",this.name,this)}}onDisable(){this.keepAnimatorControllerStateOnDisable||this._animatorController?.Reset()}onBeforeRender(){this._animatorController&&this._animatorController.update()}};k([A()],bt.prototype,"applyRootMotion",2),k([A()],bt.prototype,"hasRootMotion",2),k([A()],bt.prototype,"keepAnimatorControllerStateOnDisable",2),k([A()],bt.prototype,"runtimeAnimatorController",1);import*as Xr from"three";var Jt=class extends M{playAutomatically=!0;randomStartTime=!0;_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&&he.markDirty(this.gameObject)}}getAction(e){return this.actions?.find(t=>t.getClip().name===e)}play(e,t){if(this.init(),!this.mixer)return;let i=e;if(typeof e=="number"){if(e>=this.animations.length)return;i=this.animations[e]}else typeof e=="string"&&(i=this.animations.find(r=>r.name===e));if(!i){console.error("Could not find clip",e);return}for(let r of this.actions)if(r.getClip()===i)return this.internalOnPlay(r,t);let n=this.mixer.clipAction(i);return this.actions.push(n),this.internalOnPlay(n,t)}internalOnPlay(e,t){var i=this.currentAction;if(i===e&&i.isRunning()&&i.time<i.getClip().duration){let o=this.tryFindHandle(e);if(o)return o.getPromise()}let n=t?.exclusive??!0;t?.fadeDuration?(n&&i?.fadeOut(t.fadeDuration),e.fadeIn(t.fadeDuration)):n&&i?.stop(),e.reset(),e.enabled=!0,e.time=0,e.timeScale=1,t?.clampWhenFinished&&(e.clampWhenFinished=!0),t?.startTime!==void 0&&(e.time=t.startTime),t?.loop!==void 0&&(e.loop=t.loop?Xr.LoopRepeat:Xr.LoopOnce),e.play();let r=new jc(e,this.mixer,t,o=>{this._handles.splice(this._handles.indexOf(r),1)});return this._handles.push(r),r.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 Xr.AnimationMixer(this.gameObject);for(let e=0;e<this.animations.length;e++){let t=this.mixer.clipAction(this.animations[e]);this.actions.push(t)}}}};k([A()],Jt.prototype,"playAutomatically",2),k([A()],Jt.prototype,"randomStartTime",2);var jc=class{mixer;action;promise=null;resolve=null;reject=null;_options;_resolveCallback=null;_rejectCallback=null;_loopCallback;_finishedCallback;_resolvedOrRejectedCallback;constructor(e,t,i,n){this.action=e,this.mixer=t,this._resolvedOrRejectedCallback=n,this._options=i}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 yf}from"three/examples/jsm/loaders/GLTFLoader.js";import{Vector3 as wv}from"three";var _n=class extends M{from;to;width=0;centered=!0;_centerPos;awake(){this._centerPos=new wv}update(){if(!this.from||!this.to)return;let e=q(this.from).clone(),t=q(this.to).clone(),i=e.distanceTo(t);this._centerPos.copy(e),this._centerPos.add(t),this._centerPos.multiplyScalar(.5),ie(this.gameObject,this.centered?this._centerPos:e),this.gameObject.lookAt(q(this.to).clone()),this.gameObject.scale.set(this.width,this.width,i)}};k([A(S)],_n.prototype,"from",2),k([A(S)],_n.prototype,"to",2);var ui=class{time;value;inTangent;inWeight;outTangent;outWeight;weightedMode};k([A()],ui.prototype,"time",2),k([A()],ui.prototype,"value",2),k([A()],ui.prototype,"inTangent",2),k([A()],ui.prototype,"inWeight",2),k([A()],ui.prototype,"outTangent",2),k([A()],ui.prototype,"outWeight",2),k([A()],ui.prototype,"weightedMode",2);var sr=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 i of this.keys){if(t&&i.time>e&&e>t.time)return Q.lerp(t.value,i.value,(e-t.time)/(i.time-t.time));t=i}return this.keys[this.keys.length-1].value}};k([A(ui)],sr.prototype,"keys",2);import*as ep from"three";import*as us from"three";import{PositionalAudioHelper as _v}from"three/examples/jsm/helpers/PositionalAudioHelper.js";var _a=class extends EventTarget{context;get hasFocus(){return document.hasFocus()}get isVisible(){return this._isVisible}_isVisible=!0;constructor(e){super(),this.context=e,window.addEventListener("visibilitychange",this.onVisiblityChanged.bind(this),!1)}onVisiblityChanged(e){switch(e.target.visibilityState){case"hidden":this._isVisible=!1,this.dispatchEvent(new Event("application-hidden"));break;case"visible":this._isVisible=!0,this.dispatchEvent(new Event("application-visible"));break}}};var at=N("debugaudio");var Be=class extends M{static get userInteractionRegistered(){return Be._didCallBeginWaitForUserInteraction||(Be._didCallBeginWaitForUserInteraction=!0,Be._beginWaitForUserInteraction()),Be._userInteractionRegistered}static registerWaitForAllowAudio(e){if(e!==null){if(this._userInteractionRegistered){e();return}this.callbacks.indexOf(e)===-1&&this.callbacks.push(e),Be._didCallBeginWaitForUserInteraction||(Be._didCallBeginWaitForUserInteraction=!0,Be._beginWaitForUserInteraction())}}static _beginWaitForUserInteraction(e=null){if(this._userInteractionRegistered){e&&e();return}e!==null&&this.registerWaitForAllowAudio(e);let i=(()=>{if(i!=null&&!Be._userInteractionRegistered){Be._userInteractionRegistered=!0,console.log("registered interaction, can play audio now"),document.removeEventListener("pointerdown",i),document.removeEventListener("click",i),document.removeEventListener("dragstart",i),document.removeEventListener("touchstart",i);for(let n of this.callbacks)n();this.callbacks.length=0}}).bind(this);document.addEventListener("pointerdown",i),document.addEventListener("click",i),document.addEventListener("dragstart",i),document.addEventListener("touchstart",i)}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&&(at&&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&&Be._userInteractionRegistered){let e=S.getComponent(this.context.mainCamera,$t)??S.findObjectOfType($t,this.context);e?.listener&&(this.sound=new us.PositionalAudio(e.listener),this.gameObject.add(this.sound))}return this.sound}get ShouldPlay(){return this.shouldPlay}_focusCallback;awake(){this.audioLoader=new us.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&&Be._userInteractionRegistered&&this.play()},this.context.application.addEventListener("application-visible",this._focusCallback)}onDestroy(){this.context.application.removeEventListener("application-visible",this._focusCallback)}onEnable(){Be._userInteractionRegistered?this.playOnAwake&&this.context.application.isVisible&&this.play():Be._beginWaitForUserInteraction(()=>{this.enabled&&!this.destroyed&&this.shouldPlay&&this.loadAndPlay(this.clip)})}onDisable(){this.stop()}lerp=(e,t,i)=>e*(1-i)+t*i;onLoaded(e){at&&console.log("audio buffer loaded"),Be.registerWaitForAllowAudio(()=>{at&&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(),at&&console.log(this.name,this.shouldPlay,Be.userInteractionRegistered,this),this.shouldPlay&&Be._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(at&&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?at&&!this.helper&&(this.helper=new _v(e,e.getRefDistance()),e.add(this.helper)):this.helper&&this.helper.parent&&this.helper.removeFromParent()}loadAndPlay(e){if(e&&(this.clip=e),this.clip&&(at&&console.log(this.clip),this.clip.endsWith(".mp3")||this.clip.endsWith(".wav"))){if(this.audioLoader||(this.audioLoader=new us.AudioLoader),this.shouldPlay=!0,this._lastClipStartedLoading===this.clip){at&&console.log("Is currently loading:",this._lastClipStartedLoading,this);return}this._lastClipStartedLoading=this.clip,at&&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,at&&console.log("play",this.sound?.getVolume(),this.sound),this.sound&&!this.sound.isPlaying&&this.sound.play()}pause(){at&&console.log("Pause",this),this._hasEnded=!0,this.shouldPlay=!1,this.sound&&this.sound.isPlaying&&(this._lastContextTime=this.sound?.context.currentTime,this.sound.pause())}stop(){at&&console.log("Pause",this),this._hasEnded=!0,this.shouldPlay=!1,this.sound&&(this._lastContextTime=this.sound?.context.currentTime,at&&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,at&&console.log("Audio clip ended",this.clip),this.sound.dispatchEvent({type:"ended",target:this}))}},ue=Be;z(ue,"_didCallBeginWaitForUserInteraction",!1),z(ue,"callbacks",[]),z(ue,"_userInteractionRegistered",!1),k([A()],ue.prototype,"clip",2),k([A()],ue.prototype,"playOnAwake",2),k([A()],ue.prototype,"loop",1),k([A()],ue.prototype,"spatialBlend",1),k([A()],ue.prototype,"minDistance",1),k([A()],ue.prototype,"maxDistance",1),k([A()],ue.prototype,"volume",1),k([A()],ue.prototype,"rollOffMode",2);var $t=class extends M{get listener(){return this._listener==null&&(this._listener=new ep.AudioListener),this._listener}_listener=null;awake(){ue.registerWaitForAllowAudio(()=>{let e=this.listener;if(e==null||e.parent)return;let t=S.getComponentInParent(this.gameObject,ne);t?t.cam.add(e):this.gameObject.add(e)})}};import{GLTFLoader as Rv}from"three/examples/jsm/loaders/GLTFLoader";import*as Ra from"three";var cp=vl(lp(),1),xa=class{success;filename;hash;size;url;constructor(e,t,i,n){this.success=e,this.filename=t,this.hash=i,this.size=n}};async function dp(l,e){let t=await l.arrayBuffer(),i=hp(t),n=l.name.split(".").pop(),r=i+"."+n,o=l.name.split(".").shift();console.assert(o!==void 0);let s={alias:o,filename:r},d=await(await fetch(e+"/exists",{method:"POST",body:JSON.stringify(s)})).json();if(d.success||console.warn("exists check did fail"),d.exists)return console.log("file already exists",i),new xa(!0,r,i,l.size);console.log("begin uploading file",o,l.size);let a=new FormData;a.append("file",l);let h={};h.filesize=l.size,o&&(h.alias=o);let f=await(await fetch(e+"/upload/file",{method:"POST",body:a,headers:h})).json();if(f?.success===!1)return f.message!==void 0?console.error("Upload failed:",f.message):console.error("Upload failed"),null;console.assert(f.hash_sum===i,"hash sum did not match","received:",f.hash_sum,"expected:",i),f.success&&console.log("successfully uploaded",i,f.id);let E=new xa(f.success,r,i,l.size);return E.url=e,E}function hp(l){return(0,cp.default)(new Uint8Array(l))}async function Ta(l,e,t,i,n=!1){try{let r=await fetch(i+"/download/file",{method:"POST",body:l});if(r.status!==200)return console.error("download failed",r),null;let o=await r.blob(),s=await o.arrayBuffer();n||console.assert(o.size===t,"size mismatch","expected:",t,"got:",o.size);let c=hp(s);return n||console.assert(c===e,"hash mismatch, downloaded file is invalid"),o.arrayBuffer()}catch(r){console.error(r)}return null}async function up(l,e){let t=await fetch(l),i=t.body?.getReader(),n=t.headers.get("Content-Length"),r=n?parseInt(n):0;if(!i)return null;let o=0,s=[];for(;;){let{done:a,value:h}=await i.read();if(h&&(s.push(h),o+=h.length,e.call(null,new ProgressEvent("progress",{loaded:o,total:r}))),a)break}let c=new Uint8Array(o),d=0;for(let a of s)c.set(a,d),d+=a.length;return c}var ps=N("debugavatar"),ar=class{root;head;leftHand;rigthHand;get isValid(){return this.head!==null&&this.head!==void 0}constructor(e,t,i,n){this.root=e,this.head=t,this.leftHand=i,this.rigthHand=n,this.root?.traverse(r=>r.layers.set(2))}},xn=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 i=null;if(typeof t=="string"){if(i=await this.loadAvatar(e,t),!i){let r=new ye;i=S.instantiate(hn(t,e.scene),r)}}else i=t;if(!i)return null;let n=this.findAvatar(i);return n.isValid?(ps&&console.log("[Custom Avatar] valid config",t,ps?n:""),n):(console.warn("[Custom Avatar] config isn't valid",t,ps?n:""),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(ps&&console.log("[Custom Avatar] "+t+", loading..."),t.endsWith(".glb")||(t+=".glb"),this.avatarRegistryUrl===null){let n=await fetch("./"+t),r=null;if(n.ok){let s=await n.blob();s&&(r=await s.arrayBuffer())}return!r&&(r=await Ta(t,t,0,"no url here go away",!0),!r)?null:(await Qr(e,r,null,0))?.scene??null}let i=new Rv;return nr(i,e),new Promise((n,r)=>{let o=this.avatarRegistryUrl+"/"+t;i.load(o,async s=>{await Ca(e,o,s),n(s.scene)},s=>{ps&&console.log("[Custom Avatar] "+s.loaded/s.total*100+"% loaded of "+s.total/1024+"kB")},s=>{console.error("[Custom Avatar] Error when loading: "+s),n(null)})})}cacheModel(e,t){}findAvatar(e){let t=e,i=t;i.children.length==1&&(i=e.children[0]);let n=this.findAvatarPart(i,["head"]),r=this.findAvatarPart(i,["left","hand"]),o=this.findAvatarPart(i,["right","hand"]);if(!n){n=t;let c=new Ra.Vector3;new Ra.Box3().setFromObject(n).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&&n.scale.multiplyScalar(1/d*.3)}return new ar(t,n,r,o)}findAvatarPart(e,t){let i=e.name.toLowerCase(),n=!0;for(let r of t){if(!n)break;i.indexOf(r)===-1&&(n=!1)}if(n)return e;if(e.children)for(let r of e.children){let o=this.findAvatarPart(r,t);if(o)return o}return null}handleCustomAvatarErrors(e){if(!e.ok)throw Error(e.statusText);return e}};import{AxesHelper as Cv}from"three";var zi=class extends M{length=1;depthTest=!0;isGizmo=!0;_axes=null;onEnable(){if(this.isGizmo&&!hi)return;this._axes||(this._axes=new Cv(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)}};k([A()],zi.prototype,"length",2),k([A()],zi.prototype,"depthTest",2),k([A()],zi.prototype,"isGizmo",2);import*as fp from"three";var Yr=class extends M{from;to;hint;desiredDistance=1;onEnable(){}update(){if(!this.from||!this.to||!this.hint)return;let e=q(this.to).clone(),t=q(this.from).clone(),i=e.distanceTo(t),n=e.clone();n.sub(t);let r=t.clone();r.add(e),r.multiplyScalar(.5);let o=q(this.hint).clone();o.sub(r);let s=new fp.Vector3;s.crossVectors(o,n),s.crossVectors(n,s),s.normalize();let c=i*.5,d=Math.max(this.desiredDistance,c),a=Math.sqrt(d*d-c*c),h=s.clone();h.multiplyScalar(a),h.add(r),ie(this.gameObject,h);let u=r.clone();u.sub(s),this.gameObject.lookAt(u)}};import*as Gi from"three";import*as pi from"three";var Sv=new pi.BoxGeometry(1,1,1);function Sa(l=null){let e=new pi.Color(l??14540253),t=new pi.EdgesGeometry(Sv);return new pi.LineSegments(t,new pi.LineBasicMaterial({color:e}))}var Ov=N("gizmos"),Pa=class extends M{box=null;testBox=new Gi.Box3;_lastMatrixUpdateFrame=-1;isInBox(e){if(!!e){if(this.box||(this.box=new Gi.Box3),this.updateBox(!1),e.type==="Mesh")this.testBox.setFromObject(e);else{let t=q(e,Pa._position),i=Ch(e,Pa._size);this.testBox.setFromCenterAndSize(t,i)}return this.box?.intersectsBox(this.testBox)}}intersects(e){return e?this.updateBox(!1).intersectsBox(e):!1}updateBox(e=!1){return this.box||(this.box=new Gi.Box3),(e||this.context.time.frameCount!=this._lastMatrixUpdateFrame)&&(this._lastMatrixUpdateFrame=this.context.time.frameCount,this.box.setFromCenterAndSize(new Gi.Vector3(0,0,0),new Gi.Vector3(1,1,1)),this.box.applyMatrix4(this.gameObject.matrixWorld)),this.box}_helper=null;_color=null;awake(){this._helper=null,this._color=null,this.box=null}showHelper(e=null,t=!1){if(!(!Ov&&!t)){if(this._helper){e&&this._color?.set(e),this.gameObject.add(this._helper);return}this._helper=Sa(e),this.gameObject.add(this._helper)}}},lt=Pa;z(lt,"_position",new Gi.Vector3),z(lt,"_size",new Gi.Vector3(.01,.01,.01));import*as fs from"three";import{FrontSide as mp,DoubleSide as gp}from"three";function Zr(l,e){if(!l)return;let t=l.material;t?.isMaterial===!0&&(t.depthTest=!e.renderOnTop,t.side=e.doubleSided??!0?gp:mp,t.depthWrite=e.depthWrite??!1,t.shadowSide=e.doubleSided?gp:mp,l.castShadow=e.castShadows?e.castShadows:!1,l.receiveShadow=e.receiveShadows?e.receiveShadows:!1);for(let i of l.children)Zr(i,e)}function Jr(l,e,t){l[e]===void 0&&console.warn("Field",e,"is undefined on",l);let i=Proxy.revocable(l[e],{set(o,s,c,d){let a=o[s],h=Reflect.set(o,s,c,d);return t(c,a),h}}),n=i.revoke,r=l[e];return i.revoke=()=>{l[e]=r,n()},l[e]=i.proxy,i}function bp(l,e,t=3){let i=l.__scheduledActions;i||(i=l.__scheduledActions={});let n=e.name;i[t]||(i[t]={});let r=i[t];if(r[n])return;function*s(){e?.call(l),r[n]=null}let c=l.startCoroutine(s(),t);r[n]=c}var $r=class extends M{mass=1;set isKinematic(e){this._isKinematic=e,this._body&&(this._body.type=e?G.KINEMATIC:G.DYNAMIC)}get isKinematic(){return this._isKinematic}_isKinematic=!1;drag=0;angularDrag=1;detectCollision=!0;sleepThreshold=.01;get body(){return this._body===null&&this.initialize(),this._body}_body=null;currentVelocity;_smoothedVelocity;lastWorldPosition;dirty=!0;transformProxy;awake(){this._body=null,this.currentVelocity=new fs.Vector3,this._smoothedVelocity=new fs.Vector3,this.lastWorldPosition=q(this.gameObject).clone()}start(){this.setBodyFromGameObject()}onEnable(){this._body?this.context.physics.addBody(this.gameObject,this._body):this.initialize(),this.body&&(this.body.wakeUp(),this.gameObject.updateWorldMatrix(!0,!1),this.setBodyFromGameObject()),this.transformProxy=Jr(this.gameObject.matrix,"elements",()=>{this.context.physics.isUpdating||(this.dirty=!0)})}onDisable(){this.transformProxy?.revoke(),this._body&&this.context.physics.removeBody(this.gameObject,this._body,!1)}onDestroy(){this._body&&this.context.physics.removeBody(this.gameObject,this._body)}earlyUpdate(){this.dirty&&this.setBodyFromGameObject()}onBeforeRender(){this.updateVelocity()}initialize(){if(this._body)return;let e=new sa;e.drag=this.drag,e.angularDrag=this.angularDrag,e.mass=this.mass,e.kinematic=this.isKinematic,e.physicsEvents=this.detectCollision,e.sleepThreshold=this.sleepThreshold,this._body=this.context.physics.createBody(this.gameObject,e)}wakeUp(){this.body?.wakeUp()}applyForce(e,t){this.body?.applyForce(new _(e.x,e.y,e.z),t?new _(t.x,t.y,t.z):void 0)}getVelocity(){return this.body?$r.tempPosition.set(this.body?.velocity.x,this.body?.velocity.y,this.body?.velocity.z):$r.tempPosition.set(0,0,0)}setVelocity(e,t,i){!this.body||(this.body.velocity.x=e/this.context.time.deltaTime,this.body.velocity.y=t/this.context.time.deltaTime,this.body.velocity.z=i/this.context.time.deltaTime)}get smoothedVelocity(){return this._smoothedVelocity}setAngularVelocity(e,t,i){!this.body||(this.body.angularVelocity.x=e/this.context.time.deltaTime,this.body.angularVelocity.y=t/this.context.time.deltaTime,this.body.angularVelocity.z=i/this.context.time.deltaTime)}setBodyFromGameObject(e=null){if(this.dirty=!1,this.body&&this.gameObject&&!this.destroyed){let t=this.worldPosition;this.body.position.set(t.x,t.y,t.z);let i=this.worldQuaternion;if(this.body.quaternion.set(i.x,i.y,i.z,i.w),e){$r.copyVector3.set(e.x,e.y,e.z),this._smoothedVelocity.lerp($r.copyVector3,this.context.time.deltaTime/.1);let n=this._smoothedVelocity;this.body.velocity.x=n.x,this.body.velocity.y=n.y,this.body.velocity.z=n.z}}}updateVelocity(){if(!!this.currentVelocity&&this.body&&this.gameObject){let e=q(this.gameObject);this.currentVelocity.subVectors(e,this.lastWorldPosition),this.lastWorldPosition.copy(e),this._smoothedVelocity.lerp(this.currentVelocity,this.context.time.deltaTime/.1)}}},ce=$r;z(ce,"tempPosition",new fs.Vector3),z(ce,"copyVector3",new fs.Vector3),k([A()],ce.prototype,"mass",2),k([A()],ce.prototype,"isKinematic",1),k([A()],ce.prototype,"drag",2),k([A()],ce.prototype,"angularDrag",2),k([A()],ce.prototype,"detectCollision",2),k([A()],ce.prototype,"sleepThreshold",2);import{Vector3 as Oa}from"three";var fi=class extends M{attachedRigidbody=null;isTrigger=!1;_shape=null;awake(){super.awake(),this._shape=null}onEnable(){this.attachedRigidbody||(this.attachedRigidbody=this.gameObject.getComponentInParent(ce))}onDisable(){this._shape}};k([A(ce)],fi.prototype,"attachedRigidbody",2),k([A()],fi.prototype,"isTrigger",2);var Tn=class extends fi{radius=.5;center=new Oa(0,0,0);onEnable(){super.onEnable(),this._shape||(this._shape=this.context.physics.addSphereCollider(this.gameObject,this.center,this.radius,this.attachedRigidbody))}};k([A()],Tn.prototype,"radius",2),k([A(Oa)],Tn.prototype,"center",2);var Rn=class extends fi{size;center;onEnable(){super.onEnable(),this._shape||(this._shape=this.context.physics.addBoxCollider(this.gameObject,this.isTrigger,this.center,this.size,this.attachedRigidbody))}};k([A(Oa)],Rn.prototype,"size",2),k([A(Oa)],Rn.prototype,"center",2);var Kr=class{};var kt=class extends M{canGrab=!0;onPointerClick(e){}},It=class extends M{isUsed=!0;usedBy=null};var lr=class extends lt{},eo=class extends M{deleteBoxes=[];awake(){this.deleteBoxes=S.findObjectsOfType(lr,this.context)}update(){for(let e of this.deleteBoxes){let t=this.gameObject;e.isInBox(t)===!0&&(S.getComponentInParent(this.gameObject,It)||Lr(this.gameObject,this.context.connection))}}};var cr=class extends M{visibleOn;onEnable(){this.apply()}apply(){this.test()||S.setActive(this.gameObject,!1)}test(){return this.visibleOn<0?!0:Av()?(this.visibleOn&2)!==0:(this.visibleOn&1)!==0}};k([A()],cr.prototype,"visibleOn",2);var Aa;function Av(){if(Aa===!0||Aa===!1)return Aa;let l=!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)))&&(l=!0)}(navigator.userAgent||navigator.vendor||window.opera),Aa=l,l}import*as Vi from"three";var Ce=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,i,n){return e.prep(4,12),e.writeFloat32(n),e.writeFloat32(i),e.writeFloat32(t),e.offset()}};var to=class{bb=null;bb_pos=0;__init(e,t){return this.bb_pos=e,this.bb=t,this}position(e){return(e||new Ce).__init(this.bb_pos,this.bb)}rotation(e){return(e||new Ce).__init(this.bb_pos+12,this.bb)}scale(e){return(e||new Ce).__init(this.bb_pos+24,this.bb)}static sizeOf(){return 36}static createTransform(e,t,i,n,r,o,s,c,d,a){return e.prep(4,36),e.prep(4,12),e.writeFloat32(a),e.writeFloat32(d),e.writeFloat32(c),e.prep(4,12),e.writeFloat32(s),e.writeFloat32(o),e.writeFloat32(r),e.prep(4,12),e.writeFloat32(n),e.writeFloat32(i),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 to).__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 Cn=N("debugsync"),io="STRS";Vr(io,Mt.getRootAsSyncedTransformModel);var mi=new ft;function Nc(l,e,t=!0){mi.clear();let i=mi.createString(l);Mt.startSyncedTransformModel(mi),Mt.addGuid(mi,i),Mt.addFast(mi,t);let n=e.worldPosition,r=e.worldEuler,o=e.gameObject.scale;Mt.addTransform(mi,to.createTransform(mi,n.x,n.y,n.z,r.x,r.y,r.z,o.x,o.y,o.z));let s=Mt.endSyncedTransformModel(mi);return mi.finish(s,io),mi.asUint8Array()}var Qe=class extends M{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(){Cn&&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(){Cn&&console.log("new instance",this.guid,this),this._receivedDataBefore=!1,this._targetPosition=new Vi.Vector3,this._targetRotation=new Vi.Quaternion,this.lastWorldPos=new Vi.Vector3,this.lastWorldRotation=new Vi.Quaternion,this.rb=S.getComponentInChildren(this.gameObject,ce),this.rb&&(this._wasKinematic=this.rb.isKinematic),this.receivedUpdate=!0,this._model=new En(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(io,this.receivedDataCallback)}onDestroy(){this.syncDestroy&&Mh(this.guid,this.context.connection),this._model=null,this.context.connection.stopListening("joined-room",this.joinedRoomCallback),this.context.connection.stopListenBinary(io,this.receivedDataCallback)}tryGetLastState(){let e=this.context.connection.tryGetState(this.guid);e&&this.onReceivedData(e)}tempEuler=new Vi.Euler;onReceivedData(e){if(!this.destroyed&&typeof e.guid=="function"&&e.guid()===this.guid){Cn&&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){he.markDirty(this.gameObject,!0);let i=t.position();i&&(this.interpolatePosition&&this._targetPosition?.set(i.x(),i.y(),i.z()),(!this.interpolatePosition||!this._receivedDataBefore)&&this.setWorldPosition(i.x(),i.y(),i.z()));let n=t.rotation();n&&(this.tempEuler.set(n.x(),n.y(),n.z()),this.interpolateRotation&&this._targetRotation.setFromEuler(this.tempEuler),(!this.interpolateRotation||!this._receivedDataBefore)&&Sh(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){Cn&&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),o=t.angleTo(this.lastWorldRotation),s=this._model.hasOwnership||this.fastMode?1e-4:.001;(r>s||o>s)&&(this._model.hasOwnership?this._needsUpdate=!0:(Cn&&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),he.markDirty(this.gameObject,!0),this._needsUpdate=!1))}if(this._model&&!this._model.hasOwnership&&this._model.isOwned&&this._receivedDataBefore){let o=this._receivedFastUpdate||this.fastMode?.5:.3,s=!1;if(this.interpolatePosition&&this._targetPosition){let c=this.worldPosition;c.lerp(this._targetPosition,o),this.worldPosition=c,s=!0}if(this.interpolateRotation&&this._targetRotation){let c=this.worldQuaternion;c.slerp(this._targetRotation,o),this.worldQuaternion=c,s=!0}s&&he.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&&(Cn&&console.log("reset kinematic",this.rb.name,this._wasKinematic),this.rb.isKinematic=this._wasKinematic),this.gameObject.position.distanceTo(new Vi.Vector3(0,0,0))>1e3&&(Cn&&console.log("RESET",this.name),this.gameObject.position.set(0,1,0),this.rb.setVelocity(0,0,0),this.rb.setBodyFromGameObject()));let i=10,n=this.rb||this.fastMode;if(this._needsUpdate&&(i<=0||i>0&&this.context.time.frameCount%i===0||n)){Cn&&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=Nc(this.guid,this,!!n);this.context.connection.sendBinary(r)}}};import*as ee from"three";var Ia=class{static createButton(e,t={}){let i=document.createElement("button");function n(){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(){h.end()}),c.appendChild(d);var a=document.createElementNS("http://www.w3.org/2000/svg","path");a.setAttribute("d","M 12,12 L 28,28 M 28,12 12,28"),a.setAttribute("stroke","#fff"),a.setAttribute("stroke-width",2),d.appendChild(a),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 h=null;async function u(E){E.addEventListener("end",f),await e.xr.setSession(E),i.textContent="STOP AR",t.domOverlay.root.style.display="",h=E}function f(){h.removeEventListener("end",f),i.textContent="START AR",t.domOverlay.root.style.display="none",h=null}i.style.display="",i.style.cursor="pointer",i.style.left="calc(50% - 50px)",i.style.width="100px",i.textContent="START AR",i.onmouseenter=function(){i.style.opacity="1.0"},i.onmouseleave=function(){i.style.opacity="0.5"},i.onclick=function(){h===null?navigator.xr.requestSession("immersive-ar",t).then(u):h.end()}}function r(){i.disabled=!0,i.style.display="",i.style.cursor="auto",i.style.left="calc(50% - 75px)",i.style.width="150px",i.onmouseenter=null,i.onmouseleave=null,i.onclick=null}function o(){r(),i.textContent="AR NOT SUPPORTED"}function s(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 i.id="ARButton",i.style.display="none",s(i),navigator.xr.isSessionSupported("immersive-ar").then(function(c){c?n():o()}).catch(o),i;{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",s(c),c}}};var Ma=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 i=document.createElement("button");function n(){let c=null;async function d(h){h.addEventListener("end",a),await e.xr.setSession(h),i.textContent="EXIT VR",c=h}function a(){c.removeEventListener("end",a),i.textContent="ENTER VR",c=null}i.style.display="",i.style.cursor="pointer",i.style.left="calc(50% - 50px)",i.style.width="100px",i.textContent="ENTER VR",i.onmouseenter=function(){i.style.opacity="1.0"},i.onmouseleave=function(){i.style.opacity="0.5"},i.onclick=function(){if(c===null){let h={optionalFeatures:["local-floor","bounded-floor","hand-tracking","high-fixed-foveation-level","layers"]};navigator.xr.requestSession("immersive-vr",h).then(d)}else c.end()}}function r(){i.disabled=!0,i.style.display="",i.style.cursor="auto",i.style.left="calc(50% - 75px)",i.style.width="150px",i.onmouseenter=null,i.onmouseleave=null,i.onclick=null}function o(){r(),i.textContent="VR NOT SUPPORTED"}function s(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 i.id="VRButton",i.style.display="none",s(i),navigator.xr.isSessionSupported("immersive-vr").then(function(c){c?n():o(),Ma.xrSessionIsGranted&&(console.log("XR session is granted - will enter immersive web now"),i.click())}),i;{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",s(c),c}}static registerSessionGrantedListener(){if("xr"in navigator)try{navigator.xr.addEventListener("sessiongranted",()=>{console.log("Received session granted event"),Ma.xrSessionIsGranted=!0})}catch(e){console.error(e)}}},no=Ma;z(no,"xrSessionIsGranted",!1);no.registerSessionGrantedListener();import*as Pe from"three";import*as La from"three";var vp=vl(wc(),1);import{AudioAnalyser as Iv}from"three";var ro="noVoip",ct=N("debugvoip"),Mv=N("voip");var zc=class{id;constructor(e){this.id=e}};var Gc=class{peer;voip;userId;peerId;call=null;callErrorListener=null;stream=null;constructor(e,t,i,n){this.voip=e,this.peer=t,this.userId=i,this.peerId=n}close(){ct&&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 i of t)i.enabled=!e}async startVoipCall(){if(!await Ke.HasMicrophonePermissions()){console.warn("no permission to use microphone, can not start call");return}ct&&console.log("start voip call"),this.stream=await navigator.mediaDevices.getUserMedia({audio:!0,video:!1}),this.updateMute(this.voip.muteOutput),ct&&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=>{ct&&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(i){i.stop()}),this.stream=null):console.error(t)},this.peer.on("error",this.callErrorListener)}onCallClose(e){ct&&console.log("call closed",e)}},Vc=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,i){this.voip=e,this.obj=t,this.call=i}openAudioStream(e){let t=e.getAudioTracks();for(let i of t)if(i.kind==="audio"&&i.readyState==="live"){this.open(i);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,ue.userInteractionRegistered||ct&&console.log("Incoming call, waiting for user interaction before opening audio"),ue.registerWaitForAllowAudio(async()=>{if(this.call.open&&!this.closed){ct&&console.log("Setup audio and begin listening"),this.stream=new MediaStream([e]);let t=new La.AudioListener;this.audio=new La.Audio(t),this.audio.setVolume(this.voip.muteInput?0:1),this.audio.setMediaStreamSource(this.stream);let i=document.createElement("audio");this.audioElement=i,i.style.display="none",document.body.appendChild(i),i.srcObject=this.stream,i.sinkId!==void 0&&navigator.mediaDevices.enumerateDevices().then(n=>{if(!!i){console.log(n);for(let r of n)if(r.label==="Speakerphone"){i.sinkId=r.deviceId;break}}}),ct&&console.log("call is setup, you should hear something now"),this.analyzer=new Iv(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()}},Ke=class extends M{requireParam=!1;set muteInput(e){if(e===this._inputMuted||(this._inputMuted=e,!this.currentIncomingCalls))return;let t=this._inputMuted?0:1;for(let i in this.currentIncomingCalls)this.currentIncomingCalls[i]?.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 i in this.currentIncomingCalls){let n=this.currentIncomingCalls[i];if(n&&n.currentAnalyzer)return n.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(N(ro)){console.log("VOIP is disabled by url parameter: "+ro);return}if(this.requireParam&&!Mv){console.debug("VOIP must be enabled explicitly by url parameter");return}this.peer=new vp.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 i=new Gc(this,this.peer,this.context.connection.connectionId,e.peerId);this.connections[e.id]=i,i.startVoipCall()}}}),this.context.connection.beginListen("user-left-room",e=>{let{userId:t}=e,i=this.connections[t];this.connections[t]=null,i&&i.close();let n=this.currentIncomingCalls[t];ct&&console.log("UserLeftRoom",e,t,n),n&&(n.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){ct&&console.log("Peer connection established and received id"),this.model=new zc(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){ct&&console.log("CONNECTION",t),t.on("data",function(i){ct&&console.log("Received",i)})}))}async onReceiveCall(e){let{metadata:t}=e;console.assert(t.userId);let{userId:i}=t,{peer:n}=e,r=this.currentIncomingCalls[i];if(r&&r.close(),ct&&console.log("received call"),await Ke.HasMicrophonePermissions()){let o=await navigator.mediaDevices.getUserMedia({audio:!0,video:!1});e.answer(o)}else e.answer(null);this.currentIncomingCalls[i]=new Vc(this,this.gameObject,e),e.on("stream",o=>{ct&&console.log("receive caller stream, will setup audio now"),this.currentIncomingCalls[i]?.openAudioStream(o)}),e.on("error",console.error)}static async HasMicrophonePermissions(){return(await navigator.permissions.query({name:"microphone"})).state!=="denied"}};var oo=N("debugflags");var Wc=class{Mask=17;Has(e){let t=this.Mask&e;return oo&&console.log("HAS",e,this.Mask,"Result="+t),t!==0}Set(e){this.Mask=e,Se.Apply()}Enable(e){this.Mask|=e,Se.Apply()}Disable(e){this.Mask&=~e,Se.Apply()}Toggle(e){this.Mask^=e,Se.Apply()}EnableAll(){this.Mask=-1,Se.Apply()}DisableAll(){this.Mask=0,Se.Apply()}},vt=Wc;z(vt,"Global",new Wc);var gi=class extends M{static Apply(){for(let e of this.registry)e.UpdateVisible(vt.Global)}awake(){gi.registry.push(this)}onEnable(){gi.firstApply||(gi.firstApply=!0,gi.Apply())}onDestroy(){let e=gi.registry.indexOf(this);e>=0&&gi.registry.splice(e,1)}visibleIn;get isOn(){return this.gameObject.visible}UpdateVisible(e=null){if(!this.enabled)return;let t,i=e;i&&typeof i=="number"&&(console.assert(typeof i=="number","XRFlag.UpdateVisible: state must be a number",i),oo&&console.log(i),gi.buffer.Mask=i,e=gi.buffer);let n=e;if(n?(oo&&console.log("use passed in mask"),t=n.Has(this.visibleIn)):(oo&&console.log("use global mask"),vt.Global.Has(this.visibleIn)),t!==void 0)if(t)oo&&console.trace("is visible",this.name,this.gameObject.uuid),S.setActive(this.gameObject,!0);else{if(oo&&console.trace("is not visible",this.name,this.gameObject.uuid),!this.gameObject.visible)return;this.gameObject.visible=!1}}},Se=gi;z(Se,"registry",[]),z(Se,"firstApply"),z(Se,"buffer",new vt);import*as K from"three";import{XRControllerModelFactory as Lv}from"three/examples/jsm/webxr/XRControllerModelFactory.js";import{OculusHandModel as Dv}from"three/examples/jsm/webxr/OculusHandModel.js";import{OculusHandPointerModel as Hv}from"three/examples/jsm/webxr/OculusHandPointerModel.js";import*as Ep from"three";import*as Kt from"three";var Sn=N("debugavatar"),Wi=class extends M{static onAvatarMarkerCreated(e){return Wi._onNewAvatarMarkerAdded.push(e),e}static onAvatarMarkerDestroyed(e){return Wi._onAvatarMarkerDestroyed.push(e),e}connectionId;avatar;awake(){Wi.instances.push(this),Sn&&console.log(this);for(let e of Wi._onNewAvatarMarkerAdded)e({avatarMarker:this,gameObject:this.gameObject})}onDestroy(){Wi.instances.splice(Wi.instances.indexOf(this),1);for(let e of Wi._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):S.setActive(this.avatar,e))}},pe=Wi;z(pe,"instances",[]),z(pe,"_onNewAvatarMarkerAdded",[]),z(pe,"_onAvatarMarkerDestroyed",[]);var ms=class{_isVisible=!0;setVisible(e){this._isVisible=e,this.updateVisibility()}guid;root=null;head=null;handLeft=null;handRight=null;lastUpdate=-1;isLocalAvatar=!1;flags=null;headScale=new Kt.Vector3(1,1,1);handLeftScale=new Kt.Vector3(1,1,1);handRightScale=new Kt.Vector3(1,1,1);webxr;lastAvatarId=null;hasAvatarOverride=!1;context;avatarMarker=null;constructor(e,t,i){this.context=e,this.guid=t,this.webxr=i,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 Kt.Object3D;_handLeftTarget=new Kt.Object3D;_handRightTarget=new Kt.Object3D;_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)){this._canInterpolate=!0;let i=this.isLocalAvatar?this.head:this._headTarget;if(i.position.set(e.position.x,e.position.y,e.position.z),i.quaternion.set(e.rotation.x,e.rotation.y,e.rotation.z,e.rotation.w),i.scale.set(e.scale,e.scale,e.scale),i.scale.multiply(this.headScale),this.handLeft){let n=this.isLocalAvatar?this.handLeft:this._handLeftTarget;n.position.set(e.posLeftHand.x,e.posLeftHand.y,e.posLeftHand.z),n.quaternion.set(e.rotLeftHand._x,e.rotLeftHand._y,e.rotLeftHand._z,e.rotLeftHand._w),n.quaternion.multiply(ms.invertRotation),n.scale.set(e.scale,e.scale,e.scale),n.scale.multiply(this.handLeftScale)}if(this.handRight){let n=this.isLocalAvatar?this.handRight:this._handRightTarget;n.position.set(e.posRightHand.x,e.posRightHand.y,e.posRightHand.z),n.quaternion.set(e.rotRightHand._x,e.rotRightHand._y,e.rotRightHand._z,e.rotRightHand._w),n.quaternion.multiply(ms.invertRotation),n.scale.set(e.scale,e.scale,e.scale),n.scale.multiply(this.handRightScale)}}}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(){Sn&&console.log("Destroy avatar",this.guid),this.root?.removeFromParent(),this.avatarMarker?.destroy(),this.lastAvatarId=null,this.head&&_e.Remove(this.context,this.head)}updateVisibility(){let e=this.root;e&&S.setActive(e,this._isVisible)}async setupCustomAvatar(e){if(Sn&&console.log("LOAD",e,this),!e||typeof e=="string"&&e.length<=0)return!1;this.head&&_e.Remove(this.context,this.head);let t=e;if(t?.loadAssetAsync!==void 0){await t.loadAssetAsync();let n=t.asset;S.setActive(n,!1),e=S.instantiate(n),S.setActive(e,!0)}Sn&&console.log(e);let i=await ms.loader.getOrCreateNewAvatarInstance(this.context,e);if(Sn&&console.log(i,i?.isValid,this.lastAvatarId,e),i?.isValid){if(this.root=i.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=S.addNewComponent(this.root,pe),this.avatarMarker.connectionId=this.guid,this.avatarMarker.avatar=this,this.head&&this.head!==i.head&&this.head?.removeFromParent(),this.head=i.head,this.headScale.copy(this.head.scale),this.head&&!this.isLocalAvatar&&_e.Add(this.context,this.head,this.avatarMarker),i.leftHand&&this.handLeft?.removeFromParent(),this.handLeft=i.leftHand??this.handLeft,this.handLeft?this.handLeftScale.copy(this.handLeft.scale):this.handLeftScale.set(1,1,1),i.rigthHand&&this.handRight?.removeFromParent(),this.handRight=i.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(...S.getComponentsInChildren(this.root,Se)),this.flags.length<=0&&this.head){let n=S.addNewComponent(this.head,Se);n.visibleIn=20,this.flags.push(n),Sn&&console.log("Added flag to head: "+n.visibleIn,this.head.name)}return Sn&&console.log("[Avatar], is Local? ",this.isLocalAvatar,this.root),this.updateFlags(),this.updateVisibility(),!0}else return Sn&&console.warn("build avatar failed"),!1}},Lt=ms;z(Lt,"loader",new xn),z(Lt,"invertRotation",new Kt.Quaternion().setFromAxisAngle(new Kt.Vector3(0,1,0),Math.PI));var _e=class{static Add(e,t,i=null){if(!!t){for(let n of this.Pois)if(n.obj===t)return;this.Pois.push({obj:t,avatar:i}),this.LastChangeTime=e.time.time}}static Remove(e,t){if(!!t){for(let i of this.Pois)if(i.obj===t){this.Pois.splice(this.Pois.indexOf(i),1),this.LastChangeTime=e?.time.time??Z.Current?.time.time;return}}}};z(_e,"Pois",[]),z(_e,"LastChangeTime",0);var Uc=class{guid;position=new Ep.Vector3},Ui=class extends M{set controlledTarget(e){this.target=e;let t=D.get("MoveRandom");if(t&&this.target){let i=S.getComponent(this.target,t);i&&i.destroy()}}target=null;avatar=null;_model=null;_targetModel=new Uc;_currentTargetObject=null;_lastUpdateTime=0;_lookDuration=0;_lastPoiChangedTime=0;awake(){if(this.avatar=S.getComponentInParent(this.gameObject,pe),this.avatar){let e=S.getComponentInParent(this.gameObject,pe);this._model=new En(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&&ie(this.target,e.position)})}update(){if((!this.context.connection.isConnected||this._model?.hasOwnership)&&(_e.LastChangeTime!==this._lastPoiChangedTime&&(this._lastPoiChangedTime=_e.LastChangeTime,this._lookDuration=0),this.selectTarget(),this._currentTargetObject&&this.context.time.frameCount%10===0&&this.target)){let t=q(this._currentTargetObject);ie(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=_e.Pois;if(t.length>0){let i=t[Math.floor(Math.random()*t.length)];if(i&&i.obj){if(i.avatar&&i.avatar===this.avatar)return;this._currentTargetObject=i.obj}}}}};var dr=class extends M{},Fe=class extends M{static CreateRaycastLine(){let e=new K.Line(this.geometry),t=e.material;return t.color=this.raycastColor,e.layers.set(1),e.name="line",e.scale.z=1,e}static CreateRaycastHitPoint(){let e=new K.SphereGeometry(.5,22,22),t=new K.MeshBasicMaterial({color:this.raycastColor}),i=new K.Mesh(e,t);return i.visible=!1,i.layers.set(1),i}static Create(e,t,i,n){let r=i?S.addNewComponent(i,Fe,!1):new Fe;r.webXR=e,r.index=t,r.type=n;let o=e.context;return r.controller=o.renderer.xr.getController(t),r.controllerGrip=o.renderer.xr.getControllerGrip(t),r.controllerModel=this.Factory.createControllerModel(r.controller),r.controllerGrip.add(r.controllerModel),r.hand=o.renderer.xr.getHand(t),r.hand.add(new Dv(r.hand)),r.hand.traverse(s=>s.layers.set(2)),r.handPointerModel=new Hv(r.hand,r.controller),r.controller.addEventListener("connected",s=>{r.setControllerLayers(r.controllerModel,2),r.setControllerLayers(r.controllerGrip,2),setTimeout(()=>{r.setControllerLayers(r.controllerGrip,2)},1e3)}),r.hand.addEventListener("connected",s=>{if(s.data.hand){e.Rig&&e.Rig.add(r.hand),r.type=0,r.handPointerModel.traverse(a=>a.layers.set(2)),r.handPointerModel.pointerObject?.traverse(a=>a.layers.set(2));let d=r.hand.joints;if(d)for(let a of Object.keys(d)){let h=d[a];h.parent||r.hand.add(h)}}}),r}static addEventListener(e,t){let i=this.eventSubs[e]??[];i.push(t),this.eventSubs[e]=i}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 K.Quaternion),ve(e).multiply(this._wristQuaternion.setFromEuler(new K.Euler(-Math.PI/4,0,0)))):null}movementVector=new K.Vector3;worldRot=new K.Quaternion;joystick=new K.Vector2;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=Fe.CreateRaycastLine()),this._raycastHitPoint||(this._raycastHitPoint=Fe.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),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 K.Quaternion;update(){this.context.time.frameCount%60===0&&(this.setControllerLayers(this.controller,2),this.setControllerLayers(this.controllerGrip,2),this.setControllerLayers(this.hand,2));let e=Fe.eventSubs["update"];if(e&&e.length>0)for(let n of e)n(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(ve(this.controller),this.useSmoothing?t:1);let i=q(this.controller);if(this.raycastLine)if(this.type===1)this.raycastLine.visible=!1;else if(this.isUsingHands){this.raycastLine.visible=!this.grabbed,ie(this.raycastLine,i);let n=this.hand.joints;if(n&&n.wrist&&this.grabbed&&this.grabbed.isCloseGrab){let o=this.getWristQuaternion();o&&this.rayRotation.copy(o)}Ae(this.raycastLine,this.rayRotation)}else this.raycastLine.visible=!0,Ae(this.raycastLine,this.rayRotation),ie(this.raycastLine,i);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 i=this.input?.gamepad?.buttons;switch(this.input.handedness){case"left":let n=3*Fe.MovementSpeedFactor,r=2,o=Q.clamp01(this.joystick.length()*2),s=this.joystick.x>0?1:-1,c=Math.pow(this.joystick.x,r);c*=s,c*=o;let d=this.joystick.y>0?1:-1,a=Math.pow(this.joystick.y,r);a*=d,c*=o,t.getWorldQuaternion(this.worldRot),this.movementVector.set(c,0,a),this.movementVector.applyQuaternion(this.webXR.TransformOrientation),this.movementVector.y=0,this.movementVector.applyQuaternion(this.worldRot),t.position.add(this.movementVector.multiplyScalar(n*this.context.time.deltaTime)),this.isUsingHands&&this.runTeleport(t,i);break;case"right":let h=this.joystick.x,u=Math.abs(h);if(u<.4)this.didRotate=!1;else if(u>.5&&!this.didRotate){let f=h>0?-1:1;t.rotateY(Q.toRadians(30*f)),this.didRotate=!0}this.runTeleport(t,i);break}}runTeleport(e,t){let i=-this.joystick.y;if(this.hand?.visible&&!this.grabbed){let s=this.handPointerModel.isPinched();s&&this._pinchStartTime===void 0&&(this._pinchStartTime=this.context.time.time),s&&this._pinchStartTime&&this.context.time.time-this._pinchStartTime>.8&&(i=this.handPointerModel.isPinched()?1:0),s||(this._pinchStartTime=void 0)}else this._pinchStartTime=void 0;let n=i>.5,r=this.webXR.Rig?this.webXR.Rig?.scale?.x<.999:!1,o=null;if(t&&this.input&&!this.input.hand)for(let s=0;s<t.length;s++){let c=t[s];if(s===4)if(c.pressed&&!this.didChangeScale){this.didChangeScale=!0;let d=this.webXR.Rig;if(d)if(r){r=!1,d.scale.set(1,1,1),o=1,Fe.MovementSpeedFactor=1;let a=this.context.mainCamera;Fe.PreviousCameraFarDistance&&(a.far=Fe.PreviousCameraFarDistance)}else{r=!0,n=!0,o=.1,Fe.MovementSpeedFactor=o*2;let a=this.context.mainCamera;Fe.PreviousCameraFarDistance=a.far,a.far/=o}}else c.pressed||(this.didChangeScale=!1)}if(n){if(!this.didTeleport){let s=this.raycast();if(this.didTeleport=!0,s&&s.length>0){let c=s[0];if(r||this.isValidTeleportTarget(c.object)){let d=c.point;ie(e,d)}}}}else i<.1&&(this.didTeleport=!1);o!==null&&(e.scale.set(o,o,o),e.updateMatrixWorld())}isValidTeleportTarget(e){return S.getComponentInParent(e,dr)!=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 i=1;if(this.webXR.Rig&&(i/=this.webXR.Rig.scale.x),this.raycastLine){this.raycastLine.scale.z=i*(this.lastHit?.distance??9999);let n=this.raycastLine.material;t!=null?n.color=Fe.raycastColor:n.color=Fe.raycastNoHitColor}if(this._raycastHitPoint){if(this.lastHit!=null){this._raycastHitPoint.position.z=-1;let n=Q.clamp(this.lastHit.distance*.01*i,.015,.1);this._raycastHitPoint.scale.set(n,n,n)}this._raycastHitPoint.visible=this.lastHit!==null}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(),e&&e.length>0)for(let i of e){let n=i.object;if(!this.testIsVisible(n)){console.log("not visible");continue}this.lastSelectStartObject=n;let r={selected:n,grab:n},o=Fe.eventSubs["select-start"];if(o&&o.length>0)for(let s of o)s(this,r);r.grab!==n&&console.log("Grabbed object changed","original",n,"new",r.grab),r.grab&&(this.grabbed=dt.TryTake(this,r.grab,i,t));break}else{let i=Fe.eventSubs["select-start"],n={selected:null,grab:null};if(i&&i.length>0)for(let r of i)r(this,n)}}_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=Fe.eventSubs["select-end"];if(t&&t.length>0)for(let i of t)i(this,e);this.grabbed&&(this.grabbed.free(),this.grabbed=null)}testIsVisible(e){return e?S.isActiveInHierarchy(e):!0}setControllerLayers(e,t){if(!!e&&(e.layers.set(t),e.children))for(let i of e.children)this.grabbed?.selected===i||this.grabbed?.selectedMesh===i||this.setControllerLayers(i,t)}getRay(){let e=new K.Ray;return e.origin.copy(q(this.controller)),e.direction.set(0,0,-1).applyQuaternion(this.rayRotation),e}overlap(){let e=this.isUsingHands&&this.handPointerModel?this.handPointerModel.pointerObject:this.controllerGrip;if(!e)return new Array;let t=q(e).clone();return this.context.physics.sphereOverlap(t,.02)}raycast(){let e=new je;return e.layerMask=new K.Layers,e.layerMask.set(0),e.ray=this.getRay(),this.context.physics.raycast(e)}},ae=Fe;z(ae,"Factory",new Lv),z(ae,"raycastColor",new K.Color(.9,.3,.3)),z(ae,"raycastNoHitColor",new K.Color(.6,.6,.6)),z(ae,"geometry",new K.BufferGeometry().setFromPoints([new K.Vector3(0,0,0),new K.Vector3(0,0,-1)])),z(ae,"handModels",{}),z(ae,"eventSubs",{}),z(ae,"PreviousCameraFarDistance"),z(ae,"MovementSpeedFactor",1);var et=class{static AddEventListener(e,t){return et.Events[e]||(et.Events[e]=[]),et.Events[e].push(t),t}static RemoveEventListener(e,t){if(!t||!et.Events[e])return;let i=et.Events[e].indexOf(t);i>=0&&et.Events[e].splice(i,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,i,n){let r=S.getComponentInParent(t,kt);if(!r)return console.warn("Prevented taking object that is not interactable",t),null;let o=t,s=S.getComponentInParent(t,Qe);s&&(s.requestOwnership(),o=s.gameObject);for(let d of this.Current)if(d.selected===o)return d.controller===e||(d.free(),d.Take(e,o,t,s,r,i,n)),d;let c=new et;return c.Take(e,o,t,s,r,i,n),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,i,n,r,o,s){if(console.assert(t!==null,"Expected object to be taken but was",t),e.isUsingHands?this.positionSource=s?e.wrist:e.controller:this.positionSource=e.controller,!this.positionSource)return console.warn("No position source"),this;let c={controller:e,take:t,hit:i,sync:n,interactable:r};et.Events.WillTake?.forEach(f=>f(this,c));let d=i;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=s,this.didReparent=!1,this.sync=n,this.grabTime=e.context.time.time,this.grabUUID=Date.now().toString(),this.usageMarker=S.addNewComponent(this.selected,It),this.rigidbodies=S.getComponentsInChildren(this.selected,ce),q(this.positionSource,this.lastControllerWorldPos);let a=()=>s?this.lastControllerWorldPos.clone():o.point.clone();this.grabDistance=a().distanceTo(this.lastControllerWorldPos),this.totalChangeAlongDirection=0,this.localPositionOffsetToGrab=this.selected.worldToLocal(a());let h=e.isUsingHands&&s?this.controller.getWristQuaternion().clone():e.rayRotation.clone();ve(this.selected,this.localQuaternionToGrab).premultiply(h.invert());let u=this.controller.webXR.Rig;return u&&this.rigPositionLastFrame.copy(q(u)),_e.Add(e.context,this.selected),et.Register(this),this.sync&&(this.sync.fastMode=!0),et.Events.DidTake?.forEach(f=>f(this,c)),this}free(){if(!this.selected)return;let e={controller:this.controller,take:this.selected,hit:this.selected,sync:this.sync,interactable:null};et.Events.WillFree?.forEach(n=>n(this,e)),_e.Remove(this.controller.context,this.selected),et.Remove(this),this.sync&&(this.sync.fastMode=!1);let t=this.selectedMesh;t&&this.originalMaterial&&t.material&&(t.material=this.originalMaterial);let i=this.selected;if(this.didReparent&&i.parent){let n=this.selectedParent;n?n.attach(i):this.controller?.context.scene.attach(i)}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 n of this.rigidbodies)n.wakeUp(),n.smoothedVelocity&&n.setVelocity(n.smoothedVelocity.x,n.smoothedVelocity.y,n.smoothedVelocity.z);this.rigidbodies=null,this.localPositionOffsetToGrab=null,this.quaternionLerp=null,et.Events.DidFree?.forEach(n=>n(this,e))}grabPoint=new K.Vector3;localPositionOffsetToGrab=null;localPositionOffsetToGrab_worldSpace=new K.Vector3;localQuaternionToGrab=new K.Quaternion(0,0,0,1);targetDir=null;quaternionLerp=null;controllerDir=new K.Vector3;controllerWorldPos=new K.Vector3;lastControllerWorldPos=new K.Vector3;controllerPosDelta=new K.Vector3;totalChangeAlongDirection=0;rigPositionLastFrame=new K.Vector3;controllerMovementSinceLastFrame(){if(!this.positionSource||!this.controller)return 0;this.controllerDir.set(0,0,-1),this.controllerDir.applyQuaternion(this.controller.rayRotation),q(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 i=q(e),n=this.rigPositionLastFrame.sub(i);this.controllerPosDelta.add(n),this.rigPositionLastFrame.copy(i)}return this.controllerDir.dot(this.controllerPosDelta)}update(){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 K.Vector3),this.targetDir.set(0,0,-this.grabDistance*t);let i=this.targetDir.applyQuaternion(this.controller.rayRotation).add(this.controllerWorldPos),n=this.controller.rayRotation.clone().multiplyQuaternions(this.controller.rayRotation,this.localQuaternionToGrab);this.quaternionLerp||(this.quaternionLerp=n.clone()),this.quaternionLerp.slerp(n,this.controller.useSmoothing?this.controller.context.time.deltaTime/.03:1),Ae(this.selected,this.quaternionLerp),this.selected.updateWorldMatrix(!1,!1),this.grabPoint.copy(i),this.localPositionOffsetToGrab&&(this.localPositionOffsetToGrab_worldSpace.copy(this.localPositionOffsetToGrab),this.selected.localToWorld(this.localPositionOffsetToGrab_worldSpace).sub(q(this.selected)),i.sub(this.localPositionOffsetToGrab_worldSpace)),ie(this.selected,i)}if(this.rigidbodies!=null)for(let e of this.rigidbodies)e.wakeUp(),e.setBodyFromGameObject({x:0,y:0,z:0});he.markDirty(this.selected,!0)}}},dt=et;z(dt,"Events",{}),z(dt,"Current",[]);import*as Da from"three";var Dt=class extends M{webAR=null;invertForward=!1;get arScale(){return this._arScale}set arScale(e){e!==this._arScale&&(this._arScale=e,this.setScale(e))}_arScale=5;_rig=null;_startPose=null;_placementPose=null;_isTouching=!1;onBegin(e){this._placementPose=null,this.gameObject.visible=!1,this.gameObject.matrixAutoUpdate=!1,this._startPose=this.gameObject.matrix.clone(),e.addEventListener("selectstart",this.onSelectStart.bind(this)),e.addEventListener("selectend",this.onSelectEnd.bind(this)),setTimeout(()=>this.gameObject.visible=!1,1e3)}onUpdate(e,t,i){if(i&&!this._placementPose&&this._isTouching){if(this.webAR&&this.webAR.setReticleActive(!1),this._placementPose=new Da.Matrix4().fromArray(i.transform.matrix).invert(),e){if(this.invertForward){let n=new Da.Matrix4().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._startPose&&this.gameObject.matrix.copy(this._startPose),this.gameObject.matrixAutoUpdate=!0,e&&(e.matrixAutoUpdate=!0),he.markDirty(this.gameObject,!0),setTimeout(()=>this.gameObject.visible=!0,100)}onSelectStart(){this._isTouching=!0}onSelectEnd(){this._isTouching=!1}setScale(e){let t=this._rig;!t||!this._placementPose||(t.matrixAutoUpdate=!1,t.matrix.multiplyMatrices(new Da.Matrix4().makeScale(e,e,e),this._placementPose),t.matrix.decompose(t.position,t.quaternion,t.scale),t.updateMatrixWorld())}};k([A()],Dt.prototype,"invertForward",2),k([A()],Dt.prototype,"arScale",1);var Pn=class extends M{awake(){}};import{Object3D as jv}from"three";var hr=N("debugaddressables"),Ha=class{_context;constructor(e){this._context=e,this._context.pre_update_callbacks.push(this.preUpdate.bind(this))}preUpdate(){}_assetReferences={};findAssetReference(e){return this._assetReferences[e]||null}registerAssetReference(e){return e.uri&&(this._assetReferences[e.uri]?console.warn("Asset reference already registered",e):this._assetReferences[e.uri]=e),e}},tt=class{static getOrCreate(e,t,i){let n=ks(e,t);hr&&console.log("GetOrCreate Addressable from",e,t,"FinalPath=",n);let r=i.addressables,o=r.findAssetReference(n);if(o)return o;let s=new tt(n);return r.registerAssetReference(s),s}get asset(){return this._glbRoot??this._asset}set asset(e){this._asset=e}_loading;get uri(){return this._uri}get rawAsset(){return this._asset}_asset;_glbRoot;_uri;_progressListeners=[];_isLoadingRawBinary=!1;_rawBinary;constructor(e){this._uri=e,jh(this._uri,this.onResolvePrefab.bind(this))}async onResolvePrefab(e){return e===this.uri&&(this.mustLoad&&await this.loadAssetAsync(),this.asset)?this.asset:null}get mustLoad(){return!this.asset||this.asset.__destroyed===!0}isLoaded(){return this._rawBinary||this.asset!==void 0}unload(){this.asset&&(hr&&console.log("Unload",this.asset),this.asset.scene?S.destroy(this.asset.scene):S.destroy(this.asset)),this.asset=null}async preload(){if(!this.mustLoad||this._isLoadingRawBinary)return null;if(this._rawBinary!==void 0)return this._rawBinary;this._isLoadingRawBinary=!0,hr&&console.log("Preload",this.uri);let e=await up(this.uri,t=>{this.raiseProgressEvent(t)});return this._rawBinary=e?.buffer??null,this._isLoadingRawBinary=!1,this._rawBinary}async loadAssetAsync(e){if(!this.mustLoad)return;if(e&&this._progressListeners.push(e),this._loading!==void 0)return this._loading;let t=Z.Current;this._rawBinary?(this._loading=Qr(t,this._rawBinary,this.uri,null),this.raiseProgressEvent(new ProgressEvent("progress",{loaded:this._rawBinary.byteLength,total:this._rawBinary.byteLength}))):(hr&&console.log("Load async",this.uri),this._loading=ur(t,this.uri,null,!0,n=>{this.raiseProgressEvent(n)}));let i=await this._loading;if(this._progressListeners.length=0,this._glbRoot=this.tryGetActualGameObjectRoot(i),this._loading=void 0,i)return Ii(t),i.scene!==void 0&&(this.asset=i),this.asset}async instantiate(e){return this.onInstantiate(e,!1)}async instantiateSynced(e,t=!0){return this.onInstantiate(e,!0,t)}beginListenDownload(e){this._progressListeners.indexOf(e)<0&&this._progressListeners.push(e)}endListenDownload(e){let t=this._progressListeners.indexOf(e);t>=0&&this._progressListeners.splice(t,1)}raiseProgressEvent(e){for(let t of this._progressListeners)t(this,e)}async onInstantiate(e,t=!1,i){let n=Z.Current;if(e||(e=n.scene),this.mustLoad&&await this.loadAssetAsync(),hr&&console.log("Instantiate",this.uri,"parent:",e),this.asset){hr&&console.log("Add to scene",this.asset);let r=e instanceof ye?e:null;if(r||(r=new ye),typeof e=="object"&&(e instanceof jv?r.parent=e:Object.assign(r,e)),t){r.context=n;let o=this.asset;o.guid=this.uri;let s=Gs(o,r,void 0,i);if(s)return s}else{let o=S.instantiate(this.asset,r);if(o)return o}}else hr&&console.warn("Failed to load asset",this.uri);return null}tryGetActualGameObjectRoot(e){if(e&&e.scene){let t=e.scene;return t.isGroup&&t.children.length===1&&t.children[0].name+"glb"===t.name?t.children[0]:t}return null}},qc=class extends Ni{constructor(){super([tt])}onSerialize(e,t){if(e&&e.uri!==void 0&&typeof e.uri=="string")return e.uri}onDeserialize(e,t){return typeof e=="string"?t.context?t.gltfId?tt.getOrCreate(t.gltfId,e,t.context):(console.error("Missing spurce id"),null):(console.error("Missing context"),null):null}};new qc;import*as yt from"three";var bi=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,i,n,r){return e.prep(4,16),e.writeFloat32(r),e.writeFloat32(n),e.writeFloat32(i),e.writeFloat32(t),e.offset()}};var Me=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 Me).__init(e.readInt32(e.position())+e.position(),e)}static getSizePrefixedRootAsVrUserStateBuffer(e,t){return e.setPosition(e.position()+4),(t||new Me).__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 Ce).__init(this.bb_pos+t,this.bb):null}rotation(e){let t=this.bb.__offset(this.bb_pos,12);return t?(e||new bi).__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 Ce).__init(this.bb_pos+t,this.bb):null}posRightHand(e){let t=this.bb.__offset(this.bb_pos,18);return t?(e||new Ce).__init(this.bb_pos+t,this.bb):null}rotLeftHand(e){let t=this.bb.__offset(this.bb_pos,20);return t?(e||new bi).__init(this.bb_pos+t,this.bb):null}rotRightHand(e){let t=this.bb.__offset(this.bb_pos,22);return t?(e||new bi).__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 wp=N("debugxr"),gs=N("debugavatar");var Qc="VRUS";Vr(Qc,Me.getRootAsVrUserStateBuffer);function Xc(){return new Date().getTime()}function Bv(l){let e=l&4294967295,t=l/Math.pow(2,32)&1048575;return Xe.create(e,t)}var bs=class{guid;time;avatarId;position=new yt.Vector3;rotation=new yt.Vector4;scale=1;posLeftHand=new yt.Vector3;posRightHand=new yt.Vector3;rotLeftHand=new yt.Quaternion;rotRightHand=new yt.Quaternion;constructor(e){this.guid=e}update(e,t,i,n,r){this.time=Xc(),this.avatarId=r,this.position.set(t.x,t.y,t.z),e&&this.position.applyMatrix4(e.matrixWorld);let o=bs.quat0,s=bs.quat1;o.set(i.x,i.y,i.z,i.w),o=o.multiplyQuaternions(o,bs.invertRotation),e&&(e.getWorldQuaternion(s),o.multiplyQuaternions(s,o)),this.rotation.set(o.x,o.y,o.z,o.w),this.scale=e.scale.x;let c=n.LeftController?.controllerGrip;c&&(c.getWorldPosition(this.posLeftHand),c.getWorldQuaternion(this.rotLeftHand));let d=n.RightController?.controllerGrip;if(d&&(d.getWorldPosition(this.posRightHand),d.getWorldQuaternion(this.rotRightHand)),n.LeftController?.hand?.visible){let a=n.LeftController.wrist;a&&(a.getWorldPosition(this.posLeftHand),a.getWorldQuaternion(this.rotLeftHand))}if(n.RightController?.hand?.visible){let a=n.RightController.wrist;a&&(a.getWorldPosition(this.posRightHand),a.getWorldQuaternion(this.rotRightHand))}}sendAsBuffer(e,t){e.clear();let i=e.createString(this.guid),n=e.createString(this.avatarId);Me.startVrUserStateBuffer(e),Me.addGuid(e,i),Me.addTime(e,Bv(this.time)),Me.addAvatarId(e,n),Me.addPosition(e,Ce.createVec3(e,this.position.x,this.position.y,this.position.z)),Me.addRotation(e,bi.createVec4(e,this.rotation.x,this.rotation.y,this.rotation.z,this.rotation.w)),Me.addScale(e,this.scale),Me.addPosLeftHand(e,Ce.createVec3(e,this.posLeftHand.x,this.posLeftHand.y,this.posLeftHand.z)),Me.addPosRightHand(e,Ce.createVec3(e,this.posRightHand.x,this.posRightHand.y,this.posRightHand.z)),Me.addRotLeftHand(e,bi.createVec4(e,this.rotLeftHand.x,this.rotLeftHand.y,this.rotLeftHand.z,this.rotLeftHand.w)),Me.addRotRightHand(e,bi.createVec4(e,this.rotRightHand.x,this.rotRightHand.y,this.rotRightHand.z,this.rotRightHand.w));let r=Me.endVrUserStateBuffer(e);e.finish(r,Qc);let o=e.asUint8Array();t.sendBinary(o)}setFromBuffer(e,t){if(!e)return;this.guid=e,this.time=t.time().toFloat64();let i=t.avatarId();i&&(this.avatarId=i);let n=t.position();n&&this.position.set(n.x(),n.y(),n.z());let r=t.rotation();r&&this.rotation.set(r.x(),r.y(),r.z(),r.w());let o=t.posLeftHand();o&&this.posLeftHand.set(o.x(),o.y(),o.z());let s=t.posRightHand();s&&this.posRightHand.set(s.x(),s.y(),s.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()}},Ht=bs;z(Ht,"invertRotation",new yt.Quaternion().setFromAxisAngle(new yt.Vector3(0,1,0),Math.PI)),z(Ht,"quat0",new yt.Quaternion),z(Ht,"quat1",new yt.Quaternion);var qi=class extends M{webXR=null;debugAvatarUser=null;voip=null;async awake(){if(this.webXR||(this.webXR=this.gameObject.getComponent($)),this.webXR||(this.webXR=S.findObjectOfType($,this.context)),!this.webXR&&(console.log("Missing webxr component"),this.webXR=S.findObjectOfType($,this.context),!this.webXR)){console.error("Could not find webxr component");return}if(this.voip||(this.voip=S.findObjectOfType(Ke,this.context)),gs){let e="debug-avatar-"+gs,t=new Lt(this.context,e,this.webXR);if(this.debugAvatarUser=t,typeof gs=="string"&&gs.length>0)if(await t.setAvatarOverride(gs)){let i=new Ht(e);i.position.y+=1;let n=.5;i.posLeftHand.y+=n,i.posLeftHand.x+=n,i.posRightHand.y+=n,i.posRightHand.x-=n,t.tryUpdate(i,0)}else t.destroy()}}onEnable(){if(!this.webXR&&(this.webXR=S.getComponent(this.gameObject,$),!this.webXR)){console.warn("Missing webxr component on "+this.gameObject.name);return}this.eventSub_WebXRStartEvent=this.onXRSessionStart.bind(this),$.addEventListener("xrStarted",this.eventSub_WebXRStartEvent),this.eventSub_WebXRUpdateEvent=this.onXRSessionUpdate.bind(this),$.addEventListener("xrUpdate",this.eventSub_WebXRUpdateEvent),this.eventSub_WebXREndEvent=this.onXRSessionEnded.bind(this),$.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(Qc,e=>{let t=e.guid();if(!t)return;let i=e.time().toFloat64(),n=this.tempState;n.setFromBuffer(t,e),this.onTryGetAvatar(t,i)?.tryUpdate(n,i)}),this.context.connection.beginListen("vr-session-update",e=>{let t=e.guid,i=e.time;this.onTryGetAvatar(t,i)?.tryUpdate(e,i)})}tempState=new Ht("");onTryGetAvatar(e,t){if(e===this.context.connection.connectionId)return null;let i=new Date().getTime()-t;if(i>5e3)return wp&&console.log("old data",i,e),null;let n=this.avatars[e];if(n===void 0)try{console.log("create new avatar");let r=new Lt(this.context,e,this.webXR);n=r,this.avatars[e]=r}catch(r){this.avatars[e]=null,console.error(r)}return n}onDisable(){this.eventSub_ConnectionEvent&&this.context.connection.stopListening("joined-room",this.eventSub_ConnectionEvent),$.removeEventListener("xrStarted",this.eventSub_WebXRStartEvent),$.removeEventListener("xrUpdate",this.eventSub_WebXRUpdateEvent),$.removeEventListener("xrStopped",this.eventSub_WebXREndEvent)}update(){let e=Xc();this.debugAvatarUser&&(this.debugAvatarUser.lastUpdate=e),this.detectPotentiallyDisconnectedAvatarsAndRemove();for(let t in this.avatars){let i=this.avatars[t];!i||i.update()}}_removeAvatarsList=[];detectPotentiallyDisconnectedAvatarsAndRemove(){let e=Xc();for(let t in this.avatars){let i=this.avatars[t];if(!i){this._removeAvatarsList.push(t);continue}e-i.lastUpdate>1e4&&(console.log("avatar timed out (didnt receive any updates in a while) - destroying it now"),i.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 Lt(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(){wp&&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 ft(1024);onXRSessionUpdate(e){this.xrState??=new Ht(this.context.connection.connectionId??this.k_LocalAvatarNoNetworkingGuid),this.ownership??=new En(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:i,rig:n}=e,r=t.getViewerPose(i.getReferenceSpace());if(!r)return;let o=r?.transform,s=o.position,c=o.orientation;this.xrState.update(n,s,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 N("avatar")}};async function Fv(){return"xr"in navigator?await navigator.xr.isSessionSupported("immersive-ar")===!0:!1}async function Nv(){return"xr"in navigator?await navigator.xr.isSessionSupported("immersive-vr")===!0:!1}var Yc=!1,Zc=!1;Fv().then(l=>Yc=l);Nv().then(l=>Zc=l);var Ne=class extends M{enableVR=!0;enableAR=!0;defaultAvatar;createVRButton=!0;createARButton=!0;static get IsInWebXR(){return this._isInXr}static get XRSupported(){return"xr"in navigator&&(Yc||Zc)}static get IsARSupported(){return Yc}static get IsVRSupported(){return Zc}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){Ne.XRSupported||console.warn("WebXR is not supported on this device");let i=no.createButton(e.context.renderer);return i.classList.add("webxr-ar-button"),i.classList.add("webxr-button"),this.resetButtonStyles(i),(t?.registerClick??!0)&&i.addEventListener("click",e.onClickedVRButton.bind(e)),i}static createARButton(e,t){let i=e.webAR?.getAROverlayContainer(),n={requiredFeatures:["hit-test"]};i&&(n.domOverlay={root:i},n.optionalFeatures=["dom-overlay"]);let r=Ia.createButton(e.context.renderer,n);return r.classList.add("webxr-ar-button"),r.classList.add("webxr-button"),Ne.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}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=tt.getOrCreate(this.sourceId??"/",this.defaultAvatar,this.context)),!S.findObjectOfType(qi,this.context)){let e=S.addNewComponent(this.gameObject,qi,!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 On(this);let e=Ne.XRSupported,t,i,n=document.createElement("div");n.classList.add("webxr-buttons"),this.context.domElement.append(n),this.enableAR&&this.createARButton&&(t=Ne.createARButton(this),this._arButton=t,n.appendChild(t)),this.createVRButton&&this.enableVR&&(e||!this.enableAR)&&(i=Ne.createVRButton(this),this._vrButton=i,n.appendChild(i)),setTimeout(()=>{Ne.resetButtonStyles(i),Ne.resetButtonStyles(t)},1e3)}_transformOrientation=new Pe.Quaternion;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 i=e.getViewerPose(this.context.renderer.xr.getReferenceSpace());if(this._currentHeadPose=i,!i)return;let n=i?.transform;n&&this._transformOrientation.set(n.orientation.x,n.orientation.y,n.orientation.z,n.orientation.w);for(let r of this.controllers)r.onUpdate(t);this._isInAR&&this.webAR?.onUpdate(t,e)}Ne._isInXr===!1&&t&&this.onEnterXR(t,e),Ne.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++)ae.Create(this,e,this.gameObject,0);Ne.events.dispatchEvent({type:"requestVRSession"})}}captureCameraState(){this.context.mainCamera&&(this._originalCameraPosition.copy(q(this.context.mainCamera)),this._originalCameraRotation.copy(ve(this.context.mainCamera)),this._originalCameraParent=this.context.mainCamera.parent)}ensureRig(){if(!this.rig){let e=S.findObjectOfType(Pn,this.context);e?(this.rig=e.gameObject,this.rig.rotateY(Math.PI)):(this.rig=new Pe.Group,this.rig.name="XRRig",this.context.scene.add(this.rig))}}_originalCameraParent=null;_originalCameraPosition=new Pe.Vector3;_originalCameraRotation=new Pe.Quaternion;onEnterXR(e,t){console.log("[XR] session begin",e),Ne._isInXr=!0,this.ensureRig();let i=this.context.renderer.xr.getReferenceSpace();if(i&&this.rig){let s=t.getViewerPose(i)?.transform.orientation;if(s){let c=new Pe.Quaternion(s.x,s.y,s.z,s.w),d=new Pe.Euler().setFromQuaternion(c);this.rig.rotateY(d.y)}}let n=this.context.renderer.xr;if(this.context.mainCamera){let o=n.getCamera(this.context.mainCamera);for(let s of o.cameras)s.layers.enableAll();this.rig.add(this.context.mainCamera)}let r=this._requestedAR?2:4;switch(vt.Global.Set(r),r){case 2:this._isInAR=!0,this.webAR?.onBegin(e);break;case 4:this._isInVR=!0,this.onEnterVR(e);break}e.addEventListener("end",()=>{console.log("[XR] session end"),Ne._isInXr=!1,this.onExitXR(e)}),this.onEnterXR_HandleMirrorWindow(e),Ne.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.xrMirrorWindow&&(this.xrMirrorWindow.close(),this.xrMirrorWindow=null),this.destroyControllers(),this.context.mainCamera&&(this._originalCameraParent?.add(this.context.mainCamera),ie(this.context.mainCamera,this._originalCameraPosition),Ae(this.context.mainCamera,this._originalCameraRotation),this.context.mainCamera.scale.set(1,1,1)),vt.Global.Set(17),Ne.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){!N("mirror")||setTimeout(()=>{if(!Ne.IsInWebXR)return;let t=new URL(window.location.href);Ir(t.searchParams,ro,1),Ir(t.searchParams,"isMirror",1);let i=t.toString();this.xrMirrorWindow=window.open(i,"webxr sync","popup=yes"),this.xrMirrorWindow&&(this.xrMirrorWindow.onload=()=>{this.xrMirrorWindow&&(this.xrMirrorWindow.onbeforeunload=()=>{Ne.IsInWebXR&&e.end()})})},1e3)}},$=Ne;z($,"_isInXr",!1),z($,"events",new Pe.EventDispatcher),k([A(tt)],$.prototype,"defaultAvatar",2);var so=class{webxr;reticle=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;getAROverlayContainer(){return this.arDomOverlay=this.webxr.context.domElement,this.arOverlayElement=this.arDomOverlay.getAROverlayContainer(),this.arOverlayElement}setReticleActive(e){this.reticleActive=e}onBegin(e){let t=this.webxr.context;this.reticleActive=!0;for(let i=0;i<4;i++)ae.Create(this.webxr,i,this.webxr.gameObject,1);(!this.sessionRoot||this.sessionRoot.destroyed||!this.sessionRoot.activeAndEnabled)&&(this.sessionRoot=S.findObjectOfType(Dt,t)),this.previousBackground=t.scene.background,this.previousEnvironment=t.scene.environment,t.scene.background=null,e.requestReferenceSpace("viewer").then(i=>{e.requestHitTestSource({space:i}).then(n=>{this.hitTestSource=n})}),!this.reticle&&this.sessionRoot&&(this.reticle=new Pe.Mesh(new Pe.RingGeometry(.07,.09,32).rotateX(-Math.PI/2),new Pe.MeshBasicMaterial),this.reticle.name="AR Placement reticle",this.reticle.matrixAutoUpdate=!1,this.reticle.visible=!1,this.webxr.scene?(this.webxr.scene.add(this.reticle),this.webxr.scene.visible=!0):console.warn("Could not found WebXR Rig")),this._previousParent=this.webxr.gameObject,so.tempWebXRObject||(so.tempWebXRObject=new Pe.Object3D),this.context.scene.add(so.tempWebXRObject),S.addComponent(so.tempWebXRObject,this.webxr),this.sessionRoot?(this.sessionRoot.webAR=this,this.sessionRoot?.onBegin(e)):console.warn("No WebARSessionRoot found in scene"),this.arDomOverlay&&this.arOverlayElement&&this.arDomOverlay.onEnterAR(e,this.arOverlayElement),this.context.mainCameraComponent?.applyClearFlagsIfIsActiveCamera()}onEnd(e){this._previousParent&&(console.log("ADD",this._previousParent),S.addComponent(this._previousParent,this.webxr),this._previousParent=null),this.hitTestSource=null;let t=this.webxr.context;t.scene.background=this.previousBackground,t.scene.environment=this.previousEnvironment,this.sessionRoot&&this.sessionRoot.onEnd(this.webxr.Rig,e),this.arDomOverlay&&this.arDomOverlay.onExitAR(e),this.context.mainCameraComponent?.applyClearFlagsIfIsActiveCamera()}onUpdate(e,t){if(!this.hitTestSource)return;let i=t.getHitTestResults(this.hitTestSource);if(i.length){let n=i[0],r=this.webxr.context.renderer.xr.getReferenceSpace();if(r){let o=n.getPose(r);if(this.sessionRoot?.onUpdate(this.webxr.Rig,e,o),this.reticle&&(this.reticle.visible=this.reticleActive,this.reticleActive&&o)){let s=o.transform.matrix;this.reticle.matrix.fromArray(s),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)}},On=so;z(On,"tempWebXRObject");var Jc=!1;var ao=class extends kt{static get HasAnySelected(){return this._active!==null}transformSelf=!0;selectStartEventListener=[];selectEndEventListener=[];constructor(){super(),this.selectStartEventListener=[],this.selectEndEventListener=[],this._dragDelta=new ee.Vector2}addDragEventListener(e,t){switch(e){case"selectstart":this.selectStartEventListener.push(t);break;case"selectend":this.selectEndEventListener.push(t);break}}_dragHelper=null;start(){}_draggingRigidbodies=[];allowEdit(e=null){return this.context.connection.allowEditing}onPointerEnter(e){if(!this.allowEdit(this.gameObject)||$.IsInWebXR)return;let t=S.getComponentInParent(e.object,ao);!t||t!==this||(ao.lastHovered=e.object,this.context.domElement.style.cursor="pointer")}onPointerExit(e){!this.allowEdit(this.gameObject)||$.IsInWebXR||ao.lastHovered===e.object&&(this.context.domElement.style.cursor="auto")}_waitingForDragStart=null;onPointerDown(e){!this.allowEdit(this.gameObject)||$.IsInWebXR||(this._dragDelta.set(0,0),this._didDrag=!1,this._waitingForDragStart=e,e.StopPropagation())}onPointerUp(e){this._waitingForDragStart=null,this.allowEdit(this.gameObject)&&($.IsInWebXR||(this.onDragEnd(e),e.StopPropagation()))}update(){if(!$.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&&this.onDragEnd(null)}}_isDragging=!1;_marker=null;_dragDelta;_didDrag=!1;onDragStart(e){if(!this._dragHelper)if(this.context.mainCamera)this._dragHelper=new ja(this.context.mainCamera);else return;if(!e||!e.object)return;let t=S.getComponentInParent(e.object,ao);if(!t||t!==this)return;let i=e.object;this.transformSelf&&(i=this.gameObject);let n={selected:i,attached:i};for(let c of this.selectStartEventListener)c(this,n);if(!n.attached)return;n.attached,i=n.attached,this._isDragging=!0,this._dragHelper.setSelected(i,this.context);let r=S.getComponentInChildren(i,Qe);Jc&&console.log("DRAG START",r,i),r&&(r.fastMode=!0,r?.requestOwnership()),this._marker=S.addNewComponent(i,It),this._draggingRigidbodies.length=0;let o=S.getComponentsInChildren(i,ce);o&&this._draggingRigidbodies.push(...o);let s=El();S.invokeOnChildren(this._dragHelper.selected,s("onDragStart"))}onUpdateDrag(){if(!!this._dragHelper){this._dragHelper.onUpdate(this.context);for(let e of this._draggingRigidbodies)e.wakeUp(),e.setBodyFromGameObject()}}onDragEnd(e){if(!this||!this._isDragging||(this._isDragging=!1,!this._dragHelper))return;this._draggingRigidbodies.length=0;let t=this._dragHelper.selected;if(Jc&&console.log("DRAG END",t,t?.visible),this._dragHelper.setSelected(null,this.context),e?.object){let n=S.getComponentInChildren(e.object,Qe);n&&(n.fastMode=!1),this._marker&&this._marker.destroy()}for(let n of this.selectEndEventListener)n(this);let i=El();S.invokeOnChildren(t,i("onDragEnd"))}},Et=ao;z(Et,"_active",null),z(Et,"lastHovered");var $c=class{get hasSelected(){return this._selected!==null&&this._selected!==void 0}get selected(){return this._selected}_selected=null;_context=null;_camera;_cameraPlane=new ee.Plane;_hasGroundPlane=!1;_groundPlane=new ee.Plane;_groundOffset=new ee.Vector3;_groundOffsetFactor=0;_groundDistance=0;_groundPlanePoint=new ee.Vector3;_raycaster=new ee.Raycaster;_cameraPlaneOffset=new ee.Vector3;_intersection=new ee.Vector3;_worldPosition=new ee.Vector3;_inverseMatrix=new ee.Matrix4;_rbs=[];_groundLine;_groundMarker;constructor(e){this._camera=e;let t=new ee.Line($c.geometry),i=t.material;i.color=new ee.Color(.4,.4,.4),t.layers.set(2),t.name="line",t.scale.y=1,this._groundLine=t;let n=new ee.SphereGeometry(.5,22,22),r=new ee.MeshBasicMaterial({color:i.color}),o=new ee.Mesh(n,r);o.visible=!1,o.layers.set(2),this._groundMarker=o}setSelected(e,t){if(this._selected&&t)for(let i of this._rbs)i.wakeUp(),i.smoothedVelocity&&i.setVelocity(i.smoothedVelocity.x,i.smoothedVelocity.y,i.smoothedVelocity.z);if(this._selected&&_e.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}_e.Add(t,this._selected,null),this._groundOffsetFactor=0,this._hasGroundPlane=!0,this._groundOffset.set(0,0,0),this._requireUpdateGroundPlane=!0,this._rbs=S.getComponentsInChildren(this._selected,ce),this.onUpdateScreenSpacePlane()}}_groundOffsetVector=new ee.Vector3(0,1,0);_requireUpdateGroundPlane=!0;_didDragOnGroundPlaneLastFrame=!1;onUpdate(e){if(!this._context)return;let t=32,i=68,n=83,r=this._context?.input.isKeyPressed(t)||this._context?.input.isKeyPressed(i),o=this._context.input.getTouchesPressedCount()>=2||r;if(o){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 s=this._context.input.getPointerPositionRC(0);if(!!s&&(this._raycaster.setFromCamera(s,this._camera),this._selected)){Jc&&console.log("UPDATE DRAG",this._selected),this._groundOffsetVector.set(0,1,0);let c=q(this._camera).clone().sub(q(this._selected)).normalize(),d=Math.abs(c.dot(this._groundOffsetVector)),a=this._context?.input.isKeyPressed(t)||this._context?.input.isKeyPressed(i),h=!o&&d>.2&&!a&&this._context.input.getPointerPressedCount()<=1,u=this._didDragOnGroundPlaneLastFrame!==h;if(this._didDragOnGroundPlaneLastFrame=h,this._hasGroundPlane||(this._requireUpdateGroundPlane=!0),(this._requireUpdateGroundPlane||!h||u)&&this.onUpdateGroundPlane(),this._requireUpdateGroundPlane=!1,this._hasGroundPlane)if(this._raycaster.ray.intersectPlane(this._groundPlane,this._intersection)){let f=this._intersection.y;if(this._groundPlanePoint.copy(this._intersection).sub(this._groundOffset),this._groundPlanePoint.y=f,h){this._groundOffsetVector.set(0,1,0);let E=this._intersection.sub(this._groundOffset).add(this._groundOffsetVector.multiplyScalar(this._groundOffsetFactor));this.onUpdateWorldPosition(E,this._groundPlanePoint,!1),this.onDidUpdate();return}}else this._groundPlanePoint.set(0,99999,0);u&&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,i){if(!!this._selected){if(i){let n=q(this._selected);n.y=e.y,e=n}if(ie(this._selected,e),ie(this._groundLine,e),this._hasGroundPlane?this._groundLine.scale.y=this._groundDistance:this._groundLine.scale.y=1e3,this._groundMarker.visible=t!==null,t){let n=q(this._camera).distanceTo(t)*.01;this._groundMarker.scale.set(n,n,n),ie(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=q(this._selected),t=new ee.Ray(new ee.Vector3(0,.1,0).add(e),new ee.Vector3(0,-1,0)),i=new je;i.ignore=[this._selected];let n=this._context.physics.raycastFromRay(t,i);for(let r=0;r<n.length;r++){let o=n[r];if(!o.face||this.contains(this._selected,o.object))continue;let s=new ee.Vector3(0,1,0);this._groundPlane.setFromNormalAndCoplanarPoint(s,o.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(){he.markDirty(this._selected);for(let e of this._rbs)e.wakeUp(),e.setBodyFromGameObject({x:0,y:0,z:0}),e.setAngularVelocity(0,0,0)}contains(e,t){if(e===t)return!0;if(e.children){for(let i of e.children)if(this.contains(i,t))return!0}return!1}},ja=$c;z(ja,"geometry",new ee.BufferGeometry().setFromPoints([new ee.Vector3(0,0,0),new ee.Vector3(0,-1,0)]));var An=class extends M{filesBackendUrl;localhost;_dragOver;_drop;onEnable(){this.filesBackendUrl=this.filesBackendUrl?pt.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 i in t){let n=t[i];if(n.kind==="file"){let r=n.getAsFile();if(!r)continue;console.log("Register file "+r.name+" to",this.filesBackendUrl,r);let o=await xp(r,this.context,this.filesBackendUrl);o&&this.addObject(e,o)}else n.kind==="string"&&n.type=="text/plain"&&n.getAsString(async r=>{console.log("dropped url",r);try{let o=new URL(r);if(!o)return;let s=await Tp(o,this.context);s&&this.addObject(e,s)}catch{console.log("dropped string is not a valid URL!",r)}})}}async addObject(e,t){console.log("Dropped",t);let i=new je;i.setMask(16777215),i.screenPointFromOffset(e.offsetX,e.offsetY);let n=this.context.physics.raycast(i),r=t.scene;if(n&&n.length>0)for(let o of n){r.position.copy(o.point);break}this.gameObject.add(r),this.dispatchEvent(new CustomEvent("object-added",{detail:t}))}};k([A()],An.prototype,"filesBackendUrl",2),k([A()],An.prototype,"localhost",2);import{Vector3 as Gv,Quaternion as Vv,Object3D as Rp}from"three";var vi=class extends kt{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 Gv(0,0,0),this._startQuaternion=this.object.quaternion?.clone()??new Vv(0,0,0,1)}let e=S.getComponentInParent(this.gameObject,Et);e?e.addDragEventListener("selectstart",(t,i)=>{if(this._currentCount>=this.limitCount){i.attached=null;return}let n=this.handleDuplication(i.selected);n&&(console.assert(n!==i.selected,"Duplicated object is original"),i.attached=n)}):console.warn("Could no find drag controls in parent",this.name),ae.addEventListener("select-start",(t,i)=>{if(this._currentCount>=this.limitCount){i.grab=null;return}let n=this.handleDuplication(i.selected);n&&(i.grab=n)}),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 ye;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 i=S.instantiateSynced(this.object,t);return console.assert(i!==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),i}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 i of e.children)if(this.isInChildren(i,t))return!0}return!1}};k([A(Rp)],vi.prototype,"parent",2),k([A(Rp)],vi.prototype,"object",2),k([A()],vi.prototype,"limitCount",2),k([A()],vi.prototype,"limitInterval",2);var yi=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)}}},Wv=l=>/^[A-Z]*$/.test(l),pr=class extends Event{args},Oe=class{target;key;setEventTarget(e,t){if(this.key=e,this.target=t,this.key!==void 0){let i="",n=!1;for(let r of this.key)n&&Wv(r)&&(i+="-"),n=!0,i+=r.toLowerCase();this.key=i}}_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 i=new pr(this.key);i.args=e,t.call(this.target,i)}}}finally{this._isInvoking=!1}}addEventListener(e){return this.methods.push(new yi(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}};var lo=class extends M{};import{FlyControls as Uv}from"three/examples/jsm/controls/FlyControls";var co=class extends M{_controls=null;onEnable(){let e=S.getComponent(this.gameObject,ne)?.cam;this._controls=new Uv(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 Sp from"three";import{Color as qv}from"three";var Xi=class extends M{objectBounds=!1;color;isGizmo=!0;_gizmoObject=null;_boxHelper=null;onEnable(){this.isGizmo&&!hi||(this._gizmoObject||(this.objectBounds&&this.gameObject.isMesh===!0?this._gizmoObject=new Sp.BoxHelper(this.gameObject,this.color??16776960):(this.objectBounds=!1,this._gizmoObject=Sa(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}};k([A()],Xi.prototype,"objectBounds",2),k([A(qv)],Xi.prototype,"color",2),k([A()],Xi.prototype,"isGizmo",2);import{GLTFExporter as Zv}from"three/examples/jsm/exporters/GLTFExporter.js";import{BufferAttribute as Kc,Matrix4 as Xv,Vector3 as Pp,Quaternion as Qv}from"three";var vs=class{constructor(e){this.writer=e,this.name="EXT_mesh_gpu_instancing"}writeNode(e,t){if(e.constructor.name!=="InstancedMesh")return;let i=this.writer,n=i.extensionsUsed,r={};t.extensions=t.extensions||{},t.extensions[this.name]=r;let o=new Xv,s=new Array,c=new Array,d=new Array;for(let f=0;f<e.count;f++){e.getMatrixAt(f,o);let E=new Pp,b=new Qv,y=new Pp;o.decompose(E,b,y),s.push(E.x,E.y,E.z),c.push(b.x,b.y,b.z,b.w),d.push(y.x,y.y,y.z)}let a=new Float32Array(s),h=new Float32Array(c),u=new Float32Array(d);r.attributes={TRANSLATION:i.processAccessor(new Kc(a,3)),ROTATION:i.processAccessor(new Kc(h,4)),SCALE:i.processAccessor(new Kc(u,3))},n[this.name]=!0}};import{Object3D as Jv,Vector3 as $v}from"three";var kn=Ie,Fa="$___Export_Components",Yv="NEEDLE_components",ed=class{[qn]},td=class{node;nodeIndex;nodeDef;constructor(e,t,i){this.node=e,this.nodeIndex=t,this.nodeDef=i}},ho=class{get name(){return Yv}parser;nodeToObjectMap={};exportContext;objectToNodeMap={};context;writer;registerExport(e){e.register(t=>{let i=t.serializeUserData.bind(t);return this.writer=t,t.serializeUserData=(n,r)=>{try{this.serializeUserData(n,r),i(n,r)}finally{this.afterSerializeUserData(n,r)}},this})}beforeParse(){this.exportContext={},this.objectToNodeMap={}}serializeUserData(e,t){let i=e.userData?.components;!i||i.length<=0||(delete e.userData.components,e[Fa]=i)}afterSerializeUserData(e,t){if(e.type==="Scene"&&kn&&console.log("DONE",JSON.stringify(t)),e[Fa]===void 0)return;let i=e[Fa];delete e[Fa],i!==null&&(e.userData.components=i)}writeNode(e,t){let i=this.writer.json.nodes.length;console.log(e.name,i,e.uuid);let n=new td(e,i,t);this.exportContext[i]=n,this.objectToNodeMap[e.uuid]=i}afterParse(e){kn&&console.log("AFTER",e);for(let t in this.exportContext){let i=this.exportContext[t],n=i.node,r=i.nodeDef,o=i.nodeIndex,s=n.userData?.components;if(!s||s.length<=0)continue;let c=new ed;r.extensions=r.extensions||{},r.extensions[this.name]=c,this.context.object=n,this.context.nodeId=o,this.context.objectToNode=this.objectToNodeMap;let d=[];for(let a of s){this.context.target=a;let h=Op(a,this.context);h!==null&&d.push(h)}d.length>0&&(c[qn]=d,kn&&console.log("DID WRITE",n,"nodeIndex",o,d))}}beforeRoot(){return kn&&console.log("BEGIN LOAD"),this.nodeToObjectMap={},null}async afterRoot(e){let t=e.parser,i=t?.extensions;if(!i)return;let n=i[this.name];kn&&console.log("After root",e,this.parser,i);let r=[];if(n===!0){let o=t.json.nodes;for(let s=0;s<o.length;s++){let c=await t.getDependency("node",s);this.nodeToObjectMap[s]=c}for(let s=0;s<o.length;s++){let c=o[s],d=s,a=c.extensions;if(!a)continue;let h=a[this.name];if(!h)continue;kn&&console.log("NODE",c);let u=this.nodeToObjectMap[d];if(!u){console.error("Could not find object for node index: "+d,c,t);continue}r.push(this.createComponents(u,h))}}await Promise.all(r)}async createComponents(e,t){if(!t)return;let i=t[qn];if(i){kn&&console.log(e.name,i);for(let n in i){let r=i[n];kn&&console.log("Serialized data",JSON.parse(JSON.stringify(r))),r&&this.parser&&await Ur(this.parser,r),e.userData=e.userData||{},e.userData[qn]=e.userData[qn]||[],e.userData[qn].push(r)}}}};var uo=class extends lt{sceneRoot;start(){this.startCoroutine(this.updateGltfBox())}*updateGltfBox(){for(;;)for(let e=0;e<10;e++)yield}},jt=class extends M{binary=!0;objects=[];exporter;ext;async exportNow(e){console.log("DO EXPORT",this.objects);let t={binary:this.binary,pivot:jt.calculateCenter(this.objects)},i=await this.export(this.objects,t);this.binary?e.endsWith(".glb")||(e+=".glb"):e.endsWith(".gltf")||(e+=".gltf"),this.binary?jt.saveArrayBuffer(i,e):jt.saveJson(i,e)}async export(e,t){if(e===null||e.length<=0){console.log("no objects set to export");return}this.exporter||(this.exporter=new Zv,this.exporter.register(s=>new vs(s)),this.ext=new ho,this.ext.registerExport(this.exporter)),jt.filterTopmostParent(e);let i={trs:!1,onlyVisible:!0,truncateDrawRange:!1,binary:t?.binary??!0,maxTextureSize:1/0,embedImages:!0,includeCustomExtensions:!0,animations:jt.collectAnimations(e)},n=new Jv;t?.pivot&&n.position.sub(t.pivot),console.log("EXPORT",e),e.forEach(s=>{s&&(n.children.push(s),s.matrixAutoUpdate=!1,s.matrix.copy(s.matrixWorld),S.getComponentsInChildren(s,Te).forEach(c=>{S.isActiveInHierarchy(c.gameObject)&&c.setInstancingEnabled(!1)}))});let r=new qr(n);return this.ext.context=r,new Promise((s,c)=>{try{this.exporter?.parse(n,d=>{o(),s(d)},d=>{o(),c(d)},i)}catch(d){console.error(d),c(d)}finally{console.log("FINALLY")}});function o(){e.forEach(s=>{!s||(s.matrixAutoUpdate=!0,S.getComponentsInChildren(s,Te).forEach(c=>{S.isActiveInHierarchy(c.gameObject)&&c.setInstancingEnabled(!1)}))})}}static saveArrayBuffer(e,t){this.save(new Blob([e],{type:"application/octet-stream"}),t)}static saveJson(e,t){this.save("data: text/json;charset=utf-8,"+encodeURIComponent(JSON.stringify(e)),t)}static save(e,t){let i=document.createElement("a");i.style.display="none",document.body.appendChild(i),typeof e=="string"?i.href=e:i.href=URL.createObjectURL(e),i.download=t,i.click(),i.remove()}static collectAnimations(e,t){t=t||[];for(let i of e)!i||i.traverseVisible(n=>{n.animations&&n.animations.length>0&&t.push(...n.animations)});return t}static calculateCenter(e,t){let i=t||new $v;return i.set(0,0,0),e.forEach(n=>{i.add(q(n))}),console.log(i),i.divideScalar(e.length),i}static filterTopmostParent(e){if(!(e.length<=0))for(let t=0;t<e.length;t++){let i=e[t];if(!i){e.splice(t,1),t--;continue}for(;i.parent;){if(e.includes(i.parent)){e.splice(t,1),t--;break}i=i.parent}}}};import{Color as Na,GridHelper as Kv}from"three";var Qi=class extends M{isGizmo=!1;color0;color1;gridHelper;size;divisions;offset;onEnable(){if(this.isGizmo&&!hi)return;let e=this.size,t=this.divisions;this.gridHelper||(this.gridHelper=new Kv(e,t,this.color0??new Na(.4,.4,.4),this.color1??new Na(.6,.6,.6)),this.offset!==void 0&&(this.gridHelper.position.y+=this.offset),this.gameObject.add(this.gridHelper))}};k([A()],Qi.prototype,"isGizmo",2),k([A(Na)],Qi.prototype,"color0",2),k([A(Na)],Qi.prototype,"color1",2);import{GroundProjectedEnv as ey}from"three/examples/jsm/objects/GroundProjectedEnv.js";var Yi=class extends M{set scale(e){this._scale=e,this.env?.scale.setScalar(e)}get scale(){return this._scale}_scale=20;set radius(e){this._radius=e,this.env&&(this.env.height=e)}get radius(){return this._radius}_radius=100;set height(e){this._height=e,this.env&&(this.env.height=e)}get height(){return this._height}_height=100;_lastEnvironment;env;_watcher;onEnable(){this.updateProjection(),this._watcher||(this._watcher=new As(this.context.scene,"environment"),this._watcher.subscribeWrite(this.updateProjection.bind(this))),this._watcher.apply()}onDisable(){this._watcher?.revoke(),this.env?.removeFromParent()}updateProjection(){!this.context.scene.environment||((!this.env||this.context.scene.environment!==this._lastEnvironment)&&(console.log("Create/Update Ground Projection",this.context.scene.environment.name),this.env=new ey(this.context.scene.environment)),this._lastEnvironment=this.context.scene.environment,this.env.parent||this.gameObject.add(this.env),this.env.scale.setScalar(this._scale),this.env.radius=this._radius,this.env.height=this._height,this.env.isObject3D===!0&&this.env.layers.set(2))}};k([A()],Yi.prototype,"scale",1),k([A()],Yi.prototype,"radius",1),k([A()],Yi.prototype,"height",1);import*as it from"three";import{Color as ty}from"three";function id(l){return l*Math.PI/180}var Ap=300,kp=N("debuglights");var Ye=class extends M{type=0;range=1;spotAngle=1;innerSpotAngle=1;color=new it.Color(16777215);set shadowNearPlane(e){if(e!==this._shadowNearPlane&&(this._shadowNearPlane=e,this.light?.shadow?.camera!==void 0)){let t=this.light.shadow.camera;t.near=e}}get shadowNearPlane(){return this._shadowNearPlane}_shadowNearPlane=.1;set shadowBias(e){e!==this._shadowBias&&(this._shadowBias=e,this.light?.shadow?.bias!==void 0&&(this.light.shadow.bias=e,this.light.shadow.needsUpdate=!0))}get shadowBias(){return this._shadowBias}_shadowBias=0;set shadowNormalBias(e){e!==this._shadowNormalBias&&(this._shadowNormalBias=e,this.light?.shadow?.normalBias!==void 0&&(this.light.shadow.normalBias=e,this.light.shadow.needsUpdate=!0))}get shadowNormalBias(){return this._shadowNormalBias}_shadowNormalBias=1;set shadows(e){this._shadows=e,this.light&&(this.light.castShadow=e===1||e===2)}get shadows(){return this._shadows}_shadows=1;lightmapBakeType=4;set intensity(e){if(this._intensity=e,this.light){let t=1;if(this.context.isInXR&&this._webARRoot){let i=this._webARRoot?.arScale;typeof i=="number"&&i>0&&(t/=i)}this.light.intensity=e*t}}get intensity(){return this._intensity}_intensity=1;get shadowDistance(){let e=this.light;return e?e.shadow.camera.far:-1}set shadowDistance(e){this._shadowDistance=e;let t=this.light;if(t){let i=t.shadow.camera;i.far=e,i.updateProjectionMatrix()}}_shadowDistance;shadowWidth;shadowHeight;get shadowResolution(){let e=this.light;return e?e.shadow.mapSize.x:-1}set shadowResolution(e){if(e===this._shadowResolution)return;this._shadowResolution=e;let t=this.light;t&&(t.shadow.mapSize.set(e,e),t.shadow.needsUpdate=!0)}_shadowResolution=void 0;get isBaked(){return this.lightmapBakeType===2}get selfIsLight(){if(this.gameObject.isLight===!0)return!0;switch(this.gameObject.type){case"SpotLight":case"PointLight":case"DirectionalLight":return!0}return!1}light=void 0;getWorldPosition(e){return this.light?this.type===1?this.light.getWorldPosition(e).multiplyScalar(1):this.light.getWorldPosition(e):e}updateIntensity(){this.intensity=this._intensity}awake(){this.color=new it.Color(this.color??16777215)}onEnable(){this.createLight(),!this.isBaked&&(this.light&&(this.selfIsLight||this.light.parent!==this.gameObject&&this.gameObject.add(this.light)),this.type===1&&this.startCoroutine(this.updateMainLightRoutine(),2),this._webXRStartedListener=$.addEventListener("xrStarted",this.onWebXRStarted.bind(this)),this._webXREndedListener=$.addEventListener("xrStopped",this.onWebXREnded.bind(this)))}onDisable(){$.removeEventListener("xrStarted",this._webXRStartedListener),$.removeEventListener("xrStopped",this._webXREndedListener)}_webXRStartedListener;_webXREndedListener;_webARRoot;onWebXRStarted(){this._webARRoot=this.gameObject.getComponentInParent(Dt)??void 0,this.startCoroutine(this._updateLightIntensityInARRoutine())}*_updateLightIntensityInARRoutine(){for(;this.context.isInXR;){yield,this.updateIntensity();for(let e=0;e<30;e++)yield}}onWebXREnded(){this.updateIntensity()}createLight(){if(this.light)return;let e=this.selfIsLight;if(e)switch(this.light=this.gameObject,this.type){case 1:this.setDirectionalLight(this.light);break}else switch(this.type){case 1:let t=new it.DirectionalLight(this.color,this.intensity*Math.PI);if(t.position.set(0,0,-Ap*.5).applyQuaternion(this.gameObject.quaternion),this.gameObject.add(t.target),Mr(t.target,0,0,0),this.light=t,this.gameObject.position.set(0,0,0),this.gameObject.rotation.set(0,0,0),kp){let o=new it.DirectionalLightHelper(this.light,.2,this.color);this.context.scene.add(o)}break;case 0:let i=new it.SpotLight(this.color,this.intensity*Math.PI,this.range,id(this.spotAngle/2),1-id(this.innerSpotAngle/2)/id(this.spotAngle/2),2);i.position.set(0,0,0),i.rotation.set(0,0,0),this.light=i;let n=i.target;i.add(n),n.position.set(0,0,this.range),n.rotation.set(0,0,0);break;case 2:let r=new it.PointLight(this.color,this.intensity*Math.PI,this.range);this.light=r;break}if(this.light!==void 0){this.shadows!==0?this.light.castShadow=!0:this.light.castShadow=!1,this._shadowResolution!==void 0&&this._shadowResolution>4?(this.light.shadow.mapSize.width=this._shadowResolution,this.light.shadow.mapSize.height=this._shadowResolution):(this.light.shadow.mapSize.width=2048,this.light.shadow.mapSize.height=2048),this.light.shadow.bias=this.shadowBias*1e-5,this.light.shadow.normalBias=this.shadowNormalBias*1e-4;let t=this.light.shadow.camera;if(t.near=this.shadowNearPlane,this._shadowDistance!==void 0&&typeof this._shadowDistance=="number"?t.far=this._shadowDistance:t.far=Ap*Math.abs(this.gameObject.scale.z),this.gameObject.scale.set(1,1,1),this.shadowWidth!==void 0)t.left=-this.shadowWidth/2,t.right=this.shadowWidth/2;else{let i=this.gameObject.scale.x;t.left*=i,t.right*=i}if(this.shadowHeight!==void 0)t.top=this.shadowHeight/2,t.bottom=-this.shadowHeight/2;else{let i=this.gameObject.scale.y;t.top*=i,t.bottom*=i}this.light.shadow.needsUpdate=!0,kp&&this.context.scene.add(new it.CameraHelper(t)),this.isBaked?this.light.removeFromParent():e||this.gameObject.add(this.light)}}*updateMainLightRoutine(){for(;;){this.type===1&&((!this.context.mainLight||this.intensity>this.context.mainLight.intensity)&&(this.context.mainLight=this),yield);break}}setDirectionalLight(e){e.add(e.target),e.target.position.set(0,0,-1)}};k([A()],Ye.prototype,"type",2),k([A(ty)],Ye.prototype,"color",2),k([A()],Ye.prototype,"shadowNearPlane",1),k([A()],Ye.prototype,"shadowBias",1),k([A()],Ye.prototype,"shadowNormalBias",1),k([A()],Ye.prototype,"shadows",1),k([A()],Ye.prototype,"lightmapBakeType",2),k([A()],Ye.prototype,"intensity",1),k([A()],Ye.prototype,"shadowDistance",1),k([A()],Ye.prototype,"shadowResolution",1);var XO=new it.Vector3(0,0,0);import*as za from"three";import{Vector3 as iy}from"three";var po=N("debugLODs"),ny=N("noLODs");var Ei=class{screenRelativeTransitionHeight;distance;renderers};k([A()],Ei.prototype,"screenRelativeTransitionHeight",2),k([A()],Ei.prototype,"distance",2),k([A()],Ei.prototype,"renderers",2);var nd=class{model;renderers;constructor(e,t){this.model=t,this.renderers=[];for(let i of t.renderers){let n=this.findRenderer(i,e.gameObject);n&&n.gameObject?this.renderers.push(n):po&&console.warn("Renderer not found: "+i,e.gameObject)}}findRenderer(e,t){let i=S.foreachComponent(t,n=>n.guid===e||Object.getPrototypeOf(n)?.guid===e?n:null);if(i)return i;for(let n of t.children){let r=this.findRenderer(e,n);if(r)return r}return null}},In=class extends M{fadeMode=0;localReferencePoint=void 0;lodCount=0;size=0;animateCrossFading=!1;lodModels;_lods=[];_settings=[];_lodsHandler;start(){if(!ny&&!this._lodsHandler&&!!this.gameObject&&(po&&console.log(this),this.lodModels&&Array.isArray(this.lodModels))){let e=0,t=[];for(let n of this.lodModels){e=Math.max(n.distance,e);let r=new nd(this,n);this._lods.push(r);for(let o of r.renderers)t.includes(o)||t.push(o)}this._lodsHandler=new Array;for(let n=0;n<t.length;n++){let r=new za.LOD;this._lodsHandler.push(r),this.gameObject.add(r)}let i=new za.Object3D;po&&console.log(t);for(let n=0;n<t.length;n++){let r=t[n],o=this._lodsHandler[n],s=r.gameObject,c=0,d=0;po&&console.log(n,s.name);for(let h of this._lods){let u=null;h.renderers.includes(r)?u=s:u=i,po&&console.log("add",h.model.distance,u.name);let f=h.model.distance;d=f-c,c=Math.max(f,c),this.onAddLodLevel(o,u,f)}let a=c+d;po&&console.log("cull",a),this.onAddLodLevel(o,i,a)}}}update(){if(!this.gameObject||!this._lodsHandler)return;let e=this.context.mainCamera;if(!!e)for(let t of this._lodsHandler)t.update(e)}onAddLodLevel(e,t,i){e.addLevel(t,i*this._distanceFactor);let n={lod:e,levelIndex:e.levels.length-1,distance:i};this._settings.push(n)}_distanceFactor=1;distanceFactor(e){if(e!==this._distanceFactor){this._distanceFactor=e;for(let t of this._settings){let i=t.lod.levels[t.levelIndex];i.distance=t.distance*e}}}};k([A(iy)],In.prototype,"localReferencePoint",2),k([A(Ei)],In.prototype,"lodModels",2);var fo=class extends M{},mo=class extends M{};var rd=N("debugnestedgltf"),fr=class extends M{filePath;_isLoadingOrDoneLoading=!1;listenToProgress(e){this.filePath?.beginListenDownload(e)}preload(){this.filePath?.preload()}async start(){if(this._isLoadingOrDoneLoading)return;rd&&console.log(this,this.guid);let e=this.gameObject.parent;if(e){this._isLoadingOrDoneLoading=!0;let t=new ye;t.idProvider=new We(this.hash(this.guid)),t.parent=e,this.gameObject.updateMatrix();let i=this.gameObject.matrix;rd&&console.log("Load nested:",this.filePath?.uri??this.filePath,this.gameObject.position);let n=await this.filePath?.instantiate?.call(this.filePath,t);n&&(n.matrixAutoUpdate=!1,n.matrix.identity(),n.applyMatrix4(i),n.matrixAutoUpdate=!0),this.destroy(),rd&&console.log("Nested loading done:",this.filePath?.uri??this.filePath,n)}}hash(e){let t=0;for(let i=0;i<e.length;i++)t=e.charCodeAt(i)+((t<<5)-t);return t}};k([A(tt)],fr.prototype,"filePath",2);import{Quaternion as ry,Euler as oy,Vector3 as mr,Plane as sy}from"three";var wi=class extends M{referenceSpace;from;affectPosition=!1;affectRotation=!1;alignLookDirection=!1;levelLookDirection=!1;levelPosition=!1;positionOffset=new mr(0,0,0);rotationOffset=new mr(0,0,0);offset=new mr(0,0,0);update(){if(!this.from)return;var e=q(this.from),t=ve(this.from);this.offset.copy(this.positionOffset);let i=this.offset.length();if(this.referenceSpace&&this.offset.transformDirection(this.referenceSpace.matrixWorld).multiplyScalar(i),e.add(this.offset),this.levelPosition&&this.referenceSpace){let s=new sy(this.gameObject.up,0),c=q(this.referenceSpace);s.setFromNormalAndCoplanarPoint(this.gameObject.up,c);let d=new mr(0,0,0);s.projectPoint(e,d),e.copy(d)}this.affectPosition&&ie(this.gameObject,e);let n=new oy(this.rotationOffset.x,this.rotationOffset.y,this.rotationOffset.z),r=new ry().setFromEuler(n);this.affectRotation&&Ae(this.gameObject,t.multiply(r));let o=new mr;this.from.getWorldDirection(o).multiplyScalar(50),this.levelLookDirection&&(o.y=0),this.alignLookDirection&&this.gameObject.lookAt(o)}};k([A(S)],wi.prototype,"referenceSpace",2),k([A(S)],wi.prototype,"from",2),k([A(mr)],wi.prototype,"positionOffset",2),k([A(mr)],wi.prototype,"rotationOffset",2);import*as xe from"three";import*as ei from"three";var go=class{randomizeRotationDirection=0;duration=5;loop=!0;prewarm=!1;startDelay=void 0;startDelayMultiplier=0;startLifetime=void 0;startLifetimeMultiplier=5;startSpeed=void 0;startSpeedMultiplier=5;startSize3D=!1;startSize=void 0;startSizeMultiplier=1;startSizeX=void 0;startSizeXMultiplier=1;startSizeY=void 0;startSizeYMultiplier=1;startSizeZ=void 0;startSizeZMultiplier=1;startRotation3D=!1;startRotation=void 0;startRotationMultiplier=0;startRotationX=void 0;startRotationXMultiplier=0;startRotationY=void 0;startRotationYMultiplier=0;startRotationZ=void 0;startRotationZMultiplier=0;flipRotation=0;startColor=new ei.Color(1,1,1);startColor1=new ei.Color(0,0,0);gravityModifier=void 0;gravityModifierMultiplier=0;simulationSpace=0;customSimulationSpace=null;simulationSpeed=1;useUnscaledTime=!1;scalingMode=1;playOnAwake=!0;maxParticles=1e3;emitterVelocityMode=1;stopAction=0;ringBufferMode=0;ringBufferLoopRange=new ei.Vector2(0,1);cullingMode=0},bo=class{burstCount=0;enabled=!0;rate=10;rateMutliplier=1;rateOverDistance=0;rateOverDistanceMultiplier=0;rateOverTime=0;rateOverTimeMultiplier=0},vo=class{shapeType=od.Box;enabled=!0;alignToDirection=!1;angle=0;arc=360;arcmode=0;box=new ei.Vector3(1,1,1);boxThickness=new ei.Vector3(0,0,0);position=new ei.Vector3(0,0,0);rotation=new ei.Vector3(0,0,0);scale=new ei.Vector3(1,1,1);radius=1;sphericalDirectionAmount=0},od=(p=>(p[p.Sphere=0]="Sphere",p[p.SphereShell=1]="SphereShell",p[p.Hemisphere=2]="Hemisphere",p[p.HemisphereShell=3]="HemisphereShell",p[p.Cone=4]="Cone",p[p.Box=5]="Box",p[p.Mesh=6]="Mesh",p[p.ConeVolume=7]="ConeVolume",p[p.Circle=10]="Circle",p[p.SingleSidedEdge=11]="SingleSidedEdge",p[p.MeshRenderer=12]="MeshRenderer",p[p.SkinnedMeshRenderer=13]="SkinnedMeshRenderer",p[p.BoxShell=14]="BoxShell",p[p.BoxEdge=15]="BoxEdge",p[p.Donut=16]="Donut",p[p.Rectangle=17]="Rectangle",p[p.Sprite=18]="Sprite",p[p.SpriteRenderer=19]="SpriteRenderer",p))(od||{});var Ip=N("debugparticles"),sd=class{age=0;lifetime=0;position;velocity;color},gr=class extends M{get mainTexture(){if(this.sharedMaterial){let e=this.context.assets.findTexture(this.sharedMaterial);if(e)return e}return null}getMesh(e){return this.mesh?this.context.assets.findMesh(this.mesh):null}sharedMaterial;mesh;awake(){Ip&&console.log(this)}},yo=class extends M{main;emission;shape;renderer;geometry;material;particlesMesh;positions;positionsArray;particleStates=[];activeCount=0;shapeRotation=new xe.Quaternion;tempVec3=new xe.Vector3;tempQuat=new xe.Quaternion;awake(){this.renderer=S.getComponent(this.gameObject,gr),Ip&&console.log(this)}onEnable(){if(this.geometry)return;this.particleStates=[],this.shapeRotation.setFromEuler(new xe.Euler(this.shape.rotation.x,this.shape.rotation.y,this.shape.rotation.z)),this.geometry=new xe.BufferGeometry,this.positionsArray=new Float32Array(this.main.maxParticles*3),this.positions=new xe.Float32BufferAttribute(this.positionsArray,3),this.geometry.setAttribute("position",this.positions);let e=new Float32Array(this.main.maxParticles*3);for(let i=0;i<e.length;i++)e[i*3]=1,e[i*3+1]=1,e[i*3+2]=1;let t=new xe.Float32BufferAttribute(e,3);this.geometry.setAttribute("color",t),this.material=new xe.PointsMaterial({size:this.main.startSize,color:16777215,vertexColors:!0}),this.material.map=this.renderer.mainTexture,this.particlesMesh=new xe.Points(this.geometry,this.material),this.particlesMesh.layers.enable(2),this.gameObject.add(this.particlesMesh),this.activeCount=this.main.prewarm?this.main.maxParticles:0}update(){if(!this.geometry)return;let e=this.context.time.deltaTime;this.emit(e);for(let t=0;t<this.activeCount;t+=1){let i=this.particleStates[t];if(!i)continue;let n=i.velocity.x*e,r=i.velocity.y*e,o=i.velocity.z*e;i.position.x+=n,i.position.y+=r,i.position.z+=o,this.updateOverLifetime(t,i),this.geometry.attributes.position.setXYZ(t,i.position.x,i.position.y,i.position.z),this.geometry.attributes.color.setXYZ(t,i.color.r,i.color.g,i.color.b)}this.geometry&&(this.geometry.attributes.position.needsUpdate=!0,this.geometry.setDrawRange(0,this.activeCount))}emit(e){let t=this.activeCount;for(let i=0;i<t;i+=1){if(i>=this.particleStates.length){let r=new sd;r.lifetime=this.main.startLifetime??1,r.position=new xe.Vector3,r.velocity=new xe.Vector3,r.color=new xe.Color(1,0,0),this.particleStates.push(r),this.initializeParticle(i,r),r.age=r.lifetime*Math.random()}let n=this.particleStates[i];if(n.age>n.lifetime){this.activeCount-=1,this.activeCount=Math.max(0,this.activeCount),this.initializeParticle(i,n);continue}n.age+=e,this.particleStates[i]=n}this.activeCount+=e*this.emission.rate,this.activeCount=Math.min(this.main.maxParticles,this.activeCount)}initializeParticle(e,t){if(!this.geometry)return;t.age=0,t.color.set(this.main.startColor),this.main.startColor1&&t.color.lerp(this.main.startColor1,Math.random()),this.geometry.attributes.color.needsUpdate=!0,this.assignPosition(t.position),this.assignVelocity(t.position,t.velocity);let i=t.position;i.multiply(this.shape.scale),i.applyQuaternion(this.shapeRotation),i.add(this.shape.position),this.particleStates.splice(e,1),this.particleStates.push(t)}updateOverLifetime(e,t){}assignPosition(e){switch(this.shape.shapeType){case 0:e.set(Math.random()-.5,Math.random()-.5,Math.random()-.5).multiplyScalar(this.shape.radius);break;case 5:e.set(Math.random()-.5,Math.random()-.5,Math.random()-.5);break;default:e.set(0,0,0);break}}assignVelocity(e,t){switch(this.shape.shapeType){case 0:t.set(e.x,e.y,e.z);break;case 5:t.set(0,0,1),this.shape.sphericalDirectionAmount>0&&(this.tempVec3.set(e.x,e.y,e.z).multiply(this.shape.scale).normalize(),t.lerp(this.tempVec3,this.shape.sphericalDirectionAmount));break;case 4:let i=new xe.Vector3(0,1,0);t.copy(i);break;case 10:this.tempQuat.setFromAxisAngle(this.tempVec3.set(0,0,1),Math.random()*Q.toRadians(this.shape.arc)),t.copy(this.tempVec3.set(1,0,0).applyQuaternion(this.tempQuat));break;default:t.set(Math.random()*2-1,Math.random()*2-1,Math.random()*2-1);break}switch(t.normalize(),this.shape.shapeType){case 10:e.add(t).multiplyScalar(this.shape.radius);break}t.multiplyScalar(this.main.startSpeedMultiplier)}};import*as Lp from"three";function*Mp(l,e=null){let t=e?e.time:Z.Current.time,i=t.time;for(;t.time-i<l;)yield}var ht=class extends M{awake(){this.context.connection.beginListen("joined-room",this.tryAssignColor.bind(this))}_didAssignPlayerColor=!1;onEnable(){this._didAssignPlayerColor||this.startCoroutine(this.waitForConnection())}*waitForConnection(){for(;!this.destroyed&&this.enabled&&(yield Mp(.2),!this.tryAssignColor()););}tryAssignColor(){let e=S.getComponentInParent(this.gameObject,pe);return e&&e.connectionId?(this._didAssignPlayerColor=!0,this.assignUserColor(e.connectionId),!0):!1}assignUserColor(e){let t=ht.hashCode(e),i=ht.colorFromHashCode(t);if(this.gameObject.type==="Mesh"){let n=this.gameObject;this.assignColor(i,e,n)}else if(this.gameObject.children)for(let n of this.gameObject.children){let r=n;r.material&&r.material.color&&this.assignColor(i,e,r)}}assignColor(e,t,i){let n=i.material;!n||(n._playerMaterial!==t?(n=n.clone(),n._playerMaterial=t,i.material=n):console.log("DONT CLONE",n),n.color=e)}static hashCode(e){var t=0,i,n;if(e.length===0)return t;for(i=0;i<e.length;i++)n=e.charCodeAt(i),t=(t<<5)-t+n,t|=0;return t}static colorFromHashCode(e){let t=(e&16711680)>>16,i=(e&65280)>>8,n=e&255;return new Lp.Color(t/255,i/255,n/255)}};import*as Ga from"three";import{Object3D as cy}from"three";function ly(){return new Promise((l,e)=>{let i=()=>{i!=null&&(document.removeEventListener("pointerdown",i),document.removeEventListener("click",i),document.removeEventListener("dragstart",i),document.removeEventListener("touchstart",i),l())};document.addEventListener("pointerdown",i),document.addEventListener("click",i),document.addEventListener("dragstart",i),document.addEventListener("touchstart",i)})}async function Dp(l){await ly(),l()}var ad=N("debugvideo");var nt=class extends M{renderer=null;playOnAwake=!0;playOnEnable;targetMaterialProperty;time=0;_playbackSpeed=1;get playbackSpeed(){return this.videoElement?.playbackRate??this._playbackSpeed}set playbackSpeed(e){this._playbackSpeed=e,this.videoElement&&(this.videoElement.playbackRate=e)}_isLooping=!1;get isLooping(){return this.videoElement?.loop??this._isLooping}set isLooping(e){this._isLooping=e,this.videoElement&&(this.videoElement.loop=e)}get currentTime(){return this.videoElement?.currentTime??this.time}set currentTime(e){this.videoElement?this.videoElement.currentTime=e:this.time=e}get isPlaying(){let e=this.videoElement;return e?e.currentTime>0&&!e.paused&&!e.ended&&e.readyState>e.HAVE_CURRENT_DATA:!1}get crossOrigin(){return this.videoElement?.crossOrigin??this._crossOrigin}set crossOrigin(e){this._crossOrigin=e,this.videoElement&&(e!==null?this.videoElement.setAttribute("crossorigin",e):this.videoElement.removeAttribute("crossorigin"))}_crossOrigin="anonymous";audioOutputMode=1;source;clip=null;url=null;videoElement=null;videoTexture=null;videoMaterial=null;_isPlaying=!1;wasPlaying=!1;setClipURL(e){this.url!==e&&(this.url=e,this.source=1,ad&&console.log("set url",e),this.videoElement&&(this.videoElement.src=e,this._isPlaying&&this.videoElement.play()))}awake(){this.create(this.playOnAwake),window.addEventListener("visibilitychange",e=>{switch(document.visibilityState){case"hidden":this.wasPlaying=this._isPlaying,this.pause();break;case"visible":this.wasPlaying&&this.play();break}})}onEnable(){this.playOnEnable===!0&&this.handleBeginPlaying(!0)}onDisable(){this.pause()}onDestroy(){this.videoElement&&(this.videoElement.parentElement?.removeChild(this.videoElement),this.videoElement=null),this.videoTexture&&(this.videoTexture.dispose(),this.videoTexture=null)}_receivedInput=!1;constructor(){super(),Dp(()=>{this._receivedInput=!0,this.updateVideoElementSettings()})}play(){!this.videoElement||this._isPlaying&&!this.videoElement?.ended&&!this.videoElement?.paused||(this._isPlaying=!0,this._receivedInput||(this.videoElement.muted=!0),this.updateVideoElementSettings(),this.videoElement?.play().catch(e=>{console.warn(e)}),ad&&console.log("play",this.videoElement))}stop(){this._isPlaying=!1,this.videoElement&&(this.videoElement.currentTime=0,this.videoElement.pause())}pause(){this._isPlaying=!1,this.videoElement?.pause()}create(e){let t;switch(this.source){case 0:t=this.clip;break;case 1:t=this.url;break}!t||(this.videoElement||(this.videoElement=this.createVideoElement(),this.context.domElement?.prepend(this.videoElement),this.updateVideoElementStyles()),typeof t=="string"?this.videoElement.src=t:this.videoElement.srcObject=t,this.videoTexture||(this.videoTexture=new Ga.VideoTexture(this.videoElement)),this.videoTexture.flipY=!1,this.videoTexture.encoding=Ga.sRGBEncoding,this.handleBeginPlaying(e))}createVideoElement(){let e=document.createElement("video");return this._crossOrigin&&e.setAttribute("crossorigin",this._crossOrigin),ad&&console.log("create video elment",e),e}handleBeginPlaying(e){if(!this.enabled||!this.videoElement)return;let t=this.gameObject.material;if(t)if(t!==this.videoMaterial&&(this.videoMaterial=t.clone(),this.gameObject.material=this.videoMaterial),!this.targetMaterialProperty)this.videoMaterial.map=this.videoTexture;else switch(this.targetMaterialProperty){default:this.videoMaterial.map=this.videoTexture;break}else{console.warn("Can not play video, no material found, this might be a multimaterial case which is not supported yet");return}this.updateVideoElementSettings(),this.updateVideoElementStyles(),e&&this.play()}updateVideoElementSettings(){!this.videoElement||(this.videoElement.loop=this._isLooping,this.videoElement.currentTime=this.currentTime,this.videoElement.playbackRate=this._playbackSpeed,this.videoElement.playsInline=!0,this.videoElement.muted=!this._receivedInput&&this.audioOutputMode!==0,(this.playOnAwake||this.playOnEnable)&&(this.videoElement.autoplay=!0))}updateVideoElementStyles(){!this.videoElement||(this.videoElement.style.userSelect="none",this.videoElement.style.visibility="hidden",this.videoElement.style.display="none")}};k([A(cy)],nt.prototype,"renderer",2),k([A()],nt.prototype,"playOnAwake",2),k([A()],nt.prototype,"playOnEnable",2),k([A()],nt.prototype,"targetMaterialProperty",2),k([A()],nt.prototype,"time",2),k([A()],nt.prototype,"playbackSpeed",1),k([A()],nt.prototype,"isLooping",1);var Eo=class extends M{streamOnAwake=!0;start(){this.streamOnAwake&&this.open()}requestOpen=!1;captureStream=null;async open(e=!1){if(!(this.captureStream&&!e)){this.close(),this.requestOpen=!0;try{let t=S.getComponentInChildren(this.gameObject,nt);if(t){let i={video:!0,audio:!1};this.captureStream=await navigator.mediaDevices.getDisplayMedia(i),this.captureStream&&this.requestOpen&&(t.clip=this.captureStream,t.create(!0))}}catch(t){console.error("Error: "+t)}}}close(){if(this.requestOpen=!1,this.captureStream){for(let e of this.captureStream.getTracks())e.stop();this.captureStream=null}}};import{ShadowMaterial as dy,AdditiveBlending as hy}from"three";var Mn=class extends M{mode=0;shadowColor=new we(0,0,0,1);awake(){switch(this.mode){case 0:this.applyShadowMaterial();break;case 1:this.applyLightBlendMaterial();break}}applyLightBlendMaterial(){let e=S.getComponent(this.gameObject,Te);if(e){let t=e.material;t.blending=hy,this.applyMaterialOptions(t),t.onBeforeCompile=i=>{i.fragmentShader=i.fragmentShader.replace("vec3 outgoingLight = totalDiffuse + totalSpecular + totalEmissiveRadiance;",`vec3 outgoingLight = totalDiffuse + totalSpecular + totalEmissiveRadiance;
124
124
 
125
125
  // diffuse-only lighting with overdrive to somewhat compensate
126
126
  // for the loss of indirect lighting and to make it more visible.
@@ -131,8 +131,8 @@ a=extmap-allow-mixed`)!==-1){var m=p.sdp.split(`
131
131
  // be blended onto the scene.
132
132
  gl_FragColor = vec4(direct, max);
133
133
  return;
134
- `)}}}applyShadowMaterial(){let e=S.getComponent(this.gameObject,Te);if(e)if(e.material?.type!=="ShadowMaterial"){let t=new dy;t.color=this.shadowColor,t.opacity=this.shadowColor.alpha,this.applyMaterialOptions(t),e.material=t}else{let t=e.material;t.color=this.shadowColor,t.opacity=this.shadowColor.alpha,this.applyMaterialOptions(t)}}applyMaterialOptions(e){e&&(e.depthWrite=!1,e.stencilWrite=!1)}};k([A()],Mn.prototype,"mode",2),k([A(we)],Mn.prototype,"shadowColor",2);import{RGBELoader as fy}from"three/examples/jsm/loaders/RGBELoader.js";import{EXRLoader as my}from"three/examples/jsm/loaders/EXRLoader";import{EquirectangularRefractionMapping as gy}from"three";var Hp=N("debugautosync"),ld=class{_syncers={};getOrCreateSyncer(e){if(!e.guid)return null;if(this._syncers[e.guid])return this._syncers[e.guid];let t=new cd(e);return this._syncers[e.guid]=t,t}},jp=new ld,cd=class{comp;constructor(e){this.comp=e}hasChanges=!1;changedProperties={};data={};_boundEvent;get networkingKey(){return this.comp.constructor.name}_isReceiving=!1;_isInit=!1;init(e){if(this._isInit)return;this._isInit=!0,this.comp=e,this._boundEvent=this.onHandleSending.bind(this),this.comp.context.post_render_callbacks.push(this._boundEvent),this.comp.context.connection.beginListen(this.networkingKey,this.onHandleReceiving.bind(this));let t=this.comp.context.connection.tryGetState(this.comp.guid);t&&this.onHandleReceiving(t)}notifyChanged(e,t){this._isReceiving||(this.hasChanges=!0,this.changedProperties[e]=t)}onHandleSending(){if(!this.hasChanges)return;this.hasChanges=!1;let e=this.comp.context.connection;if(!e||!e.isConnected){for(let t in this.changedProperties)delete this.changedProperties[t];return}for(let t in this.data)delete this.data[t];this.data.guid=this.comp.guid;for(let t in this.changedProperties){let i=this.changedProperties[t];delete this.changedProperties[t],this.data[t]=i}e.send(this.networkingKey,this.data)}onHandleReceiving(e){if(!this._isInit||!this.comp)return;let t=e.guid;if(!(t&&t!==this.comp.guid)){Hp&&console.log("RECEIVED",this.comp.name,this.comp.guid,e);try{this._isReceiving=!0;for(let i in e){if(i==="guid")continue;let n=e[i];this.comp[i]=n}}catch(i){console.error(i)}finally{this._isReceiving=!1}}}};function uy(l,e){let t=e!==l;if(!t&&l&&e){if(Array.isArray(l)&&Array.isArray(e))t=!0;else if(typeof l=="object"&&typeof e=="object"){for(let i of Object.keys(l))if(l[i]!==e[i]){t=!0;break}}}return t}function py(l){if(l.__autoPropertySyncHandler)return l.__autoPropertySyncHandler;let e=jp.getOrCreateSyncer(l);return e?.init(l),l.__autoPropertySyncHandler=e,e}var Va=function(l){return function(e,t){let i=null,n=l?e[l]:void 0,r=e,o=r.__internalAwake;Hp&&console.log(t);let s=t+"k__BackingField";r.__internalAwake=function(){if(this[s]!==void 0)return;this[s]=this[t],o.call(this),i=jp.getOrCreateSyncer(this),Object.getOwnPropertyDescriptor(this,t)?.set===void 0&&Object.defineProperty(this,t,{set:function(d){let a=this[s];this[s]=d,uy(d,a)&&n?.call(this,d,a)!==!1&&py(this)?.notifyChanged(t,d)},get:function(){return this[s]},configurable:!0,enumerable:!0}),i?.init(this)}}};var Ln=class extends M{url;allowDrop=!0;_loader;_prevLoadedEnvironment;_prevEnvironment=null;_prevBackground=null;onEnable(){this.setSkybox(this.url),this.registerDropEvents()}onDisable(){this.context.scene.environment===this._prevLoadedEnvironment&&(this.context.isInXR||(this.context.scene.environment=this._prevEnvironment,this.context.scene.background=this._prevBackground),this._prevLoadedEnvironment=void 0),this.unregisterDropEvents()}async setSkybox(e){if(!e)return;if(!e?.endsWith(".hdr")&&!e.endsWith(".exr")&&console.warn("Potentially invalid skybox url",this.url,"on",this.name),!this._loader){let n=e.endsWith(".exr");this._loader=n?new my:new fy}let t=await this._loader.loadAsync(e);if(!t||!this.enabled)return;this.url=e,t.mapping=gy,this._prevBackground=this.context.scene.background,this._prevEnvironment=this.context.scene.environment,console.log("Set skybox",this.url),this.context.scene.environment=t,this.context.scene.background=t,this._prevLoadedEnvironment=t;let i=e.lastIndexOf("/");t.name=e.substring(i>=0?i+1:0)}dragOverEvent;dropEvent;registerDropEvents(){this.dragOverEvent||(this.dragOverEvent=e=>{if(!!this.allowDrop&&!!e.dataTransfer)for(let t of e.dataTransfer.types)t==="text/uri-list"&&e.preventDefault()},this.dropEvent=e=>{if(!!this.allowDrop&&(e.preventDefault(),!!e.dataTransfer)){for(let t of e.dataTransfer.types)if(t==="text/uri-list"){let i=e.dataTransfer.getData(t);console.log(t,i);let n=new RegExp(/polyhaven.com\/asset_img\/.+?\/(?<name>.+)\.png/).exec(i)?.groups?.name;if(n||(n=new RegExp(/polyhaven\.com\/a\/(?<name>.+)/).exec(i)?.groups?.name),console.log(n),n){let r="https://dl.polyhaven.org/file/ph-assets/HDRIs/exr/1k/"+n+"_1k.exr";this.setSkybox(r)}else console.warn("Could not resolve skybox name from dropped url",i)}}},this.context.domElement.addEventListener("dragover",this.dragOverEvent),this.context.domElement.addEventListener("drop",this.dropEvent))}unregisterDropEvents(){!this.dragOverEvent||(this.context.domElement.removeEventListener("dragover",this.dragOverEvent),this.context.domElement.removeEventListener("drop",this.dropEvent))}};k([Va("setSkybox"),A()],Ln.prototype,"url",2),k([A()],Ln.prototype,"allowDrop",2);import*as wo from"three";import{Object3D as by}from"three";var dd=class extends M{target=null;followFactor=.1;rotateFactor=.1;flipForward=!1;_firstUpdate=!0;onEnable(){let e=S.getComponentInChildren(this.gameObject,ne);e&&e.cam&&(e.gameObject.position.set(0,0,0),e.cam.position.set(0,0,0),e.gameObject.quaternion.identity(),e.cam.quaternion.setFromEuler(new wo.Euler(0,Math.PI,0)))}onBeforeRender(){this.followFactor<=0||this.updateNow(!1)}updateNow(e){if(!(!this.target||this.target===this.gameObject)){if(this.followFactor>0){let t=q(this.target),i=this._firstUpdate||e?1:Q.clamp01(this.context.time.deltaTime*this.followFactor);this.worldPosition=this.worldPosition.lerp(t,i)}if(this.rotateFactor>0){let t=ve(this.target);this.flipForward&&t.premultiply(dd._invertForward);let i=this._firstUpdate||e?1:Q.clamp01(this.context.time.deltaTime*this.rotateFactor);this.worldQuaternion=this.worldQuaternion.slerp(t,i)}this._firstUpdate=!1}}},_i=dd;z(_i,"_invertForward",new wo.Quaternion().setFromAxisAngle(new wo.Vector3(0,1,0),Math.PI)),k([A(by)],_i.prototype,"target",2);import{Layers as Np}from"three";var Wa=N("debugspatialtrigger"),Bp=new Np,Fp=new Np;function vy(l,e){return Bp.mask=l,Fp.mask=e,Bp.test(Fp)}var wt=class extends M{triggerMask=0;onEnter;onStay;onExit;start(){Wa&&console.log(this.name,this.triggerMask,this)}update(){this.currentIntersected.length=0;for(let e of Zi.triggers)vy(e.triggerMask,this.triggerMask)&&e.test(this.gameObject)&&this.currentIntersected.push(e);for(let e=this.lastIntersected.length-1;e>=0;e--){let t=this.lastIntersected[e];this.currentIntersected.indexOf(t)<0&&(this.onExitTrigger(t),this.lastIntersected.splice(e,1))}for(let e of this.currentIntersected)this.lastIntersected.indexOf(e)<0&&this.onEnterTrigger(e),this.onStayTrigger(e);this.lastIntersected.length=0,this.lastIntersected.push(...this.currentIntersected)}currentIntersected=[];lastIntersected=[];onEnterTrigger(e){Wa&&console.log("ENTER TRIGGER",this.name,e.name,this,e),e.raiseOnEnterEvent(this),this.onEnter?.invoke(this,e)}onExitTrigger(e){Wa&&console.log("EXIT TRIGGER",this.name,e.name,this,e),e.raiseOnExitEvent(this),this.onExit?.invoke(this,e)}onStayTrigger(e){e.raiseOnStayEvent(this),this.onStay?.invoke(this,e)}};k([A()],wt.prototype,"triggerMask",2),k([A(Oe)],wt.prototype,"onEnter",2),k([A(Oe)],wt.prototype,"onStay",2),k([A(Oe)],wt.prototype,"onExit",2);var ys=class extends M{triggerMask;boxHelper;start(){Wa&&console.log(this.name,this.triggerMask,this)}onEnable(){ys.triggers.push(this),this.boxHelper||(this.boxHelper=S.addNewComponent(this.gameObject,lt),this.boxHelper?.showHelper())}onDisable(){ys.triggers.splice(ys.triggers.indexOf(this),1)}test(e){return this.boxHelper?this.boxHelper.isInBox(e)??!1:!1}raiseOnEnterEvent(e){S.foreachComponent(this.gameObject,t=>{t!==e&&t instanceof wt&&t.onEnterTrigger(this)},!1)}raiseOnStayEvent(e){S.foreachComponent(this.gameObject,t=>{t!==e&&t instanceof wt&&t.onStayTrigger(this)},!1)}raiseOnExitEvent(e){S.foreachComponent(this.gameObject,t=>{t!==e&&t instanceof wt&&t.onExitTrigger(this)},!1)}},Zi=ys;z(Zi,"triggers",[]),k([A()],Zi.prototype,"triggerMask",2);import*as Bt from"three";var _o=class extends M{cam=null;_firstPersonMode=!0;get firstPersonMode(){return this._firstPersonMode??!1}set firstPersonMode(e){this._firstPersonMode=e}enableFirstPersonMode(){this._firstPersonMode=!0,this.updateUI(),this.cam&&(this.firstPersonFollow&&(this.firstPersonFollow.enabled=!0,this.firstPersonFollow.updateNow(!0)),this.orbit&&(this.orbit.enabled=!1))}enableThirdPersonMode(){this._firstPersonMode=!1,this.updateUI(),this.firstPersonFollow&&(this.firstPersonFollow.enabled=!1),this.cam&&(ie(this.cam.cam,this._orbitStartPos),Ae(this.cam.cam,this._orbitStartRot),ie(this.cam.gameObject,this._orbitStartPos2),Ae(this.cam.gameObject,this._orbitStartRot2),this.orbit&&(this.orbit.enabled=!0,this.orbit.setFromTargetPosition()))}orbit=null;firstPersonFollow=null;spectatorUIDomElement=null;eventSub_WebXRRequestStartEvent=null;eventSub_WebXRStartEvent=null;eventSub_WebXREndEvent=null;awake(){if(S.setActive(this.gameObject,!1),!this.isSupportedPlatform()){console.log("Disable spectator cam",window.navigator.userAgent,this);return}if(this.cam=S.getComponent(this.gameObject,ne),!this.cam){console.error("Spectator camera needs camera component",this);return}let e="#spectator-camera-ui";this.spectatorUIDomElement=this.context.domElement.querySelector(e),this.spectatorUIDomElement||console.warn("Could not find spectator camera UI element",e),this.spectatorUIDomElement?.classList.add("hidden"),this.cam&&(this.cam.enabled=!0,this._orbitStartPos.copy(q(this.cam.cam)),this._orbitStartRot.copy(ve(this.cam.cam)),this._orbitStartPos2.copy(q(this.cam.gameObject)),this._orbitStartRot2.copy(ve(this.cam.gameObject))),this.eventSub_WebXRRequestStartEvent=this.onXRSessionRequestStart.bind(this),this.eventSub_WebXRStartEvent=this.onXRSessionStart.bind(this),this.eventSub_WebXREndEvent=this.onXRSessionEnded.bind(this),$.addEventListener("requestVRSession",this.eventSub_WebXRRequestStartEvent),$.addEventListener("xrStarted",this.eventSub_WebXRStartEvent),$.addEventListener("xrStopped",this.eventSub_WebXREndEvent),this.context.domElement.querySelector("button#toggle-spectator-view")?.addEventListener("click",this.toggleView.bind(this)),this.updateUI()}onDestroy(){$.removeEventListener("requestVRSession",this.eventSub_WebXRStartEvent),$.removeEventListener("xrStarted",this.eventSub_WebXRStartEvent),$.removeEventListener("xrStopped",this.eventSub_WebXREndEvent)}toggleView(){this.firstPersonMode=!this.firstPersonMode}updateUI(){let e=this.context.domElement.querySelector("button#toggle-spectator-view");if(!!e&&(e.disabled=!0,e.firstChild&&(this._sessionHasStarted?e.firstChild.textContent=this.firstPersonMode?"\u{1F441}\uFE0F":"\u{1F4F7}":e.firstChild.textContent="Waiting for VR session"),e.children?.length>1)){let t=e.children[1];t.style.display=this._sessionHasStarted?"block":"none",this.firstPersonMode?t.textContent="First-Person View. See what the person in VR sees":t.textContent="Third-Person View. Freely move the camera around"}}isSupportedPlatform(){let e=window.navigator.userAgent,t=/Windows|MacOS/.test(e),i=/Windows NT/.test(e)&&/Edg/.test(e)&&!/Win64/.test(e);return t&&!i}onXRSessionRequestStart(e){this._sessionHasStarted=!1,this.spectatorUIDomElement?.classList.remove("hidden"),S.setActive(this.gameObject,!0),this.cam&&this.cam.cam&&(ie(this.cam.cam,this._orbitStartPos),Ae(this.cam.cam,this._orbitStartRot),ie(this.cam.gameObject,this._orbitStartPos2),Ae(this.cam.gameObject,this._orbitStartRot2)),this.firstPersonMode?this.enableFirstPersonMode():this.enableThirdPersonMode()}onXRSessionStart(e){if(this._sessionHasStarted=!0,this.updateUI(),this.context.mainCamera){let t=this.context.renderer.xr.getCamera(this.context.mainCamera);this.setupFollowMode(t)}}onXRSessionEnded(e){this._sessionHasStarted=!1,this._firstPersonIsSetup=!1,this.spectatorUIDomElement?.classList.add("hidden"),S.setActive(this.gameObject,!1)}_sessionHasStarted=!1;_firstPersonIsSetup=!1;_orbitStartPos=new Bt.Vector3;_orbitStartRot=new Bt.Quaternion;_orbitStartPos2=new Bt.Vector3;_orbitStartRot2=new Bt.Quaternion;onAfterRender(){if(!this.cam)return;this.context.input.isKeyDown(83)&&(this.firstPersonMode=!this.firstPersonMode),this.updateFollowSettings();let e=this.context.renderer,t=e.xr.enabled;if(!e.xr.isPresenting)return;let i=e.getRenderTarget(),n=null;if(!i){if(!e.state.bindFramebuffer||!e.state.bindXRFramebuffer)return;n=e._framebuffer,e.state.bindXRFramebuffer(null)}this.setAvatarFlagsBeforeRender(),e.setClearColor(new Bt.Color(1,1,1)),e.setRenderTarget(null),e.xr.enabled=!1;let r=this.cam?.cam;this.context.updateAspect(r);let o=e.xr.isPresenting;e.xr.isPresenting=!1,e.setSize(this.context.domWidth,this.context.domHeight),e.render(this.context.scene,r),e.xr.isPresenting=o,e.xr.enabled=t,i?e.setRenderTarget(i):e.state.bindXRFramebuffer(n),this.resetAvatarFlags()}setupFollowMode(e){if(!e||!this.cam||this._firstPersonIsSetup)return;this._firstPersonIsSetup=!0,this.firstPersonFollow=S.addNewComponent(this.cam.gameObject,_i);let t=new Bt.Object3D;e.add(t),t.add(new Bt.AxesHelper(.2)),this.firstPersonFollow.target=t,this.updateFollowSettings();let i=this.context.mainCamera;i&&(this.cam.cam.near=i.near,this.cam.cam.far=i.far,this.cam.cam.updateProjectionMatrix()),this.orbit&&(this.orbit.enabled=!1)}updateFollowSettings(){let e=this.firstPersonFollow?.target;!e||!this.firstPersonFollow||(this.firstPersonMode===!1?(this.firstPersonFollow.followFactor=3,this.firstPersonFollow.rotateFactor=2,this.firstPersonFollow.flipForward=!1,e.position.set(0,.5,1.5),e.quaternion.identity()):(e.position.set(0,0,0),e.quaternion.identity(),this.firstPersonFollow.followFactor=12,this.firstPersonFollow.rotateFactor=5,this.firstPersonFollow.flipForward=!1))}setAvatarFlagsBeforeRender(){for(let e of pe.instances)if(e.avatar&&"isLocalAvatar"in e.avatar){let t=this.firstPersonMode&&this._firstPersonIsSetup&&e.avatar.isLocalAvatar?8:16,i=e.avatar.flags;if(!i)continue;for(let n of i)n.UpdateVisible(t)}}resetAvatarFlags(){for(let e of pe.instances)if(e.avatar&&"flags"in e.avatar){let t=e.avatar.flags;if(!t)continue;for(let i of t)e.avatar?.isLocalAvatar?i.UpdateVisible(8):i.UpdateVisible(16)}}};var xo=class extends M{anchor=null;connectedBody=null;connectedAnchor=null;spring=10;damper=.2;rb=null;awake(){if(this.rb=S.getComponent(this.gameObject,ce),!this.connectedBody||!this.connectedBody.body||!this.rb||!this.rb.body)return;this.connectedBody.body.mass=Math.min(this.rb.body.mass*.99,this.connectedBody.body.mass);let e=new ta(this.rb.body,this.connectedBody.body,{restLength:.01,stiffness:this.spring*.5,damping:this.damper});this.context.physics.addPostStepListener(t=>{e.applyForce()})}update(){}};import*as _t from"three";import{Material as yy,Texture as Ey}from"three";var br=class{texture;triangles;uv;vertices;_geometry};k([A(Ey)],br.prototype,"texture",2);var Ua=class{static getOrCreateGeometry(e){if(e._geometry)return e._geometry;let t=new _t.BufferGeometry;e._geometry=t;let i=new Float32Array(e.triangles.length*3),n=new Float32Array(e.triangles.length*2);for(let r=0;r<e.triangles.length;r+=1){let o=e.triangles[r];i[r*3]=-e.vertices[o].x,i[r*3+1]=e.vertices[o].y,i[r*3+2]=0;let s=e.uv[o];n[r*2]=s.x,n[r*2+1]=1-s.y}return t.setAttribute("position",new _t.BufferAttribute(i,3)),t.setAttribute("uv",new _t.BufferAttribute(n,2)),t}},Ji=class extends M{drawMode=0;size={x:1,y:1};color;sharedMaterial;get sprite(){return this._sprite}set sprite(e){e!==this._sprite&&(this._sprite=e,this.updateSprite())}_sprite;_currentSprite;awake(){this._currentSprite=void 0}start(){this.drawMode===2&&console.warn("Tiled draw mode is not supported yet",this),this._currentSprite?this.gameObject&&this.gameObject.add(this._currentSprite):this.updateSprite()}updateSprite(){if(!!this.__didAwake&&!!this.sprite&&!!this.sharedMaterial){if(this._currentSprite)this._currentSprite.geometry=Ua.getOrCreateGeometry(this.sprite),this._currentSprite.material.map=this.sprite.texture;else{let e=new _t.MeshBasicMaterial({color:16777215,side:_t.DoubleSide});if(!e)return;if(this.color&&(e.color||(e.color=new _t.Color),e.color.copy(this.color),e.opacity=this.color.alpha),e.alphaTest=.5,this.sprite.texture&&!e.wireframe){let t=this.sprite.texture;e.map=t}this._currentSprite=new _t.Mesh(Ua.getOrCreateGeometry(this.sprite),e)}this._currentSprite.parent!==this.gameObject&&(this.drawMode===2&&this._currentSprite.scale.set(this.size.x,this.size.y,1),this.gameObject&&this.gameObject.add(this._currentSprite))}}};k([A()],Ji.prototype,"drawMode",2),k([A(we)],Ji.prototype,"color",2),k([A(yy)],Ji.prototype,"sharedMaterial",2);var xt=class{bb=null;bb_pos=0;__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsSyncedCameraModel(e,t){return(t||new xt).__init(e.readInt32(e.position())+e.position(),e)}static getSizePrefixedRootAsSyncedCameraModel(e,t){return e.setPosition(e.position()+4),(t||new xt).__init(e.readInt32(e.position())+e.position(),e)}userId(e){let t=this.bb.__offset(this.bb_pos,4);return t?this.bb.__string(this.bb_pos+t,e):null}guid(e){let t=this.bb.__offset(this.bb_pos,6);return t?this.bb.__string(this.bb_pos+t,e):null}dontSave(){let e=this.bb.__offset(this.bb_pos,8);return e?!!this.bb.readInt8(this.bb_pos+e):!1}pos(e){let t=this.bb.__offset(this.bb_pos,10);return t?(e||new Ce).__init(this.bb_pos+t,this.bb):null}rot(e){let t=this.bb.__offset(this.bb_pos,12);return t?(e||new Ce).__init(this.bb_pos+t,this.bb):null}static startSyncedCameraModel(e){e.startObject(5)}static addUserId(e,t){e.addFieldOffset(0,t,0)}static addGuid(e,t){e.addFieldOffset(1,t,0)}static addDontSave(e,t){e.addFieldInt8(2,+t,0)}static addPos(e,t){e.addFieldStruct(3,t,0)}static addRot(e,t){e.addFieldStruct(4,t,0)}static endSyncedCameraModel(e){return e.endObject()}static finishSyncedCameraModelBuffer(e,t){e.finish(t)}static finishSizePrefixedSyncedCameraModelBuffer(e,t){e.finish(t,void 0,!0)}};import{Object3D as wy}from"three";var qa="SCAM";Vr(qa,xt.getRootAsSyncedCameraModel);var Tt=new ft,hd=class{userId;guid;constructor(e,t){this.guid=t,this.userId=e}send(e,t){let i=e.cam?.cam;if(i){Tt.clear();let n=Tt.createString(this.guid),r=Tt.createString(this.userId);xt.startSyncedCameraModel(Tt),xt.addGuid(Tt,n),xt.addUserId(Tt,r);let o=q(i),s=Bs(i);xt.addPos(Tt,Ce.createVec3(Tt,o.x,o.y,o.z)),xt.addRot(Tt,Ce.createVec3(Tt,s.x,s.y,s.z));let c=xt.endSyncedCameraModel(Tt);Tt.finish(c,qa),t.sendBinary(Tt.asUint8Array())}}},Dn=class extends M{getUserCamera(e){let t=this.userToCamMap[e];return t?this.remoteCams[t].obj:null}cam=null;cameraPrefab=null;_lastWorldPosition;_lastWorldQuaternion;_model=null;_needsUpdate=!0;_lastUpdateTime=0;remoteCams={};userToCamMap={};_camTimeoutInSeconds=10;_receiveCallback=null;async awake(){this._lastWorldPosition=this.worldPosition.clone(),this._lastWorldQuaternion=this.worldQuaternion.clone(),this.cameraPrefab&&("uri"in this.cameraPrefab&&(this.cameraPrefab=await this.cameraPrefab.instantiate(this.gameObject)),this.cameraPrefab&&"isObject3D"in this.cameraPrefab&&(this.cameraPrefab.visible=!1))}start(){this.cam||(console.warn("Missing camera, fallback to main camera",this),this.cam=this.context.mainCameraComponent??null)}onEnable(){this._receiveCallback=this.context.connection.beginListenBinrary(qa,this.onReceivedRemoteCameraInfoBin.bind(this))}onDisable(){this.context.connection.stopListenBinary(qa,this._receiveCallback)}update(){for(let i in this.remoteCams){let n=this.remoteCams[i],r=this.context.time.realtimeSinceStartup-n.lastUpdate;if(!n||r>this._camTimeoutInSeconds){console.log("Remote cam timeout",n,r),n?.obj&&S.destroy(n.obj),delete this.remoteCams[i],n&&delete this.userToCamMap[n.userId];continue}}if($.IsInWebXR)return;if(this.cam===null){this.enabled=!1;return}if(!this.context.connection.isConnected||this.context.connection.connectionId===null)return;this._model===null&&(this._model=new hd(this.context.connection.connectionId,this.context.connection.connectionId+"_camera"));let e=q(this.cam.cam),t=ve(this.cam.cam);(e.distanceTo(this._lastWorldPosition)>.001||t.angleTo(this._lastWorldQuaternion)>.01)&&(this._needsUpdate=!0),this._lastWorldPosition.copy(e),this._lastWorldQuaternion.copy(t),!((!this._needsUpdate||this.context.time.frameCount%2!==0)&&!(this.context.time.realtimeSinceStartup-this._lastUpdateTime>this._camTimeoutInSeconds*.5))&&(this._lastUpdateTime=this.context.time.realtimeSinceStartup,this._needsUpdate=!1,this._model.send(this,this.context.connection))}onReceivedRemoteCameraInfoBin(e){let t=e.guid();if(!t)return;let i=e.userId();if(!i||!this.context.connection.userIsInRoom(i)||!this.cameraPrefab)return;let n=this.remoteCams[t];if(!n)if("isObject3D"in this.cameraPrefab){let c=new ye;c.context=this.context;let d=S.instantiate(this.cameraPrefab,c);n=this.remoteCams[t]={obj:d,lastUpdate:this.context.time.realtimeSinceStartup,userId:i},n.obj.visible=!0,this.gameObject.add(d),this.userToCamMap[i]=t;let a=S.getOrAddComponent(d,pe);a.connectionId=i,a.avatar=d}else return;let r=n.obj;n.lastUpdate=this.context.time.realtimeSinceStartup,he.markDirty(r);let o=e.pos();o&&Mr(r,o.x(),o.y(),o.z());let s=e.rot();s&&Fs(r,s.x(),s.y(),s.z())}};k([A(ne)],Dn.prototype,"cam",2),k([A([wy,tt])],Dn.prototype,"cameraPrefab",2);var ud="view",zp=N("debugsyncedroom"),ti=class extends M{roomName;urlParameterName;joinRandomRoom=!0;requireRoomParameter=!1;autoRejoin=!0;_roomPrefix;awake(){this._roomPrefix===void 0&&(this._roomPrefix=this.roomName,this.roomName="")}onEnable(){let e=N(ud);if(e&&typeof e=="string"&&e.length>0){console.log("Join as viewer"),this.context.connection.joinRoom(e,!0);return}this.tryJoinRoom()}onDisable(){this.roomName&&this.roomName.length>0&&this.context.connection.leaveRoom(this.roomName)}tryJoinRoom(e=0){let t=!1;if(this.urlParameterName){let i=N(this.urlParameterName);if(i&&typeof i=="string"){t=!0;let n=dh(i);this.roomName=n}else if(this.joinRandomRoom&&(console.log("No room name found in url, generating random one"),this.setRandomRoomUrlParameter(),e<1))return this.tryJoinRoom(e+1)}else this.joinRandomRoom&&(this.roomName===null||this.roomName===void 0||this.roomName.length<=0)&&(console.log("generate room name"),this.roomName=this.generateRoomName());return this.requireRoomParameter&&!t?(zp&&console.log('No required room parameter "'+this.urlParameterName+'" in url - will not connect to networking backend.'),!1):!this.roomName||this.roomName.length<=0?(zp&&console.error('Missing room name on "'+this.name+'". Make sure this is correctly configured in Unity',this.context.connection.isDebugEnabled?this:""),!1):(this.context.connection.isConnected||this.context.connection.connect(),this._roomPrefix&&(this.roomName=this._roomPrefix+this.roomName),this.context.connection.joinRoom(this.roomName),!0)}_lastPingTime=0;_lastRoomTime=-1;update(){this.context.connection.isConnected&&(this.context.time.time-this._lastPingTime>3&&(this._lastPingTime=this.context.time.time,this.context.connection.send("ping",{time:this.context.time.time})),this.context.connection.isInRoom&&(this._lastRoomTime=this.context.time.time)),this._lastRoomTime>0&&this.context.time.time-this._lastRoomTime>.3&&(this._lastRoomTime=-1,this.autoRejoin?(console.log("Disconnected from networking backend - attempt reconnecting now"),this.tryJoinRoom()):console.warn("You are not connected to a room anymore (possibly because the tab was inactive for too long and the server kicked you)"))}get currentRoomName(){let e=N(ud);return e||N(this.urlParameterName)}setRandomRoomUrlParameter(){let e=_l(),t=this.generateRoomName();N(this.urlParameterName)?e.set(this.urlParameterName,t):e.append(this.urlParameterName,t),ah(t,e)}generateRoomName(){return ch()+"_"+lh(100,999)}getViewOnlyUrl(){if(this.context.connection.isConnected&&this.context.connection.currentRoomViewId){let e=window.location.search,t=new URLSearchParams(e);return t.has(this.urlParameterName)&&t.delete(this.urlParameterName),t.set(ud,this.context.connection.currentRoomViewId),window.location.origin+window.location.pathname+"?"+t.toString()}return null}};k([A()],ti.prototype,"roomName",2),k([A()],ti.prototype,"urlParameterName",2),k([A()],ti.prototype,"joinRandomRoom",2),k([A()],ti.prototype,"requireRoomParameter",2),k([A()],ti.prototype,"autoRejoin",2);function Gp(){let l=N("testwindowcount")||0;l&&l>0&&_y(l)}function _y(l){if(N("testwindow"))return null;let e=new URL(window.location.href);Ir(e.searchParams,ro,1),Ir(e.searchParams,"testwindow",1);let t=e.toString(),i=[];window.onbeforeunload=()=>{for(let c of i)c.close()};let n=.05,r=128,o=0,s=0;for(let c=0;c<l;c++){o*r+r*.01>=window.innerWidth&&(s+=1,o=0);let d=o*(r*(1+n))+window.screenLeft,a=s*(r*(1+n))+window.screenTop+90+60*s;o+=1;let h=window.open(t,"test window "+c,`popup=yes width=${r} height=${r} top=${a} left=${d}`);if(!h){console.warn("Failed to open window");continue}i.push(h),h.onload=()=>{h.onbeforeunload=()=>{for(let u=0;u<i.length;u++){let f=i[u];f!==h&&f.close()}i.length=0}}}return i}import{Vector3 as Ty}from"three";var To=class extends M{awake(){Gp()}},Ro=class extends M{transformsPerFrame=10;interval=0;useFlatbuffers=!0;awake(){if(this.useFlatbuffers)this.context.connection.beginListenBinrary(io,e=>{});else{this.models=[];for(let e=0;e<this.transformsPerFrame;e++)this.models.push(new Xa(this.context.connection.connectionId+"_simulatedTransform_"+e,this))}}builder=null;models=null;update(){if(!!this.context.connection.isConnected){if(this.useFlatbuffers){if(!this.context.connection.connectionId||this.context.time.frameCount%this.interval!==0)return;this.builder===null&&(this.builder=new ft(1024));let e=this.builder;for(let t=0;t<this.transformsPerFrame;t++){e.clear();let i=Nc(this.context.connection.connectionId,this);this.context.connection.sendBinary(i)}}else if(this.models)for(let e=0;e<this.models.length;e++){let t=this.models[e];t.dontSave=!0,t.update(this,null),this.context.connection.send("TestSimulateUserData-"+e,t)}}}},Xa=class{guid;fast=!1;position;rotation;velocity=void 0;dontSave;isValid(){return this.fast!==void 0||this.position!==void 0||this.rotation!==void 0||this.velocity!==void 0}constructor(e,t){this.guid=e,this.position={x:0,y:0,z:0},this.rotation={x:0,y:0,z:0,w:0},this.update(t,null)}update(e,t){let i=e.worldPosition;this.position.x=i.x,this.position.y=i.y,this.position.z=i.z;let n=e.worldQuaternion;if(this.rotation.x=n.x,this.rotation.y=n.y,this.rotation.z=n.z,this.rotation.w=n.w,this.fast=!1,t){let r=t.getVelocity();this.velocity===void 0&&(this.velocity={x:0,y:0,z:0}),this.velocity.x=r.x,this.velocity.y=r.y,this.velocity.z=r.z}}};z(Xa,"temp",new Ty);import{MathUtils as Ry}from"three";import{TransformControls as Cy}from"three/examples/jsm/controls/TransformControls";import{OrbitControls as Sy}from"three/examples/jsm/controls/OrbitControls";var vr=class extends M{isGizmo=!0;control;orbit;awake(){this.isGizmo&&!hi||!this.context.mainCamera||(this.control=new Cy(this.context.mainCamera,this.context.renderer.domElement),this.control.visible=!0,this.control.enabled=!0,this.control.getRaycaster().layers.set(2),this.control.size=.6,this.control.traverse(e=>{let t=e;if(t.layers.set(2),t){let i=t.material;i&&(i.opacity=.3)}}))}start(){if(this.context.mainCamera){let e=S.getComponentInParent(this.context.mainCamera,Sy)??void 0;this.orbit=e}}changeEventListener;windowKeyDownListener;windowKeyUpListener;onEnable(){this.control&&(this.context.scene.add(this.control),this.control.attach(this.gameObject)),this.changeEventListener=this.onControlChangedEvent.bind(this),this.control?.addEventListener("dragging-changed",this.changeEventListener),this.attachWindowEvents()}onDisable(){this.control?.removeFromParent(),this.changeEventListener&&this.control?.removeEventListener("dragging-changed",this.changeEventListener)}onControlChangedEvent(e){let t=this.orbit;if(t&&(t.enabled=!e.value),e.value){let i=S.getComponentInParent(this.gameObject,Qe);i&&i.requestOwnership()}}attachWindowEvents(){let e=this.control;!e||(this.windowKeyDownListener||(this.windowKeyDownListener=t=>{switch(t.keyCode){case 81:e.setSpace(e.space==="local"?"world":"local");break;case 16:e.setTranslationSnap(100),e.setRotationSnap(Ry.degToRad(15)),e.setScaleSnap(.25);break;case 87:e.setMode("translate");break;case 69:e.setMode("rotate");break;case 82:e.setMode("scale");break;case 187:case 107:e.setSize(e.size+.1);break;case 189:case 109:e.setSize(Math.max(e.size-.1,.1));break;case 88:e.showX=!e.showX;break;case 89:e.showY=!e.showY;break;case 90:e.showZ=!e.showZ;break;case 32:e.enabled=!e.enabled;break}}),this.windowKeyUpListener||(this.windowKeyUpListener=t=>{switch(t.keyCode){case 16:e.setTranslationSnap(null),e.setRotationSnap(null),e.setScaleSnap(null);break}}),window.addEventListener("keydown",this.windowKeyDownListener),window.addEventListener("keyup",this.windowKeyUpListener))}};k([A()],vr.prototype,"isGizmo",2);import{LinearToneMapping as Vp,ACESFilmicToneMapping as Py,ReinhardToneMapping as Oy}from"three";var Co=class{overrideState=!1;value=0},xi=class{active=!1;parameters},jn=class extends xi{mode;get isToneMapping(){return!0}},Bn=class extends xi{postExposure};function Ay(l){return"mode"in l?jn:"postExposure"in l?Bn:xi}var Hn=class{components;apply(e){if(!!this.components){for(let t of this.components)if(t instanceof jn){let i=t;if(!t.active){e.renderer.toneMapping=Vp;continue}switch(i.mode?.value??0){case 0:e.renderer.toneMapping=Vp;break;case 1:e.renderer.toneMapping=Oy;break;case 2:e.renderer.toneMapping=Py;break}}else if(t instanceof Bn){let i=t;console.log(i.postExposure);let n=Math.pow(2,i.postExposure?.value??0);e.renderer.toneMappingExposure=i.postExposure?.overrideState?n:1}}}};k([A([l=>Ay(l),xi])],Hn.prototype,"components",2);var yr=class extends M{sharedProfile;onEnable(){this.sharedProfile?.apply(this.context)}};k([A(Hn)],yr.prototype,"sharedProfile",2);import*as Wp from"three";var Er=class{guid;dontSave=!0;userId;point={x:0,y:0,z:0};source={x:0,y:0,z:0};target;update(e,t,i,n=void 0){this.userId=e.connection.connectionId,this.point.x=t.x,this.point.y=t.y,this.point.z=t.z,this.source.x=i.x,this.source.y=i.y,this.source.z=i.z,this.target=n}},So=class extends M{prefab=null;_grabModels=[];_grabModelsUpdateTime=[];_addOrUpdateSub=null;_endSub=null;_freeSub=null;_instances={};awake(){this.prefab&&(this.prefab.visible=!1)}onEnable(){this._addOrUpdateSub=this.context.connection.beginListen("xr-grab-visual-start-or-update",this.onRemoteGrabStartOrUpdate.bind(this)),this._endSub=this.context.connection.beginListen("xr-grab-visual-end",this.onRemoteGrabEnd.bind(this)),this._freeSub=dt.AddEventListener("WillFree",this.onAttachedObjectFree.bind(this))}onDisable(){this.context.connection.stopListening("xr-grab-visual-start-or-update",this._addOrUpdateSub),this.context.connection.stopListening("xr-grab-visual-end",this._endSub),dt.RemoveEventListener("WillFree",this._freeSub)}addOrUpdateGrab(e){this.context.connection.send("xr-grab-visual-start-or-update",e,2)}endGrab(e){this.context.connection.send("xr-grab-visual-end",e,2)}onRemoteGrabStartOrUpdate(e){if(!this.prefab)return;let t=this._instances[e.guid];if(!t){let i=S.instantiate(this.prefab);if(i.visible=!0,this._instances[e.guid]={instance:i,model:e},e.userId){let n=S.getComponentsInChildren(i,ht);if(n?.length>0)for(let r of n)r.assignUserColor(e.userId)}return}t.model=e}onRemoteGrabEnd(e){if(!e)return;let t=e.guid;this._instances[t]&&(S.destroy(this._instances[t].instance),delete this._instances[t])}onAttachedObjectFree(e){if(this._grabModels.length<=0)return;let t=this._grabModels[0];this.updateModel(t,e),this.endGrab(t)}onBeforeRender(){if(this.updateRendering(),!!this.prefab&&(this.prefab.visible=!1,this.context.time.frameCount%10===0))for(let e=0;e<dt.Current.length;e++){let t=dt.Current[e];if(!t.controller||!t.selected)continue;this._grabModels.length<=e&&(this._grabModels.push(new Er),this._grabModelsUpdateTime.push(0)),this._grabModelsUpdateTime[e]=this.context.time.time;let i=this._grabModels[e];this.updateModel(i,t),this.addOrUpdateGrab(i)}}updateModel(e,t){if(!t.controller||!t.selected)return;e.guid=t.grabUUID;let i=t.selected.guid;e.update(this.context,t.grabPoint,t.controller.worldPosition,i)}temp=new Wp.Vector3;updateRendering(){let e=this.context.time.deltaTime/.5;for(let t in this._instances){let{instance:i,model:n}=this._instances[t];if(!i||!n)continue;let{point:r}=n,o=q(i);this.temp.set(r.x,r.y,r.z),o.lerp(this.temp,e),ie(i,o)}}};import{Object3D as ky}from"three";var Ti=class extends M{eyes=[];lastBlinkTime=0;blinkLength=0;eyesOpen=!0;state=null;awake(){this.state=S.getComponentInParent(this.gameObject,Se)}update(){if(!this.gameObject||!this.gameObject.visible||!this.eyes||!Array.isArray(this.eyes)||this.eyes.length===0)return;if(this.context.time.time-this.lastBlinkTime>this.blinkLength){if(this.lastBlinkTime=this.context.time.time,this.state&&!this.state.isOn||!this.activeAndEnabled)return;if(this.eyesOpen=!this.eyesOpen,this.blinkLength=Math.random(),this.eyesOpen?(this.blinkLength*=3,this.blinkLength+=.5,Math.random()<.1&&(this.blinkLength=.1+Math.random()*.2)):(this.blinkLength*=Math.random()*.2,this.blinkLength+=.1),Math.random()<.1&&(this.blinkLength*=3),this.blinkLength=Math.max(.2,this.blinkLength),this.blinkLength=Math.min(3,this.blinkLength),this.eyes)for(let t of this.eyes)t&&(t.visible=this.eyesOpen)}}};k([A(ky)],Ti.prototype,"eyes",2),k([A()],Ti.prototype,"lastBlinkTime",2),k([A()],Ti.prototype,"blinkLength",2),k([A()],Ti.prototype,"eyesOpen",2);import*as Qa from"three";import{Object3D as pd}from"three";var fd=class extends M{head=null;eyes=null;target=null;brain=null;awake(){this.brain||(this.brain=S.getComponentInParent(this.gameObject,Ui)),this.brain||(console.log("No look at brain found, adding it now"),this.brain=S.addNewComponent(this.gameObject,Ui)),this.brain&&this.target&&(this.brain.controlledTarget=this.target)}vec=new Qa.Vector3;currentTargetPoint=new Qa.Vector3;update(){let e=this.target;if(e&&this.head){let t=this.eyes;if(t){let i=q(e);this.currentTargetPoint.lerp(i,this.context.time.deltaTime/.1);let n=q(this.head),r=this.vec.copy(this.currentTargetPoint).sub(n).normalize();if(r.length()<.1)return;let o=fd.forward;if(o.set(0,0,1),o.applyQuaternion(ve(this.head)),o.dot(r)>.45)for(let c=0;c<t.length;c++)t[c].lookAt(this.currentTargetPoint)}}}},Ri=fd;z(Ri,"forward",new Qa.Vector3(0,0,1)),k([A(pd)],Ri.prototype,"head",2),k([A(pd)],Ri.prototype,"eyes",2),k([A(pd)],Ri.prototype,"target",2);import{Object3D as Up}from"three";var Iy=N("debugmouth"),Fn=class extends M{idle=[];talking=[];marker=null;voip=null;lastMouthChangeTime=0;mouthChangeLength=0;awake(){setTimeout(()=>{this.voip=S.findObjectOfType(Ke,this.context),this.marker||(this.marker=S.getComponentInParent(this.gameObject,pe))},3e3)}update(){if(!this.voip||this.context.time.frameCount%10!==0)return;let e=this.marker?.connectionId??null;if(!e){Iy&&(e=null);return}let t=this.voip.getFrequency(e)??0;this.updateLips(t)}updateLips(e){if(this.context.time.time-this.lastMouthChangeTime>this.mouthChangeLength){if(this.mouthChangeLength=.05+Math.random()*.1,this.talking&&this.talking.length>0&&e>30){this.lastMouthChangeTime=this.context.time.time;let t=Math.floor(Math.random()*this.talking.length);this.setMouthShapeActive(this.talking,t)}else if(this.idle.length>0&&this.context.time.time-this.lastMouthChangeTime>.5){this.lastMouthChangeTime=this.context.time.time;let t=Math.floor(Math.random()*this.idle.length);this.setMouthShapeActive(this.idle,t)}}}setMouthShapeActive(e,t){if(!!e){e!=this.idle?this.idle.map(i=>i.visible=!1):this.talking.map(i=>i.visible=!1);for(let i=0;i<e.length;i++){let n=e[i];n&&(n.visible=i===t)}}}};k([A(Up)],Fn.prototype,"idle",2),k([A(Up)],Fn.prototype,"talking",2);var Po=class extends M{voip=null;marker=null;_startPosition=null;awake(){this.voip=S.findObjectOfType(Ke,this.context),this.marker=S.getComponentInParent(this.gameObject,pe)}update(){if(!this.voip||!this.marker||this.context.time.frameCount%10!==0)return;let e=this.marker.connectionId,t=this.voip.getFrequency(e);if(t==null)return;this._startPosition||(this._startPosition=this.gameObject.position.clone());let i=t/100;this.gameObject.position.y=this._startPosition.y+i*.07}};var My=N("logstats"),Oo=class extends M{onEnable(){console.log(this),My&&this.startCoroutine(this.run(),4)}*run(){for(;this.enabled;){let e=this.context.renderer.info;console.log(e.memory,e.render,e.programs),yield}}};import*as Qp from"three";var wr=class{guid},_r=class{signal;reaction;$serializedTypes={signal:wr,reaction:Oe}},$i=class extends M{events;start(){console.log(this)}invoke(e){if(!this.events||!Array.isArray(this.events))return;let t=typeof e=="object"?e.guid:e;for(let i of this.events)if(i.signal.guid===t)try{if(i.reaction){if(!i.reaction.invoke){console.warn("Missing invoke - possibly a serialization error",i,this);continue}}else{console.warn("Missing reaction for signal",i,this);continue}i.reaction.invoke()}catch(n){console.error(n)}}};k([A(_r)],$i.prototype,"events",2);import*as re from"three";import{Quaternion as Ly,Vector3 as Dy}from"three";var Ao=N("debugtimeline"),ko=class{director;track;get muted(){return this.track.muted}set muted(e){e!==this.track.muted&&(this.track.muted=e,this.onMuteChanged?.call(this))}*forEachClip(e=!1){if(!!this.track?.clips)if(e)for(let t=this.track.clips.length-1;t>=0;t--)yield this.track.clips[t];else for(let t of this.track.clips)yield t}getClipTime(e,t){return t.clipIn+(e-t.start)*t.timeScale}getClipTimeNormalized(e,t){return(e-t.start)/t.duration}evaluateWeight(e,t,i,n=!0){if(t<0||t>=i.length)return 0;let r=i[t];if(n||e>=r.start&&e<=r.end){let o=1,s=!1;return r.easeInDuration>0&&(o*=Math.min((e-r.start)/r.easeInDuration,1)),r.easeOutDuration>0&&!s&&(o*=Math.min((r.end-e)/r.easeOutDuration,1)),o}return 0}},md=class{clip;rootPositionOffset;rootQuaternionOffset;get hasOffsets(){return this.rootPositionOffset!==void 0||this.rootQuaternionOffset!==void 0}rootStartPosition;rootEndPosition;rootStartQuaternion;rootEndQuaternion;constructor(e){let t=e.getClip();this.clip=t;let i=e.getRoot(),n=i.name+".position",r=i.name+".quaternion";Ao&&console.log(t.name,t.tracks,n);for(let o of t.tracks)if(!(o.times.length<=0)){if(o.name.endsWith(n))this.rootStartPosition=new re.Vector3().fromArray(o.values,0),this.rootEndPosition=new re.Vector3().fromArray(o.values,o.values.length-3),this.rootPositionOffset=this.rootEndPosition.clone().sub(this.rootStartPosition),Ao&&console.log(this.rootPositionOffset);else if(o.name.endsWith(r)&&(this.rootStartQuaternion=new re.Quaternion().fromArray(o.values,0),this.rootEndQuaternion=new re.Quaternion().fromArray(o.values,o.values.length-4),this.rootQuaternionOffset=this.rootEndQuaternion.clone().multiply(this.rootStartQuaternion),Ao)){let s=new re.Euler().setFromQuaternion(this.rootQuaternionOffset);console.log("ROT",s)}}}},Nn=class extends ko{models=[];trackOffset;target;mixer;clips=[];actions=[];_actionOffsets=[];_didBind=!1;createHooks(e,t){if(t.tracks?.length<=0){console.warn("No tracks in AnimationClip",t);return}let i=t.tracks[0].name.split("."),n=i[i.length-2],r=n+".position",o=n+".quaternion",s=!1,c=!1;for(let d of t.tracks)d.name.endsWith(r)?(s=!0,this.createPositionInterpolant(t,e,d)):d.name.endsWith(o)&&(c=!0,this.createRotationInterpolant(t,e,d));if(!s||!c){let d=this.mixer?.getRoot(),a=t.tracks[0],h=a.name.lastIndexOf("."),u=a.name.substring(0,h),f=u.substring(u.lastIndexOf(".")+1),E=d.getObjectByName(f);if(E)if(s){if(!c){let b=t.tracks[0].name.substring(0,h)+".quaternion";Ao&&console.warn("Create quaternion track",f,E);let y=E.quaternion,g=new re.QuaternionKeyframeTrack(b,[0,t.duration],[y.x,y.y,y.z,y.w,y.x,y.y,y.z,y.w]);t.tracks.push(g),this.createRotationInterpolant(t,e,g)}}else{let b=u+".position";Ao&&console.warn("Create position track",f,E);let y=E.position,g=new re.VectorKeyframeTrack(b,[0,t.duration],[y.x,y.y,y.z,y.x,y.y,y.z]);t.tracks.push(g),this.createPositionInterpolant(t,e,g)}}}bind(){if(!this._didBind){this._didBind=!0,Ao&&console.log(this.models),this.mixer?this.target=this.mixer.getRoot():console.warn("No mixer was assigned to animation track");for(let e of this.actions){let t=new md(e);this._actionOffsets.push(t)}for(let e of this.models){let t=e.asset,i=t.position,n=t.rotation;i.x!==void 0&&(i.isVector3||(t.position=new Dy(i.x,i.y,i.z)),n.isQuaternion||(t.rotation=new Ly(n.x,n.y,n.z,n.w)))}this.ensureTrackOffsets()}}ensureTrackOffsets(){if(this.trackOffset){let e=this.trackOffset.position;e&&(e.isVector3||(this.trackOffset.position=new re.Vector3(e.x,e.y,e.z)));let t=this.trackOffset.rotation;t&&(t.isQuaternion||(this.trackOffset.rotation=new re.Quaternion(t.x,t.y,t.z,t.w)))}}_useclipOffsets=!0;_totalOffsetPosition=new re.Vector3;_totalOffsetRotation=new re.Quaternion;_totalOffsetPosition2=new re.Vector3;_totalOffsetRotation2=new re.Quaternion;_summedPos=new re.Vector3;_tempPos=new re.Vector3;_summedRot=new re.Quaternion;_tempRot=new re.Quaternion;evaluate(e){if(this.track.muted||!this.mixer)return;this.bind(),this._totalOffsetPosition.set(0,0,0),this._totalOffsetRotation.set(0,0,0,1),this._totalOffsetPosition2.set(0,0,0),this._totalOffsetRotation2.set(0,0,0,1);let t=0,i=0,n=!1;for(let r=0;r<this.clips.length;r++){let o=this.models[r],s=this.actions[r],c=o.asset;s.weight=0;let d=e>=o.start&&e<=o.end,a=o.postExtrapolationMode,h=d;if(!h&&!n&&o.end<e&&o.postExtrapolationMode!==0){let u=r<this.clips.length-1?this.models[r+1]:null;(!u||u.start>e)&&(h=!0,n=!0)}if(h){let u=1;u*=this.evaluateWeight(e,r,this.models,h);let f=this.getClipTime(e,o),E=0,b=c.duration;if(d){if(c.loop)for(E+=Math.floor(f/(b+1e-6));f>b;)f-=b}else if(!d)switch(a){case 2:f%=b;break;case 3:let p=Math.floor(f/b)%2!==0;f%=b,p&&(f=b-f);break}s.time=f,s.timeScale=0;let y=u*this.director.weight;if(s.weight=y,s.clampWhenFinished=!0,s.isRunning()||s.play(),this._useclipOffsets){let g=t==0?this._totalOffsetPosition:this._totalOffsetPosition2,p=t==0?this._totalOffsetRotation:this._totalOffsetRotation2;t<1&&(i=1-u),t+=1;let m=this._summedPos.set(0,0,0),v=this._tempPos.set(0,0,0),w=this._summedRot.identity(),x=this._tempRot.identity(),T=c.rotation,R=new re.Quaternion;R.slerp(T,u);let C=this._actionOffsets[r];if(C.hasOffsets)for(let O=0;O<E;O++)C.rootPositionOffset?v.copy(C.rootPositionOffset):v.set(0,0,0),v.applyQuaternion(w).applyQuaternion(R),C.rootQuaternionOffset&&(x.copy(C.rootQuaternionOffset),w.multiply(x)),m.add(v);p.multiply(R),p.multiply(w),m.add(c.position),g.add(m)}}}this._useclipOffsets&&(this._totalOffsetPosition.lerp(this._totalOffsetPosition2,i),this._totalOffsetRotation.slerp(this._totalOffsetRotation2,i)),this.mixer.update(e)}createRotationInterpolant(e,t,i){let n=i.createInterpolant.bind(i),r=new re.Quaternion;this.ensureTrackOffsets();let o=this.trackOffset?.rotation;i.createInterpolant=()=>{let s=n(),c=s.evaluate.bind(s);return s.evaluate=d=>{let a=c(d);return r.set(a[0],a[1],a[2],a[3]),r.premultiply(this._totalOffsetRotation),o&&r.premultiply(o),a[0]=r.x,a[1]=r.y,a[2]=r.z,a[3]=r.w,a},s}}createPositionInterpolant(e,t,i){let n=i.createInterpolant.bind(i),r=new re.Vector3;this.ensureTrackOffsets();let o=this.trackOffset?.rotation,s=this.trackOffset?.position,c;i.createInterpolant=()=>{let d=n(),a=d.evaluate.bind(d);return d.evaluate=h=>{let u=a(h);return r.set(u[0],u[1],u[2]),t.removeStartOffset&&(c===void 0?(c=null,c=this._actionOffsets.find(f=>f.clip===e)?.rootStartPosition?.clone()):c?.isVector3&&r.sub(c)),r.applyQuaternion(this._totalOffsetRotation),r.add(this._totalOffsetPosition),o&&r.applyQuaternion(o),s&&(r.x-=s.x,r.y+=s.y,r.z+=s.z),u[0]=r.x,u[1]=r.y,u[2]=r.z,u},d}}},zn=class extends ko{models=[];listener;audio=[];audioContextTimeOffset=[];lastTime=0;getAudioFilePath(e){let t=this.director.sourceId;return ks(t,e)}onAllowAudioChanged(e){for(let t=0;t<this.models.length;t++){let i=this.models[t];this.audio[t].setVolume(e?i.asset.volume:0)}}addModel(e){let t=this.getAudioFilePath(e.asset.clip),i=new re.Audio(this.listener);i.setVolume(e.asset.volume);let n=new re.AudioLoader;console.log(t,this.director.sourceId),n.load(t,r=>{i.setBuffer(r),i.loop=e.asset.loop,this.audio.push(i),this.models.push(e)})}onDisable(){for(let e of this.audio)e.isPlaying&&e.stop()}onMuteChanged(){if(this.muted)for(let e=0;e<this.audio.length;e++){let t=this.audio[e];t?.isPlaying&&t.stop()}}evaluate(e){if(!this.track.muted){for(let t=0;t<this.models.length;t++){let i=this.models[t],n=this.audio[t];if(e>=i.start&&e<=i.end){if(this.director.isPaused&&(n.isPlaying&&n.stop(),this.lastTime===e))continue;n.isPlaying||(n.offset=i.clipIn+(e-i.start)*i.timeScale,n.play());let r=i.asset.volume;i.easeInDuration>0&&(r*=Math.min((e-i.start)/i.easeInDuration,1)),i.easeOutDuration>0&&(r*=Math.min((i.end-e)/i.easeOutDuration,1)),n.setVolume(r*this.director.weight)}else n.isPlaying&&n.stop()}this.lastTime=e}}},en=class extends ko{models=[];didTrigger=[];receivers=[];evaluate(e){if(!(this.receivers.length<=0)&&!this.track.muted)for(let t=0;t<this.models.length;t++){let i=this.models[t],n=this.didTrigger[t],r=i.time-e;if(i.retroActive?r<0:r<0&&Math.abs(r)<.1){if(!n){this.didTrigger[t]=!0;for(let s of this.receivers)!s||s.invoke(i.asset)}}else i.emitOnce||(this.didTrigger[t]=!1)}}},Es=class extends ko{models=[];timelines=[];resolveSourceObjects(e){for(let t=this.models.length-1;t>=0;t--){let n=this.models[t].asset;if(typeof n.sourceObject=="string"){let r=n.sourceObject;Es.resolved[r]?n.sourceObject=Es.resolved[r]:(n.sourceObject=S.findByGuid(r,e.scene),Es.resolved[r]=n.sourceObject)}if(n.sourceObject){let r=S.getComponent(n.sourceObject,tn);this.timelines.push(r),r&&n.updateDirector&&(r.playOnAwake=!1)}else{this.models.splice(t,1);continue}}}_previousActiveModel=null;evaluate(e){this._previousActiveModel=null;for(let t=0;t<this.models.length;t++){let i=this.models[t],n=i.asset;if(e>=i.start&&e<=i.end){this._previousActiveModel=i;let r=this.getClipTime(e,i);if(n.controlActivation){let o=n.sourceObject;o.visible=!0}if(n.updateDirector){let o=this.timelines[t];o&&(o.isPlaying&&o.pause(),o.time=r,o.evaluate())}}else{let r=this._previousActiveModel?.asset;if(n.controlActivation){let o=n.sourceObject;r?.sourceObject!==o&&(o.visible=!1)}}}}},Ki=Es;z(Ki,"resolved",{});var Xp=N("debugtimeline");var Ya=class extends M{static registerCreateTrack(e,t){this.createTrackFunctions[e]=t}playableAsset;playOnAwake;extrapolationMode=1;get isPlaying(){return this._isPlaying}get isPaused(){return this._isPaused}get time(){return this._time}set time(e){this._time=e}get duration(){return this._duration}set duration(e){this._duration=e}get weight(){return this._weight}set weight(e){this._weight=e}_visibilityChangeEvt;_clonedPlayableAsset=!1;awake(){Xp&&console.log(this,this.playableAsset?.tracks),this.rebuildGraph(),this.playOnAwake?this.play():this.evaluate(),this.isValid()||console.warn("PlayableDirector is not valid",this.playableAsset,this.playableAsset?.tracks,Array.isArray(this.playableAsset?.tracks),this)}onEnable(){for(let e of this._audioTracks)e.onEnable?.();for(let e of this._customTracks)e.onEnable?.();this.playOnAwake&&this.play(),this._visibilityChangeEvt||(this._visibilityChangeEvt=()=>{switch(document.visibilityState){case"hidden":this.setAudioTracksAllowPlaying(!1);break;case"visible":this.setAudioTracksAllowPlaying(!0);break}}),window.addEventListener("visibilitychange",this._visibilityChangeEvt)}onDisable(){this.stop();for(let e of this._audioTracks)e.onDisable?.();for(let e of this._customTracks)e.onDisable?.();this._visibilityChangeEvt&&window.removeEventListener("visibilitychange",this._visibilityChangeEvt)}onDestroy(){for(let e of this._audioTracks)e.onDestroy?.()}rebuildGraph(){!this.isValid()||(this.resolveBindings(),this.updateTimelineDuration(),this.setupAndCreateTrackHandlers())}play(){!this.isValid()||(this._isPaused=!1,!this._isPlaying&&(this._isPlaying=!0,this._internalUpdateRoutine=this.startCoroutine(this.internalUpdate())))}pause(){this._isPaused=!0}stop(){this._isPlaying&&(this._time=0,this._isPlaying=!1,this._isPaused=!1,this.evaluate()),this._isPlaying=!1,this._isPaused=!1,this._internalUpdateRoutine&&this.stopCoroutine(this._internalUpdateRoutine),this._internalUpdateRoutine=null}evaluate(){if(!this.isValid())return;let e=this._time;switch(this.extrapolationMode){case 0:e=Math.min(e,this._duration);break;case 1:e%=this._duration;break;case 2:if(e>this._duration){this.stop();return}break}this.internalEvaluate(e)}isValid(){return this.playableAsset&&this.playableAsset.tracks&&Array.isArray(this.playableAsset.tracks)}*forEachTrack(){for(let e of this._allTracks)for(let t of e)yield t}get audioTracks(){return this._audioTracks}_guidsMap;resolveGuids(e){this._guidsMap=e}_isPlaying=!1;_internalUpdateRoutine;_isPaused=!1;_time=0;_duration=0;_weight=1;_animationTracks=[];_audioTracks=[];_signalTracks=[];_controlTracks=[];_customTracks=[];_allTracks=[this._animationTracks,this._audioTracks,this._signalTracks,this._controlTracks,this._customTracks];*internalUpdate(){for(;this._isPlaying;)!this._isPaused&&this._isPlaying&&(this._time+=this.context.time.deltaTime,this.evaluate()),yield}internalEvaluate(e){for(let t of this.playableAsset.tracks)if(!t.muted)switch(t.type){case"ActivationTrack":for(let i=0;i<t.outputs.length;i++){let n=t.outputs[i];if(typeof n=="object"){let r=!1;for(let s of t.clips)s.start<=e&&e<=s.end&&(r=!0);let o=n;o.visible!==void 0&&(o.visible=r)}}break}for(let t of this._animationTracks)t.evaluate(e);for(let t of this._audioTracks)t.evaluate(e);for(let t of this._signalTracks)t.evaluate(e);for(let t of this._controlTracks)t.evaluate(e);for(let t of this._customTracks)t.evaluate(e)}resolveBindings(){if(this._clonedPlayableAsset||(this._clonedPlayableAsset=!0,this.playableAsset=qo(this.playableAsset)),!this.playableAsset||!this.playableAsset.tracks)return;let e=this.findRoot(this.gameObject);for(let t of this.playableAsset.tracks)for(let i=t.outputs.length-1;i>=0;i--){let n=t.outputs[i];if(typeof n=="string"){this._guidsMap&&this._guidsMap[n]&&(n=this._guidsMap[n]);let r=S.findByGuid(n,e);r===null||typeof r!="object"?(t.outputs.splice(i,1),console.warn("Failed to resolve binding",n,t.name,t.type)):(Xp&&console.log("Resolved binding",n,"to",r),t.outputs[i]=r)}else if(n===null){if(t.outputs.splice(i,1),Ya.createTrackFunctions[t.type])continue;t.type!=="AudioTrack"&&t.type!=="ControlTrack"&&t.type!=="MarkerTrack"&&console.warn("Missing binding",n,t.name,t.type,this.name,this.playableAsset.name)}}}findRoot(e){return e.parent?this.findRoot(e.parent):e}updateTimelineDuration(){if(this._duration=0,!(!this.playableAsset||!this.playableAsset.tracks)){for(let e of this.playableAsset.tracks)if(e.muted!==!0)for(let t of e.clips)t.end>this._duration&&(this._duration=t.end)}}setupAndCreateTrackHandlers(){if(this._animationTracks.length=0,this._audioTracks.length=0,this._signalTracks.length=0,!this.playableAsset)return;let e=[];for(let t of this.playableAsset.tracks){let i=t.type,n=Ya.createTrackFunctions[i];if(n!=null){let r=n(this,t);if(typeof r.evaluate=="function"){r.director=this,r.track=t,this._customTracks.push(r);continue}}if(t.type==="AnimationTrack"){if(t.clips.length<=0)continue;for(let r=t.outputs.length-1;r>=0;r--){let o=t.outputs[r];typeof o.enabled=="boolean"&&(o.enabled=!1);let s=o?.gameObject?.animations;if(s){let c=new Nn;c.trackOffset=t.trackOffset,c.director=this,c.track=t;for(let d=0;d<t.clips.length;d++){let a=t.clips[d],h=a.asset;if(!h){console.error("MISSING anim model?","clip#"+d,a,t,this.playableAsset,this.name);continue}let u=h.clip,f=u;if((typeof f=="string"||typeof f=="number")&&(f=s.find(b=>b.name===u)),!f){console.warn("Could not find animationClip for model",a,t.name,this.name,this.playableAsset?.name);continue}c.mixer||(c.mixer=new Qp.AnimationMixer(o.gameObject)),c.clips.push(f),c.mixer.uncacheAction(f),c.createHooks(a.asset,f);let E=c.mixer.clipAction(f);c.actions.push(E),c.models.push(a)}this._animationTracks.push(c)}}}else if(t.type==="AudioTrack"){if(t.clips.length<=0)continue;e.push(t)}else if(t.type==="MarkerTrack"){let r=new en;r.director=this,r.track=t;for(let o of t.markers)switch(o.type){case"SignalEmitter":r.models.push(o),r.didTrigger.push(!1);break}if(r!==null&&r.models.length>0){let o=S.getComponent(this.gameObject,$i);o&&(r.receivers.push(o),this._signalTracks.push(r))}}else if(t.type==="SignalTrack"){let r=new en;r.director=this,r.track=t;for(let o of t.markers)r.models.push(o),r.didTrigger.push(!1);for(let o of t.outputs)r.receivers.push(o);this._signalTracks.push(r)}else if(t.type==="ControlTrack"){let r=new Ki;r.director=this,r.track=t;for(let o of t.clips)r.models.push(o);r.resolveSourceObjects(this.context),this._controlTracks.push(r)}}ue.registerWaitForAllowAudio(()=>{let t=S.findObjectOfType($t,this.context);if(!!t)for(let i of e){let n=new zn;n.director=this,n.track=i,n.listener=t.listener;for(let r=0;r<i.clips.length;r++){let o=i.clips[r];n.addModel(o)}this._audioTracks.push(n)}})}setAudioTracksAllowPlaying(e){for(let t of this._audioTracks)t.onAllowAudioChanged(e)}},tn=Ya;z(tn,"createTrackFunctions",{});import*as Yp from"three-mesh-ui";var ii=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 jy}from"three";var By=N("debugeventsystem"),Ci=class extends M{static createIfNoneExists(e){this.didSearchEventSystem||(this.didSearchEventSystem=!0,Ci.systems.length<=0&&Ci.systems.push(...S.findObjectsOfType(Ci,e)));for(let i of Ci.systems)if(i.context===e)return;let t=new jy;S.addNewComponent(t,Ci),e.scene.add(t)}static ensureUpdateMeshUI(e,t){ni.update(e,t)}static markUIDirty(e){ni.markDirty()}static get instance(){return this.systems[0]}orbitControl=null;orbitControlWasEnabled=!1;raycaster=[];constructor(){super(),Ci.systems.push(this)}onDestroy(){Ci.systems.splice(Ci.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)}onEnable(){ae.addEventListener("select-start",(t,i)=>{if(!i.grab)return;ni.resetLastSelected();let n=new ii;n.inputSource=t,n.isDown=t.selectionDown,n.isUp=t.selectionUp,n.isPressed=t.selectionPressed,n.isClicked=!1,i.grab&&!this.handleEvents(i.grab,n)&&(i.grab=null)});let e=new je;ae.addEventListener("select-end",(t,i)=>{if(!i.grab)return;let n=new ii;n.inputSource=t,n.isDown=t.selectionDown,n.isUp=t.selectionUp,n.isPressed=t.selectionPressed,n.isClicked=t.selectionClick,this.handleEvents(i.grab,n)}),ae.addEventListener("update",t=>{e.ray=t.getRay();let i=this.performRaycast(e);if(!i)return;let n=new ii;n.inputSource=t,this.handleIntersections(i,n)}),this.context.pre_update_callbacks.push(this.onBeforeUpdate.bind(this)),this.context.input.addEventListener("pointerDown",this.onPointerDown.bind(this))}onDisable(){}onPointerDown(){this.onBeforeUpdate()}lastPointerEvent=null;objectsHoveredThisFrame=[];objectsHoveredLastFrame=[];raisedPointerDownEvents=[];_didMove=!1;onBeforeUpdate(){if(this.objectsHoveredThisFrame.length=0,this.resetMeshUIStates(),$.IsInWebXR||this.context.input.isKeyPressed(18))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 ii(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 i=null,n=null;this.context.input.mouseDown&&this.currentActiveMeshUIComponents.length>0&&this.context.mainCameraComponent&&(i=S.getComponent(this.context.mainCameraComponent.gameObject,gt)??null,i&&(n=i.enabled,i.enabled=!1)),this.handleIntersections(e,t),i&&(this.orbitControl=i,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}for(let t of this.objectsHoveredLastFrame)if(this.objectsHoveredThisFrame.indexOf(t)<0){this._tempComponentsArray.length=0;let i=S.getComponentsInParent(t,M,this._tempComponentsArray);this.lastPointerEvent.object=t;for(let n=0;n<i.length;n++){let r=i[n];if(!r.gameObject||r.destroyed)continue;let o=r;o.onPointerExit&&o.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 i=t.performRaycast(e);i&&i.length>0&&this._sortedHits.push(...i)}return this._sortedHits.sort((t,i)=>t.distance-i.distance),this._sortedHits}handleIntersections(e,t){if(!e||e.length<=0)return!1;e=this.sortCandidates(e);for(let i of e){let{object:n}=i;if(this.handleEvents(n,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 i=e[t],n=i.object;if(n.material&&n.material.depthTest===!1){this._noDepthTestingResults.push(i);continue}this._sortingBuffer.push(i)}for(let t of this._sortingBuffer)this._noDepthTestingResults.push(t);return this._noDepthTestingResults}handleEventsArray=[];handleEvents(e,t){if(!this.testIsVisible(e))return t.isClicked&&By&&console.log("not allowed",e),!1;t.object=e,this.lastPointerEvent=t;let i=e.parent,n=!1,r=t.isClicked??!1,o=null;if(i&&i.isUI){let s=(t.isPressed||t.isClicked)??!1;if(i.shadowComponentOwner){let c=i.shadowComponentOwner.gameObject;if(c){if(o=this.tryFindCanvasGroup(c),o?.blocksRaycasts===!1)return!1;if(o?.interactable===!1)return!0;let d=this.handleMeshUIIntersection(e,s);e=c,n=!0}}if(!n&&this.handleMeshUiObjectWithoutShadowDom(i,s))return!0}if(this.objectsHoveredThisFrame.push(e),o===null||o.interactable){let s=this.objectsHoveredLastFrame.indexOf(e)>=0;this.handleEventsArray.length=0;let c=S.getComponentsInParent(e,M,this.handleEventsArray);for(let d=0;d<c.length;d++){if(t.used)return!0;if(c[d].destroyed)continue;let a=c[d];a.interactable!==!1&&(a.onPointerEnter&&(s||a.onPointerEnter(t)),t.isDown&&a.onPointerDown&&!this.raisedPointerDownEvents.includes(a)&&(a.onPointerDown(t),this.raisedPointerDownEvents.push(a)),t.isUp&&a.onPointerUp&&a.onPointerUp(t),t.isClicked&&a.onPointerClick&&a.onPointerClick(t))}}return!0}handleMeshUiObjectWithoutShadowDom(e,t){return!e||!e.isUI?!0:this.handleMeshUIIntersection(e,t)}currentActiveMeshUIComponents=[];handleMeshUIIntersection(e,t){let i=ni.updateState(e,t);return i&&this.currentActiveMeshUIComponents.push(i),i!==null}resetMeshUIStates(){if(this.context.input.getPointerPressedCount()>0&&ni.resetLastSelected(),!(!this.currentActiveMeshUIComponents||this.currentActiveMeshUIComponents.length<=0)){for(let e=0;e<this.currentActiveMeshUIComponents.length;e++){let t=this.currentActiveMeshUIComponents[e];ni.resetState(t)}this.currentActiveMeshUIComponents.length=0}}testIsVisible(e){return e?S.isActiveSelf(e)?this.testIsVisible(e.parent):!1:!0}tryFindCanvasGroup(e){if(!e)return null;let t=S.foreachComponent(e,i=>{let n=i;if(n.blocksRaycasts!==void 0&&n.interactable!==void 0)return n},!1);return t!==void 0?t:this.tryFindCanvasGroup(e.parent)}},Ze=Ci;z(Ze,"didSearchEventSystem",!1),z(Ze,"systems",[]);var ni=class{static markDirty(){this.needsUpdate=!0}static update(e,t){for(let i of this.lastUpdateFrame)if(i.context===t){if(t.time.frameCount===i.frame)return;i.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 i=null;if(e&&(i=this.findBlockInParent(e),i&&i!==this.lastSelected)){if(i.interactable===!1)return null;t?(this.lastSelected=i,i.states.pressed&&i.setState("pressed")):i.states.hovered&&i.setState("hovered"),this.needsUpdate=!0}return i}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}};z(ni,"lastSelected",null),z(ni,"lastUpdateFrame",[]),z(ni,"needsUpdate",!1);import{AxesHelper as Fy}from"three";var Io="./include";Yp.Block.prototype.interactable={get(){return this.interactive},set(l){this.interactable=l}};var Ue=class extends M{isRoot(){return this.Root?.gameObject===this.gameObject}markDirty(){Ze.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=S.getComponentInParent(this.gameObject,nn)),this._root}_parentComponent=void 0;onEnable(){super.onEnable()}addShadowComponent(e,t){this.removeShadowComponent();let i=this.isRoot()?this.gameObject:this.gameObject.parent;if(this._parentComponent=S.getComponentInParent(i,Ue),!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.shadowComponentOwner=this;let n=this.raycastTarget;if(e.traverse(r=>{r.shadowComponentOwner===void 0&&(r.shadowComponentOwner=this),n===!1&&r.layers.set(2)}),this.Root?.gameObject===this.gameObject)this.gameObject.add(e);else{let r=this._parentComponent.shadowComponent;r&&r?.add(e)}this.shadowComponent=e,t&&t.shadowComponent&&this.shadowComponent&&t.shadowComponent.add(this.shadowComponent),hi&&e.add(new Fy(.5)),this.onAfterAddedToScene()}set(e){}traverseOwnedShadowComponents(e,t,i){if(!!e&&e.shadowComponentOwner===t){i(e);for(let n of e.children)this.traverseOwnedShadowComponents(n,t,i)}}removeShadowComponent(){this.shadowComponent&&this.shadowComponent.removeFromParent()}onAfterAddedToScene(){}setInteractable(e){this.shadowComponent&&(this.shadowComponent.interactable=e)}},nn=class extends Ue{awake(){super.awake()}};import{Color as Gy,Texture as $p}from"three";import*as bd from"three-mesh-ui";import{Matrix4 as Ny,Object3D as zy,Vector2 as Zp,Vector3 as gd}from"three";var Jp=N("debugui"),Mo=class{width;height},xr=class{x;y;width;height},ut=class extends Ue{offset=.01;get translation(){return this.gameObject.position}get rotation(){return this.gameObject.quaternion}get scale(){return this.gameObject.scale}_anchoredPosition;get anchoredPosition(){return this._anchoredPosition||(this._anchoredPosition=new gd),this._anchoredPosition}rect;sizeDelta;anchoredPosition3D;pivot;lastMatrix;rectBlock;_transformNeedsUpdate=!1;awake(){super.awake(),this.lastMatrix=new Ny,this.rectBlock=new zy,this.rectBlock.position.z=.1,this.rectBlock.name=this.name,this._anchoredPosition||(this._anchoredPosition=new gd),Jr(this,"_anchoredPosition",()=>{this._transformNeedsUpdate=!0})}onEnable(){super.onEnable(),this.addShadowComponent(this.rectBlock),this.applyTransform()}onDisable(){super.onDisable(),this.removeShadowComponent()}applyTransform(){let e=this.shadowComponent;!e||(this._transformNeedsUpdate=!1,this.isRoot()?e.rotation.y=Math.PI:(e.position.copy(this.gameObject.position),e.position.x*=-1,e.position.z*=-1,e.position.z-=this.offset,e.quaternion.copy(this.gameObject.quaternion),e.rotation.x*=-1,e.rotation.z*=-1,e.scale.copy(this.gameObject.scale)),this.applyAnchoring(e.position),this.lastMatrix.copy(this.gameObject.matrix))}markDirty(){this._transformNeedsUpdate=!0}onBeforeRender(){(this._transformNeedsUpdate||this.lastMatrix.equals(this.gameObject.matrix)===!1)&&(Jp&&console.log("updating",this.name),this.applyTransform()),Ze.ensureUpdateMeshUI(bd,this.context)}applyAnchoring(e){if(this.pivot&&this.sizeDelta){let t=this.pivot.x*2-1,i=this.pivot.y*2-1;i-=this.anchoredPosition.y*.05;let n=this.sizeDelta.x*t,r=this.sizeDelta.y*i;e.x-=n*.5,e.y-=r*.5}}getBasicOptions(){let e={width:this.rect.width,height:this.rect.height,offset:this.offset,backgroundOpacity:0,borderWidth:0,borderRadius:0,borderOpacity:0};return this.ensureValidSize(e),e}ensureValidSize(e,t=1e-4){return e.width<=0&&(e.width=t),e.height<=0&&(e.height=1e-4),e}_createdBlocks=[];createNewBlock(e){e={...this.getBasicOptions(),...e},Jp&&console.log(this.name,e);let t=new bd.Block(e);return this._createdBlocks.push(t),t}};k([A(xr)],ut.prototype,"rect",2),k([A(Zp)],ut.prototype,"sizeDelta",2),k([A(gd)],ut.prototype,"anchoredPosition3D",2),k([A(Zp)],ut.prototype,"pivot",2);var Rt=class extends Ue{get color(){return this._color||(this._color=new we(1,1,1,1)),this._color}set color(e){(!this._color||this._color.r!==e.r||this._color.g!==e.g||this._color.b!==e.b||this._color.alpha!==e.alpha)&&(this._color||(this._color=new we(1,1,1,1)),this._color.copy(e))}onColorChanged(){let e=this.color;this.setOptions({backgroundColor:e,backgroundOpacity:e.alpha,borderOpacity:e.alpha})}get m_Color(){return this._color}raycastTarget=!0;uiObject=null;_color=null;_rect=null;get rectTransform(){return this._rect||(this._rect=this.gameObject.getComponent(ut)),this._rect}setState(e){this.makePanel(),this.uiObject&&this.uiObject.setState(e)}setupState(e){this.makePanel(),this.uiObject&&this.uiObject.setupState(e)}setOptions(e){this.makePanel(),this.uiObject&&(this.uiObject.set(e),(e.backgroundColor!==void 0||e.backgroundOpacity!==void 0)&&this.uiObject.updateBackgroundMaterial?.call(this.uiObject))}awake(){super.awake(),this.makePanel(),Jr(this,"_color",()=>bp(this,this.onColorChanged))}onEnable(){super.onEnable(),this.uiObject&&(this.rectTransform.shadowComponent?.add(this.uiObject),this.addShadowComponent(this.uiObject,this.rectTransform))}onDisable(){super.onDisable(),this.uiObject&&this.removeShadowComponent()}_currentlyCreatingPanel=!1;makePanel(){if(this.uiObject||this._currentlyCreatingPanel)return;this._currentlyCreatingPanel=!0;let e={backgroundColor:this.color,backgroundOpacity:this.color.alpha,offset:1};this.onBeforeCreate(e),this.onCreate(e),this.controlsChildLayout=!1,this._currentlyCreatingPanel=!1,this.onAfterCreated()}onBeforeCreate(e){}onCreate(e){this.uiObject=this.rectTransform.createNewBlock(e),this.uiObject.name=this.name}onAfterCreated(){}async setTexture(e){!e||(this.setOptions({backgroundOpacity:0}),e&&this.setOptions({backgroundTexture:e,borderRadius:0,backgroundOpacity:this.color.alpha,backgroundSize:"stretch"}))}onAfterAddedToScene(){this.shadowComponent&&(this.shadowComponent.offset=this.shadowComponent.position.z)}};k([A(we)],Rt.prototype,"color",1),k([A()],Rt.prototype,"raycastTarget",2);var rn=class extends Rt{onAfterCreated(){this.uiObject&&(this.uiObject.scale.y*=-1)}};var Za=class{texture;rect};k([A($p)],Za.prototype,"texture",2);var on=class extends rn{sprite;isBuiltinSprite(){switch(this.sprite?.texture?.name){case"InputFieldBackground":case"UISprite":case"Background":return!0}return!1}onBeforeCreate(e){this.isBuiltinSprite()&&(e.borderRadius=5,e.borderColor=new Gy(.4,.4,.4),e.borderOpacity=this.color.alpha,e.borderWidth=.3)}onAfterCreated(){super.onAfterCreated(),!this.isBuiltinSprite()&&this.setTexture(this.sprite?.texture)}};k([A(Za)],on.prototype,"sprite",2);var Tr=class extends rn{mainTexture;onAfterCreated(){super.onAfterCreated(),this.setTexture(this.mainTexture)}};k([A($p)],Tr.prototype,"mainTexture",2);var Lo=N("debugbutton");var Ft=class extends M{onClick;_isHovered=!1;onPointerEnter(e){Lo&&console.log("Button Enter",this.animationTriggers?.highlightedTrigger,this.animator),this._isHovered=!0,this.transition==3&&this.animationTriggers&&this.animator?this.animator.SetTrigger(this.animationTriggers.highlightedTrigger):this.transition===1&&this.colors&&this._image?.setState("hovered")}onPointerExit(){Lo&&console.log("Button Exit",this.animationTriggers?.highlightedTrigger,this.animator),this._isHovered=!1,this.transition==3&&this.animationTriggers&&this.animator?this.animator.SetTrigger(this.animationTriggers.normalTrigger):this.transition===1&&this.colors&&this._image?.setState("normal")}onPointerDown(e){Lo&&console.log("Button Down",this.animationTriggers?.highlightedTrigger,this.animator),this.transition==3&&this.animationTriggers&&this.animator?this.animator.SetTrigger(this.animationTriggers.pressedTrigger):this.transition===1&&this.colors&&this._image?.setState("pressed")}onPointerUp(e){Lo&&console.log("Button Down",this.animationTriggers?.highlightedTrigger,this.animator),this.transition==3&&this.animationTriggers&&this.animator?this.animator.SetTrigger(this._isHovered?this.animationTriggers.highlightedTrigger:this.animationTriggers.normalTrigger):this.transition===1&&this.colors&&this._image?.setState(this._isHovered?"hovered":"normal")}onPointerClick(e){Lo&&console.trace("Button Click",this.onClick),this.onClick?.invoke()}colors;transition;animationTriggers;animator;set interactable(e){this._interactable=e,this._image&&(this._image.setInteractable(e),e?this._image.setState("normal"):this._image.setState("disabled"))}get interactable(){return this._interactable}_interactable=!0;set_interactable(e){this.interactable=e}awake(){super.awake(),Lo&&console.log(this),this.init()}start(){this._image?.setInteractable(this.interactable)}onEnable(){super.onEnable()}_requestedAnimatorTrigger;*setAnimatorTriggerAtEndOfFrame(e){this._requestedAnimatorTrigger=e,yield,yield,this._requestedAnimatorTrigger==e&&this.animator?.SetTrigger(e)}_isInit=!1;_image;init(){this._isInit||(this._isInit=!0,this._image=S.getComponent(this.gameObject,on),this._image&&(this.stateSetup(this._image),this.interactable?this._image.setState("normal"):this._image.setState("disabled")))}stateSetup(e){e.setInteractable(this.interactable);let t=this.getFinalColor(e.color,this.colors?.normalColor),i={state:"normal",attributes:{backgroundColor:t,backgroundOpacity:t.alpha}};e.setupState(i);let n=this.getFinalColor(e.color,this.colors?.highlightedColor),r={state:"hovered",attributes:{backgroundColor:n,backgroundOpacity:n.alpha}};e.setupState(r);let o=this.getFinalColor(e.color,this.colors?.pressedColor),s={state:"pressed",attributes:{backgroundColor:o,backgroundOpacity:o.alpha}};e.setupState(s);let c=this.getFinalColor(e.color,this.colors?.selectedColor),d={state:"selected",attributes:{backgroundColor:c,backgroundOpacity:c.alpha}};e.setupState(d);let a=this.getFinalColor(e.color,this.colors?.disabledColor),h={state:"disabled",attributes:{backgroundColor:a,backgroundOpacity:a.alpha}};e.setupState(h)}getFinalColor(e,t){return t?e.clone().multiply(t):e.clone()}};k([A(Oe)],Ft.prototype,"onClick",2),k([A()],Ft.prototype,"colors",2),k([A()],Ft.prototype,"transition",2),k([A()],Ft.prototype,"animationTriggers",2),k([A(bt)],Ft.prototype,"animator",2),k([A()],Ft.prototype,"interactable",1);var vd=class extends nn{set renderOnTop(e){e!==this._renderOnTop&&(this._renderOnTop=e,this.onRenderSettingsChanged())}get renderOnTop(){return this._renderOnTop}_renderOnTop=!1;set depthWrite(e){this._depthWrite!==e&&(this._depthWrite=e,this.onRenderSettingsChanged())}get depthWrite(){return this._depthWrite}_depthWrite=!1;set doubleSided(e){this._doubleSided!==e&&(this._doubleSided=e,this.onRenderSettingsChanged())}get doubleSided(){return this._doubleSided}_doubleSided=!0;set castShadows(e){this._castShadows!==e&&(this._castShadows=e,this.onRenderSettingsChanged())}get castShadows(){return this._castShadows}_castShadows=!0;set receiveShadows(e){this._receiveShadows!==e&&(this._receiveShadows=e,this.onRenderSettingsChanged())}get receiveShadows(){return this._receiveShadows}_receiveShadows=!0;get renderMode(){return this._renderMode}set renderMode(e){this._renderMode!==e&&(this._renderMode=e,this.onRenderSettingsChanged())}_renderMode=-1;_rootCanvas;set rootCanvas(e){this._rootCanvas instanceof vd||(this._rootCanvas=e)}get rootCanvas(){return this._rootCanvas}awake(){this.shadowComponent=this.gameObject,super.awake()}onEnable(){super.onEnable(),this._updateRenderSettingsRoutine=void 0,this.onRenderSettingsChanged()}previousAspect=-1;onBeforeRender(){this.isScreenSpace&&this.context.mainCameraComponent&&this.context.mainCameraComponent.aspect!==this.previousAspect&&(this.previousAspect=this.context.mainCameraComponent.aspect,this.updateRenderMode())}_updateRenderSettingsRoutine;onRenderSettingsChanged(){this._updateRenderSettingsRoutine||(this._updateRenderSettingsRoutine=this.startCoroutine(this._updateRenderSettingsDelayed(),3))}*_updateRenderSettingsDelayed(){if(yield,this._updateRenderSettingsRoutine=void 0,this.shadowComponent){this.updateRenderMode(),Zr(this.shadowComponent,this);for(let e of this.gameObject.getComponentsInChildren(Ue))Zr(e.shadowComponent,this)}}_activeRenderMode=-1;get isScreenSpace(){return this._activeRenderMode===1||this._activeRenderMode===0}updateRenderMode(){if(this.renderMode!==this._activeRenderMode)switch(this.renderMode){case 0:case 1:let e=this.context.mainCameraComponent;if(!e)return;let t=this.gameObject;e.gameObject?.add(t);let n=e.farClipPlane;t.position.x=0,t.position.y=0,t.position.z=-n;let r=Math.tan(Q.toRadians(e.fieldOfView)*n)*(e.aspect*1.333333),o=r*(this.context.domHeight/this.context.domWidth);t.scale.x=-r,t.scale.y=o;break;case 2:break}}},Je=vd;k([A()],Je.prototype,"renderOnTop",1),k([A()],Je.prototype,"depthWrite",1),k([A()],Je.prototype,"doubleSided",1),k([A()],Je.prototype,"castShadows",1),k([A()],Je.prototype,"receiveShadows",1),k([A()],Je.prototype,"renderMode",1),k([A(Je)],Je.prototype,"rootCanvas",1);var sn=class extends M{get alpha(){return this._alpha}set alpha(e){e!==this._alpha&&(this._alpha=e,this.markDirty())}_alpha=1;interactable=!0;blocksRaycasts=!0;_isDirty=!1;markDirty(){this._isDirty||(this._isDirty=!0,this.startCoroutine(this.applyChangesDelayed(),3))}*applyChangesDelayed(){this._isDirty=!1,this.applyChangesNow()}_buffer=[];applyChangesNow(){for(let e of S.getComponentsInChildren(this.gameObject,Rt,this._buffer)){let t=e.color;t.alpha=this._alpha,e.color=t}}};k([A()],sn.prototype,"alpha",1),k([A()],sn.prototype,"interactable",2),k([A()],sn.prototype,"blocksRaycasts",2);import*as Kp from"three-mesh-ui";import{Color as B}from"three";var Vy=N("debugtext");var Le=class extends Rt{canvas;alignment=0;verticalOverflow=0;horizontalOverflow=0;lineSpacing=1;supportRichText=!1;font;fontStyle=0;get text(){return this._text}set text(e){if(this._text=e,!this._textMeshUi&&this._text.length>0&&this.context.time.frame>0&&this.createText(e,this.getTextOpts(),this.supportRichText),this._textMeshUi){if(this._textMeshUi.length>1){this.requestRebuild();return}this._textMeshUi[0].set({content:e}),this.markDirty()}}set_text(e){this.text=e}get fontSize(){return this._fontSize}set fontSize(e){if(this._fontSize=e,this._textMeshUi){if(this._textMeshUi.length>1){this.requestRebuild();return}this._textMeshUi[0].set({content:e}),this.markDirty()}}onColorChanged(){if(this._textMeshUi){if(this._textMeshUi.length>1){this.requestRebuild();return}let e=this.color;this._textMeshUi[0].set({fontColor:e,fontOpacity:e.alpha}),this.markDirty()}}_isWaitingForRebuild=!1;requestRebuild(){this._isWaitingForRebuild||(this._isWaitingForRebuild=!0,this.startCoroutine(this.rebuildDelayedRoutine(),0))}*rebuildDelayedRoutine(){if(this._isWaitingForRebuild=!1,this._textMeshUi){for(let e of this._textMeshUi)e.removeFromParent();this._textMeshUi.length=0}this.createText(this.text,this.getTextOpts(),this.supportRichText),this.markDirty()}onCreate(e){Vy&&console.log(this);let t=this.verticalOverflow==0&&this.horizontalOverflow==0;t&&(this.context.renderer.localClippingEnabled=!0);let i=this.rectTransform;this._textContainer=this.uiObject=this.createBlock(i,t,null,!0),this.createText(this.text,this.getTextOpts(),this.supportRichText),this.uiObject,this.uiObject=this.createBlock(i,t,this.uiObject,!1)}onAfterAddedToScene(){super.onAfterAddedToScene(),this.handleTextRenderOnTop()}_text="";_fontSize=12;_textMeshUi=null;_textContainer=null;getTextOpts(){let e={content:this.text,fontColor:this.color,fontOpacity:this.color.alpha,fontSize:this.fontSize,fontKerning:"normal"};return this.font=this.font?.toLocaleLowerCase(),this.setFont(e,this.fontStyle),e}onEnable(){super.onEnable(),this._didHandleTextRenderOnTop=!1,this.uiObject&&(this.uiObject.onAfterUpdate=this.updateWidth.bind(this))}createBlock(e,t,i,n=!1){let r={};r.hiddenOverflow=t,r.interLine=(this.lineSpacing-1)*this.fontSize*1.333,this.getAlignment(r,n);let o=e.createNewBlock(r);return i&&(Array.isArray(i)?o.add(...i):o.add(i)),o}getAlignment(e,t=!1){switch(t||(e.contentDirection="row"),this.alignment){default:case 0:case 1:case 2:e.justifyContent="start";break;case 3:case 4:case 5:e.justifyContent="center";break;case 6:case 7:case 8:e.justifyContent="end";break}switch(this.alignment){case 0:case 3:case 6:e.alignContent=t?"left":"top";break;case 1:case 4:case 7:e.alignContent="center";break;case 2:case 5:case 8:e.alignContent=t?"right":"bottom";break}return e}updateWidth(){this.horizontalOverflow===1&&setTimeout(()=>{if(!this._textMeshUi)return;let e=this._textMeshUi[0].parent;if(!!e&&e.lines){let t=e.lines.reduce((i,n)=>i+n.width,0);t+=e.getFontSize()*5,t+=e.padding*2||0,t+=this.fontSize*1.5,e.set({width:t}),this.ensureShadowComponentOwner()}},1)}ensureShadowComponentOwner(){this.shadowComponent&&this.shadowComponent.traverse(e=>{e.shadowComponentOwner===void 0&&(e.shadowComponentOwner=this)})}createText(e,t,i){if(!(!e||e.length<=0))if(this._textMeshUi||(this._textMeshUi=[]),i){let n=this.getNextTag(e);if(n)n.startIndex>0&&this.createText(e.substring(0,n.startIndex),t,!1);else return this.createText(e,t,!1);let r=[];for(;n;){let o=this.getNextTag(e,n.endIndex);if(o){let s=this.getText(e,n,o);this.handleTag(n,t,r),this.createText(s,t,!1)}else{let s=e.substring(n.endIndex);this.handleTag(n,t,r),this.createText(s,t,!1)}n=o}}else{let n={...t};n.content=e;let r=new Kp.Text(n);this._textMeshUi.push(r),this._textContainer&&this._textContainer.add(r)}}_didHandleTextRenderOnTop=!1;handleTextRenderOnTop(){this._didHandleTextRenderOnTop||(this._didHandleTextRenderOnTop=!0,this.startCoroutine(this.renderOnTopCoroutine()))}*renderOnTopCoroutine(){if(!this.canvas)return;let e=[],t=this.canvas,i={renderOnTop:t.renderOnTop,depthWrite:t.depthWrite,doubleSided:t.doubleSided};for(;;){let n=!1;if(this._textMeshUi)for(let r=0;r<this._textMeshUi.length;r++){if(e[r]===!0)continue;n=!0;let o=this._textMeshUi[r];!o.textContent||(Zr(o,i),e[r]=!0)}if(!n)break;yield}}handleTag(e,t,i){if(e.isEndTag){if(i.length>0){let n=i.pop();if(n)for(let r in n.previousValues){let o=n.previousValues[r];t[r]=o}}}else if(e.type.includes("color")){let n=new ws(e,{fontColor:t.fontColor});if(i.push(n),e.type.length>6){let r=e.type.substring(6);t.fontColor=Wy(r)}else t.fontColor=new B(1,1,1)}else if(e.type=="b"){let n=new ws(e,{fontFamily:t.fontFamily,fontTexture:t.fontTexture});i.push(n),this.setFont(t,1)}else if(e.type=="i"){let n=new ws(e,{fontFamily:t.fontFamily,fontTexture:t.fontTexture});i.push(n),this.setFont(t,2)}}getText(e,t,i){return e.substring(t.endIndex,i.startIndex)}getNextTag(e,t=0){let i=e.indexOf("<",t),n=e.indexOf(">",i);if(i>=0&&n>=0){let r=e.substring(i+1,n);return{type:r,startIndex:i,endIndex:n+1,isEndTag:r.startsWith("/")}}return null}setFont(e,t){let i=this.getFontName(t),n=i;n?.endsWith("-msdf.json")||(n+="-msdf.json"),e.fontFamily=n;let r=i;r?.endsWith(".png")||(r+=".png"),e.fontTexture=r}getFontName(e){return this.font?this.font:null}};k([A(Je)],Le.prototype,"canvas",2),k([A()],Le.prototype,"alignment",2),k([A()],Le.prototype,"verticalOverflow",2),k([A()],Le.prototype,"horizontalOverflow",2),k([A()],Le.prototype,"lineSpacing",2),k([A()],Le.prototype,"supportRichText",2),k([A()],Le.prototype,"font",2),k([A()],Le.prototype,"fontStyle",2),k([A()],Le.prototype,"text",1),k([A()],Le.prototype,"fontSize",1);var ws=class{tag;previousValues;constructor(e,t){this.tag=e,this.previousValues=t}};function Wy(l){if(l.startsWith("#")){let t=l.substring(1);var e=parseInt(t,16);let i=e>>16&255,n=e>>8&255,r=e&255;return new B(i/255,n/255,r/255)}switch(l){case"black":return new B(0,0,0);case"white":return new B(1,1,1);case"red":return new B(1,0,0);case"lime":return new B(0,1,0);case"blue":return new B(0,0,1);case"yellow":return new B(1,1,0);case"cyan":return new B(0,1,1);case"magenta":return new B(1,0,1);case"silver":return new B(.75,.75,.75);case"gray":return new B(.5,.5,.5);case"maroon":return new B(.5,0,0);case"olive":return new B(.5,.5,0);case"green":return new B(0,.5,0);case"purple":return new B(.5,0,.5);case"teal":return new B(0,.5,.5);case"navy":return new B(0,0,.5);case"darkred":return new B(.54,0,0);case"brown":return new B(.55,.27,0);case"firebrick":return new B(.69,.13,.13);case"crimson":return new B(.86,.08,.24);case"tomato":return new B(1,.39,.28);case"coral":return new B(1,.49,.31);case"indianred":return new B(.6,.31,.51);case"lightcoral":return new B(.94,.5,.5);case"darkorange":return new B(1,.55,0);case"orange":return new B(1,.65,0);case"gold":return new B(1,.84,0);case"darkgoldenrod":return new B(.72,.53,.04);case"goldenrod":return new B(.85,.65,.13);case"palegoldenrod":return new B(.93,.87,.67);case"darkkhaki":return new B(.74,.7,.42);case"khaki":return new B(.94,.9,.55);case"yellowgreen":return new B(.6,.8,.19);case"darkolivegreen":return new B(.33,.42,.18);case"olivedrab":return new B(.42,.56,.14);case"lawngreen":return new B(.49,.99,0);case"chartreuse":return new B(.5,1,0);case"greenyellow":return new B(.68,1,.18);case"darkgreen":return new B(0,.39,0);case"forestgreen":return new B(.13,.55,.13);case"limegreen":return new B(.19,.8,.19);case"lightgreen":return new B(.56,.93,.56);case"palegreen":return new B(.59,.98,.59);case"darkseagreen":return new B(.56,.74,.56);case"mediumspringgreen":return new B(0,.98,.6);case"springgreen":return new B(0,1,.5);case"seagreen":return new B(.18,.31,.31);case"mediumaquamarine":return new B(.4,.8,.66);case"mediumseagreen":return new B(.24,.7,.44);case"lightseagreen":return new B(.13,.7,.67);case"darkslategray":return new B(.18,.31,.31);case"darkcyan":return new B(0,.55,.55);case"aqua":return new B(0,1,1);case"lightcyan":return new B(.8,1,1);case"darkturquoise":return new B(0,.81,.82);case"turquoise":return new B(0,.82,.82);case"mediumturquoise":return new B(.28,.82,.8);case"paleturquoise":return new B(.68,1,.93);case"aquamarine":return new B(.5,1,.83);case"powderblue":return new B(.69,.88,.9);case"cadetblue":return new B(.37,.62,.63);case"steelblue":return new B(.27,.51,.71);case"cornflowerblue":return new B(.39,.58,.93);case"deepskyblue":return new B(0,.7,1);case"dodgerblue":return new B(.12,.56,1);case"lightblue":return new B(.68,.85,.9);case"skyblue":return new B(.53,.81,.92);case"lightskyblue":return new B(.53,.81,.98);case"midnightblue":return new B(.18,.18,.31);case"darkblue":return new B(0,0,.55);case"mediumblue":return new B(0,0,.82);case"royalblue":return new B(.25,.41,.88);case"blueviolet":return new B(.54,.17,.89);case"indigo":return new B(.29,0,.51);case"darkslateblue":return new B(.28,.24,.55);case"slateblue":return new B(.42,.35,.8);case"mediumslateblue":return new B(.48,.41,.9);case"mediumpurple":return new B(.58,.44,.86);case"darkmagenta":return new B(.55,0,.55);case"darkviolet":return new B(.58,0,.83);case"darkorchid":return new B(.6,.2,.8);case"mediumorchid":return new B(.73,.33,.83);case"thistle":return new B(.84,.75,.85);case"plum":return new B(.87,.63,.87);case"violet":return new B(.93,.51,.93);case"fuchsia":return new B(1,0,1);case"orchid":return new B(.85,.44,.84);case"mediumvioletred":return new B(.78,.08,.52);case"palevioletred":return new B(.86,.44,.58);case"hotpink":return new B(1,.4,.71);case"deeppink":return new B(1,.08,.58);case"lightpink":return new B(1,.71,.76);case"pink":return new B(1,.75,.78);case"antiquewhite":return new B(.98,.92,.84);case"beige":return new B(.96,.96,.86);case"bisque":return new B(1,.89,.77);case"blanchedalmond":return new B(1,.92,.82);case"wheat":return new B(.96,.87,.87);case"cornsilk":return new B(1,.97,.86);case"lemonchiffon":return new B(1,.98,.8);case"lightgoldenrodyellow":return new B(.98,.98,.82);case"lightyellow":return new B(1,1,.8);case"saddlebrown":return new B(.55,.27,.07);case"sienna":return new B(.63,.32,.18);case"chocolate":return new B(.82,.41,.12);case"peru":return new B(.82,.52,.25);case"sandybrown":return new B(.96,.64,.38);case"burlywood":return new B(.87,.72,.53);case"tan":return new B(.82,.71,.55);case"rosybrown":return new B(.74,.56,.56);case"moccasin":return new B(1,.89,.71);case"navajowhite":return new B(1,.87,.68);case"peachpuff":return new B(1,.85,.73);case"mistyrose":return new B(1,.89,.88);case"lavenderblush":return new B(1,.94,.93);case"linen":return new B(.98,.94,.9);case"oldlace":return new B(.99,.96,.9);case"papayawhip":return new B(1,.94,.84);case"seashell":return new B(1,.96,.93);case"mintcream":return new B(.98,1,.98);case"slategray":return new B(.44,.5,.56);case"lightslategray":return new B(.47,.53,.6);case"lightsteelblue":return new B(.69,.77,.87);case"lavender":return new B(.9,.9,.98);case"floralwhite":return new B(1,.98,.98);case"aliceblue":return new B(.94,.97,1);case"ghostwhite":return new B(.97,.97,1);case"honeydew":return new B(.94,1,.94);case"ivory":return new B(1,1,.94);case"azure":return new B(.94,1,1);case"snow":return new B(1,.98,.98);case"dimgray":return new B(.4,.4,.4);case"darkgray":return new B(.66,.66,.66);case"lightgray":return new B(.83,.83,.83);case"gainsboro":return new B(.86,.86,.86);case"whitesmoke":return new B(.96,.96,.96)}return new B(1,1,1)}var Rr=N("debuginputfield"),Y=class extends M{get text(){return this.textComponent?.text??""}get isFocused(){return Y.active===this}textComponent;placeholder;onValueChanged;onEndEdit;inputEventFn;start(){Rr&&console.log(this.name,this)}onEnable(){Y.htmlField||(Y.htmlField=document.createElement("input"),Y.htmlField.classList.add("ar"),document.body.appendChild(Y.htmlField)),this.inputEventFn||(this.inputEventFn=this.onInput.bind(this)),Y.htmlField.addEventListener("keyup",this.inputEventFn),this.placeholder&&this.textComponent?.text.length&&S.setActive(this.placeholder.gameObject,!1)}onDisable(){Y.htmlField?.removeEventListener("keyup",this.inputEventFn),this.onDeselected()}onPointerClick(e){Rr&&console.log("CLICK",e,Y.active),Y.activeTime=this.context.time.time,Y.active!==this&&this.startCoroutine(this.activeLoop(),2),this.selectInputField()}*activeLoop(){for(this.onSelected();Y.active===this&&!(this.context.input.getPointerUp(0)&&this.context.time.time-Y.activeTime>.2);)this.setTextFromInputField(),yield;this.onDeselected()}onSelected(){if(Y.active!==this&&(Rr&&console.log("Select",this.name,this,Y.htmlField,this.context.isInXR,this.context.AROverlayElement,this.textComponent?.text,Y.htmlField?.value),Y.active?.onDeselected(),Y.active=this,this.placeholder&&S.setActive(this.placeholder.gameObject,!1),Y.htmlField)){if(Y.htmlField.value=this.textComponent?.text||"",Rr&&console.log("set input field value",Y.htmlField.value),this.context.isInXR){let e=this.context.AROverlayElement;e&&(Y.htmlField.style.width="0px",Y.htmlField.style.height="0px",e.append(Y.htmlField))}this.selectInputField()}}onDeselected(){Y.active===this&&(Y.active=null,Rr&&console.log("Deselect",this.name,this),Y.htmlField&&(Y.htmlField.blur(),document.body.append(Y.htmlField),Y.htmlField.style.width="",Y.htmlField.style.height=""),this.placeholder&&(!this.textComponent||this.textComponent.text.length<=0)&&S.setActive(this.placeholder.gameObject,!0),this.onEndEdit?.invoke())}onInput(e){if(Y.active===this){if(Rr&&console.log(e.code,e,Y.htmlField?.value,this.textComponent?.text),e.code==="Escape"||e.code==="Enter"){this.onDeselected();return}Y.htmlField&&(this.textComponent&&(this.setTextFromInputField(),this.placeholder&&S.setActive(this.placeholder.gameObject,this.textComponent.text.length<=0)),this.selectInputField())}}setTextFromInputField(){if(this.textComponent&&Y.htmlField){if(this.textComponent.text!==Y.htmlField.value){Rr&&console.log("VALUE CHANGED");let e=this.textComponent.text,t=Y.htmlField.value;this.onValueChanged?.invoke(t,e)}this.textComponent.text=Y.htmlField.value}}selectInputField(){Y.htmlField&&(Y.htmlField.setSelectionRange(Y.htmlField.value.length,Y.htmlField.value.length),Y.htmlField.focus())}},Ct=Y;z(Ct,"active",null),z(Ct,"activeTime",-1),z(Ct,"htmlField",null),k([A(Le)],Ct.prototype,"textComponent",2),k([A(Le)],Ct.prototype,"placeholder",2),k([A(Oe)],Ct.prototype,"onValueChanged",2),k([A(Oe)],Ct.prototype,"onEndEdit",2);import*as ef from"three-mesh-ui";import*as _s from"three";var tf=(s=>(s[s.fr=0]="fr",s[s.ru=1]="ru",s[s.de=2]="de",s[s.es=3]="es",s[s.el=4]="el",s[s.nord=5]="nord",s[s.eng=6]="eng",s))(tf||{}),Do=class extends Ue{font;text;keymap;padding;margin;fontSize;borderRadius;colors={keyboardBack:8750469,panelBack:2500134,button:3552822,hovered:1842204,selected:1088605};awake(){super.awake();let e=tf[this.keymap||6];this.makeKeyboard(e)}onEnable(){this.addShadowComponent(this.keyboard)}onDisable(){this.removeShadowComponent()}keyboard=null;_lastKeyPressed;_lastKeyPressedStartTime=0;_lastKeyPressedTime=0;makeKeyboard(e){!e&&!navigator.language&&(e="en");let t=this.font?this.font:"arial",i=this.gameObject.getComponent(ut);if(!i){console.error("Missing rect transform, please add this component inside a canvas");return}let n={...i.getBasicOptions(),margin:this.margin||0,padding:this.padding||0,language:e,fontFamily:Io+"/"+t+"-msdf.json",fontTexture:Io+"/"+t+".png",fontSize:this.fontSize||6,backgroundColor:new _s.Color(this.colors.keyboardBack),backspaceTexture:Io+"/backspace.png",shiftTexture:Io+"/shift.png",enterTexture:Io+"/enter.png",borderRadius:this.borderRadius||0,autoLayout:!1},r=this.gameObject.scale;n.width*=this.gameObject.scale.x,n.height*=this.gameObject.scale.y,n.fontSize*=Math.max(r.x,r.y),this.keyboard=new ef.Keyboard(n),this.gameObject.scale.set(1,1,1),this.keyboard.keys.forEach(o=>{o.setupState({state:"normal",attributes:{offset:.003,backgroundColor:new _s.Color(this.colors.button),backgroundOpacity:1}}),o.setState("normal"),o.setupState({state:"hovered",attributes:{offset:.3,backgroundColor:new _s.Color(this.colors.hovered),backgroundOpacity:1}}),o.setupState({state:"pressed",attributes:{offset:.1,backgroundColor:new _s.Color(this.colors.selected),backgroundOpacity:1},onSet:()=>{let s=o.info.input,c=o.info.command;if(this._lastKeyPressed!==s)this._lastKeyPressedStartTime=this.context.time.time;else if(this.context.time.time-this._lastKeyPressedTime>.05)this._lastKeyPressedStartTime=this.context.time.time;else if(this.context.time.time-this._lastKeyPressedStartTime<.5||c=="switch"||c=="shift"||c=="switch-set"){this._lastKeyPressedTime=this.context.time.time;return}if(this._lastKeyPressedTime=this.context.time.time,this._lastKeyPressed=s,c)switch(c){case"switch":this.keyboard.setNextPanel();break;case"switch-set":this.keyboard.setNextCharset();break;case"enter":this.tryAppend(`
135
- `);break;case"space":this.tryAppend(" ");break;case"backspace":if(!this.text?.text?.length)break;this.text?.text&&(this.text.text=this.text.text.substring(0,this.text.text.length-1)||"");break;case"shift":this.keyboard.toggleCase();break}else o.info.input!==void 0&&this.tryAppend(o.info.input)}})})}tryAppend(e){this.text&&(this.text.text+=e,this.markDirty())}};var an=class extends M{reverseArrangement=!1},Ho=class extends an{},jo=class extends an{},Bo=class extends an{};var Cr=class extends M{awake(){Ze.createIfNoneExists(this.context)}onEnable(){Ze.instance?.register(this)}onDisable(){Ze.instance?.unregister(this)}performRaycast(e=null){return null}},Si=class extends Cr{targets=null;raycastHits=[];start(){this.targets=[this.gameObject]}performRaycast(e=null){return this.targets?(e??=new je,e.targets=this.targets,e.results=this.raycastHits,this.context.physics.raycast(e)):null}},Fo=class extends Si{eventCamera=null;ignoreReversedGraphics=!1;rootRaycaster=null};import*as nf from"three";import{HTMLMesh as Uy}from"three/examples/jsm/interactive/HTMLMesh.js";import{InteractiveGroup as qy}from"three/examples/jsm/interactive/InteractiveGroup.js";var No=class extends M{id=null;keepAspect=!1;start(){if(!this.id||!this.context.mainCamera)return;let e=document.getElementById(this.id);if(!e){console.warn('Could not find element with id "'+this.id+'"');return}e.style.display="block",e.style.visibility="hidden";let t=new qy(this.context.renderer,this.context.mainCamera);this.gameObject.add(t);let i=new Uy(e);t.add(i),i.visible=!1,console.log(i);let n=i.material;n.transparent=!0,setTimeout(()=>{i.visible=!0;let r=Bs(this.gameObject).clone();Fs(this.gameObject,0,0,0),this.gameObject.updateMatrixWorld();let o=new nf.Box3;o.setFromObject(t),this.setWorldRotation(r.x,r.y,r.z);let s=o.max.x-o.min.x,c=o.max.y-o.min.y;if(this.keepAspect){let a=s/c;s>c?i.scale.set(1/s,1/c/a,1):i.scale.set(1/s*a,1/c,1)}else i.scale.set(1/s,1/c,1);let d=this.gameObject.scale;i.scale.multiply(d)},1)}};var Ja=class extends M{toggleKey=80;update(){this.context.input.isKeyDown(80)&&this.context.domElement.classList.toggle("presentation-mode")}};import*as rf from"three";import{Raycaster as Yy,Vector3 as Zy}from"three";import*as $a from"three";import{MeshLine as Xy,MeshLineMaterial as Qy}from"three.meshline";var yd=class{id=0;points=[];line=new Xy;material;mesh;constructor(e,t){if(t&&(this.material=t.material),this.material||(this.material=this.defaultLineMaterial),t){let i=t.options;i&&Object.assign(this.material,i)}this.mesh=new $a.Mesh(this.line,this.material),e.add(this.mesh)}appendPoint(e){let t=yd.wp;t.set(e.x,e.y,e.z);let i=this.mesh?.parent;return i&&(t=i.worldToLocal(t),e.x=t.x,e.y=t.y,e.z=t.z),this.points.push(e.x,e.y,e.z),this.line.setPoints(this.points),e}defaultLineMaterial=new Qy({color:10066329,lineWidth:.01})},zo=yd;z(zo,"wp",new $a.Vector3);var Sr=class extends M{startLine(e,t){let i=Math.random()*Number.MAX_SAFE_INTEGER;return this.internalStartLine(e,i,!0,t)}updateLine(e,t){let i=this.inFlight[e.id];if(!i)return;t.point&&(t.point=i.appendPoint(t.point));let n=this.buffer[e.id];n&&(t.point&&n.push(t.point.x,t.point.y,t.point.z),n.length>5&&(this.sendLineUpdate(i,!1,void 0,n),n.length=0))}endLine(e,t=!0){let i=this.inFlight[e.id];if(!i)return;this.finished.push(i),delete this.inFlight[e.id],t&&this.sendLineUpdate(i,!0,0);let n=this.buffer[e.id];if(n){delete this.buffer[e.id];let r=n;r.length=0,this.freeBuffer.push(r)}return i}getLine(e){return this.inFlight[e.id]}finished=[];inFlight=[];buffer={};freeBuffer=new Array;awake(){this.context.connection.beginListen("line-start",e=>{this.onEnsureLine(e.id,e.parentGuid)}),this.context.connection.beginListen("line-update",e=>{let t=this.onEnsureLine(e.guid,e.parentGuid);t&&e.points&&(e.startIndex<=0?t.points=e.points:e.startIndex>=t.points.length&&t.points.push(...e.points),t.line.setPoints(t.points),t.material.lineWidth=e.width,t.material.color.fromArray(e.color),e.finished===!0&&this.endLine({id:t.id},!1))})}onEnsureLine(e,t){if(this.inFlight[e])return this.inFlight[e];let i=S.findByGuid(t,this.context.scene);if(!!i)return this.internalStartLine(i,e,!1),this.inFlight[e]}internalStartLine(e,t,i=!0,n){let r=new zo(e??this.context.scene,n);r.id=t,this.inFlight[t]=r,i&&this.sendLineStart(r);let o;return this.freeBuffer.length<=0?o=new Array:o=this.freeBuffer.pop(),this.buffer[t]=o,{id:t}}sendLineStart(e){let t=e.mesh.parent;this.context.connection.send("line-start",{id:e.id,parentGuid:t?t.guid:void 0})}sendLineUpdate(e,t,i,n){if(e){let r={parentGuid:e.mesh.parent.guid,guid:e.id,points:n?[...n]:e.points,width:e.material.lineWidth,color:e.material.color.toArray(),startIndex:i!==void 0?i:e.points.length,finished:t};this.context.connection.send("line-update",r)}}};import{MeshLineMaterial as Jy}from"three.meshline";var Ka=class{isDrawing;lastHit;currentHandle;maxDistance;prevDistance;lastParent;constructor(){this.isDrawing=!1,this.lastHit=new Zy,this.currentHandle=null,this.maxDistance=0,this.prevDistance=0,this.lastParent=null}},el=class extends M{lines;colliders;alignToSurface=!0;addToPaintedObject=!0;orbit;start(){this.lines||(this.lines=S.getComponent(this.gameObject,Sr),this.lines||(this.lines=S.addNewComponent(this.gameObject,Sr))),this.orbit=S.findObjectOfType(gt,this.context)??void 0,this._states.mouse=new Ka;let e={};ae.addEventListener("select-start",(t,i)=>{e[t.controller.uuid]=!0}),ae.addEventListener("update",(t,i)=>{if(e[t.controller.uuid]===!0){let n=t.getRay();this.updateLine(t.controller.uuid,n,!0,!1,!1)}}),ae.addEventListener("select-end",(t,i)=>{e[t.controller.uuid]=!1;let n=t.getRay();this.updateLine(t.controller.uuid,n,!0,!0,!1)})}_states={};update(){this.orbit&&this._states.mouse&&this.orbit&&(this.orbit.enabled=!this._states.mouse.isDrawing);let e=this.context.input.getPointerPressedCount()>1,t=this.context.input.getPointerPositionRC(0);el._raycaster.setFromCamera(t,this.context.mainCamera);let i=el._raycaster.ray;this.updateLine("mouse",i,this.context.input.getPointerPressed(0),this.context.input.getPointerUp(0),e||this.context.input.isKeyPressed(18))}updateLine(e,t,i,n,r=!1){let o=this._states[e];if(o||(this._states[e]=new Ka,o=this._states[e]),n)o.isDrawing=!1,o.currentHandle&&(this.lines.endLine(o.currentHandle),o.currentHandle=null);else if(i){if(r)return o;let s=this.getHit(t),c=null,d=o.prevDistance;if(s)o.currentHandle||(o.maxDistance=s.distance),c=s.point,c.add(s.face.normal.multiplyScalar(.01)),o.prevDistance=s.distance;else if(o.maxDistance>0){let a=o.maxDistance;if(!o.currentHandle&&o.lastHit){let h=q(this.context.mainCamera);a=o.lastHit.distanceTo(h)}c=t.origin.add(t.direction.multiplyScalar(o.maxDistance)),o.prevDistance=o.maxDistance}if(c){if(!o.currentHandle){let a=o.lastParent??this.gameObject;this.addToPaintedObject&&s&&(a=s.object),o.lastParent=a,o.currentHandle=this.lines.startLine(a,{material:this.createRandomMaterial()})}if(this.alignToSurface&&(o.prevDistance>o.maxDistance||Math.abs(d-o.prevDistance)>.2)){let a=o.maxDistance;c=t.origin.add(t.direction.multiplyScalar(a)),o.prevDistance=a}if(o.lastHit&&o.lastHit.distanceTo(c)<o.prevDistance*.01)return o;this.lines.updateLine(o.currentHandle,{point:c}),o.lastHit.copy(c)}o.isDrawing=o.currentHandle!==null}return o}_raycastOptions=new je;getHit(e){(!this.colliders||this.colliders.length===0)&&(this.colliders=[this.gameObject]),this._raycastOptions.targets=this.colliders,this._raycastOptions.ray=e;let t=this.context.physics.raycast(this._raycastOptions);if(t.length>0){for(let i of t)if(!!S.isActiveInHierarchy(i.object))return i}return null}createRandomMaterial(){let e;return this.context.connection.connectionId?e=ht.colorFromHashCode(ht.hashCode(this.context.connection.connectionId)):e=new rf.Color("hsl("+(Math.random()*100).toFixed(0)+", 80%, 30%)"),new Jy({color:e,lineWidth:Q.lerp(.005,.01,Math.random())})}},xs=el;z(xs,"_raycaster",new Yy);import{Object3D as $y}from"three";var Ts=class extends M{asset;joinedRoomFunction;awake(){this.watchTabVisible(),this.joinedRoomFunction=this.onUserJoined.bind(this)}onEnable(){this.context.connection.beginListen("joined-room",this.joinedRoomFunction)}onDisable(){this.context.connection.stopListening("joined-room",this.joinedRoomFunction)}async onUserJoined(e){let t=await this.asset?.instantiateSynced({parent:this.gameObject},!0);if(t){let i=S.getComponent(t,Pi);i&&(i.owner=this.context.connection.connectionId)}}watchTabVisible(){window.addEventListener("visibilitychange",e=>{if(document.visibilityState==="visible")for(let t=Pi.all.length-1;t>=0;t--){let i=Pi.all[t];(!i.owner||!this.context.connection.userIsInRoom(i.owner))&&i.doDestroy()}})}};k([A(tt)],Ts.prototype,"asset",2);var Nt=class extends M{static get all(){return Nt._all}static get local(){return Nt._local}static isLocalPlayer(e){return e instanceof $y?S.getComponentInParent(e,Nt)?.isLocalPlayer??!1:e instanceof ot?S.getComponentInParent(e.gameObject,Nt)?.isLocalPlayer??!1:!1}owner;get isLocalPlayer(){return this.owner===this.context.connection.connectionId}awake(){this.isLocalPlayer&&Nt.local.push(this),Nt.all.push(this),this.context.connection.beginListen("user-left-room",e=>{if(e.userId===this.owner){this.doDestroy();return}})}start(){if(!this.owner||!this.context.connection.userIsInRoom(this.owner)){this.doDestroy();return}}doDestroy(){Lr(this.gameObject,this.context.connection)}onDestroy(){if(Nt.all.splice(Nt.all.indexOf(this),1),this.isLocalPlayer){let e=Nt._local.indexOf(this);e>=0&&Nt._local.splice(e,1)}}},Pi=Nt;z(Pi,"_all",[]),z(Pi,"_local",[]),k([Va(),A()],Pi.prototype,"owner",2);D.add("AlignmentConstraint",_n);D.add("Animation",Jt);D.add("AnimationCurve",sr);D.add("Animator",bt);D.add("AnimatorController",Zt);D.add("AudioListener",$t);D.add("AudioSource",ue);D.add("AvatarModel",ar);D.add("AvatarLoader",xn);D.add("AxesHelper",zi);D.add("BasicIKConstraint",Yr);D.add("BoxHelperComponent",lt);D.add("Camera",ne);D.add("Collider",fi);D.add("SphereCollider",Tn);D.add("BoxCollider",Rn);D.add("InstantiateOptions",ye);D.add("UnityObject",Kr);D.add("DeleteBox",lr);D.add("Deletable",eo);D.add("DeviceFlag",cr);D.add("DragControls",Et);D.add("DropListener",An);D.add("Duplicatable",vi);D.add("CallInfo",yi);D.add("EventListEvent",pr);D.add("EventList",Oe);D.add("EventTrigger",lo);D.add("FlyControls",co);D.add("BoxGizmo",Xi);D.add("GltfExportBox",uo);D.add("GltfExport",jt);D.add("GridHelper",Qi);D.add("GroundProjectedEnv",Yi);D.add("Interactable",kt);D.add("UsageMarker",It);D.add("Light",Ye);D.add("LODModel",Ei);D.add("LODGroup",In);D.add("LookAtConstraint",Fi);D.add("NavMesh",fo);D.add("NavMeshAgent",mo);D.add("NestedGltf",fr);D.add("Networking",pt);D.add("OffsetConstraint",wi);D.add("OrbitControls",gt);D.add("ParticleSystemRenderer",gr);D.add("ParticleSystem",yo);D.add("MainModule",go);D.add("EmissionModule",bo);D.add("ShapeModule",vo);D.add("PlayerColor",ht);D.add("FieldWithDefault",Fr);D.add("Renderer",Te);D.add("MeshRenderer",rr);D.add("SkinnedMeshRenderer",Nr);D.add("InstancingUtil",he);D.add("RendererLightmap",ji);D.add("Rigidbody",ce);D.add("ScreenCapture",Eo);D.add("ShadowCatcher",Mn);D.add("RemoteSkybox",Ln);D.add("SmoothFollow",_i);D.add("SpatialTriggerReceiver",wt);D.add("SpatialTrigger",Zi);D.add("SpectatorCamera",_o);D.add("SpringJoint",xo);D.add("Sprite",br);D.add("SpriteRenderer",Ji);D.add("SyncedCamera",Dn);D.add("SyncedRoom",ti);D.add("SyncedTransform",Qe);D.add("TestRunner",To);D.add("TestSimulateUserData",Ro);D.add("TransformGizmo",vr);D.add("VideoPlayer",nt);D.add("Voip",Ke);D.add("VolumeParameter",Co);D.add("VolumeComponent",xi);D.add("ToneMapping",jn);D.add("ColorAdjustments",Bn);D.add("VolumeProfile",Hn);D.add("Volume",yr);D.add("WebARSessionRoot",Dt);D.add("WebXR",$);D.add("WebAR",On);D.add("AvatarMarker",pe);D.add("WebXRAvatar",Lt);D.add("TeleportTarget",dr);D.add("WebXRController",ae);D.add("AttachedObject",dt);D.add("XRGrabModel",Er);D.add("XRGrabRendering",So);D.add("XRRig",Pn);D.add("VRUserState",Ht);D.add("WebXRSync",qi);D.add("XRState",vt);D.add("XRFlag",Se);D.add("AvatarBlink_Simple",Ti);D.add("AvatarEyeLook_Rotation",Ri);D.add("Avatar_POI",_e);D.add("Avatar_Brain_LookAt",Ui);D.add("Avatar_MouthShapes",Fn);D.add("Avatar_MustacheShake",Po);D.add("LogStats",Oo);D.add("RGBAColor",we);D.add("PlayableDirector",tn);D.add("SignalAsset",wr);D.add("SignalReceiverEvent",_r);D.add("SignalReceiver",$i);D.add("AnimationTrackHandler",Nn);D.add("AudioTrackHandler",zn);D.add("SignalTrackHandler",en);D.add("ControlTrackHandler",Ki);D.add("BaseUIComponent",Ue);D.add("UIRootComponent",nn);D.add("Button",Ft);D.add("Canvas",Je);D.add("CanvasGroup",sn);D.add("EventSystem",Ze);D.add("Graphic",Rt);D.add("MaskableGraphic",rn);D.add("Image",on);D.add("RawImage",Tr);D.add("InputField",Ct);D.add("Keyboard",Do);D.add("LayoutGroup",an);D.add("VerticalLayoutGroup",Ho);D.add("HorizontalLayoutGroup",jo);D.add("GridLayoutGroup",Bo);D.add("PointerEventData",ii);D.add("Raycaster",Cr);D.add("ObjectRaycaster",Si);D.add("GraphicRaycaster",Fo);D.add("Size",Mo);D.add("Rect",xr);D.add("RectTransform",ut);D.add("SpatialHtml",No);D.add("Text",Le);D.add("PresentationMode",Ja);D.add("LinesDrawer",xs);D.add("LineInstanceHandler",zo);D.add("LinesManager",Sr);D.add("PlayerSync",Ts);D.add("PlayerState",Pi);import*as of from"three";import{Color as Ky,Object3D as eE}from"three";var wd=class extends Ni{constructor(){super([Ky,we])}onDeserialize(e){if(e!=null)return e.a!==void 0?new we(e.r,e.g,e.b,e.a):e.alpha!==void 0?new we(e.r,e.g,e.b,e.alpha):new of.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}}},Xj=new wd,_d=class extends Ni{constructor(){super(eE)}onSerialize(e,t){if(t.objectToNode!==void 0&&e.uuid){let i=t.objectToNode[e.uuid];return Ie&&console.log(i,e.name,e.uuid),{node:i}}}onDeserialize(e,t){if(e){if(e.node!==void 0&&t.nodeToObject){let i=t.nodeToObject[e.node];return Ie&&console.log("Deserialized object reference?",e,i,t?.nodeToObject),i||console.warn("Did not find node: "+e.node,t.nodeToObject,t.object),i}else if(e.guid){if(!t.context){console.error("Missing context");return}let i,n=t.gltf?.scene;return n&&(i=S.findByGuid(e.guid,n)),i||(i=S.findByGuid(e.guid,t.context.scene)),i?Ie&&console.log("Deserialized object reference?",e,i,t?.nodeToObject):console.warn("could not resolve reference",e,t.target,t.path,t.context.scene),i}}}},tE=new _d,xd=class extends Ni{constructor(){super([ot,M])}onSerialize(e,t){if(e?.guid)return{guid:e.guid}}onDeserialize(e,t){if(e?.guid){Ie&&console.log(e.guid,t.root,t.object,t.target);let i=this.findObjectForGuid(e.guid,t.root);if(i)return i;if(t.context)return this.findObjectForGuid(e.guid,t.context?.scene)}}findObjectForGuid(e,t){return S.foreachComponent(t,i=>{if(e===i.gameObject.guid)return i.gameObject;if(i.guid===e)return i})}},Ed=new xd,Td=class extends Ni{constructor(){super([Oe])}onSerialize(e,t){console.log("TODO: SERIALIZE EVENT")}onDeserialize(e,t){if(e&&e.type==="EventList"){Ie&&console.log("DESERIALIZE EVENT",e);let i=new Array;for(let o of e.calls){Ie&&console.log(o);let s=Ed.findObjectForGuid(o.target,t.root);!s&&t.context?.scene&&(s=Ed.findObjectForGuid(o.target,t.context?.scene));let c=o.method?.length>0;if(s&&c){let u=()=>console.warn(`Could not find method ${o.method} on object ${s.name}`,s,typeof s[o.method]);if(typeof s[o.method]!="function"){let f=!1;o.method.startsWith("set_")&&o.method.length>4&&(o.method=o.method.substring(4),s[o.method]!==void 0&&(f=!0)),f||u()}}let d,a=o.argument;o.argument!==void 0?(typeof a=="object"&&(a=tE.onDeserialize(o.argument,t),a||(a=Ed.onDeserialize(o.argument,t))),d=new yi(c?(...u)=>h(...u):void 0,o.enabled)):d=new yi(c?(...u)=>h(...u):void 0,o.enabled);let h=(...u)=>{let f=s[o.method];typeof f=="function"?a!==void 0?f?.call(s,a):f?.call(s,...u):s[o.method]=a};if(d.method||(d.__debuginfo=t.object?.name),!s||!d.method){let u=t.object?"Current object: "+t.object.name+", "+t.object.guid:null;s?console.warn('EventList method not found: "'+o.method+'" on',s):console.warn("EventList is missing target - will be ignored",o.target,u,e)}else i.push(d)}let n=new Oe(i);Ie&&console.log(n);let r=t.target;return r!==void 0&&t.path!==void 0&&n.setEventTarget(t.path,r),n}}},Qj=new Td;var sf=Ie;function Op(l,e){let i=Lc(l,e);return i!==void 0?i:null}async function Ca(l,e,t,i=null,n){if(!t)return;let r=[],o=i;typeof o=="number"&&(o=new We(i));let s=new qr(t.scene);s.gltfId=e,s.context=l,s.gltf=t,s.nodeToObject=n?.nodeToObjectMap;let c=[];if(t.scenes)for(let d of t.scenes)await Cd(s,d,c,r);if(t.children)for(let d of t.children)await Cd(s,d,c,r);l.new_scripts_pre_setup_callbacks.push(()=>{for(let d of c)nE(d,s);if(o){Rd(t,o);for(let d of t.scenes)Rd(d,o)}})}function Rd(l,e){if(e!==null&&!!l){if(l.guid=e.generateUUID(),l&&l.userData&&l.userData.components)for(let t of l.userData.components)t!==null&&(t.guid=e.generateUUID());if(l.children)for(let t of l.children)Rd(t,e)}}var Rs=[];async function Cd(l,e,t,i){if(!e)return;let n=e.userData;if(n){let r=n.builtin_components;if(r&&r.length>0)for(let o of r)try{if(o===null)continue;let s=D.get(o.name);if(s!=null){let c=new s;c.sourceId=l.gltfId,ds(c,o),Is(c,e,!1),t.push({instance:c,compData:o,obj:e})}else sf&&console.debug("unknown component: "+o.name),Rs.includes(o.name)||Rs.push(o.name)}catch(s){console.error(o.name+" - "+s.message,s)}if(Rs.length>0){let o=Rs.join(", ");console.warn("unknown components: "+o),Rs.length=0}}if(e.children)for(let r of e.children)await Cd(l,r,t,i)}function nE(l,e){let{instance:t,compData:i,obj:n}=l;e.object=n,e.target=t;let r=!0;r=cs(t,i,e)===!0,sf&&console.debug("add "+i.name,i,t)}import*as me from"three";import*as af from"three";var rE=new af.FileLoader;async function Sd(l){return new Promise((e,t)=>{rE.load(l,e,void 0,t)})}import{Vector4 as Gn,FileLoader as sE,DataTexture as Id,RGBAFormat as aE,Color as lE}from"three";var Cs=new Uint8Array(4);Cs[0]=255;Cs[1]=255;Cs[2]=255;Cs[3]=255;var df=new Id(Cs,1,1,aE);function hf(l,e=1){let t="alpha"in l,i=e*e,n=new Uint8Array(4*i),r=Math.floor(l.r*255),o=Math.floor(l.g*255),s=Math.floor(l.b*255);for(let d=0;d<i;d++){let a=d*4;n[a+0]=r,n[a+1]=o,n[a+2]=s,t?n[a+3]=Math.floor(l.alpha*255):n[a+3]=255}let c=new Id(n,e,e);return c.needsUpdate=!0,c}function uf(l,e,t,i=1,n=3){let s=i*n,c=[l,e,t],d=c.length,a=new Uint8Array(4*d*s),h=new lE;for(let f=0;f<n;f++){let E=Math.floor(f/n*d),b=Q.clamp(E+1,0,d-1),y=c[E],g=c[b],p=f/n*d%1;h.lerpColors(y,g,p);let m=Math.floor(h.r*255),v=Math.floor(h.g*255),w=Math.floor(h.b*255);for(let x=0;x<i;x++){let T=(f*i+x)*4;a[T+0]=m,a[T+1]=v,a[T+2]=w,a[T+3]=255}}let u=new Id(a,i,n);return u.needsUpdate=!0,u}var Od=class{stage;code;constructor(e,t){this.stage=e,this.code=t}},Ad=class{loaded=new Map;async loadShader(e){let t=await Sd(e);return JSON.parse(t)}async load(e,t){if(this.loaded.has(t))return new Promise((r,o)=>{let s=this.loaded.get(t);s?r(s):o("Shader not found")});let i=await Sd(t),n=new Od(e,i);return this.loaded.set(t,n),n}},lB=new Ad;function Ss(l,e){let t=l.elements;e||(e=[]),e.length=0;for(let i=0;i<16;i+=4){let n=t[i],r=t[i+1],o=t[i+2],s=t[i+3],c=new Gn(n,r,o,s);e.push(c)}return e}var Pd=[],lf=[];function Md(l,e){if(Pd.length===0)for(let t=0;t<27;t++)Pd.push(0);e||(e=Pd);for(let t=0;t<27;t++)lf[t]=e[t];e=lf,l.unity_SHAr={value:new Gn(e[9],e[3],e[6],e[0])},l.unity_SHBr={value:new Gn(e[12],e[15],e[18],e[21])},l.unity_SHAg={value:new Gn(e[10],e[4],e[7],e[1])},l.unity_SHBg={value:new Gn(e[13],e[16],e[19],e[22])},l.unity_SHAb={value:new Gn(e[11],e[5],e[8],e[2])},l.unity_SHBb={value:new Gn(e[14],e[17],e[20],e[23])},l.unity_SHC={value:new Gn(e[24],e[25],e[26],1)}}var kd=class{vertexShader;fragmentShader;technique;constructor(e,t,i){this.vertexShader=e,this.fragmentShader=t,this.technique=i}};async function pf(l,e){if(!l)return console.error("Can not find technique: no shader data"),null;let t=l.programs[e],i=t.vertexShader,n=t.fragmentShader;if(i!==void 0&&n!==void 0){let r=l.shaders[i],o=l.shaders[n];if(r.uri&&o.uri||r.code&&o.code){if(!r.code&&r.uri&&await cf(r),!o.code&&o.uri&&await cf(o),!r.code||!o.code)return null;let s=l.techniques[e];return new kd(r.code,o.code,s)}}return console.error("Shader technique not found",e),null}async function cf(l){let e=l.uri;if(!!e)if(e.endsWith(".glsl")){let i=await new sE().loadAsync(e);l.code=i.toString()}else l.code=cE(l.uri)}function cE(l){return decodeURIComponent(Array.prototype.map.call(atob(l),function(e){return"%"+("00"+e.charCodeAt(0).toString(16)).slice(-2)}).join(""))}import{RawShaderMaterial as hE}from"three";var ln=N("debugshaders"),Go="NEEDLE_techniques_webgl";var Ld=class{objectToWorldMatrix=new me.Matrix4;worldToObjectMatrix=new me.Matrix4;objectToWorld=new Array;worldToObject=new Array;updateFrom(e){this.objectToWorldMatrix.copy(e.matrixWorld),Ss(this.objectToWorldMatrix,this.objectToWorld),this.worldToObjectMatrix.copy(e.matrixWorld).invert(),Ss(this.worldToObjectMatrix,this.worldToObject)}};var fe=class extends hE{identifier;onBeforeRenderSceneCallback=this.onBeforeRenderScene.bind(this);constructor(e,...t){super(...t),this.identifier=e,ln&&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}ln&&console.log(t);let i=t.array,n=t.texture;this.uniforms.unity_SpecCube0={value:n},Md(this.uniforms,i);let r=Math.sqrt(Math.PI*.5);this.uniforms.unity_SpecCube0_HDR={value:new me.Vector4(r,r,r,r)},ln&&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 Ld;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,i,n,r,o){n.attributes.tangent||n.computeTangents(),this.onUpdateUniforms(i,r)}onUpdateUniforms(e,t){let i=Z.Current;e&&(fe.viewProjection&&this.uniforms[this._viewProjectionName]&&(fe.viewProjection.copy(e.projectionMatrix).multiply(e.matrixWorldInverse),Ss(fe.viewProjection,fe._viewProjectionValues)),fe.viewMatrix&&this.uniforms[this._viewMatrixName]&&(fe.viewMatrix.copy(e.matrixWorldInverse),Ss(fe.viewMatrix,fe._viewMatrixValues)),this.uniforms[fe._worldSpaceCameraPosName]&&fe._worldSpaceCameraPos.setFromMatrixPosition(e.matrixWorld)),this.uniforms._TimeParameters&&(this.uniforms._TimeParameters.value=i.rendererData.timeVec4);let n=i?.mainLight;if(n){let s=n.getWorldPosition(fe._mainLightPosition);this.uniforms._MainLightPosition={value:s.normalize()},fe._mainLightColor.set(n.color.r,n.color.g,n.color.b,0),this.uniforms._MainLightColor={value:fe._mainLightColor};let c=n.intensity;fe._lightData.z=c,this.uniforms.unity_LightData={value:fe._lightData}}if(e&&(fe.viewProjection&&this.uniforms[this._viewProjectionName]&&(this.uniforms[this._viewProjectionName].value=fe._viewProjectionValues),fe.viewMatrix&&this.uniforms[this._viewMatrixName]&&(this.uniforms[this._viewMatrixName].value=fe._viewMatrixValues),this.uniforms[fe._worldSpaceCameraPosName]&&(this.uniforms[fe._worldSpaceCameraPosName]={value:fe._worldSpaceCameraPos}),i.mainCameraComponent)){if(this.uniforms._ProjectionParams){let s=this.uniforms._ProjectionParams.value;s.x=1,s.y=i.mainCameraComponent.nearClipPlane,s.z=i.mainCameraComponent.farClipPlane,s.w=1/s.z,this.uniforms._ProjectionParams.value=s}if(this.uniforms._ZBufferParams){let s=this.uniforms._ZBufferParams.value,c=i.mainCameraComponent;s.x=1-c.farClipPlane/c.nearClipPlane,s.y=c.farClipPlane/c.nearClipPlane,s.z=s.x/c.farClipPlane,s.w=s.y/c.farClipPlane,this.uniforms._ZBufferParams.value=s}if(this.uniforms._ScreenParams){let s=this.uniforms._ScreenParams.value;s.x=i.domWidth,s.y=i.domHeight,s.z=1+1/s.x,s.w=1+1/s.y,this.uniforms._ScreenParams.value=s}}let r=this.depthTextureUniform;r&&(r.value=i.depthTexture);let o=this.opaqueTextureUniform;if(o&&(o.value=i.opaqueColorTexture),t){let s=this._rendererData;s.updateFrom(t),this.uniforms[this._worldToObjectName].value=s.worldToObject,this.uniforms[this._objToWorldName].value=s.objectToWorld}this.uniformsNeedUpdate=!0}},zt=fe;z(zt,"viewProjection",new me.Matrix4),z(zt,"_viewProjectionValues",[]),z(zt,"viewMatrix",new me.Matrix4),z(zt,"_viewMatrixValues",[]),z(zt,"_worldSpaceCameraPosName","_WorldSpaceCameraPos"),z(zt,"_worldSpaceCameraPos",new me.Vector3),z(zt,"_mainLightColor",new me.Vector4),z(zt,"_mainLightPosition",new me.Vector3),z(zt,"_lightData",new me.Vector4);var tl=class{get name(){return Go}parser;identifier;constructor(e,t){this.parser=e,this.identifier=t}loadMaterial(e){let t=this.parser.json.materials[e];if(!t)return ln&&console.log(e,this.parser.json.materials),null;if(!t.extensions||!t.extensions[Go])return ln&&console.log("material "+e+" does not use NEEDLE_techniques_webgl"),null;let i=t.extensions[Go].technique;if(i<0)return null;let n=this.parser.json.extensions[Go];if(!n)return null;ln&&console.log(n);let r=n.techniques[i];return r?new Promise(async(o,s)=>{let c=await pf(n,r.program),d=c?.fragmentShader,a=c?.vertexShader;if(!d||!a)return s();ln&&console.log("loadMaterial",t,c);let h={},u=r.uniforms;for(let y in u){let g=y;switch(g){case"_TimeParameters":let p=new me.Vector4;h[g]={value:p};break;case"hlslcc_mtx4x4unity_MatrixV":case"hlslcc_mtx4x4unity_MatrixVP":h[g]={value:[]};break;case"_MainLightPosition":case"_MainLightColor":case"_WorldSpaceCameraPos":h[g]={value:[0,0,0,1]};break;case"unity_OrthoParams":break;case"unity_SpecCube0":h[g]={value:null};break;default:case"_ScreenParams":case"_ZBufferParams":case"_ProjectionParams":h[g]={value:[0,0,0,0]};break;case"_CameraOpaqueTexture":case"_CameraDepthTexture":h[g]={value:null};break}}let f=!1;if(t.extensions&&t.extensions[Go]){let y=t.extensions[Go];if(y.technique===i){ln&&console.log(t.name,"Material Properties",y);for(let g in y.values){let p=y.values[g];if(typeof p=="string"){if(p.startsWith("textures/")){let m=p.substring(9),v=Number.parseInt(m);if(v>=0){let w=await this.parser.getDependency("texture",v);w&&(w.encoding=me.LinearEncoding,w.needsUpdate=!0),h[g]={value:w};continue}}switch(g){case"alphaMode":p==="BLEND"&&(f=!0);continue}}if(Array.isArray(p)&&p.length===4){h[g]={value:new me.Vector4(p[0],p[1],p[2],p[3])};continue}h[g]={value:p}}}}let E=new zt(this.identifier,{name:t.name??"",uniforms:h,vertexShader:a,fragmentShader:d,lights:!1});switch(h._Cull?.value){case 0:E.side=me.DoubleSide;break;case 1:E.side=me.BackSide;break;case 2:E.side=me.FrontSide;break;default:E.side=me.FrontSide;break}E.transparent=f,f&&(E.depthWrite=!1),Md(h),E.onUpdateUniforms();for(let y in u){let g=y,p=u[y].type;if(h[g]?.value===void 0)switch(p){case 35678:h[g]={value:df},console.warn("Missing/unassigned texture, fallback to white: "+g);break;default:console.warn("TODO: EXPECTED UNIFORM / fallback NOT SET: "+g,u[y]);break}}ln&&console.log(E.uuid,h),o(E)}):null}};import{EXRLoader as uE}from"three/examples/jsm/loaders/EXRLoader";var Dd=N("debugexr"),il=class{constructor(e){this.parser=e,this.name="EXT_texture_exr",Dd&&console.log(e)}loadTexture(e){let t=this.name,i=this.parser,r=i.json.textures[e];if(Dd&&console.log("EXT_texture_exr.loadTexture",e,r),!r.extensions||!r.extensions[t])return null;let o=r.extensions[t],s=new uE(i.options.manager);return Dd&&console.log("EXT_texture_exr.loadTexture",o,s),i.loadTextureImage(e,o.source,s)}};var ff="NEEDLE_gameobject_data",nl=class{get name(){return ff}parser;constructor(e){this.parser=e}afterRoot(e){let t=[];for(let i=0;i<this.parser.json.nodes.length;i++){let n=this.parser.json.nodes[i];if(n&&n.extensions){let r=n.extensions[ff];if(r){let o=this.findAndApplyExtensionData(i,r);t.push(o)}}}return Promise.all(t).then(()=>{})}async findAndApplyExtensionData(e,t){let i=await this.parser.getDependency("node",e);i&&this.applyExtensionData(i,t)}applyExtensionData(e,t){e.userData.layer=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{FloatType as pE,HalfFloatType as fE,sRGBEncoding as mE}from"three";var mf="NEEDLE_lightmaps",gE=N("debuglightmapsextension"),Ps=(i=>(i[i.Lightmap=0]="Lightmap",i[i.Skybox=1]="Skybox",i[i.Reflection=2]="Reflection",i))(Ps||{}),rl=class{get name(){return mf}parser;registry;source;constructor(e,t,i){this.parser=e,this.registry=t,this.source=i}afterRoot(e){let t=this.parser.json.extensions;if(t){let i=t[mf];if(i){let n=i.textures;return n.length?(gE&&console.log(i),new Promise(async(r,o)=>{let s=[];for(let c of n)if(c.pointer){let d=Ur(this.parser,c.pointer).then(a=>{let h=a;h?.isTexture&&(this.registry?(c.type!==0&&(h.encoding=mE),(h.type==pE||h.type==fE)&&(h.flipY=!0),this.registry.registerTexture(this.source,c.type,h,c.index)):console.log(Ps[c.type],c.pointer,h))});s.push(d)}await Promise.all(s),r()})):null}}return null}};import{AmbientLight as EE,Color as gf,HemisphereLight as wE}from"three";import{Vector4 as bE,EquirectangularReflectionMapping as ol,sRGBEncoding as sl,WebGLCubeRenderTarget as vE}from"three";import{LightProbeGenerator as yE}from"three/examples/jsm/lights/LightProbeGenerator.js";var Hd=N("debugenvlight"),Bd=(n=>(n[n.Skybox=0]="Skybox",n[n.Trilight=1]="Trilight",n[n.Flat=3]="Flat",n[n.Custom=4]="Custom",n))(Bd||{});var al=class{context;constructor(e){this.context=e,this.context.pre_update_callbacks.push(this.preUpdate.bind(this))}sceneLightSettings;preUpdate(){let e=this.context.time;this._timevec4.x=e.time,this._timevec4.y=Math.sin(e.time),this._timevec4.z=Math.cos(e.time),this._timevec4.w=e.deltaTime}_timevec4=new bE;get timeVec4(){return this._timevec4}get environmentIntensity(){return this.sceneLightSettings?this.sceneLightSettings.ambientIntensity:1}registerSceneLightSettings(e){this.sceneLightSettings=e}registerReflection(e,t){let i=new jd(this.context,t,1);this._lighting[e]=i}getReflection(e){return this._lighting[e]}enableReflection(e){switch(Hd&&console.log(this.sceneLightSettings?Bd[this.sceneLightSettings.ambientMode]:"Unknown ambient mode"),this.sceneLightSettings?.ambientMode){case 0:case 4:let t=this.getReflection(e);if(t&&t.Source){let i=this.context.scene,n=t.Source;n.encoding=sl,n.mapping=ol,i.environment=n;return}break}if(this.sceneLightSettings?.environmentReflectionSource===1)switch(this.sceneLightSettings?.ambientMode){case 1:if(this.sceneLightSettings.ambientTrilight){let t=this.sceneLightSettings.ambientTrilight,i=uf(t[0],t[1],t[2],64,64);i.encoding=sl,i.mapping=ol,this.context.scene.environment=i}else console.error("Missing ambient trilight",this.sceneLightSettings.sourceId);return;case 3:if(this.sceneLightSettings.ambientLight){let t=hf(this.sceneLightSettings.ambientLight,64);t.encoding=sl,t.mapping=ol,this.context.scene.environment=t}else console.error("Missing ambientlight",this.sceneLightSettings.sourceId);return;default:return}}disableReflection(){let e=this.context.scene;e.environment=null}async getSceneLightingData(e){return Hd&&console.log("GET SCENE LIGHT DATA"),this._waitPromise?this._waitPromise:(this._waitPromise=new Promise((t,i)=>{let n=setInterval(async()=>{let r=this.getReflection(e);r&&(clearInterval(n),t(r.getSphericalHarmonicsArray(this.sceneLightSettings?.ambientIntensity??1)))},10)}),this._waitPromise)}_waitPromise;_lighting={}},jd=class{get Source(){return this._source}get Array(){return this._sphericalHarmonicsArray}_context;_source;_sphericalHarmonics=null;_sphericalHarmonicsArray;_ambientScale=1;_lightProbe;constructor(e,t,i=1){this._context=e,this._source=t,this._ambientScale=i,t.mapping=ol,t.encoding=sl}getSphericalHarmonicsArray(e=1){if(this._sphericalHarmonicsArray?.length&&this._source)return{array:this._sphericalHarmonicsArray,texture:this._source,lightProbe:this._lightProbe};try{let t=this._source,i=null;if(t){Hd&&console.log("GENERATING LIGHT PROBE",t);let n=Math.min(t.image.width,512);i=new vE(n).fromEquirectangularTexture(this._context.renderer,t),this._source=i.texture}if(this._sphericalHarmonicsArray=[],i){let n=yE.fromCubeRenderTarget(this._context.renderer,i);this._lightProbe=n;let r=this._ambientScale*(e*e*Math.PI*.5)-1;this._sphericalHarmonics=n.sh,this._sphericalHarmonicsArray=this._sphericalHarmonics.toArray();let o=e/(Math.PI*.5);for(let s=0;s<this._sphericalHarmonicsArray.length;s++)this._sphericalHarmonicsArray[s]*=o;if(n.sh.scale(r),this._source)return{array:this._sphericalHarmonicsArray,texture:this._source,lightProbe:n}}}catch(t){console.error(t)}return null}};var bf="NEEDLE_lighting_settings",Os=N("debugenvlight"),ll=class{get name(){return bf}parser;sourceId;context;constructor(e,t,i){this.parser=e,this.sourceId=t,this.context=i}afterRoot(e){let t=this.parser.json.extensions;if(t){let i=t[bf];if(i){Os&&console.log(i);let n=S.addNewComponent(e.scene,Fd,!1);n.sourceId=this.sourceId,n.ambientIntensity=i.ambientIntensity,n.ambientLight=new gf().fromArray(i.ambientLight),Array.isArray(i.ambientTrilight)&&(n.ambientTrilight=i.ambientTrilight.map(r=>new gf().fromArray(r))),n.ambientMode=i.ambientMode,n.environmentReflectionSource=i.environmentReflectionSource,this.context&&this.context.rendererData.registerSceneLightSettings(n)}}return null}},Fd=class extends M{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)}Os&&window.addEventListener("keydown",e=>{switch(e.key){case"l":this.enabled=!this.enabled;break}})}onEnable(){let e=this.context.mainCameraComponent?.sourceId===this.sourceId;if(Os&&console.log("enable",this.sourceId,e,this,this.context.mainCameraComponent?.sourceId),this.ambientMode==3)this.ambientLight&&(this._ambientLightObj=new EE(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],i=this.ambientTrilight[this.ambientTrilight.length-1],n=new wE(i,t,this.ambientIntensity);this.gameObject.add(n)}}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=>{Os&&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(){Os&&console.log("disable",this.sourceId,this),this._lightProbeObj&&this._lightProbeObj.removeFromParent(),this.sourceId&&this.context.rendererData.disableReflection()}};function zd(l){let e=new ho;return l.register(t=>(e.parser=t,e)),e}var Nd=class{resolvePath(e){return e.includes("/extensions/builtin_components/")&&(e=e.replace("/extensions/builtin_components/","/userData/components/")),e}};function Gd(l,e,t){l.register(n=>new nl(n)),l.register(n=>new ba(n)),l.register(n=>new rl(n,e.lightmaps,t)),l.register(n=>new ll(n,t,e)),l.register(n=>new tl(n,t)),l.register(n=>new ir(n,t)),l.register(n=>new Bi(n,t,e)),l.register(n=>new il(n));let i=l.setAnimationPointerResolver;typeof i=="function"&&i.bind(l)(new Nd)}var _E=N("printGltf");var Vn=class{context;loader;path;gltf;constructor(e,t,i,n){this.context=e,this.path=t,this.loader=i,this.gltf=n}},vf={};function Vo(l,e){if(vf[l])for(let t of vf[l])t(e)}async function Ef(l,e,t,i,n){_E&&console.log(t),await l.assets.registerGltf(t),await Ca(l,e,t,i,n)}function Qr(l,e,t,i){typeof t!="string"&&console.warn("Parse gltf binary without path, this might lead to errors in resolving extensions. Please provide the source path of the gltf/glb file",t,typeof t);let n=new yf;Gd(n,l,t);let o=zd(n);return new Promise((s,c)=>{try{nr(n,l),Vo(0,new Vn(l,t,n)),n.parse(e,t,async d=>{Vo(1,new Vn(l,t,n,d)),await Ef(l,t,d,i,o),Vo(10,new Vn(l,t,n,d)),s(d)},d=>{console.error("failed loading "+t,d),s(void 0)})}catch(d){console.error(d),c(d)}})}function ur(l,e,t,i=!1,n){let r=new yf;Gd(r,l,e);let s=zd(r);return new Promise((c,d)=>{try{nr(r,l),Vo(0,new Vn(l,e,r)),r.load(e,async a=>{Vo(1,new Vn(l,e,r,a)),await Ef(l,e,a,t,s),Vo(10,new Vn(l,e,r,a)),c(a)},a=>{n?.call(r,a)},a=>{console.error("failed loading "+e,a),c(void 0)})}catch(a){console.error(a),d(a)}})}import*as Wn from"three";function cl(l,e,t){let i=S.getComponentInChildren(l,Et);if(i||(i=S.addNewComponent(l,Et,!1),i.guid=e.generateUUID()),i&&!S.getComponent(i.gameObject,Qe)){let r=S.addNewComponent(i.gameObject,Qe,!1);r.guid=e.generateUUID()}if(i&&!S.getComponentInParent(i.gameObject,Si)){let r=S.addNewComponent(i.gameObject,Si,!1);r.guid=e.generateUUID()}if(t&&t.animations?.length>0){let r=t.animations[0],o=S.addNewComponent(l,Jt,!1);o.animations=[r]}let n=!1;l.traverse(r=>{!r||r.isSkinnedMesh===!0&&(n||console.log("Disabling frustum culling for skinned meshes",t),n=!0,r.frustumCulled=!1)})}var Vd=class{guid;file_name;file_hash;file_size;position;seed;sender;serverUrl;parentGuid;boundsSize;constructor(e,t,i,n,r,o,s,c){this.seed=t,this.guid=i,this.file_name=n,this.file_hash=r,this.file_size=o,this.position=s,this.sender=e,this.serverUrl=c}};async function xp(l,e,t){let i=l.name;return i.endsWith(".gltf")||i.endsWith(".glb")?new Promise((n,r)=>{let o=new FileReader;o.readAsDataURL(l),o.onloadend=async s=>{let c=o.result,d=Vs(),a=new We(d),h=await ur(e,c,a,!0);if(h&&h.scene){let u=h.scene;if(!u.guid){let f=new We(d);u.guid=f.generateUUID()}t&&TE(e.connection,l,d,u,t),cl(u,a,h),n(h)}}}):(console.warn("Unsupported file type: "+i),console.log(l),null)}async function Tp(l,e){return new Promise(async(t,i)=>{let n=Vs(),r=new We(n),o=await ur(e,l.toString(),r,!0);if(o&&o.scene){let s=o.scene;cl(s,r,o),t(o)}else console.warn("Unsupported file type: "+l.toString())})}function wf(l){l.connection.beginListen("file-spawned",async e=>{if(e.sender!==l.connection.connectionId){console.log("received file event",e),RE(e,l);let t=null;try{t=await Ta(e.file_name,e.file_hash,e.file_size,e.serverUrl)}finally{CE(e,l)}if(t){let i=new We(e.seed),n=await Qr(l,t,null,i);if(n&&n.scene){let r=n.scene;if(cl(r,i,n),e.parentGuid){let o=S.findByGuid(e.parentGuid,l.scene);"add"in o&&o.add(r)}r.parent||l.scene.add(r),e.position!==null&&r.position.copy(e.position)}}else console.error("download didnt return file")}})}async function TE(l,e,t,i,n){if(!l.connectionId){console.error("Can not upload file - no connection id");return}if(!i.guid){console.error("Can not upload file - no guid",i,i.guid);return}let r=await dp(e,n);if(!r)return;if(!r.filename){console.error("Can not send upload event - no filename",e.name);return}if(!r.hash){console.error("Can not send upload event - no hash",e.name);return}let o=new Vd(l.connectionId,t,i.guid,r.filename,r.hash,e.size,i.position,r.url??n);i.parent&&(o.parentGuid=i.parent.guid),l.send("file-spawned",o)}var Wd={};function RE(l,e){let t=new Wn.BoxGeometry,i=new Wn.Mesh(t,new Wn.MeshBasicMaterial({color:65280})),n=new Wn.BoxHelper(i,5592405);if(Wd[l.guid]=n,e.scene.add(n),l.parentGuid){let r=S.findByGuid(l.parentGuid,e.scene);r&&r.add(n)}l.position&&n.position.copy(l.position)}function CE(l,e){let t=l.guid,i=Wd[t];i&&(delete Wd[t],i.removeFromParent())}import*as _f from"three";var vF=N("debugassets");var dl=class{constructor(){window.addEventListener("unhandledrejection",e=>{if(e.defaultPrevented)return;let t=e?.reason?.path;if(t){let i=t[0];i&&i.tagName==="IMG"&&(console.warn(`Could not load image:
134
+ `)}}}applyShadowMaterial(){let e=S.getComponent(this.gameObject,Te);if(e)if(e.material?.type!=="ShadowMaterial"){let t=new dy;t.color=this.shadowColor,t.opacity=this.shadowColor.alpha,this.applyMaterialOptions(t),e.material=t}else{let t=e.material;t.color=this.shadowColor,t.opacity=this.shadowColor.alpha,this.applyMaterialOptions(t)}}applyMaterialOptions(e){e&&(e.depthWrite=!1,e.stencilWrite=!1)}};k([A()],Mn.prototype,"mode",2),k([A(we)],Mn.prototype,"shadowColor",2);import{RGBELoader as fy}from"three/examples/jsm/loaders/RGBELoader.js";import{EXRLoader as my}from"three/examples/jsm/loaders/EXRLoader";import{EquirectangularRefractionMapping as gy}from"three";var Hp=N("debugautosync"),ld=class{_syncers={};getOrCreateSyncer(e){if(!e.guid)return null;if(this._syncers[e.guid])return this._syncers[e.guid];let t=new cd(e);return this._syncers[e.guid]=t,t}},jp=new ld,cd=class{comp;constructor(e){this.comp=e}hasChanges=!1;changedProperties={};data={};_boundEvent;get networkingKey(){return this.comp.constructor.name}_isReceiving=!1;_isInit=!1;init(e){if(this._isInit)return;this._isInit=!0,this.comp=e,this._boundEvent=this.onHandleSending.bind(this),this.comp.context.post_render_callbacks.push(this._boundEvent),this.comp.context.connection.beginListen(this.networkingKey,this.onHandleReceiving.bind(this));let t=this.comp.context.connection.tryGetState(this.comp.guid);t&&this.onHandleReceiving(t)}notifyChanged(e,t){this._isReceiving||(this.hasChanges=!0,this.changedProperties[e]=t)}onHandleSending(){if(!this.hasChanges)return;this.hasChanges=!1;let e=this.comp.context.connection;if(!e||!e.isConnected){for(let t in this.changedProperties)delete this.changedProperties[t];return}for(let t in this.data)delete this.data[t];this.data.guid=this.comp.guid;for(let t in this.changedProperties){let i=this.changedProperties[t];delete this.changedProperties[t],this.data[t]=i}e.send(this.networkingKey,this.data)}onHandleReceiving(e){if(!this._isInit||!this.comp)return;let t=e.guid;if(!(t&&t!==this.comp.guid)){Hp&&console.log("RECEIVED",this.comp.name,this.comp.guid,e);try{this._isReceiving=!0;for(let i in e){if(i==="guid")continue;let n=e[i];this.comp[i]=n}}catch(i){console.error(i)}finally{this._isReceiving=!1}}}};function uy(l,e){let t=e!==l;if(!t&&l&&e){if(Array.isArray(l)&&Array.isArray(e))t=!0;else if(typeof l=="object"&&typeof e=="object"){for(let i of Object.keys(l))if(l[i]!==e[i]){t=!0;break}}}return t}function py(l){if(l.__autoPropertySyncHandler)return l.__autoPropertySyncHandler;let e=jp.getOrCreateSyncer(l);return e?.init(l),l.__autoPropertySyncHandler=e,e}var Va=function(l){return function(e,t){let i=null,n=l?e[l]:void 0,r=e,o=r.__internalAwake;Hp&&console.log(t);let s=t+"k__BackingField";r.__internalAwake=function(){if(this[s]!==void 0)return;this[s]=this[t],o.call(this),i=jp.getOrCreateSyncer(this),Object.getOwnPropertyDescriptor(this,t)?.set===void 0&&Object.defineProperty(this,t,{set:function(d){let a=this[s];this[s]=d,uy(d,a)&&n?.call(this,d,a)!==!1&&py(this)?.notifyChanged(t,d)},get:function(){return this[s]},configurable:!0,enumerable:!0}),i?.init(this)}}};var Ln=class extends M{url;allowDrop=!0;_loader;_prevLoadedEnvironment;_prevEnvironment=null;_prevBackground=null;onEnable(){this.setSkybox(this.url),this.registerDropEvents()}onDisable(){this.context.scene.environment===this._prevLoadedEnvironment&&(this.context.isInXR||(this.context.scene.environment=this._prevEnvironment,this.context.scene.background=this._prevBackground),this._prevLoadedEnvironment=void 0),this.unregisterDropEvents()}async setSkybox(e){if(!e)return;if(!e?.endsWith(".hdr")&&!e.endsWith(".exr")&&console.warn("Potentially invalid skybox url",this.url,"on",this.name),!this._loader){let n=e.endsWith(".exr");this._loader=n?new my:new fy}let t=await this._loader.loadAsync(e);if(!t||!this.enabled)return;this.url=e,t.mapping=gy,this._prevBackground=this.context.scene.background,this._prevEnvironment=this.context.scene.environment,console.log("Set skybox",this.url),this.context.scene.environment=t,this.context.scene.background=t,this._prevLoadedEnvironment=t;let i=e.lastIndexOf("/");t.name=e.substring(i>=0?i+1:0)}dragOverEvent;dropEvent;registerDropEvents(){this.dragOverEvent||(this.dragOverEvent=e=>{if(!!this.allowDrop&&!!e.dataTransfer)for(let t of e.dataTransfer.types)t==="text/uri-list"&&e.preventDefault()},this.dropEvent=e=>{if(!!this.allowDrop&&(e.preventDefault(),!!e.dataTransfer)){for(let t of e.dataTransfer.types)if(t==="text/uri-list"){let i=e.dataTransfer.getData(t);console.log(t,i);let n=new RegExp(/polyhaven.com\/asset_img\/.+?\/(?<name>.+)\.png/).exec(i)?.groups?.name;if(n||(n=new RegExp(/polyhaven\.com\/a\/(?<name>.+)/).exec(i)?.groups?.name),console.log(n),n){let r="https://dl.polyhaven.org/file/ph-assets/HDRIs/exr/1k/"+n+"_1k.exr";this.setSkybox(r)}else console.warn("Could not resolve skybox name from dropped url",i)}}},this.context.domElement.addEventListener("dragover",this.dragOverEvent),this.context.domElement.addEventListener("drop",this.dropEvent))}unregisterDropEvents(){!this.dragOverEvent||(this.context.domElement.removeEventListener("dragover",this.dragOverEvent),this.context.domElement.removeEventListener("drop",this.dropEvent))}};k([Va("setSkybox"),A()],Ln.prototype,"url",2),k([A()],Ln.prototype,"allowDrop",2);import*as wo from"three";import{Object3D as by}from"three";var dd=class extends M{target=null;followFactor=.1;rotateFactor=.1;flipForward=!1;_firstUpdate=!0;onEnable(){let e=S.getComponentInChildren(this.gameObject,ne);e&&e.cam&&(e.gameObject.position.set(0,0,0),e.cam.position.set(0,0,0),e.gameObject.quaternion.identity(),e.cam.quaternion.setFromEuler(new wo.Euler(0,Math.PI,0)))}onBeforeRender(){this.followFactor<=0||this.updateNow(!1)}updateNow(e){if(!(!this.target||this.target===this.gameObject)){if(this.followFactor>0){let t=q(this.target),i=this._firstUpdate||e?1:Q.clamp01(this.context.time.deltaTime*this.followFactor);this.worldPosition=this.worldPosition.lerp(t,i)}if(this.rotateFactor>0){let t=ve(this.target);this.flipForward&&t.premultiply(dd._invertForward);let i=this._firstUpdate||e?1:Q.clamp01(this.context.time.deltaTime*this.rotateFactor);this.worldQuaternion=this.worldQuaternion.slerp(t,i)}this._firstUpdate=!1}}},_i=dd;z(_i,"_invertForward",new wo.Quaternion().setFromAxisAngle(new wo.Vector3(0,1,0),Math.PI)),k([A(by)],_i.prototype,"target",2);import{Layers as Np}from"three";var Wa=N("debugspatialtrigger"),Bp=new Np,Fp=new Np;function vy(l,e){return Bp.mask=l,Fp.mask=e,Bp.test(Fp)}var wt=class extends M{triggerMask=0;onEnter;onStay;onExit;start(){Wa&&console.log(this.name,this.triggerMask,this)}update(){this.currentIntersected.length=0;for(let e of Zi.triggers)vy(e.triggerMask,this.triggerMask)&&e.test(this.gameObject)&&this.currentIntersected.push(e);for(let e=this.lastIntersected.length-1;e>=0;e--){let t=this.lastIntersected[e];this.currentIntersected.indexOf(t)<0&&(this.onExitTrigger(t),this.lastIntersected.splice(e,1))}for(let e of this.currentIntersected)this.lastIntersected.indexOf(e)<0&&this.onEnterTrigger(e),this.onStayTrigger(e);this.lastIntersected.length=0,this.lastIntersected.push(...this.currentIntersected)}currentIntersected=[];lastIntersected=[];onEnterTrigger(e){Wa&&console.log("ENTER TRIGGER",this.name,e.name,this,e),e.raiseOnEnterEvent(this),this.onEnter?.invoke(this,e)}onExitTrigger(e){Wa&&console.log("EXIT TRIGGER",this.name,e.name,this,e),e.raiseOnExitEvent(this),this.onExit?.invoke(this,e)}onStayTrigger(e){e.raiseOnStayEvent(this),this.onStay?.invoke(this,e)}};k([A()],wt.prototype,"triggerMask",2),k([A(Oe)],wt.prototype,"onEnter",2),k([A(Oe)],wt.prototype,"onStay",2),k([A(Oe)],wt.prototype,"onExit",2);var ys=class extends M{triggerMask;boxHelper;start(){Wa&&console.log(this.name,this.triggerMask,this)}onEnable(){ys.triggers.push(this),this.boxHelper||(this.boxHelper=S.addNewComponent(this.gameObject,lt),this.boxHelper?.showHelper())}onDisable(){ys.triggers.splice(ys.triggers.indexOf(this),1)}test(e){return this.boxHelper?this.boxHelper.isInBox(e)??!1:!1}raiseOnEnterEvent(e){S.foreachComponent(this.gameObject,t=>{t!==e&&t instanceof wt&&t.onEnterTrigger(this)},!1)}raiseOnStayEvent(e){S.foreachComponent(this.gameObject,t=>{t!==e&&t instanceof wt&&t.onStayTrigger(this)},!1)}raiseOnExitEvent(e){S.foreachComponent(this.gameObject,t=>{t!==e&&t instanceof wt&&t.onExitTrigger(this)},!1)}},Zi=ys;z(Zi,"triggers",[]),k([A()],Zi.prototype,"triggerMask",2);import*as Bt from"three";var _o=class extends M{cam=null;_firstPersonMode=!0;get firstPersonMode(){return this._firstPersonMode??!1}set firstPersonMode(e){this._firstPersonMode=e}enableFirstPersonMode(){this._firstPersonMode=!0,this.updateUI(),this.cam&&(this.firstPersonFollow&&(this.firstPersonFollow.enabled=!0,this.firstPersonFollow.updateNow(!0)),this.orbit&&(this.orbit.enabled=!1))}enableThirdPersonMode(){this._firstPersonMode=!1,this.updateUI(),this.firstPersonFollow&&(this.firstPersonFollow.enabled=!1),this.cam&&(ie(this.cam.cam,this._orbitStartPos),Ae(this.cam.cam,this._orbitStartRot),ie(this.cam.gameObject,this._orbitStartPos2),Ae(this.cam.gameObject,this._orbitStartRot2),this.orbit&&(this.orbit.enabled=!0,this.orbit.setFromTargetPosition()))}orbit=null;firstPersonFollow=null;spectatorUIDomElement=null;eventSub_WebXRRequestStartEvent=null;eventSub_WebXRStartEvent=null;eventSub_WebXREndEvent=null;awake(){if(S.setActive(this.gameObject,!1),!this.isSupportedPlatform()){console.log("Disable spectator cam",window.navigator.userAgent,this);return}if(this.cam=S.getComponent(this.gameObject,ne),!this.cam){console.error("Spectator camera needs camera component",this);return}let e="#spectator-camera-ui";this.spectatorUIDomElement=this.context.domElement.querySelector(e),this.spectatorUIDomElement||console.warn("Could not find spectator camera UI element",e),this.spectatorUIDomElement?.classList.add("hidden"),this.cam&&(this.cam.enabled=!0,this._orbitStartPos.copy(q(this.cam.cam)),this._orbitStartRot.copy(ve(this.cam.cam)),this._orbitStartPos2.copy(q(this.cam.gameObject)),this._orbitStartRot2.copy(ve(this.cam.gameObject))),this.eventSub_WebXRRequestStartEvent=this.onXRSessionRequestStart.bind(this),this.eventSub_WebXRStartEvent=this.onXRSessionStart.bind(this),this.eventSub_WebXREndEvent=this.onXRSessionEnded.bind(this),$.addEventListener("requestVRSession",this.eventSub_WebXRRequestStartEvent),$.addEventListener("xrStarted",this.eventSub_WebXRStartEvent),$.addEventListener("xrStopped",this.eventSub_WebXREndEvent),this.context.domElement.querySelector("button#toggle-spectator-view")?.addEventListener("click",this.toggleView.bind(this)),this.updateUI()}onDestroy(){$.removeEventListener("requestVRSession",this.eventSub_WebXRStartEvent),$.removeEventListener("xrStarted",this.eventSub_WebXRStartEvent),$.removeEventListener("xrStopped",this.eventSub_WebXREndEvent)}toggleView(){this.firstPersonMode=!this.firstPersonMode}updateUI(){let e=this.context.domElement.querySelector("button#toggle-spectator-view");if(!!e&&(e.disabled=!0,e.firstChild&&(this._sessionHasStarted?e.firstChild.textContent=this.firstPersonMode?"\u{1F441}\uFE0F":"\u{1F4F7}":e.firstChild.textContent="Waiting for VR session"),e.children?.length>1)){let t=e.children[1];t.style.display=this._sessionHasStarted?"block":"none",this.firstPersonMode?t.textContent="First-Person View. See what the person in VR sees":t.textContent="Third-Person View. Freely move the camera around"}}isSupportedPlatform(){let e=window.navigator.userAgent,t=/Windows|MacOS/.test(e),i=/Windows NT/.test(e)&&/Edg/.test(e)&&!/Win64/.test(e);return t&&!i}onXRSessionRequestStart(e){this._sessionHasStarted=!1,this.spectatorUIDomElement?.classList.remove("hidden"),S.setActive(this.gameObject,!0),this.cam&&this.cam.cam&&(ie(this.cam.cam,this._orbitStartPos),Ae(this.cam.cam,this._orbitStartRot),ie(this.cam.gameObject,this._orbitStartPos2),Ae(this.cam.gameObject,this._orbitStartRot2)),this.firstPersonMode?this.enableFirstPersonMode():this.enableThirdPersonMode()}onXRSessionStart(e){if(this._sessionHasStarted=!0,this.updateUI(),this.context.mainCamera){let t=this.context.renderer.xr.getCamera(this.context.mainCamera);this.setupFollowMode(t)}}onXRSessionEnded(e){this._sessionHasStarted=!1,this._firstPersonIsSetup=!1,this.spectatorUIDomElement?.classList.add("hidden"),S.setActive(this.gameObject,!1)}_sessionHasStarted=!1;_firstPersonIsSetup=!1;_orbitStartPos=new Bt.Vector3;_orbitStartRot=new Bt.Quaternion;_orbitStartPos2=new Bt.Vector3;_orbitStartRot2=new Bt.Quaternion;onAfterRender(){if(!this.cam)return;this.context.input.isKeyDown(83)&&(this.firstPersonMode=!this.firstPersonMode),this.updateFollowSettings();let e=this.context.renderer,t=e.xr.enabled;if(!e.xr.isPresenting)return;let i=e.getRenderTarget(),n=null;if(!i){if(!e.state.bindFramebuffer||!e.state.bindXRFramebuffer)return;n=e._framebuffer,e.state.bindXRFramebuffer(null)}this.setAvatarFlagsBeforeRender(),e.setClearColor(new Bt.Color(1,1,1)),e.setRenderTarget(null),e.xr.enabled=!1;let r=this.cam?.cam;this.context.updateAspect(r);let o=e.xr.isPresenting;e.xr.isPresenting=!1,e.setSize(this.context.domWidth,this.context.domHeight),e.render(this.context.scene,r),e.xr.isPresenting=o,e.xr.enabled=t,i?e.setRenderTarget(i):e.state.bindXRFramebuffer(n),this.resetAvatarFlags()}setupFollowMode(e){if(!e||!this.cam||this._firstPersonIsSetup)return;this._firstPersonIsSetup=!0,this.firstPersonFollow=S.addNewComponent(this.cam.gameObject,_i);let t=new Bt.Object3D;e.add(t),t.add(new Bt.AxesHelper(.2)),this.firstPersonFollow.target=t,this.updateFollowSettings();let i=this.context.mainCamera;i&&(this.cam.cam.near=i.near,this.cam.cam.far=i.far,this.cam.cam.updateProjectionMatrix()),this.orbit&&(this.orbit.enabled=!1)}updateFollowSettings(){let e=this.firstPersonFollow?.target;!e||!this.firstPersonFollow||(this.firstPersonMode===!1?(this.firstPersonFollow.followFactor=3,this.firstPersonFollow.rotateFactor=2,this.firstPersonFollow.flipForward=!1,e.position.set(0,.5,1.5),e.quaternion.identity()):(e.position.set(0,0,0),e.quaternion.identity(),this.firstPersonFollow.followFactor=12,this.firstPersonFollow.rotateFactor=5,this.firstPersonFollow.flipForward=!1))}setAvatarFlagsBeforeRender(){for(let e of pe.instances)if(e.avatar&&"isLocalAvatar"in e.avatar){let t=this.firstPersonMode&&this._firstPersonIsSetup&&e.avatar.isLocalAvatar?8:16,i=e.avatar.flags;if(!i)continue;for(let n of i)n.UpdateVisible(t)}}resetAvatarFlags(){for(let e of pe.instances)if(e.avatar&&"flags"in e.avatar){let t=e.avatar.flags;if(!t)continue;for(let i of t)e.avatar?.isLocalAvatar?i.UpdateVisible(8):i.UpdateVisible(16)}}};var xo=class extends M{anchor=null;connectedBody=null;connectedAnchor=null;spring=10;damper=.2;rb=null;awake(){if(this.rb=S.getComponent(this.gameObject,ce),!this.connectedBody||!this.connectedBody.body||!this.rb||!this.rb.body)return;this.connectedBody.body.mass=Math.min(this.rb.body.mass*.99,this.connectedBody.body.mass);let e=new ta(this.rb.body,this.connectedBody.body,{restLength:.01,stiffness:this.spring*.5,damping:this.damper});this.context.physics.addPostStepListener(t=>{e.applyForce()})}update(){}};import*as _t from"three";import{Material as yy,Texture as Ey}from"three";var br=class{texture;triangles;uv;vertices;_geometry};k([A(Ey)],br.prototype,"texture",2);var Ua=class{static getOrCreateGeometry(e){if(e._geometry)return e._geometry;let t=new _t.BufferGeometry;e._geometry=t;let i=new Float32Array(e.triangles.length*3),n=new Float32Array(e.triangles.length*2);for(let r=0;r<e.triangles.length;r+=1){let o=e.triangles[r];i[r*3]=-e.vertices[o].x,i[r*3+1]=e.vertices[o].y,i[r*3+2]=0;let s=e.uv[o];n[r*2]=s.x,n[r*2+1]=1-s.y}return t.setAttribute("position",new _t.BufferAttribute(i,3)),t.setAttribute("uv",new _t.BufferAttribute(n,2)),t}},Ji=class extends M{drawMode=0;size={x:1,y:1};color;sharedMaterial;get sprite(){return this._sprite}set sprite(e){e!==this._sprite&&(this._sprite=e,this.updateSprite())}_sprite;_currentSprite;awake(){this._currentSprite=void 0}start(){this.drawMode===2&&console.warn("Tiled draw mode is not supported yet",this),this._currentSprite?this.gameObject&&this.gameObject.add(this._currentSprite):this.updateSprite()}updateSprite(){if(!!this.__didAwake&&!!this.sprite&&!!this.sharedMaterial){if(this._currentSprite)this._currentSprite.geometry=Ua.getOrCreateGeometry(this.sprite),this._currentSprite.material.map=this.sprite.texture;else{let e=new _t.MeshBasicMaterial({color:16777215,side:_t.DoubleSide});if(!e)return;if(this.color&&(e.color||(e.color=new _t.Color),e.color.copy(this.color),e.opacity=this.color.alpha),e.alphaTest=.5,this.sprite.texture&&!e.wireframe){let t=this.sprite.texture;e.map=t}this._currentSprite=new _t.Mesh(Ua.getOrCreateGeometry(this.sprite),e)}this._currentSprite.parent!==this.gameObject&&(this.drawMode===2&&this._currentSprite.scale.set(this.size.x,this.size.y,1),this.gameObject&&this.gameObject.add(this._currentSprite))}}};k([A()],Ji.prototype,"drawMode",2),k([A(we)],Ji.prototype,"color",2),k([A(yy)],Ji.prototype,"sharedMaterial",2);var xt=class{bb=null;bb_pos=0;__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsSyncedCameraModel(e,t){return(t||new xt).__init(e.readInt32(e.position())+e.position(),e)}static getSizePrefixedRootAsSyncedCameraModel(e,t){return e.setPosition(e.position()+4),(t||new xt).__init(e.readInt32(e.position())+e.position(),e)}userId(e){let t=this.bb.__offset(this.bb_pos,4);return t?this.bb.__string(this.bb_pos+t,e):null}guid(e){let t=this.bb.__offset(this.bb_pos,6);return t?this.bb.__string(this.bb_pos+t,e):null}dontSave(){let e=this.bb.__offset(this.bb_pos,8);return e?!!this.bb.readInt8(this.bb_pos+e):!1}pos(e){let t=this.bb.__offset(this.bb_pos,10);return t?(e||new Ce).__init(this.bb_pos+t,this.bb):null}rot(e){let t=this.bb.__offset(this.bb_pos,12);return t?(e||new Ce).__init(this.bb_pos+t,this.bb):null}static startSyncedCameraModel(e){e.startObject(5)}static addUserId(e,t){e.addFieldOffset(0,t,0)}static addGuid(e,t){e.addFieldOffset(1,t,0)}static addDontSave(e,t){e.addFieldInt8(2,+t,0)}static addPos(e,t){e.addFieldStruct(3,t,0)}static addRot(e,t){e.addFieldStruct(4,t,0)}static endSyncedCameraModel(e){return e.endObject()}static finishSyncedCameraModelBuffer(e,t){e.finish(t)}static finishSizePrefixedSyncedCameraModelBuffer(e,t){e.finish(t,void 0,!0)}};import{Object3D as wy}from"three";var qa="SCAM";Vr(qa,xt.getRootAsSyncedCameraModel);var Tt=new ft,hd=class{userId;guid;constructor(e,t){this.guid=t,this.userId=e}send(e,t){let i=e.cam?.cam;if(i){Tt.clear();let n=Tt.createString(this.guid),r=Tt.createString(this.userId);xt.startSyncedCameraModel(Tt),xt.addGuid(Tt,n),xt.addUserId(Tt,r);let o=q(i),s=Bs(i);xt.addPos(Tt,Ce.createVec3(Tt,o.x,o.y,o.z)),xt.addRot(Tt,Ce.createVec3(Tt,s.x,s.y,s.z));let c=xt.endSyncedCameraModel(Tt);Tt.finish(c,qa),t.sendBinary(Tt.asUint8Array())}}},Dn=class extends M{getUserCamera(e){let t=this.userToCamMap[e];return t?this.remoteCams[t].obj:null}cam=null;cameraPrefab=null;_lastWorldPosition;_lastWorldQuaternion;_model=null;_needsUpdate=!0;_lastUpdateTime=0;remoteCams={};userToCamMap={};_camTimeoutInSeconds=10;_receiveCallback=null;async awake(){this._lastWorldPosition=this.worldPosition.clone(),this._lastWorldQuaternion=this.worldQuaternion.clone(),this.cameraPrefab&&("uri"in this.cameraPrefab&&(this.cameraPrefab=await this.cameraPrefab.instantiate(this.gameObject)),this.cameraPrefab&&"isObject3D"in this.cameraPrefab&&(this.cameraPrefab.visible=!1))}start(){this.cam||(console.warn("Missing camera, fallback to main camera",this),this.cam=this.context.mainCameraComponent??null)}onEnable(){this._receiveCallback=this.context.connection.beginListenBinrary(qa,this.onReceivedRemoteCameraInfoBin.bind(this))}onDisable(){this.context.connection.stopListenBinary(qa,this._receiveCallback)}update(){for(let i in this.remoteCams){let n=this.remoteCams[i],r=this.context.time.realtimeSinceStartup-n.lastUpdate;if(!n||r>this._camTimeoutInSeconds){console.log("Remote cam timeout",n,r),n?.obj&&S.destroy(n.obj),delete this.remoteCams[i],n&&delete this.userToCamMap[n.userId];continue}}if($.IsInWebXR)return;if(this.cam===null){this.enabled=!1;return}if(!this.context.connection.isConnected||this.context.connection.connectionId===null)return;this._model===null&&(this._model=new hd(this.context.connection.connectionId,this.context.connection.connectionId+"_camera"));let e=q(this.cam.cam),t=ve(this.cam.cam);(e.distanceTo(this._lastWorldPosition)>.001||t.angleTo(this._lastWorldQuaternion)>.01)&&(this._needsUpdate=!0),this._lastWorldPosition.copy(e),this._lastWorldQuaternion.copy(t),!((!this._needsUpdate||this.context.time.frameCount%2!==0)&&!(this.context.time.realtimeSinceStartup-this._lastUpdateTime>this._camTimeoutInSeconds*.5))&&(this._lastUpdateTime=this.context.time.realtimeSinceStartup,this._needsUpdate=!1,this._model.send(this,this.context.connection))}onReceivedRemoteCameraInfoBin(e){let t=e.guid();if(!t)return;let i=e.userId();if(!i||!this.context.connection.userIsInRoom(i)||!this.cameraPrefab)return;let n=this.remoteCams[t];if(!n)if("isObject3D"in this.cameraPrefab){let c=new ye;c.context=this.context;let d=S.instantiate(this.cameraPrefab,c);n=this.remoteCams[t]={obj:d,lastUpdate:this.context.time.realtimeSinceStartup,userId:i},n.obj.visible=!0,this.gameObject.add(d),this.userToCamMap[i]=t;let a=S.getOrAddComponent(d,pe);a.connectionId=i,a.avatar=d}else return;let r=n.obj;n.lastUpdate=this.context.time.realtimeSinceStartup,he.markDirty(r);let o=e.pos();o&&Mr(r,o.x(),o.y(),o.z());let s=e.rot();s&&Fs(r,s.x(),s.y(),s.z())}};k([A(ne)],Dn.prototype,"cam",2),k([A([wy,tt])],Dn.prototype,"cameraPrefab",2);var ud="view",zp=N("debugsyncedroom"),ti=class extends M{roomName;urlParameterName;joinRandomRoom=!0;requireRoomParameter=!1;autoRejoin=!0;_roomPrefix;awake(){this._roomPrefix===void 0&&(this._roomPrefix=this.roomName,this.roomName="")}onEnable(){let e=N(ud);if(e&&typeof e=="string"&&e.length>0){console.log("Join as viewer"),this.context.connection.joinRoom(e,!0);return}this.tryJoinRoom()}onDisable(){this.roomName&&this.roomName.length>0&&this.context.connection.leaveRoom(this.roomName)}tryJoinRoom(e=0){let t=!1;if(this.urlParameterName){let i=N(this.urlParameterName);if(i&&typeof i=="string"){t=!0;let n=dh(i);this.roomName=n}else if(this.joinRandomRoom&&(console.log("No room name found in url, generating random one"),this.setRandomRoomUrlParameter(),e<1))return this.tryJoinRoom(e+1)}else this.joinRandomRoom&&(this.roomName===null||this.roomName===void 0||this.roomName.length<=0)&&(console.log("generate room name"),this.roomName=this.generateRoomName());return this.requireRoomParameter&&!t?(zp&&console.log('No required room parameter "'+this.urlParameterName+'" in url - will not connect to networking backend.'),!1):!this.roomName||this.roomName.length<=0?(zp&&console.error('Missing room name on "'+this.name+'". Make sure this is correctly configured in Unity',this.context.connection.isDebugEnabled?this:""),!1):(this.context.connection.isConnected||this.context.connection.connect(),this._roomPrefix&&(this.roomName=this._roomPrefix+this.roomName),this.context.connection.joinRoom(this.roomName),!0)}_lastPingTime=0;_lastRoomTime=-1;update(){this.context.connection.isConnected&&(this.context.time.time-this._lastPingTime>3&&(this._lastPingTime=this.context.time.time,this.context.connection.send("ping",{time:this.context.time.time})),this.context.connection.isInRoom&&(this._lastRoomTime=this.context.time.time)),this._lastRoomTime>0&&this.context.time.time-this._lastRoomTime>.3&&(this._lastRoomTime=-1,this.autoRejoin?(console.log("Disconnected from networking backend - attempt reconnecting now"),this.tryJoinRoom()):console.warn("You are not connected to a room anymore (possibly because the tab was inactive for too long and the server kicked you)"))}get currentRoomName(){let e=N(ud);return e||N(this.urlParameterName)}setRandomRoomUrlParameter(){let e=_l(),t=this.generateRoomName();N(this.urlParameterName)?e.set(this.urlParameterName,t):e.append(this.urlParameterName,t),ah(t,e)}generateRoomName(){return ch()+"_"+lh(100,999)}getViewOnlyUrl(){if(this.context.connection.isConnected&&this.context.connection.currentRoomViewId){let e=window.location.search,t=new URLSearchParams(e);return t.has(this.urlParameterName)&&t.delete(this.urlParameterName),t.set(ud,this.context.connection.currentRoomViewId),window.location.origin+window.location.pathname+"?"+t.toString()}return null}};k([A()],ti.prototype,"roomName",2),k([A()],ti.prototype,"urlParameterName",2),k([A()],ti.prototype,"joinRandomRoom",2),k([A()],ti.prototype,"requireRoomParameter",2),k([A()],ti.prototype,"autoRejoin",2);function Gp(){let l=N("testwindowcount")||0;l&&l>0&&_y(l)}function _y(l){if(N("testwindow"))return null;let e=new URL(window.location.href);Ir(e.searchParams,ro,1),Ir(e.searchParams,"testwindow",1);let t=e.toString(),i=[];window.onbeforeunload=()=>{for(let c of i)c.close()};let n=.05,r=128,o=0,s=0;for(let c=0;c<l;c++){o*r+r*.01>=window.innerWidth&&(s+=1,o=0);let d=o*(r*(1+n))+window.screenLeft,a=s*(r*(1+n))+window.screenTop+90+60*s;o+=1;let h=window.open(t,"test window "+c,`popup=yes width=${r} height=${r} top=${a} left=${d}`);if(!h){console.warn("Failed to open window");continue}i.push(h),h.onload=()=>{h.onbeforeunload=()=>{for(let u=0;u<i.length;u++){let f=i[u];f!==h&&f.close()}i.length=0}}}return i}import{Vector3 as Ty}from"three";var To=class extends M{awake(){Gp()}},Ro=class extends M{transformsPerFrame=10;interval=0;useFlatbuffers=!0;awake(){if(this.useFlatbuffers)this.context.connection.beginListenBinrary(io,e=>{});else{this.models=[];for(let e=0;e<this.transformsPerFrame;e++)this.models.push(new Xa(this.context.connection.connectionId+"_simulatedTransform_"+e,this))}}builder=null;models=null;update(){if(!!this.context.connection.isConnected){if(this.useFlatbuffers){if(!this.context.connection.connectionId||this.context.time.frameCount%this.interval!==0)return;this.builder===null&&(this.builder=new ft(1024));let e=this.builder;for(let t=0;t<this.transformsPerFrame;t++){e.clear();let i=Nc(this.context.connection.connectionId,this);this.context.connection.sendBinary(i)}}else if(this.models)for(let e=0;e<this.models.length;e++){let t=this.models[e];t.dontSave=!0,t.update(this,null),this.context.connection.send("TestSimulateUserData-"+e,t)}}}},Xa=class{guid;fast=!1;position;rotation;velocity=void 0;dontSave;isValid(){return this.fast!==void 0||this.position!==void 0||this.rotation!==void 0||this.velocity!==void 0}constructor(e,t){this.guid=e,this.position={x:0,y:0,z:0},this.rotation={x:0,y:0,z:0,w:0},this.update(t,null)}update(e,t){let i=e.worldPosition;this.position.x=i.x,this.position.y=i.y,this.position.z=i.z;let n=e.worldQuaternion;if(this.rotation.x=n.x,this.rotation.y=n.y,this.rotation.z=n.z,this.rotation.w=n.w,this.fast=!1,t){let r=t.getVelocity();this.velocity===void 0&&(this.velocity={x:0,y:0,z:0}),this.velocity.x=r.x,this.velocity.y=r.y,this.velocity.z=r.z}}};z(Xa,"temp",new Ty);import{MathUtils as Ry}from"three";import{TransformControls as Cy}from"three/examples/jsm/controls/TransformControls";import{OrbitControls as Sy}from"three/examples/jsm/controls/OrbitControls";var vr=class extends M{isGizmo=!0;control;orbit;awake(){this.isGizmo&&!hi||!this.context.mainCamera||(this.control=new Cy(this.context.mainCamera,this.context.renderer.domElement),this.control.visible=!0,this.control.enabled=!0,this.control.getRaycaster().layers.set(2),this.control.size=.6,this.control.traverse(e=>{let t=e;if(t.layers.set(2),t){let i=t.material;i&&(i.opacity=.3)}}))}start(){if(this.context.mainCamera){let e=S.getComponentInParent(this.context.mainCamera,Sy)??void 0;this.orbit=e}}changeEventListener;windowKeyDownListener;windowKeyUpListener;onEnable(){this.control&&(this.context.scene.add(this.control),this.control.attach(this.gameObject)),this.changeEventListener=this.onControlChangedEvent.bind(this),this.control?.addEventListener("dragging-changed",this.changeEventListener),this.attachWindowEvents()}onDisable(){this.control?.removeFromParent(),this.changeEventListener&&this.control?.removeEventListener("dragging-changed",this.changeEventListener)}onControlChangedEvent(e){let t=this.orbit;if(t&&(t.enabled=!e.value),e.value){let i=S.getComponentInParent(this.gameObject,Qe);i&&i.requestOwnership()}}attachWindowEvents(){let e=this.control;!e||(this.windowKeyDownListener||(this.windowKeyDownListener=t=>{switch(t.keyCode){case 81:e.setSpace(e.space==="local"?"world":"local");break;case 16:e.setTranslationSnap(100),e.setRotationSnap(Ry.degToRad(15)),e.setScaleSnap(.25);break;case 87:e.setMode("translate");break;case 69:e.setMode("rotate");break;case 82:e.setMode("scale");break;case 187:case 107:e.setSize(e.size+.1);break;case 189:case 109:e.setSize(Math.max(e.size-.1,.1));break;case 88:e.showX=!e.showX;break;case 89:e.showY=!e.showY;break;case 90:e.showZ=!e.showZ;break;case 32:e.enabled=!e.enabled;break}}),this.windowKeyUpListener||(this.windowKeyUpListener=t=>{switch(t.keyCode){case 16:e.setTranslationSnap(null),e.setRotationSnap(null),e.setScaleSnap(null);break}}),window.addEventListener("keydown",this.windowKeyDownListener),window.addEventListener("keyup",this.windowKeyUpListener))}};k([A()],vr.prototype,"isGizmo",2);import{LinearToneMapping as Vp,ACESFilmicToneMapping as Py,ReinhardToneMapping as Oy}from"three";var Co=class{overrideState=!1;value=0},xi=class{active=!1;parameters},jn=class extends xi{mode;get isToneMapping(){return!0}},Bn=class extends xi{postExposure};function Ay(l){return"mode"in l?jn:"postExposure"in l?Bn:xi}var Hn=class{components;apply(e){if(!!this.components){for(let t of this.components)if(t instanceof jn){let i=t;if(!t.active){e.renderer.toneMapping=Vp;continue}switch(i.mode?.value??0){case 0:e.renderer.toneMapping=Vp;break;case 1:e.renderer.toneMapping=Oy;break;case 2:e.renderer.toneMapping=Py;break}}else if(t instanceof Bn){let i=t;console.log(i.postExposure);let n=Math.pow(2,i.postExposure?.value??0);e.renderer.toneMappingExposure=i.postExposure?.overrideState?n:1}}}};k([A([l=>Ay(l),xi])],Hn.prototype,"components",2);var yr=class extends M{sharedProfile;onEnable(){this.sharedProfile?.apply(this.context)}};k([A(Hn)],yr.prototype,"sharedProfile",2);import*as Wp from"three";var Er=class{guid;dontSave=!0;userId;point={x:0,y:0,z:0};source={x:0,y:0,z:0};target;update(e,t,i,n=void 0){this.userId=e.connection.connectionId,this.point.x=t.x,this.point.y=t.y,this.point.z=t.z,this.source.x=i.x,this.source.y=i.y,this.source.z=i.z,this.target=n}},So=class extends M{prefab=null;_grabModels=[];_grabModelsUpdateTime=[];_addOrUpdateSub=null;_endSub=null;_freeSub=null;_instances={};awake(){this.prefab&&(this.prefab.visible=!1)}onEnable(){this._addOrUpdateSub=this.context.connection.beginListen("xr-grab-visual-start-or-update",this.onRemoteGrabStartOrUpdate.bind(this)),this._endSub=this.context.connection.beginListen("xr-grab-visual-end",this.onRemoteGrabEnd.bind(this)),this._freeSub=dt.AddEventListener("WillFree",this.onAttachedObjectFree.bind(this))}onDisable(){this.context.connection.stopListening("xr-grab-visual-start-or-update",this._addOrUpdateSub),this.context.connection.stopListening("xr-grab-visual-end",this._endSub),dt.RemoveEventListener("WillFree",this._freeSub)}addOrUpdateGrab(e){this.context.connection.send("xr-grab-visual-start-or-update",e,2)}endGrab(e){this.context.connection.send("xr-grab-visual-end",e,2)}onRemoteGrabStartOrUpdate(e){if(!this.prefab)return;let t=this._instances[e.guid];if(!t){let i=S.instantiate(this.prefab);if(i.visible=!0,this._instances[e.guid]={instance:i,model:e},e.userId){let n=S.getComponentsInChildren(i,ht);if(n?.length>0)for(let r of n)r.assignUserColor(e.userId)}return}t.model=e}onRemoteGrabEnd(e){if(!e)return;let t=e.guid;this._instances[t]&&(S.destroy(this._instances[t].instance),delete this._instances[t])}onAttachedObjectFree(e){if(this._grabModels.length<=0)return;let t=this._grabModels[0];this.updateModel(t,e),this.endGrab(t)}onBeforeRender(){if(this.updateRendering(),!!this.prefab&&(this.prefab.visible=!1,this.context.time.frameCount%10===0))for(let e=0;e<dt.Current.length;e++){let t=dt.Current[e];if(!t.controller||!t.selected)continue;this._grabModels.length<=e&&(this._grabModels.push(new Er),this._grabModelsUpdateTime.push(0)),this._grabModelsUpdateTime[e]=this.context.time.time;let i=this._grabModels[e];this.updateModel(i,t),this.addOrUpdateGrab(i)}}updateModel(e,t){if(!t.controller||!t.selected)return;e.guid=t.grabUUID;let i=t.selected.guid;e.update(this.context,t.grabPoint,t.controller.worldPosition,i)}temp=new Wp.Vector3;updateRendering(){let e=this.context.time.deltaTime/.5;for(let t in this._instances){let{instance:i,model:n}=this._instances[t];if(!i||!n)continue;let{point:r}=n,o=q(i);this.temp.set(r.x,r.y,r.z),o.lerp(this.temp,e),ie(i,o)}}};import{Object3D as ky}from"three";var Ti=class extends M{eyes=[];lastBlinkTime=0;blinkLength=0;eyesOpen=!0;state=null;awake(){this.state=S.getComponentInParent(this.gameObject,Se)}update(){if(!this.gameObject||!this.gameObject.visible||!this.eyes||!Array.isArray(this.eyes)||this.eyes.length===0)return;if(this.context.time.time-this.lastBlinkTime>this.blinkLength){if(this.lastBlinkTime=this.context.time.time,this.state&&!this.state.isOn||!this.activeAndEnabled)return;if(this.eyesOpen=!this.eyesOpen,this.blinkLength=Math.random(),this.eyesOpen?(this.blinkLength*=3,this.blinkLength+=.5,Math.random()<.1&&(this.blinkLength=.1+Math.random()*.2)):(this.blinkLength*=Math.random()*.2,this.blinkLength+=.1),Math.random()<.1&&(this.blinkLength*=3),this.blinkLength=Math.max(.2,this.blinkLength),this.blinkLength=Math.min(3,this.blinkLength),this.eyes)for(let t of this.eyes)t&&(t.visible=this.eyesOpen)}}};k([A(ky)],Ti.prototype,"eyes",2),k([A()],Ti.prototype,"lastBlinkTime",2),k([A()],Ti.prototype,"blinkLength",2),k([A()],Ti.prototype,"eyesOpen",2);import*as Qa from"three";import{Object3D as pd}from"three";var fd=class extends M{head=null;eyes=null;target=null;brain=null;awake(){this.brain||(this.brain=S.getComponentInParent(this.gameObject,Ui)),this.brain||(console.log("No look at brain found, adding it now"),this.brain=S.addNewComponent(this.gameObject,Ui)),this.brain&&this.target&&(this.brain.controlledTarget=this.target)}vec=new Qa.Vector3;currentTargetPoint=new Qa.Vector3;update(){let e=this.target;if(e&&this.head){let t=this.eyes;if(t){let i=q(e);this.currentTargetPoint.lerp(i,this.context.time.deltaTime/.1);let n=q(this.head),r=this.vec.copy(this.currentTargetPoint).sub(n).normalize();if(r.length()<.1)return;let o=fd.forward;if(o.set(0,0,1),o.applyQuaternion(ve(this.head)),o.dot(r)>.45)for(let c=0;c<t.length;c++)t[c].lookAt(this.currentTargetPoint)}}}},Ri=fd;z(Ri,"forward",new Qa.Vector3(0,0,1)),k([A(pd)],Ri.prototype,"head",2),k([A(pd)],Ri.prototype,"eyes",2),k([A(pd)],Ri.prototype,"target",2);import{Object3D as Up}from"three";var Iy=N("debugmouth"),Fn=class extends M{idle=[];talking=[];marker=null;voip=null;lastMouthChangeTime=0;mouthChangeLength=0;awake(){setTimeout(()=>{this.voip=S.findObjectOfType(Ke,this.context),this.marker||(this.marker=S.getComponentInParent(this.gameObject,pe))},3e3)}update(){if(!this.voip||this.context.time.frameCount%10!==0)return;let e=this.marker?.connectionId??null;if(!e){Iy&&(e=null);return}let t=this.voip.getFrequency(e)??0;this.updateLips(t)}updateLips(e){if(this.context.time.time-this.lastMouthChangeTime>this.mouthChangeLength){if(this.mouthChangeLength=.05+Math.random()*.1,this.talking&&this.talking.length>0&&e>30){this.lastMouthChangeTime=this.context.time.time;let t=Math.floor(Math.random()*this.talking.length);this.setMouthShapeActive(this.talking,t)}else if(this.idle.length>0&&this.context.time.time-this.lastMouthChangeTime>.5){this.lastMouthChangeTime=this.context.time.time;let t=Math.floor(Math.random()*this.idle.length);this.setMouthShapeActive(this.idle,t)}}}setMouthShapeActive(e,t){if(!!e){e!=this.idle?this.idle.map(i=>i.visible=!1):this.talking.map(i=>i.visible=!1);for(let i=0;i<e.length;i++){let n=e[i];n&&(n.visible=i===t)}}}};k([A(Up)],Fn.prototype,"idle",2),k([A(Up)],Fn.prototype,"talking",2);var Po=class extends M{voip=null;marker=null;_startPosition=null;awake(){this.voip=S.findObjectOfType(Ke,this.context),this.marker=S.getComponentInParent(this.gameObject,pe)}update(){if(!this.voip||!this.marker||this.context.time.frameCount%10!==0)return;let e=this.marker.connectionId,t=this.voip.getFrequency(e);if(t==null)return;this._startPosition||(this._startPosition=this.gameObject.position.clone());let i=t/100;this.gameObject.position.y=this._startPosition.y+i*.07}};var My=N("logstats"),Oo=class extends M{onEnable(){console.log(this),My&&this.startCoroutine(this.run(),4)}*run(){for(;this.enabled;){let e=this.context.renderer.info;console.log(e.memory,e.render,e.programs),yield}}};import*as Qp from"three";var wr=class{guid},_r=class{signal;reaction;$serializedTypes={signal:wr,reaction:Oe}},$i=class extends M{events;start(){console.log(this)}invoke(e){if(!this.events||!Array.isArray(this.events))return;let t=typeof e=="object"?e.guid:e;for(let i of this.events)if(i.signal.guid===t)try{if(i.reaction){if(!i.reaction.invoke){console.warn("Missing invoke - possibly a serialization error",i,this);continue}}else{console.warn("Missing reaction for signal",i,this);continue}i.reaction.invoke()}catch(n){console.error(n)}}};k([A(_r)],$i.prototype,"events",2);import*as re from"three";import{Quaternion as Ly,Vector3 as Dy}from"three";var Ao=N("debugtimeline"),ko=class{director;track;get muted(){return this.track.muted}set muted(e){e!==this.track.muted&&(this.track.muted=e,this.onMuteChanged?.call(this))}*forEachClip(e=!1){if(!!this.track?.clips)if(e)for(let t=this.track.clips.length-1;t>=0;t--)yield this.track.clips[t];else for(let t of this.track.clips)yield t}getClipTime(e,t){return t.clipIn+(e-t.start)*t.timeScale}getClipTimeNormalized(e,t){return(e-t.start)/t.duration}evaluateWeight(e,t,i,n=!0){if(t<0||t>=i.length)return 0;let r=i[t];if(n||e>=r.start&&e<=r.end){let o=1,s=!1;return r.easeInDuration>0&&(o*=Math.min((e-r.start)/r.easeInDuration,1)),r.easeOutDuration>0&&!s&&(o*=Math.min((r.end-e)/r.easeOutDuration,1)),o}return 0}},md=class{clip;rootPositionOffset;rootQuaternionOffset;get hasOffsets(){return this.rootPositionOffset!==void 0||this.rootQuaternionOffset!==void 0}rootStartPosition;rootEndPosition;rootStartQuaternion;rootEndQuaternion;constructor(e){let t=e.getClip();this.clip=t;let i=e.getRoot(),n=i.name+".position",r=i.name+".quaternion";Ao&&console.log(t.name,t.tracks,n);for(let o of t.tracks)if(!(o.times.length<=0)){if(o.name.endsWith(n))this.rootStartPosition=new re.Vector3().fromArray(o.values,0),this.rootEndPosition=new re.Vector3().fromArray(o.values,o.values.length-3),this.rootPositionOffset=this.rootEndPosition.clone().sub(this.rootStartPosition),Ao&&console.log(this.rootPositionOffset);else if(o.name.endsWith(r)&&(this.rootStartQuaternion=new re.Quaternion().fromArray(o.values,0),this.rootEndQuaternion=new re.Quaternion().fromArray(o.values,o.values.length-4),this.rootQuaternionOffset=this.rootEndQuaternion.clone().multiply(this.rootStartQuaternion),Ao)){let s=new re.Euler().setFromQuaternion(this.rootQuaternionOffset);console.log("ROT",s)}}}},Nn=class extends ko{models=[];trackOffset;target;mixer;clips=[];actions=[];_actionOffsets=[];_didBind=!1;createHooks(e,t){if(t.tracks?.length<=0){console.warn("No tracks in AnimationClip",t);return}let i=t.tracks[0].name.split("."),n=i[i.length-2],r=n+".position",o=n+".quaternion",s=!1,c=!1;for(let d of t.tracks)d.name.endsWith(r)?(s=!0,this.createPositionInterpolant(t,e,d)):d.name.endsWith(o)&&(c=!0,this.createRotationInterpolant(t,e,d));if(!s||!c){let d=this.mixer?.getRoot(),a=t.tracks[0],h=a.name.lastIndexOf("."),u=a.name.substring(0,h),f=u.substring(u.lastIndexOf(".")+1),E=d.getObjectByName(f);if(E)if(s){if(!c){let b=t.tracks[0].name.substring(0,h)+".quaternion";Ao&&console.warn("Create quaternion track",f,E);let y=E.quaternion,g=new re.QuaternionKeyframeTrack(b,[0,t.duration],[y.x,y.y,y.z,y.w,y.x,y.y,y.z,y.w]);t.tracks.push(g),this.createRotationInterpolant(t,e,g)}}else{let b=u+".position";Ao&&console.warn("Create position track",f,E);let y=E.position,g=new re.VectorKeyframeTrack(b,[0,t.duration],[y.x,y.y,y.z,y.x,y.y,y.z]);t.tracks.push(g),this.createPositionInterpolant(t,e,g)}}}bind(){if(!this._didBind){this._didBind=!0,Ao&&console.log(this.models),this.mixer?this.target=this.mixer.getRoot():console.warn("No mixer was assigned to animation track");for(let e of this.actions){let t=new md(e);this._actionOffsets.push(t)}for(let e of this.models){let t=e.asset,i=t.position,n=t.rotation;i.x!==void 0&&(i.isVector3||(t.position=new Dy(i.x,i.y,i.z)),n.isQuaternion||(t.rotation=new Ly(n.x,n.y,n.z,n.w)))}this.ensureTrackOffsets()}}ensureTrackOffsets(){if(this.trackOffset){let e=this.trackOffset.position;e&&(e.isVector3||(this.trackOffset.position=new re.Vector3(e.x,e.y,e.z)));let t=this.trackOffset.rotation;t&&(t.isQuaternion||(this.trackOffset.rotation=new re.Quaternion(t.x,t.y,t.z,t.w)))}}_useclipOffsets=!0;_totalOffsetPosition=new re.Vector3;_totalOffsetRotation=new re.Quaternion;_totalOffsetPosition2=new re.Vector3;_totalOffsetRotation2=new re.Quaternion;_summedPos=new re.Vector3;_tempPos=new re.Vector3;_summedRot=new re.Quaternion;_tempRot=new re.Quaternion;evaluate(e){if(this.track.muted||!this.mixer)return;this.bind(),this._totalOffsetPosition.set(0,0,0),this._totalOffsetRotation.set(0,0,0,1),this._totalOffsetPosition2.set(0,0,0),this._totalOffsetRotation2.set(0,0,0,1);let t=0,i=0,n=!1;for(let r=0;r<this.clips.length;r++){let o=this.models[r],s=this.actions[r],c=o.asset;s.weight=0;let d=e>=o.start&&e<=o.end,a=o.postExtrapolationMode,h=d;if(!h&&!n&&o.end<e&&o.postExtrapolationMode!==0){let u=r<this.clips.length-1?this.models[r+1]:null;(!u||u.start>e)&&(h=!0,n=!0)}if(h){let u=1;u*=this.evaluateWeight(e,r,this.models,h);let f=this.getClipTime(e,o),E=0,b=c.duration;if(d){if(c.loop)for(E+=Math.floor(f/(b+1e-6));f>b;)f-=b}else if(!d)switch(a){case 2:f%=b;break;case 3:let p=Math.floor(f/b)%2!==0;f%=b,p&&(f=b-f);break}s.time=f,s.timeScale=0;let y=u*this.director.weight;if(s.weight=y,s.clampWhenFinished=!0,s.isRunning()||s.play(),this._useclipOffsets){let g=t==0?this._totalOffsetPosition:this._totalOffsetPosition2,p=t==0?this._totalOffsetRotation:this._totalOffsetRotation2;t<1&&(i=1-u),t+=1;let m=this._summedPos.set(0,0,0),v=this._tempPos.set(0,0,0),w=this._summedRot.identity(),x=this._tempRot.identity(),T=c.rotation,R=new re.Quaternion;R.slerp(T,u);let C=this._actionOffsets[r];if(C.hasOffsets)for(let O=0;O<E;O++)C.rootPositionOffset?v.copy(C.rootPositionOffset):v.set(0,0,0),v.applyQuaternion(w).applyQuaternion(R),C.rootQuaternionOffset&&(x.copy(C.rootQuaternionOffset),w.multiply(x)),m.add(v);p.multiply(R),p.multiply(w),m.add(c.position),g.add(m)}}}this._useclipOffsets&&(this._totalOffsetPosition.lerp(this._totalOffsetPosition2,i),this._totalOffsetRotation.slerp(this._totalOffsetRotation2,i)),this.mixer.update(e)}createRotationInterpolant(e,t,i){let n=i.createInterpolant.bind(i),r=new re.Quaternion;this.ensureTrackOffsets();let o=this.trackOffset?.rotation;i.createInterpolant=()=>{let s=n(),c=s.evaluate.bind(s);return s.evaluate=d=>{let a=c(d);return r.set(a[0],a[1],a[2],a[3]),r.premultiply(this._totalOffsetRotation),o&&r.premultiply(o),a[0]=r.x,a[1]=r.y,a[2]=r.z,a[3]=r.w,a},s}}createPositionInterpolant(e,t,i){let n=i.createInterpolant.bind(i),r=new re.Vector3;this.ensureTrackOffsets();let o=this.trackOffset?.rotation,s=this.trackOffset?.position,c;i.createInterpolant=()=>{let d=n(),a=d.evaluate.bind(d);return d.evaluate=h=>{let u=a(h);return r.set(u[0],u[1],u[2]),t.removeStartOffset&&(c===void 0?(c=null,c=this._actionOffsets.find(f=>f.clip===e)?.rootStartPosition?.clone()):c?.isVector3&&r.sub(c)),r.applyQuaternion(this._totalOffsetRotation),r.add(this._totalOffsetPosition),o&&r.applyQuaternion(o),s&&(r.x-=s.x,r.y+=s.y,r.z+=s.z),u[0]=r.x,u[1]=r.y,u[2]=r.z,u},d}}},zn=class extends ko{models=[];listener;audio=[];audioContextTimeOffset=[];lastTime=0;getAudioFilePath(e){let t=this.director.sourceId;return ks(t,e)}onAllowAudioChanged(e){for(let t=0;t<this.models.length;t++){let i=this.models[t];this.audio[t].setVolume(e?i.asset.volume:0)}}addModel(e){let t=this.getAudioFilePath(e.asset.clip),i=new re.Audio(this.listener);i.setVolume(e.asset.volume);let n=new re.AudioLoader;console.log(t,this.director.sourceId),n.load(t,r=>{i.setBuffer(r),i.loop=e.asset.loop,this.audio.push(i),this.models.push(e)})}onDisable(){for(let e of this.audio)e.isPlaying&&e.stop()}onMuteChanged(){if(this.muted)for(let e=0;e<this.audio.length;e++){let t=this.audio[e];t?.isPlaying&&t.stop()}}evaluate(e){if(!this.track.muted){for(let t=0;t<this.models.length;t++){let i=this.models[t],n=this.audio[t];if(e>=i.start&&e<=i.end){if(this.director.isPaused&&(n.isPlaying&&n.stop(),this.lastTime===e))continue;n.isPlaying||(n.offset=i.clipIn+(e-i.start)*i.timeScale,n.play());let r=i.asset.volume;i.easeInDuration>0&&(r*=Math.min((e-i.start)/i.easeInDuration,1)),i.easeOutDuration>0&&(r*=Math.min((i.end-e)/i.easeOutDuration,1)),n.setVolume(r*this.director.weight)}else n.isPlaying&&n.stop()}this.lastTime=e}}},en=class extends ko{models=[];didTrigger=[];receivers=[];evaluate(e){if(!(this.receivers.length<=0)&&!this.track.muted)for(let t=0;t<this.models.length;t++){let i=this.models[t],n=this.didTrigger[t],r=i.time-e;if(i.retroActive?r<0:r<0&&Math.abs(r)<.1){if(!n){this.didTrigger[t]=!0;for(let s of this.receivers)!s||s.invoke(i.asset)}}else i.emitOnce||(this.didTrigger[t]=!1)}}},Es=class extends ko{models=[];timelines=[];resolveSourceObjects(e){for(let t=this.models.length-1;t>=0;t--){let n=this.models[t].asset;if(typeof n.sourceObject=="string"){let r=n.sourceObject;Es.resolved[r]?n.sourceObject=Es.resolved[r]:(n.sourceObject=S.findByGuid(r,e.scene),Es.resolved[r]=n.sourceObject)}if(n.sourceObject){let r=S.getComponent(n.sourceObject,tn);this.timelines.push(r),r&&n.updateDirector&&(r.playOnAwake=!1)}else{this.models.splice(t,1);continue}}}_previousActiveModel=null;evaluate(e){this._previousActiveModel=null;for(let t=0;t<this.models.length;t++){let i=this.models[t],n=i.asset;if(e>=i.start&&e<=i.end){this._previousActiveModel=i;let r=this.getClipTime(e,i);if(n.controlActivation){let o=n.sourceObject;o.visible=!0}if(n.updateDirector){let o=this.timelines[t];o&&(o.isPlaying&&o.pause(),o.time=r,o.evaluate())}}else{let r=this._previousActiveModel?.asset;if(n.controlActivation){let o=n.sourceObject;r?.sourceObject!==o&&(o.visible=!1)}}}}},Ki=Es;z(Ki,"resolved",{});var Xp=N("debugtimeline");var Ya=class extends M{static registerCreateTrack(e,t){this.createTrackFunctions[e]=t}playableAsset;playOnAwake;extrapolationMode=1;get isPlaying(){return this._isPlaying}get isPaused(){return this._isPaused}get time(){return this._time}set time(e){this._time=e}get duration(){return this._duration}set duration(e){this._duration=e}get weight(){return this._weight}set weight(e){this._weight=e}_visibilityChangeEvt;_clonedPlayableAsset=!1;awake(){Xp&&console.log(this,this.playableAsset?.tracks),this.rebuildGraph(),this.playOnAwake?this.play():this.evaluate(),this.isValid()||console.warn("PlayableDirector is not valid",this.playableAsset,this.playableAsset?.tracks,Array.isArray(this.playableAsset?.tracks),this)}onEnable(){for(let e of this._audioTracks)e.onEnable?.();for(let e of this._customTracks)e.onEnable?.();this.playOnAwake&&this.play(),this._visibilityChangeEvt||(this._visibilityChangeEvt=()=>{switch(document.visibilityState){case"hidden":this.setAudioTracksAllowPlaying(!1);break;case"visible":this.setAudioTracksAllowPlaying(!0);break}}),window.addEventListener("visibilitychange",this._visibilityChangeEvt)}onDisable(){this.stop();for(let e of this._audioTracks)e.onDisable?.();for(let e of this._customTracks)e.onDisable?.();this._visibilityChangeEvt&&window.removeEventListener("visibilitychange",this._visibilityChangeEvt)}onDestroy(){for(let e of this._audioTracks)e.onDestroy?.()}rebuildGraph(){!this.isValid()||(this.resolveBindings(),this.updateTimelineDuration(),this.setupAndCreateTrackHandlers())}play(){!this.isValid()||(this._isPaused=!1,!this._isPlaying&&(this._isPlaying=!0,this._internalUpdateRoutine=this.startCoroutine(this.internalUpdate())))}pause(){this._isPaused=!0}stop(){this._isPlaying&&(this._time=0,this._isPlaying=!1,this._isPaused=!1,this.evaluate()),this._isPlaying=!1,this._isPaused=!1,this._internalUpdateRoutine&&this.stopCoroutine(this._internalUpdateRoutine),this._internalUpdateRoutine=null}evaluate(){if(!this.isValid())return;let e=this._time;switch(this.extrapolationMode){case 0:e=Math.min(e,this._duration);break;case 1:e%=this._duration;break;case 2:if(e>this._duration){this.stop();return}break}this.internalEvaluate(e)}isValid(){return this.playableAsset&&this.playableAsset.tracks&&Array.isArray(this.playableAsset.tracks)}*forEachTrack(){for(let e of this._allTracks)for(let t of e)yield t}get audioTracks(){return this._audioTracks}_guidsMap;resolveGuids(e){this._guidsMap=e}_isPlaying=!1;_internalUpdateRoutine;_isPaused=!1;_time=0;_duration=0;_weight=1;_animationTracks=[];_audioTracks=[];_signalTracks=[];_controlTracks=[];_customTracks=[];_allTracks=[this._animationTracks,this._audioTracks,this._signalTracks,this._controlTracks,this._customTracks];*internalUpdate(){for(;this._isPlaying;)!this._isPaused&&this._isPlaying&&(this._time+=this.context.time.deltaTime,this.evaluate()),yield}internalEvaluate(e){for(let t of this.playableAsset.tracks)if(!t.muted)switch(t.type){case"ActivationTrack":for(let i=0;i<t.outputs.length;i++){let n=t.outputs[i];if(typeof n=="object"){let r=!1;for(let s of t.clips)s.start<=e&&e<=s.end&&(r=!0);let o=n;o.visible!==void 0&&(o.visible=r)}}break}for(let t of this._animationTracks)t.evaluate(e);for(let t of this._audioTracks)t.evaluate(e);for(let t of this._signalTracks)t.evaluate(e);for(let t of this._controlTracks)t.evaluate(e);for(let t of this._customTracks)t.evaluate(e)}resolveBindings(){if(this._clonedPlayableAsset||(this._clonedPlayableAsset=!0,this.playableAsset=qo(this.playableAsset)),!this.playableAsset||!this.playableAsset.tracks)return;let e=this.findRoot(this.gameObject);for(let t of this.playableAsset.tracks)for(let i=t.outputs.length-1;i>=0;i--){let n=t.outputs[i];if(typeof n=="string"){this._guidsMap&&this._guidsMap[n]&&(n=this._guidsMap[n]);let r=S.findByGuid(n,e);r===null||typeof r!="object"?(t.outputs.splice(i,1),console.warn("Failed to resolve binding",n,t.name,t.type)):(Xp&&console.log("Resolved binding",n,"to",r),t.outputs[i]=r)}else if(n===null){if(t.outputs.splice(i,1),Ya.createTrackFunctions[t.type])continue;t.type!=="AudioTrack"&&t.type!=="ControlTrack"&&t.type!=="MarkerTrack"&&console.warn("Missing binding",n,t.name,t.type,this.name,this.playableAsset.name)}}}findRoot(e){return e.parent?this.findRoot(e.parent):e}updateTimelineDuration(){if(this._duration=0,!(!this.playableAsset||!this.playableAsset.tracks)){for(let e of this.playableAsset.tracks)if(e.muted!==!0)for(let t of e.clips)t.end>this._duration&&(this._duration=t.end)}}setupAndCreateTrackHandlers(){if(this._animationTracks.length=0,this._audioTracks.length=0,this._signalTracks.length=0,!this.playableAsset)return;let e=[];for(let t of this.playableAsset.tracks){let i=t.type,n=Ya.createTrackFunctions[i];if(n!=null){let r=n(this,t);if(typeof r.evaluate=="function"){r.director=this,r.track=t,this._customTracks.push(r);continue}}if(t.type==="AnimationTrack"){if(t.clips.length<=0)continue;for(let r=t.outputs.length-1;r>=0;r--){let o=t.outputs[r];typeof o.enabled=="boolean"&&(o.enabled=!1);let s=o?.gameObject?.animations;if(s){let c=new Nn;c.trackOffset=t.trackOffset,c.director=this,c.track=t;for(let d=0;d<t.clips.length;d++){let a=t.clips[d],h=a.asset;if(!h){console.error("MISSING anim model?","clip#"+d,a,t,this.playableAsset,this.name);continue}let u=h.clip,f=u;if((typeof f=="string"||typeof f=="number")&&(f=s.find(b=>b.name===u)),!f){console.warn("Could not find animationClip for model",a,t.name,this.name,this.playableAsset?.name);continue}c.mixer||(c.mixer=new Qp.AnimationMixer(o.gameObject)),c.clips.push(f),c.mixer.uncacheAction(f),c.createHooks(a.asset,f);let E=c.mixer.clipAction(f);c.actions.push(E),c.models.push(a)}this._animationTracks.push(c)}}}else if(t.type==="AudioTrack"){if(t.clips.length<=0)continue;e.push(t)}else if(t.type==="MarkerTrack"){let r=new en;r.director=this,r.track=t;for(let o of t.markers)switch(o.type){case"SignalEmitter":r.models.push(o),r.didTrigger.push(!1);break}if(r!==null&&r.models.length>0){let o=S.getComponent(this.gameObject,$i);o&&(r.receivers.push(o),this._signalTracks.push(r))}}else if(t.type==="SignalTrack"){let r=new en;r.director=this,r.track=t;for(let o of t.markers)r.models.push(o),r.didTrigger.push(!1);for(let o of t.outputs)r.receivers.push(o);this._signalTracks.push(r)}else if(t.type==="ControlTrack"){let r=new Ki;r.director=this,r.track=t;for(let o of t.clips)r.models.push(o);r.resolveSourceObjects(this.context),this._controlTracks.push(r)}}ue.registerWaitForAllowAudio(()=>{let t=S.findObjectOfType($t,this.context);if(!!t)for(let i of e){let n=new zn;n.director=this,n.track=i,n.listener=t.listener;for(let r=0;r<i.clips.length;r++){let o=i.clips[r];n.addModel(o)}this._audioTracks.push(n)}})}setAudioTracksAllowPlaying(e){for(let t of this._audioTracks)t.onAllowAudioChanged(e)}},tn=Ya;z(tn,"createTrackFunctions",{});import*as Yp from"three-mesh-ui";var ii=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 jy}from"three";var By=N("debugeventsystem"),Ci=class extends M{static createIfNoneExists(e){this.didSearchEventSystem||(this.didSearchEventSystem=!0,Ci.systems.length<=0&&Ci.systems.push(...S.findObjectsOfType(Ci,e)));for(let i of Ci.systems)if(i.context===e)return;let t=new jy;S.addNewComponent(t,Ci),e.scene.add(t)}static ensureUpdateMeshUI(e,t){ni.update(e,t)}static markUIDirty(e){ni.markDirty()}static get instance(){return this.systems[0]}orbitControl=null;orbitControlWasEnabled=!1;raycaster=[];constructor(){super(),Ci.systems.push(this)}onDestroy(){Ci.systems.splice(Ci.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)}onEnable(){ae.addEventListener("select-start",(t,i)=>{if(!i.grab)return;ni.resetLastSelected();let n=new ii;n.inputSource=t,n.isDown=t.selectionDown,n.isUp=t.selectionUp,n.isPressed=t.selectionPressed,n.isClicked=!1,i.grab&&!this.handleEvents(i.grab,n)&&(i.grab=null)});let e=new je;ae.addEventListener("select-end",(t,i)=>{if(!i.grab)return;let n=new ii;n.inputSource=t,n.isDown=t.selectionDown,n.isUp=t.selectionUp,n.isPressed=t.selectionPressed,n.isClicked=t.selectionClick,this.handleEvents(i.grab,n)}),ae.addEventListener("update",t=>{e.ray=t.getRay();let i=this.performRaycast(e);if(!i)return;let n=new ii;n.inputSource=t,this.handleIntersections(i,n)}),this.context.pre_update_callbacks.push(this.onBeforeUpdate.bind(this)),this.context.input.addEventListener("pointerDown",this.onPointerDown.bind(this))}onDisable(){}onPointerDown(){this.onBeforeUpdate()}lastPointerEvent=null;objectsHoveredThisFrame=[];objectsHoveredLastFrame=[];raisedPointerDownEvents=[];_didMove=!1;onBeforeUpdate(){if(this.objectsHoveredThisFrame.length=0,this.resetMeshUIStates(),$.IsInWebXR||this.context.input.isKeyPressed(18))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 ii(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 i=null,n=null;this.context.input.mouseDown&&this.currentActiveMeshUIComponents.length>0&&this.context.mainCameraComponent&&(i=S.getComponent(this.context.mainCameraComponent.gameObject,gt)??null,i&&(n=i.enabled,i.enabled=!1)),this.handleIntersections(e,t),i&&(this.orbitControl=i,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}for(let t of this.objectsHoveredLastFrame)if(this.objectsHoveredThisFrame.indexOf(t)<0){this._tempComponentsArray.length=0;let i=S.getComponentsInParent(t,M,this._tempComponentsArray);this.lastPointerEvent.object=t;for(let n=0;n<i.length;n++){let r=i[n];if(!r.gameObject||r.destroyed)continue;let o=r;o.onPointerExit&&o.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 i=t.performRaycast(e);i&&i.length>0&&this._sortedHits.push(...i)}return this._sortedHits.sort((t,i)=>t.distance-i.distance),this._sortedHits}handleIntersections(e,t){if(!e||e.length<=0)return!1;e=this.sortCandidates(e);for(let i of e){let{object:n}=i;if(this.handleEvents(n,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 i=e[t],n=i.object;if(n.material&&n.material.depthTest===!1){this._noDepthTestingResults.push(i);continue}this._sortingBuffer.push(i)}for(let t of this._sortingBuffer)this._noDepthTestingResults.push(t);return this._noDepthTestingResults}handleEventsArray=[];handleEvents(e,t){if(!this.testIsVisible(e))return t.isClicked&&By&&console.log("not allowed",e),!1;t.object=e,this.lastPointerEvent=t;let i=e.parent,n=!1,r=t.isClicked??!1,o=null;if(i&&i.isUI){let s=(t.isPressed||t.isClicked)??!1;if(i.shadowComponentOwner){let c=i.shadowComponentOwner.gameObject;if(c){if(o=this.tryFindCanvasGroup(c),o?.blocksRaycasts===!1)return!1;if(o?.interactable===!1)return!0;let d=this.handleMeshUIIntersection(e,s);e=c,n=!0}}if(!n&&this.handleMeshUiObjectWithoutShadowDom(i,s))return!0}if(this.objectsHoveredThisFrame.push(e),o===null||o.interactable){let s=this.objectsHoveredLastFrame.indexOf(e)>=0;this.handleEventsArray.length=0;let c=S.getComponentsInParent(e,M,this.handleEventsArray);for(let d=0;d<c.length;d++){if(t.used)return!0;if(c[d].destroyed)continue;let a=c[d];a.interactable!==!1&&(a.onPointerEnter&&(s||a.onPointerEnter(t)),t.isDown&&a.onPointerDown&&!this.raisedPointerDownEvents.includes(a)&&(a.onPointerDown(t),this.raisedPointerDownEvents.push(a)),t.isUp&&a.onPointerUp&&a.onPointerUp(t),t.isClicked&&a.onPointerClick&&a.onPointerClick(t))}}return!0}handleMeshUiObjectWithoutShadowDom(e,t){return!e||!e.isUI?!0:this.handleMeshUIIntersection(e,t)}currentActiveMeshUIComponents=[];handleMeshUIIntersection(e,t){let i=ni.updateState(e,t);return i&&this.currentActiveMeshUIComponents.push(i),i!==null}resetMeshUIStates(){if(this.context.input.getPointerPressedCount()>0&&ni.resetLastSelected(),!(!this.currentActiveMeshUIComponents||this.currentActiveMeshUIComponents.length<=0)){for(let e=0;e<this.currentActiveMeshUIComponents.length;e++){let t=this.currentActiveMeshUIComponents[e];ni.resetState(t)}this.currentActiveMeshUIComponents.length=0}}testIsVisible(e){return e?S.isActiveSelf(e)?this.testIsVisible(e.parent):!1:!0}tryFindCanvasGroup(e){if(!e)return null;let t=S.foreachComponent(e,i=>{let n=i;if(n.blocksRaycasts!==void 0&&n.interactable!==void 0)return n},!1);return t!==void 0?t:this.tryFindCanvasGroup(e.parent)}},Ze=Ci;z(Ze,"didSearchEventSystem",!1),z(Ze,"systems",[]);var ni=class{static markDirty(){this.needsUpdate=!0}static update(e,t){for(let i of this.lastUpdateFrame)if(i.context===t){if(t.time.frameCount===i.frame)return;i.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 i=null;if(e&&(i=this.findBlockInParent(e),i&&i!==this.lastSelected)){if(i.interactable===!1)return null;t?(this.lastSelected=i,i.states.pressed&&i.setState("pressed")):i.states.hovered&&i.setState("hovered"),this.needsUpdate=!0}return i}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}};z(ni,"lastSelected",null),z(ni,"lastUpdateFrame",[]),z(ni,"needsUpdate",!1);import{AxesHelper as Fy}from"three";var Io="./include";Yp.Block.prototype.interactable={get(){return this.interactive},set(l){this.interactable=l}};var Ue=class extends M{isRoot(){return this.Root?.gameObject===this.gameObject}markDirty(){Ze.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=S.getComponentInParent(this.gameObject,nn)),this._root}_parentComponent=void 0;onEnable(){super.onEnable()}addShadowComponent(e,t){this.removeShadowComponent();let i=this.isRoot()?this.gameObject:this.gameObject.parent;if(this._parentComponent=S.getComponentInParent(i,Ue),!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}if(e.name=this.name+" ("+(this.constructor.name??"UI")+")",e.autoLayout=this._parentComponent.controlsChildLayout,e.shadowComponentOwner=this,e.traverse(n=>{n.shadowComponentOwner===void 0&&(n.shadowComponentOwner=this)}),this.Root?.gameObject===this.gameObject)this.gameObject.add(e);else{let n=this._parentComponent.shadowComponent;n&&n?.add(e)}this.shadowComponent=e,t&&t.shadowComponent&&this.shadowComponent&&t.shadowComponent.add(this.shadowComponent),hi&&e.add(new Fy(.5)),this.onAfterAddedToScene()}set(e){}traverseOwnedShadowComponents(e,t,i){if(!!e&&e.shadowComponentOwner===t){i(e);for(let n of e.children)this.traverseOwnedShadowComponents(n,t,i)}}removeShadowComponent(){this.shadowComponent&&this.shadowComponent.removeFromParent()}onAfterAddedToScene(){}setInteractable(e){this.shadowComponent&&(this.shadowComponent.interactable=e)}},nn=class extends Ue{awake(){super.awake()}};import{Color as Gy,Texture as $p}from"three";import*as bd from"three-mesh-ui";import{Matrix4 as Ny,Object3D as zy,Vector2 as Zp,Vector3 as gd}from"three";var Jp=N("debugui"),Mo=class{width;height},xr=class{x;y;width;height},ut=class extends Ue{offset=.01;get translation(){return this.gameObject.position}get rotation(){return this.gameObject.quaternion}get scale(){return this.gameObject.scale}_anchoredPosition;get anchoredPosition(){return this._anchoredPosition||(this._anchoredPosition=new gd),this._anchoredPosition}rect;sizeDelta;anchoredPosition3D;pivot;lastMatrix;rectBlock;_transformNeedsUpdate=!1;awake(){super.awake(),this.lastMatrix=new Ny,this.rectBlock=new zy,this.rectBlock.position.z=.1,this.rectBlock.name=this.name,this._anchoredPosition||(this._anchoredPosition=new gd),Jr(this,"_anchoredPosition",()=>{this._transformNeedsUpdate=!0})}onEnable(){super.onEnable(),this.addShadowComponent(this.rectBlock),this._transformNeedsUpdate=!0}onDisable(){super.onDisable(),this.removeShadowComponent()}applyTransform(){let e=this.shadowComponent;!e||(this._transformNeedsUpdate=!1,this.isRoot()?e.rotation.y=Math.PI:(e.position.copy(this.gameObject.position),e.position.x*=-1,e.position.z*=-1,e.position.z-=this.offset,e.quaternion.copy(this.gameObject.quaternion),e.rotation.x*=-1,e.rotation.z*=-1,e.scale.copy(this.gameObject.scale)),this.applyAnchoring(e.position),this.lastMatrix.copy(this.gameObject.matrix))}markDirty(){this._transformNeedsUpdate=!0}onBeforeRender(){(this._transformNeedsUpdate||this.lastMatrix.equals(this.gameObject.matrix)===!1)&&(Jp&&console.log("updating",this.name),this.applyTransform()),Ze.ensureUpdateMeshUI(bd,this.context)}applyAnchoring(e){if(this.pivot&&this.sizeDelta){let t=this.pivot.x*2-1,i=this.pivot.y*2-1;i-=this.anchoredPosition.y*.05;let n=this.sizeDelta.x*t,r=this.sizeDelta.y*i;e.x-=n*.5,e.y-=r*.5}}getBasicOptions(){let e={width:this.rect.width,height:this.rect.height,offset:this.offset,backgroundOpacity:0,borderWidth:0,borderRadius:0,borderOpacity:0};return this.ensureValidSize(e),e}ensureValidSize(e,t=1e-4){return e.width<=0&&(e.width=t),e.height<=0&&(e.height=1e-4),e}_createdBlocks=[];createNewBlock(e){e={...this.getBasicOptions(),...e},Jp&&console.log(this.name,e);let t=new bd.Block(e);return this._createdBlocks.push(t),t}};k([A(xr)],ut.prototype,"rect",2),k([A(Zp)],ut.prototype,"sizeDelta",2),k([A(gd)],ut.prototype,"anchoredPosition3D",2),k([A(Zp)],ut.prototype,"pivot",2);var Rt=class extends Ue{get color(){return this._color||(this._color=new we(1,1,1,1)),this._color}set color(e){(!this._color||this._color.r!==e.r||this._color.g!==e.g||this._color.b!==e.b||this._color.alpha!==e.alpha)&&(this._color||(this._color=new we(1,1,1,1)),this._color.copy(e))}onColorChanged(){let e=this.color;this.setOptions({backgroundColor:e,backgroundOpacity:e.alpha,borderOpacity:e.alpha})}get m_Color(){return this._color}raycastTarget=!0;uiObject=null;_color=null;_rect=null;get rectTransform(){return this._rect||(this._rect=this.gameObject.getComponent(ut)),this._rect}setState(e){this.makePanel(),this.uiObject&&this.uiObject.setState(e)}setupState(e){this.makePanel(),this.uiObject&&this.uiObject.setupState(e)}setOptions(e){this.makePanel(),this.uiObject&&(this.uiObject.set(e),(e.backgroundColor!==void 0||e.backgroundOpacity!==void 0)&&this.uiObject.updateBackgroundMaterial?.call(this.uiObject))}awake(){super.awake(),this.makePanel(),Jr(this,"_color",()=>bp(this,this.onColorChanged))}onEnable(){super.onEnable(),this.uiObject&&(this.rectTransform.shadowComponent?.add(this.uiObject),this.addShadowComponent(this.uiObject,this.rectTransform))}onDisable(){super.onDisable(),this.uiObject&&this.removeShadowComponent()}_currentlyCreatingPanel=!1;makePanel(){if(this.uiObject||this._currentlyCreatingPanel)return;this._currentlyCreatingPanel=!0;let e={backgroundColor:this.color,backgroundOpacity:this.color.alpha,offset:1};this.onBeforeCreate(e),this.onCreate(e),this.controlsChildLayout=!1,this._currentlyCreatingPanel=!1,this.onAfterCreated()}onBeforeCreate(e){}onCreate(e){this.uiObject=this.rectTransform.createNewBlock(e),this.uiObject.name=this.name}onAfterCreated(){}async setTexture(e){!e||(this.setOptions({backgroundOpacity:0}),e&&this.setOptions({backgroundTexture:e,borderRadius:0,backgroundOpacity:this.color.alpha,backgroundSize:"stretch"}))}onAfterAddedToScene(){this.shadowComponent&&(this.shadowComponent.offset=this.shadowComponent.position.z)}};k([A(we)],Rt.prototype,"color",1),k([A()],Rt.prototype,"raycastTarget",2);var rn=class extends Rt{onAfterCreated(){this.uiObject&&(this.uiObject.scale.y*=-1)}};var Za=class{texture;rect};k([A($p)],Za.prototype,"texture",2);var on=class extends rn{sprite;isBuiltinSprite(){switch(this.sprite?.texture?.name){case"InputFieldBackground":case"UISprite":case"Background":return!0}return this.sprite?.texture?.image?.width===32&&this.sprite?.texture?.image?.height===32}onBeforeCreate(e){this.isBuiltinSprite()&&(e.borderRadius=5,e.borderColor=new Gy(.4,.4,.4),e.borderOpacity=this.color.alpha,e.borderWidth=.3)}onAfterCreated(){super.onAfterCreated(),!this.isBuiltinSprite()&&this.setTexture(this.sprite?.texture)}};k([A(Za)],on.prototype,"sprite",2);var Tr=class extends rn{mainTexture;onAfterCreated(){super.onAfterCreated(),this.setTexture(this.mainTexture)}};k([A($p)],Tr.prototype,"mainTexture",2);var Lo=N("debugbutton");var Ft=class extends M{onClick;_isHovered=!1;onPointerEnter(e){Lo&&console.log("Button Enter",this.animationTriggers?.highlightedTrigger,this.animator),this._isHovered=!0,this.transition==3&&this.animationTriggers&&this.animator?this.animator.SetTrigger(this.animationTriggers.highlightedTrigger):this.transition===1&&this.colors&&this._image?.setState("hovered")}onPointerExit(){Lo&&console.log("Button Exit",this.animationTriggers?.highlightedTrigger,this.animator),this._isHovered=!1,this.transition==3&&this.animationTriggers&&this.animator?this.animator.SetTrigger(this.animationTriggers.normalTrigger):this.transition===1&&this.colors&&this._image?.setState("normal")}onPointerDown(e){Lo&&console.log("Button Down",this.animationTriggers?.highlightedTrigger,this.animator),this.transition==3&&this.animationTriggers&&this.animator?this.animator.SetTrigger(this.animationTriggers.pressedTrigger):this.transition===1&&this.colors&&this._image?.setState("pressed")}onPointerUp(e){Lo&&console.log("Button Down",this.animationTriggers?.highlightedTrigger,this.animator),this.transition==3&&this.animationTriggers&&this.animator?this.animator.SetTrigger(this._isHovered?this.animationTriggers.highlightedTrigger:this.animationTriggers.normalTrigger):this.transition===1&&this.colors&&this._image?.setState(this._isHovered?"hovered":"normal")}onPointerClick(e){Lo&&console.trace("Button Click",this.onClick),this.onClick?.invoke()}colors;transition;animationTriggers;animator;set interactable(e){this._interactable=e,this._image&&(this._image.setInteractable(e),e?this._image.setState("normal"):this._image.setState("disabled"))}get interactable(){return this._interactable}_interactable=!0;set_interactable(e){this.interactable=e}awake(){super.awake(),Lo&&console.log(this),this.init()}start(){this._image?.setInteractable(this.interactable)}onEnable(){super.onEnable()}_requestedAnimatorTrigger;*setAnimatorTriggerAtEndOfFrame(e){this._requestedAnimatorTrigger=e,yield,yield,this._requestedAnimatorTrigger==e&&this.animator?.SetTrigger(e)}_isInit=!1;_image;init(){this._isInit||(this._isInit=!0,this._image=S.getComponent(this.gameObject,on),this._image&&(this.stateSetup(this._image),this.interactable?this._image.setState("normal"):this._image.setState("disabled")))}stateSetup(e){e.setInteractable(this.interactable);let t=this.getFinalColor(e.color,this.colors?.normalColor),i={state:"normal",attributes:{backgroundColor:t,backgroundOpacity:t.alpha}};e.setupState(i);let n=this.getFinalColor(e.color,this.colors?.highlightedColor),r={state:"hovered",attributes:{backgroundColor:n,backgroundOpacity:n.alpha}};e.setupState(r);let o=this.getFinalColor(e.color,this.colors?.pressedColor),s={state:"pressed",attributes:{backgroundColor:o,backgroundOpacity:o.alpha}};e.setupState(s);let c=this.getFinalColor(e.color,this.colors?.selectedColor),d={state:"selected",attributes:{backgroundColor:c,backgroundOpacity:c.alpha}};e.setupState(d);let a=this.getFinalColor(e.color,this.colors?.disabledColor),h={state:"disabled",attributes:{backgroundColor:a,backgroundOpacity:a.alpha}};e.setupState(h)}getFinalColor(e,t){return t?e.clone().multiply(t):e.clone()}};k([A(Oe)],Ft.prototype,"onClick",2),k([A()],Ft.prototype,"colors",2),k([A()],Ft.prototype,"transition",2),k([A()],Ft.prototype,"animationTriggers",2),k([A(bt)],Ft.prototype,"animator",2),k([A()],Ft.prototype,"interactable",1);var vd=class extends nn{set renderOnTop(e){e!==this._renderOnTop&&(this._renderOnTop=e,this.onRenderSettingsChanged())}get renderOnTop(){return this._renderOnTop}_renderOnTop=!1;set depthWrite(e){this._depthWrite!==e&&(this._depthWrite=e,this.onRenderSettingsChanged())}get depthWrite(){return this._depthWrite}_depthWrite=!1;set doubleSided(e){this._doubleSided!==e&&(this._doubleSided=e,this.onRenderSettingsChanged())}get doubleSided(){return this._doubleSided}_doubleSided=!0;set castShadows(e){this._castShadows!==e&&(this._castShadows=e,this.onRenderSettingsChanged())}get castShadows(){return this._castShadows}_castShadows=!0;set receiveShadows(e){this._receiveShadows!==e&&(this._receiveShadows=e,this.onRenderSettingsChanged())}get receiveShadows(){return this._receiveShadows}_receiveShadows=!0;get renderMode(){return this._renderMode}set renderMode(e){this._renderMode!==e&&(this._renderMode=e,this.onRenderSettingsChanged())}_renderMode=-1;_rootCanvas;set rootCanvas(e){this._rootCanvas instanceof vd||(this._rootCanvas=e)}get rootCanvas(){return this._rootCanvas}awake(){this.shadowComponent=this.gameObject,super.awake()}onEnable(){super.onEnable(),this._updateRenderSettingsRoutine=void 0,this.onRenderSettingsChanged()}previousAspect=-1;onBeforeRender(){this.isScreenSpace&&this.context.mainCameraComponent&&this.context.mainCameraComponent.aspect!==this.previousAspect&&(this.previousAspect=this.context.mainCameraComponent.aspect,this.updateRenderMode())}_updateRenderSettingsRoutine;onRenderSettingsChanged(){this._updateRenderSettingsRoutine||(this._updateRenderSettingsRoutine=this.startCoroutine(this._updateRenderSettingsDelayed(),3))}*_updateRenderSettingsDelayed(){if(yield,this._updateRenderSettingsRoutine=void 0,this.shadowComponent){this.updateRenderMode(),Zr(this.shadowComponent,this);for(let e of this.gameObject.getComponentsInChildren(Ue))Zr(e.shadowComponent,this)}}_activeRenderMode=-1;get isScreenSpace(){return this._activeRenderMode===1||this._activeRenderMode===0}updateRenderMode(){if(this.renderMode!==this._activeRenderMode)switch(this.renderMode){case 0:case 1:let e=this.context.mainCameraComponent;if(!e)return;let t=this.gameObject;e.gameObject?.add(t);let n=e.farClipPlane;t.position.x=0,t.position.y=0,t.position.z=-n;let r=Math.tan(Q.toRadians(e.fieldOfView)*n)*(e.aspect*1.333333),o=r*(this.context.domHeight/this.context.domWidth);t.scale.x=-r,t.scale.y=o;break;case 2:break}}},Je=vd;k([A()],Je.prototype,"renderOnTop",1),k([A()],Je.prototype,"depthWrite",1),k([A()],Je.prototype,"doubleSided",1),k([A()],Je.prototype,"castShadows",1),k([A()],Je.prototype,"receiveShadows",1),k([A()],Je.prototype,"renderMode",1),k([A(Je)],Je.prototype,"rootCanvas",1);var sn=class extends M{get alpha(){return this._alpha}set alpha(e){e!==this._alpha&&(this._alpha=e,this.markDirty())}_alpha=1;interactable=!0;blocksRaycasts=!0;_isDirty=!1;markDirty(){this._isDirty||(this._isDirty=!0,this.startCoroutine(this.applyChangesDelayed(),3))}*applyChangesDelayed(){this._isDirty=!1,this.applyChangesNow()}_buffer=[];applyChangesNow(){for(let e of S.getComponentsInChildren(this.gameObject,Rt,this._buffer)){let t=e.color;t.alpha=this._alpha,e.color=t}}};k([A()],sn.prototype,"alpha",1),k([A()],sn.prototype,"interactable",2),k([A()],sn.prototype,"blocksRaycasts",2);import*as Kp from"three-mesh-ui";import{Color as B}from"three";var Vy=N("debugtext");var Le=class extends Rt{canvas;alignment=0;verticalOverflow=0;horizontalOverflow=0;lineSpacing=1;supportRichText=!1;font;fontStyle=0;get text(){return this._text}set text(e){if(this._text=e,!this._textMeshUi&&this._text.length>0&&this.context.time.frame>0&&this.createText(e,this.getTextOpts(),this.supportRichText),this._textMeshUi){if(this._textMeshUi.length>1){this.requestRebuild();return}this._textMeshUi[0].set({content:e}),this.markDirty()}}set_text(e){this.text=e}get fontSize(){return this._fontSize}set fontSize(e){if(this._fontSize=e,this._textMeshUi){if(this._textMeshUi.length>1){this.requestRebuild();return}this._textMeshUi[0].set({content:e}),this.markDirty()}}onColorChanged(){if(this._textMeshUi){if(this._textMeshUi.length>1){this.requestRebuild();return}let e=this.color;this._textMeshUi[0].set({fontColor:e,fontOpacity:e.alpha}),this.markDirty()}}_isWaitingForRebuild=!1;requestRebuild(){this._isWaitingForRebuild||(this._isWaitingForRebuild=!0,this.startCoroutine(this.rebuildDelayedRoutine(),0))}*rebuildDelayedRoutine(){if(this._isWaitingForRebuild=!1,this._textMeshUi){for(let e of this._textMeshUi)e.removeFromParent();this._textMeshUi.length=0}this.createText(this.text,this.getTextOpts(),this.supportRichText),this.markDirty()}onCreate(e){Vy&&console.log(this);let t=this.verticalOverflow==0&&this.horizontalOverflow==0;t&&(this.context.renderer.localClippingEnabled=!0);let i=this.rectTransform;this._textContainer=this.uiObject=this.createBlock(i,t,null,!0),this.createText(this.text,this.getTextOpts(),this.supportRichText),this.uiObject,this.uiObject=this.createBlock(i,t,this.uiObject,!1)}onAfterAddedToScene(){super.onAfterAddedToScene(),this.handleTextRenderOnTop()}_text="";_fontSize=12;_textMeshUi=null;_textContainer=null;getTextOpts(){let e={content:this.text,fontColor:this.color,fontOpacity:this.color.alpha,fontSize:this.fontSize,fontKerning:"normal"};return this.font=this.font?.toLocaleLowerCase(),this.setFont(e,this.fontStyle),e}onEnable(){super.onEnable(),this._didHandleTextRenderOnTop=!1,this.uiObject&&(this.uiObject.onAfterUpdate=this.updateWidth.bind(this))}createBlock(e,t,i,n=!1){let r={};r.hiddenOverflow=t,r.interLine=(this.lineSpacing-1)*this.fontSize*1.333,this.getAlignment(r,n);let o=e.createNewBlock(r);return i&&(Array.isArray(i)?o.add(...i):o.add(i)),o}getAlignment(e,t=!1){switch(t||(e.contentDirection="row"),this.alignment){default:case 0:case 1:case 2:e.justifyContent="start";break;case 3:case 4:case 5:e.justifyContent="center";break;case 6:case 7:case 8:e.justifyContent="end";break}switch(this.alignment){case 0:case 3:case 6:e.alignContent=t?"left":"top";break;case 1:case 4:case 7:e.alignContent="center";break;case 2:case 5:case 8:e.alignContent=t?"right":"bottom";break}return e}updateWidth(){this.horizontalOverflow===1&&setTimeout(()=>{if(!this._textMeshUi)return;let e=this._textMeshUi[0].parent;if(!!e&&e.lines){let t=e.lines.reduce((i,n)=>i+n.width,0);t+=e.getFontSize()*5,t+=e.padding*2||0,t+=this.fontSize*1.5,e.set({width:t}),this.ensureShadowComponentOwner()}},1)}ensureShadowComponentOwner(){this.shadowComponent&&this.shadowComponent.traverse(e=>{e.shadowComponentOwner===void 0&&(e.shadowComponentOwner=this)})}createText(e,t,i){if(!(!e||e.length<=0))if(this._textMeshUi||(this._textMeshUi=[]),i){let n=this.getNextTag(e);if(n)n.startIndex>0&&this.createText(e.substring(0,n.startIndex),t,!1);else return this.createText(e,t,!1);let r=[];for(;n;){let o=this.getNextTag(e,n.endIndex);if(o){let s=this.getText(e,n,o);this.handleTag(n,t,r),this.createText(s,t,!1)}else{let s=e.substring(n.endIndex);this.handleTag(n,t,r),this.createText(s,t,!1)}n=o}}else{let n={...t};n.content=e;let r=new Kp.Text(n);this._textMeshUi.push(r),this._textContainer&&this._textContainer.add(r)}}_didHandleTextRenderOnTop=!1;handleTextRenderOnTop(){this._didHandleTextRenderOnTop||(this._didHandleTextRenderOnTop=!0,this.startCoroutine(this.renderOnTopCoroutine()))}*renderOnTopCoroutine(){if(!this.canvas)return;let e=[],t=this.canvas,i={renderOnTop:t.renderOnTop,depthWrite:t.depthWrite,doubleSided:t.doubleSided};for(;;){let n=!1;if(this._textMeshUi)for(let r=0;r<this._textMeshUi.length;r++){if(e[r]===!0)continue;n=!0;let o=this._textMeshUi[r];!o.textContent||(Zr(o,i),e[r]=!0)}if(!n)break;yield}}handleTag(e,t,i){if(e.isEndTag){if(i.length>0){let n=i.pop();if(n)for(let r in n.previousValues){let o=n.previousValues[r];t[r]=o}}}else if(e.type.includes("color")){let n=new ws(e,{fontColor:t.fontColor});if(i.push(n),e.type.length>6){let r=e.type.substring(6);t.fontColor=Wy(r)}else t.fontColor=new B(1,1,1)}else if(e.type=="b"){let n=new ws(e,{fontFamily:t.fontFamily,fontTexture:t.fontTexture});i.push(n),this.setFont(t,1)}else if(e.type=="i"){let n=new ws(e,{fontFamily:t.fontFamily,fontTexture:t.fontTexture});i.push(n),this.setFont(t,2)}}getText(e,t,i){return e.substring(t.endIndex,i.startIndex)}getNextTag(e,t=0){let i=e.indexOf("<",t),n=e.indexOf(">",i);if(i>=0&&n>=0){let r=e.substring(i+1,n);return{type:r,startIndex:i,endIndex:n+1,isEndTag:r.startsWith("/")}}return null}setFont(e,t){let i=this.getFontName(t),n=i;n?.endsWith("-msdf.json")||(n+="-msdf.json"),e.fontFamily=n;let r=i;r?.endsWith(".png")||(r+=".png"),e.fontTexture=r}getFontName(e){return this.font?this.font:null}};k([A(Je)],Le.prototype,"canvas",2),k([A()],Le.prototype,"alignment",2),k([A()],Le.prototype,"verticalOverflow",2),k([A()],Le.prototype,"horizontalOverflow",2),k([A()],Le.prototype,"lineSpacing",2),k([A()],Le.prototype,"supportRichText",2),k([A()],Le.prototype,"font",2),k([A()],Le.prototype,"fontStyle",2),k([A()],Le.prototype,"text",1),k([A()],Le.prototype,"fontSize",1);var ws=class{tag;previousValues;constructor(e,t){this.tag=e,this.previousValues=t}};function Wy(l){if(l.startsWith("#")){let t=l.substring(1);var e=parseInt(t,16);let i=e>>16&255,n=e>>8&255,r=e&255;return new B(i/255,n/255,r/255)}switch(l){case"black":return new B(0,0,0);case"white":return new B(1,1,1);case"red":return new B(1,0,0);case"lime":return new B(0,1,0);case"blue":return new B(0,0,1);case"yellow":return new B(1,1,0);case"cyan":return new B(0,1,1);case"magenta":return new B(1,0,1);case"silver":return new B(.75,.75,.75);case"gray":return new B(.5,.5,.5);case"maroon":return new B(.5,0,0);case"olive":return new B(.5,.5,0);case"green":return new B(0,.5,0);case"purple":return new B(.5,0,.5);case"teal":return new B(0,.5,.5);case"navy":return new B(0,0,.5);case"darkred":return new B(.54,0,0);case"brown":return new B(.55,.27,0);case"firebrick":return new B(.69,.13,.13);case"crimson":return new B(.86,.08,.24);case"tomato":return new B(1,.39,.28);case"coral":return new B(1,.49,.31);case"indianred":return new B(.6,.31,.51);case"lightcoral":return new B(.94,.5,.5);case"darkorange":return new B(1,.55,0);case"orange":return new B(1,.65,0);case"gold":return new B(1,.84,0);case"darkgoldenrod":return new B(.72,.53,.04);case"goldenrod":return new B(.85,.65,.13);case"palegoldenrod":return new B(.93,.87,.67);case"darkkhaki":return new B(.74,.7,.42);case"khaki":return new B(.94,.9,.55);case"yellowgreen":return new B(.6,.8,.19);case"darkolivegreen":return new B(.33,.42,.18);case"olivedrab":return new B(.42,.56,.14);case"lawngreen":return new B(.49,.99,0);case"chartreuse":return new B(.5,1,0);case"greenyellow":return new B(.68,1,.18);case"darkgreen":return new B(0,.39,0);case"forestgreen":return new B(.13,.55,.13);case"limegreen":return new B(.19,.8,.19);case"lightgreen":return new B(.56,.93,.56);case"palegreen":return new B(.59,.98,.59);case"darkseagreen":return new B(.56,.74,.56);case"mediumspringgreen":return new B(0,.98,.6);case"springgreen":return new B(0,1,.5);case"seagreen":return new B(.18,.31,.31);case"mediumaquamarine":return new B(.4,.8,.66);case"mediumseagreen":return new B(.24,.7,.44);case"lightseagreen":return new B(.13,.7,.67);case"darkslategray":return new B(.18,.31,.31);case"darkcyan":return new B(0,.55,.55);case"aqua":return new B(0,1,1);case"lightcyan":return new B(.8,1,1);case"darkturquoise":return new B(0,.81,.82);case"turquoise":return new B(0,.82,.82);case"mediumturquoise":return new B(.28,.82,.8);case"paleturquoise":return new B(.68,1,.93);case"aquamarine":return new B(.5,1,.83);case"powderblue":return new B(.69,.88,.9);case"cadetblue":return new B(.37,.62,.63);case"steelblue":return new B(.27,.51,.71);case"cornflowerblue":return new B(.39,.58,.93);case"deepskyblue":return new B(0,.7,1);case"dodgerblue":return new B(.12,.56,1);case"lightblue":return new B(.68,.85,.9);case"skyblue":return new B(.53,.81,.92);case"lightskyblue":return new B(.53,.81,.98);case"midnightblue":return new B(.18,.18,.31);case"darkblue":return new B(0,0,.55);case"mediumblue":return new B(0,0,.82);case"royalblue":return new B(.25,.41,.88);case"blueviolet":return new B(.54,.17,.89);case"indigo":return new B(.29,0,.51);case"darkslateblue":return new B(.28,.24,.55);case"slateblue":return new B(.42,.35,.8);case"mediumslateblue":return new B(.48,.41,.9);case"mediumpurple":return new B(.58,.44,.86);case"darkmagenta":return new B(.55,0,.55);case"darkviolet":return new B(.58,0,.83);case"darkorchid":return new B(.6,.2,.8);case"mediumorchid":return new B(.73,.33,.83);case"thistle":return new B(.84,.75,.85);case"plum":return new B(.87,.63,.87);case"violet":return new B(.93,.51,.93);case"fuchsia":return new B(1,0,1);case"orchid":return new B(.85,.44,.84);case"mediumvioletred":return new B(.78,.08,.52);case"palevioletred":return new B(.86,.44,.58);case"hotpink":return new B(1,.4,.71);case"deeppink":return new B(1,.08,.58);case"lightpink":return new B(1,.71,.76);case"pink":return new B(1,.75,.78);case"antiquewhite":return new B(.98,.92,.84);case"beige":return new B(.96,.96,.86);case"bisque":return new B(1,.89,.77);case"blanchedalmond":return new B(1,.92,.82);case"wheat":return new B(.96,.87,.87);case"cornsilk":return new B(1,.97,.86);case"lemonchiffon":return new B(1,.98,.8);case"lightgoldenrodyellow":return new B(.98,.98,.82);case"lightyellow":return new B(1,1,.8);case"saddlebrown":return new B(.55,.27,.07);case"sienna":return new B(.63,.32,.18);case"chocolate":return new B(.82,.41,.12);case"peru":return new B(.82,.52,.25);case"sandybrown":return new B(.96,.64,.38);case"burlywood":return new B(.87,.72,.53);case"tan":return new B(.82,.71,.55);case"rosybrown":return new B(.74,.56,.56);case"moccasin":return new B(1,.89,.71);case"navajowhite":return new B(1,.87,.68);case"peachpuff":return new B(1,.85,.73);case"mistyrose":return new B(1,.89,.88);case"lavenderblush":return new B(1,.94,.93);case"linen":return new B(.98,.94,.9);case"oldlace":return new B(.99,.96,.9);case"papayawhip":return new B(1,.94,.84);case"seashell":return new B(1,.96,.93);case"mintcream":return new B(.98,1,.98);case"slategray":return new B(.44,.5,.56);case"lightslategray":return new B(.47,.53,.6);case"lightsteelblue":return new B(.69,.77,.87);case"lavender":return new B(.9,.9,.98);case"floralwhite":return new B(1,.98,.98);case"aliceblue":return new B(.94,.97,1);case"ghostwhite":return new B(.97,.97,1);case"honeydew":return new B(.94,1,.94);case"ivory":return new B(1,1,.94);case"azure":return new B(.94,1,1);case"snow":return new B(1,.98,.98);case"dimgray":return new B(.4,.4,.4);case"darkgray":return new B(.66,.66,.66);case"lightgray":return new B(.83,.83,.83);case"gainsboro":return new B(.86,.86,.86);case"whitesmoke":return new B(.96,.96,.96)}return new B(1,1,1)}var Rr=N("debuginputfield"),Y=class extends M{get text(){return this.textComponent?.text??""}get isFocused(){return Y.active===this}textComponent;placeholder;onValueChanged;onEndEdit;inputEventFn;start(){Rr&&console.log(this.name,this)}onEnable(){Y.htmlField||(Y.htmlField=document.createElement("input"),Y.htmlField.classList.add("ar"),document.body.appendChild(Y.htmlField)),this.inputEventFn||(this.inputEventFn=this.onInput.bind(this)),Y.htmlField.addEventListener("keyup",this.inputEventFn),this.placeholder&&this.textComponent?.text.length&&S.setActive(this.placeholder.gameObject,!1)}onDisable(){Y.htmlField?.removeEventListener("keyup",this.inputEventFn),this.onDeselected()}onPointerClick(e){Rr&&console.log("CLICK",e,Y.active),Y.activeTime=this.context.time.time,Y.active!==this&&this.startCoroutine(this.activeLoop(),2),this.selectInputField()}*activeLoop(){for(this.onSelected();Y.active===this&&!(this.context.input.getPointerUp(0)&&this.context.time.time-Y.activeTime>.2);)this.setTextFromInputField(),yield;this.onDeselected()}onSelected(){if(Y.active!==this&&(Rr&&console.log("Select",this.name,this,Y.htmlField,this.context.isInXR,this.context.arOverlayElement,this.textComponent?.text,Y.htmlField?.value),Y.active?.onDeselected(),Y.active=this,this.placeholder&&S.setActive(this.placeholder.gameObject,!1),Y.htmlField)){if(Y.htmlField.value=this.textComponent?.text||"",Rr&&console.log("set input field value",Y.htmlField.value),this.context.isInXR){let e=this.context.arOverlayElement;e&&(Y.htmlField.style.width="0px",Y.htmlField.style.height="0px",e.append(Y.htmlField))}this.selectInputField()}}onDeselected(){Y.active===this&&(Y.active=null,Rr&&console.log("Deselect",this.name,this),Y.htmlField&&(Y.htmlField.blur(),document.body.append(Y.htmlField),Y.htmlField.style.width="",Y.htmlField.style.height=""),this.placeholder&&(!this.textComponent||this.textComponent.text.length<=0)&&S.setActive(this.placeholder.gameObject,!0),this.onEndEdit?.invoke())}onInput(e){if(Y.active===this){if(Rr&&console.log(e.code,e,Y.htmlField?.value,this.textComponent?.text),e.code==="Escape"||e.code==="Enter"){this.onDeselected();return}Y.htmlField&&(this.textComponent&&(this.setTextFromInputField(),this.placeholder&&S.setActive(this.placeholder.gameObject,this.textComponent.text.length<=0)),this.selectInputField())}}setTextFromInputField(){if(this.textComponent&&Y.htmlField){if(this.textComponent.text!==Y.htmlField.value){Rr&&console.log("VALUE CHANGED");let e=this.textComponent.text,t=Y.htmlField.value;this.onValueChanged?.invoke(t,e)}this.textComponent.text=Y.htmlField.value}}selectInputField(){Y.htmlField&&(Y.htmlField.setSelectionRange(Y.htmlField.value.length,Y.htmlField.value.length),Y.htmlField.focus())}},Ct=Y;z(Ct,"active",null),z(Ct,"activeTime",-1),z(Ct,"htmlField",null),k([A(Le)],Ct.prototype,"textComponent",2),k([A(Le)],Ct.prototype,"placeholder",2),k([A(Oe)],Ct.prototype,"onValueChanged",2),k([A(Oe)],Ct.prototype,"onEndEdit",2);import*as ef from"three-mesh-ui";import*as _s from"three";var tf=(s=>(s[s.fr=0]="fr",s[s.ru=1]="ru",s[s.de=2]="de",s[s.es=3]="es",s[s.el=4]="el",s[s.nord=5]="nord",s[s.eng=6]="eng",s))(tf||{}),Do=class extends Ue{font;text;keymap;padding;margin;fontSize;borderRadius;colors={keyboardBack:8750469,panelBack:2500134,button:3552822,hovered:1842204,selected:1088605};awake(){super.awake();let e=tf[this.keymap||6];this.makeKeyboard(e)}onEnable(){this.addShadowComponent(this.keyboard)}onDisable(){this.removeShadowComponent()}keyboard=null;_lastKeyPressed;_lastKeyPressedStartTime=0;_lastKeyPressedTime=0;makeKeyboard(e){!e&&!navigator.language&&(e="en");let t=this.font?this.font:"arial",i=this.gameObject.getComponent(ut);if(!i){console.error("Missing rect transform, please add this component inside a canvas");return}let n={...i.getBasicOptions(),margin:this.margin||0,padding:this.padding||0,language:e,fontFamily:Io+"/"+t+"-msdf.json",fontTexture:Io+"/"+t+".png",fontSize:this.fontSize||6,backgroundColor:new _s.Color(this.colors.keyboardBack),backspaceTexture:Io+"/backspace.png",shiftTexture:Io+"/shift.png",enterTexture:Io+"/enter.png",borderRadius:this.borderRadius||0,autoLayout:!1},r=this.gameObject.scale;n.width*=this.gameObject.scale.x,n.height*=this.gameObject.scale.y,n.fontSize*=Math.max(r.x,r.y),this.keyboard=new ef.Keyboard(n),this.gameObject.scale.set(1,1,1),this.keyboard.keys.forEach(o=>{o.setupState({state:"normal",attributes:{offset:.003,backgroundColor:new _s.Color(this.colors.button),backgroundOpacity:1}}),o.setState("normal"),o.setupState({state:"hovered",attributes:{offset:.3,backgroundColor:new _s.Color(this.colors.hovered),backgroundOpacity:1}}),o.setupState({state:"pressed",attributes:{offset:.1,backgroundColor:new _s.Color(this.colors.selected),backgroundOpacity:1},onSet:()=>{let s=o.info.input,c=o.info.command;if(this._lastKeyPressed!==s)this._lastKeyPressedStartTime=this.context.time.time;else if(this.context.time.time-this._lastKeyPressedTime>.05)this._lastKeyPressedStartTime=this.context.time.time;else if(this.context.time.time-this._lastKeyPressedStartTime<.5||c=="switch"||c=="shift"||c=="switch-set"){this._lastKeyPressedTime=this.context.time.time;return}if(this._lastKeyPressedTime=this.context.time.time,this._lastKeyPressed=s,c)switch(c){case"switch":this.keyboard.setNextPanel();break;case"switch-set":this.keyboard.setNextCharset();break;case"enter":this.tryAppend(`
135
+ `);break;case"space":this.tryAppend(" ");break;case"backspace":if(!this.text?.text?.length)break;this.text?.text&&(this.text.text=this.text.text.substring(0,this.text.text.length-1)||"");break;case"shift":this.keyboard.toggleCase();break}else o.info.input!==void 0&&this.tryAppend(o.info.input)}})})}tryAppend(e){this.text&&(this.text.text+=e,this.markDirty())}};var an=class extends M{reverseArrangement=!1},Ho=class extends an{},jo=class extends an{},Bo=class extends an{};var Cr=class extends M{awake(){Ze.createIfNoneExists(this.context)}onEnable(){Ze.instance?.register(this)}onDisable(){Ze.instance?.unregister(this)}performRaycast(e=null){return null}},Si=class extends Cr{targets=null;raycastHits=[];start(){this.targets=[this.gameObject]}performRaycast(e=null){return this.targets?(e??=new je,e.targets=this.targets,e.results=this.raycastHits,this.context.physics.raycast(e)):null}},Fo=class extends Si{eventCamera=null;ignoreReversedGraphics=!1;rootRaycaster=null};import*as nf from"three";import{HTMLMesh as Uy}from"three/examples/jsm/interactive/HTMLMesh.js";import{InteractiveGroup as qy}from"three/examples/jsm/interactive/InteractiveGroup.js";var No=class extends M{id=null;keepAspect=!1;start(){if(!this.id||!this.context.mainCamera)return;let e=document.getElementById(this.id);if(!e){console.warn('Could not find element with id "'+this.id+'"');return}e.style.display="block",e.style.visibility="hidden";let t=new qy(this.context.renderer,this.context.mainCamera);this.gameObject.add(t);let i=new Uy(e);t.add(i),i.visible=!1,console.log(i);let n=i.material;n.transparent=!0,setTimeout(()=>{i.visible=!0;let r=Bs(this.gameObject).clone();Fs(this.gameObject,0,0,0),this.gameObject.updateMatrixWorld();let o=new nf.Box3;o.setFromObject(t),this.setWorldRotation(r.x,r.y,r.z);let s=o.max.x-o.min.x,c=o.max.y-o.min.y;if(this.keepAspect){let a=s/c;s>c?i.scale.set(1/s,1/c/a,1):i.scale.set(1/s*a,1/c,1)}else i.scale.set(1/s,1/c,1);let d=this.gameObject.scale;i.scale.multiply(d)},1)}};var Ja=class extends M{toggleKey=80;update(){this.context.input.isKeyDown(80)&&this.context.domElement.classList.toggle("presentation-mode")}};import*as rf from"three";import{Raycaster as Yy,Vector3 as Zy}from"three";import*as $a from"three";import{MeshLine as Xy,MeshLineMaterial as Qy}from"three.meshline";var yd=class{id=0;points=[];line=new Xy;material;mesh;constructor(e,t){if(t&&(this.material=t.material),this.material||(this.material=this.defaultLineMaterial),t){let i=t.options;i&&Object.assign(this.material,i)}this.mesh=new $a.Mesh(this.line,this.material),e.add(this.mesh)}appendPoint(e){let t=yd.wp;t.set(e.x,e.y,e.z);let i=this.mesh?.parent;return i&&(t=i.worldToLocal(t),e.x=t.x,e.y=t.y,e.z=t.z),this.points.push(e.x,e.y,e.z),this.line.setPoints(this.points),e}defaultLineMaterial=new Qy({color:10066329,lineWidth:.01})},zo=yd;z(zo,"wp",new $a.Vector3);var Sr=class extends M{startLine(e,t){let i=Math.random()*Number.MAX_SAFE_INTEGER;return this.internalStartLine(e,i,!0,t)}updateLine(e,t){let i=this.inFlight[e.id];if(!i)return;t.point&&(t.point=i.appendPoint(t.point));let n=this.buffer[e.id];n&&(t.point&&n.push(t.point.x,t.point.y,t.point.z),n.length>5&&(this.sendLineUpdate(i,!1,void 0,n),n.length=0))}endLine(e,t=!0){let i=this.inFlight[e.id];if(!i)return;this.finished.push(i),delete this.inFlight[e.id],t&&this.sendLineUpdate(i,!0,0);let n=this.buffer[e.id];if(n){delete this.buffer[e.id];let r=n;r.length=0,this.freeBuffer.push(r)}return i}getLine(e){return this.inFlight[e.id]}finished=[];inFlight=[];buffer={};freeBuffer=new Array;awake(){this.context.connection.beginListen("line-start",e=>{this.onEnsureLine(e.id,e.parentGuid)}),this.context.connection.beginListen("line-update",e=>{let t=this.onEnsureLine(e.guid,e.parentGuid);t&&e.points&&(e.startIndex<=0?t.points=e.points:e.startIndex>=t.points.length&&t.points.push(...e.points),t.line.setPoints(t.points),t.material.lineWidth=e.width,t.material.color.fromArray(e.color),e.finished===!0&&this.endLine({id:t.id},!1))})}onEnsureLine(e,t){if(this.inFlight[e])return this.inFlight[e];let i=S.findByGuid(t,this.context.scene);if(!!i)return this.internalStartLine(i,e,!1),this.inFlight[e]}internalStartLine(e,t,i=!0,n){let r=new zo(e??this.context.scene,n);r.id=t,this.inFlight[t]=r,i&&this.sendLineStart(r);let o;return this.freeBuffer.length<=0?o=new Array:o=this.freeBuffer.pop(),this.buffer[t]=o,{id:t}}sendLineStart(e){let t=e.mesh.parent;this.context.connection.send("line-start",{id:e.id,parentGuid:t?t.guid:void 0})}sendLineUpdate(e,t,i,n){if(e){let r={parentGuid:e.mesh.parent.guid,guid:e.id,points:n?[...n]:e.points,width:e.material.lineWidth,color:e.material.color.toArray(),startIndex:i!==void 0?i:e.points.length,finished:t};this.context.connection.send("line-update",r)}}};import{MeshLineMaterial as Jy}from"three.meshline";var Ka=class{isDrawing;lastHit;currentHandle;maxDistance;prevDistance;lastParent;constructor(){this.isDrawing=!1,this.lastHit=new Zy,this.currentHandle=null,this.maxDistance=0,this.prevDistance=0,this.lastParent=null}},el=class extends M{lines;colliders;alignToSurface=!0;addToPaintedObject=!0;orbit;start(){this.lines||(this.lines=S.getComponent(this.gameObject,Sr),this.lines||(this.lines=S.addNewComponent(this.gameObject,Sr))),this.orbit=S.findObjectOfType(gt,this.context)??void 0,this._states.mouse=new Ka;let e={};ae.addEventListener("select-start",(t,i)=>{e[t.controller.uuid]=!0}),ae.addEventListener("update",(t,i)=>{if(e[t.controller.uuid]===!0){let n=t.getRay();this.updateLine(t.controller.uuid,n,!0,!1,!1)}}),ae.addEventListener("select-end",(t,i)=>{e[t.controller.uuid]=!1;let n=t.getRay();this.updateLine(t.controller.uuid,n,!0,!0,!1)})}_states={};update(){this.orbit&&this._states.mouse&&this.orbit&&(this.orbit.enabled=!this._states.mouse.isDrawing);let e=this.context.input.getPointerPressedCount()>1,t=this.context.input.getPointerPositionRC(0);el._raycaster.setFromCamera(t,this.context.mainCamera);let i=el._raycaster.ray;this.updateLine("mouse",i,this.context.input.getPointerPressed(0),this.context.input.getPointerUp(0),e||this.context.input.isKeyPressed(18))}updateLine(e,t,i,n,r=!1){let o=this._states[e];if(o||(this._states[e]=new Ka,o=this._states[e]),n)o.isDrawing=!1,o.currentHandle&&(this.lines.endLine(o.currentHandle),o.currentHandle=null);else if(i){if(r)return o;let s=this.getHit(t),c=null,d=o.prevDistance;if(s)o.currentHandle||(o.maxDistance=s.distance),c=s.point,c.add(s.face.normal.multiplyScalar(.01)),o.prevDistance=s.distance;else if(o.maxDistance>0){let a=o.maxDistance;if(!o.currentHandle&&o.lastHit){let h=q(this.context.mainCamera);a=o.lastHit.distanceTo(h)}c=t.origin.add(t.direction.multiplyScalar(o.maxDistance)),o.prevDistance=o.maxDistance}if(c){if(!o.currentHandle){let a=o.lastParent??this.gameObject;this.addToPaintedObject&&s&&(a=s.object),o.lastParent=a,o.currentHandle=this.lines.startLine(a,{material:this.createRandomMaterial()})}if(this.alignToSurface&&(o.prevDistance>o.maxDistance||Math.abs(d-o.prevDistance)>.2)){let a=o.maxDistance;c=t.origin.add(t.direction.multiplyScalar(a)),o.prevDistance=a}if(o.lastHit&&o.lastHit.distanceTo(c)<o.prevDistance*.01)return o;this.lines.updateLine(o.currentHandle,{point:c}),o.lastHit.copy(c)}o.isDrawing=o.currentHandle!==null}return o}_raycastOptions=new je;getHit(e){(!this.colliders||this.colliders.length===0)&&(this.colliders=[this.gameObject]),this._raycastOptions.targets=this.colliders,this._raycastOptions.ray=e;let t=this.context.physics.raycast(this._raycastOptions);if(t.length>0){for(let i of t)if(!!S.isActiveInHierarchy(i.object))return i}return null}createRandomMaterial(){let e;return this.context.connection.connectionId?e=ht.colorFromHashCode(ht.hashCode(this.context.connection.connectionId)):e=new rf.Color("hsl("+(Math.random()*100).toFixed(0)+", 80%, 30%)"),new Jy({color:e,lineWidth:Q.lerp(.005,.01,Math.random())})}},xs=el;z(xs,"_raycaster",new Yy);import{Object3D as $y}from"three";var Ts=class extends M{asset;joinedRoomFunction;awake(){this.watchTabVisible(),this.joinedRoomFunction=this.onUserJoined.bind(this)}onEnable(){this.context.connection.beginListen("joined-room",this.joinedRoomFunction)}onDisable(){this.context.connection.stopListening("joined-room",this.joinedRoomFunction)}async onUserJoined(e){let t=await this.asset?.instantiateSynced({parent:this.gameObject},!0);if(t){let i=S.getComponent(t,Pi);i&&(i.owner=this.context.connection.connectionId)}}watchTabVisible(){window.addEventListener("visibilitychange",e=>{if(document.visibilityState==="visible")for(let t=Pi.all.length-1;t>=0;t--){let i=Pi.all[t];(!i.owner||!this.context.connection.userIsInRoom(i.owner))&&i.doDestroy()}})}};k([A(tt)],Ts.prototype,"asset",2);var Nt=class extends M{static get all(){return Nt._all}static get local(){return Nt._local}static isLocalPlayer(e){return e instanceof $y?S.getComponentInParent(e,Nt)?.isLocalPlayer??!1:e instanceof ot?S.getComponentInParent(e.gameObject,Nt)?.isLocalPlayer??!1:!1}owner;get isLocalPlayer(){return this.owner===this.context.connection.connectionId}awake(){this.isLocalPlayer&&Nt.local.push(this),Nt.all.push(this),this.context.connection.beginListen("user-left-room",e=>{if(e.userId===this.owner){this.doDestroy();return}})}start(){if(!this.owner||!this.context.connection.userIsInRoom(this.owner)){this.doDestroy();return}}doDestroy(){Lr(this.gameObject,this.context.connection)}onDestroy(){if(Nt.all.splice(Nt.all.indexOf(this),1),this.isLocalPlayer){let e=Nt._local.indexOf(this);e>=0&&Nt._local.splice(e,1)}}},Pi=Nt;z(Pi,"_all",[]),z(Pi,"_local",[]),k([Va(),A()],Pi.prototype,"owner",2);D.add("AlignmentConstraint",_n);D.add("Animation",Jt);D.add("AnimationCurve",sr);D.add("Animator",bt);D.add("AnimatorController",Zt);D.add("AudioListener",$t);D.add("AudioSource",ue);D.add("AvatarModel",ar);D.add("AvatarLoader",xn);D.add("AxesHelper",zi);D.add("BasicIKConstraint",Yr);D.add("BoxHelperComponent",lt);D.add("Camera",ne);D.add("Collider",fi);D.add("SphereCollider",Tn);D.add("BoxCollider",Rn);D.add("InstantiateOptions",ye);D.add("UnityObject",Kr);D.add("DeleteBox",lr);D.add("Deletable",eo);D.add("DeviceFlag",cr);D.add("DragControls",Et);D.add("DropListener",An);D.add("Duplicatable",vi);D.add("CallInfo",yi);D.add("EventListEvent",pr);D.add("EventList",Oe);D.add("EventTrigger",lo);D.add("FlyControls",co);D.add("BoxGizmo",Xi);D.add("GltfExportBox",uo);D.add("GltfExport",jt);D.add("GridHelper",Qi);D.add("GroundProjectedEnv",Yi);D.add("Interactable",kt);D.add("UsageMarker",It);D.add("Light",Ye);D.add("LODModel",Ei);D.add("LODGroup",In);D.add("LookAtConstraint",Fi);D.add("NavMesh",fo);D.add("NavMeshAgent",mo);D.add("NestedGltf",fr);D.add("Networking",pt);D.add("OffsetConstraint",wi);D.add("OrbitControls",gt);D.add("ParticleSystemRenderer",gr);D.add("ParticleSystem",yo);D.add("MainModule",go);D.add("EmissionModule",bo);D.add("ShapeModule",vo);D.add("PlayerColor",ht);D.add("FieldWithDefault",Fr);D.add("Renderer",Te);D.add("MeshRenderer",rr);D.add("SkinnedMeshRenderer",Nr);D.add("InstancingUtil",he);D.add("RendererLightmap",ji);D.add("Rigidbody",ce);D.add("ScreenCapture",Eo);D.add("ShadowCatcher",Mn);D.add("RemoteSkybox",Ln);D.add("SmoothFollow",_i);D.add("SpatialTriggerReceiver",wt);D.add("SpatialTrigger",Zi);D.add("SpectatorCamera",_o);D.add("SpringJoint",xo);D.add("Sprite",br);D.add("SpriteRenderer",Ji);D.add("SyncedCamera",Dn);D.add("SyncedRoom",ti);D.add("SyncedTransform",Qe);D.add("TestRunner",To);D.add("TestSimulateUserData",Ro);D.add("TransformGizmo",vr);D.add("VideoPlayer",nt);D.add("Voip",Ke);D.add("VolumeParameter",Co);D.add("VolumeComponent",xi);D.add("ToneMapping",jn);D.add("ColorAdjustments",Bn);D.add("VolumeProfile",Hn);D.add("Volume",yr);D.add("WebARSessionRoot",Dt);D.add("WebXR",$);D.add("WebAR",On);D.add("AvatarMarker",pe);D.add("WebXRAvatar",Lt);D.add("TeleportTarget",dr);D.add("WebXRController",ae);D.add("AttachedObject",dt);D.add("XRGrabModel",Er);D.add("XRGrabRendering",So);D.add("XRRig",Pn);D.add("VRUserState",Ht);D.add("WebXRSync",qi);D.add("XRState",vt);D.add("XRFlag",Se);D.add("AvatarBlink_Simple",Ti);D.add("AvatarEyeLook_Rotation",Ri);D.add("Avatar_POI",_e);D.add("Avatar_Brain_LookAt",Ui);D.add("Avatar_MouthShapes",Fn);D.add("Avatar_MustacheShake",Po);D.add("LogStats",Oo);D.add("RGBAColor",we);D.add("PlayableDirector",tn);D.add("SignalAsset",wr);D.add("SignalReceiverEvent",_r);D.add("SignalReceiver",$i);D.add("AnimationTrackHandler",Nn);D.add("AudioTrackHandler",zn);D.add("SignalTrackHandler",en);D.add("ControlTrackHandler",Ki);D.add("BaseUIComponent",Ue);D.add("UIRootComponent",nn);D.add("Button",Ft);D.add("Canvas",Je);D.add("CanvasGroup",sn);D.add("EventSystem",Ze);D.add("Graphic",Rt);D.add("MaskableGraphic",rn);D.add("Image",on);D.add("RawImage",Tr);D.add("InputField",Ct);D.add("Keyboard",Do);D.add("LayoutGroup",an);D.add("VerticalLayoutGroup",Ho);D.add("HorizontalLayoutGroup",jo);D.add("GridLayoutGroup",Bo);D.add("PointerEventData",ii);D.add("Raycaster",Cr);D.add("ObjectRaycaster",Si);D.add("GraphicRaycaster",Fo);D.add("Size",Mo);D.add("Rect",xr);D.add("RectTransform",ut);D.add("SpatialHtml",No);D.add("Text",Le);D.add("PresentationMode",Ja);D.add("LinesDrawer",xs);D.add("LineInstanceHandler",zo);D.add("LinesManager",Sr);D.add("PlayerSync",Ts);D.add("PlayerState",Pi);import*as of from"three";import{Color as Ky,Object3D as eE}from"three";var wd=class extends Ni{constructor(){super([Ky,we])}onDeserialize(e){if(e!=null)return e.a!==void 0?new we(e.r,e.g,e.b,e.a):e.alpha!==void 0?new we(e.r,e.g,e.b,e.alpha):new of.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}}},Xj=new wd,_d=class extends Ni{constructor(){super(eE)}onSerialize(e,t){if(t.objectToNode!==void 0&&e.uuid){let i=t.objectToNode[e.uuid];return Ie&&console.log(i,e.name,e.uuid),{node:i}}}onDeserialize(e,t){if(e){if(e.node!==void 0&&t.nodeToObject){let i=t.nodeToObject[e.node];return Ie&&console.log("Deserialized object reference?",e,i,t?.nodeToObject),i||console.warn("Did not find node: "+e.node,t.nodeToObject,t.object),i}else if(e.guid){if(!t.context){console.error("Missing context");return}let i,n=t.gltf?.scene;return n&&(i=S.findByGuid(e.guid,n)),i||(i=S.findByGuid(e.guid,t.context.scene)),i?Ie&&console.log("Deserialized object reference?",e,i,t?.nodeToObject):console.warn("could not resolve reference",e,t.target,t.path,t.context.scene),i}}}},tE=new _d,xd=class extends Ni{constructor(){super([ot,M])}onSerialize(e,t){if(e?.guid)return{guid:e.guid}}onDeserialize(e,t){if(e?.guid){Ie&&console.log(e.guid,t.root,t.object,t.target);let i=this.findObjectForGuid(e.guid,t.root);if(i)return i;if(t.context)return this.findObjectForGuid(e.guid,t.context?.scene)}}findObjectForGuid(e,t){if(t.guid===e)return t;let i=S.foreachComponent(t,n=>{if(n.guid===e)return n},!1);if(i!==void 0)return i;for(let n=0;n<t.children.length;n++){let r=t.children[n],o=this.findObjectForGuid(e,r);if(o)return o}}},Ed=new xd,Td=class extends Ni{constructor(){super([Oe])}onSerialize(e,t){console.log("TODO: SERIALIZE EVENT")}onDeserialize(e,t){if(e&&e.type==="EventList"){Ie&&console.log("DESERIALIZE EVENT",e);let i=new Array;for(let o of e.calls){Ie&&console.log(o);let s=Ed.findObjectForGuid(o.target,t.root);!s&&t.context?.scene&&(s=Ed.findObjectForGuid(o.target,t.context?.scene));let c=o.method?.length>0;if(s&&c){let u=()=>console.warn(`Could not find method ${o.method} on object ${s.name}`,s,typeof s[o.method]);if(typeof s[o.method]!="function"){let f=!1;o.method.startsWith("set_")&&o.method.length>4&&(o.method=o.method.substring(4),s[o.method]!==void 0&&(f=!0)),f||u()}}let d,a=o.argument;o.argument!==void 0?(typeof a=="object"&&(a=tE.onDeserialize(o.argument,t),a||(a=Ed.onDeserialize(o.argument,t))),d=new yi(c?(...u)=>h(...u):void 0,o.enabled)):d=new yi(c?(...u)=>h(...u):void 0,o.enabled);let h=(...u)=>{let f=s[o.method];typeof f=="function"?a!==void 0?f?.call(s,a):f?.call(s,...u):s[o.method]=a};if(d.method||(d.__debuginfo=t.object?.name),!s||!d.method){let u=t.object?"Current object: "+t.object.name+", "+t.object.guid:null;s?console.warn('EventList method not found: "'+o.method+'" on',s):console.warn("EventList is missing target - will be ignored",o.target,u,e)}else i.push(d)}let n=new Oe(i);Ie&&console.log(n);let r=t.target;return r!==void 0&&t.path!==void 0&&n.setEventTarget(t.path,r),n}}},Qj=new Td;var sf=Ie;function Op(l,e){let i=Lc(l,e);return i!==void 0?i:null}async function Ca(l,e,t,i=null,n){if(!t)return;let r=[],o=i;typeof o=="number"&&(o=new We(i));let s=new qr(t.scene);s.gltfId=e,s.context=l,s.gltf=t,s.nodeToObject=n?.nodeToObjectMap;let c=[];if(t.scenes)for(let d of t.scenes)await Cd(s,d,c,r);if(t.children)for(let d of t.children)await Cd(s,d,c,r);l.new_scripts_pre_setup_callbacks.push(()=>{for(let d of c)nE(d,s);if(o){Rd(t,o);for(let d of t.scenes)Rd(d,o)}})}function Rd(l,e){if(e!==null&&!!l){if(l.guid=e.generateUUID(),l&&l.userData&&l.userData.components)for(let t of l.userData.components)t!==null&&(t.guid=e.generateUUID());if(l.children)for(let t of l.children)Rd(t,e)}}var Rs=[];async function Cd(l,e,t,i){if(!e)return;let n=e.userData;if(n){let r=n.builtin_components;if(r&&r.length>0)for(let o of r)try{if(o===null)continue;let s=D.get(o.name);if(s!=null){let c=new s;c.sourceId=l.gltfId,ds(c,o),Is(c,e,!1),t.push({instance:c,compData:o,obj:e})}else sf&&console.debug("unknown component: "+o.name),Rs.includes(o.name)||Rs.push(o.name)}catch(s){console.error(o.name+" - "+s.message,s)}if(Rs.length>0){let o=Rs.join(", ");console.warn("unknown components: "+o),Rs.length=0}}if(e.children)for(let r of e.children)await Cd(l,r,t,i)}function nE(l,e){let{instance:t,compData:i,obj:n}=l;e.object=n,e.target=t;let r=!0;r=cs(t,i,e)===!0,sf&&console.debug("add "+i.name,i,t)}import*as me from"three";import*as af from"three";var rE=new af.FileLoader;async function Sd(l){return new Promise((e,t)=>{rE.load(l,e,void 0,t)})}import{Vector4 as Gn,FileLoader as sE,DataTexture as Id,RGBAFormat as aE,Color as lE}from"three";var Cs=new Uint8Array(4);Cs[0]=255;Cs[1]=255;Cs[2]=255;Cs[3]=255;var df=new Id(Cs,1,1,aE);function hf(l,e=1){let t="alpha"in l,i=e*e,n=new Uint8Array(4*i),r=Math.floor(l.r*255),o=Math.floor(l.g*255),s=Math.floor(l.b*255);for(let d=0;d<i;d++){let a=d*4;n[a+0]=r,n[a+1]=o,n[a+2]=s,t?n[a+3]=Math.floor(l.alpha*255):n[a+3]=255}let c=new Id(n,e,e);return c.needsUpdate=!0,c}function uf(l,e,t,i=1,n=3){let s=i*n,c=[l,e,t],d=c.length,a=new Uint8Array(4*d*s),h=new lE;for(let f=0;f<n;f++){let E=Math.floor(f/n*d),b=Q.clamp(E+1,0,d-1),y=c[E],g=c[b],p=f/n*d%1;h.lerpColors(y,g,p);let m=Math.floor(h.r*255),v=Math.floor(h.g*255),w=Math.floor(h.b*255);for(let x=0;x<i;x++){let T=(f*i+x)*4;a[T+0]=m,a[T+1]=v,a[T+2]=w,a[T+3]=255}}let u=new Id(a,i,n);return u.needsUpdate=!0,u}var Od=class{stage;code;constructor(e,t){this.stage=e,this.code=t}},Ad=class{loaded=new Map;async loadShader(e){let t=await Sd(e);return JSON.parse(t)}async load(e,t){if(this.loaded.has(t))return new Promise((r,o)=>{let s=this.loaded.get(t);s?r(s):o("Shader not found")});let i=await Sd(t),n=new Od(e,i);return this.loaded.set(t,n),n}},lB=new Ad;function Ss(l,e){let t=l.elements;e||(e=[]),e.length=0;for(let i=0;i<16;i+=4){let n=t[i],r=t[i+1],o=t[i+2],s=t[i+3],c=new Gn(n,r,o,s);e.push(c)}return e}var Pd=[],lf=[];function Md(l,e){if(Pd.length===0)for(let t=0;t<27;t++)Pd.push(0);e||(e=Pd);for(let t=0;t<27;t++)lf[t]=e[t];e=lf,l.unity_SHAr={value:new Gn(e[9],e[3],e[6],e[0])},l.unity_SHBr={value:new Gn(e[12],e[15],e[18],e[21])},l.unity_SHAg={value:new Gn(e[10],e[4],e[7],e[1])},l.unity_SHBg={value:new Gn(e[13],e[16],e[19],e[22])},l.unity_SHAb={value:new Gn(e[11],e[5],e[8],e[2])},l.unity_SHBb={value:new Gn(e[14],e[17],e[20],e[23])},l.unity_SHC={value:new Gn(e[24],e[25],e[26],1)}}var kd=class{vertexShader;fragmentShader;technique;constructor(e,t,i){this.vertexShader=e,this.fragmentShader=t,this.technique=i}};async function pf(l,e){if(!l)return console.error("Can not find technique: no shader data"),null;let t=l.programs[e],i=t.vertexShader,n=t.fragmentShader;if(i!==void 0&&n!==void 0){let r=l.shaders[i],o=l.shaders[n];if(r.uri&&o.uri||r.code&&o.code){if(!r.code&&r.uri&&await cf(r),!o.code&&o.uri&&await cf(o),!r.code||!o.code)return null;let s=l.techniques[e];return new kd(r.code,o.code,s)}}return console.error("Shader technique not found",e),null}async function cf(l){let e=l.uri;if(!!e)if(e.endsWith(".glsl")){let i=await new sE().loadAsync(e);l.code=i.toString()}else l.code=cE(l.uri)}function cE(l){return decodeURIComponent(Array.prototype.map.call(atob(l),function(e){return"%"+("00"+e.charCodeAt(0).toString(16)).slice(-2)}).join(""))}import{RawShaderMaterial as hE}from"three";var ln=N("debugshaders"),Go="NEEDLE_techniques_webgl";var Ld=class{objectToWorldMatrix=new me.Matrix4;worldToObjectMatrix=new me.Matrix4;objectToWorld=new Array;worldToObject=new Array;updateFrom(e){this.objectToWorldMatrix.copy(e.matrixWorld),Ss(this.objectToWorldMatrix,this.objectToWorld),this.worldToObjectMatrix.copy(e.matrixWorld).invert(),Ss(this.worldToObjectMatrix,this.worldToObject)}};var fe=class extends hE{identifier;onBeforeRenderSceneCallback=this.onBeforeRenderScene.bind(this);constructor(e,...t){super(...t),this.identifier=e,ln&&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}ln&&console.log(t);let i=t.array,n=t.texture;this.uniforms.unity_SpecCube0={value:n},Md(this.uniforms,i);let r=Math.sqrt(Math.PI*.5);this.uniforms.unity_SpecCube0_HDR={value:new me.Vector4(r,r,r,r)},ln&&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 Ld;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,i,n,r,o){n.attributes.tangent||n.computeTangents(),this.onUpdateUniforms(i,r)}onUpdateUniforms(e,t){let i=Z.Current;e&&(fe.viewProjection&&this.uniforms[this._viewProjectionName]&&(fe.viewProjection.copy(e.projectionMatrix).multiply(e.matrixWorldInverse),Ss(fe.viewProjection,fe._viewProjectionValues)),fe.viewMatrix&&this.uniforms[this._viewMatrixName]&&(fe.viewMatrix.copy(e.matrixWorldInverse),Ss(fe.viewMatrix,fe._viewMatrixValues)),this.uniforms[fe._worldSpaceCameraPosName]&&fe._worldSpaceCameraPos.setFromMatrixPosition(e.matrixWorld)),this.uniforms._TimeParameters&&(this.uniforms._TimeParameters.value=i.rendererData.timeVec4);let n=i?.mainLight;if(n){let s=n.getWorldPosition(fe._mainLightPosition);this.uniforms._MainLightPosition={value:s.normalize()},fe._mainLightColor.set(n.color.r,n.color.g,n.color.b,0),this.uniforms._MainLightColor={value:fe._mainLightColor};let c=n.intensity;fe._lightData.z=c,this.uniforms.unity_LightData={value:fe._lightData}}if(e&&(fe.viewProjection&&this.uniforms[this._viewProjectionName]&&(this.uniforms[this._viewProjectionName].value=fe._viewProjectionValues),fe.viewMatrix&&this.uniforms[this._viewMatrixName]&&(this.uniforms[this._viewMatrixName].value=fe._viewMatrixValues),this.uniforms[fe._worldSpaceCameraPosName]&&(this.uniforms[fe._worldSpaceCameraPosName]={value:fe._worldSpaceCameraPos}),i.mainCameraComponent)){if(this.uniforms._ProjectionParams){let s=this.uniforms._ProjectionParams.value;s.x=1,s.y=i.mainCameraComponent.nearClipPlane,s.z=i.mainCameraComponent.farClipPlane,s.w=1/s.z,this.uniforms._ProjectionParams.value=s}if(this.uniforms._ZBufferParams){let s=this.uniforms._ZBufferParams.value,c=i.mainCameraComponent;s.x=1-c.farClipPlane/c.nearClipPlane,s.y=c.farClipPlane/c.nearClipPlane,s.z=s.x/c.farClipPlane,s.w=s.y/c.farClipPlane,this.uniforms._ZBufferParams.value=s}if(this.uniforms._ScreenParams){let s=this.uniforms._ScreenParams.value;s.x=i.domWidth,s.y=i.domHeight,s.z=1+1/s.x,s.w=1+1/s.y,this.uniforms._ScreenParams.value=s}}let r=this.depthTextureUniform;r&&(r.value=i.depthTexture);let o=this.opaqueTextureUniform;if(o&&(o.value=i.opaqueColorTexture),t){let s=this._rendererData;s.updateFrom(t),this.uniforms[this._worldToObjectName].value=s.worldToObject,this.uniforms[this._objToWorldName].value=s.objectToWorld}this.uniformsNeedUpdate=!0}},zt=fe;z(zt,"viewProjection",new me.Matrix4),z(zt,"_viewProjectionValues",[]),z(zt,"viewMatrix",new me.Matrix4),z(zt,"_viewMatrixValues",[]),z(zt,"_worldSpaceCameraPosName","_WorldSpaceCameraPos"),z(zt,"_worldSpaceCameraPos",new me.Vector3),z(zt,"_mainLightColor",new me.Vector4),z(zt,"_mainLightPosition",new me.Vector3),z(zt,"_lightData",new me.Vector4);var tl=class{get name(){return Go}parser;identifier;constructor(e,t){this.parser=e,this.identifier=t}loadMaterial(e){let t=this.parser.json.materials[e];if(!t)return ln&&console.log(e,this.parser.json.materials),null;if(!t.extensions||!t.extensions[Go])return ln&&console.log("material "+e+" does not use NEEDLE_techniques_webgl"),null;let i=t.extensions[Go].technique;if(i<0)return null;let n=this.parser.json.extensions[Go];if(!n)return null;ln&&console.log(n);let r=n.techniques[i];return r?new Promise(async(o,s)=>{let c=await pf(n,r.program),d=c?.fragmentShader,a=c?.vertexShader;if(!d||!a)return s();ln&&console.log("loadMaterial",t,c);let h={},u=r.uniforms;for(let y in u){let g=y;switch(g){case"_TimeParameters":let p=new me.Vector4;h[g]={value:p};break;case"hlslcc_mtx4x4unity_MatrixV":case"hlslcc_mtx4x4unity_MatrixVP":h[g]={value:[]};break;case"_MainLightPosition":case"_MainLightColor":case"_WorldSpaceCameraPos":h[g]={value:[0,0,0,1]};break;case"unity_OrthoParams":break;case"unity_SpecCube0":h[g]={value:null};break;default:case"_ScreenParams":case"_ZBufferParams":case"_ProjectionParams":h[g]={value:[0,0,0,0]};break;case"_CameraOpaqueTexture":case"_CameraDepthTexture":h[g]={value:null};break}}let f=!1;if(t.extensions&&t.extensions[Go]){let y=t.extensions[Go];if(y.technique===i){ln&&console.log(t.name,"Material Properties",y);for(let g in y.values){let p=y.values[g];if(typeof p=="string"){if(p.startsWith("/textures/")){let m=p.substring(10),v=Number.parseInt(m);if(v>=0){let w=await this.parser.getDependency("texture",v);w&&(w.encoding=me.LinearEncoding,w.needsUpdate=!0),h[g]={value:w};continue}}switch(g){case"alphaMode":p==="BLEND"&&(f=!0);continue}}if(Array.isArray(p)&&p.length===4){h[g]={value:new me.Vector4(p[0],p[1],p[2],p[3])};continue}h[g]={value:p}}}}let E=new zt(this.identifier,{name:t.name??"",uniforms:h,vertexShader:a,fragmentShader:d,lights:!1});switch(h._Cull?.value){case 0:E.side=me.DoubleSide;break;case 1:E.side=me.BackSide;break;case 2:E.side=me.FrontSide;break;default:E.side=me.FrontSide;break}E.transparent=f,f&&(E.depthWrite=!1),Md(h),E.onUpdateUniforms();for(let y in u){let g=y,p=u[y].type;if(h[g]?.value===void 0)switch(p){case 35678:h[g]={value:df},console.warn("Missing/unassigned texture, fallback to white: "+g);break;default:console.warn("TODO: EXPECTED UNIFORM / fallback NOT SET: "+g,u[y]);break}}ln&&console.log(E.uuid,h),o(E)}):null}};import{EXRLoader as uE}from"three/examples/jsm/loaders/EXRLoader";var Dd=N("debugexr"),il=class{constructor(e){this.parser=e,this.name="EXT_texture_exr",Dd&&console.log(e)}loadTexture(e){let t=this.name,i=this.parser,r=i.json.textures[e];if(Dd&&console.log("EXT_texture_exr.loadTexture",e,r),!r.extensions||!r.extensions[t])return null;let o=r.extensions[t],s=new uE(i.options.manager);return Dd&&console.log("EXT_texture_exr.loadTexture",o,s),i.loadTextureImage(e,o.source,s)}};var ff="NEEDLE_gameobject_data",nl=class{get name(){return ff}parser;constructor(e){this.parser=e}afterRoot(e){let t=[];for(let i=0;i<this.parser.json.nodes.length;i++){let n=this.parser.json.nodes[i];if(n&&n.extensions){let r=n.extensions[ff];if(r){let o=this.findAndApplyExtensionData(i,r);t.push(o)}}}return Promise.all(t).then(()=>{})}async findAndApplyExtensionData(e,t){let i=await this.parser.getDependency("node",e);i&&this.applyExtensionData(i,t)}applyExtensionData(e,t){e.userData.layer=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{FloatType as pE,HalfFloatType as fE,sRGBEncoding as mE}from"three";var mf="NEEDLE_lightmaps",gE=N("debuglightmapsextension"),Ps=(i=>(i[i.Lightmap=0]="Lightmap",i[i.Skybox=1]="Skybox",i[i.Reflection=2]="Reflection",i))(Ps||{}),rl=class{get name(){return mf}parser;registry;source;constructor(e,t,i){this.parser=e,this.registry=t,this.source=i}afterRoot(e){let t=this.parser.json.extensions;if(t){let i=t[mf];if(i){let n=i.textures;return n.length?(gE&&console.log(i),new Promise(async(r,o)=>{let s=[];for(let c of n)if(c.pointer){let d=Ur(this.parser,c.pointer).then(a=>{let h=a;h?.isTexture&&(this.registry?(c.type!==0&&(h.encoding=mE),(h.type==pE||h.type==fE)&&(h.flipY=!0),this.registry.registerTexture(this.source,c.type,h,c.index)):console.log(Ps[c.type],c.pointer,h))});s.push(d)}await Promise.all(s),r()})):null}}return null}};import{AmbientLight as EE,Color as gf,HemisphereLight as wE}from"three";import{Vector4 as bE,EquirectangularReflectionMapping as ol,sRGBEncoding as sl,WebGLCubeRenderTarget as vE}from"three";import{LightProbeGenerator as yE}from"three/examples/jsm/lights/LightProbeGenerator.js";var Hd=N("debugenvlight"),Bd=(n=>(n[n.Skybox=0]="Skybox",n[n.Trilight=1]="Trilight",n[n.Flat=3]="Flat",n[n.Custom=4]="Custom",n))(Bd||{});var al=class{context;constructor(e){this.context=e,this.context.pre_update_callbacks.push(this.preUpdate.bind(this))}sceneLightSettings;preUpdate(){let e=this.context.time;this._timevec4.x=e.time,this._timevec4.y=Math.sin(e.time),this._timevec4.z=Math.cos(e.time),this._timevec4.w=e.deltaTime}_timevec4=new bE;get timeVec4(){return this._timevec4}get environmentIntensity(){return this.sceneLightSettings?this.sceneLightSettings.ambientIntensity:1}registerSceneLightSettings(e){this.sceneLightSettings=e}registerReflection(e,t){let i=new jd(this.context,t,1);this._lighting[e]=i}getReflection(e){return this._lighting[e]}enableReflection(e){switch(Hd&&console.log(this.sceneLightSettings?Bd[this.sceneLightSettings.ambientMode]:"Unknown ambient mode"),this.sceneLightSettings?.ambientMode){case 0:case 4:let t=this.getReflection(e);if(t&&t.Source){let i=this.context.scene,n=t.Source;n.encoding=sl,n.mapping=ol,i.environment=n;return}break}if(this.sceneLightSettings?.environmentReflectionSource===1)switch(this.sceneLightSettings?.ambientMode){case 1:if(this.sceneLightSettings.ambientTrilight){let t=this.sceneLightSettings.ambientTrilight,i=uf(t[0],t[1],t[2],64,64);i.encoding=sl,i.mapping=ol,this.context.scene.environment=i}else console.error("Missing ambient trilight",this.sceneLightSettings.sourceId);return;case 3:if(this.sceneLightSettings.ambientLight){let t=hf(this.sceneLightSettings.ambientLight,64);t.encoding=sl,t.mapping=ol,this.context.scene.environment=t}else console.error("Missing ambientlight",this.sceneLightSettings.sourceId);return;default:return}}disableReflection(){let e=this.context.scene;e.environment=null}async getSceneLightingData(e){return Hd&&console.log("GET SCENE LIGHT DATA"),this._waitPromise?this._waitPromise:(this._waitPromise=new Promise((t,i)=>{let n=setInterval(async()=>{let r=this.getReflection(e);r&&(clearInterval(n),t(r.getSphericalHarmonicsArray(this.sceneLightSettings?.ambientIntensity??1)))},10)}),this._waitPromise)}_waitPromise;_lighting={}},jd=class{get Source(){return this._source}get Array(){return this._sphericalHarmonicsArray}_context;_source;_sphericalHarmonics=null;_sphericalHarmonicsArray;_ambientScale=1;_lightProbe;constructor(e,t,i=1){this._context=e,this._source=t,this._ambientScale=i,t.mapping=ol,t.encoding=sl}getSphericalHarmonicsArray(e=1){if(this._sphericalHarmonicsArray?.length&&this._source)return{array:this._sphericalHarmonicsArray,texture:this._source,lightProbe:this._lightProbe};try{let t=this._source,i=null;if(t){Hd&&console.log("GENERATING LIGHT PROBE",t);let n=Math.min(t.image.width,512);i=new vE(n).fromEquirectangularTexture(this._context.renderer,t),this._source=i.texture}if(this._sphericalHarmonicsArray=[],i){let n=yE.fromCubeRenderTarget(this._context.renderer,i);this._lightProbe=n;let r=this._ambientScale*(e*e*Math.PI*.5)-1;this._sphericalHarmonics=n.sh,this._sphericalHarmonicsArray=this._sphericalHarmonics.toArray();let o=e/(Math.PI*.5);for(let s=0;s<this._sphericalHarmonicsArray.length;s++)this._sphericalHarmonicsArray[s]*=o;if(n.sh.scale(r),this._source)return{array:this._sphericalHarmonicsArray,texture:this._source,lightProbe:n}}}catch(t){console.error(t)}return null}};var bf="NEEDLE_lighting_settings",Os=N("debugenvlight"),ll=class{get name(){return bf}parser;sourceId;context;constructor(e,t,i){this.parser=e,this.sourceId=t,this.context=i}afterRoot(e){let t=this.parser.json.extensions;if(t){let i=t[bf];if(i){Os&&console.log(i);let n=S.addNewComponent(e.scene,Fd,!1);n.sourceId=this.sourceId,n.ambientIntensity=i.ambientIntensity,n.ambientLight=new gf().fromArray(i.ambientLight),Array.isArray(i.ambientTrilight)&&(n.ambientTrilight=i.ambientTrilight.map(r=>new gf().fromArray(r))),n.ambientMode=i.ambientMode,n.environmentReflectionSource=i.environmentReflectionSource,this.context&&this.context.rendererData.registerSceneLightSettings(n)}}return null}},Fd=class extends M{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)}Os&&window.addEventListener("keydown",e=>{switch(e.key){case"l":this.enabled=!this.enabled;break}})}onEnable(){let e=this.context.mainCameraComponent?.sourceId===this.sourceId;if(Os&&console.log("enable",this.sourceId,e,this,this.context.mainCameraComponent?.sourceId),this.ambientMode==3)this.ambientLight&&(this._ambientLightObj=new EE(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],i=this.ambientTrilight[this.ambientTrilight.length-1],n=new wE(i,t,this.ambientIntensity);this.gameObject.add(n)}}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=>{Os&&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(){Os&&console.log("disable",this.sourceId,this),this._lightProbeObj&&this._lightProbeObj.removeFromParent(),this.sourceId&&this.context.rendererData.disableReflection()}};function zd(l){let e=new ho;return l.register(t=>(e.parser=t,e)),e}var Nd=class{resolvePath(e){return e.includes("/extensions/builtin_components/")&&(e=e.replace("/extensions/builtin_components/","/userData/components/")),e}};function Gd(l,e,t){l.register(n=>new nl(n)),l.register(n=>new ba(n)),l.register(n=>new rl(n,e.lightmaps,t)),l.register(n=>new ll(n,t,e)),l.register(n=>new tl(n,t)),l.register(n=>new ir(n,t)),l.register(n=>new Bi(n,t,e)),l.register(n=>new il(n));let i=l.setAnimationPointerResolver;typeof i=="function"&&i.bind(l)(new Nd)}var _E=N("printGltf");var Vn=class{context;loader;path;gltf;constructor(e,t,i,n){this.context=e,this.path=t,this.loader=i,this.gltf=n}},vf={};function Vo(l,e){if(vf[l])for(let t of vf[l])t(e)}async function Ef(l,e,t,i,n){_E&&console.log(t),await l.assets.registerGltf(t),await Ca(l,e,t,i,n)}function Qr(l,e,t,i){typeof t!="string"&&console.warn("Parse gltf binary without path, this might lead to errors in resolving extensions. Please provide the source path of the gltf/glb file",t,typeof t);let n=new yf;Gd(n,l,t);let o=zd(n);return new Promise((s,c)=>{try{nr(n,l),Vo(0,new Vn(l,t,n)),n.parse(e,t,async d=>{Vo(1,new Vn(l,t,n,d)),await Ef(l,t,d,i,o),Vo(10,new Vn(l,t,n,d)),s(d)},d=>{console.error("failed loading "+t,d),s(void 0)})}catch(d){console.error(d),c(d)}})}function ur(l,e,t,i=!1,n){let r=new yf;Gd(r,l,e);let s=zd(r);return new Promise((c,d)=>{try{nr(r,l),Vo(0,new Vn(l,e,r)),r.load(e,async a=>{Vo(1,new Vn(l,e,r,a)),await Ef(l,e,a,t,s),Vo(10,new Vn(l,e,r,a)),c(a)},a=>{n?.call(r,a)},a=>{console.error("failed loading "+e,a),c(void 0)})}catch(a){console.error(a),d(a)}})}import*as Wn from"three";function cl(l,e,t){let i=S.getComponentInChildren(l,Et);if(i||(i=S.addNewComponent(l,Et,!1),i.guid=e.generateUUID()),i&&!S.getComponent(i.gameObject,Qe)){let r=S.addNewComponent(i.gameObject,Qe,!1);r.guid=e.generateUUID()}if(i&&!S.getComponentInParent(i.gameObject,Si)){let r=S.addNewComponent(i.gameObject,Si,!1);r.guid=e.generateUUID()}if(t&&t.animations?.length>0){let r=t.animations[0],o=S.addNewComponent(l,Jt,!1);o.animations=[r]}let n=!1;l.traverse(r=>{!r||r.isSkinnedMesh===!0&&(n||console.log("Disabling frustum culling for skinned meshes",t),n=!0,r.frustumCulled=!1)})}var Vd=class{guid;file_name;file_hash;file_size;position;seed;sender;serverUrl;parentGuid;boundsSize;constructor(e,t,i,n,r,o,s,c){this.seed=t,this.guid=i,this.file_name=n,this.file_hash=r,this.file_size=o,this.position=s,this.sender=e,this.serverUrl=c}};async function xp(l,e,t){let i=l.name;return i.endsWith(".gltf")||i.endsWith(".glb")?new Promise((n,r)=>{let o=new FileReader;o.readAsDataURL(l),o.onloadend=async s=>{let c=o.result,d=Vs(),a=new We(d),h=await ur(e,c,a,!0);if(h&&h.scene){let u=h.scene;if(!u.guid){let f=new We(d);u.guid=f.generateUUID()}t&&TE(e.connection,l,d,u,t),cl(u,a,h),n(h)}}}):(console.warn("Unsupported file type: "+i),console.log(l),null)}async function Tp(l,e){return new Promise(async(t,i)=>{let n=Vs(),r=new We(n),o=await ur(e,l.toString(),r,!0);if(o&&o.scene){let s=o.scene;cl(s,r,o),t(o)}else console.warn("Unsupported file type: "+l.toString())})}function wf(l){l.connection.beginListen("file-spawned",async e=>{if(e.sender!==l.connection.connectionId){console.log("received file event",e),RE(e,l);let t=null;try{t=await Ta(e.file_name,e.file_hash,e.file_size,e.serverUrl)}finally{CE(e,l)}if(t){let i=new We(e.seed),n=await Qr(l,t,null,i);if(n&&n.scene){let r=n.scene;if(cl(r,i,n),e.parentGuid){let o=S.findByGuid(e.parentGuid,l.scene);"add"in o&&o.add(r)}r.parent||l.scene.add(r),e.position!==null&&r.position.copy(e.position)}}else console.error("download didnt return file")}})}async function TE(l,e,t,i,n){if(!l.connectionId){console.error("Can not upload file - no connection id");return}if(!i.guid){console.error("Can not upload file - no guid",i,i.guid);return}let r=await dp(e,n);if(!r)return;if(!r.filename){console.error("Can not send upload event - no filename",e.name);return}if(!r.hash){console.error("Can not send upload event - no hash",e.name);return}let o=new Vd(l.connectionId,t,i.guid,r.filename,r.hash,e.size,i.position,r.url??n);i.parent&&(o.parentGuid=i.parent.guid),l.send("file-spawned",o)}var Wd={};function RE(l,e){let t=new Wn.BoxGeometry,i=new Wn.Mesh(t,new Wn.MeshBasicMaterial({color:65280})),n=new Wn.BoxHelper(i,5592405);if(Wd[l.guid]=n,e.scene.add(n),l.parentGuid){let r=S.findByGuid(l.parentGuid,e.scene);r&&r.add(n)}l.position&&n.position.copy(l.position)}function CE(l,e){let t=l.guid,i=Wd[t];i&&(delete Wd[t],i.removeFromParent())}import*as _f from"three";var vF=N("debugassets");var dl=class{constructor(){window.addEventListener("unhandledrejection",e=>{if(e.defaultPrevented)return;let t=e?.reason?.path;if(t){let i=t[0];i&&i.tagName==="IMG"&&(console.warn(`Could not load image:
136
136
  `+i.src),e.preventDefault())}})}texturesLoader=new _f.TextureLoader;textures={};texturesLoading={};async loadTexture(e){if(this.textures[e])return this.textures[e];if(this.texturesLoading[e])return await this.texturesLoading[e];let t=this.texturesLoader.loadAsync(e);this.texturesLoading[e]=t;let i=await t;return delete this.texturesLoading[e],this.textures[e]=i,i}getTexture(e){return this._textures.get(e)||null}findTexture(e){for(let t of this._textures.values())if(t.name===e)return t;return null}findMesh(e){for(let t of this._meshes.values())if(t.name===e)return t;return null}findMaterial(e){for(let t of this._materials.values())if(t.name===e)return t;return null}async registerGltf(e){}registerAsset(e){}_materials=new Map;_meshes=new Map;_textures=new Map};import*as Tf from"three/examples/jsm/libs/stats.module";import*as Oi from"three";var xf=!!N("debuglightmaps"),hl=class{_context;_lightmaps=new Map;constructor(e){this._context=e}registerTexture(e,t,i,n){xf&&console.log("Registering lightmap",e,Ps[t],i),this._lightmaps.has(e)||this._lightmaps.set(e,new Map);let r=this._lightmaps.get(e),o=r?.get(t)??[];o.length<n&&(o.length=n+1),o[n]=i,r?.set(t,o)}tryGetLightmap(e,t=0){return this.tryGet(e,0,t)}tryGetSkybox(e){return this.tryGet(e,1,0)}tryGetReflection(e){return this.tryGet(e,2,0)}tryGet(e,t,i){if(!e)return xf&&console.warn("Missing source id"),null;let n=this._lightmaps.get(e)?.get(t)??null;return!n?.length||n.length<=i?null:n[i]}};Oi.ShaderChunk.lights_fragment_maps=Oi.ShaderChunk.lights_fragment_maps.replace("vec4 lightMapTexel = texture2D( lightMap, vUv2 );",`
137
137
 
138
138
  vec2 lUv = vUv2.xy * lightmapScaleOffset.xy + vec2(lightmapScaleOffset.z, (1. - (lightmapScaleOffset.y + lightmapScaleOffset.w)));
@@ -157,7 +157,7 @@ a=extmap-allow-mixed`)!==-1){var m=p.sdp.split(`
157
157
  irradiance += 0.;
158
158
  #else
159
159
  irradiance += getLightProbeIrradiance( lightProbe, geometry.normal );
160
- #endif`);Oi.UniformsLib.lightmap.lightmapScaleOffset={value:new Oi.Vector4(1,1,0,0)};var kE=N("debugSetup"),IE=N("stats"),ul={};var St=class{static get Current(){return this._current}static set Current(e){this._current=e}name;alias;isManagedExternally=!1;domElement;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}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;_sizeChanged=!1;_isCreated=!1;_stats=IE?Tf.default():null;constructor(e){if(this.name=e?.name||"",this.alias=e?.alias,this.domElement=e?.domElement||document.body,e?.renderer)this.renderer=e.renderer,this.isManagedExternally=!0;else{let i=N("postfx");this.renderer=new PE({antialias:!0}),this.renderer.toneMappingExposure=1,this.renderer.toneMapping=De.NoToneMapping,this.renderer.setClearColor(new De.Color("lightgrey"),0),this.renderer.antialias=!0,this.renderer.alpha=!1,this.renderer.shadowMap.enabled=!0,this.renderer.shadowMap.type=De.PCFSoftShadowMap,this.renderer.setSize(this.domWidth,this.domHeight),this.renderer.outputEncoding=De.sRGBEncoding,this.renderer.physicallyCorrectLights=!0,this.composer=i?new OE(this.renderer):null}this.scene=new De.Scene,this.application=new _a(this),this.time=new la,this.input=new Ws(this),this.physics=new aa(this),this.connection=new fa(this),this.assets=new dl,this.rendererData=new al(this),this.addressables=new Ha(this),this.lightmaps=new hl(this),window.addEventListener("resize",this.updateSize.bind(this)),new ResizeObserver(i=>this._sizeChanged=!0).observe(this.domElement)}updateSize(){if(!this.isManagedExternally&&!this.renderer.xr.isPresenting){this._sizeChanged=!1;let e=this.domWidth,t=this.domHeight,i=this.mainCamera;this.updateAspect(i),this.renderer.setSize(e,t),this.renderer.setPixelRatio(window.devicePixelRatio),this.composer&&(this.composer.setSize(e,t),this.composer.setPixelRatio(window.devicePixelRatio))}}updateAspect(e){if(!e)return;let t=this.domWidth,i=this.domHeight,n=e.aspect;e.aspect=t/i,n!==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,S.destroy(this.scene,!0),this.renderer?.setAnimationLoop(null),this.isManagedExternally||this.renderer?.dispose())}registerCoroutineUpdate(e,t,i){return this.coroutines[i]||(this.coroutines[i]=[]),this.coroutines[i].push({comp:e,main:t}),t}unregisterCoroutineUpdate(e,t){if(!this.coroutines[t])return;let i=this.coroutines[t].findIndex(n=>n.main===e);i>=0&&this.coroutines[t].splice(i,1)}stopAllCoroutinesFrom(e){for(let t in this.coroutines){let i=this.coroutines[t];for(let n=i.length-1;n>=0;n--)i[n].comp===e&&i.splice(n,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 i=e.cam;i.isPerspectiveCamera&&this.updateAspect(i),this.mainCameraComponent?.applyClearFlagsIfIsActiveCamera()}_onBeforeRenderListeners={};addBeforeRenderListener(e,t){if(!this._onBeforeRenderListeners[e.uuid]){this._onBeforeRenderListeners[e.uuid]=[];let i=(n,r,o,s,c,d)=>{let a=this._onBeforeRenderListeners[e.uuid];if(!!a)for(let h=0;h<a.length;h++){let u=a[h];u(n,r,o,s,c,d)}};e.onBeforeRender=i}this._onBeforeRenderListeners[e.uuid].push(t)}removeBeforeRenderListener(e,t){if(this._onBeforeRenderListeners[e.uuid]){let i=this._onBeforeRenderListeners[e.uuid],n=i.indexOf(t);n>=0&&i.splice(n,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){let i=!0;try{St.Current=this,e&&await e(this,t)}catch(r){console.error(r),i=!1}if(!i)return;this.isManagedExternally||this.domElement.prepend(this.renderer.domElement),Dh(this),Lh(this),wf(this),St._current=this;for(let r=0;r<this.new_scripts.length;r++){let o=this.new_scripts[r];if(o.gameObject!==void 0&&o.gameObject!==null){o.gameObject.userData===void 0&&(o.gameObject.userData={}),o.gameObject.userData.components===void 0&&(o.gameObject.userData.components=[]);let s=o.gameObject.userData.components;s.includes(o)||s.push(o)}}if(this.post_setup_callbacks)for(let r=0;r<this.post_setup_callbacks.length;r++)St._current=this,await this.post_setup_callbacks[r](this);if(!this.mainCamera){St._current=this;let r=S.findObjectsOfType(ne,this),o=r.find(s=>s.tag=="MainCamera")??r.find(s=>!0);if(o)o.tag!=="MainCamera"&&console.warn('No mainCamera configured. Some components rely on a mainCamera object being present. When exporting your scene, make sure to set the mainCamera tag on your camera. Using "'+o.name+'" as mainCamera now.'),this.setCurrentCamera(o);else{console.error("No camera found");let s=Qu(this.scene);this.setCurrentCamera(s)}}St._current=this,Ii(this);let n=this.mainCameraComponent;if(n&&n.applyClearFlagsIfIsActiveCamera(),!this.isManagedExternally&&this.composer&&this.mainCamera){let r=new AE(this.scene,this.mainCamera);this.renderer.setSize(this.domWidth,this.domHeight),this.composer.addPass(r),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)),kE&&Qo(this.scene,!0)}render(e,t){for(this._stats?.begin(),St._current=this,this.time.update(),Ii(this),mh(),fh(this);this._cameraStack.length>0&&(!this.mainCameraComponent||this.mainCameraComponent.destroyed);){this._cameraStack.splice(this._cameraStack.length-1,1);let i=this._cameraStack[this._cameraStack.length-1];this.setCurrentCamera(i)}if(this.pre_update_callbacks)for(let i in this.pre_update_callbacks)this.pre_update_callbacks[i]();for(let i=0;i<this.scripts_earlyUpdate.length;i++){let n=this.scripts_earlyUpdate[i];!n.activeAndEnabled||n.earlyUpdate!==void 0&&(St._current=this,n.earlyUpdate())}this.executeCoroutines(0);for(let i=0;i<this.scripts_update.length;i++){let n=this.scripts_update[i];!n.activeAndEnabled||n.update!==void 0&&(St._current=this,n.update())}this.executeCoroutines(1);for(let i=0;i<this.scripts_lateUpdate.length;i++){let n=this.scripts_lateUpdate[i];!n.activeAndEnabled||n.lateUpdate!==void 0&&(St._current=this,n.lateUpdate())}this.mainLight=null,this.executeCoroutines(2);try{let n=this.time.deltaTime/2;for(let r=0;r<2;r++)this.physics.step(n),this.executeCoroutines(10)}catch(i){console.error(i)}this.physics.postStep();for(let i=0;i<this.scripts_onBeforeRender.length;i++){let n=this.scripts_onBeforeRender[i];!n.activeAndEnabled||n.onBeforeRender!==void 0&&(St._current=this,n.onBeforeRender(t))}if(this.executeCoroutines(3),this._sizeChanged&&this.updateSize(),this.pre_render_callbacks)for(let i in this.pre_render_callbacks)this.pre_render_callbacks[i]();this._isRendering=!0,this.renderRequiredTextures(),this.isManagedExternally||(this.composer?this.composer.render():this.mainCamera&&this.renderer.render(this.scene,this.mainCamera)),this._isRendering=!1;for(let i=0;i<this.scripts_onAfterRender.length;i++){let n=this.scripts_onAfterRender[i];!n.activeAndEnabled||n.onAfterRender!==void 0&&(St._current=this,n.onAfterRender())}if(this.executeCoroutines(4),this.post_render_callbacks)for(let i in this.post_render_callbacks)this.post_render_callbacks[i]();this.connection.sendBufferedMessagesNow(),this._stats?.end()}renderRequiredTextures(){if(!this.mainCamera||!this._requireDepthTexture&&!this._requireColorTexture)return;if(!this._renderTarget){if(this._renderTarget=new De.WebGLRenderTarget(this.domWidth,this.domHeight),this._requireDepthTexture){let i=new SE(this.domWidth,this.domHeight);this._renderTarget.depthTexture=i}this._requireColorTexture&&(this._renderTarget.texture=new De.Texture,this._renderTarget.texture.generateMipmaps=!1,this._renderTarget.texture.minFilter=De.NearestFilter,this._renderTarget.texture.magFilter=De.NearestFilter,this._renderTarget.texture.format=De.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 i=this.coroutines[e];for(let n=0;n<i.length;n++){let r=i[n];if(!r.comp||r.comp.destroyed||!r.main||r.comp.enabled===!1){i.splice(n,1),--n;continue}let s=r.chained;if(s&&s.length>0){let h=s[s.length-1].next();if(h.done&&s.pop(),t(h)&&(r.chained||(r.chained=[]),r.chained.push(h.value)),!h.done)continue}let c=r.main.next();if(c.done===!0){i.splice(n,1),--n;continue}let d=c.value;if(t(d)){if(d.next().done)continue;r.chained||(r.chained=[]),r.chained.push(d)}}}function t(i){return!!(i&&i.next&&i.return)}}},Z=St;z(Z,"_current");var Pr="ar",ME="quit-ar",pl=class{get ARContainer(){return this.arContainer}constructor(){this.closeARCallback=this.onRequestedEndAR.bind(this)}arContainer=null;closeARCallback;currentSession=null;registeredCloseEventElements=[];_createdAROnlyElements=[];_reparentedObjects=[];requestEndAR(){this.onRequestedEndAR()}onBegin(e,t,i){this.currentSession=i,this.arContainer=t,e.domElement.querySelectorAll(`.${Pr}`).forEach(o=>{!o||o!==this.arContainer&&(this._reparentedObjects.push({el:o,previousParent:o.parentElement}),this.arContainer?.appendChild(o))});let r=t.getElementsByClassName(ME);if(!r||r.length<=0)console.warn("Missing quit AR elements"),this.createFallbackCloseARButton(this.arContainer);else for(let o=0;o<r.length;o++){let s=r[o];!s||(s.addEventListener("click",this.closeARCallback),this.registeredCloseEventElements.push(s))}}onEnd(e){for(let t of this._createdAROnlyElements)t.remove&&t.remove();for(let t of this._reparentedObjects){let i=t.el;t.previousParent?.appendChild(i)}this._reparentedObjects.length=0}findOrCreateARContainer(e){if(e.classList.contains(Pr))return e;if(e.children){for(let i of e.children)if(!(!i||!i.classList)&&i.classList.contains(Pr))return i}let t=document.createElement("div");return t.classList.add(Pr),e.appendChild(t)}onRequestedEndAR(){if(!!this.currentSession){this.currentSession.end(),this.currentSession=null;for(let e of this.registeredCloseEventElements)e.removeEventListener("click",this.closeARCallback);this.registeredCloseEventElements.length=0}}createFallbackCloseARButton(e){var t=document.createElementNS("http://www.w3.org/2000/svg","svg");t.setAttribute("width","38px"),t.setAttribute("height","38px"),t.style.position="absolute",t.style.right="20px",t.style.top="40px",t.style.zIndex="9999",t.style.pointerEvents="auto",t.addEventListener("click",this.closeARCallback),e.appendChild(t),this._createdAROnlyElements.push(t);var i=document.createElementNS("http://www.w3.org/2000/svg","path");i.setAttribute("d","M 12,12 L 28,28 M 28,12 12,28"),i.setAttribute("stroke","#eee"),i.setAttribute("stroke-width","2px"),t.appendChild(i),this._createdAROnlyElements.push(i)}};var LE=N("debugloadingbar");function Ud(l){return l.index/l.count+l.progress.loaded/l.progress.total/l.count}var fl=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 i=this.container.children[t];if(i.classList.contains("loading")){if(!this._allowCustomLoadingElement){this.container.removeChild(i);continue}this._loadingElement=this.createLoadingElement();return}}this._loadingElement=this.createLoadingElement()}this._progress=0,this.loadingProgress=0,this._loadingElement.style.display="",this.container.appendChild(this._loadingElement),this.smoothProgressLoop(),this.setMessage(e??"")}onLoadingUpdate(e,t){this._loadingElement?.parentElement||this.onLoadingBegin(t);let i=0;typeof e=="number"?i=e:("index"in e&&(i=Ud(e)),!t&&"name"in e&&this.setMessage(e.name)),this.loadingProgress=i,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;LE&&(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=Q.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");let t=this._loadingElementOptions?.className??"loading";if(this._loadingElement.classList.add(t),this._loadingElementOptions?.additionalClasses)for(let s of this._loadingElementOptions.additionalClasses)this._loadingElement.classList.add(s);e||(this._loadingElement.style.color="white",this._loadingElement.style.display="flex");let i=document.createElement("div"),n=20;i.style.display="flex",i.style.width=n+"%",i.style.height="2px",i.style.background="rgba(255,255,255,.1)",this._loadingElement.appendChild(i),this._loadingBar=document.createElement("div"),i.appendChild(this._loadingBar);let r=function(s){return Q.lerp(n*.5,100-n*.5,s)+"%"};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 o=document.createElement("div");return this._messageContainer=o,o.style.display="flex",o.style.fontSize=".8em",o.style.paddingTop=".5em",o.style.color="rgba(255,255,255,.5)",this._loadingElement.appendChild(o),this._loadingElement}};var Or=N("debugwebcomponent"),qd=class{id;context;previouslyAdded;previousSource;networkEvent;constructor(e,t){this.id=e,this.context=t,this.networkEvent="needle-engine-source-changed",this.id&&(this.networkEvent+="-"+this.id),this.context.connection.beginListen(this.networkEvent,i=>{this.onSourceChanged(i,!0)})}async onSourceChanged(e,t=!1,i=!1){this.previouslyAdded&&(t&&e===this.previousSource||S.destroySynced(this.previouslyAdded)),this.previouslyAdded=null,t||this.context.connection.send(this.networkEvent,e),this.previousSource=e,Z.Current=this.context;let n=await ur(this.context,e,this.getHashFromString(e));i||Ii(this.context);let r=n?.scene;r&&(this.previouslyAdded=r,this.context.scene.add(r))}getHashFromString(e){let t=0;for(let i=0;i<e.length;i++)t=e.charCodeAt(i)+((t<<5)-t);return t}},DE="needle-engine",HE="vr",jE="desktop",BE=[Pr,HE,jE],Xd=class extends HTMLElement{get loadingProgress01(){return this._loadingProgress01}get loadingFinished(){return this.loadingProgress01>.999}getContext(){return new Promise((e,t)=>{if(this._context&&this.loadingFinished)e(this._context);else{let i=()=>{this.removeEventListener("loadfinished",i),this._context&&this.loadingFinished&&e(this._context)};this.addEventListener("loadfinished",i)}})}get Context(){return this._context}gameObject=S;GameObject=S;_context=null;_overlay_ar;_loadingProgress01=0;_watcher;_loadingView;constructor(){super(),this._overlay_ar=new pl}async connectedCallback(){this.onSetupDesktop();var e=new MutationObserver(this.onElementsChanged.bind(this));e.observe(this,{childList:!0});let t=()=>{let o=this.getAttribute("src");return o?.endsWith(".glb")||o?.endsWith(".gltf")?o:null},i="loadScene",n=t();n&&(i=n);let r=this.getAttribute("alias");if(this._context=new Z({name:i,domElement:this,alias:r}),this._watcher=new qd(this.getAttribute("id")??r??"",this._context),i&&i.length>0){if(!n)for(;Object.keys(ul).length<=0;){if(!this.isConnected)return;await hh(10)}let o=ul[i]??window[i],s=null;if((!o||n)&&(n&&(i=n),o=async c=>{let d=t();d&&this._watcher&&(s=d,await this._watcher.onSourceChanged(d,!0,!0))}),o){this.classList.add("loading"),console.log("Needle Engine: Begin loading",r??"");let c=this.dispatchEvent(new CustomEvent("loadstart",{detail:{context:this._context,alias:r},cancelable:!0}));!this._loadingView&&c&&(this._loadingView=new fl(this)),c&&this._loadingView?.onLoadingBegin("begin load");let d=(h,u)=>{this._loadingProgress01=Ud(h),c&&this._loadingView?.onLoadingUpdate(h,u),this.dispatchEvent(new CustomEvent("progress",{detail:{context:this._context,name:h.name,progress:h.progress,index:h.index,count:h.count,totalProgress01:this._loadingProgress01}}))};this.onBeforeBeginLoading(),await this._context.onCreate(o,{progress:d});let a=t();a&&a!==s&&await this._watcher.onSourceChanged(a,!0,!0),this._loadingProgress01=1,c&&this._loadingView?.onLoadingFinished("create scene"),this.classList.remove("loading"),this.classList.add("loading-finished"),console.log("Needle Engine: finished loading",r??""),this.dispatchEvent(new CustomEvent("loadfinished",{detail:{context:this._context,src:r??i}})),this.onSetupDesktop()}else console.error('Could not find scene function named "'+i+'", it must be either in global scope or added to build_scene_functions',ul)}else console.error("Missing src attribute - please provide a function name",this)}disconnectedCallback(){this._context&&this._context.onDestroy()}static get observedAttributes(){return["src","loadstart","progress","loadfinished","dracoDecoderPath","dracoDecoderType","ktx2DecoderPath"]}attributeChangedCallback(e,t,i){switch(e){case"src":this._watcher?.onSourceChanged(i);break;case"loadstart":case"progress":case"loadfinished":typeof i=="string"&&i.length>0&&(Or&&console.log(e+" attribute changed",i),this.registerEventFromAttribute(e,i));break;case"dracoDecoderPath":Or&&console.log("dracoDecoderPath",i),ac(i);break;case"dracoDecoderType":i==="wasm"||i==="js"?(Or&&console.log("dracoDecoderType",i),lc(i)):console.error("Invalid dracoDecoderType",i,"expected js or wasm");break;case"ktx2DecoderPath":Or&&console.log("ktx2DecoderPath",i),cc(i);break}}registerEventFromAttribute(e,t){if(typeof t=="string"&&t.length>0){let i=(0,eval)(t);typeof i=="function"&&this.addEventListener(e,n=>i?.call(globalThis,this._context,n))}}getAROverlayContainer(){return this._overlay_ar.findOrCreateARContainer(this)}getVROverlayContainer(){for(let e=0;e<this.children.length;e++){let t=this.children[e];if(t.classList.contains("vr"))return t}return null}onEnterAR(e,t){this.onSetupAR(),this._overlay_ar.onBegin(this._context,t,e),this.dispatchEvent(new CustomEvent("enter-ar",{detail:{session:e,context:this._context,htmlContainer:this._overlay_ar?.ARContainer}}))}onExitAR(e){this._overlay_ar.onEnd(this._context),this.onSetupDesktop(),this.dispatchEvent(new CustomEvent("exit-ar",{detail:{session:e,context:this._context,htmlContainer:this._overlay_ar?.ARContainer}}))}onEnterVR(e){this.onSetupVR(),this.dispatchEvent(new CustomEvent("enter-vr",{detail:{session:e,context:this._context}}))}onExitVR(e){this.onSetupDesktop(),this.dispatchEvent(new CustomEvent("exit-vr",{detail:{session:e,context:this._context}}))}onElementsChanged(){}onSetupAR(){this.classList.add("ar-session-active"),this.classList.remove("desktop-session-active"),this.foreachHtmlElement(e=>this.setupElementsForMode(e,Pr))}onSetupVR(){this.classList.remove("ar-session-active"),this.classList.remove("desktop-session-active"),this.foreachHtmlElement(e=>this.setupElementsForMode(e,"vr"))}onSetupDesktop(){this.classList.remove("ar-session-active"),this.classList.add("desktop-session-active"),this.foreachHtmlElement(e=>this.setupElementsForMode(e,"desktop"))}setupElementsForMode(e,t,i=null){if(e===this._context?.renderer.domElement||e.id==="VRButton"||e.id==="ARButton")return;if(e.style.position="absolute",e.classList.contains(t))e.style.visibility="visible",e.style.display==="none"&&(e.style.display="block");else for(let r of BE)e.classList.contains(r)&&(e.style.visibility="hidden",e.style.display="none")}foreachHtmlElement(e){for(let t=0;t<this.children.length;t++){let i=this.children[t];i.style&&e(i)}}onBeforeBeginLoading(){let e=this.getAttribute("dracoDecoderPath");e&&(Or&&console.log("using custom draco decoder path",e),ac(e));let t=this.getAttribute("dracoDecoderType");t&&(Or&&console.log("using custom draco decoder type",t),lc(t));let i=this.getAttribute("ktx2DecoderPath");i&&(Or&&console.log("using custom ktx2 decoder path",i),cc(i))}};window.customElements.define(DE,Xd);var Qd={};rh(Qd,{AlignmentConstraint:()=>_n,Animation:()=>Jt,AnimationCurve:()=>sr,AnimationTrackHandler:()=>Nn,Animator:()=>bt,AnimatorController:()=>Zt,AttachedObject:()=>dt,AudioListener:()=>$t,AudioSource:()=>ue,AudioTrackHandler:()=>zn,AvatarBlink_Simple:()=>Ti,AvatarEyeLook_Rotation:()=>Ri,AvatarLoader:()=>xn,AvatarMarker:()=>pe,AvatarModel:()=>ar,Avatar_Brain_LookAt:()=>Ui,Avatar_MouthShapes:()=>Fn,Avatar_MustacheShake:()=>Po,Avatar_POI:()=>_e,AxesHelper:()=>zi,BaseUIComponent:()=>Ue,BasicIKConstraint:()=>Yr,BoxCollider:()=>Rn,BoxGizmo:()=>Xi,BoxHelperComponent:()=>lt,Button:()=>Ft,CallInfo:()=>yi,Camera:()=>ne,Canvas:()=>Je,CanvasGroup:()=>sn,Collider:()=>fi,ColorAdjustments:()=>Bn,ControlTrackHandler:()=>Ki,Deletable:()=>eo,DeleteBox:()=>lr,DeviceFlag:()=>cr,DragControls:()=>Et,DropListener:()=>An,Duplicatable:()=>vi,EmissionModule:()=>bo,EventList:()=>Oe,EventListEvent:()=>pr,EventSystem:()=>Ze,EventTrigger:()=>lo,FieldWithDefault:()=>Fr,FlyControls:()=>co,GltfExport:()=>jt,GltfExportBox:()=>uo,Graphic:()=>Rt,GraphicRaycaster:()=>Fo,GridHelper:()=>Qi,GridLayoutGroup:()=>Bo,GroundProjectedEnv:()=>Yi,HorizontalLayoutGroup:()=>jo,Image:()=>on,InputField:()=>Ct,InstancingUtil:()=>he,InstantiateOptions:()=>ye,Interactable:()=>kt,Keyboard:()=>Do,LODGroup:()=>In,LODModel:()=>Ei,LayoutGroup:()=>an,Light:()=>Ye,LogStats:()=>Oo,LookAtConstraint:()=>Fi,MainModule:()=>go,MaskableGraphic:()=>rn,MeshRenderer:()=>rr,NavMesh:()=>fo,NavMeshAgent:()=>mo,NestedGltf:()=>fr,Networking:()=>pt,ObjectRaycaster:()=>Si,OffsetConstraint:()=>wi,OrbitControls:()=>gt,ParticleSystem:()=>yo,ParticleSystemRenderer:()=>gr,PlayableDirector:()=>tn,PlayerColor:()=>ht,PointerEventData:()=>ii,RGBAColor:()=>we,RawImage:()=>Tr,Raycaster:()=>Cr,Rect:()=>xr,RectTransform:()=>ut,RemoteSkybox:()=>Ln,Renderer:()=>Te,RendererLightmap:()=>ji,Rigidbody:()=>ce,ScreenCapture:()=>Eo,ShadowCatcher:()=>Mn,ShapeModule:()=>vo,SignalAsset:()=>wr,SignalReceiver:()=>$i,SignalReceiverEvent:()=>_r,SignalTrackHandler:()=>en,Size:()=>Mo,SkinnedMeshRenderer:()=>Nr,SmoothFollow:()=>_i,SpatialHtml:()=>No,SpatialTrigger:()=>Zi,SpatialTriggerReceiver:()=>wt,SpectatorCamera:()=>_o,SphereCollider:()=>Tn,SpringJoint:()=>xo,Sprite:()=>br,SpriteRenderer:()=>Ji,SyncedCamera:()=>Dn,SyncedRoom:()=>ti,SyncedTransform:()=>Qe,TeleportTarget:()=>dr,TestRunner:()=>To,TestSimulateUserData:()=>Ro,Text:()=>Le,ToneMapping:()=>jn,TransformGizmo:()=>vr,UIRootComponent:()=>nn,UnityObject:()=>Kr,UsageMarker:()=>It,VRUserState:()=>Ht,VerticalLayoutGroup:()=>Ho,VideoPlayer:()=>nt,Voip:()=>Ke,Volume:()=>yr,VolumeComponent:()=>xi,VolumeParameter:()=>Co,VolumeProfile:()=>Hn,WebAR:()=>On,WebARSessionRoot:()=>Dt,WebXR:()=>$,WebXRAvatar:()=>Lt,WebXRController:()=>ae,WebXRSync:()=>qi,XRFlag:()=>Se,XRGrabModel:()=>Er,XRGrabRendering:()=>So,XRRig:()=>Pn,XRState:()=>vt});import*as FE from"three";var Yd={Context:Z};globalThis.Needle=Yd;function Rf(l){for(let e in l)Yd[e]=l[e]}Rf(jl);Rf(Qd);for(let l of Object.getOwnPropertyNames(S))switch(l){case"prototype":case"constructor":case"length":case"name":continue;default:Yd[l]=S[l];break}globalThis.THREE?console.warn("Threejs is already imported"):globalThis.THREE=FE;export{_n as AlignmentConstraint,Jt as Animation,sr as AnimationCurve,Nn as AnimationTrackHandler,bt as Animator,Zt as AnimatorController,dt as AttachedObject,$t as AudioListener,ue as AudioSource,zn as AudioTrackHandler,Ti as AvatarBlink_Simple,Ri as AvatarEyeLook_Rotation,xn as AvatarLoader,pe as AvatarMarker,ar as AvatarModel,Ui as Avatar_Brain_LookAt,Fn as Avatar_MouthShapes,Po as Avatar_MustacheShake,_e as Avatar_POI,zi as AxesHelper,Ue as BaseUIComponent,Yr as BasicIKConstraint,M as Behaviour,Rn as BoxCollider,Xi as BoxGizmo,lt as BoxHelperComponent,Ft as Button,yi as CallInfo,ne as Camera,Je as Canvas,sn as CanvasGroup,fi as Collider,Bn as ColorAdjustments,Ki as ControlTrackHandler,eo as Deletable,lr as DeleteBox,cr as DeviceFlag,Et as DragControls,An as DropListener,vi as Duplicatable,bo as EmissionModule,Oe as EventList,pr as EventListEvent,Ze as EventSystem,lo as EventTrigger,Fr as FieldWithDefault,co as FlyControls,S as GameObject,jt as GltfExport,uo as GltfExportBox,Rt as Graphic,Fo as GraphicRaycaster,Qi as GridHelper,Bo as GridLayoutGroup,Yi as GroundProjectedEnv,jo as HorizontalLayoutGroup,on as Image,Ct as InputField,he as InstancingUtil,ye as InstantiateOptions,kt as Interactable,Do as Keyboard,In as LODGroup,Ei as LODModel,an as LayoutGroup,Ye as Light,Oo as LogStats,Fi as LookAtConstraint,go as MainModule,rn as MaskableGraphic,rr as MeshRenderer,fo as NavMesh,mo as NavMeshAgent,fr as NestedGltf,pt as Networking,Si as ObjectRaycaster,wi as OffsetConstraint,gt as OrbitControls,yo as ParticleSystem,gr as ParticleSystemRenderer,tn as PlayableDirector,ht as PlayerColor,ii as PointerEventData,we as RGBAColor,Tr as RawImage,Cr as Raycaster,xr as Rect,ut as RectTransform,Ln as RemoteSkybox,Te as Renderer,ji as RendererLightmap,ce as Rigidbody,Eo as ScreenCapture,Mn as ShadowCatcher,vo as ShapeModule,wr as SignalAsset,$i as SignalReceiver,_r as SignalReceiverEvent,en as SignalTrackHandler,Mo as Size,Nr as SkinnedMeshRenderer,_i as SmoothFollow,No as SpatialHtml,Zi as SpatialTrigger,wt as SpatialTriggerReceiver,_o as SpectatorCamera,Tn as SphereCollider,xo as SpringJoint,br as Sprite,Ji as SpriteRenderer,Dn as SyncedCamera,ti as SyncedRoom,Qe as SyncedTransform,dr as TeleportTarget,To as TestRunner,Ro as TestSimulateUserData,Le as Text,jn as ToneMapping,vr as TransformGizmo,nn as UIRootComponent,Kr as UnityObject,It as UsageMarker,Ht as VRUserState,Ho as VerticalLayoutGroup,nt as VideoPlayer,Ke as Voip,yr as Volume,xi as VolumeComponent,Co as VolumeParameter,Hn as VolumeProfile,On as WebAR,Dt as WebARSessionRoot,$ as WebXR,Lt as WebXRAvatar,ae as WebXRController,qi as WebXRSync,Se as XRFlag,Er as XRGrabModel,So as XRGrabRendering,Pn as XRRig,vt as XRState,A as serializeable};
160
+ #endif`);Oi.UniformsLib.lightmap.lightmapScaleOffset={value:new Oi.Vector4(1,1,0,0)};var kE=N("debugSetup"),IE=N("stats"),ul={};var St=class{static get Current(){return this._current}static set Current(e){this._current=e}name;alias;isManagedExternally=!1;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}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;_sizeChanged=!1;_isCreated=!1;_stats=IE?Tf.default():null;constructor(e){if(this.name=e?.name||"",this.alias=e?.alias,this.domElement=e?.domElement||document.body,e?.renderer)this.renderer=e.renderer,this.isManagedExternally=!0;else{let i=N("postfx");this.renderer=new PE({antialias:!0}),this.renderer.toneMappingExposure=1,this.renderer.toneMapping=De.NoToneMapping,this.renderer.setClearColor(new De.Color("lightgrey"),0),this.renderer.antialias=!0,this.renderer.alpha=!1,this.renderer.shadowMap.enabled=!0,this.renderer.shadowMap.type=De.PCFSoftShadowMap,this.renderer.setSize(this.domWidth,this.domHeight),this.renderer.outputEncoding=De.sRGBEncoding,this.renderer.physicallyCorrectLights=!0,this.composer=i?new OE(this.renderer):null}this.scene=new De.Scene,this.application=new _a(this),this.time=new la,this.input=new Ws(this),this.physics=new aa(this),this.connection=new fa(this),this.assets=new dl,this.rendererData=new al(this),this.addressables=new Ha(this),this.lightmaps=new hl(this),window.addEventListener("resize",this.updateSize.bind(this)),new ResizeObserver(i=>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,i=this.domHeight*e,n=this.mainCamera;this.updateAspect(n),this.renderer.setSize(t,i),this.renderer.setPixelRatio(window.devicePixelRatio),this.renderer.domElement.style.width=this.domWidth+"px",this.renderer.domElement.style.height=this.domHeight+"px",this.composer&&(this.composer.setSize(t,i),this.composer.setPixelRatio(window.devicePixelRatio))}}updateAspect(e){if(!e)return;let t=this.domWidth,i=this.domHeight,n=e.aspect;e.aspect=t/i,n!==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,S.destroy(this.scene,!0),this.renderer?.setAnimationLoop(null),this.isManagedExternally||this.renderer?.dispose())}registerCoroutineUpdate(e,t,i){return this.coroutines[i]||(this.coroutines[i]=[]),this.coroutines[i].push({comp:e,main:t}),t}unregisterCoroutineUpdate(e,t){if(!this.coroutines[t])return;let i=this.coroutines[t].findIndex(n=>n.main===e);i>=0&&this.coroutines[t].splice(i,1)}stopAllCoroutinesFrom(e){for(let t in this.coroutines){let i=this.coroutines[t];for(let n=i.length-1;n>=0;n--)i[n].comp===e&&i.splice(n,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 i=e.cam;i.isPerspectiveCamera&&this.updateAspect(i),this.mainCameraComponent?.applyClearFlagsIfIsActiveCamera()}_onBeforeRenderListeners={};addBeforeRenderListener(e,t){if(!this._onBeforeRenderListeners[e.uuid]){this._onBeforeRenderListeners[e.uuid]=[];let i=(n,r,o,s,c,d)=>{let a=this._onBeforeRenderListeners[e.uuid];if(!!a)for(let h=0;h<a.length;h++){let u=a[h];u(n,r,o,s,c,d)}};e.onBeforeRender=i}this._onBeforeRenderListeners[e.uuid].push(t)}removeBeforeRenderListener(e,t){if(this._onBeforeRenderListeners[e.uuid]){let i=this._onBeforeRenderListeners[e.uuid],n=i.indexOf(t);n>=0&&i.splice(n,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){let i=!0;try{St.Current=this,e&&await e(this,t)}catch(r){console.error(r),i=!1}if(!i)return;this.isManagedExternally||this.domElement.prepend(this.renderer.domElement),Dh(this),Lh(this),wf(this),St._current=this;for(let r=0;r<this.new_scripts.length;r++){let o=this.new_scripts[r];if(o.gameObject!==void 0&&o.gameObject!==null){o.gameObject.userData===void 0&&(o.gameObject.userData={}),o.gameObject.userData.components===void 0&&(o.gameObject.userData.components=[]);let s=o.gameObject.userData.components;s.includes(o)||s.push(o)}}if(this.post_setup_callbacks)for(let r=0;r<this.post_setup_callbacks.length;r++)St._current=this,await this.post_setup_callbacks[r](this);if(!this.mainCamera){St._current=this;let r=S.findObjectsOfType(ne,this),o=r.find(s=>s.tag=="MainCamera")??r.find(s=>!0);if(o)o.tag!=="MainCamera"&&console.warn('No mainCamera configured. Some components rely on a mainCamera object being present. When exporting your scene, make sure to set the mainCamera tag on your camera. Using "'+o.name+'" as mainCamera now.'),this.setCurrentCamera(o);else{console.error("No camera found");let s=Qu(this.scene);this.setCurrentCamera(s)}}St._current=this,Ii(this);let n=this.mainCameraComponent;if(n&&n.applyClearFlagsIfIsActiveCamera(),!this.isManagedExternally&&this.composer&&this.mainCamera){let r=new AE(this.scene,this.mainCamera);this.renderer.setSize(this.domWidth,this.domHeight),this.composer.addPass(r),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)),kE&&Qo(this.scene,!0)}render(e,t){for(this._stats?.begin(),St._current=this,this.time.update(),Ii(this),mh(),fh(this);this._cameraStack.length>0&&(!this.mainCameraComponent||this.mainCameraComponent.destroyed);){this._cameraStack.splice(this._cameraStack.length-1,1);let i=this._cameraStack[this._cameraStack.length-1];this.setCurrentCamera(i)}if(this.pre_update_callbacks)for(let i in this.pre_update_callbacks)this.pre_update_callbacks[i]();for(let i=0;i<this.scripts_earlyUpdate.length;i++){let n=this.scripts_earlyUpdate[i];!n.activeAndEnabled||n.earlyUpdate!==void 0&&(St._current=this,n.earlyUpdate())}this.executeCoroutines(0);for(let i=0;i<this.scripts_update.length;i++){let n=this.scripts_update[i];!n.activeAndEnabled||n.update!==void 0&&(St._current=this,n.update())}this.executeCoroutines(1);for(let i=0;i<this.scripts_lateUpdate.length;i++){let n=this.scripts_lateUpdate[i];!n.activeAndEnabled||n.lateUpdate!==void 0&&(St._current=this,n.lateUpdate())}this.mainLight=null,this.executeCoroutines(2);try{let n=this.time.deltaTime/2;for(let r=0;r<2;r++)this.physics.step(n),this.executeCoroutines(10)}catch(i){console.error(i)}this.physics.postStep();for(let i=0;i<this.scripts_onBeforeRender.length;i++){let n=this.scripts_onBeforeRender[i];!n.activeAndEnabled||n.onBeforeRender!==void 0&&(St._current=this,n.onBeforeRender(t))}if(this.executeCoroutines(3),this._sizeChanged&&this.updateSize(),this.pre_render_callbacks)for(let i in this.pre_render_callbacks)this.pre_render_callbacks[i]();this._isRendering=!0,this.renderRequiredTextures(),this.isManagedExternally||(this.composer?this.composer.render():this.mainCamera&&this.renderer.render(this.scene,this.mainCamera)),this._isRendering=!1;for(let i=0;i<this.scripts_onAfterRender.length;i++){let n=this.scripts_onAfterRender[i];!n.activeAndEnabled||n.onAfterRender!==void 0&&(St._current=this,n.onAfterRender())}if(this.executeCoroutines(4),this.post_render_callbacks)for(let i in this.post_render_callbacks)this.post_render_callbacks[i]();this.connection.sendBufferedMessagesNow(),this._stats?.end()}renderRequiredTextures(){if(!this.mainCamera||!this._requireDepthTexture&&!this._requireColorTexture)return;if(!this._renderTarget){if(this._renderTarget=new De.WebGLRenderTarget(this.domWidth,this.domHeight),this._requireDepthTexture){let i=new SE(this.domWidth,this.domHeight);this._renderTarget.depthTexture=i}this._requireColorTexture&&(this._renderTarget.texture=new De.Texture,this._renderTarget.texture.generateMipmaps=!1,this._renderTarget.texture.minFilter=De.NearestFilter,this._renderTarget.texture.magFilter=De.NearestFilter,this._renderTarget.texture.format=De.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 i=this.coroutines[e];for(let n=0;n<i.length;n++){let r=i[n];if(!r.comp||r.comp.destroyed||!r.main||r.comp.enabled===!1){i.splice(n,1),--n;continue}let s=r.chained;if(s&&s.length>0){let h=s[s.length-1].next();if(h.done&&s.pop(),t(h)&&(r.chained||(r.chained=[]),r.chained.push(h.value)),!h.done)continue}let c=r.main.next();if(c.done===!0){i.splice(n,1),--n;continue}let d=c.value;if(t(d)){if(d.next().done)continue;r.chained||(r.chained=[]),r.chained.push(d)}}}function t(i){return!!(i&&i.next&&i.return)}}},Z=St;z(Z,"_current");var Pr="ar",ME="quit-ar",pl=class{get ARContainer(){return this.arContainer}constructor(){this.closeARCallback=this.onRequestedEndAR.bind(this)}arContainer=null;closeARCallback;currentSession=null;registeredCloseEventElements=[];_createdAROnlyElements=[];_reparentedObjects=[];requestEndAR(){this.onRequestedEndAR()}onBegin(e,t,i){this.currentSession=i,this.arContainer=t,e.domElement.querySelectorAll(`.${Pr}`).forEach(o=>{!o||o!==this.arContainer&&(this._reparentedObjects.push({el:o,previousParent:o.parentElement}),this.arContainer?.appendChild(o))});let r=t.getElementsByClassName(ME);if(!r||r.length<=0)console.warn("Missing quit AR elements"),this.createFallbackCloseARButton(this.arContainer);else for(let o=0;o<r.length;o++){let s=r[o];!s||(s.addEventListener("click",this.closeARCallback),this.registeredCloseEventElements.push(s))}}onEnd(e){for(let t of this._createdAROnlyElements)t.remove&&t.remove();for(let t of this._reparentedObjects){let i=t.el;t.previousParent?.appendChild(i)}this._reparentedObjects.length=0}findOrCreateARContainer(e){if(e.classList.contains(Pr))return e;if(e.children){for(let i of e.children)if(!(!i||!i.classList)&&i.classList.contains(Pr))return i}let t=document.createElement("div");return t.classList.add(Pr),e.appendChild(t)}onRequestedEndAR(){if(!!this.currentSession){this.currentSession.end(),this.currentSession=null;for(let e of this.registeredCloseEventElements)e.removeEventListener("click",this.closeARCallback);this.registeredCloseEventElements.length=0}}createFallbackCloseARButton(e){var t=document.createElementNS("http://www.w3.org/2000/svg","svg");t.setAttribute("width","38px"),t.setAttribute("height","38px"),t.style.position="absolute",t.style.right="20px",t.style.top="40px",t.style.zIndex="9999",t.style.pointerEvents="auto",t.addEventListener("click",this.closeARCallback),e.appendChild(t),this._createdAROnlyElements.push(t);var i=document.createElementNS("http://www.w3.org/2000/svg","path");i.setAttribute("d","M 12,12 L 28,28 M 28,12 12,28"),i.setAttribute("stroke","#eee"),i.setAttribute("stroke-width","2px"),t.appendChild(i),this._createdAROnlyElements.push(i)}};var LE=N("debugloadingbar");function Ud(l){return l.index/l.count+l.progress.loaded/l.progress.total/l.count}var fl=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 i=this.container.children[t];if(i.classList.contains("loading")){if(!this._allowCustomLoadingElement){this.container.removeChild(i);continue}this._loadingElement=this.createLoadingElement();return}}this._loadingElement=this.createLoadingElement()}this._progress=0,this.loadingProgress=0,this._loadingElement.style.display="",this.container.appendChild(this._loadingElement),this.smoothProgressLoop(),this.setMessage(e??"")}onLoadingUpdate(e,t){this._loadingElement?.parentElement||this.onLoadingBegin(t);let i=0;typeof e=="number"?i=e:("index"in e&&(i=Ud(e)),!t&&"name"in e&&this.setMessage(e.name)),this.loadingProgress=i,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;LE&&(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=Q.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");let t=this._loadingElementOptions?.className??"loading";if(this._loadingElement.classList.add(t),this._loadingElementOptions?.additionalClasses)for(let s of this._loadingElementOptions.additionalClasses)this._loadingElement.classList.add(s);e||(this._loadingElement.style.color="white",this._loadingElement.style.display="flex");let i=document.createElement("div"),n=20;i.style.display="flex",i.style.width=n+"%",i.style.height="2px",i.style.background="rgba(255,255,255,.1)",this._loadingElement.appendChild(i),this._loadingBar=document.createElement("div"),i.appendChild(this._loadingBar);let r=function(s){return Q.lerp(n*.5,100-n*.5,s)+"%"};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 o=document.createElement("div");return this._messageContainer=o,o.style.display="flex",o.style.fontSize=".8em",o.style.paddingTop=".5em",o.style.color="rgba(255,255,255,.5)",this._loadingElement.appendChild(o),this._loadingElement}};var Or=N("debugwebcomponent"),qd=class{id;context;previouslyAdded;previousSource;networkEvent;constructor(e,t){this.id=e,this.context=t,this.networkEvent="needle-engine-source-changed",this.id&&(this.networkEvent+="-"+this.id),this.context.connection.beginListen(this.networkEvent,i=>{this.onSourceChanged(i,!0)})}async onSourceChanged(e,t=!1,i=!1){this.previouslyAdded&&(t&&e===this.previousSource||S.destroySynced(this.previouslyAdded)),this.previouslyAdded=null,t||this.context.connection.send(this.networkEvent,e),this.previousSource=e,Z.Current=this.context;let n=await ur(this.context,e,this.getHashFromString(e));i||Ii(this.context);let r=n?.scene;r&&(this.previouslyAdded=r,this.context.scene.add(r))}getHashFromString(e){let t=0;for(let i=0;i<e.length;i++)t=e.charCodeAt(i)+((t<<5)-t);return t}},DE="needle-engine",HE="vr",jE="desktop",BE=[Pr,HE,jE],Xd=class extends HTMLElement{get loadingProgress01(){return this._loadingProgress01}get loadingFinished(){return this.loadingProgress01>.999}getContext(){return new Promise((e,t)=>{if(this._context&&this.loadingFinished)e(this._context);else{let i=()=>{this.removeEventListener("loadfinished",i),this._context&&this.loadingFinished&&e(this._context)};this.addEventListener("loadfinished",i)}})}get Context(){return this._context}gameObject=S;GameObject=S;_context=null;_overlay_ar;_loadingProgress01=0;_watcher;_loadingView;constructor(){super(),this._overlay_ar=new pl}async connectedCallback(){this.onSetupDesktop();var e=new MutationObserver(this.onElementsChanged.bind(this));e.observe(this,{childList:!0});let t=()=>{let o=this.getAttribute("src");return o?.endsWith(".glb")||o?.endsWith(".gltf")?o:null},i="loadScene",n=t();n&&(i=n);let r=this.getAttribute("alias");if(this._context=new Z({name:i,domElement:this,alias:r}),this._watcher=new qd(this.getAttribute("id")??r??"",this._context),i&&i.length>0){if(!n)for(;Object.keys(ul).length<=0;){if(!this.isConnected)return;await hh(10)}let o=ul[i]??window[i],s=null;if((!o||n)&&(n&&(i=n),o=async c=>{let d=t();d&&this._watcher&&(s=d,await this._watcher.onSourceChanged(d,!0,!0))}),o){this.classList.add("loading"),console.log("Needle Engine: Begin loading",r??"");let c=this.dispatchEvent(new CustomEvent("loadstart",{detail:{context:this._context,alias:r},cancelable:!0}));!this._loadingView&&c&&(this._loadingView=new fl(this)),c&&this._loadingView?.onLoadingBegin("begin load");let d=(h,u)=>{this._loadingProgress01=Ud(h),c&&this._loadingView?.onLoadingUpdate(h,u),this.dispatchEvent(new CustomEvent("progress",{detail:{context:this._context,name:h.name,progress:h.progress,index:h.index,count:h.count,totalProgress01:this._loadingProgress01}}))};this.onBeforeBeginLoading(),await this._context.onCreate(o,{progress:d});let a=t();a&&a!==s&&await this._watcher.onSourceChanged(a,!0,!0),this._loadingProgress01=1,c&&this._loadingView?.onLoadingFinished("create scene"),this.classList.remove("loading"),this.classList.add("loading-finished"),console.log("Needle Engine: finished loading",r??""),this.dispatchEvent(new CustomEvent("loadfinished",{detail:{context:this._context,src:r??i}})),this.onSetupDesktop()}else console.error('Could not find scene function named "'+i+'", it must be either in global scope or added to build_scene_functions',ul)}else console.error("Missing src attribute - please provide a function name",this)}disconnectedCallback(){this._context&&this._context.onDestroy()}static get observedAttributes(){return["src","loadstart","progress","loadfinished","dracoDecoderPath","dracoDecoderType","ktx2DecoderPath"]}attributeChangedCallback(e,t,i){switch(e){case"src":this._watcher?.onSourceChanged(i);break;case"loadstart":case"progress":case"loadfinished":typeof i=="string"&&i.length>0&&(Or&&console.log(e+" attribute changed",i),this.registerEventFromAttribute(e,i));break;case"dracoDecoderPath":Or&&console.log("dracoDecoderPath",i),ac(i);break;case"dracoDecoderType":i==="wasm"||i==="js"?(Or&&console.log("dracoDecoderType",i),lc(i)):console.error("Invalid dracoDecoderType",i,"expected js or wasm");break;case"ktx2DecoderPath":Or&&console.log("ktx2DecoderPath",i),cc(i);break}}registerEventFromAttribute(e,t){if(typeof t=="string"&&t.length>0){let i=(0,eval)(t);typeof i=="function"&&this.addEventListener(e,n=>i?.call(globalThis,this._context,n))}}getAROverlayContainer(){return this._overlay_ar.findOrCreateARContainer(this)}getVROverlayContainer(){for(let e=0;e<this.children.length;e++){let t=this.children[e];if(t.classList.contains("vr"))return t}return null}onEnterAR(e,t){this.onSetupAR(),this._overlay_ar.onBegin(this._context,t,e),this.dispatchEvent(new CustomEvent("enter-ar",{detail:{session:e,context:this._context,htmlContainer:this._overlay_ar?.ARContainer}}))}onExitAR(e){this._overlay_ar.onEnd(this._context),this.onSetupDesktop(),this.dispatchEvent(new CustomEvent("exit-ar",{detail:{session:e,context:this._context,htmlContainer:this._overlay_ar?.ARContainer}}))}onEnterVR(e){this.onSetupVR(),this.dispatchEvent(new CustomEvent("enter-vr",{detail:{session:e,context:this._context}}))}onExitVR(e){this.onSetupDesktop(),this.dispatchEvent(new CustomEvent("exit-vr",{detail:{session:e,context:this._context}}))}onElementsChanged(){}onSetupAR(){this.classList.add("ar-session-active"),this.classList.remove("desktop-session-active"),this.foreachHtmlElement(e=>this.setupElementsForMode(e,Pr))}onSetupVR(){this.classList.remove("ar-session-active"),this.classList.remove("desktop-session-active"),this.foreachHtmlElement(e=>this.setupElementsForMode(e,"vr"))}onSetupDesktop(){this.classList.remove("ar-session-active"),this.classList.add("desktop-session-active"),this.foreachHtmlElement(e=>this.setupElementsForMode(e,"desktop"))}setupElementsForMode(e,t,i=null){if(e===this._context?.renderer.domElement||e.id==="VRButton"||e.id==="ARButton")return;if(e.style.position="absolute",e.classList.contains(t))e.style.visibility="visible",e.style.display==="none"&&(e.style.display="block");else for(let r of BE)e.classList.contains(r)&&(e.style.visibility="hidden",e.style.display="none")}foreachHtmlElement(e){for(let t=0;t<this.children.length;t++){let i=this.children[t];i.style&&e(i)}}onBeforeBeginLoading(){let e=this.getAttribute("dracoDecoderPath");e&&(Or&&console.log("using custom draco decoder path",e),ac(e));let t=this.getAttribute("dracoDecoderType");t&&(Or&&console.log("using custom draco decoder type",t),lc(t));let i=this.getAttribute("ktx2DecoderPath");i&&(Or&&console.log("using custom ktx2 decoder path",i),cc(i))}};window.customElements.define(DE,Xd);var Qd={};rh(Qd,{AlignmentConstraint:()=>_n,Animation:()=>Jt,AnimationCurve:()=>sr,AnimationTrackHandler:()=>Nn,Animator:()=>bt,AnimatorController:()=>Zt,AttachedObject:()=>dt,AudioListener:()=>$t,AudioSource:()=>ue,AudioTrackHandler:()=>zn,AvatarBlink_Simple:()=>Ti,AvatarEyeLook_Rotation:()=>Ri,AvatarLoader:()=>xn,AvatarMarker:()=>pe,AvatarModel:()=>ar,Avatar_Brain_LookAt:()=>Ui,Avatar_MouthShapes:()=>Fn,Avatar_MustacheShake:()=>Po,Avatar_POI:()=>_e,AxesHelper:()=>zi,BaseUIComponent:()=>Ue,BasicIKConstraint:()=>Yr,BoxCollider:()=>Rn,BoxGizmo:()=>Xi,BoxHelperComponent:()=>lt,Button:()=>Ft,CallInfo:()=>yi,Camera:()=>ne,Canvas:()=>Je,CanvasGroup:()=>sn,Collider:()=>fi,ColorAdjustments:()=>Bn,ControlTrackHandler:()=>Ki,Deletable:()=>eo,DeleteBox:()=>lr,DeviceFlag:()=>cr,DragControls:()=>Et,DropListener:()=>An,Duplicatable:()=>vi,EmissionModule:()=>bo,EventList:()=>Oe,EventListEvent:()=>pr,EventSystem:()=>Ze,EventTrigger:()=>lo,FieldWithDefault:()=>Fr,FlyControls:()=>co,GltfExport:()=>jt,GltfExportBox:()=>uo,Graphic:()=>Rt,GraphicRaycaster:()=>Fo,GridHelper:()=>Qi,GridLayoutGroup:()=>Bo,GroundProjectedEnv:()=>Yi,HorizontalLayoutGroup:()=>jo,Image:()=>on,InputField:()=>Ct,InstancingUtil:()=>he,InstantiateOptions:()=>ye,Interactable:()=>kt,Keyboard:()=>Do,LODGroup:()=>In,LODModel:()=>Ei,LayoutGroup:()=>an,Light:()=>Ye,LogStats:()=>Oo,LookAtConstraint:()=>Fi,MainModule:()=>go,MaskableGraphic:()=>rn,MeshRenderer:()=>rr,NavMesh:()=>fo,NavMeshAgent:()=>mo,NestedGltf:()=>fr,Networking:()=>pt,ObjectRaycaster:()=>Si,OffsetConstraint:()=>wi,OrbitControls:()=>gt,ParticleSystem:()=>yo,ParticleSystemRenderer:()=>gr,PlayableDirector:()=>tn,PlayerColor:()=>ht,PointerEventData:()=>ii,RGBAColor:()=>we,RawImage:()=>Tr,Raycaster:()=>Cr,Rect:()=>xr,RectTransform:()=>ut,RemoteSkybox:()=>Ln,Renderer:()=>Te,RendererLightmap:()=>ji,Rigidbody:()=>ce,ScreenCapture:()=>Eo,ShadowCatcher:()=>Mn,ShapeModule:()=>vo,SignalAsset:()=>wr,SignalReceiver:()=>$i,SignalReceiverEvent:()=>_r,SignalTrackHandler:()=>en,Size:()=>Mo,SkinnedMeshRenderer:()=>Nr,SmoothFollow:()=>_i,SpatialHtml:()=>No,SpatialTrigger:()=>Zi,SpatialTriggerReceiver:()=>wt,SpectatorCamera:()=>_o,SphereCollider:()=>Tn,SpringJoint:()=>xo,Sprite:()=>br,SpriteRenderer:()=>Ji,SyncedCamera:()=>Dn,SyncedRoom:()=>ti,SyncedTransform:()=>Qe,TeleportTarget:()=>dr,TestRunner:()=>To,TestSimulateUserData:()=>Ro,Text:()=>Le,ToneMapping:()=>jn,TransformGizmo:()=>vr,UIRootComponent:()=>nn,UnityObject:()=>Kr,UsageMarker:()=>It,VRUserState:()=>Ht,VerticalLayoutGroup:()=>Ho,VideoPlayer:()=>nt,Voip:()=>Ke,Volume:()=>yr,VolumeComponent:()=>xi,VolumeParameter:()=>Co,VolumeProfile:()=>Hn,WebAR:()=>On,WebARSessionRoot:()=>Dt,WebXR:()=>$,WebXRAvatar:()=>Lt,WebXRController:()=>ae,WebXRSync:()=>qi,XRFlag:()=>Se,XRGrabModel:()=>Er,XRGrabRendering:()=>So,XRRig:()=>Pn,XRState:()=>vt});import*as FE from"three";var Yd={Context:Z};globalThis.Needle=Yd;function Rf(l){for(let e in l)Yd[e]=l[e]}Rf(jl);Rf(Qd);for(let l of Object.getOwnPropertyNames(S))switch(l){case"prototype":case"constructor":case"length":case"name":continue;default:Yd[l]=S[l];break}globalThis.THREE?console.warn("Threejs is already imported"):globalThis.THREE=FE;export{_n as AlignmentConstraint,Jt as Animation,sr as AnimationCurve,Nn as AnimationTrackHandler,bt as Animator,Zt as AnimatorController,dt as AttachedObject,$t as AudioListener,ue as AudioSource,zn as AudioTrackHandler,Ti as AvatarBlink_Simple,Ri as AvatarEyeLook_Rotation,xn as AvatarLoader,pe as AvatarMarker,ar as AvatarModel,Ui as Avatar_Brain_LookAt,Fn as Avatar_MouthShapes,Po as Avatar_MustacheShake,_e as Avatar_POI,zi as AxesHelper,Ue as BaseUIComponent,Yr as BasicIKConstraint,M as Behaviour,Rn as BoxCollider,Xi as BoxGizmo,lt as BoxHelperComponent,Ft as Button,yi as CallInfo,ne as Camera,Je as Canvas,sn as CanvasGroup,fi as Collider,Bn as ColorAdjustments,Ki as ControlTrackHandler,eo as Deletable,lr as DeleteBox,cr as DeviceFlag,Et as DragControls,An as DropListener,vi as Duplicatable,bo as EmissionModule,Oe as EventList,pr as EventListEvent,Ze as EventSystem,lo as EventTrigger,Fr as FieldWithDefault,co as FlyControls,S as GameObject,jt as GltfExport,uo as GltfExportBox,Rt as Graphic,Fo as GraphicRaycaster,Qi as GridHelper,Bo as GridLayoutGroup,Yi as GroundProjectedEnv,jo as HorizontalLayoutGroup,on as Image,Ct as InputField,he as InstancingUtil,ye as InstantiateOptions,kt as Interactable,Do as Keyboard,In as LODGroup,Ei as LODModel,an as LayoutGroup,Ye as Light,Oo as LogStats,Fi as LookAtConstraint,go as MainModule,rn as MaskableGraphic,rr as MeshRenderer,fo as NavMesh,mo as NavMeshAgent,fr as NestedGltf,pt as Networking,Si as ObjectRaycaster,wi as OffsetConstraint,gt as OrbitControls,yo as ParticleSystem,gr as ParticleSystemRenderer,tn as PlayableDirector,ht as PlayerColor,ii as PointerEventData,we as RGBAColor,Tr as RawImage,Cr as Raycaster,xr as Rect,ut as RectTransform,Ln as RemoteSkybox,Te as Renderer,ji as RendererLightmap,ce as Rigidbody,Eo as ScreenCapture,Mn as ShadowCatcher,vo as ShapeModule,wr as SignalAsset,$i as SignalReceiver,_r as SignalReceiverEvent,en as SignalTrackHandler,Mo as Size,Nr as SkinnedMeshRenderer,_i as SmoothFollow,No as SpatialHtml,Zi as SpatialTrigger,wt as SpatialTriggerReceiver,_o as SpectatorCamera,Tn as SphereCollider,xo as SpringJoint,br as Sprite,Ji as SpriteRenderer,Dn as SyncedCamera,ti as SyncedRoom,Qe as SyncedTransform,dr as TeleportTarget,To as TestRunner,Ro as TestSimulateUserData,Le as Text,jn as ToneMapping,vr as TransformGizmo,nn as UIRootComponent,Kr as UnityObject,It as UsageMarker,Ht as VRUserState,Ho as VerticalLayoutGroup,nt as VideoPlayer,Ke as Voip,yr as Volume,xi as VolumeComponent,Co as VolumeParameter,Hn as VolumeProfile,On as WebAR,Dt as WebARSessionRoot,$ as WebXR,Lt as WebXRAvatar,ae as WebXRController,qi as WebXRSync,Se as XRFlag,Er as XRGrabModel,So as XRGrabRendering,Pn as XRRig,vt as XRState,A as serializeable};
161
161
  /*!
162
162
  * Determine if an object is a Buffer
163
163
  *