@needle-tools/engine 4.7.0-next.da47826 → 4.7.0-next.ef983f9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +5 -0
- package/dist/{needle-engine.bundle-CO1Ub9sm.js → needle-engine.bundle-450ujan4.js} +585 -574
- package/dist/{needle-engine.bundle-D95XN5pP.min.js → needle-engine.bundle-BDMr_I34.min.js} +33 -30
- package/dist/{needle-engine.bundle-Bu88IoKB.umd.cjs → needle-engine.bundle-CbNroJbN.umd.cjs} +32 -29
- package/dist/needle-engine.js +2 -2
- package/dist/needle-engine.min.js +1 -1
- package/dist/needle-engine.umd.cjs +1 -1
- package/lib/engine/engine_context.js +4 -3
- package/lib/engine/engine_context.js.map +1 -1
- package/lib/engine/engine_three_utils.js +4 -0
- package/lib/engine/engine_three_utils.js.map +1 -1
- package/lib/engine/webcomponents/needle-engine.attributes.d.ts +1 -1
- package/lib/engine-components/Camera.js +1 -1
- package/lib/engine-components/Camera.js.map +1 -1
- package/lib/engine-components/CameraUtils.js +5 -3
- package/lib/engine-components/CameraUtils.js.map +1 -1
- package/lib/engine-components/Skybox.js +4 -4
- package/lib/engine-components/Skybox.js.map +1 -1
- package/lib/engine-components/postprocessing/Effects/Antialiasing.js +8 -1
- package/lib/engine-components/postprocessing/Effects/Antialiasing.js.map +1 -1
- package/lib/engine-components/postprocessing/Effects/ScreenspaceAmbientOcclusionN8.js +1 -1
- package/lib/engine-components/postprocessing/PostProcessingHandler.js +15 -1
- package/lib/engine-components/postprocessing/PostProcessingHandler.js.map +1 -1
- package/lib/engine-components/postprocessing/Volume.js +1 -1
- package/lib/engine-components/postprocessing/Volume.js.map +1 -1
- package/package.json +1 -1
- package/plugins/common/logger.js +223 -0
- package/plugins/types/userconfig.d.ts +3 -1
- package/plugins/vite/alias.js +55 -40
- package/plugins/vite/imports-logger.js +1 -1
- package/plugins/vite/index.js +4 -0
- package/plugins/vite/logger.client.js +216 -0
- package/plugins/vite/logger.js +85 -0
- package/plugins/vite/materialx.js +32 -0
- package/plugins/vite/transform.js +1 -0
- package/src/engine/engine_context.ts +4 -3
- package/src/engine/engine_three_utils.ts +3 -0
- package/src/engine/webcomponents/needle-engine.attributes.ts +1 -1
- package/src/engine-components/Camera.ts +1 -1
- package/src/engine-components/CameraUtils.ts +5 -3
- package/src/engine-components/Skybox.ts +5 -5
- package/src/engine-components/postprocessing/Effects/Antialiasing.ts +8 -1
- package/src/engine-components/postprocessing/Effects/ScreenspaceAmbientOcclusionN8.ts +1 -1
- package/src/engine-components/postprocessing/PostProcessingHandler.ts +14 -2
- package/src/engine-components/postprocessing/Volume.ts +1 -1
|
@@ -79,7 +79,7 @@ varying vec2 vUv;
|
|
|
79
79
|
void main(){
|
|
80
80
|
vUv = uv;
|
|
81
81
|
gl_Position = vec4(position.xy, 0., 1.0);
|
|
82
|
-
}`);let Bb=Db;const Gs=class{static copyTexture(e,t){t||(t=this.blitMaterial),this.blitMaterial.reset();const s=t||this.blitMaterial;s.uniforms.map.value=e,s.needsUpdate=!0,s.uniformsNeedUpdate=!0;const o=s.vertexShader;s.vertexShader=Bb.vertex;const r=this.mesh;r.material=s,r.frustumCulled=!1,this.scene.children.length=0,this.scene.add(r),this.renderer.setSize(e.image.width,e.image.height),this.renderer.clear(),this.renderer.render(this.scene,this.perspectiveCam);const l=new je(this.renderer.domElement);return l.name="Copy",l.needsUpdate=!0,s.vertexShader=o,l}static blit(e,t,s){const{renderer:o=this.renderer,blitMaterial:r=this.blitMaterial,flipY:l=!1,depthTexture:c=null,depthTest:h=!0,depthWrite:d=!0}=s||{};this.blitMaterial.reset(),r.uniforms.map&&(r.uniforms.map.value=e),r.uniforms.flipY&&(r.uniforms.flipY.value=l),c?(r.uniforms.writeDepth=new Qi(!0),r.uniforms.depthTexture.value=c):(r.uniforms.writeDepth=new Qi(!1),r.uniforms.depthTexture.value=null),r.needsUpdate=!0,r.uniformsNeedUpdate=!0;const u=this.mesh;u.material=r,u.frustumCulled=!1,this.scene.children.length=0,this.scene.add(u);const p=o.getRenderTarget(),g=o.getContext(),f=g.getParameter(g.DEPTH_TEST),y=g.getParameter(g.DEPTH_WRITEMASK),v=g.getParameter(g.DEPTH_FUNC);h?o.getContext().enable(o.getContext().DEPTH_TEST):o.getContext().disable(o.getContext().DEPTH_TEST),o.state.buffers.depth.setMask(d),o.setClearColor(new oe(0,0,0),0),o.setPixelRatio(window.devicePixelRatio),o.setRenderTarget(t),o.clear(),o.render(this.scene,this.perspectiveCam),o.setRenderTarget(p);const b=o.state.buffers.depth;b.setTest(f),b.setMask(y),b.setFunc(v)}static textureToCanvas(e,t=!1){if(!e)return null;(t===!0||e.isCompressedTexture===!0)&&(e=Fb(e));const s=e.image;if(Tk(s)){const o=document.createElement("canvas");o.width=s.width,o.height=s.height;const r=o.getContext("2d");return r?(r.drawImage(s,0,0,s.width,s.height,0,0,o.width,o.height),o):(console.error("Failed getting canvas 2d context"),null)}return null}};a(Gs,"planeGeometry",new Ns(2,2,1,1)),a(Gs,"renderer",new fr({antialias:!1,alpha:!0})),a(Gs,"perspectiveCam",new we),a(Gs,"orthographicCam",new ud),a(Gs,"scene",new xi),a(Gs,"blitMaterial",new Bb),a(Gs,"mesh",new G(Gs.planeGeometry,Gs.blitMaterial));let Jl=Gs;function Fb(n){return Jl.copyTexture(n)}function Rk(n,e=!1){return Jl.textureToCanvas(n,e)}function Tk(n){return typeof HTMLImageElement<"u"&&n instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&n instanceof HTMLCanvasElement||typeof OffscreenCanvas<"u"&&n instanceof OffscreenCanvas||typeof ImageBitmap<"u"&&n instanceof ImageBitmap}function Ek(n){const e=n.type;return e==="Mesh"||e==="SkinnedMesh"}function mg(n,e){e?n["needle:rendercustomshadow"]=!0:n["needle:rendercustomshadow"]=!1}function Ub(n){return!!(n&&(n["needle:rendercustomshadow"]===!0||n["needle:rendercustomshadow"]==null))}function si(n,e=void 0,t=void 0,s=void 0){const o=s||new Si;o.makeEmpty();const r=[];function l(h){let d=!0;if(h.visible&&Pb(h)!==!1&&!(h.type==="TransformControlsGizmo"||h.type==="TransformControlsPlane")){if(h instanceof EC&&(d=!1),h instanceof Mm&&(d=!1),h instanceof ka&&(d=!1),h.isGizmo===!0&&(d=!1),h.material instanceof kv&&(d=!1),Ek(h)||(d=!1),t&&h.layers.test(t)===!1&&(d=!1),d&&(e&&Array.isArray(e)&&e!=null&&e.includes(h)||typeof e=="function"&&e(h)===!0))return;if(h.isUI!==!0){if(d){const u=h.children;h.children=r;const p=h.position,g=h.scale;if(Number.isNaN(p.x)||Number.isNaN(p.y)||Number.isNaN(p.z)){console.warn(`Object "${h.name}" has NaN values in position or scale.... will ignore it`,p,g);return}o.expandByObject(h,!0),h.children=u}for(const u of h.children)l(u)}}}let c=!1;Array.isArray(n)||(n=[n]);for(const h of n)h&&(c=!0,h.updateMatrixWorld(),l(h));return c||console.warn("No objects to fit camera to..."),o}function zb(n,e,t){const s=si([n],t?.ignore),o=new S;s.getSize(o);const r=new S;s.getCenter(r);const l=new S;e.getSize(l);const c=new S;e.getCenter(c);const h=new S;h.set(l.x/o.x,l.y/o.y,l.z/o.z);const d=Math.min(h.x,h.y,h.z),u=t?.scale!==!1;if(u&&Ta(n,Ge(n).multiplyScalar(d)),t?.position!==!1){const p=new S;s.getCenter(p),p.y=s.min.y;const g=new S;e.getCenter(g),g.y=e.min.y;const f=g.clone().sub(p);u&&f.multiplyScalar(d),lt(n,ee(n).add(f))}return{boundsBefore:s,scale:h}}function Nb(n,e){const t=si([n]),s=new S;t.getCenter(s),s.y=t.min.y;const o=e.clone().sub(s),r=ee(n);return lt(n,r.add(o)),{offset:o,bounds:t}}function gg(n,e,t,s){if(Array.isArray(e)){let l=!0;for(let c=0;c<e.length;c++)gg(n,e[c],c,e)||(l=!1);return l}if(e.type==="MeshStandardMaterial"||e.type==="MeshBasicMaterial")return!1;if(e["material:fbx"]!=null)return!0;const o=new bt;o["material:fbx"]=e;const r=e;return r&&(r.map?o.color.set(1,1,1):o.color.copyLinearToSRGB(r.color),o.emissive.copyLinearToSRGB(r.emissive),o.emissiveIntensity=r.emissiveIntensity,o.opacity=r.opacity,o.displacementScale=r.displacementScale,o.transparent=r.transparent,o.bumpMap=r.bumpMap,o.aoMap=r.aoMap,o.map=r.map,o.displacementMap=r.displacementMap,o.emissiveMap=r.emissiveMap,o.normalMap=r.normalMap,o.envMap=r.envMap,o.alphaMap=r.alphaMap,o.metalness=r.reflectivity,o.vertexColors=r.vertexColors,r.shininess&&(o.roughness=1-Math.sqrt(r.shininess)/10),o.needsUpdate=!0),t===void 0?n.material=o:s[t]=o,!0}let Ld=!1;nk((...n)=>{var e;F()&&(e=pe.Current)!=null&&e.isInXR&&(wr(!0),Wb("error",...n))});function wr(n){if(n){if(Ld)return;Ld=!0,Ik()}else{if(!Ld)return;Ld=!1,Lk()}}const ec={log:void 0,warn:void 0,error:void 0};class Ak{constructor(){a(this,"familyName","needle-xr"),a(this,"root",null),a(this,"context",null),a(this,"defaultFontSize",.06),a(this,"targetObject",new E),a(this,"userForwardViewPoint",new S),a(this,"oneEuroFilter",new og(90,.8)),a(this,"_lastElementRemoveTime",0),a(this,"onBeforeRender",()=>{var e,t;const s=(e=this.context)==null?void 0:e.mainCamera;if(this.context&&s instanceof we){const o=this.getRoot();Number.isNaN(o.position.x)&&o.position.set(0,0,0),Number.isNaN(o.quaternion.x)&&o.quaternion.set(0,0,0,1),this.context.scene.add(this.targetObject);const r=((t=this.context.xr)==null?void 0:t.rigScale)??1,l=3.5*r,c=s.worldForward;c.y=0,c.normalize().multiplyScalar(l),this.userForwardViewPoint.copy(s.worldPosition).sub(c),this.targetObject.position.distanceTo(this.userForwardViewPoint)>2*r&&(this.targetObject.position.copy(this.userForwardViewPoint),Kl(this.targetObject,s,!0,!0),this.targetObject.rotateY(Math.PI)),this.oneEuroFilter.filter(this.targetObject.position,o.position,this.context.time.time);const h=this.context.time.deltaTime;if(o.quaternion.slerp(this.targetObject.quaternion,h*5),o.scale.setScalar(r),this.targetObject.removeFromParent(),this.context.scene.add(o),this.context.time.time-this._lastElementRemoveTime>.1){this._lastElementRemoveTime=this.context.time.time;const d=Date.now();for(let u=0;u<this._activeTexts.length;u++){const p=this._activeTexts[u];if(p instanceof Re.Text&&d-p._activatedTime>2e4){p.removeFromParent(),this._textBuffer.push(p),this._activeTexts.splice(u,1);break}}}}}),a(this,"textOptions",{fontSize:this.defaultFontSize,fontFamily:this.familyName,padding:.03,margin:.005,color:0,backgroundColor:16777215,backgroundOpacity:.4,borderRadius:.03,offset:.025}),a(this,"_textBuffer",[]),a(this,"_activeTexts",[]),this.ensureFont()}onEnable(){this.context=pe.Current||pe.All[0],this.context.pre_render_callbacks.push(this.onBeforeRender)}onDisable(){var e,t,s;(t=this.context)==null||t.pre_render_callbacks.splice((e=this.context)==null?void 0:e.pre_render_callbacks.indexOf(this.onBeforeRender),1),(s=this.root)==null||s.removeFromParent()}addLog(e,t){const s=this.getRoot(),o=this.getText();let r=16777215,l=0;switch(e){case"log":r=16777215,l=0;break;case"warn":r=16772761,l=4465152;break;case"error":r=16755370,l=7798784;break}t.length>1e3&&(t=t.substring(0,1e3)+"...");const c=new Date().toISOString().split("T")[1].split(".")[0];o.textContent="["+c+"] "+t,o.visible=!0,o._activatedTime=Date.now(),s.add(o),this._activeTexts.push(o),this.context&&this.context.scene.add(s),o.set({backgroundColor:r,color:l}),Re.update()}ensureFont(){let e=Re.FontLibrary.getFontFamily(this.familyName);if(!e){e=Re.FontLibrary.addFontFamily(this.familyName);const t=e.addVariant("normal","normal","./include/needle/arial-msdf.json","./include/needle/arial.png");t?.addEventListener("ready",()=>{Re.update()})}}getText(){const e=this.getRoot();if(this._textBuffer.length>0){const s=this._textBuffer.pop();return s.visible=!0,setTimeout(()=>this.disableDepthTestRecursive(s),100),s}if(e.children.length>20&&this._activeTexts.length>0)return this._activeTexts.shift();const t=new Re.Text(this.textOptions);return setTimeout(()=>this.disableDepthTestRecursive(t),500),setTimeout(()=>this.disableDepthTestRecursive(t),1500),t}disableDepthTestRecursive(e,t=0){for(let o=0;o<e.children.length;o++){const r=e.children[o];r instanceof E&&this.disableDepthTestRecursive(r,t+1)}e.renderOrder=10*t,e.layers.set(2);const s=e.material;s&&(s.depthWrite=!1,s.depthTest=!1,s.transparent=!0),t===0&&Re.update()}getRoot(){if(this.root)return this.root;const e=this.defaultFontSize,t={boxSizing:"border-box",fontFamily:this.familyName,width:"2.6",fontSize:e,color:0,lineHeight:1,backgroundColor:16777215,backgroundOpacity:0,whiteSpace:"pre-wrap",flexDirection:"column-reverse"};return this.root=new Re.Block(t),this.root}}let _s=null;function Ik(){_s||(_s=new Ak),_s.onEnable();for(const n in ec){ec[n]=console[n];let e=!1;console[n]=function(){var t;if((t=ec[n])==null||t.apply(console,arguments),!e)try{e=!0,Wb(n,...arguments)}finally{e=!1}}}}function Lk(){_s?.onDisable();for(const n in ec)console[n]=ec[n]}const tc=new Map;function Wb(n,...e){try{switch(tc.clear(),n){case"log":_s?.addLog("log",t());break;case"warn":_s?.addLog("warn",t());break;case"error":_s?.addLog("error",t());break}}catch(r){console.error("Error in spatial console",r)}finally{tc.clear()}function t(){let r="";for(let l=0;l<e.length;l++){const c=e[l];r+=s(c),l<e.length-1&&(r+=", ")}return r}function s(r,l=0){if(typeof r=="string")return'"'+r+'"';if(typeof r=="number"){if(r%1!==0){const c=r.toFixed(5),h=c.indexOf(".");let d=c.length-1;for(;d>h&&c[d]==="0";)d--;return c.substring(0,d+1)}return r.toString()}else if(Array.isArray(r)){let c="[";for(let h=0;h<r.length;h++){const d=r[h];c+=s(d,l+1),h<r.length-1&&(c+=", ")}return c+="]",c}else{if(r===null)return"null";if(r===void 0)return"undefined";if(typeof r=="function")return r.name+"()"}if(r instanceof re)return`(${s(r.x)}, ${s(r.y)})`;if(r instanceof S)return`(${s(r.x)}, ${s(r.y)}, ${s(r.z)})`;if(r instanceof fe)return`(${s(r.x)}, ${s(r.y)}, ${s(r.z)}, ${s(r.w)})`;if(r instanceof V)return`(${s(r.x)}, ${s(r.y)}, ${s(r.z)}, ${s(r.w)})`;if(r instanceof Pe||r instanceof je)return r.name;if(r instanceof Mv)return`[${r.elements.join(", ")}]`;if(r instanceof se)return`[${r.elements.join(", ")}]`;if(r instanceof uo)return r.mask.toString();if(typeof r=="object"){if(tc.has(r))return"*";let c=`{
|
|
82
|
+
}`);let Bb=Db;const Gs=class{static copyTexture(e,t){t||(t=this.blitMaterial),this.blitMaterial.reset();const s=t||this.blitMaterial;s.uniforms.map.value=e,s.needsUpdate=!0,s.uniformsNeedUpdate=!0;const o=s.vertexShader;s.vertexShader=Bb.vertex;const r=this.mesh;r.material=s,r.frustumCulled=!1,this.scene.children.length=0,this.scene.add(r),this.renderer.setSize(e.image.width,e.image.height),this.renderer.clear(),this.renderer.render(this.scene,this.perspectiveCam);const l=new je(this.renderer.domElement);return l.name="Copy",l.needsUpdate=!0,s.vertexShader=o,l}static blit(e,t,s){const{renderer:o=this.renderer,blitMaterial:r=this.blitMaterial,flipY:l=!1,depthTexture:c=null,depthTest:h=!0,depthWrite:d=!0}=s||{};this.blitMaterial.reset(),r.uniforms.map&&(r.uniforms.map.value=e),r.uniforms.flipY&&(r.uniforms.flipY.value=l),c?(r.uniforms.writeDepth=new Qi(!0),r.uniforms.depthTexture.value=c):(r.uniforms.writeDepth=new Qi(!1),r.uniforms.depthTexture.value=null),r.needsUpdate=!0,r.uniformsNeedUpdate=!0;const u=this.mesh;u.material=r,u.frustumCulled=!1,this.scene.children.length=0,this.scene.add(u);const p=o.getRenderTarget(),g=o.getContext(),f=g.getParameter(g.DEPTH_TEST),y=g.getParameter(g.DEPTH_WRITEMASK),v=g.getParameter(g.DEPTH_FUNC);h?o.getContext().enable(o.getContext().DEPTH_TEST):o.getContext().disable(o.getContext().DEPTH_TEST),o.state.buffers.depth.setMask(d),o.setClearColor(new oe(0,0,0),0),o.setPixelRatio(window.devicePixelRatio),o.setRenderTarget(t),o.clear(),o.render(this.scene,this.perspectiveCam),o.setRenderTarget(p);const b=o.state.buffers.depth;b.setTest(f),b.setMask(y),b.setFunc(v)}static textureToCanvas(e,t=!1){if(!e)return null;(t===!0||e.isCompressedTexture===!0)&&(e=Fb(e));const s=e.image;if(Tk(s)){const o=document.createElement("canvas");o.width=s.width,o.height=s.height;const r=o.getContext("2d");return r?(r.drawImage(s,0,0,s.width,s.height,0,0,o.width,o.height),o):(console.error("Failed getting canvas 2d context"),null)}return null}};a(Gs,"planeGeometry",new Ns(2,2,1,1)),a(Gs,"renderer",new fr({antialias:!1,alpha:!0})),a(Gs,"perspectiveCam",new we),a(Gs,"orthographicCam",new ud),a(Gs,"scene",new xi),a(Gs,"blitMaterial",new Bb),a(Gs,"mesh",new G(Gs.planeGeometry,Gs.blitMaterial));let Jl=Gs;function Fb(n){return Jl.copyTexture(n)}function Rk(n,e=!1){return Jl.textureToCanvas(n,e)}function Tk(n){return typeof HTMLImageElement<"u"&&n instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&n instanceof HTMLCanvasElement||typeof OffscreenCanvas<"u"&&n instanceof OffscreenCanvas||typeof ImageBitmap<"u"&&n instanceof ImageBitmap}function Ek(n){const e=n.type;return e==="Mesh"||e==="SkinnedMesh"}function mg(n,e){e?n["needle:rendercustomshadow"]=!0:n["needle:rendercustomshadow"]=!1}function Ub(n){return!!(n&&(n["needle:rendercustomshadow"]===!0||n["needle:rendercustomshadow"]==null))}function si(n,e=void 0,t=void 0,s=void 0){const o=s||new Si;o.makeEmpty();const r=[];function l(h){let d=!0;if(h.visible&&Pb(h)!==!1&&!(h.type==="TransformControlsGizmo"||h.type==="TransformControlsPlane")){if(h instanceof EC&&(d=!1),h instanceof Mm&&(d=!1),h instanceof ka&&(d=!1),h.isGizmo===!0&&(d=!1),h.material instanceof kv&&(d=!1),Ek(h)||(d=!1),t&&h.layers.test(t)===!1&&(d=!1),d&&(e&&Array.isArray(e)&&e!=null&&e.includes(h)||typeof e=="function"&&e(h)===!0))return;if(h.isUI!==!0){if(d){const u=h.children;h.children=r;const p=h.position,g=h.scale;if(Number.isNaN(p.x)||Number.isNaN(p.y)||Number.isNaN(p.z)){console.warn(`Object "${h.name}" has NaN values in position or scale.... will ignore it`,p,g);return}h.geometry===null&&(h.geometry=void 0),o.expandByObject(h,!0),h.children=u}for(const u of h.children)l(u)}}}let c=!1;Array.isArray(n)||(n=[n]);for(const h of n)h&&(c=!0,h.updateMatrixWorld(),l(h));return c||console.warn("No objects to fit camera to..."),o}function zb(n,e,t){const s=si([n],t?.ignore),o=new S;s.getSize(o);const r=new S;s.getCenter(r);const l=new S;e.getSize(l);const c=new S;e.getCenter(c);const h=new S;h.set(l.x/o.x,l.y/o.y,l.z/o.z);const d=Math.min(h.x,h.y,h.z),u=t?.scale!==!1;if(u&&Ta(n,Ge(n).multiplyScalar(d)),t?.position!==!1){const p=new S;s.getCenter(p),p.y=s.min.y;const g=new S;e.getCenter(g),g.y=e.min.y;const f=g.clone().sub(p);u&&f.multiplyScalar(d),lt(n,ee(n).add(f))}return{boundsBefore:s,scale:h}}function Nb(n,e){const t=si([n]),s=new S;t.getCenter(s),s.y=t.min.y;const o=e.clone().sub(s),r=ee(n);return lt(n,r.add(o)),{offset:o,bounds:t}}function gg(n,e,t,s){if(Array.isArray(e)){let l=!0;for(let c=0;c<e.length;c++)gg(n,e[c],c,e)||(l=!1);return l}if(e.type==="MeshStandardMaterial"||e.type==="MeshBasicMaterial")return!1;if(e["material:fbx"]!=null)return!0;const o=new bt;o["material:fbx"]=e;const r=e;return r&&(r.map?o.color.set(1,1,1):o.color.copyLinearToSRGB(r.color),o.emissive.copyLinearToSRGB(r.emissive),o.emissiveIntensity=r.emissiveIntensity,o.opacity=r.opacity,o.displacementScale=r.displacementScale,o.transparent=r.transparent,o.bumpMap=r.bumpMap,o.aoMap=r.aoMap,o.map=r.map,o.displacementMap=r.displacementMap,o.emissiveMap=r.emissiveMap,o.normalMap=r.normalMap,o.envMap=r.envMap,o.alphaMap=r.alphaMap,o.metalness=r.reflectivity,o.vertexColors=r.vertexColors,r.shininess&&(o.roughness=1-Math.sqrt(r.shininess)/10),o.needsUpdate=!0),t===void 0?n.material=o:s[t]=o,!0}let Ld=!1;nk((...n)=>{var e;F()&&(e=pe.Current)!=null&&e.isInXR&&(wr(!0),Wb("error",...n))});function wr(n){if(n){if(Ld)return;Ld=!0,Ik()}else{if(!Ld)return;Ld=!1,Lk()}}const ec={log:void 0,warn:void 0,error:void 0};class Ak{constructor(){a(this,"familyName","needle-xr"),a(this,"root",null),a(this,"context",null),a(this,"defaultFontSize",.06),a(this,"targetObject",new E),a(this,"userForwardViewPoint",new S),a(this,"oneEuroFilter",new og(90,.8)),a(this,"_lastElementRemoveTime",0),a(this,"onBeforeRender",()=>{var e,t;const s=(e=this.context)==null?void 0:e.mainCamera;if(this.context&&s instanceof we){const o=this.getRoot();Number.isNaN(o.position.x)&&o.position.set(0,0,0),Number.isNaN(o.quaternion.x)&&o.quaternion.set(0,0,0,1),this.context.scene.add(this.targetObject);const r=((t=this.context.xr)==null?void 0:t.rigScale)??1,l=3.5*r,c=s.worldForward;c.y=0,c.normalize().multiplyScalar(l),this.userForwardViewPoint.copy(s.worldPosition).sub(c),this.targetObject.position.distanceTo(this.userForwardViewPoint)>2*r&&(this.targetObject.position.copy(this.userForwardViewPoint),Kl(this.targetObject,s,!0,!0),this.targetObject.rotateY(Math.PI)),this.oneEuroFilter.filter(this.targetObject.position,o.position,this.context.time.time);const h=this.context.time.deltaTime;if(o.quaternion.slerp(this.targetObject.quaternion,h*5),o.scale.setScalar(r),this.targetObject.removeFromParent(),this.context.scene.add(o),this.context.time.time-this._lastElementRemoveTime>.1){this._lastElementRemoveTime=this.context.time.time;const d=Date.now();for(let u=0;u<this._activeTexts.length;u++){const p=this._activeTexts[u];if(p instanceof Re.Text&&d-p._activatedTime>2e4){p.removeFromParent(),this._textBuffer.push(p),this._activeTexts.splice(u,1);break}}}}}),a(this,"textOptions",{fontSize:this.defaultFontSize,fontFamily:this.familyName,padding:.03,margin:.005,color:0,backgroundColor:16777215,backgroundOpacity:.4,borderRadius:.03,offset:.025}),a(this,"_textBuffer",[]),a(this,"_activeTexts",[]),this.ensureFont()}onEnable(){this.context=pe.Current||pe.All[0],this.context.pre_render_callbacks.push(this.onBeforeRender)}onDisable(){var e,t,s;(t=this.context)==null||t.pre_render_callbacks.splice((e=this.context)==null?void 0:e.pre_render_callbacks.indexOf(this.onBeforeRender),1),(s=this.root)==null||s.removeFromParent()}addLog(e,t){const s=this.getRoot(),o=this.getText();let r=16777215,l=0;switch(e){case"log":r=16777215,l=0;break;case"warn":r=16772761,l=4465152;break;case"error":r=16755370,l=7798784;break}t.length>1e3&&(t=t.substring(0,1e3)+"...");const c=new Date().toISOString().split("T")[1].split(".")[0];o.textContent="["+c+"] "+t,o.visible=!0,o._activatedTime=Date.now(),s.add(o),this._activeTexts.push(o),this.context&&this.context.scene.add(s),o.set({backgroundColor:r,color:l}),Re.update()}ensureFont(){let e=Re.FontLibrary.getFontFamily(this.familyName);if(!e){e=Re.FontLibrary.addFontFamily(this.familyName);const t=e.addVariant("normal","normal","./include/needle/arial-msdf.json","./include/needle/arial.png");t?.addEventListener("ready",()=>{Re.update()})}}getText(){const e=this.getRoot();if(this._textBuffer.length>0){const s=this._textBuffer.pop();return s.visible=!0,setTimeout(()=>this.disableDepthTestRecursive(s),100),s}if(e.children.length>20&&this._activeTexts.length>0)return this._activeTexts.shift();const t=new Re.Text(this.textOptions);return setTimeout(()=>this.disableDepthTestRecursive(t),500),setTimeout(()=>this.disableDepthTestRecursive(t),1500),t}disableDepthTestRecursive(e,t=0){for(let o=0;o<e.children.length;o++){const r=e.children[o];r instanceof E&&this.disableDepthTestRecursive(r,t+1)}e.renderOrder=10*t,e.layers.set(2);const s=e.material;s&&(s.depthWrite=!1,s.depthTest=!1,s.transparent=!0),t===0&&Re.update()}getRoot(){if(this.root)return this.root;const e=this.defaultFontSize,t={boxSizing:"border-box",fontFamily:this.familyName,width:"2.6",fontSize:e,color:0,lineHeight:1,backgroundColor:16777215,backgroundOpacity:0,whiteSpace:"pre-wrap",flexDirection:"column-reverse"};return this.root=new Re.Block(t),this.root}}let _s=null;function Ik(){_s||(_s=new Ak),_s.onEnable();for(const n in ec){ec[n]=console[n];let e=!1;console[n]=function(){var t;if((t=ec[n])==null||t.apply(console,arguments),!e)try{e=!0,Wb(n,...arguments)}finally{e=!1}}}}function Lk(){_s?.onDisable();for(const n in ec)console[n]=ec[n]}const tc=new Map;function Wb(n,...e){try{switch(tc.clear(),n){case"log":_s?.addLog("log",t());break;case"warn":_s?.addLog("warn",t());break;case"error":_s?.addLog("error",t());break}}catch(r){console.error("Error in spatial console",r)}finally{tc.clear()}function t(){let r="";for(let l=0;l<e.length;l++){const c=e[l];r+=s(c),l<e.length-1&&(r+=", ")}return r}function s(r,l=0){if(typeof r=="string")return'"'+r+'"';if(typeof r=="number"){if(r%1!==0){const c=r.toFixed(5),h=c.indexOf(".");let d=c.length-1;for(;d>h&&c[d]==="0";)d--;return c.substring(0,d+1)}return r.toString()}else if(Array.isArray(r)){let c="[";for(let h=0;h<r.length;h++){const d=r[h];c+=s(d,l+1),h<r.length-1&&(c+=", ")}return c+="]",c}else{if(r===null)return"null";if(r===void 0)return"undefined";if(typeof r=="function")return r.name+"()"}if(r instanceof re)return`(${s(r.x)}, ${s(r.y)})`;if(r instanceof S)return`(${s(r.x)}, ${s(r.y)}, ${s(r.z)})`;if(r instanceof fe)return`(${s(r.x)}, ${s(r.y)}, ${s(r.z)}, ${s(r.w)})`;if(r instanceof V)return`(${s(r.x)}, ${s(r.y)}, ${s(r.z)}, ${s(r.w)})`;if(r instanceof Pe||r instanceof je)return r.name;if(r instanceof Mv)return`[${r.elements.join(", ")}]`;if(r instanceof se)return`[${r.elements.join(", ")}]`;if(r instanceof uo)return r.mask.toString();if(typeof r=="object"){if(tc.has(r))return"*";let c=`{
|
|
83
83
|
`;c+=o(l);const h=Object.keys(r);let d="";for(let u=0;u<h.length;u++){const p=h[u],g=r[p];if(tc.has(g)){d+="";continue}tc.set(g,!0),d+=p+":"+s(g,l+1),u<h.length-1&&(d+=", "),d.length>=60&&(d+=`
|
|
84
84
|
`,d+=o(l),c+=d,d="")}return c+=d,c+=`
|
|
85
85
|
}`,c}return r}function o(r){let l="";for(let c=0;c<r;c++)l+=" ";return l}}const jk=C("nodevlogs");function De(n,e=ki.Log){Hs(e,n)}function be(n){De(n,ki.Warn)}function ic(n){De(n,ki.Error)}let fg,yg;function F(){if(jk)return!1;if(fg!==void 0)return fg;if(yg!==void 0)return yg;let n=Xt();return n||(n=window.location.hostname.endsWith(".local-credentialless.webcontainer.io")),yg=n,n}function Dk(n){fg=n}let ni,Ki=null,qs=null,sc=!1,Vb=null;const $b="terminal",nc=C("console"),Bk=C("noerrors")||C("noconsole")||window.crossOriginIsolated;if(nc&&bg(),!Bk&&(nc||Xt())){if(Xt()&&!nc){const e=new URL(window.location.href);e.searchParams.set("console","1"),console.log('\u{1F335} Tip: You can add the "?console" query parameter to the url to show the debug console (on mobile it will automatically open in the bottom right corner when your get errors during development. In VR a spatial console will appear.)',`
|
|
@@ -142,7 +142,7 @@ Open this page to get the console: `+e.toString())}const n=X.isMobileDevice()||X
|
|
|
142
142
|
#__vconsole .vc-mask {
|
|
143
143
|
overflow: hidden;
|
|
144
144
|
}
|
|
145
|
-
`,Ki?.prepend(s),n===!0&&tg()<=0&&Hb(),console.log("\u{1F335} Debug console has loaded")}},e.onerror=()=>{console.warn("\u{1F335} Debug console failed to load."+(window.crossOriginIsolated?"This page is using cross-origin isolation, so external scripts can't be loaded.":"")),sc=!1,ni=null},e.src="https://cdn.jsdelivr.net/npm/vconsole@3.9.1/dist/vconsole.min.js",document.body.appendChild(e)}function Wk(){if(!globalThis.VConsole)return;const n=new VConsole.VConsolePlugin("needle-console","\u{1F335} Inspect glTF"),e=()=>document.querySelector("#__vc_plug_"+n._id+" iframe");return n.on("renderTab",function(t){const s=globalThis["needle:codegen_files"];if(!s||s.length===0)return;let o=globalThis["needle:codegen_files"][0];const r=o.indexOf("?");r>-1&&(o=o.substring(0,r));const l=location.protocol+"//"+location.host+location.pathname+"/"+o,c=encodeURIComponent(l);n.fullUrl="https://viewer.needle.tools?inspect&file="+c;var h='<iframe src="" style="width: 100%; height: 99%; border: none;"></iframe>';t(h)}),n.on("show",function(){const t=e();t&&t.src!==n.fullUrl&&(t.src=n.fullUrl)}),n.on("hide",function(){const t=e();t&&(t.src="")}),n.on("addTopBar",function(t){var s=new Array;s.push({name:"Open in new window \u2197",onClick:function(o){window.open(n.fullUrl,"_blank"),ni?.hide()}}),s.push({name:"Reload",onClick:function(o){const r=e();r&&(r.src=n.fullUrl)}}),s.push({name:"Fullscreen",onClick:function(o){const r=e();r.requestFullscreen?r.requestFullscreen():r.webkitRequestFullscreen instanceof Function&&r.webkitRequestFullscreen()}}),t(s)}),n}function Vk(){return document.querySelector("#__vconsole .vc-switch")||null}function $k(){return document.querySelector("#__vconsole")||null}const Qb=C("debugdefines");bo('if(!globalThis["NEEDLE_ENGINE_VERSION"]) globalThis["NEEDLE_ENGINE_VERSION"] = "0.0.0";'),bo('if(!globalThis["NEEDLE_ENGINE_GENERATOR"]) globalThis["NEEDLE_ENGINE_GENERATOR"] = "unknown";'),bo('if(!globalThis["NEEDLE_PROJECT_BUILD_TIME"]) globalThis["NEEDLE_PROJECT_BUILD_TIME"] = "unknown";'),bo('if(!globalThis["NEEDLE_PUBLIC_KEY"]) globalThis["NEEDLE_PUBLIC_KEY"] = "unknown";'),bo('globalThis["__NEEDLE_ENGINE_VERSION__"] = "4.7.0-alpha";'),bo('globalThis["__NEEDLE_ENGINE_GENERATOR__"] = "undefined";'),bo('globalThis["__NEEDLE_PROJECT_BUILD_TIME__"] = "
|
|
145
|
+
`,Ki?.prepend(s),n===!0&&tg()<=0&&Hb(),console.log("\u{1F335} Debug console has loaded")}},e.onerror=()=>{console.warn("\u{1F335} Debug console failed to load."+(window.crossOriginIsolated?"This page is using cross-origin isolation, so external scripts can't be loaded.":"")),sc=!1,ni=null},e.src="https://cdn.jsdelivr.net/npm/vconsole@3.9.1/dist/vconsole.min.js",document.body.appendChild(e)}function Wk(){if(!globalThis.VConsole)return;const n=new VConsole.VConsolePlugin("needle-console","\u{1F335} Inspect glTF"),e=()=>document.querySelector("#__vc_plug_"+n._id+" iframe");return n.on("renderTab",function(t){const s=globalThis["needle:codegen_files"];if(!s||s.length===0)return;let o=globalThis["needle:codegen_files"][0];const r=o.indexOf("?");r>-1&&(o=o.substring(0,r));const l=location.protocol+"//"+location.host+location.pathname+"/"+o,c=encodeURIComponent(l);n.fullUrl="https://viewer.needle.tools?inspect&file="+c;var h='<iframe src="" style="width: 100%; height: 99%; border: none;"></iframe>';t(h)}),n.on("show",function(){const t=e();t&&t.src!==n.fullUrl&&(t.src=n.fullUrl)}),n.on("hide",function(){const t=e();t&&(t.src="")}),n.on("addTopBar",function(t){var s=new Array;s.push({name:"Open in new window \u2197",onClick:function(o){window.open(n.fullUrl,"_blank"),ni?.hide()}}),s.push({name:"Reload",onClick:function(o){const r=e();r&&(r.src=n.fullUrl)}}),s.push({name:"Fullscreen",onClick:function(o){const r=e();r.requestFullscreen?r.requestFullscreen():r.webkitRequestFullscreen instanceof Function&&r.webkitRequestFullscreen()}}),t(s)}),n}function Vk(){return document.querySelector("#__vconsole .vc-switch")||null}function $k(){return document.querySelector("#__vconsole")||null}const Qb=C("debugdefines");bo('if(!globalThis["NEEDLE_ENGINE_VERSION"]) globalThis["NEEDLE_ENGINE_VERSION"] = "0.0.0";'),bo('if(!globalThis["NEEDLE_ENGINE_GENERATOR"]) globalThis["NEEDLE_ENGINE_GENERATOR"] = "unknown";'),bo('if(!globalThis["NEEDLE_PROJECT_BUILD_TIME"]) globalThis["NEEDLE_PROJECT_BUILD_TIME"] = "unknown";'),bo('if(!globalThis["NEEDLE_PUBLIC_KEY"]) globalThis["NEEDLE_PUBLIC_KEY"] = "unknown";'),bo('globalThis["__NEEDLE_ENGINE_VERSION__"] = "4.7.0-alpha";'),bo('globalThis["__NEEDLE_ENGINE_GENERATOR__"] = "undefined";'),bo('globalThis["__NEEDLE_PROJECT_BUILD_TIME__"] = "Fri Jul 25 2025 19:57:11 GMT+0000 (Coordinated Universal Time)";'),bo('globalThis["__NEEDLE_PUBLIC_KEY__"] = "'+NEEDLE_PUBLIC_KEY+'";');const ws="4.7.0-alpha",jd="undefined",_g="Fri Jul 25 2025 19:57:11 GMT+0000 (Coordinated Universal Time)";Qb&&console.log(`Engine version: ${ws} (generator: ${jd})
|
|
146
146
|
Project built at ${_g}`);const Ea=NEEDLE_PUBLIC_KEY,En="needle_isActiveInHierarchy",xr="builtin_components",oc="needle_editor_guid";function bo(n){try{(0,eval)(n)}catch(e){Qb&&console.error(e)}}let Yb,Kb=null;function xs(){return Yb}function wg(n){if(n==null){console.warn("Oh no: someone tried registering a non-existend gltf-loader. When you see this log it might mean that needle-engine is being imported multiple times. Please check your project setup.");return}Kb!==n&&(Kb=n,Yb=new n)}const Mi=Symbol("shadowDomOwner"),Hk=C("debugpatch");function Dd(n,e,t,s){const o=Hk===e;if(!t&&!s)return;const r=e+"___needle";qk(n,e,t,s);const l=Object.getOwnPropertyDescriptor(n,e),c=n[e];o&&console.log("Patch",n.constructor.name,e,l,c),l?(o&&console.log("Apply patch with existing descriptor",n.constructor.name,e,l),typeof l.value=="function"&&(n[e]=Jb(l.value,n,e))):(o&&console.log("Create patch with new property",n.constructor.name,e,l),Object.defineProperty(n,e,{set:function(h){if(typeof h=="function")this[r]=Jb(h,n,e);else{const d=this[r];e_(n,e,this,d,h),this[r]=h,t_(n,e,this,d,h)}},get:function(){const h=this[r];return typeof h=="function"&&h[r]?h[r]:h}}))}function Gk(n,e,t){const s=Sg(n,e);if(s)for(let o=s.length-1;o>=0;o--){const r=s[o];r.prefix===t&&(r.prefix=null),r.postfix===t&&(r.postfix=null),!r.prefix&&!r.postfix&&s.splice(o,1)}}const Zb=Symbol("Needle:Patches:WrappedFunction");function Jb(n,e,t){if(n[Zb])return n;const s=function(...o){e_(e,t,this,...o);const r=n.apply(this,o);return t_(e,t,this,r,...o),r};return s[Zb]=!0,s}const Bd="Needle:Patches";function xg(){return globalThis[Bd]||(globalThis[Bd]=new WeakMap),globalThis[Bd]}function Sg(n,e){const t=xg().get(n);return t?t.get(e):null}function qk(n,e,t,s){let o=xg().get(n);o||(o=new Map,xg().set(n,o));let r=o.get(e);r||(r=[],o.set(e,r)),r.push({prefix:t,postfix:s})}function e_(n,e,t,...s){var o;if(!t)return;const r=Sg(n,e);if(r)for(const l of r)(o=l.prefix)==null||o.call(t,...s)}function t_(n,e,t,s,...o){var r;if(!t)return;const l=Sg(n,e);if(l)for(const c of l)(r=c.postfix)==null||r.call(t,s,...o)}const Aa=[];function Fd(n){Aa.indexOf(n)===-1&&Aa.push(n)}function Xk(n){const e=Aa.indexOf(n);e!==-1&&Aa.splice(e,1)}const Ia=[];function Cg(n){Ia.indexOf(n)===-1&&Ia.push(n)}function Qk(n){const e=Ia.indexOf(n);e!==-1&&Ia.splice(e,1)}function i_(n){globalThis.dispatchEvent(new CustomEvent("needle-xrsession-start",{detail:n}));for(let e=0;e<Aa.length;e++)Aa[e](n)}function s_(n){globalThis.dispatchEvent(new CustomEvent("needle-xrsession-end",{detail:n}));for(let e=0;e<Ia.length;e++)Ia[e](n)}const ct=C("debuginput");var Ud=(n=>(n.Mouse="mouse",n.Touch="touch",n.Controller="controller",n.Hand="hand",n))(Ud||{}),Be=(n=>(n.PointerDown="pointerdown",n.PointerUp="pointerup",n.PointerMove="pointermove",n.KeyDown="keydown",n.KeyUp="keyup",n.KeyPressed="keypress",n))(Be||{});class An extends PointerEvent{constructor(e,t,s){super(e,s),a(this,"clientZ"),a(this,"deviceIndex"),a(this,"origin"),a(this,"source"),a(this,"mode"),a(this,"_ray"),a(this,"space"),a(this,"isClick",!1),a(this,"isDoubleClick",!1),a(this,"_used",!1),a(this,"_pointerid"),a(this,"_pointerType"),a(this,"_type"),a(this,"metadata",{}),a(this,"intersections",new Array),a(this,"_immediatePropagationStopped",!1),a(this,"_propagationStopped",!1),this.clientZ=s.clientZ,this._pointerid=s.pointerId,this._pointerType=s.pointerType,this._type=e,this.deviceIndex=s.deviceIndex,this.origin=s.origin,this.source=t,this.mode=s.mode,this._ray=s.ray,this.space=s.device}get isSpatial(){return this.mode!="screen"}get ray(){return this._ray||(this._ray=new po(this.space.worldPosition.clone(),this.space.worldForward.clone())),this._ray}set ray(e){this._ray=e}get hasRay(){return this._ray!==void 0}get used(){return this._used}use(){this._used=!0}get pointerId(){return this._pointerid}get pointerType(){return this._pointerType}get type(){return this._type}get immediatePropagationStopped(){return this._immediatePropagationStopped}get propagationStopped(){return this._immediatePropagationStopped||this._propagationStopped}stopImmediatePropagation(){var e;this._immediatePropagationStopped=!0,super.stopImmediatePropagation(),(e=this.source)==null||e.stopImmediatePropagation()}stopPropagation(){var e;this._propagationStopped=!0,super.stopPropagation(),(e=this.source)==null||e.stopPropagation(),ct&&console.warn("Stop propagation...",this.pointerId,this.pointerType)}}class rc extends KeyboardEvent{constructor(e,t,s){super(e,s),a(this,"source"),this.source=t}stopImmediatePropagation(){var e;super.stopImmediatePropagation(),(e=this.source)==null||e.stopImmediatePropagation()}}class Yk{constructor(e){a(this,"key"),a(this,"keyType"),a(this,"source"),this.key=e.key,this.keyType=e.type,this.source=e}}var oi=(n=>(n[n.Early=-100]="Early",n[n.Default=0]="Default",n[n.Late=100]="Late",n))(oi||{});class n_{constructor(e){a(this,"_eventListeners",{}),a(this,"_doubleClickTimeThreshold",.2),a(this,"_longPressTimeThreshold",1),a(this,"_setCursorTypes",[]),a(this,"context"),a(this,"_pointerDown",[!1]),a(this,"_pointerUp",[!1]),a(this,"_pointerClick",[!1]),a(this,"_pointerDoubleClick",[!1]),a(this,"_pointerPressed",[!1]),a(this,"_pointerPositions",[new re]),a(this,"_pointerPositionsLastFrame",[new re]),a(this,"_pointerPositionsDelta",[new re]),a(this,"_pointerPositionsRC",[new re]),a(this,"_pointerPositionDown",[new S]),a(this,"_pointerDownTime",[]),a(this,"_pointerUpTime",[]),a(this,"_pointerUpTimestamp",[]),a(this,"_pointerIds",[]),a(this,"_pointerTypes",[""]),a(this,"_mouseWheelChanged",[!1]),a(this,"_mouseWheelDeltaY",[0]),a(this,"_pointerEvent",[]),a(this,"_pointerEventsPressed",[]),a(this,"_pointerSpace",[]),a(this,"_pressedStack",new Map),a(this,"_htmlEventSource"),a(this,"onLostFocus",()=>{for(const t in this.keysPressed)this.keysPressed[t].pressed=!1}),a(this,"_receivedPointerMoveEventsThisFrame",new Array),a(this,"onEndOfFrame",()=>{this._receivedPointerMoveEventsThisFrame.length=0;for(let t=0;t<this._pointerUp.length;t++)this._pointerUp[t]=!1;for(let t=0;t<this._pointerDown.length;t++)this._pointerDown[t]=!1;for(let t=0;t<this._pointerClick.length;t++)this._pointerClick[t]=!1;for(let t=0;t<this._pointerDoubleClick.length;t++)this._pointerDoubleClick[t]=!1;for(const t of this._pointerPositionsDelta)t.set(0,0);for(let t=0;t<this._mouseWheelChanged.length;t++)this._mouseWheelChanged[t]=!1;for(let t=0;t<this._mouseWheelDeltaY.length;t++)this._mouseWheelDeltaY[t]=0}),a(this,"onContextMenu",t=>{this.canReceiveInput(t)!==!1&&t instanceof PointerEvent&&t.pointerType}),a(this,"keysPressed",{}),a(this,"onKeyDown",t=>{if(ct&&console.log(`key down ${t.code}, ${this.context.application.hasFocus}`,t),!this.context.application.hasFocus)return;const s=this.keysPressed[t.code];if(s&&s.pressed)return;this.keysPressed[t.code]={pressed:!0,frame:this.context.time.frameCount+1,startFrame:this.context.time.frameCount+1,key:t.key,code:t.code};const o=new rc("keydown",t,t);this.onDispatchEvent(o)}),a(this,"onKeyPressed",t=>{if(!this.context.application.hasFocus)return;const s=this.keysPressed[t.code];if(!s)return;s.pressed=!0,s.frame=this.context.time.frameCount+1;const o=new rc("keypress",t,t);this.onDispatchEvent(o)}),a(this,"onKeyUp",t=>{if(!this.context.application.hasFocus)return;const s=this.keysPressed[t.code];if(!s)return;s.pressed=!1,s.frame=this.context.time.frameCount+1;const o=new rc("keyup",t,t);this.onDispatchEvent(o)}),a(this,"onWheelWindow",t=>{document.pointerLockElement&&this.onMouseWheel(t)}),a(this,"onMouseWheel",t=>{if(this.canReceiveInput(t)===!1)return;this._mouseWheelDeltaY.length<=0&&this._mouseWheelDeltaY.push(0),this._mouseWheelChanged.length<=0&&this._mouseWheelChanged.push(!1),this._mouseWheelChanged[0]=!0;const s=this._mouseWheelDeltaY[0];this._mouseWheelDeltaY[0]=s+t.deltaY}),a(this,"onPointerDown",t=>{if(this.context.isInAR||this.canReceiveInput(t)===!1)return;t.target instanceof HTMLElement&&t.target.setPointerCapture(t.pointerId);const s=this.getPointerId(t);ct&&De(`pointer down #${s}, identifier:${t.pointerId}`);const o=this.getAndUpdateSpatialObjectForScreenPosition(s,t.clientX,t.clientY),r=new An("pointerdown",t,{origin:this,mode:"screen",deviceIndex:0,pointerId:s,button:t.button,clientX:t.clientX,clientY:t.clientY,pointerType:t.pointerType,buttonName:this.getButtonName(t),device:o,pressure:t.pressure});this.onDown(r)}),a(this,"onPointerMove",t=>{if(this.context.isInAR||this._receivedPointerMoveEventsThisFrame.includes(t.pointerId))return;this._receivedPointerMoveEventsThisFrame.push(t.pointerId);let s=t.button;t.pointerType==="mouse"&&(s=this.getFirstPressedButtonForPointer(0)??0);const o=this.getPointerId(t,s);s===-1&&(s=o);const r=this.getAndUpdateSpatialObjectForScreenPosition(o,t.clientX,t.clientY),l=new An("pointermove",t,{origin:this,mode:"screen",deviceIndex:0,pointerId:o,button:s,clientX:t.clientX,clientY:t.clientY,pointerType:t.pointerType,buttonName:this.getButtonName(t),device:r,pressure:t.pressure});this.onMove(l)}),a(this,"onPointerCancel",t=>{this.context.isInAR||(ct&&console.log("Pointer cancel",t),this.onPointerUp(t))}),a(this,"onPointerUp",t=>{if(this.context.isInAR)return;t.target instanceof HTMLElement&&t.target.releasePointerCapture(t.pointerId);const s=this.getPointerId(t),o=new An("pointerup",t,{origin:this,mode:"screen",deviceIndex:0,pointerId:s,button:t.button,clientX:t.clientX,clientY:t.clientY,pointerType:t.pointerType,buttonName:this.getButtonName(t),device:this.getAndUpdateSpatialObjectForScreenPosition(s,t.clientX,t.clientY),pressure:t.pressure});this.onUp(o),this._pointerIds[s]=-1,ct&&console.log("ID="+s,"PointerId="+t.pointerId,"ALL:",[...this._pointerIds])}),a(this,"onTouchStart",t=>{if(this.context.isInAR)for(let s=0;s<t.changedTouches.length;s++){const o=t.changedTouches[s],r=this.getPointerIndex(o.identifier),l=this.getAndUpdateSpatialObjectForScreenPosition(r,o.clientX,o.clientY),c=new An("pointerdown",t,{origin:this,mode:"screen",deviceIndex:0,pointerId:r,button:0,clientX:o.clientX,clientY:o.clientY,pointerType:"touch",buttonName:"unknown",device:l,pressure:o.force});this.onDown(c)}}),a(this,"onTouchMove",t=>{if(this.context.isInAR)for(let s=0;s<t.changedTouches.length;s++){const o=t.changedTouches[s],r=this.getPointerIndex(o.identifier),l=this.getAndUpdateSpatialObjectForScreenPosition(r,o.clientX,o.clientY),c=new An("pointermove",t,{origin:this,mode:"screen",deviceIndex:0,pointerId:r,button:0,clientX:o.clientX,clientY:o.clientY,pointerType:"touch",buttonName:"unknown",device:l,pressure:o.force});this.onMove(c)}}),a(this,"onTouchEnd",t=>{if(this.context.isInAR)for(let s=0;s<t.changedTouches.length;s++){const o=t.changedTouches[s],r=this.getPointerIndex(o.identifier),l=new An("pointerup",t,{origin:this,mode:"screen",deviceIndex:0,pointerId:r,button:0,clientX:o.clientX,clientY:o.clientY,pointerType:"touch",buttonName:"unknown",device:this.getAndUpdateSpatialObjectForScreenPosition(r,o.clientX,o.clientY),pressure:o.force});this.onUp(l),this._pointerIds[r]=-1}}),a(this,"tempNearPlaneVector",new S),a(this,"tempFarPlaneVector",new S),a(this,"tempLookMatrix",new se),this.context=e,this.context.post_render_callbacks.push(this.onEndOfFrame)}addEventListener(e,t,s){if(this._eventListeners[e]||(this._eventListeners[e]=[]),!t||typeof t!="function"){console.error("Invalid call to addEventListener: callback is required and must be a function!");return}s?s={...s}:s={};let o=0;s?.queue!=null&&(o=s.queue);const r=this._eventListeners[e],l=r.find(c=>c.priority===o);l?l.listeners.push({callback:t,options:s}):(r.push({priority:o,listeners:[{callback:t,options:s}]}),r.sort((c,h)=>c.priority-h.priority))}removeEventListener(e,t,s){if(!this._eventListeners[e]||!t)return;const o=this._eventListeners[e];if(s?.queue!=null){const r=o.find(c=>c.priority===s.queue);if(!r)return;const l=r.listeners.findIndex(c=>c.callback===t);l>=0&&r.listeners.splice(l,1)}else for(const r of o){const l=r.listeners.findIndex(c=>c.callback===t);l>=0&&r.listeners.splice(l,1)}}dispatchEvent(e){var t,s,o,r;let l=!1;if(e instanceof rc){const c=this._eventListeners[e.type];if(c)for(const h of c)for(let d=0;d<h.listeners.length;d++){const u=h.listeners[d];if((s=(t=u.options)==null?void 0:t.signal)!=null&&s.aborted){h.listeners.splice(d,1),d--;continue}u.options.once&&(h.listeners.splice(d,1),d--),u.callback(e)}}if(e instanceof An){const c=this._eventListeners[e.type];if(c)for(const h of c){if(l)break;for(let d=0;d<h.listeners.length;d++){const u=h.listeners[d];if((r=(o=u.options)==null?void 0:o.signal)!=null&&r.aborted){h.listeners.splice(d,1),d--;continue}if(e.immediatePropagationStopped){l=!0,ct&&console.log("immediatePropagationStopped",e.type);break}else e.propagationStopped&&(l=!0,ct&&console.log("propagationStopped",e.type));u.options.once&&(h.listeners.splice(d,1),d--),u.callback(e)}}}}get mousePosition(){return this._pointerPositions[0]}get mousePositionRC(){return this._pointerPositionsRC[0]}get mouseDown(){return this._pointerDown[0]}get mouseUp(){return this._pointerUp[0]}get mouseClick(){return this._pointerClick[0]}get mouseDoubleClick(){return this._pointerDoubleClick[0]}get mousePressed(){return this._pointerPressed[0]}get mouseWheelChanged(){return this.getMouseWheelChanged(0)}get click(){return this._pointerClick[0]}get doubleClick(){return this._pointerDoubleClick[0]}getGamepad(e=0){return typeof navigator<"u"&&"getGamepads"in navigator&&navigator.getGamepads()[e]||null}setCursorPointer(){this.setCursor("pointer")}setCursorNormal(){this.unsetCursor("pointer")}setCursor(e){this._setCursorTypes.push(e),this._setCursorTypes.length>10&&this._setCursorTypes.shift(),this.updateCursor()}unsetCursor(e){for(let t=this._setCursorTypes.length-1;t>=0;t--)if(this._setCursorTypes[t]===e){this._setCursorTypes.splice(t,1),this.updateCursor();break}}updateCursor(){var e;((e=this._setCursorTypes)==null?void 0:e.length)==0?this.context.domElement.style.cursor="default":this.context.domElement.style.cursor=this._setCursorTypes[this._setCursorTypes.length-1]}getIsPointerIdInUse(e){for(const t of this._pointerEventsPressed)if(t.pointerId===e&&t.used)return!0;return!1}getPointerPressedCount(){let e=0;for(let t=0;t<this._pointerPressed.length;t++)this._pointerPressed[t]&&e++;return e}getPointerPosition(e){return e>=this._pointerPositions.length?null:this._pointerPositions[e]}getPointerPositionLastFrame(e){return e>=this._pointerPositionsLastFrame.length?null:this._pointerPositionsLastFrame[e]}getPointerPositionDelta(e){return e>=this._pointerPositionsDelta.length?null:this._pointerPositionsDelta[e]}getPointerPositionRC(e){return e>=this._pointerPositionsRC.length?null:this._pointerPositionsRC[e]}getPointerDown(e){return e>=this._pointerDown.length?!1:this._pointerDown[e]}getPointerUp(e){return e>=this._pointerUp.length?!1:this._pointerUp[e]}getPointerPressed(e){return e>=this._pointerPressed.length?!1:this._pointerPressed[e]}getPointerClicked(e){return e>=this._pointerClick.length?!1:this._pointerClick[e]}getPointerDoubleClicked(e){return e>=this._pointerDoubleClick.length?!1:this._pointerDoubleClick[e]}getPointerDownTime(e){return e>=this._pointerDownTime.length?-1:this._pointerDownTime[e]}getPointerUpTime(e){return e>=this._pointerUpTime.length?-1:this._pointerUpTime[e]}getPointerLongPress(e){return e>=this._pointerDownTime.length?!1:this.getPointerPressed(e)&&this.context.time.time-this._pointerDownTime[e]>this._longPressTimeThreshold}getIsMouse(e){return e<0||e>=this._pointerTypes.length?!1:this._pointerTypes[e]==="mouse"}getIsTouch(e){return e<0||e>=this._pointerTypes.length?!1:this._pointerTypes[e]==="touch"}getTouchesPressedCount(){let e=0;for(let t=0;t<this._pointerPressed.length;t++)this._pointerPressed[t]&&this.getIsTouch(t)&&e++;return e}getMouseWheelChanged(e=0){return e>=this._mouseWheelChanged.length?!1:this._mouseWheelChanged[e]}getMouseWheelDeltaY(e=0){return e>=this._mouseWheelDeltaY.length?0:this._mouseWheelDeltaY[e]}getPointerEvent(e){if(!(e>=this._pointerEvent.length))return this._pointerEvent[e]??void 0}*foreachPointerId(e){for(let t=0;t<this._pointerTypes.length;t++)if(this._pointerIsActive(t)){if(e!==void 0){const s=this._pointerTypes[t];if(Array.isArray(e)){let o=!1;for(const r of e)if(s===r){o=!0;break}if(!o)continue}else if(e!==s)continue}yield t}}*foreachTouchId(){for(let e=0;e<this._pointerTypes.length;e++)this._pointerTypes[e]==="touch"&&this._pointerIsActive[e]&&(yield e)}_pointerIsActive(e){return e<0?!1:this._pointerPressed[e]||this._pointerDown[e]||this._pointerUp[e]}onDownButton(e,t){let s=this._pressedStack.get(e);s||(s=[],this._pressedStack.set(e,s)),s.push(t)}onReleaseButton(e,t){const s=this._pressedStack.get(e);if(!s)return;const o=s.indexOf(t);o>=0&&s.splice(o,1)}getFirstPressedButtonForPointer(e){const t=this._pressedStack.get(e);if(t)return t[0]}getLatestPressedButtonForPointer(e){const t=this._pressedStack.get(e);if(t)return t[t.length-1]}getKeyDown(e){if(e!==void 0)return this.isKeyDown(e);for(const t in this.keysPressed){const s=this.keysPressed[t];if(s.startFrame===this.context.time.frameCount)return s.key}return null}getKeyPressed(e){if(e!==void 0)return this.isKeyPressed(e);for(const t in this.keysPressed){const s=this.keysPressed[t];if(s.pressed)return s.key}return null}getKeyUp(e){if(e!==void 0)return this.isKeyUp(e);for(const t in this.keysPressed){const s=this.keysPressed[t];return s.pressed===!1&&s.frame===this.context.time.frameCount}return null}isKeyDown(e){if(!this.context.application.isVisible||!this.context.application.hasFocus)return!1;const t=this.getCodeForCommonKeyName(e);if(t!==null){for(const o of t)if(this.isKeyDown(o))return!0;return!1}const s=this.keysPressed[e];return s?s.startFrame===this.context.time.frameCount&&s.pressed:!1}isKeyUp(e){if(!this.context.application.isVisible||!this.context.application.hasFocus)return!1;const t=this.getCodeForCommonKeyName(e);if(t!==null){for(const o of t)if(this.isKeyUp(o))return!0;return!1}const s=this.keysPressed[e];return s?s.frame===this.context.time.frameCount&&s.pressed===!1:!1}isKeyPressed(e){if(!this.context.application.isVisible||!this.context.application.hasFocus)return!1;const t=this.getCodeForCommonKeyName(e);if(t!==null){for(const o of t)if(this.isKeyPressed(o))return!0;return!1}const s=this.keysPressed[e];return s&&s.pressed||!1}getCodeForCommonKeyName(e){if(e.length===1){if(e>="0"&&e<="9")return["Digit"+e];if(e>="a"&&e<="z")return["Key"+e.toUpperCase()];if(e==" ")return["Space"]}switch(e){case"shift":case"Shift":return["ShiftLeft","ShiftRight"];case"control":case"Control":return["ControlLeft","ControlRight"];case"alt":case"Alt":return["AltLeft","AltRight"]}return null}createInputEvent(e){switch(e.type){case"pointerdown":ct&&De("Create Pointer down"),this.onDownButton(e.deviceIndex,e.button),this.onDown(e);break;case"pointermove":ct&&De("Create Pointer move"),this.onMove(e);break;case"pointerup":ct&&De("Create Pointer up"),this.onUp(e),this.onReleaseButton(e.deviceIndex,e.button);break}}convertScreenspaceToRaycastSpace(e){return e.x=(e.x-this.context.domX)/this.context.domWidth*2-1,e.y=-((e.y-this.context.domY)/this.context.domHeight)*2+1,e}bindEvents(){this.unbindEvents(),this._htmlEventSource=this.context.renderer.domElement,window.addEventListener("contextmenu",this.onContextMenu),this._htmlEventSource.addEventListener("pointerdown",this.onPointerDown,{passive:!0}),window.addEventListener("pointermove",this.onPointerMove,{passive:!0,capture:!0}),window.addEventListener("pointerup",this.onPointerUp,{passive:!0}),window.addEventListener("pointercancel",this.onPointerCancel,{passive:!0}),window.addEventListener("touchstart",this.onTouchStart,{passive:!0}),window.addEventListener("touchmove",this.onTouchMove,{passive:!0}),window.addEventListener("touchend",this.onTouchEnd,{passive:!0}),this._htmlEventSource.addEventListener("wheel",this.onMouseWheel,{passive:!0}),window.addEventListener("wheel",this.onWheelWindow,{passive:!0}),window.addEventListener("keydown",this.onKeyDown,!1),window.addEventListener("keypress",this.onKeyPressed,!1),window.addEventListener("keyup",this.onKeyUp,!1),window.addEventListener("blur",this.onLostFocus)}unbindEvents(){var e,t;window.removeEventListener("contextmenu",this.onContextMenu),(e=this._htmlEventSource)==null||e.removeEventListener("pointerdown",this.onPointerDown),window.removeEventListener("pointermove",this.onPointerMove),window.removeEventListener("pointerup",this.onPointerUp),window.removeEventListener("pointercancel",this.onPointerCancel),window.removeEventListener("touchstart",this.onTouchStart),window.removeEventListener("touchmove",this.onTouchMove),window.removeEventListener("touchend",this.onTouchEnd),(t=this._htmlEventSource)==null||t.removeEventListener("wheel",this.onMouseWheel,!1),window.removeEventListener("wheel",this.onWheelWindow,!1),window.removeEventListener("keydown",this.onKeyDown,!1),window.removeEventListener("keypress",this.onKeyPressed,!1),window.removeEventListener("keyup",this.onKeyUp,!1),window.removeEventListener("blur",this.onLostFocus)}dispose(){const e=this.context.post_render_callbacks.indexOf(this.onEndOfFrame);e>=0&&this.context.post_render_callbacks.splice(e,1),this.unbindEvents()}canReceiveInput(e){var t;return e.target===((t=this.context.renderer)==null?void 0:t.domElement)||e.target===this.context.domElement||this.context.isInAR||this.context.isInAR&&e.target===document.body&&X.isMozillaXR()?!0:(ct&&console.warn("CanReceiveInput:False for",e.target),!1)}getPointerId(e,t){return e.pointerType==="mouse"?0+(t??e.button):this.getPointerIndex(e.pointerId)}getButtonName(e){const t=e.button;if(e.pointerType==="mouse")switch(t){case 0:return"left";case 1:return"middle";case 2:return"right"}return"unknown"}getAndUpdateSpatialObjectForScreenPosition(e,t,s){let o=this._pointerSpace[e];o||(o=new E,this._pointerSpace[e]=o),this._pointerSpace[e]=o;const r=this.context.mainCamera;if(r){const l=this.tempNearPlaneVector.set(t,s,-1);this.convertScreenspaceToRaycastSpace(l);const c=this.tempFarPlaneVector.set(l.x,l.y,1);l.unproject(r),c.unproject(r);const h=r.worldUp||q(0,1,0).applyQuaternion(Se(r));this.tempLookMatrix.lookAt(c,l,h),o.position.set(l.x,l.y,l.z),o.quaternion.setFromRotationMatrix(this.tempLookMatrix)}return o}isInRect(e){if(this.context.isInXR)return!0;const t=this.context.domElement.getBoundingClientRect(),s=e.clientX,o=e.clientY,r=s>=t.x&&s<=t.right&&o>=t.y&&o<=t.bottom;return ct&&!r&&console.log("Not in rect",t,s,o),r}onDown(e){const t=e.pointerId;if(this.getPointerPressed(t)&&console.warn(`Received pointerDown for pointerId that is already pressed: ${t}`,ct?e:""),ct&&console.log(e.pointerType,"DOWN",t),!!this.isInRect(e)){for(this.setPointerState(t,this._pointerPressed,!0),this.setPointerState(t,this._pointerDown,!0),this.setPointerStateT(t,this._pointerEvent,e.source);t>=this._pointerTypes.length;)this._pointerTypes.push(e.pointerType);for(this._pointerTypes[t]=e.pointerType;t>=this._pointerPositionDown.length;)this._pointerPositionDown.push(new S);for(this._pointerPositionDown[t].set(e.clientX,e.clientY,e.clientZ??0);t>=this._pointerPositions.length;)this._pointerPositions.push(new re);this._pointerPositions[t].set(e.clientX,e.clientY),t>=this._pointerDownTime.length&&this._pointerDownTime.push(0),this._pointerDownTime[t]=this.context.time.realtimeSinceStartup,this.updatePointerPosition(e),this._pointerEventsPressed.push(e),this.onDispatchEvent(e)}}onMove(e){const t=e.pointerId,s=this.getPointerPressed(t);s===!1&&!this.isInRect(e)||e.pointerType==="touch"&&!s||(this.updatePointerPosition(e),this.setPointerStateT(t,this._pointerEvent,e.source),this.onDispatchEvent(e))}onUp(e){const t=e.pointerId;if(!this.getPointerPressed(t)){ct&&console.log(e.pointerType,"UP",t,"was not down");return}ct&&console.log(e.pointerType,"UP",t),this.setPointerState(t,this._pointerPressed,!1),this.setPointerStateT(t,this._pointerEvent,e.source),this.setPointerState(t,this._pointerUp,!0),this.updatePointerPosition(e);for(let c=this._pointerEventsPressed.length-1;c>=0;c--)if(this._pointerEventsPressed[c].pointerId===t){this._pointerEventsPressed.splice(c,1);break}if(!this._pointerPositionDown[t]){ct&&be("Received pointer up event without matching down event for button: "+t),console.warn("Received pointer up event without matching down event for button: "+t);return}const s=this._pointerUpTime[t],o=this._pointerDownTime[t],r=this.context.time.realtimeSinceStartup,l=r-o;if(t>=this._pointerUpTime.length&&this._pointerUpTime.push(-99),this._pointerUpTime[t]=r,l<1){let c=e.clientX-this._pointerPositionDown[t].x,h=e.clientY-this._pointerPositionDown[t].y,d=0;if(e.isSpatial&&e.clientZ!=null&&(d=e.clientZ-this._pointerPositionDown[t].z,c*=200,h*=200,d*=200),Math.abs(c)<5&&Math.abs(h)<5&&Math.abs(d)<5){this.setPointerState(t,this._pointerClick,!0),e.isClick=!0;const u=r-s;ct&&console.log("CLICK",t,c,h,d,u),u<this._doubleClickTimeThreshold&&u>0&&(this.setPointerState(t,this._pointerDoubleClick,!0),e.isDoubleClick=!0)}}this.onDispatchEvent(e)}updatePointerPosition(e){const t=e.pointerId;for(;t>=this._pointerPositions.length;)this._pointerPositions.push(new re);for(;t>=this._pointerPositionsLastFrame.length;)this._pointerPositionsLastFrame.push(new re);for(;t>=this._pointerPositionsDelta.length;)this._pointerPositionsDelta.push(new re);const s=this._pointerPositionsLastFrame[t];s.copy(this._pointerPositions[t]);const o=this._pointerPositionsDelta[t];let r=e.clientX-s.x,l=e.clientY-s.y;if(e.source instanceof MouseEvent||e.source instanceof TouchEvent){const u=e.source;r===0&&u.movementX!==0&&(r=u.movementX||0),l===0&&u.movementY!==0&&(l=u.movementY||0)}o.x+=r,o.y+=l,this._pointerPositions[t].x=e.clientX,this._pointerPositions[t].y=e.clientY;const c=e.clientX,h=e.clientY;for(;t>=this._pointerPositionsRC.length;)this._pointerPositionsRC.push(new re);const d=this._pointerPositionsRC[t];d.set(c,h),this.convertScreenspaceToRaycastSpace(d)}getPointerIndex(e){let t=-1;for(let s=0;s<this._pointerIds.length;s++){if(this._pointerIds[s]===e)return s;t===-1&&this._pointerIds[s]===-1&&(t=s)}return t!==-1?(this._pointerIds[t]=e,t):(ct&&console.log("PUSH pointerId:",e),this._pointerIds.push(e),this._pointerIds.length-1)}setPointerState(e,t,s){t[e]=s}setPointerStateT(e,t,s){return t[e]=s,s}onDispatchEvent(e){const t=J.Current;try{J.Current=this.context,this.dispatchEvent(e)}finally{J.Current=t}}}const La=new se().makeRotationY(Math.PI),Zi=new V().setFromAxisAngle(new S(0,1,0),Math.PI),Kk=C("debugwebxr");class Zk{constructor(){if(a(this,"priority",-1e5),a(this,"gameObject"),this.gameObject=new E,this.gameObject.name="Implicit XR Rig",Kk){const e=Vg(16733661);e.position.y+=.5,this.gameObject.add(e)}}isXRRig(){return!0}get isActive(){return this.gameObject.visible}}const In=C("debugwebxr"),zd=C("debugcustomgesture"),Jk="https://cdn.jsdelivr.net/npm/@webxr-input-profiles/assets@1.0/dist/profiles",eM="generic-trigger",tM=new V().setFromEuler(new Dt(Cn.degToRad(0),Cn.degToRad(-90),Cn.degToRad(-90))),iM=new S(.04,-.04,0);class Pg{constructor(e,t,s){a(this,"xr"),a(this,"inputSource"),a(this,"index",0),a(this,"emitEvents",!0),a(this,"_connected",!0),a(this,"_isTracking",!1),a(this,"__gamepad"),a(this,"__hand"),a(this,"__side"),a(this,"_hitTestSource"),a(this,"_hasSelectEvent",!1),a(this,"_isMxInk",!1),a(this,"_isMetaQuestTouchController",!1),a(this,"_handJointPoses",new Map),a(this,"_gripMatrix",new se),a(this,"_gripPosition",new S),a(this,"_gripQuaternion",new V),a(this,"_linearVelocity",new S),a(this,"_rayPositionRaw",new S),a(this,"_rayRotationRaw",new V),a(this,"_rayMatrix",new se),a(this,"_rayPosition",new S),a(this,"_rayQuaternion",new V),a(this,"_gripWorldPosition",new S),a(this,"_gripWorldQuaternion",new V),a(this,"_rayWorldPosition",new S),a(this,"_rayWorldQuaternion",new V),a(this,"_pinchPosition",new S),a(this,"_ray"),a(this,"_hand_wristDotUp"),a(this,"_object"),a(this,"_gripSpaceObject"),a(this,"_raySpaceObject"),a(this,"model",null),a(this,"_debugAxesHelper",new Ci(.15)),a(this,"_debugGripAxesHelper",new Ci(.07)),a(this,"_debugRayAxesHelper",new Ci(.07)),a(this,"_hitTestSourcePromise",null),a(this,"onPointerHits",o=>{}),a(this,"_needleGamepadButtons",{}),a(this,"_buttonMap",new Map),a(this,"_motioncontroller"),a(this,"_layout"),a(this,"getMotionController"),a(this,"emitPointerDownEvent",!0),a(this,"emitPointerUpEvent",!0),a(this,"emitPointerMoveEvent",!0),a(this,"pointerMoveDistanceThreshold",.03),a(this,"pointerMoveAngleThreshold",.05),a(this,"_selectButtonIndex"),a(this,"_squeezeButtonIndex"),a(this,"onSelectStart",o=>{var r,l,c,h;if(!this.emitPointerDownEvent||this.inputSource!==o.inputSource)return;this.onUpdateFrame(o.frame),this._hasSelectEvent=!0;const d=(r=this._layout)==null?void 0:r.selectComponentId,u=(h=(c=(l=this._layout)==null?void 0:l.components[d])==null?void 0:c.gamepadIndices)==null?void 0:h.button;u!==void 0&&(this._selectButtonIndex=u),!zd&&(In&&$.DrawDirection(this.rayWorldPosition,q(0,.01,1).applyQuaternion(this.rayWorldQuaternion),16711680,10),this.emitPointerEvent(Be.PointerDown,this._selectButtonIndex||0,"xr-standard-trigger",!0,o))}),a(this,"onSelectEnd",o=>{this.emitPointerUpEvent&&(zd||this.inputSource===o.inputSource&&this.emitPointerEvent(Be.PointerUp,this._selectButtonIndex||0,"xr-standard-trigger",!0,o))}),a(this,"onSequeezeStart",o=>{var r,l,c;this.emitPointerDownEvent&&this.inputSource===o.inputSource&&(this._squeezeButtonIndex=(c=(l=(r=this._layout)==null?void 0:r.components["xr-standard-squeeze"])==null?void 0:l.gamepadIndices)==null?void 0:c.button,this._squeezeButtonIndex!==void 0&&(In&&$.DrawDirection(this.rayWorldPosition,q(0,.01,1).applyQuaternion(this.rayWorldQuaternion),255,10),this.emitPointerEvent(Be.PointerDown,this._squeezeButtonIndex||0,"xr-standard-squeeze",!0,o)))}),a(this,"onSequeezeEnd",o=>{this.emitPointerUpEvent&&this.inputSource===o.inputSource&&this._squeezeButtonIndex!==void 0&&this.emitPointerEvent(Be.PointerUp,this._squeezeButtonIndex||0,"xr-standard-squeeze",!0,o)}),a(this,"states",{}),a(this,"_didMoveLastFrame",!1),a(this,"_lastPointerMovePosition",new S),a(this,"_lastPointerMoveQuaternion",new V),a(this,"pointerInit"),this.xr=e,this.inputSource=t,this.index=s,this._object=new E,this._object.name=`NeedleXRController_${s}`,In&&(this._object.add(this._debugAxesHelper),this._gripSpaceObject=new E,this._raySpaceObject=new E,this._gripSpaceObject.name=`NeedleXRController_${s}_gripSpace`,this._raySpaceObject.name=`NeedleXRController_${s}_raySpace`,this._gripSpaceObject.add(this._debugGripAxesHelper),this._raySpaceObject.add(this._debugRayAxesHelper),this.xr.context.scene.add(this._gripSpaceObject),this.xr.context.scene.add(this._raySpaceObject)),this.xr.context.scene.add(this._object),this._ray=new po,this.pointerInit={origin:this,pointerType:this.hand?"hand":"controller",deviceIndex:this.index,pointerId:-1,mode:this.inputSource.targetRayMode,ray:this._ray,device:this._object,buttonName:"none"},this.initialize(),this.subscribeEvents()}get context(){return this.xr.context}get connected(){return this._connected}get isTracking(){return this._isTracking}get gamepad(){return this.__gamepad??(this.__gamepad=this.inputSource.gamepad)}get isHand(){return this.hand!=null}get hand(){return this.__hand??(this.__hand=this.inputSource.hand)}get handObject(){return this.context.renderer.xr.getHand(this.index)}get profiles(){return this.inputSource.profiles}get layout(){return this._layout}get targetRayMode(){return this.inputSource.targetRayMode}get targetRaySpace(){return this.inputSource.targetRaySpace}get gripSpace(){return this.inputSource.gripSpace}get side(){return this.__side??(this.__side=this.inputSource.handedness)}get isRight(){return this.side==="right"}get isLeft(){return this.side==="left"}get isStylus(){return this._isMxInk}getHitTestSource(){return this._hitTestSource||this._requestHitTestSource(),this._hitTestSource}get hasHitTestSource(){return this._hitTestSource}cancelHitTestSource(){this._hitTestSource&&(this._hitTestSource.cancel(),this._hitTestSource=void 0)}get hasSelectEvent(){return this._hasSelectEvent}getHitTest(){return this.xr.getHitTest(this)}getHandJointPose(e,t){var s;if(t=t||this.xr.frame,!this.hand||!(t!=null&&t.getJointPose)||!this.xr.referenceSpace)return null;let o=(s=this._handJointPoses)==null?void 0:s.get(e);return o||(o=t.getJointPose(e,this.xr.referenceSpace),o&&this._handJointPoses.set(e,o),o)}get gripPosition(){return q(this._gripPosition)}get gripQuaternion(){return bs(this._gripQuaternion)}get gripMatrix(){return this._gripMatrix}get gripLinearVelocity(){return q(this._linearVelocity).applyQuaternion(Zi)}get rayPosition(){return q(this._rayPosition)}get rayQuaternion(){return bs(this._rayQuaternion)}get gripWorldPosition(){return q(this._gripWorldPosition)}get gripWorldQuaternion(){return bs(this._gripWorldQuaternion)}get rayWorldPosition(){return q(this._rayWorldPosition)}updateRayWorldPosition(){var e;const t=(e=this.xr.context.mainCamera)==null?void 0:e.parent;this._rayWorldPosition.copy(this._rayPositionRaw),t&&this._rayWorldPosition.applyMatrix4(t.matrixWorld)}get rayWorldQuaternion(){return bs(this._rayWorldQuaternion)}get pinchPosition(){return q(this._pinchPosition)}updateRayWorldQuaternion(){var e;const t=(e=this.xr.context.mainCamera)==null?void 0:e.parent,s=t?Se(t):void 0;this._rayWorldQuaternion.copy(this._rayRotationRaw).multiply(Zi),s&&this._rayWorldQuaternion.premultiply(s)}get ray(){return this._ray.origin.copy(this.rayWorldPosition),this._ray.direction.copy(q(0,0,1).applyQuaternion(this.rayWorldQuaternion)),this._ray}get handWristDotUp(){var e;if(this._hand_wristDotUp!==void 0)return this._hand_wristDotUp;const t=(e=this.handObject)==null?void 0:e.joints.wrist;if(t){const s=q(0,1,0).applyQuaternion(t.quaternion),o=q(0,1,0).dot(s);return this._hand_wristDotUp=o}}get isHandUpsideDown(){return this.handWristDotUp!==void 0?this.handWristDotUp<-.7:!1}get isTeleportGesture(){var e;return this.isHandUpsideDown&&((e=this.getGesture("pinch"))==null?void 0:e.isDown)}get object(){return this._object}async getModelUrl(){var e;return(e=this.getMotionController)==null?void 0:e.then(t=>t?.assetUrl||null)}_requestHitTestSource(){var e;return this._hitTestSourcePromise?this._hitTestSourcePromise:this.xr.mode==="immersive-ar"&&this.inputSource.targetRayMode==="tracked-pointer"&&this.xr.session.requestHitTestSourceForTransientInput?this._hitTestSourcePromise=((e=this.xr.session.requestHitTestSourceForTransientInput({profile:this.inputSource.profiles[0],offsetRay:new XRRay}))==null?void 0:e.then(t=>(this._hitTestSourcePromise=null,this.connected?this._hitTestSource=t:(t.cancel(),null))))??null:null}onUpdate(e){this.onUpdateFrame(e),this.updateInputEvents(),this.onUpdateMove()}onRenderDebug(){var e;$.DrawSphere(this.rayWorldPosition,.003),$.DrawDirection(this.rayWorldPosition,q(0,0,10).applyQuaternion(this.rayWorldQuaternion));const t=(this.inputSource.gripSpace?this.gripWorldPosition:this.object.worldPosition).sub(this.object.worldForward.multiplyScalar(.1)),s=this.inputSource.profiles.join(`
|
|
147
147
|
`);let o=`Controller[${this.index}] (${this.inputSource.targetRayMode}, ${this.side})
|
|
148
148
|
C:${this.connected?"x":"-"} T:${this.isTracking?"x":"-"} Hand:${this.inputSource.hand?"x":"-"} Pen: ${this._isMxInk?"x":"-"}`;if(this.inputSource.hand&&(o+=`
|
|
@@ -163,7 +163,7 @@ See https://engine.needle.tools/docs/scripting.html#special-lifecycle-hooks for
|
|
|
163
163
|
`+Ri);const c=await import("./vendor-BlSxe9JJ.min.js").then(p=>p.index),h=((s=c.default)==null?void 0:s.WebsocketBuilder)??c.WebsocketBuilder,d=((o=c.default)==null?void 0:o.ExponentialBackoff)??c.ExponentialBackoff,u=new h(Ri).withMaxRetries(10).withBackoff(new d(2e3,4)).onOpen(()=>{this._connectingToWebsocketPromise=null,this._ws=u,this.connected=!0,F()||ri?console.log(`\u229E Connected to networking backend
|
|
164
164
|
`+Ri):console.debug("\u229E Connected to networking backend",Ri),l(!0),this.onSendQueued(Ss.OnConnection)}).onClose(p=>{this._connectingToWebsocketPromise=null,this.connected=!1,this._isInRoom=!1,l(!1);let g="Websocket connection closed...";Ri!=null&&Ri.includes("/socket")||(g+=' Do you perhaps mean to connect to "/socket"?'),console.error(g)}).onError(p=>{console.error("\u22A0 Websocket connection failed..."),l(!1)}).onRetry(()=>{console.log("\u2192 Retry connecting to networking websocket")}).build();u.addEventListener(c.WebsocketEvent.message,(p,g)=>{this.onMessage(p,g)})})}onMessage(e,t){const s=t.data;try{if(typeof s!="string"){s.size&&this.handleIncomingBinaryMessage(s);return}const o=JSON.parse(s);if(Array.isArray(o))for(const r of o)this.handleIncomingStringMessage(r);else this.handleIncomingStringMessage(o);return}catch(o){ri&&s==="pong"?console.log("<<",s):F()&&console.error("Failed to parse message",o)}}async handleIncomingBinaryMessage(e){Vd&&console.log("<< bin",this.context.time.frame);const t=await e.arrayBuffer();var s=new Uint8Array(t);const o=new vO(s),r=o.getBufferIdentifier(),l=this._listenersBinary[r],c=d_(o),h=u_(c);if(h&&typeof h=="string"&&(this._state[h]=c),!l)return;const d=c??o;for(const u of l)u(d)}handleIncomingStringMessage(e){var t,s;if(ri&&console.log("<<",e.key??e),e.key)switch(e.key){case"connection-start-info":if(e.data){const h=e.data;h&&(console.assert(h.id!==void 0&&h.id!==null&&h.id.length>0,"server did not send connection id",h.id),console.debug("Your id is: "+h.id,this.context.alias??""),this._connectionId=h.id)}else console.warn("Expected connection id in "+e.key);break;case"joined-room":if(ri&&console.log(e),e){this._isInRoom=!0;const h=e;this._currentRoomName=h.room,this._currentRoomViewId=h.viewId,this._currentRoomAllowEditing=h.allowEditing??!0,this._currentInRoom.length=0,this._currentInRoom.push(...h.inRoom),(Vd||F())&&console.debug("Joined Needle Engine Room: "+h.room);const d=new URL(window.location.href);d.searchParams.has("room")&&d.searchParams.delete("room"),d.searchParams.set("view",this._currentRoomViewId),console.debug(`Room view id: ${this._currentRoomViewId}
|
|
165
165
|
${d.href}`)}this.onSendQueued(Ss.OnRoomJoin);break;case"left-room":const l=e;l.room===this.currentRoomName&&(this._isInRoom=!1,this._currentRoomName=null,this._currentRoomAllowEditing=!0,this._currentInRoom.length=0,(Vd||F())&&console.debug("Left Needle Engine Room: "+l.room));break;case"user-joined-room":if(e.data){const h=e.data;this._currentInRoom.push(h.userId),ri&&console.log(h.userId+" joined","now in room:",this._currentInRoom)}break;case"user-left-room":if(e.data){const h=e.data,d=this._currentInRoom.indexOf(h.userId);d>=0&&(ri&&console.log(h.userId+" left","now in room:",this._currentInRoom),this._currentInRoom.splice(d,1)),h.userId===this.connectionId&&console.log("you left the room")}break;case"all-room-state-deleted":ri&&console.log("RECEIVED all-room-state-deleted"),this._state={};break;case"ping":case"pong":const c=(t=e.data)==null?void 0:t.time;c&&(this._currentDelay=this.context.time.time-c),ri&&console.log(`Current latency: ${(this._currentDelay*1e3).toFixed()} ms`,"Clients in room: "+((s=this._currentInRoom)==null?void 0:s.length));break}const o=e.data;o&&(this._state[o.guid]=o);let r=this._listeners[e.key];if(r){r=[...r];for(const l of r)try{l(e.data)}catch(c){console.error('Error invoking callback for "'+e.key+'"',c)}}}toMessage(e,t){return{key:e,data:t}}sendWithWebsocket(e,t,s=Ss.OnRoomJoin){if(!this._ws){const r=this._waitingForSocket[s]||[];r.push(()=>this.sendWithWebsocket(e,t,s)),this._waitingForSocket[s]=r;return}const o=JSON.stringify(this.toMessage(e,t));ri&&console.log(">>",e),this._ws.send(o)}onSendQueued(e){const t=this._waitingForSocket[e];if(t){for(const s of t)s();t.length=0}}}const lc=C("debugwebxr");class Ig{constructor(e,t){a(this,"controllerStates",[]),a(this,"userId"),a(this,"context"),a(this,"userStateEvtName"),a(this,"onReceivedControllerState",s=>{lc&&console.log(`XRSync: Received change for ${this.userId}: ${s.type} ${s.handedness}; tracked=${s.isTracking}`);let o=!1;for(let r=0;r<this.controllerStates.length;r++)if(this.controllerStates[r].index===s.index){this.controllerStates[r]=s,o=!0;break}o||this.controllerStates.push(s)}),this.userId=e,this.context=t,this.userStateEvtName="xr-sync-user-state-"+e,this.context.connection.beginListen(this.userStateEvtName,this.onReceivedControllerState)}dispose(){this.context.connection.stopListen(this.userStateEvtName,this.onReceivedControllerState)}update(e){if(this.context.connection.isConnected!=!1){for(let t=this.controllerStates.length-1;t>=0;t--){const s=this.controllerStates[t];let o=!1;for(let r=0;r<e.controllers.length;r++)e.controllers[r].index===s.index&&(o=!0);o||(lc&&console.log(`XRSync: ${s.type} ${s.handedness} removed`,s.index),this.controllerStates.splice(t,1),this.sendControllerRemoved(s))}for(const t of e.controllers)this.updateControllerStates(t)}}onExitXR(e){for(const t of this.controllerStates)this.sendControllerRemoved(t);this.controllerStates.length=0}sendControllerRemoved(e){e.isTracking=!1,e.guid="",this.context.connection.send(this.userStateEvtName,e),this.context.connection.sendDeleteRemoteState(e.guid)}updateControllerStates(e){const t=this.controllerStates.find(s=>s.index===e.index);if(t){let s=!1;s||(s=t.isTracking!=e.isTracking),s&&(t.isTracking=e.isTracking,this.context.connection.send(this.userStateEvtName,t))}else{const s={guid:this.userId+"-"+e.index,isTracking:e.isTracking,handedness:e.side,index:e.index,type:e.hand?"hand":"controller"};this.controllerStates.push(s),this.context.connection.send(this.userStateEvtName,s),lc&&console.log(`XRSync: ${s.type} ${s.handedness} added`,s.index)}}}class __{constructor(e){a(this,"context"),a(this,"onJoinedRoom",()=>{if(this.context.connection.connectionId){this._states.has(this.context.connection.connectionId)||(lc&&console.log("XRSync: Local user joined room",this.context.connection.connectionId),this._states.set(this.context.connection.connectionId,new Ig(this.context.connection.connectionId,this.context)));for(const t of this.context.connection.usersInRoom())this._states.has(t)||this._states.set(t,new Ig(t,this.context))}}),a(this,"onLeftRoom",()=>{if(this.context.connection.connectionId&&!this._states.has(this.context.connection.connectionId)){const t=this._states.get(this.context.connection.connectionId);t?.dispose(),this._states.delete(this.context.connection.connectionId)}}),a(this,"onOtherUserJoinedRoom",t=>{const s=t.userId;this._states.has(s)||(lc&&console.log("XRSync: Remote user joined room",s),this._states.set(s,new Ig(s,this.context)))}),a(this,"onOtherUserLeftRoom",t=>{const s=t.userId;if(!this._states.has(s)){const o=this._states.get(s);o?.dispose(),this._states.delete(s)}}),a(this,"_states",new Map),this.context=e,this.context.connection.beginListen(ie.JoinedRoom,this.onJoinedRoom),this.context.connection.beginListen(ie.LeftRoom,this.onLeftRoom),this.context.connection.beginListen(ie.UserJoinedRoom,this.onOtherUserJoinedRoom),this.context.connection.beginListen(ie.UserLeftRoom,this.onOtherUserLeftRoom)}hasState(e){return e?this._states.has(e):!1}isTracking(e,t){if(!e)return;const s=this._states.get(e);if(!s)return;const o=s.controllerStates.find(r=>r.handedness===t);return o?.isTracking||!1}getDeviceType(e,t){if(!e)return;const s=this._states.get(e);if(!s)return;const o=s.controllerStates.find(r=>r.handedness===t);return o?.type||"unknown"}destroy(){this.context.connection.stopListen(ie.JoinedRoom,this.onJoinedRoom),this.context.connection.stopListen(ie.LeftRoom,this.onLeftRoom),this.context.connection.stopListen(ie.UserJoinedRoom,this.onOtherUserJoinedRoom),this.context.connection.stopListen(ie.UserLeftRoom,this.onOtherUserLeftRoom)}onUpdate(e){if(this.context.connection.isConnected&&this.context.connection.connectionId){const t=this._states.get(this.context.connection.connectionId);t?.update(e)}}onExitXR(e){if(this.context.connection.isConnected&&this.context.connection.connectionId){const t=this._states.get(this.context.connection.connectionId);t?.onExitXR(e)}}}class w_{constructor(){a(this,"_fadeToColorQuad"),a(this,"_fadeToColorMaterial"),a(this,"_requestedFadeValue",0),a(this,"_transitionPromise",null),a(this,"_transitionResolve",null),this._fadeToColorMaterial=new Me({color:0,transparent:!0,depthTest:!1,fog:!1,side:Pi}),this._fadeToColorQuad=new G(new Ns(10,10),this._fadeToColorMaterial)}dispose(){this._fadeToColorQuad.geometry.dispose(),this._fadeToColorMaterial.dispose()}update(e,t){const s=this._fadeToColorQuad,o=this._fadeToColorMaterial;s.parent!==e&&o.opacity>0?e.add(s):o.opacity===0&&s.removeFromParent(),s.layers.set(2),s.material=this._fadeToColorMaterial,s.position.z=-1,s.renderOrder=1/0;const r=this._requestedFadeValue;o.opacity=W.lerp(o.opacity,r,t/.03),Math.abs(o.opacity-r)<=.01&&this._transitionResolve&&(this._transitionResolve(),this._transitionResolve=null,this._transitionPromise=null,this._requestedFadeValue=0)}remove(){this._fadeToColorQuad.removeFromParent()}fadeTransition(){if(this._transitionPromise)return this._transitionPromise;this._requestedFadeValue=1;const e=new Promise(t=>{this._transitionResolve=t});return this._transitionPromise=e,e}}var Cr=(n=>(n[n.Quad=0]="Quad",n[n.Cube=1]="Cube",n[n.Sphere=2]="Sphere",n[n.Cylinder=3]="Cylinder",n[n.RoundedCube=10]="RoundedCube",n))(Cr||{}),$d,Lg;class wo{static createText(e,t){let s=null;const o=t?.font||dM(t?.familyFamily||null);o instanceof YP?s=dd(this,$d,Lg).call(this,e,o,t):s==null&&(s=new Vs);const r=t?.color||16777215,l=new G(s,t?.material??new bt({color:r}));return this.applyDefaultObjectOptions(l,t),o instanceof Promise?o.then(c=>{l.geometry=dd(this,$d,Lg).call(this,e,c,t),t!=null&&t.onGeometry&&t.onGeometry(l)}):t!=null&&t.onGeometry&&t.onGeometry(l),l}static createOccluder(e){const t=new Me({colorWrite:!1,depthWrite:!0,side:Pi});return this.createPrimitive(e,{material:t})}static createPrimitive(e,t){let s;const o=t?.color||16777215;switch(e){case"Quad":case 0:{const r=new Ns(1,1,1,1),l=t?.material??new bt({color:o});t!=null&&t.texture&&"map"in l&&(l.map=t.texture),s=new G(r,l),s.name="Quad"}break;case"Cube":case 1:{const r=new xa(1,1,1),l=t?.material??new bt({color:o});t!=null&&t.texture&&"map"in l&&(l.map=t.texture),s=new G(r,l),s.name="Cube"}break;case 10:case"RoundedCube":{const r=hM(1,1,1,.1,2),l=t?.material??new bt({color:o});t!=null&&t.texture&&"map"in l&&(l.map=t.texture),s=new G(r,l),s.name="RoundedCube"}break;case"Sphere":case 2:{const r=new pd(.5,16,16),l=t?.material??new bt({color:o});t!=null&&t.texture&&"map"in l&&(l.map=t.texture),s=new G(r,l),s.name="Sphere"}break;case"Cylinder":case 3:{const r=new Rv(.5,.5,1,32),l=t?.material??new bt({color:o});t!=null&&t.texture&&"map"in l&&(l.map=t.texture),s=new G(r,l),s.name="Cylinder"}break;case"ShaderBall":s=new mo,s.name="ShaderBall",uM(s,t);break}return this.applyDefaultObjectOptions(s,t),s}static createSprite(e){const t=new AC({color:16777215});e!=null&&e.texture&&"map"in t&&(t.map=e.texture);const s=new IC(t);return this.applyDefaultObjectOptions(s,e),s}static applyDefaultObjectOptions(e,t){e.receiveShadow=!0,e.castShadow=!0,t!=null&&t.name&&(e.name=t.name),t!=null&&t.position&&(Array.isArray(t.position)?e.position.set(t.position[0],t.position[1],t.position[2]):e.position.set(t.position.x,t.position.y,t.position.z)),t!=null&&t.rotation&&(Array.isArray(t.rotation)?e.rotation.set(t.rotation[0],t.rotation[1],t.rotation[2]):e.rotation.set(t.rotation.x,t.rotation.y,t.rotation.z)),t!=null&&t.scale&&(typeof t.scale=="number"?e.scale.set(t.scale,t.scale,t.scale):Array.isArray(t.scale)?e.scale.set(t.scale[0],t.scale[1],t.scale[2]):e.scale.set(t.scale.x,t.scale.y,t.scale.z)),t?.receiveShadow!=null&&(e.receiveShadow=t.receiveShadow),t?.castShadow!=null&&(e.castShadow=t.castShadow),t!=null&&t.parent&&t.parent.add(e)}}$d=new WeakSet,Lg=function(n,e,t){const s=t?.depth||.1;return new KP(n,{font:e,size:1,depth:s,height:s,bevelEnabled:t?.bevel||!1,bevelThickness:.01,bevelOffset:.01,bevelSize:.01})},Us(wo,$d);function hM(n,e,t,s,o){const r=new LC,l=1e-5,c=s-l;r.absarc(l,l,l,-Math.PI/2,-Math.PI,!0),r.absarc(l,e-c*2,l,Math.PI,Math.PI/2,!0),r.absarc(n-c*2,e-c*2,l,Math.PI/2,0,!0),r.absarc(n-c*2,l,l,0,-Math.PI/2,!0);const h=new jC(r,{bevelEnabled:!0,bevelSegments:o*2,steps:1,bevelSize:c,bevelThickness:s,curveSegments:o});return h.scale(1,1,1-s),h.center(),h.computeVertexNormals(),h}const Hd=new Map;function dM(n){let e="";switch(n){default:case"OpenSans":e="https://cdn.needle.tools/static/fonts/facetype/Open Sans_Regular_ascii.json";break;case"Helvetiker":e="https://raw.githubusercontent.com/mrdoob/three.js/master/examples/fonts/helvetiker_regular.typeface.json";break}if(Hd.has(e)){const o=Hd.get(e);if(o)return o}const t=new ZP,s=new Promise((o,r)=>{t.load(e,l=>{Hd.set(e,l),o(l)},void 0,r)});return Hd.set(e,s),s}let jg=!1,Dg=null;function uM(n,e){if(Dg===null){const t="https://cdn.needle.tools/static/models/shaderball.glb",s=new Rn,o=Nm(null);s.setDRACOLoader(o.dracoLoader),s.setKTX2Loader(o.ktx2Loader),jg=!0,Dg=s.loadAsync(t).then(r=>{const l=r.scene;return l.position.y-=.5,l}).catch(r=>(console.warn("Failed to load shaderball mesh: "+r.message),S_())).finally(()=>{jg=!1})}if(jg){const t=S_();t.name="ShaderBall-Placeholder";const s=t.children[0];s?.type==="Mesh"&&x_(s,e),n.add(t)}Dg.then(t=>{n.children.forEach(r=>{r.name==="ShaderBall-Placeholder"&&n.remove(r)});const s=t.clone(),o=s.children[0];o?.type==="Mesh"&&x_(o,e),n.add(s)})}function x_(n,e){var t;if(e?.color||e?.material||e?.texture){const s=e?.material??((t=n.material)==null?void 0:t.clone())??new bt;e.color&&"color"in s&&s.color instanceof oe&&s.color.set(e.color),e!=null&&e.texture&&"map"in s&&(s.map=e.texture),n.material=s}}function S_(){return new mo().add(wo.createPrimitive("Sphere",{material:new Me({transparent:!0,opacity:.1})}))}const Bg=class gC{constructor(e,t,s){a(this,"_session"),a(this,"_mode"),a(this,"_init"),a(this,"_renderer"),a(this,"_camera"),a(this,"_scene"),a(this,"onEnd",()=>{var o;(o=this._session)==null||o.removeEventListener("end",this.onEnd),this._renderer.setAnimationLoop(null),this._renderer.dispose(),this._scene.clear()}),a(this,"_lastTime",0),a(this,"onFrame",(o,r)=>{const l=o-this._lastTime;this.update(o,l),this._camera.parent!==this._scene&&this._scene.add(this._camera),this._renderer.render(this._scene,this._camera)}),a(this,"_objects",[]),this._mode=e,this._init=t,this._session=s,this._session.addEventListener("end",this.onEnd),this._renderer=new fr({alpha:!0}),this._renderer.setAnimationLoop(this.onFrame),this._renderer.xr.setSession(s),this._renderer.xr.enabled=!0,this._camera=new we,this._scene=new xi,this._scene.fog=new Tv(4473924,10,250),this._scene.add(this._camera),this.setupScene()}static get active(){return this._active}static async start(e,t){if(this._active)return console.error("Cannot start a new XR session while one is already active"),null;if(this._requestInFlight)return console.error("Cannot start a new XR session while a request is already in flight"),null;if("xr"in navigator&&navigator.xr){if(!t)return console.error("XRSessionInit must be provided"),null;this._requestInFlight=!0;const s=await navigator.xr.requestSession(e,t);return s.addEventListener("end",()=>{this._active=null}),this._requestInFlight?(this._requestInFlight=!1,this._active=new gC(e,t,s),this._active):(s.end(),null)}return null}static async handoff(){return this._active?this._active.handoff():null}static async stop(){this._requestInFlight=!1,this._active&&(await this._active.end(),await vs(100)),this._active=null}get isAR(){return this._mode==="immersive-ar"}end(){return this._session?this._session.end():Promise.resolve()}async handoff(){if(!this._session)throw new Error("Cannot handoff a session that has already ended");const e={session:this._session,mode:this._mode,init:this._init};return await this.onBeforeHandoff(),this.onEnd(),this._session=null,e}async onBeforeHandoff(){await vs(1e3),this._scene.clear()}setupScene(){this._scene.background=new oe(0),this._scene.add(new Mm(5,10,1118481,1118481));const e=new Rm(16777215,1);e.position.set(0,20,0),e.castShadow=!1,this._scene.add(e);const t=new Rm(16777215,1);t.position.set(0,-1,0),t.castShadow=!1,this._scene.add(t);const s=new Tm(16777215,1,100,1);s.position.set(0,2,0),s.castShadow=!1,s.distance=200,this._scene.add(s);const o=50;for(let r=0;r<100;r++){const l=new bt({color:2236962,metalness:1,roughness:.8});this.isAR&&(l.emissive=new oe(Math.random(),Math.random(),Math.random()),l.emissiveIntensity=Math.random());const c=W.random(0,1)>.5?Cr.Sphere:Cr.Cube,h=wo.createPrimitive(c,{material:l});h.position.x=W.random(-o,o),h.position.y=W.random(-2,o),h.position.z=W.random(-o,o),h.rotation.x=W.random(0,Math.PI*2),h.rotation.y=W.random(0,Math.PI*2),h.rotation.z=W.random(0,Math.PI*2),h.scale.multiplyScalar(.5+Math.random()*10);const d=h.position.distanceTo(this._camera.position)-h.scale.x;d<1&&h.position.multiplyScalar(1+1/d),this._objects.push(h),this._scene.add(h)}}update(e,t){const s=e*4e-4;for(let o=0;o<this._objects.length;o++){const r=this._objects[o];r.position.y+=Math.sin(s+o*.5)*.005,r.rotateY(.002)}}};a(Bg,"_active",null),a(Bg,"_requestInFlight",!1);let Gd=Bg;var cc;(n=>{const e=[];function t(){if(!(e!=null&&e.length))return!1;for(const r of e)r.exportAndOpen();return!0}n.exportAndOpen=t;function s(r){e.push(r)}n.registerExporter=s;function o(r){if(!e)return;const l=e.indexOf(r);l>=0&&e.splice(l,1)}n.unregisterExporter=o})(cc||(cc={}));const Je=C("debugwebxr"),C_=C("stats");let Fg=0;function pM(n){let e=null;const t=n;return t.getAROverlayContainer?e=t.getAROverlayContainer():e=n,e}mM();async function mM(){var n;if(C("debugasap")){let e=globalThis["needle:XRSession"];if(e instanceof Promise){delete globalThis["needle:XRSession"],pe.addContextCreatedCallback(async t=>{if(!e)return;wr(!0);const s=await e;if(s){const o=ne.getDefaultSessionInit("immersive-vr");ne.setSession("immersive-vr",s,o,t.context)}else console.error("NeedleXRSession: ASAP session was rejected");e=void 0});return}}if("xr"in navigator){if(/WebXRViewer\//i.test(navigator.userAgent)){console.warn("WebXRViewer does not support addEventListener");return}(n=navigator.xr)==null||n.addEventListener("sessiongranted",async()=>{wr(!0),console.log("Received Session Granted..."),await vs(100);const e=sessionStorage.getItem("needle_xr_session_mode"),t=sessionStorage.getItem("needle_xr_session_init")??null,s=t?JSON.parse(t):null;let o=null;if(P_()&&(await Gd.start(e||"immersive-vr",s||ne.getDefaultSessionInit("immersive-vr")),await yM(),o=await Gd.handoff()),o)ne.setSession(o.mode,o.session,o.init,J.Current);else if(e&&t){console.log("Session Granted: Restore last session");const r=JSON.parse(t);ne.start(e,r).catch(l=>console.warn(l))}else ne.start("immersive-vr").catch(r=>console.warn("Session Granted failed:",r))},{once:!0})}}function gM(n,e){sessionStorage.setItem("needle_xr_session_mode",n),sessionStorage.setItem("needle_xr_session_init",JSON.stringify(e))}function fM(){sessionStorage.removeItem("needle_xr_session_mode"),sessionStorage.removeItem("needle_xr_session_init")}const Ug=new Set;pe.registerCallback(me.ContextCreationStart,async n=>{Ug.add(n.context)}),pe.registerCallback(me.ContextCreated,async n=>{var e;Ug.delete(n.context);const t=((e=n.context)==null?void 0:e.domElement.getAttribute("autostart"))||null;vM(t)});function P_(){return Ug.size>0}function yM(){return new Promise(n=>{const e=Date.now(),t=setInterval(()=>{(!P_()||Date.now()-e>6e4)&&(clearInterval(t),n())},100)})}X.isDesktop()&&F()&&window.addEventListener("keydown",n=>{(n.key==="x"||n.key==="Escape")&&ne.active&&ne.stop()});function vM(n){if(n)switch(n?.toLowerCase()){case"ar":Ln.registerWaitForInteraction(()=>{ne.start("ar")});break}}const ai=class ba{constructor(e,t,s,o){a(this,"context"),a(this,"session"),a(this,"mode"),a(this,"controllers",[]),a(this,"_rigScale",1),a(this,"_lastRigScaleUpdate",-1),a(this,"_rigs",[]),a(this,"_viewerHitTestSource",null),a(this,"_defaultRig"),a(this,"_xr_scripts"),a(this,"_xr_update_scripts",[]),a(this,"_inactive_scripts",[]),a(this,"_controllerAdded"),a(this,"_controllerRemoved"),a(this,"_originalCameraWorldPosition"),a(this,"_originalCameraWorldRotation"),a(this,"_originalCameraWorldScale"),a(this,"_originalCameraParent"),a(this,"_mainCamera",null),a(this,"onRendererSessionSet",()=>{var c;this.running&&(this.context.renderer.xr.enabled=!0,this.context.renderer.xr.updateCamera(this.context.mainCamera),(c=this.context.mainCameraComponent)==null||c.applyClearFlags())}),a(this,"onInputSourceAdded",c=>{if(c.targetRayMode==="screen")return;let h=0;for(let u=0;u<this.session.inputSources.length;u++)if(this.session.inputSources[u]===c){h=u;break}if(this.controllers.find(u=>u.inputSource===c)){console.debug("Controller already exists for input source",h);return}else if(this._newControllers.find(u=>u.inputSource===c)){console.debug("Controller already registered for input source",h);return}const d=new Pg(this,c,h);this._newControllers.push(d)}),a(this,"_ended",!1),a(this,"_newControllers",[]),a(this,"onEnd",c=>{var h,d,u;if(this._ended)return;this._ended=!0,console.debug("XR Session ended"),fM(),this.onAfterRender(),this.revertCustomForward(),this._didStart=!1,this._previousCameraParent=null,_o(this.onBefore,Oe.LateUpdate);const p=this.context.pre_render_callbacks.indexOf(this.onBeforeRender);p>=0&&this.context.pre_render_callbacks.splice(p,1);const g=this.context.post_render_callbacks.indexOf(this.onAfterRender);g>=0&&this.context.post_render_callbacks.splice(g,1),this.context.xr=null,this.context.renderer.xr.enabled=!1,this.context.pre_update_oneshot_callbacks.push(()=>{var y,v;(y=this.context.mainCameraComponent)==null||y.applyClearFlags(),(v=this.context.mainCameraComponent)==null||v.applyClippingPlane()}),s_({session:this});for(const y of ba._xrEndListeners)y({xr:this});const f=[...this.controllers];for(let y=0;y<f.length;y++)this.disconnectInputSource(f[y].inputSource);this._newControllers.length=0,this.controllers.length=0;for(const y of this._xr_scripts)(h=y?.onLeaveXR)==null||h.call(y,{xr:this});(d=this.sync)==null||d.onExitXR(this),this.context.mainCamera&&((u=this._originalCameraParent)==null||u.add(this.context.mainCamera),this._originalCameraWorldPosition&<(this.context.mainCamera,this._originalCameraWorldPosition),this._originalCameraWorldRotation&&Yi(this.context.mainCamera,this._originalCameraWorldRotation),this._originalCameraWorldScale&&Ta(this.context.mainCamera,this._originalCameraWorldScale)),this.context.requestSizeUpdate(),this._defaultRig.gameObject.removeFromParent(),wr(!1)}),a(this,"_didStart",!1),a(this,"onBefore",c=>{var h,d,u,p,g,f,y,v;const b=c.xrFrame;if(!b)return;this.context.xr=this,this.context.mainCameraComponent&&this.context.mainCameraComponent!==this._mainCamera&&(this._mainCamera=this.context.mainCameraComponent),((h=this.rig)==null?void 0:h.isActive)==!1&&(Je&&console.warn("Latest rig is not active - trying to activate a different rig",this.rig),this.updateActiveXRRig()),this.rig&&(d=this._mainCamera)!=null&&d.gameObject&&((p=(u=this._mainCamera)==null?void 0:u.gameObject)==null?void 0:p.parent)!==this.rig.gameObject&&this.rig.gameObject.add((g=this._mainCamera)==null?void 0:g.gameObject),this.internalUpdateState(),this.applyCustomForward();const _={xr:this};if(this._didStart){if(this.context.new_scripts_xr.length>0){const w=[...this.context.new_scripts_xr];for(let x=0;x<w.length;x++){const k=this.context.new_scripts_xr[x];if(!k||k.destroyed||((f=k.supportsXR)==null?void 0:f.call(k,this.mode))==!1){this.context.new_scripts_xr.splice(x,1);continue}if(!k.activeAndEnabled){this.context.new_scripts_xr.splice(x,1),this.markInactive(k);continue}if(this.addScript(k)){this.invokeCallback_EnterXR(k);for(const M of this.controllers)this.invokeCallback_ControllerAdded(k,M)}}}}else{if(this._didStart=!0,this.mode==="immersive-vr"){const x=si(this.context.scene.children);if(x){const k=x.getSize(q());if(k.length()>0){const M=this._defaultRig.gameObject;M.position.set(x.min.x+k.x*.5,x.min.y,x.max.z+k.z*.5+1.5);const T=x.getCenter(q());T.y=M.position.y,M.lookAt(T)}}}i_({session:this}),Sr();for(const x of ba._xrStartListeners)x(_);const w=[...this._xr_scripts];Je&&console.log("NeedleXRSession start, handle scripts:",w);for(const x of w){if(x.destroyed){this._script_to_remove.push(x);continue}if(!x.activeAndEnabled){this.markInactive(x);continue}this.invokeCallback_EnterXR(x);for(const k of this.controllers)this.invokeCallback_ControllerAdded(x,k)}}this.syncCameraCullingMask();for(const w of this.controllers)w.onUpdate(b);if(this._newControllers.length>0){const w=[...this._newControllers];this._newControllers.length=0;for(const x of w){if(!x.connected){console.warn("New controller is not connected",x);continue}this.controllers.push(x);for(const k of this._xr_scripts){if(k.destroyed){this._script_to_remove.push(k);continue}k.activeAndEnabled!==!1&&this.invokeCallback_ControllerAdded(k,x)}}this.controllers.sort((x,k)=>x.index-k.index)}Je&&this.context.time.frame%30===0&&this.controllers.length<=0&&this.session.inputSources.length>0&&(wr(!0),console.error("XRControllers are not added but inputSources are present"));for(const w of this._xr_update_scripts){if(w.destroyed===!0){this._script_to_remove.push(w);continue}if(w.activeAndEnabled===!1){this.markInactive(w);continue}w.onUpdateXR&&w.onUpdateXR(_)}if(this.handleInactiveScripts(),this._script_to_remove.length>0){const w=[...new Set(this._script_to_remove)];this._script_to_remove.length=0;for(const x of w)!x.destroyed&&this.running&&((y=x.onLeaveXR)==null||y.call(x,_)),this.removeScript(x)}(v=this.sync)==null||v.onUpdate(this),this.onRenderDebug()}),a(this,"onBeforeRender",()=>{this.context.mainCamera&&this.updateFade(this.context.mainCamera)}),a(this,"onAfterRender",()=>{if(this.onUpdateFade_PostRender(),X.isDesktop()||!this._renderOnceOnDevice){const c=this.context.renderer;if(c.xr.isPresenting&&this.context.mainCamera){this._renderOnceOnDevice=!0;const h=c.xr.enabled,d=c.getRenderTarget(),u=this.context.scene.background;c.xr.enabled=!1,c.setRenderTarget(null),this.isPassThrough&&(this.context.scene.background=null),this.context.composer?this.context.composer.render(this.context.time.deltaTime):c.render(this.context.scene,this.context.mainCamera),c.xr.enabled=h,c.setRenderTarget(d),this.context.scene.background=u}}}),a(this,"_script_to_remove",[]),a(this,"_camera"),a(this,"_cameraRenderParent",new E().rotateY(Math.PI)),a(this,"_previousCameraParent"),a(this,"_customforward",!0),a(this,"originalCameraNearPlane"),a(this,"_viewerPose"),a(this,"_transformOrientation",new V),a(this,"_transformPosition",new S),a(this,"_transition");var r,l;gM(e,o.init),this.session=t,this.mode=e,this.context=s,(Je||C("console"))&&wr(!0),this._xr_scripts=[...o.scripts],this._xr_update_scripts=this._xr_scripts.filter(c=>typeof c.onUpdateXR=="function"),this._controllerAdded=o.controller_added,this._controllerRemoved=o.controller_removed,jn(this.onBefore,Oe.LateUpdate),this.context.pre_render_callbacks.push(this.onBeforeRender),this.context.post_render_callbacks.push(this.onAfterRender),((r=o.init.optionalFeatures)!=null&&r.includes("hit-test")||(l=o.init.requiredFeatures)!=null&&l.includes("hit-test"))&&t.requestReferenceSpace("viewer").then(c=>{var h,d;return(d=(h=t.requestHitTestSource)==null?void 0:h.call(t,{space:c}))==null?void 0:d.then(u=>this._viewerHitTestSource=u).catch(u=>console.error(u))}).catch(c=>console.error(c)),this.context.mainCamera&&(this._originalCameraWorldPosition=ee(this.context.mainCamera,new S),this._originalCameraWorldRotation=Se(this.context.mainCamera,new V),this._originalCameraWorldScale=Ge(this.context.mainCamera,new S),this._originalCameraParent=this.context.mainCamera.parent),this._defaultRig=new Zk,this.context.scene.add(this._defaultRig.gameObject),this.addRig(this._defaultRig);for(let c=0;c<t.inputSources.length;c++){const h=t.inputSources[c];if(!h.handedness){console.warn("Input source in xr session has no handedness - ignoring",c);continue}this.onInputSourceAdded(h)}this.session.addEventListener("end",this.onEnd),this.session.addEventListener("inputsourceschange",c=>{for(const h of c.removed)this.disconnectInputSource(h);for(const h of c.added)this.onInputSourceAdded(h)}),this.context.xr=this,this.context.renderer.xr.setSession(this.session).then(this.onRendererSessionSet),"controllerAutoUpdate"in this.context.renderer.xr?(console.debug("Disabling three.js controllerAutoUpdate"),this.context.renderer.xr.controllerAutoUpdate=!1):Je&&console.warn("controllerAutoUpdate is not available in three.js - cannot disable it")}static getXRSync(e){return this._sync||(this._sync=new __(e)),this._sync}static get currentSessionRequest(){return this._currentSessionRequestMode}static get active(){return this._activeSession}static get activeMode(){var e;return((e=this._activeSession)==null?void 0:e.mode)??null}static get xrSystem(){return"xr"in navigator?navigator.xr:void 0}static isXRSupported(){return Promise.all([this.isVRSupported(),this.isARSupported()]).then(e=>e.some(t=>t)).catch(()=>!1)}static isVRSupported(){return this.isSessionSupported("immersive-vr")}static isARSupported(){return this.isSessionSupported("immersive-ar")}static isSessionSupported(e){var t;return((t=this.xrSystem)==null?void 0:t.isSessionSupported(e).catch(s=>(Je&&console.error(s),!1)))??Promise.resolve(!1)}static onSessionRequestStart(e){this._sessionRequestStartListeners.push(e)}static offSessionRequestStart(e){const t=this._sessionRequestStartListeners.indexOf(e);t>=0&&this._sessionRequestStartListeners.splice(t,1)}static onSessionRequestEnd(e){this._sessionRequestEndListeners.push(e)}static offSessionRequestEnd(e){const t=this._sessionRequestEndListeners.indexOf(e);t>=0&&this._sessionRequestEndListeners.splice(t,1)}static onXRSessionStart(e){this._xrStartListeners.push(e)}static offXRSessionStart(e){const t=this._xrStartListeners.indexOf(e);t>=0&&this._xrStartListeners.splice(t,1)}static onXRSessionEnd(e){this._xrEndListeners.push(e)}static offXRSessionEnd(e){const t=this._xrEndListeners.indexOf(e);t>=0&&this._xrEndListeners.splice(t,1)}static onControllerAdded(e){this._controllerAddedListeners.push(e)}static offControllerAdded(e){const t=this._controllerAddedListeners.indexOf(e);t>=0&&this._controllerAddedListeners.splice(t,1)}static onControllerRemoved(e){this._controllerRemovedListeners.push(e)}static offControllerRemoved(e){const t=this._controllerRemovedListeners.indexOf(e);t>=0&&this._controllerRemovedListeners.splice(t,1)}static offerSession(e,t,s){return"xr"in navigator&&navigator.xr&&"offerSession"in navigator.xr?(typeof navigator.xr.offerSession=="function"&&(console.log("WebXR offerSession is available - requesting mode: "+e),t=="default"&&(t=this.getDefaultSessionInit(e)),navigator.xr.offerSession(e,{...t}).then(o=>ba.setSession(e,o,t,s)).catch(o=>{console.log("XRSession offer rejected (perhaps because another call to offerSession was made or a call to requestSession was made)")})),!0):!1}static getDefaultSessionInit(e){switch(e){case"immersive-ar":const t=["anchors","local-floor","layers","dom-overlay","hit-test","unbounded"];return X.isVisionOS()||t.push("hand-tracking"),{optionalFeatures:t};case"immersive-vr":const s=["local-floor","bounded-floor","high-fixed-foveation-level","layers"];return X.isVisionOS()||s.push("hand-tracking"),{optionalFeatures:s};default:return console.warn("No default session init for mode",e),{}}}static async start(e,t,s){var o,r,l,c;if(X.isiOS()){if(e==="ar")if(await this.isARSupported())e="immersive-ar";else return cc.exportAndOpen(),null}else e=="ar"&&(e="immersive-ar");if(F()&&C("debugxrpreroom"))return console.warn("Debug: Starting temporary XR session"),await Gd.start(e,t||ba.getDefaultSessionInit(e)),null;if(this._currentSessionRequest)return console.warn("A XRSession is already being requested"),(Je||F())&&be("A XRSession is already being requested"),this._currentSessionRequest.then(()=>this._activeSession);if(this._activeSession)return console.error("A XRSession is already running"),this._activeSession;if(s||(s=J.Current),s||(s=pe.All[0]),!s)throw new Error("No Needle Engine Context found");switch(t||(t={}),e){case"immersive-ar":{if(await((o=this.xrSystem)==null?void 0:o.isSessionSupported("immersive-ar"))!==!0)return console.error(e+" is not supported by this browser."),null;const u=this.getDefaultSessionInit(e),p=pM(s.domElement);p&&!X.isQuest()&&(u.domOverlay={root:p},u.optionalFeatures.push("dom-overlay")),t={...u,...t}}break;case"immersive-vr":{if(await((r=this.xrSystem)==null?void 0:r.isSessionSupported("immersive-vr"))!==!0)return console.error(e+" is not supported by this browser."),null;t={...this.getDefaultSessionInit(e),...t}}break;default:console.warn("No default session init for mode",e);break}t.optionalFeatures??(t.optionalFeatures=[]),t.requiredFeatures??(t.requiredFeatures=[]),await Gd.stop();const h=e=="immersive-ar"?s.scripts_immersive_ar:s.scripts_immersive_vr;Je?console.log(`%cRequesting ${e} session`,"font-weight:bold;",t,h):console.log(`%cRequesting ${e} session`,"font-weight:bold;");for(const u of h)u.onBeforeXR&&u.onBeforeXR(e,t);for(const u of this._sessionRequestStartListeners)u({mode:e,init:t});Je&&De("Requesting "+e+" session ("+Date.now()+")"),this._currentSessionRequest=(l=navigator.xr)==null?void 0:l.requestSession(e,t),this._currentSessionRequestMode=e;const d=await((c=this._currentSessionRequest)==null?void 0:c.catch(u=>{console.error(u,"Code: "+u.code),u.code===9&&be("Make sure your device has the required permissions (e.g. camera access)"),console.log("If the specified XR configuration is not supported (e.g. entering AR doesnt work) - make sure you access the website on a secure connection (HTTPS) and your device has the required permissions (e.g. camera access)"),location.protocol==="http:"&&be("XR requires a secure connection (HTTPS)")}));this._currentSessionRequest=void 0,this._currentSessionRequestMode=null;for(const u of this._sessionRequestEndListeners)u({mode:e,init:t,newSession:d||null});return d?this.setSession(e,d,t,s):(console.warn("XR Session request was rejected"),null)}static setSession(e,t,s,o){if(this._activeSession)return console.error("A XRSession is already running"),this._activeSession;const r=e=="immersive-ar"?o.scripts_immersive_ar:o.scripts_immersive_vr;return this._activeSession=new ba(e,t,o,{scripts:r,controller_added:this._controllerAddedListeners,controller_removed:this._controllerRemovedListeners,init:s}),t.addEventListener("end",this.onEnd),Je?console.log(`%cStarted ${e} session`,"font-weight:bold;",r):console.log(`%cStarted ${e} session`,"font-weight:bold;"),this._activeSession}static stop(){const e=this._activeSession;e&&(e[this.$_stop_request]===void 0?(Je&&console.log("[NeedleXRSession] Stopping XR Session... (new)"),e[this.$_stop_request]=setTimeout(()=>{e.end()})):Je&&console.warn("[NeedleXRSession] XR Session stop already requested"))}get sync(){return ba._sync}get running(){return!this._ended&&this.session!=null}get interactionMode(){return this.session.interactionMode}get visibilityState(){return this.session.visibilityState}get isVisibleBlurred(){return this.session.visibilityState==="visible-blurred"}get isSystemKeyboardSupported(){return this.session.isSystemKeyboardSupported}get environmentBlendMode(){return this.session.environmentBlendMode}get frame(){return this.context.xrFrame}get leftController(){return this.controllers.find(e=>e.side==="left")}get rightController(){return this.controllers.find(e=>e.side==="right")}getController(e){return typeof e=="number"?this.controllers[e]||null:this.controllers.find(t=>t.side===e)||null}get isPassThrough(){return!!(this.environmentBlendMode!=="opaque"&&this.interactionMode==="world-space"||this.mode==="immersive-ar"&&this.environmentBlendMode!=="opaque"&&this.controllers.some(e=>e.inputSource.targetRayMode==="tracked-pointer")||F()&&X.isDesktop()&&this.mode==="immersive-ar")}get isAR(){return this.mode==="immersive-ar"}get isVR(){return this.mode==="immersive-vr"}get isScreenBasedAR(){return this.isAR&&!this.isPassThrough}get posePosition(){return this._transformPosition}get poseOrientation(){return this._transformOrientation}get referenceSpace(){return this.context.renderer.xr.getReferenceSpace()}get viewerPose(){return this._viewerPose}get isTrackingImages(){if(this.frame&&"getImageTrackingResults"in this.frame&&typeof this.frame.getImageTrackingResults=="function")try{const e=this.frame.getImageTrackingResults();for(const t of e)if(t.trackingState==="tracked")return!0}catch{return!1}return!1}get rig(){const e=this._rigs[0]??null;return e!=null&&e.gameObject&&Er(e.gameObject)||e?.isActive===!1?(this.updateActiveXRRig(),this._rigs[0]??null):e}get rigScale(){return this._rigs[0]?(this._lastRigScaleUpdate!==this.context.time.frame&&(this._lastRigScaleUpdate=this.context.time.frame,this._rigScale=this._rigs[0].gameObject.worldScale.x),this._rigScale):1}addRig(e){this._rigs.indexOf(e)>=0||(e.priority===void 0&&(e.priority=0),this._rigs.push(e),this.updateActiveXRRig())}removeRig(e){const t=this._rigs.indexOf(e);t!==-1&&(this._rigs.splice(t,1),this.updateActiveXRRig())}setRigActive(e){const t=this._rigs.indexOf(e),s=this._rigs[0];this._rigs.splice(t,1),this._rigs.unshift(e),e.priority=s?.priority??0,this.updateActiveXRRig()}getUserOffsetInRig(){var e;const t=(e=this.context.mainCamera)==null?void 0:e.position;if(!t||!this.rig)return q(0,0,0);const s=q(t);return s.x*=-1,s.z*=-1,s.applyQuaternion(bs(this.rig.gameObject.quaternion)),s}updateActiveXRRig(){const e=this._rigs[0]??null;this._defaultRig.gameObject.parent!==this.context.scene&&this.context.scene.add(this._defaultRig.gameObject),this._defaultRig.gameObject.visible=!0,this._rigs.includes(this._defaultRig)||this._rigs.push(this._defaultRig);let t=this._rigs[0];t&&t.priority===void 0&&(t.priority=0);for(let s=1;s<this._rigs.length;s++){const o=this._rigs[s];if(o.isActive){if(Er(o.gameObject)){this._rigs.splice(s,1),s--;continue}(!t||t.isActive===!1||o.priority!==void 0&&o.priority>t.priority)&&(t=o)}}if(e!==t){const s=this._rigs.indexOf(t);s>=0&&this._rigs.splice(s,1),this._rigs.unshift(t)}Je&&(e===t?console.log("Updated Active XR Rig:",t,"prev:",e):console.log("Updated Active XRRig:",t," (the same as before)"))}getHitTest(e){if(e)return this.getControllerHitTest(e);if(!this._viewerHitTestSource)return null;const t=this._viewerHitTestSource,s=this.frame.getHitTestResults(t);if(s.length>0){const o=s[0];return this.convertHitTestResult(o)}return null}getControllerHitTest(e){const t=e.getHitTestSource();if(!t)return null;const s=this.frame.getHitTestResultsForTransientInput(t);for(const o of s)if(o.inputSource===e.inputSource)for(const r of o.results)return this.convertHitTestResult(r);return null}convertHitTestResult(e){const t=this.context.renderer.xr.getReferenceSpace(),s=t&&e.getPose(t);if(s){const o=q(s.transform.position),r=bs(s.transform.orientation),l=this.context.mainCamera;if(l?.parent!==this._cameraRenderParent&&o.applyMatrix4(La),l!=null&&l.parent){o.applyMatrix4(l.parent.matrixWorld),r.multiply(Zi);const c=Se(l.parent);c.premultiply(Zi),r.premultiply(c)}return{hit:e,position:o,quaternion:r}}return null}convertSpace(e){const t=q(e.position);t.applyMatrix4(La);const s=bs(e.orientation);return s.premultiply(Zi),{position:t,quaternion:s}}disconnectInputSource(e){const t=(s,o,r)=>{if(s.inputSource===e){Je&&console.log("Disconnecting controller",s.index),this.controllers.splice(r,1),this.invokeControllerEvent(s,this._controllerRemoved,"removed");const l={xr:this,controller:s,change:"removed"};for(const c of this._xr_scripts)c.onXRControllerRemoved&&c.onXRControllerRemoved(l);s.onDisconnected()}};for(let s=this.controllers.length-1;s>=0;s--){const o=this.controllers[s];t(o,this.controllers,s)}for(let s=this._newControllers.length-1;s>=0;s--){const o=this._newControllers[s];t(o,this._newControllers,s)}}end(){this._ended||this.session.end().catch(e=>console.warn(e))}onRenderDebug(){if(Je)for(const e of this.controllers)e.onRenderDebug();if((Je||C_)&&this.rig&&(Fg++,Fg>=20)){const e=this.rig.gameObject.worldPosition,t=this.rig.gameObject.worldForward;e.add(t.multiplyScalar(1.5));const s=this.rig.gameObject.worldUp;e.add(s.multiplyScalar(2.5));let o="";if(o+=`${this.context.time.smoothedFps.toFixed(0)} FPS`,o+=`, calls: ${this.context.renderer.info.render.calls}, tris: ${this.context.renderer.info.render.triangles.toLocaleString()}`,Je||C_)for(const r of this.controllers)o+=`
|
|
166
|
-
${r.hand?"hand":"ctrl"} ${r.inputSource.handedness}[${r.index}] con:${r.connected} tr:${r.isTracking} hts:${r.hasHitTestSource?"yes":"no"}`;Fg=0,$.DrawLabel(e,o,void 0,1/60*20)}}addScript(e){return this._xr_scripts.includes(e)?!1:(Je&&console.log("Register new XRScript",e),this._xr_scripts.push(e),typeof e.onUpdateXR=="function"&&this._xr_update_scripts.push(e),!0)}markInactive(e){if(!(this._inactive_scripts.indexOf(e)>=0)){this.removeScript(e,!1),this._inactive_scripts.push(e);for(const t of this.controllers)this.invokeCallback_ControllerRemoved(e,t);this.invokeCallback_LeaveXR(e)}}handleInactiveScripts(){if(this._inactive_scripts.length>0)for(let e=this._inactive_scripts.length-1;e>=0;e--){const t=this._inactive_scripts[e];if(t.activeAndEnabled){this._inactive_scripts.splice(e,1),this.addScript(t),this.invokeCallback_EnterXR(t);for(const s of this.controllers)this.invokeCallback_ControllerAdded(t,s)}}}removeScript(e,t=!0){Je&&console.log("Remove XRScript",e);const s=this._xr_scripts.indexOf(e);s>=0&&this._xr_scripts.splice(s,1);const o=this._xr_update_scripts.indexOf(e);if(o>=0&&this._xr_update_scripts.splice(o,1),t){const r=this._inactive_scripts.indexOf(e);r>=0&&this._inactive_scripts.splice(r,1)}}invokeCallback_EnterXR(e){e.onEnterXR&&e.onEnterXR({xr:this})}invokeCallback_ControllerAdded(e,t){e.onXRControllerAdded&&e.onXRControllerAdded({xr:this,controller:t,change:"added"})}invokeCallback_ControllerRemoved(e,t){e.onXRControllerRemoved&&e.onXRControllerRemoved({xr:this,controller:t,change:"removed"})}invokeCallback_LeaveXR(e){e.onLeaveXR&&!e.destroyed&&e.onLeaveXR({xr:this})}syncCameraCullingMask(){var e;const t=this.context.xrCamera,s=(e=this.context.mainCameraComponent)==null?void 0:e.cullingMask;if(t&&s!==void 0){for(const o of t.cameras)o.layers.mask=s;t.layers.mask=s}else if(t){for(const o of t.cameras)o.layers.enableAll();t.layers.enableAll()}}invokeControllerEvent(e,t,s){for(let o=t.length-1;o>=0;o--){const r=t[o];if(r)try{r({xr:this,controller:e,change:s})}catch(l){console.error(l)}}}applyCustomForward(){var e;if(this.context.mainCamera&&this._customforward){this._camera=this.context.mainCamera,this._camera.parent!==this._cameraRenderParent&&(this._previousCameraParent=this._camera.parent,(e=this._previousCameraParent)==null||e.add(this._cameraRenderParent)),this._cameraRenderParent.name="XR Camera Render Parent",this._cameraRenderParent.add(this._camera);let t=.02;if(this.rig){const s=Ge(this.rig.gameObject);t*=s.x}this._camera instanceof we&&this._camera.near>t&&(this.originalCameraNearPlane=this._camera.near,this._camera.near=t)}}revertCustomForward(){this._camera&&this._previousCameraParent&&this._previousCameraParent.add(this._camera),this._previousCameraParent=null,this._camera instanceof we&&this.originalCameraNearPlane!=null&&(this._camera.near=this.originalCameraNearPlane)}internalUpdateState(){const e=this.context.renderer.xr.getReferenceSpace();if(!e){this._viewerPose=void 0;return}if(this._viewerPose=this.frame.getViewerPose(e),this._viewerPose){const t=this._viewerPose.transform;this._transformPosition.set(t.position.x,t.position.y,t.position.z),this._transformOrientation.set(t.orientation.x,t.orientation.y,t.orientation.z,t.orientation.w)}}get transition(){return this._transition||(this._transition=new w_),this._transition}fadeTransition(){return this._transition||(this._transition=new w_),this._transition.fadeTransition()}updateFade(e){this._transition&&e instanceof we&&this._transition.update(e,this.context.time.deltaTime)}onUpdateFade_PostRender(){var e;(e=this._transition)==null||e.remove()}};a(ai,"_sync",null),a(ai,"_currentSessionRequestMode",null),a(ai,"_currentSessionRequest"),a(ai,"_activeSession"),a(ai,"_sessionRequestStartListeners",[]),a(ai,"_sessionRequestEndListeners",[]),a(ai,"_xrStartListeners",[]),a(ai,"_xrEndListeners",[]),a(ai,"_controllerAddedListeners",[]),a(ai,"_controllerRemovedListeners",[]),a(ai,"$_stop_request",Symbol()),a(ai,"onEnd",()=>{Je&&console.log("XR Session ended"),ai._activeSession=null});let ne=ai;const zg=C("debugwebxr");class O_{static tryFindAvatarObjects(e,t,s){if(s.head&&s.leftHand&&s.rightHand)return;const o=e.name.toLocaleLowerCase();!s.head&&o.includes("head")&&(zg&&console.log("FOUND AVATAR HEAD",e.name),s.head=new ce("",t,e)),o.includes("hand")&&(!s.leftHand&&o.includes("left")&&(zg&&console.log("FOUND AVATAR LEFT HAND",e.name),s.leftHand=new ce("",t,e)),!s.rightHand&&o.includes("right")&&(zg&&console.log("FOUND AVATAR RIGHT HAND",e.name),s.rightHand=new ce("",t,e)));for(let r=0;r<e.children.length;r++){if(s.head&&s.leftHand&&s.rightHand)return;const l=e.children[r];this.tryFindAvatarObjects(l,t,s)}}}const Bt=new S,k_=new S,M_=new V,bM=C("debuggizmos"),Cs=8947848,Ng=32,Wg=class Bs{constructor(){}static isGizmo(e){return e[$g]!==void 0}static setVisible(e){for(const t of Ee.timedObjectsBuffer)t.visible=e}static DrawLabel(e,t,s=.05,o=0,r,l,c){var h;if(!Bs.enabled)return null;r||(r=Cs);const d=((h=ne.active)==null?void 0:h.rigScale)??1,u=Ee.getTextLabel(o,t,s*d,r,l);return c instanceof E&&c.add(u),u.position.x=e.x,u.position.y=e.y,u.position.z=e.z,u}static DrawRay(e,t,s=Cs,o=0,r=!0){if(!Bs.enabled)return;const l=Ee.getLine(o),c=l.geometry.getAttribute("position");c.setXYZ(0,e.x,e.y,e.z),Bt.set(t.x,t.y,t.z).multiplyScalar(999999999),c.setXYZ(1,e.x+Bt.x,e.y+Bt.y,e.z+Bt.z),c.needsUpdate=!0,l.material.color.set(s),l.material.depthTest=r,l.material.depthWrite=!1}static DrawDirection(e,t,s=Cs,o=0,r=!0,l=1){if(!Bs.enabled)return;const c=Ee.getLine(o),h=c.geometry.getAttribute("position");h.setXYZ(0,e.x,e.y,e.z),t.w!==void 0?(Bt.set(0,0,-l),M_.set(t.x,t.y,t.z,t.w),Bt.applyQuaternion(M_)):(Bt.set(t.x,t.y,t.z),Bt.multiplyScalar(l)),h.setXYZ(1,e.x+Bt.x,e.y+Bt.y,e.z+Bt.z),h.needsUpdate=!0,c.material.color.set(s),c.material.depthTest=r,c.material.depthWrite=!1}static DrawLine(e,t,s=Cs,o=0,r=!0){if(!Bs.enabled)return;const l=Ee.getLine(o),c=l.geometry.getAttribute("position");c.setXYZ(0,e.x,e.y,e.z),c.setXYZ(1,t.x,t.y,t.z),c.needsUpdate=!0,l.material.color.set(s),l.material.depthTest=r,l.material.depthWrite=!1,l.material.fog=!1}static DrawCircle(e,t,s,o=Cs,r=0,l=!0){if(!Bs.enabled)return;const c=Ee.getCircle(r);c.position.set(e.x,e.y,e.z),c.scale.set(s,s,s),c.quaternion.setFromUnitVectors(this._up,Bt.set(t.x,t.y,t.z).normalize()),c.material.color.set(o),c.material.depthTest=l,c.material.depthWrite=!1,c.material.fog=!1}static DrawWireSphere(e,t,s=Cs,o=0,r=!0){if(!Bs.enabled)return;const l=Ee.getSphere(t,o,!0);br(l,e.x,e.y,e.z),l.material.color.set(s),l.material.depthTest=r,l.material.depthWrite=!1,l.material.fog=!1}static DrawSphere(e,t,s=Cs,o=0,r=!0){if(!Bs.enabled)return;const l=Ee.getSphere(t,o,!1);br(l,e.x,e.y,e.z),l.material.color.set(s),l.material.depthTest=r,l.material.depthWrite=!1}static DrawWireBox(e,t,s=Cs,o=0,r=!0){if(!Bs.enabled)return;const l=Ee.getBox(o);l.position.set(e.x,e.y,e.z),l.scale.set(t.x,t.y,t.z),l.material.color.set(s),l.material.depthTest=r,l.material.wireframe=!0,l.material.depthWrite=!1,l.material.fog=!1}static DrawWireBox3(e,t=Cs,s=0,o=!0){if(!Bs.enabled)return;const r=Ee.getBox(s);r.position.copy(e.getCenter(Bt)),r.scale.copy(e.getSize(Bt)),r.material.color.set(t),r.material.depthTest=o,r.material.wireframe=!0,r.material.depthWrite=!1,r.material.fog=!1}static DrawArrow(e,t,s=Cs,o=0,r=!0,l=!1){if(!Bs.enabled)return;const c=Ee.getArrowHead(o);c.position.set(t.x,t.y,t.z),c.quaternion.setFromUnitVectors(this._up.set(0,1,0),Bt.set(t.x,t.y,t.z).sub(k_.set(e.x,e.y,e.z)).normalize());const h=Bt.set(t.x,t.y,t.z).sub(k_.set(e.x,e.y,e.z)).length()*.1;c.scale.set(h,h,h),c.material.color.set(s),c.material.depthTest=r,c.material.wireframe=l,this.DrawLine(e,t,s,o,r)}static DrawWireMesh(e){const t=Ee.getMesh(e.duration??0);"mesh"in e?(t.geometry=e.mesh.geometry,t.matrix.copy(e.mesh.matrixWorld)):(t.geometry=e.geometry,t.matrix.copy(e.matrix)),t.matrixAutoUpdate=!1,t.matrixWorldAutoUpdate=!1,t.material.color.set(e.color??Cs),t.material.depthTest=e.depthTest??!0,t.material.wireframe=!0}};a(Wg,"enabled",!0),a(Wg,"_up",new S(0,1,0));let $=Wg;const _M=new xa(1,1,1);function Vg(n=null){const e=new oe(n??14540253),t=new DC(_M);return new Ev(t,new Av({color:e}))}const $g=Symbol("GizmoCache");class Ee{static ensureFont(){let e=Re.FontLibrary.getFontFamily(this.familyName);if(!e){e=Re.FontLibrary.addFontFamily(this.familyName);const t=e.addVariant("normal","normal","https://uploads.needle.tools/include/font-msdf.json","https://uploads.needle.tools/include/font.png");t?.addEventListener("ready",()=>{Re.update()})}}static getTextLabel(e,t,s,o,r){this.ensureFont();let l=this.textLabelCache.pop(),c=1;r&&typeof r=="string"&&r?.length>=8&&r.startsWith("#")?(c=parseInt(r.substring(7),16)/255,r=r.substring(0,7),bM&&console.log(r,c)):typeof r=="object"&&r.a!==void 0&&(c=r.a);const h={boxSizing:"border-box",fontFamily:this.familyName,width:"auto",fontSize:s,color:o,lineHeight:1,backgroundColor:r??void 0,backgroundOpacity:c,textContent:t,borderRadius:.5*s,padding:.8*s,whiteSpace:"pre",offset:.05*s};if(l)l.set(h);else{l=new Jv(h);const d=this,u=l;u.setText=function(p){this.set({textContent:p}),d.tmuiNeedsUpdate=!0}}return this.tmuiNeedsUpdate=!0,this.registerTimedObject(J.Current,l,e,this.textLabelCache),l}static getBox(e){let t=this.boxesCache.pop();if(!t){const s=new xa(1,1,1);t=new G(s)}return this.registerTimedObject(J.Current,t,e,this.boxesCache),t}static getLine(e){let t=this.linesCache.pop();if(!t){t=new $l;let s=t.geometry.getAttribute("position");s||(s=new _t(new Float32Array(6),3),t.geometry.setAttribute("position",s))}return t.frustumCulled=!1,this.registerTimedObject(J.Current,t,e,this.linesCache),t}static getCircle(e){let t=this.circlesCache.pop();if(!t){t=new $l;let s=t.geometry.getAttribute("position");if(!s){s=new _t(new Float32Array(Ng*3),3),t.geometry.setAttribute("position",s);const o=q(0,1,0),r=q(0,0,1),l=q(r);l.cross(o).normalize();const c=q(l),h=Math.PI*2/(Ng-1);for(let d=0;d<Ng+1;d++){const u=h*d;o.copy(c).multiplyScalar(Math.cos(u)*1),l.copy(r).multiplyScalar(Math.sin(u)*1);const p=o.add(l);s.setXYZ(d,p.x,p.y,p.z)}}}return t.frustumCulled=!1,this.registerTimedObject(J.Current,t,e,this.circlesCache),t}static getSphere(e,t,s){let o=this.spheresCache.pop();return o||(o=new G(new pd(1,8,8))),o.scale.set(e,e,e),o.material.wireframe=s,this.registerTimedObject(J.Current,o,t,this.spheresCache),o}static getArrowHead(e){let t=this.arrowHeadsCache.pop();return t||(t=new G(new Rv(0,.5,1,8))),this.registerTimedObject(J.Current,t,e,this.arrowHeadsCache),t}static getMesh(e){let t=this.mesh.pop();return t||(t=new G,t.material=new Me),this.registerTimedObject(J.Current,t,e,this.mesh),t}static registerTimedObject(e,t,s,o){if(!e){console.error("No Needle Engine context available. Did you call a Gizmos function in global scope?");return}const r=this.contextBeforeRenderCallbacks.get(e),l=this.contextPostRenderCallbacks.get(e);if(r){if(e.pre_render_callbacks[e.pre_render_callbacks.length-1]!==r){const c=e.pre_render_callbacks.indexOf(r);c>=0&&e.pre_render_callbacks.splice(c,1),e.pre_render_callbacks.push(r)}}else{const c=()=>{this.onBeforeRender(e,this.timedObjectsBuffer)};this.contextBeforeRenderCallbacks.set(e,c),e.pre_render_callbacks.push(c)}if(l){if(e.post_render_callbacks[e.post_render_callbacks.length-1]!==l){const c=e.post_render_callbacks.indexOf(l);c>=0&&e.post_render_callbacks.splice(c,1),e.post_render_callbacks.push(l)}}else{const c=()=>{this.onPostRender(e,this.timedObjectsBuffer,this.timesBuffer)};this.contextPostRenderCallbacks.set(e,c),e.post_render_callbacks.push(c)}t.traverse(c=>{c.layers.disableAll(),c.layers.enable(2)}),t.renderOrder=999999,t[$g]=o,t.castShadow=!1,t.receiveShadow=!1,t.isGizmo=!0,this.timedObjectsBuffer.push(t),this.timesBuffer.push(J.Current.time.realtimeSinceStartup+s),e.scene.add(t)}static onBeforeRender(e,t){this.tmuiNeedsUpdate&&(this.tmuiNeedsUpdate=!1,Re.update());for(let s=0;s<t.length;s++){const o=t[s];if(e.mainCamera&&o instanceof Re.MeshUIBaseElement){if(Er(o))continue;const r=e.isInVR,l=!1,c=!r;Kl(o,e.mainCamera,l,c)}}}static onPostRender(e,t,s){const o=e.time.realtimeSinceStartup;for(let r=t.length-1;r>=0;r--){const l=t[r];o>=s[r]-1e-6&&(t.splice(r,1),s.splice(r,1),l.removeFromParent(),Er(l)!=!0&&l[$g].push(l))}}}a(Ee,"familyName","needle-gizmos"),a(Ee,"linesCache",[]),a(Ee,"circlesCache",[]),a(Ee,"spheresCache",[]),a(Ee,"boxesCache",[]),a(Ee,"arrowHeadsCache",[]),a(Ee,"mesh",[]),a(Ee,"textLabelCache",[]),a(Ee,"timedObjectsBuffer",new Array),a(Ee,"timesBuffer",new Array),a(Ee,"contextPostRenderCallbacks",new Map),a(Ee,"contextBeforeRenderCallbacks",new Map),a(Ee,"tmuiNeedsUpdate",!1);const Ti=C("debugphysics"),R_=new uo;class Qs{constructor(){a(this,"ray"),a(this,"cam"),a(this,"screenPoint"),a(this,"raycaster"),a(this,"results"),a(this,"targets"),a(this,"recursive",!0),a(this,"minDistance"),a(this,"maxDistance"),a(this,"lineThreshold"),a(this,"layerMask"),a(this,"ignore"),a(this,"testObject"),a(this,"useAcceleratedRaycast")}screenPointFromOffset(e,t){this.screenPoint===void 0&&(this.screenPoint=new re),this.screenPoint.x=e/window.innerWidth*2-1,this.screenPoint.y=-(t/window.innerHeight)*2+1}setLayer(e){R_.set(e),this.layerMask=R_}setMask(e){this.layerMask||(this.layerMask=new uo);const t=this.layerMask;t?t.mask=e:this.layerMask=e}}a(Qs,"AllLayers",4294967295);class Hg{constructor(e,t,s){a(this,"distance"),a(this,"point"),a(this,"object"),this.object=e,this.distance=t,this.point=s}}const T_=class yv{constructor(e){a(this,"context"),a(this,"engine"),a(this,"raycaster",new md),a(this,"defaultRaycastOptions",new Qs),a(this,"targetBuffer",new Array(1)),a(this,"defaultThresholds",{Mesh:{},Line:{threshold:-1},LOD:{},Points:{threshold:0},Sprite:{}}),a(this,"sphereResults",new Array),a(this,"sphereMask",new uo),a(this,"sphere",new gd),a(this,"tempBoundingBox",new Si),this.context=e}static get raycasting(){return this._raycasting>0}raycastPhysicsFast(e,t=void 0,s=1/0,o=!0){var r;return((r=this.context.physics.engine)==null?void 0:r.raycast(e,t,{maxDistance:s,solid:o}))??null}raycastPhysicsFastAndGetNormal(e,t=void 0,s=1/0,o=!0){var r;return((r=this.context.physics.engine)==null?void 0:r.raycastAndGetNormal(e,t,{maxDistance:s,solid:o}))??null}sphereOverlapPhysics(e,t){var s;return((s=this.context.physics.engine)==null?void 0:s.sphereOverlap(e,t))??null}sphereOverlap(e,t,s=!0,o=!1,r=null){if(this.sphereResults.length=0,!this.context.scene)return this.sphereResults;const l=this.sphereMask;l.enableAll(),l.disable(2);for(const c of this.context.scene.children)this.intersectSphere(c,e,t,l,this.sphereResults,s,o,r);return this.sphereResults.sort((c,h)=>c.distance-h.distance)}raycastFromRay(e,t=null){const s=t??this.defaultRaycastOptions;s.ray=e;const o=this.raycast(s);return s===this.defaultRaycastOptions&&(s.ray=void 0),o}raycast(e=null){Ti&&performance.mark("raycast.start"),e||(e=this.defaultRaycastOptions);const t=e.screenPoint??this.context.input.mousePositionRC,s=e.raycaster??this.raycaster;if(s.near=e.minDistance??0,s.far=e.maxDistance??1/0,s.params=this.defaultThresholds,e.lineThreshold===void 0&&(e.lineThreshold=-1),s.params.Line={threshold:e.lineThreshold},e.ray)s.ray.copy(e.ray);else{const c=e.cam??this.context.mainCamera;if(!c)return Ti&&console.error("Can not perform raycast - no main camera found"),this.defaultRaycastOptions.results&&(this.defaultRaycastOptions.results.length=0),this.defaultRaycastOptions.results??[];const h=this.context.xrCamera;this.context.isInXR&&h instanceof BC&&h.cameras.length>0?s.setFromCamera(t,h.cameras[0]):s.setFromCamera(t,c)}let o=e.targets;o||(o=this.targetBuffer,o.length=1,o[0]=this.context.scene);let r=e.results;this.defaultRaycastOptions.results&&(this.defaultRaycastOptions.results.length=0),r||(this.defaultRaycastOptions.results||(this.defaultRaycastOptions.results=new Array),r=this.defaultRaycastOptions.results),e.layerMask!==void 0?e.layerMask instanceof uo?s.layers.mask=e.layerMask.mask:s.layers.mask=e.layerMask:(s.layers.enableAll(),s.layers.disable(2)),Ti&&console.time("raycast"),r.length=0,yv._raycasting++,this.intersect(this.raycaster,o,r,e),r.sort((c,h)=>c.distance-h.distance);const l=e.ignore;return l!==void 0&&l.length>0&&(r=r.filter(c=>!l.includes(c.object))),yv._raycasting--,Ti&&(console.timeEnd("raycast"),console.warn("#"+this.context.time.frame+", hits:",r!=null&&r.length?[...r]:"nothing"),performance.mark("raycast.end"),performance.measure("raycast","raycast.start","raycast.end")),r}intersect(e,t,s,o){var r,l,c;for(const h of t){if(!h||h.visible===!1||$.isGizmo(h)||o.lineThreshold!==void 0&&o.lineThreshold<0&&h instanceof $l)continue;let d=!0;const u=h,p=u.geometry;if(o.testObject){const g=(r=o.testObject)==null?void 0:r.call(o,h);if(g===!1)continue;g==="continue in children"&&(d=!1)}if(d&&(p&&E_(p)||(d=!1)),d){const g=Wv(h);g&&(u.geometry=g);const f=s.length;let y=!0;if(o.precise===!1&&(y=!1),y||(y=((c=(l=p.getAttribute("position"))==null?void 0:l.array)==null?void 0:c.length)<64),u instanceof ka&&(y=!1),!y&&xM(u,e,s)||(o.useAcceleratedRaycast!==!1?Xd.runMeshBVHRaycast(e,u,s,this.context):e.intersectObject(u,!1,s)),Ti&&s.length!=f){const v=s[s.length-1],b=g?8969557:7798784;$.DrawWireSphere(v.point,.1,b,1,!1),$.DrawWireMesh({mesh:h,depthTest:!1,duration:.2,color:b})}u.geometry=p}o.recursive!==!1&&this.intersect(e,h.children,s,o)}return s}intersectSphere(e,t,s,o,r,l,c,h){let d=e&&e.isMesh&&e.layers.test(o)&&!$.isGizmo(e);d&&(d=e.visible),d&&(d=!(e instanceof $l)),d&&(d=!(e instanceof ka));const u=e,p=u.geometry;if(d&&h){const g=h(e);if(g===!1)return;g==="continue in children"&&(d=!1)}if(p&&E_(p)||(d=!1),d){if(c){const g=this.sphere;g.center.copy(t),g.radius=s;const f=r.length;if(Xd.runMeshBVHRaycast(this.sphere,u,r,this.context),f!=r.length&&!l)return}else if(p.boundingBox||p.computeBoundingBox(),p.boundingBox){u.matrixWorldNeedsUpdate&&u.updateWorldMatrix(!1,!1);const g=this.tempBoundingBox.copy(p.boundingBox).applyMatrix4(u.matrixWorld),f=this.sphere;if(f.center.copy(t),f.radius=s,f.intersectsBox(g)){const y=ee(e),v=y.distanceTo(f.center),b=new Hg(e,v,y);if(r.push(b),!l)return}}}if(e.children)for(const g of e.children){const f=r.length;if(this.intersectSphere(g,t,s,o,r,l,c,h),f!=r.length&&!l)return}}};a(T_,"_raycasting",0);let Gg=T_;function E_(n){return!(n.index&&n.index.array.length<3)}const Pr=new gd,qd=new yr,wM=new Mv;function xM(n,e,t){const s=n._computeIntersections;if(!s)return!1;let o=n["_computeIntersections:Needle"];return o||(o=n["_computeIntersections:Needle"]=function(r,l,c){const h=this,d=h.geometry.boundingSphere;if(d){if(h instanceof ka){qd.setFromNormalAndCoplanarPoint(q(0,1,0),q(0,-h.position.y,0)),qd.applyMatrix4(h.matrixWorld,wM);const p=r.ray.intersectPlane(qd,q());if(p){Pr.copy(d),Pr.applyMatrix4(h.matrixWorld);const g=q(p).sub(r.ray.origin).length(),f=Pr.radius*.5;g<f&&l.push({distance:g,point:p,object:h,normal:qd.normal.clone()})}return}Pr.copy(d),Pr.applyMatrix4(h.matrixWorld);const u=r.ray.intersectSphere(Pr,q());if(u){const p=q(u).sub(r.ray.origin),g=p.length();if(g>Pr.radius){const f=p.clone().normalize();l.push({distance:g,point:u,object:h,normal:f})}}}}),n._computeIntersections=o,e.intersectObject(n,!1,t),n._computeIntersections=s,!0}var Xd;(n=>{function e(_,w,x,k){var M,T,L;if(!w.geometry||!w.geometry.hasAttribute("position"))return!1;const D=w.geometry;if(w!=null&&w.isSkinnedMesh){const z=w,j=z.bvhNeedsUpdate;if(!z.staticGenerator)c(),r&&(z.staticGenerator=new r(w),z.staticGenerator.applyWorldTransforms=!1,z.staticGeometry=z.staticGenerator.generate(),D.boundsTree=l?.call(z.staticGeometry),z.staticGeometryLastUpdate=performance.now()+Math.random()*200,z.autoUpdateMeshBVH===void 0&&(z.autoUpdateMeshBVH=!1));else if(D.boundsTree&&(z.autoUpdateMeshBVH===!0||j===!0)){const H=performance.now(),K=H-z.staticGeometryLastUpdate;(j||K>100)&&(z.bvhNeedsUpdate=!1,z.staticGeometryLastUpdate=H,(M=z.staticGenerator)==null||M.generate(z.staticGeometry),D.boundsTree.refit())}}else if(!D.boundsTree){d||b();let z=!0;if((k.xr||D[f]===!1||(T=D.getAttribute("position"))!=null&&T.isInterleavedBufferAttribute||D.index&&(L=D.index)!=null&&L.isInterleavedBufferAttribute)&&(z=!1),z&&p){if(D[g]===void 0){let j=null;if(v.length>0){const H=v.shift();H&&!H.running&&(j=H)}if(!j&&y.length<3&&(j=new p,y.push(j)),j!=null&&!j.running){const H=w.name;Ti&&console.log("<<<< worker start",H,j),D[g]="queued",performance.mark("bvh.create.start");const K=D.clone();try{j.generate(K).then(U=>{D[g]="done",D.boundsTree=U}).catch(U=>{D[g]="failed - "+U?.message,D[f]=!1,Ti&&console.error("Failed to generate mesh bvh on worker",U)}).finally(()=>{Ti&&console.log(">>>>> worker done",H,{hasBoundsTre:D.boundsTree!=null}),v.push(j),K.dispose(),performance.mark("bvh.create.end"),performance.measure("bvh.create (worker)","bvh.create.start","bvh.create.end")})}catch(U){console.error("Failed to generate mesh bvh on worker",U)}}else Ti&&console.warn("No worker available")}}else(!u||!z)&&(c(),o&&(performance.mark("bvh.create.start"),D.boundsTree=new o(D),performance.mark("bvh.create.end"),performance.measure("bvh.create","bvh.create.start","bvh.create.end")))}if(_ instanceof md){const z=_,j=w.raycast;D.boundsTree?(c(),s&&(w.acceleratedRaycast||(w.acceleratedRaycast=s.bind(w),Ti&&console.debug(`Physics: bind acceleratedRaycast fn to "${w.name}"`)),w.raycast=w.acceleratedRaycast)):Ti&&console.warn("No bounds tree found for mesh",w.name,{workerTask:D[g],hasAcceleratedRaycast:s!=null});const H=z.firstHitOnly;return z.firstHitOnly=!1,z.intersectObject(w,!1,x),z.firstHitOnly=H,w.raycast=j,!0}else if(_ instanceof gd){const z=D.boundsTree;if(z){const j=_;if(h.copy(w.matrixWorld).invert(),j.applyMatrix4(h),z.intersectsSphere(j)){const H=ee(w),K=H.distanceTo(j.center),U=new Hg(w,K,H);x.push(U)}}return!0}return!1}n.runMeshBVHRaycast=e;let t=!1,s=null,o=null,r=null,l=null;function c(){t||(t=!0,import("./vendor-BlSxe9JJ.min.js").then(_=>_.index$1).then(_=>{s=_.acceleratedRaycast,o=_.MeshBVH,r=_.StaticGeometryGenerator,l=_.computeBoundsTree}).catch(_=>{(Ti||F())&&console.error("Failed to load BVH library...",_.message)}))}const h=new se;let d=!1,u=!1,p=null;const g=Symbol("Needle:MeshBVH-Worker"),f=Symbol("Needle:MeshBVH-CanUseWorker"),y=[],v=[];function b(){d=!0,u=!0,Promise.resolve().then(()=>XL).then(_=>{p=_.GenerateMeshBVHWorker}).catch(_=>{(Ti||F())&&console.warn("Failed to setup mesh bvh worker")}).finally(()=>{u=!1})}})(Xd||(Xd={}));const A_=Symbol("gltf-loader-internal-usage-tracker"),SM=C("debugusers"),I_=class fm{constructor(e){a(this,"parser"),a(this,"_getDependency"),a(this,"_loadingId"),a(this,"_loadedObjects",new Set),this.parser=e,this._getDependency=this.parser.getDependency,this._loadingId=Date.now().toString()}get name(){return"NEEDLE_internal_usage_tracker"}static isLoading(e){return fm._loadingProcesses>0}beforeRoot(){fm._loadingProcesses++;const e=this,t=this._getDependency;return this.parser.getDependency=function(s,o){const r=t.call(this,s,o);return r.then(l=>(l&&(e._loadedObjects.add(l),l[A_]=e._loadingId),l)),r},null}afterRoot(e){fm._loadingProcesses--,this.parser.getDependency=this._getDependency;for(const t of this._loadedObjects)delete t[A_],t instanceof E&&(t.parent||t instanceof G&&setTimeout(()=>{SM&&console.warn("> GLTF LOADER: Mesh not used in scene!",t),t.material=null,t.geometry=null},1e3));return null}};a(I_,"_loadingProcesses",0);let L_=I_;class j_{constructor(){window.addEventListener("unhandledrejection",e=>{var t;if(e.defaultPrevented)return;const s=(t=e?.reason)==null?void 0:t.path;if(s){const o=s[0];o&&o.tagName==="IMG"&&(console.warn(`Could not load image:
|
|
166
|
+
${r.hand?"hand":"ctrl"} ${r.inputSource.handedness}[${r.index}] con:${r.connected} tr:${r.isTracking} hts:${r.hasHitTestSource?"yes":"no"}`;Fg=0,$.DrawLabel(e,o,void 0,1/60*20)}}addScript(e){return this._xr_scripts.includes(e)?!1:(Je&&console.log("Register new XRScript",e),this._xr_scripts.push(e),typeof e.onUpdateXR=="function"&&this._xr_update_scripts.push(e),!0)}markInactive(e){if(!(this._inactive_scripts.indexOf(e)>=0)){this.removeScript(e,!1),this._inactive_scripts.push(e);for(const t of this.controllers)this.invokeCallback_ControllerRemoved(e,t);this.invokeCallback_LeaveXR(e)}}handleInactiveScripts(){if(this._inactive_scripts.length>0)for(let e=this._inactive_scripts.length-1;e>=0;e--){const t=this._inactive_scripts[e];if(t.activeAndEnabled){this._inactive_scripts.splice(e,1),this.addScript(t),this.invokeCallback_EnterXR(t);for(const s of this.controllers)this.invokeCallback_ControllerAdded(t,s)}}}removeScript(e,t=!0){Je&&console.log("Remove XRScript",e);const s=this._xr_scripts.indexOf(e);s>=0&&this._xr_scripts.splice(s,1);const o=this._xr_update_scripts.indexOf(e);if(o>=0&&this._xr_update_scripts.splice(o,1),t){const r=this._inactive_scripts.indexOf(e);r>=0&&this._inactive_scripts.splice(r,1)}}invokeCallback_EnterXR(e){e.onEnterXR&&e.onEnterXR({xr:this})}invokeCallback_ControllerAdded(e,t){e.onXRControllerAdded&&e.onXRControllerAdded({xr:this,controller:t,change:"added"})}invokeCallback_ControllerRemoved(e,t){e.onXRControllerRemoved&&e.onXRControllerRemoved({xr:this,controller:t,change:"removed"})}invokeCallback_LeaveXR(e){e.onLeaveXR&&!e.destroyed&&e.onLeaveXR({xr:this})}syncCameraCullingMask(){var e;const t=this.context.xrCamera,s=(e=this.context.mainCameraComponent)==null?void 0:e.cullingMask;if(t&&s!==void 0){for(const o of t.cameras)o.layers.mask=s;t.layers.mask=s}else if(t){for(const o of t.cameras)o.layers.enableAll();t.layers.enableAll()}}invokeControllerEvent(e,t,s){for(let o=t.length-1;o>=0;o--){const r=t[o];if(r)try{r({xr:this,controller:e,change:s})}catch(l){console.error(l)}}}applyCustomForward(){var e;if(this.context.mainCamera&&this._customforward){this._camera=this.context.mainCamera,this._camera.parent!==this._cameraRenderParent&&(this._previousCameraParent=this._camera.parent,(e=this._previousCameraParent)==null||e.add(this._cameraRenderParent)),this._cameraRenderParent.name="XR Camera Render Parent",this._cameraRenderParent.add(this._camera);let t=.02;if(this.rig){const s=Ge(this.rig.gameObject);t*=s.x}this._camera instanceof we&&this._camera.near>t&&(this.originalCameraNearPlane=this._camera.near,this._camera.near=t)}}revertCustomForward(){this._camera&&this._previousCameraParent&&this._previousCameraParent.add(this._camera),this._previousCameraParent=null,this._camera instanceof we&&this.originalCameraNearPlane!=null&&(this._camera.near=this.originalCameraNearPlane)}internalUpdateState(){const e=this.context.renderer.xr.getReferenceSpace();if(!e){this._viewerPose=void 0;return}if(this._viewerPose=this.frame.getViewerPose(e),this._viewerPose){const t=this._viewerPose.transform;this._transformPosition.set(t.position.x,t.position.y,t.position.z),this._transformOrientation.set(t.orientation.x,t.orientation.y,t.orientation.z,t.orientation.w)}}get transition(){return this._transition||(this._transition=new w_),this._transition}fadeTransition(){return this._transition||(this._transition=new w_),this._transition.fadeTransition()}updateFade(e){this._transition&&e instanceof we&&this._transition.update(e,this.context.time.deltaTime)}onUpdateFade_PostRender(){var e;(e=this._transition)==null||e.remove()}};a(ai,"_sync",null),a(ai,"_currentSessionRequestMode",null),a(ai,"_currentSessionRequest"),a(ai,"_activeSession"),a(ai,"_sessionRequestStartListeners",[]),a(ai,"_sessionRequestEndListeners",[]),a(ai,"_xrStartListeners",[]),a(ai,"_xrEndListeners",[]),a(ai,"_controllerAddedListeners",[]),a(ai,"_controllerRemovedListeners",[]),a(ai,"$_stop_request",Symbol()),a(ai,"onEnd",()=>{Je&&console.log("XR Session ended"),ai._activeSession=null});let ne=ai;const zg=C("debugwebxr");class O_{static tryFindAvatarObjects(e,t,s){if(s.head&&s.leftHand&&s.rightHand)return;const o=e.name.toLocaleLowerCase();!s.head&&o.includes("head")&&(zg&&console.log("FOUND AVATAR HEAD",e.name),s.head=new ce("",t,e)),o.includes("hand")&&(!s.leftHand&&o.includes("left")&&(zg&&console.log("FOUND AVATAR LEFT HAND",e.name),s.leftHand=new ce("",t,e)),!s.rightHand&&o.includes("right")&&(zg&&console.log("FOUND AVATAR RIGHT HAND",e.name),s.rightHand=new ce("",t,e)));for(let r=0;r<e.children.length;r++){if(s.head&&s.leftHand&&s.rightHand)return;const l=e.children[r];this.tryFindAvatarObjects(l,t,s)}}}const Bt=new S,k_=new S,M_=new V,bM=C("debuggizmos"),Cs=8947848,Ng=32,Wg=class Bs{constructor(){}static isGizmo(e){return e[$g]!==void 0}static setVisible(e){for(const t of Ee.timedObjectsBuffer)t.visible=e}static DrawLabel(e,t,s=.05,o=0,r,l,c){var h;if(!Bs.enabled)return null;r||(r=Cs);const d=((h=ne.active)==null?void 0:h.rigScale)??1,u=Ee.getTextLabel(o,t,s*d,r,l);return c instanceof E&&c.add(u),u.position.x=e.x,u.position.y=e.y,u.position.z=e.z,u}static DrawRay(e,t,s=Cs,o=0,r=!0){if(!Bs.enabled)return;const l=Ee.getLine(o),c=l.geometry.getAttribute("position");c.setXYZ(0,e.x,e.y,e.z),Bt.set(t.x,t.y,t.z).multiplyScalar(999999999),c.setXYZ(1,e.x+Bt.x,e.y+Bt.y,e.z+Bt.z),c.needsUpdate=!0,l.material.color.set(s),l.material.depthTest=r,l.material.depthWrite=!1}static DrawDirection(e,t,s=Cs,o=0,r=!0,l=1){if(!Bs.enabled)return;const c=Ee.getLine(o),h=c.geometry.getAttribute("position");h.setXYZ(0,e.x,e.y,e.z),t.w!==void 0?(Bt.set(0,0,-l),M_.set(t.x,t.y,t.z,t.w),Bt.applyQuaternion(M_)):(Bt.set(t.x,t.y,t.z),Bt.multiplyScalar(l)),h.setXYZ(1,e.x+Bt.x,e.y+Bt.y,e.z+Bt.z),h.needsUpdate=!0,c.material.color.set(s),c.material.depthTest=r,c.material.depthWrite=!1}static DrawLine(e,t,s=Cs,o=0,r=!0){if(!Bs.enabled)return;const l=Ee.getLine(o),c=l.geometry.getAttribute("position");c.setXYZ(0,e.x,e.y,e.z),c.setXYZ(1,t.x,t.y,t.z),c.needsUpdate=!0,l.material.color.set(s),l.material.depthTest=r,l.material.depthWrite=!1,l.material.fog=!1}static DrawCircle(e,t,s,o=Cs,r=0,l=!0){if(!Bs.enabled)return;const c=Ee.getCircle(r);c.position.set(e.x,e.y,e.z),c.scale.set(s,s,s),c.quaternion.setFromUnitVectors(this._up,Bt.set(t.x,t.y,t.z).normalize()),c.material.color.set(o),c.material.depthTest=l,c.material.depthWrite=!1,c.material.fog=!1}static DrawWireSphere(e,t,s=Cs,o=0,r=!0){if(!Bs.enabled)return;const l=Ee.getSphere(t,o,!0);br(l,e.x,e.y,e.z),l.material.color.set(s),l.material.depthTest=r,l.material.depthWrite=!1,l.material.fog=!1}static DrawSphere(e,t,s=Cs,o=0,r=!0){if(!Bs.enabled)return;const l=Ee.getSphere(t,o,!1);br(l,e.x,e.y,e.z),l.material.color.set(s),l.material.depthTest=r,l.material.depthWrite=!1}static DrawWireBox(e,t,s=Cs,o=0,r=!0){if(!Bs.enabled)return;const l=Ee.getBox(o);l.position.set(e.x,e.y,e.z),l.scale.set(t.x,t.y,t.z),l.material.color.set(s),l.material.depthTest=r,l.material.wireframe=!0,l.material.depthWrite=!1,l.material.fog=!1}static DrawWireBox3(e,t=Cs,s=0,o=!0){if(!Bs.enabled)return;const r=Ee.getBox(s);r.position.copy(e.getCenter(Bt)),r.scale.copy(e.getSize(Bt)),r.material.color.set(t),r.material.depthTest=o,r.material.wireframe=!0,r.material.depthWrite=!1,r.material.fog=!1}static DrawArrow(e,t,s=Cs,o=0,r=!0,l=!1){if(!Bs.enabled)return;const c=Ee.getArrowHead(o);c.position.set(t.x,t.y,t.z),c.quaternion.setFromUnitVectors(this._up.set(0,1,0),Bt.set(t.x,t.y,t.z).sub(k_.set(e.x,e.y,e.z)).normalize());const h=Bt.set(t.x,t.y,t.z).sub(k_.set(e.x,e.y,e.z)).length()*.1;c.scale.set(h,h,h),c.material.color.set(s),c.material.depthTest=r,c.material.wireframe=l,this.DrawLine(e,t,s,o,r)}static DrawWireMesh(e){const t=Ee.getMesh(e.duration??0);"mesh"in e?(t.geometry=e.mesh.geometry,t.matrix.copy(e.mesh.matrixWorld)):(t.geometry=e.geometry,t.matrix.copy(e.matrix)),t.matrixAutoUpdate=!1,t.matrixWorldAutoUpdate=!1,t.material.color.set(e.color??Cs),t.material.depthTest=e.depthTest??!0,t.material.wireframe=!0}};a(Wg,"enabled",!0),a(Wg,"_up",new S(0,1,0));let $=Wg;const _M=new xa(1,1,1);function Vg(n=null){const e=new oe(n??14540253),t=new DC(_M);return new Ev(t,new Av({color:e}))}const $g=Symbol("GizmoCache");class Ee{static ensureFont(){let e=Re.FontLibrary.getFontFamily(this.familyName);if(!e){e=Re.FontLibrary.addFontFamily(this.familyName);const t=e.addVariant("normal","normal","https://uploads.needle.tools/include/font-msdf.json","https://uploads.needle.tools/include/font.png");t?.addEventListener("ready",()=>{Re.update()})}}static getTextLabel(e,t,s,o,r){this.ensureFont();let l=this.textLabelCache.pop(),c=1;r&&typeof r=="string"&&r?.length>=8&&r.startsWith("#")?(c=parseInt(r.substring(7),16)/255,r=r.substring(0,7),bM&&console.log(r,c)):typeof r=="object"&&r.a!==void 0&&(c=r.a);const h={boxSizing:"border-box",fontFamily:this.familyName,width:"auto",fontSize:s,color:o,lineHeight:1,backgroundColor:r??void 0,backgroundOpacity:c,textContent:t,borderRadius:.5*s,padding:.8*s,whiteSpace:"pre",offset:.05*s};if(l)l.set(h);else{l=new Jv(h);const d=this,u=l;u.setText=function(p){this.set({textContent:p}),d.tmuiNeedsUpdate=!0}}return this.tmuiNeedsUpdate=!0,this.registerTimedObject(J.Current,l,e,this.textLabelCache),l}static getBox(e){let t=this.boxesCache.pop();if(!t){const s=new xa(1,1,1);t=new G(s)}return this.registerTimedObject(J.Current,t,e,this.boxesCache),t}static getLine(e){let t=this.linesCache.pop();if(!t){t=new $l;let s=t.geometry.getAttribute("position");s||(s=new _t(new Float32Array(6),3),t.geometry.setAttribute("position",s))}return t.frustumCulled=!1,this.registerTimedObject(J.Current,t,e,this.linesCache),t}static getCircle(e){let t=this.circlesCache.pop();if(!t){t=new $l;let s=t.geometry.getAttribute("position");if(!s){s=new _t(new Float32Array(Ng*3),3),t.geometry.setAttribute("position",s);const o=q(0,1,0),r=q(0,0,1),l=q(r);l.cross(o).normalize();const c=q(l),h=Math.PI*2/(Ng-1);for(let d=0;d<Ng+1;d++){const u=h*d;o.copy(c).multiplyScalar(Math.cos(u)*1),l.copy(r).multiplyScalar(Math.sin(u)*1);const p=o.add(l);s.setXYZ(d,p.x,p.y,p.z)}}}return t.frustumCulled=!1,this.registerTimedObject(J.Current,t,e,this.circlesCache),t}static getSphere(e,t,s){let o=this.spheresCache.pop();return o||(o=new G(new pd(1,8,8))),o.scale.set(e,e,e),o.material.wireframe=s,this.registerTimedObject(J.Current,o,t,this.spheresCache),o}static getArrowHead(e){let t=this.arrowHeadsCache.pop();return t||(t=new G(new Rv(0,.5,1,8))),this.registerTimedObject(J.Current,t,e,this.arrowHeadsCache),t}static getMesh(e){let t=this.mesh.pop();return t||(t=new G,t.material=new Me),this.registerTimedObject(J.Current,t,e,this.mesh),t}static registerTimedObject(e,t,s,o){if(!e){console.error("No Needle Engine context available. Did you call a Gizmos function in global scope?");return}const r=this.contextBeforeRenderCallbacks.get(e),l=this.contextPostRenderCallbacks.get(e);if(r){if(e.pre_render_callbacks[e.pre_render_callbacks.length-1]!==r){const c=e.pre_render_callbacks.indexOf(r);c>=0&&e.pre_render_callbacks.splice(c,1),e.pre_render_callbacks.push(r)}}else{const c=()=>{this.onBeforeRender(e,this.timedObjectsBuffer)};this.contextBeforeRenderCallbacks.set(e,c),e.pre_render_callbacks.push(c)}if(l){if(e.post_render_callbacks[e.post_render_callbacks.length-1]!==l){const c=e.post_render_callbacks.indexOf(l);c>=0&&e.post_render_callbacks.splice(c,1),e.post_render_callbacks.push(l)}}else{const c=()=>{this.onPostRender(e,this.timedObjectsBuffer,this.timesBuffer)};this.contextPostRenderCallbacks.set(e,c),e.post_render_callbacks.push(c)}t.traverse(c=>{c.layers.disableAll(),c.layers.enable(2)}),t.renderOrder=999999,t[$g]=o,t.castShadow=!1,t.receiveShadow=!1,t.isGizmo=!0,this.timedObjectsBuffer.push(t),this.timesBuffer.push(J.Current.time.realtimeSinceStartup+s),e.scene.add(t)}static onBeforeRender(e,t){this.tmuiNeedsUpdate&&(this.tmuiNeedsUpdate=!1,Re.update());for(let s=0;s<t.length;s++){const o=t[s];if(e.mainCamera&&o instanceof Re.MeshUIBaseElement){if(Er(o))continue;const r=e.isInVR,l=!1,c=!r;Kl(o,e.mainCamera,l,c)}}}static onPostRender(e,t,s){const o=e.time.realtimeSinceStartup;for(let r=t.length-1;r>=0;r--){const l=t[r];o>=s[r]-1e-6&&(t.splice(r,1),s.splice(r,1),l.removeFromParent(),Er(l)!=!0&&l[$g].push(l))}}}a(Ee,"familyName","needle-gizmos"),a(Ee,"linesCache",[]),a(Ee,"circlesCache",[]),a(Ee,"spheresCache",[]),a(Ee,"boxesCache",[]),a(Ee,"arrowHeadsCache",[]),a(Ee,"mesh",[]),a(Ee,"textLabelCache",[]),a(Ee,"timedObjectsBuffer",new Array),a(Ee,"timesBuffer",new Array),a(Ee,"contextPostRenderCallbacks",new Map),a(Ee,"contextBeforeRenderCallbacks",new Map),a(Ee,"tmuiNeedsUpdate",!1);const Ti=C("debugphysics"),R_=new uo;class Qs{constructor(){a(this,"ray"),a(this,"cam"),a(this,"screenPoint"),a(this,"raycaster"),a(this,"results"),a(this,"targets"),a(this,"recursive",!0),a(this,"minDistance"),a(this,"maxDistance"),a(this,"lineThreshold"),a(this,"layerMask"),a(this,"ignore"),a(this,"testObject"),a(this,"useAcceleratedRaycast")}screenPointFromOffset(e,t){this.screenPoint===void 0&&(this.screenPoint=new re),this.screenPoint.x=e/window.innerWidth*2-1,this.screenPoint.y=-(t/window.innerHeight)*2+1}setLayer(e){R_.set(e),this.layerMask=R_}setMask(e){this.layerMask||(this.layerMask=new uo);const t=this.layerMask;t?t.mask=e:this.layerMask=e}}a(Qs,"AllLayers",4294967295);class Hg{constructor(e,t,s){a(this,"distance"),a(this,"point"),a(this,"object"),this.object=e,this.distance=t,this.point=s}}const T_=class yv{constructor(e){a(this,"context"),a(this,"engine"),a(this,"raycaster",new md),a(this,"defaultRaycastOptions",new Qs),a(this,"targetBuffer",new Array(1)),a(this,"defaultThresholds",{Mesh:{},Line:{threshold:-1},LOD:{},Points:{threshold:0},Sprite:{}}),a(this,"sphereResults",new Array),a(this,"sphereMask",new uo),a(this,"sphere",new gd),a(this,"tempBoundingBox",new Si),this.context=e}static get raycasting(){return this._raycasting>0}raycastPhysicsFast(e,t=void 0,s=1/0,o=!0){var r;return((r=this.context.physics.engine)==null?void 0:r.raycast(e,t,{maxDistance:s,solid:o}))??null}raycastPhysicsFastAndGetNormal(e,t=void 0,s=1/0,o=!0){var r;return((r=this.context.physics.engine)==null?void 0:r.raycastAndGetNormal(e,t,{maxDistance:s,solid:o}))??null}sphereOverlapPhysics(e,t){var s;return((s=this.context.physics.engine)==null?void 0:s.sphereOverlap(e,t))??null}sphereOverlap(e,t,s=!0,o=!1,r=null){if(this.sphereResults.length=0,!this.context.scene)return this.sphereResults;const l=this.sphereMask;l.enableAll(),l.disable(2);for(const c of this.context.scene.children)this.intersectSphere(c,e,t,l,this.sphereResults,s,o,r);return this.sphereResults.sort((c,h)=>c.distance-h.distance)}raycastFromRay(e,t=null){const s=t??this.defaultRaycastOptions;s.ray=e;const o=this.raycast(s);return s===this.defaultRaycastOptions&&(s.ray=void 0),o}raycast(e=null){Ti&&performance.mark("raycast.start"),e||(e=this.defaultRaycastOptions);const t=e.screenPoint??this.context.input.mousePositionRC,s=e.raycaster??this.raycaster;if(s.near=e.minDistance??0,s.far=e.maxDistance??1/0,s.params=this.defaultThresholds,e.lineThreshold===void 0&&(e.lineThreshold=-1),s.params.Line={threshold:e.lineThreshold},e.ray)s.ray.copy(e.ray);else{const c=e.cam??this.context.mainCamera;if(!c)return Ti&&console.error("Can not perform raycast - no main camera found"),this.defaultRaycastOptions.results&&(this.defaultRaycastOptions.results.length=0),this.defaultRaycastOptions.results??[];const h=this.context.xrCamera;this.context.isInXR&&h instanceof BC&&h.cameras.length>0?s.setFromCamera(t,h.cameras[0]):s.setFromCamera(t,c)}let o=e.targets;o||(o=this.targetBuffer,o.length=1,o[0]=this.context.scene);let r=e.results;this.defaultRaycastOptions.results&&(this.defaultRaycastOptions.results.length=0),r||(this.defaultRaycastOptions.results||(this.defaultRaycastOptions.results=new Array),r=this.defaultRaycastOptions.results),e.layerMask!==void 0?e.layerMask instanceof uo?s.layers.mask=e.layerMask.mask:s.layers.mask=e.layerMask:(s.layers.enableAll(),s.layers.disable(2)),Ti&&console.time("raycast"),r.length=0,yv._raycasting++,this.intersect(this.raycaster,o,r,e),r.sort((c,h)=>c.distance-h.distance);const l=e.ignore;return l!==void 0&&l.length>0&&(r=r.filter(c=>!l.includes(c.object))),yv._raycasting--,Ti&&(console.timeEnd("raycast"),console.warn("#"+this.context.time.frame+", hits:",r!=null&&r.length?[...r]:"nothing"),performance.mark("raycast.end"),performance.measure("raycast","raycast.start","raycast.end")),r}intersect(e,t,s,o){var r,l,c;for(const h of t){if(!h||h.visible===!1||$.isGizmo(h)||o.lineThreshold!==void 0&&o.lineThreshold<0&&h instanceof $l)continue;let d=!0;const u=h,p=u.geometry;if(o.testObject){const g=(r=o.testObject)==null?void 0:r.call(o,h);if(g===!1)continue;g==="continue in children"&&(d=!1)}if(d&&(p&&E_(p)||(d=!1)),d){const g=Wv(h);g&&(u.geometry=g);const f=s.length;let y=!0;if(o.precise===!1&&(y=!1),y||(y=((c=(l=p.getAttribute("position"))==null?void 0:l.array)==null?void 0:c.length)<64),u instanceof ka&&(y=!1),!y&&xM(u,e,s)||(o.useAcceleratedRaycast!==!1?Xd.runMeshBVHRaycast(e,u,s,this.context):e.intersectObject(u,!1,s)),Ti&&s.length!=f){const v=s[s.length-1],b=g?8969557:7798784;$.DrawWireSphere(v.point,.1,b,1,!1),$.DrawWireMesh({mesh:h,depthTest:!1,duration:.2,color:b})}u.geometry=p}o.recursive!==!1&&this.intersect(e,h.children,s,o)}return s}intersectSphere(e,t,s,o,r,l,c,h){let d=e&&e.isMesh&&e.layers.test(o)&&!$.isGizmo(e);d&&(d=e.visible),d&&(d=!(e instanceof $l)),d&&(d=!(e instanceof ka));const u=e,p=u.geometry;if(d&&h){const g=h(e);if(g===!1)return;g==="continue in children"&&(d=!1)}if(p&&E_(p)||(d=!1),d){if(c){const g=this.sphere;g.center.copy(t),g.radius=s;const f=r.length;if(Xd.runMeshBVHRaycast(this.sphere,u,r,this.context),f!=r.length&&!l)return}else if(p.boundingBox||p.computeBoundingBox(),p.boundingBox){u.matrixWorldNeedsUpdate&&u.updateWorldMatrix(!1,!1);const g=this.tempBoundingBox.copy(p.boundingBox).applyMatrix4(u.matrixWorld),f=this.sphere;if(f.center.copy(t),f.radius=s,f.intersectsBox(g)){const y=ee(e),v=y.distanceTo(f.center),b=new Hg(e,v,y);if(r.push(b),!l)return}}}if(e.children)for(const g of e.children){const f=r.length;if(this.intersectSphere(g,t,s,o,r,l,c,h),f!=r.length&&!l)return}}};a(T_,"_raycasting",0);let Gg=T_;function E_(n){return!(n.index&&n.index.array.length<3)}const Pr=new gd,qd=new yr,wM=new Mv;function xM(n,e,t){const s=n._computeIntersections;if(!s)return!1;let o=n["_computeIntersections:Needle"];return o||(o=n["_computeIntersections:Needle"]=function(r,l,c){const h=this,d=h.geometry.boundingSphere;if(d){if(h instanceof ka){qd.setFromNormalAndCoplanarPoint(q(0,1,0),q(0,-h.position.y,0)),qd.applyMatrix4(h.matrixWorld,wM);const p=r.ray.intersectPlane(qd,q());if(p){Pr.copy(d),Pr.applyMatrix4(h.matrixWorld);const g=q(p).sub(r.ray.origin).length(),f=Pr.radius*.5;g<f&&l.push({distance:g,point:p,object:h,normal:qd.normal.clone()})}return}Pr.copy(d),Pr.applyMatrix4(h.matrixWorld);const u=r.ray.intersectSphere(Pr,q());if(u){const p=q(u).sub(r.ray.origin),g=p.length();if(g>Pr.radius){const f=p.clone().normalize();l.push({distance:g,point:u,object:h,normal:f})}}}}),n._computeIntersections=o,e.intersectObject(n,!1,t),n._computeIntersections=s,!0}var Xd;(n=>{function e(_,w,x,k){var M,T,L;if(!w.geometry||!w.geometry.hasAttribute("position"))return!1;const D=w.geometry;if(w!=null&&w.isSkinnedMesh){const z=w,j=z.bvhNeedsUpdate;if(!z.staticGenerator)c(),r&&(z.staticGenerator=new r(w),z.staticGenerator.applyWorldTransforms=!1,z.staticGeometry=z.staticGenerator.generate(),D.boundsTree=l?.call(z.staticGeometry),z.staticGeometryLastUpdate=performance.now()+Math.random()*200,z.autoUpdateMeshBVH===void 0&&(z.autoUpdateMeshBVH=!1));else if(D.boundsTree&&(z.autoUpdateMeshBVH===!0||j===!0)){const H=performance.now(),K=H-z.staticGeometryLastUpdate;(j||K>100)&&(z.bvhNeedsUpdate=!1,z.staticGeometryLastUpdate=H,(M=z.staticGenerator)==null||M.generate(z.staticGeometry),D.boundsTree.refit())}}else if(!D.boundsTree){d||b();let z=!0;if((k.xr||D[f]===!1||(T=D.getAttribute("position"))!=null&&T.isInterleavedBufferAttribute||D.index&&(L=D.index)!=null&&L.isInterleavedBufferAttribute)&&(z=!1),z&&p){if(D[g]===void 0){let j=null;if(v.length>0){const H=v.shift();H&&!H.running&&(j=H)}if(!j&&y.length<3&&(j=new p,y.push(j)),j!=null&&!j.running){const H=w.name;Ti&&console.log("<<<< worker start",H,j),D[g]="queued",performance.mark("bvh.create.start");const K=D.clone();try{j.generate(K).then(U=>{D[g]="done",D.boundsTree=U}).catch(U=>{D[g]="failed - "+U?.message,D[f]=!1,Ti&&console.error("Failed to generate mesh bvh on worker",U)}).finally(()=>{Ti&&console.log(">>>>> worker done",H,{hasBoundsTre:D.boundsTree!=null}),v.push(j),K.dispose(),performance.mark("bvh.create.end"),performance.measure("bvh.create (worker)","bvh.create.start","bvh.create.end")})}catch(U){console.error("Failed to generate mesh bvh on worker",U)}}else Ti&&console.warn("No worker available")}}else(!u||!z)&&(c(),o&&(performance.mark("bvh.create.start"),D.boundsTree=new o(D),performance.mark("bvh.create.end"),performance.measure("bvh.create","bvh.create.start","bvh.create.end")))}if(_ instanceof md){const z=_,j=w.raycast;D.boundsTree?(c(),s&&(w.acceleratedRaycast||(w.acceleratedRaycast=s.bind(w),Ti&&console.debug(`Physics: bind acceleratedRaycast fn to "${w.name}"`)),w.raycast=w.acceleratedRaycast)):Ti&&console.warn("No bounds tree found for mesh",w.name,{workerTask:D[g],hasAcceleratedRaycast:s!=null});const H=z.firstHitOnly;return z.firstHitOnly=!1,z.intersectObject(w,!1,x),z.firstHitOnly=H,w.raycast=j,!0}else if(_ instanceof gd){const z=D.boundsTree;if(z){const j=_;if(h.copy(w.matrixWorld).invert(),j.applyMatrix4(h),z.intersectsSphere(j)){const H=ee(w),K=H.distanceTo(j.center),U=new Hg(w,K,H);x.push(U)}}return!0}return!1}n.runMeshBVHRaycast=e;let t=!1,s=null,o=null,r=null,l=null;function c(){t||(t=!0,import("./vendor-BlSxe9JJ.min.js").then(_=>_.index$1).then(_=>{s=_.acceleratedRaycast,o=_.MeshBVH,r=_.StaticGeometryGenerator,l=_.computeBoundsTree}).catch(_=>{(Ti||F())&&console.error("Failed to load BVH library...",_.message)}))}const h=new se;let d=!1,u=!1,p=null;const g=Symbol("Needle:MeshBVH-Worker"),f=Symbol("Needle:MeshBVH-CanUseWorker"),y=[],v=[];function b(){d=!0,u=!0,Promise.resolve().then(()=>QL).then(_=>{p=_.GenerateMeshBVHWorker}).catch(_=>{(Ti||F())&&console.warn("Failed to setup mesh bvh worker")}).finally(()=>{u=!1})}})(Xd||(Xd={}));const A_=Symbol("gltf-loader-internal-usage-tracker"),SM=C("debugusers"),I_=class fm{constructor(e){a(this,"parser"),a(this,"_getDependency"),a(this,"_loadingId"),a(this,"_loadedObjects",new Set),this.parser=e,this._getDependency=this.parser.getDependency,this._loadingId=Date.now().toString()}get name(){return"NEEDLE_internal_usage_tracker"}static isLoading(e){return fm._loadingProcesses>0}beforeRoot(){fm._loadingProcesses++;const e=this,t=this._getDependency;return this.parser.getDependency=function(s,o){const r=t.call(this,s,o);return r.then(l=>(l&&(e._loadedObjects.add(l),l[A_]=e._loadingId),l)),r},null}afterRoot(e){fm._loadingProcesses--,this.parser.getDependency=this._getDependency;for(const t of this._loadedObjects)delete t[A_],t instanceof E&&(t.parent||t instanceof G&&setTimeout(()=>{SM&&console.warn("> GLTF LOADER: Mesh not used in scene!",t),t.material=null,t.geometry=null},1e3));return null}};a(I_,"_loadingProcesses",0);let L_=I_;class j_{constructor(){window.addEventListener("unhandledrejection",e=>{var t;if(e.defaultPrevented)return;const s=(t=e?.reason)==null?void 0:t.path;if(s){const o=s[0];o&&o.tagName==="IMG"&&(console.warn(`Could not load image:
|
|
167
167
|
`+o.src),e.preventDefault())}})}}const Qd=C("trackresources");function D_(){return Qd==="dispose"}let Or=!0;Qd===0&&(Or=!1);function CM(n){Or=n}function B_(){return Or}const F_=Symbol("disposable");function qg(n,e){n&&(n[F_]=e,kr&&console.warn("Set disposable",e,n))}const U_=Symbol("disposed");function PM(n){return n[U_]===!0}function Te(n){var e;if(n){if(n[F_]===!1){kr&&console.warn("Object is marked as not disposable",n);return}if(typeof n=="object"&&(n[U_]=!0),n instanceof xi)Te(n.environment),Te(n.background),Te(n.customDepthMaterial),Te(n.customDistanceMaterial);else if(n instanceof Pn)Te(n.geometry),Te(n.material),Te(n.skeleton),Te(n.bindMatrix),Te(n.bindMatrixInverse),Te(n.customDepthMaterial),Te(n.customDistanceMaterial),n.geometry=null,n.material=null,n.visible=!1;else if(n instanceof G)Te(n.geometry),Te(n.material),Te(n.customDepthMaterial),Te(n.customDistanceMaterial),n.geometry=null,n.material=null,n.visible=!1;else if(n instanceof Vs){Fa(n);for(const t of Object.keys(n.attributes)){const s=n.attributes[t];Te(s)}}else if(n instanceof _t||n instanceof Iv)kr&&console.warn("BufferAttribute dispose not supported",n.count);else if(n instanceof Array)for(const t of n)t instanceof Pe&&Te(t);else if(n instanceof Pe){Fa(n);for(const s of Object.keys(n)){const o=n[s];o instanceof je&&(Te(o),n[s]=null)}const t=n.uniforms;if(t)for(const s of Object.keys(t)){const o=t[s];o instanceof je?(Te(o),t[s]=null):o instanceof Qi&&(Te(o.value),o.value=null)}}else n instanceof je?(Fa(n),Fa(n.source),((e=n.source)==null?void 0:e.data)instanceof ImageBitmap&&Fa(n.source.data)):n instanceof FC?(Fa(n.boneTexture),n.boneTexture=null):n instanceof UC||!(n instanceof E)&&kr&&console.warn("Unknown object type",n)}}function Fa(n){n&&((kr||D_()||Qd)&&console.warn("\u{1F9E8} FREE",n),n instanceof ImageBitmap?n.close():n instanceof zC?n.data=null:n.dispose())}function z_(n){(n instanceof G||n instanceof Pn)&&(n.material=null,n.geometry=null)}const OM=new Set;function Xg(n,e,t=null,s){if(s||(s=OM,s.clear()),!n)return s;const o=n[hc];if(o)for(const r of o)s.has(r)||t?.call(null,r)!==!1&&(s.add(r),e&&Xg(r,!0,t,s));return s}function kM(n){return n[dc]}const kr=C("debugresourceusers")||C("debugmemory"),hc=Symbol("needle-resource-users"),dc=Symbol("needle-resource-users-count");function Qt(n,e){Dd(n,e,function(t,s){Or&&!Gg.raycasting&&(Yd(hc,this,t,!1),Yd(hc,this,s,!0))})}Or&&(Qt(G.prototype,"material"),Qt(G.prototype,"geometry"),Qt(Pe.prototype,"map"),Qt(Pe.prototype,"bumpMap"),Qt(Pe.prototype,"alphaMap"),Qt(Pe.prototype,"normalMap"),Qt(Pe.prototype,"displacementMap"),Qt(Pe.prototype,"roughnessMap"),Qt(Pe.prototype,"metalnessMap"),Qt(Pe.prototype,"emissiveMap"),Qt(Pe.prototype,"specularMap"),Qt(Pe.prototype,"envMap"),Qt(Pe.prototype,"lightMap"),Qt(Pe.prototype,"aoMap"),Qt(Pe.prototype,"gradientMap"));function MM(n){if(Or===!1)return;const e=n[hc];if(e)for(const t of e)Yd(hc,t,n,!1)}Or&&Dd(Pe.prototype,"dispose",function(){MM(this)});let Qg=0;function Yd(n,e,t,s){if(Qg>0)return;if(Array.isArray(t)){for(const r of t)Yd(n,e,r,s);return}if(!t)return;let o=t[n];if(o||(o=new Set),s){if(e&&!o.has(e)){o.add(e);let r=t[dc]||0;r+=1,t[dc]=r,kr&&console.warn(`\u{1F7E2} Added user of "${t.type}"`,e,t,r,"users:",o)}}else if(e&&o.has(e)){o.delete(e);let r=t[dc]||0;r>0&&(r-=1,t[dc]=r),kr&&console.warn(`\u{1F534} Removed user of "${t.type}"`,e,t,r,"users:",o),r<=0&&(L_.isLoading(t)||(Qd&&console.warn(`\u{1F534} Removed all user of "${t.type}"`,t),D_()&&Te(t)))}t[n]=o}try{Dd(fr.prototype,"render",function(){Qg++},function(){Qg--})}catch(n){console.warn("Could not wrap WebGLRenderer.render",n)}const N_=C("debugcomponentevents");class uc{static addComponentLifecylceEventListener(e,t){this.eventListeners.has(e)&&this.eventListeners.set(e,[]);let s=this.eventListeners.get(e);s||(s=[]),s.push(t),this.eventListeners.set(e,s),N_&&console.log("Added event listener for "+e,this.eventListeners)}static removeComponentLifecylceEventListener(e,t){const s=this.eventListeners.get(e);if(!s)return;const o=s.indexOf(t);o<0||s.splice(o,1)}static dispatchComponentLifecycleEvent(e,t){const s=this.eventListeners.get(e);if(N_&&console.log("Dispatching event "+e,s),!!s)for(const o of s)o(t)}}a(uc,"eventListeners",new Map);const pc=Symbol("NEEDLE_NEED_UPDATE_INSTANCE"),W_=Symbol("isUsingInstancing"),V_=Symbol("instancingRenderer"),mc=Symbol("instancingAutoUpdateBounds");class ms{static isUsingInstancing(e){return e[W_]===!0}static getRenderer(e){return e[V_]||null}setAutoUpdateBounds(e,t){const s=ms.getRenderer(e);s&&(s[mc]=t)}static markDirty(e,t=!0){if(e&&(this.isUsingInstancing(e)&&(e[pc]=!0,e.matrixWorldNeedsUpdate=!0),t))for(const s of e.children)ms.markDirty(s,!0)}}function Ua(n,e){try{e||n()}catch(t){return console.error(t),!1}return!0}const Yg=C("debugnewscripts"),RM=C("debughierarchy"),Fe=[];function TM(){return Fe.length>0}function Kd(n){if(Yg&&console.log("Register new components",n.new_scripts.length,[...n.new_scripts],n.alias?"element: "+n.alias:n.hash,n),n.new_scripts_pre_setup_callbacks.length>0){for(const e of n.new_scripts_pre_setup_callbacks)e&&e();n.new_scripts_pre_setup_callbacks.length=0}if(!(n.new_scripts.length<=0)){Fe.length=0,n.new_scripts.length>0&&Fe.push(...n.new_scripts),n.new_scripts.length=0;for(let e=0;e<Fe.length;e++)try{const t=Fe[e];if(t.isComponent!==!0){(F()||Yg)&&console.error(`Registered script is not a Needle Engine component.
|
|
168
168
|
The script will be ignored. Please make sure your component extends "Behaviour" imported from "@needle-tools/engine"
|
|
169
169
|
`,t),Fe.splice(e,1),e--;continue}if(t.destroyed)continue;if(!t.gameObject){console.warn(`Component can not be initialized: no GameObject assigned.
|
|
@@ -781,7 +781,7 @@ Possible solutions:
|
|
|
781
781
|
`,s),this._renderlooperrors>=3&&(console.warn("Stopping render loop due to error"),this.renderer.setAnimationLoop(null)),this.domElement.dispatchEvent(new CustomEvent("error",{detail:s}))}else this.internalStep(e,t)}updatePhysics(e){this.internalUpdatePhysics(e)}internalStep(e,t){this.internalOnBeforeRender(e,t)!==!1&&(this.internalOnRender(),this.internalOnAfterRender())}internalOnBeforeRender(e,t){var s;this.renderer.info.autoReset=!!t,this.renderer.info.autoReset===!1&&this.renderer.info.reset();const o=t!==null&&this._xrFrame===null;if(this._xrFrame=t,o&&this.domElement.dispatchEvent(new CustomEvent("xr-session-started",{detail:{context:this,session:this.xrSession,frame:t}})),this._currentFrameEvent=-1,this.isManagedExternally===!1&&this.isInXR===!1&&this.targetFrameRate!==void 0){this._lastTimestamp===0&&(this._lastTimestamp=e),this._accumulatedTime+=(e-this._lastTimestamp)/1e3,this._lastTimestamp=e;let r=this.targetFrameRate;if(typeof r=="object"&&(r=r.value),this._accumulatedTime<1/(r+1))return!1;this._accumulatedTime=0}if((s=this._stats)==null||s.begin(),Le.Current=this,this.onHandlePaused())return!1;for(Le.Current=this,this.time.update(),TR&&console.log("FPS",this.time.smoothedFps.toFixed(0)),Kd(this),Zd(this.scene),$_(this),Xs(this,-1);this._cameraStack.length>0&&(!this.mainCameraComponent||this.mainCameraComponent.destroyed);){this._cameraStack.splice(this._cameraStack.length-1,1);const r=this._cameraStack[this._cameraStack.length-1];this.setCurrentCamera(r)}if(this.pre_update_oneshot_callbacks){for(const r in this.pre_update_oneshot_callbacks)this.pre_update_oneshot_callbacks[r]();this.pre_update_oneshot_callbacks.length=0}if(this.pre_update_callbacks)for(const r in this.pre_update_callbacks)this.pre_update_callbacks[r]();this._currentFrameEvent=0;for(let r=0;r<this.scripts_earlyUpdate.length;r++){const l=this.scripts_earlyUpdate[r];l.activeAndEnabled&&l.earlyUpdate!==void 0&&(Le.Current=this,l.earlyUpdate())}if(this.executeCoroutines(0),Xs(this,0),this.onHandlePaused())return!1;this._currentFrameEvent=1;for(let r=0;r<this.scripts_update.length;r++){const l=this.scripts_update[r];l.activeAndEnabled&&l.update!==void 0&&(Le.Current=this,l.update())}if(this.executeCoroutines(1),Xs(this,1),this.onHandlePaused())return!1;this._currentFrameEvent=2;for(let r=0;r<this.scripts_lateUpdate.length;r++){const l=this.scripts_lateUpdate[r];l.activeAndEnabled&&l.lateUpdate!==void 0&&(Le.Current=this,l.lateUpdate())}if(this.executeCoroutines(2),Xs(this,2),this.onHandlePaused()||(this.physicsSteps===void 0&&(this.physicsSteps=1),this.physics.engine&&this.physicsSteps>0&&this.internalUpdatePhysics(this.physicsSteps),this.onHandlePaused()))return!1;if(this.isVisibleToUser||this.runInBackground){this._currentFrameEvent=3;for(let r=0;r<this.scripts_onBeforeRender.length;r++){const l=this.scripts_onBeforeRender[r];l.activeAndEnabled&&l.onBeforeRender!==void 0&&(Le.Current=this,l.onBeforeRender(t))}if(this.executeCoroutines(3),Xs(this,3),this._needsUpdateSize&&this.updateSize(),this.pre_render_callbacks)for(const r in this.pre_render_callbacks)this.pre_render_callbacks[r](t)}return!0}internalUpdatePhysics(e){if(!this.physics.engine)return!1;const t=e,s=this.time.deltaTime/t;for(let o=0;o<t;o++)this._currentFrameEvent=9,this.executeCoroutines(9),this.physics.engine.step(s),this._currentFrameEvent=10,this.executeCoroutines(10);return this.physics.engine.postStep(),!0}internalOnRender(){this.isManagedExternally||(LM(this),this._currentFrameEvent=-1,eO.update(),this.renderNow(),this._currentFrameEvent=4)}internalOnAfterRender(){if(this.isVisibleToUser||this.runInBackground){for(let e=0;e<this.scripts_onAfterRender.length;e++){const t=this.scripts_onAfterRender[e];t.activeAndEnabled&&t.onAfterRender!==void 0&&(Le.Current=this,t.onAfterRender())}if(this.executeCoroutines(4),Xs(this,4),this.post_render_callbacks)for(const e in this.post_render_callbacks)this.post_render_callbacks[e]()}this._currentFrameEvent=-1,this.connection.sendBufferedMessagesNow(),this._stats&&(this._stats.end(),this.time.frameCount%150===0&&console.log(this.renderer.info.render.calls+" DrawCalls",`
|
|
782
782
|
Render:`,{...this.renderer.info.render},`
|
|
783
783
|
Memory:`,{...this.renderer.info.memory},`
|
|
784
|
-
Target Framerate: `+this.targetFrameRate)),this._dispatchReadyAfterFrame&&(this._dispatchReadyAfterFrame=!1,this.domElement.dispatchEvent(new CustomEvent("ready")),pe.dispatchCallback(me.ContextFirstFrameRendered,this))}renderNow(e){var t;if(!e&&(e=this.mainCamera,!e))return!1;if(this.handleRendererContextLost(),this._isRendering=!0,this.renderRequiredTextures(),this.renderer.toneMapping!==bd&&Hw(),this.composer&&!this.isInXR){e&&"setMainCamera"in this.composer&&((t=this.composer.passes[0])==null?void 0:t.mainCamera)!=e&&this.composer.setMainCamera(e);const s=this.renderer.getClearColor(this._tempClearColor);this._tempClearColor2.copy(s),this.renderer.setClearColor(s.convertSRGBToLinear()),this.composer.render(this.time.deltaTime),this.renderer.setClearColor(this._tempClearColor2)}else e&&(this.isInXR&&X.isMacOS()&&this.renderer.clearDepth(),this.renderer.render(this.scene,e));return this._isRendering=!1,!0}handleRendererContextLost(){this.time.frame%10&&this.renderer.getContext().isContextLost()&&this._contextRestoreTries++<100&&(console.warn("Attempting to recover WebGL context..."),this.renderer.forceContextRestore())}onHandlePaused(){const e=this.evaluatePaused();if(this._wasPaused!==e){RR&&console.log("Paused?",e,"context:"+this.alias);for(let t=0;t<this.scripts_pausedChanged.length;t++){const s=this.scripts_pausedChanged[t];s.activeAndEnabled&&s.onPausedChanged!==void 0&&(Le.Current=this,s.onPausedChanged(e,this._wasPaused))}}return this._wasPaused=e,e}evaluatePaused(){return this.isInXR?!1:this.isPaused?!0:this.runInBackground?!1:!this.isVisibleToUser}renderRequiredTextures(){if(!this.mainCamera||!this._requireDepthTexture&&!this._requireColorTexture)return;if(!this._renderTarget){if(this._renderTarget=new $s(this.domWidth,this.domHeight),this._requireDepthTexture){const s=new Lv(this.domWidth,this.domHeight);this._renderTarget.depthTexture=s}this._requireColorTexture&&(this._renderTarget.texture=new je,this._renderTarget.texture.generateMipmaps=!1,this._renderTarget.texture.minFilter=_d,this._renderTarget.texture.magFilter=_d,this._renderTarget.texture.format=fd)}const e=this._renderTarget;e.texture&&(e.texture.colorSpace=this.renderer.outputColorSpace);const t=this.renderer.getRenderTarget();this.renderer.setRenderTarget(e),this.renderer.render(this.scene,this.mainCamera),this.renderer.setRenderTarget(t)}executeCoroutines(e){var t;if(this.coroutines[e]){const o=this.coroutines[e];for(let r=0;r<o.length;r++)try{const l=o[r];if(!l.comp||l.comp.destroyed||!l.main||l.comp.enabled===!1){ER&&console.log("Removing coroutine",l.comp,l.comp.enabled),o.splice(r,1),--r;continue}const c=l.chained;if(c&&c.length>0){const u=c[c.length-1].next();if(u.done&&c.pop(),s(u)&&(l.chained||(l.chained=[]),l.chained.push(u.value)),!u.done)continue}const h=l.main.next();if(h.done===!0){o.splice(r,1),--r;continue}const d=h.value;if(s(d)){if(d.next().done)continue;l.chained||(l.chained=[]),l.chained.push(d)}else if(d instanceof Promise){const u=d;l.chained||(l.chained=[]);const p=Iw(u);(t=l.chained)==null||t.push(p);continue}}catch(l){console.error(l)}}function s(o){return!!(o&&o.next&&o.return)}}};a(Rf,"_defaultTargetFramerate",{value:90,toString(){return this.value}}),a(Rf,"_defaultWebglRendererParameters",{antialias:!0,alpha:!1,powerPreference:X.isiOS()||X.isMacOS()?"default":"high-performance",stencil:!0});let J=Rf;const Ii=C("debuglicense"),ex=[];let Ks="basic";Ii&&console.log("License Type: "+Ks);function Zs(){switch(Ks){case"pro":case"enterprise":return!0}return!1}function kc(){switch(Ks){case"indie":return!0}return!1}function Tf(){switch(Ks){case"edu":return!0}return!1}function Js(){return Zs()||kc()||Tf()}function LR(n){if(Zs()||kc()||Tf())return n(!0);ex.push(n)}function _u(n){for(const e of ex)try{e(n)}catch{}}pe.registerCallback(me.ContextRegistered,n=>{BR(n.context),DR(n.context),setTimeout(()=>UR(n.context),2e3)});let jr,Ef=!1,wu="";async function jR(){if(jr)return jr;if(Ks==="basic")try{const n="https://engine.needle.tools/licensing/check?location="+encodeURIComponent(window.location.href)+"&version="+ws+"&generator="+encodeURIComponent(jd),e=await fetch(n,{method:"GET"}).catch(t=>{Ii&&console.error("License check failed",t)});e?.status===200?(Ef=!1,Ii&&console.log("License check succeeded"),Ks="pro",_u(!0)):e?.status===403?(_u(!1),Ef=!0,wu=await e.text()):(_u(!1),Ii&&console.log("License check failed with status "+e?.status))}catch(n){_u(!1),Ii&&console.error("License check failed",n)}else Ii&&console.log('Runtime license check is skipped because license is already applied as "'+Ks+'"')}jr=jR();async function DR(n){function e(){const o=document.createElement("div");o.className="needle-forbidden",o.style.cssText=`
|
|
784
|
+
Target Framerate: `+this.targetFrameRate)),this._dispatchReadyAfterFrame&&(this._dispatchReadyAfterFrame=!1,this.domElement.dispatchEvent(new CustomEvent("ready")),pe.dispatchCallback(me.ContextFirstFrameRendered,this))}renderNow(e){var t;if(!e&&(e=this.mainCamera,!e))return!1;if(this.handleRendererContextLost(),this._isRendering=!0,this.renderRequiredTextures(),this.renderer.toneMapping!==bd&&Hw(),this.composer&&!this.isInXR){e&&"setMainCamera"in this.composer&&((t=this.composer.passes[0])==null?void 0:t.mainCamera)!=e&&this.composer.setMainCamera(e);const s=this.renderer.getClearColor(this._tempClearColor),o=this.renderer.getClearAlpha();this._tempClearColor2.copy(s),this.renderer.setClearColor(s.convertSRGBToLinear(),this.renderer.getClearAlpha()),this.composer.render(this.time.deltaTime),this.renderer.setClearColor(this._tempClearColor2,o)}else e&&(this.isInXR&&X.isMacOS()&&this.renderer.clearDepth(),this.renderer.render(this.scene,e));return this._isRendering=!1,!0}handleRendererContextLost(){this.time.frame%10&&this.renderer.getContext().isContextLost()&&this._contextRestoreTries++<100&&(console.warn("Attempting to recover WebGL context..."),this.renderer.forceContextRestore())}onHandlePaused(){const e=this.evaluatePaused();if(this._wasPaused!==e){RR&&console.log("Paused?",e,"context:"+this.alias);for(let t=0;t<this.scripts_pausedChanged.length;t++){const s=this.scripts_pausedChanged[t];s.activeAndEnabled&&s.onPausedChanged!==void 0&&(Le.Current=this,s.onPausedChanged(e,this._wasPaused))}}return this._wasPaused=e,e}evaluatePaused(){return this.isInXR?!1:this.isPaused?!0:this.runInBackground?!1:!this.isVisibleToUser}renderRequiredTextures(){if(!this.mainCamera||!this._requireDepthTexture&&!this._requireColorTexture)return;if(!this._renderTarget){if(this._renderTarget=new $s(this.domWidth,this.domHeight),this._requireDepthTexture){const s=new Lv(this.domWidth,this.domHeight);this._renderTarget.depthTexture=s}this._requireColorTexture&&(this._renderTarget.texture=new je,this._renderTarget.texture.generateMipmaps=!1,this._renderTarget.texture.minFilter=_d,this._renderTarget.texture.magFilter=_d,this._renderTarget.texture.format=fd)}const e=this._renderTarget;e.texture&&(e.texture.colorSpace=this.renderer.outputColorSpace);const t=this.renderer.getRenderTarget();this.renderer.setRenderTarget(e),this.renderer.render(this.scene,this.mainCamera),this.renderer.setRenderTarget(t)}executeCoroutines(e){var t;if(this.coroutines[e]){const o=this.coroutines[e];for(let r=0;r<o.length;r++)try{const l=o[r];if(!l.comp||l.comp.destroyed||!l.main||l.comp.enabled===!1){ER&&console.log("Removing coroutine",l.comp,l.comp.enabled),o.splice(r,1),--r;continue}const c=l.chained;if(c&&c.length>0){const u=c[c.length-1].next();if(u.done&&c.pop(),s(u)&&(l.chained||(l.chained=[]),l.chained.push(u.value)),!u.done)continue}const h=l.main.next();if(h.done===!0){o.splice(r,1),--r;continue}const d=h.value;if(s(d)){if(d.next().done)continue;l.chained||(l.chained=[]),l.chained.push(d)}else if(d instanceof Promise){const u=d;l.chained||(l.chained=[]);const p=Iw(u);(t=l.chained)==null||t.push(p);continue}}catch(l){console.error(l)}}function s(o){return!!(o&&o.next&&o.return)}}};a(Rf,"_defaultTargetFramerate",{value:90,toString(){return this.value}}),a(Rf,"_defaultWebglRendererParameters",{antialias:!0,alpha:!1,powerPreference:X.isiOS()||X.isMacOS()?"default":"high-performance",stencil:!0});let J=Rf;const Ii=C("debuglicense"),ex=[];let Ks="basic";Ii&&console.log("License Type: "+Ks);function Zs(){switch(Ks){case"pro":case"enterprise":return!0}return!1}function kc(){switch(Ks){case"indie":return!0}return!1}function Tf(){switch(Ks){case"edu":return!0}return!1}function Js(){return Zs()||kc()||Tf()}function LR(n){if(Zs()||kc()||Tf())return n(!0);ex.push(n)}function _u(n){for(const e of ex)try{e(n)}catch{}}pe.registerCallback(me.ContextRegistered,n=>{BR(n.context),DR(n.context),setTimeout(()=>UR(n.context),2e3)});let jr,Ef=!1,wu="";async function jR(){if(jr)return jr;if(Ks==="basic")try{const n="https://engine.needle.tools/licensing/check?location="+encodeURIComponent(window.location.href)+"&version="+ws+"&generator="+encodeURIComponent(jd),e=await fetch(n,{method:"GET"}).catch(t=>{Ii&&console.error("License check failed",t)});e?.status===200?(Ef=!1,Ii&&console.log("License check succeeded"),Ks="pro",_u(!0)):e?.status===403?(_u(!1),Ef=!0,wu=await e.text()):(_u(!1),Ii&&console.log("License check failed with status "+e?.status))}catch(n){_u(!1),Ii&&console.error("License check failed",n)}else Ii&&console.log('Runtime license check is skipped because license is already applied as "'+Ks+'"')}jr=jR();async function DR(n){function e(){const o=document.createElement("div");o.className="needle-forbidden",o.style.cssText=`
|
|
785
785
|
position: fixed;
|
|
786
786
|
top: 0;
|
|
787
787
|
left: 0;
|
|
@@ -936,7 +936,7 @@ ${t.path}! : AssetReference;
|
|
|
936
936
|
Could not find method ${d.method} on object ${p.name}. Please rename ${d.method} to ${y}?
|
|
937
937
|
`,p[y],`
|
|
938
938
|
in script: `,p),be("EventList methods must start with lowercase letter, see console for details");return}else console.warn(`EventList method:
|
|
939
|
-
Could not find method ${d.method} on object ${p.name}`,p,typeof p[d.method])};if(typeof p[d.method]!="function"){let y=!1,v=p;for(;v;){const b=Object.getOwnPropertyDescriptor(v,d.method);if(b&&(b.writable===!0||b.set)){y=!0;break}v=Object.getPrototypeOf(v)}!y&&(F()||wt)&&f()}}if(p){let f=d.argument;if(f!==void 0?f=u(f):d.arguments!==void 0&&(f=d.arguments.map(u)),!p[d.method])console.warn(`EventList method not found: "${d.method}" on ${p?.name}`);else{f!==void 0&&!Array.isArray(f)&&(f=[f]);const y=new Un(p,d.method,f,d.enabled);l.push(y)}}else F()&&console.warn("[Debug] EventList: Could not find event listener in scene",d,t.object,e)}const c=new xe(l);wt&&console.log(c);const h=t.target;return h!==void 0&&t.path!==void 0&&c.setEventTarget(t.path,h),c}}}const CT=new ST,Eu=new WeakMap,PT=je.prototype.clone;je.prototype.clone=function(){const n=PT.call(this);return Eu.has(n)||Eu.set(n,this),n};class Cx extends es{constructor(){super([Ac,$s])}onSerialize(e,t){}onDeserialize(e,t){if(e instanceof je&&t.type===Ac){let s=e;Eu.has(s)&&(s=Eu.get(s)),s.isRenderTargetTexture=!0,s.flipY=!0,s.offset.y=1,s.repeat.y=-1,s.needsUpdate=!0,s.mipmaps=[],s instanceof XC&&(s.isCompressedTexture=!1,s.format=fd);const o=new Ac(s.image.width,s.image.height,{colorSpace:On});return o.texture=s,o}}}new Cx;class Px extends es{constructor(){super([URL])}onSerialize(e,t){return null}onDeserialize(e,t){if(typeof e=="string"&&e.length>0)return yo(t.gltfId,e)}}new Px;var OT=Object.defineProperty,kT=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&OT(e,t,o),o};class Ya extends I{awake(){ii.createIfNoneExists(this.context)}onEnable(){var e;(e=ii.get(this.context))==null||e.register(this)}onDisable(){var e;(e=ii.get(this.context))==null||e.unregister(this)}}class ji extends Ya{constructor(){super(...arguments),a(this,"targets",null),a(this,"raycastHits",[]),a(this,"ignoreSkinnedMeshes",!1)}start(){this.targets=[this.gameObject]}performRaycast(e=null){if(!this.targets)return null;e??(e=new Qs),e.targets=this.targets,e.results=this.raycastHits,e.useAcceleratedRaycast=!0;const t=e.testObject;this.ignoreSkinnedMeshes&&(e.testObject=o=>o instanceof Pn?"continue in children":t?t(o):!0);const s=this.context.physics.raycast(e);return e.testObject=t,s}}kT([m()],ji.prototype,"ignoreSkinnedMeshes");class Au extends ji{constructor(){super(),this.ignoreSkinnedMeshes=!0}}const Ox=class yC extends Ya{performRaycast(e){if(!ne.active||!yC.allow||!(e!=null&&e.ray))return null;const t=e.ray.origin;return this.context.physics.sphereOverlap(t,.015,!1,!0)}};a(Ox,"allow",!0);let Dc=Ox;class zf{static getObject(e){const t=e[Mi];return t&&(t.isComponent===!0?e=t.gameObject:e=t),e}static isInteractable(e,t){if(t&&(t.canvasGroup=void 0,t.graphic=void 0),e==null||!e.visible||(e=this.getObject(e),!e.visible))return!1;const s=this.tryFindCanvasGroup(e);if(s?.isCanvasGroup===!0&&(t&&(t.canvasGroup=s),s.blocksRaycasts===!1||s.interactable===!1))return!1;const o=Ar(e,r=>{if(r.isGraphic===!0)return r},!1);return t&&o?.isGraphic===!0&&(t.graphic=o),!(o?.raycastTarget===!1||o?.layer===2)}static tryFindCanvasGroup(e){if(!e)return null;const t=Ar(e,s=>{const o=s;if(o.blocksRaycasts!==void 0&&o.interactable!==void 0)return o},!1);return t!==void 0?t:this.tryFindCanvasGroup(e.parent)}}function Nf(n){return n[Mi]||(n.parent?Nf(n.parent):null)}function MT(n){return n.isUI===!0||typeof n[Mi]=="object"}function Iu(n,e){if(!n)return;const t=n.material;if(t?.isMaterial===!0){const s=n.parent;s&&s.isText,t.side=e.doubleSided??!0?Pi:fo,t.shadowSide=e.doubleSided?Pi:fo,n.castShadow=e.castShadows?e.castShadows:!1,n.receiveShadow=e.receiveShadows?e.receiveShadows:!1}for(const s of n.children)Iu(s,e)}function Ka(n,e,t){n[e]===void 0&&console.warn("Field",e,"is undefined on",n);const s=Proxy.revocable(n[e],{set(l,c,h,d){const u=l[c],p=Reflect.set(l,c,h,d);return t(h,u),p}}),o=s.revoke,r=n[e];return s.revoke=()=>{n[e]=r,o()},n[e]=s.proxy,s}const kx=Symbol("Scheduled action");function RT(n,e,t=Oe.OnBeforeRender){let s=n[kx];s||(s=n[kx]={});const o=e.name;s[t]||(s[t]={});const r=s[t];if(r[o])return;function*l(){e?.call(n),r[o]=null}const c=n.startCoroutine(l(),t);r[o]=c}const Eo=C("debugeventsystem");var Wf=(n=>(n.BeforeHandleInput="BeforeHandleInput",n.AfterHandleInput="AfterHandleInput",n))(Wf||{});vx(n=>{ii.createIfNoneExists(n)});class ii extends I{constructor(){super(...arguments),a(this,"raycaster",[]),a(this,"pressedByID",new Map),a(this,"hoveredByID",new Map),a(this,"onPointerEvent",e=>{if(e===void 0||e.propagationStopped||e.defaultPrevented||e.used)return;const t=new cd(this.context.input,e);this._currentPointerEventName=e.type,t.inputSource=this.context.input,t.isClick=e.isClick,t.isDoubleClick=e.isDoubleClick,t.isDown=e.type==Be.PointerDown,t.isUp=e.type==Be.PointerUp,t.isPressed=this.context.input.getPointerPressed(e.pointerId),Eo&&(t.isDown?console.log("DOWN",t.pointerId):t.isUp&&console.log("UP",t.pointerId),t.isClick&&console.log("CLICK",t.pointerId));const s=new Qs;e.hasRay?s.ray=e.ray:s.screenPoint=this.context.input.getPointerPositionRC(e.pointerId);const o=this.performRaycast(s);if(o){for(const l of o)l.event=e,e.intersections.push(l);e.origin.onPointerHits&&e.origin.onPointerHits({sender:this,event:e,hits:o})}Eo&&t.isClick&&De("EventSystem: "+t.pointerId+" - "+this.context.time.frame+" - Up:"+t.isUp+", Down:"+t.isDown);const r={sender:this,args:t,hasActiveUI:this.currentActiveMeshUIComponents.length>0};this.dispatchEvent(new CustomEvent("BeforeHandleInput",{detail:r})),this.handleIntersections(o,t),this.dispatchEvent(new CustomEvent("AfterHandleInput",{detail:r}))}),a(this,"_sortedHits",[]),a(this,"_testObjectsCache",new Map),a(this,"_currentlyActiveRaycaster",null),a(this,"_currentPointerEventName",null),a(this,"shouldRaycastObject",e=>{var t;const s=e&&"getComponent"in e?e.getComponent(Ya):null;if(s&&s!=this._currentlyActiveRaycaster)return!1;let o=null;if(MT(e)&&(o=(t=e[Mi])==null?void 0:t.gameObject),this._testObjectsCache.has(e)||o&&this._testObjectsCache.has(o))return this._testObjectsCache.get(e)===!1?"continue in children":!0;{let r=Mu(e,this._currentPointerEventName);if(!r&&o&&(r=Mu(o,this._currentPointerEventName)),r){this._testObjectsCache.set(e,!0);for(const l of e.children)this.shouldRaycastObject_AddToYesCache(l);return!0}return this._testObjectsCache.set(e,!1),"continue in children"}}),a(this,"_sortingBuffer",[]),a(this,"_noDepthTestingResults",[]),a(this,"out",{}),a(this,"_capturedPointer",{}),a(this,"pointerEnterSymbol",Symbol("pointerEnter")),a(this,"pointerExitSymbol",Symbol("pointerExit")),a(this,"currentActiveMeshUIComponents",[])}static ensureUpdateMeshUI(e,t,s=!1){Ao.update(e,t,s)}static markUIDirty(e){Ao.markDirty()}static createIfNoneExists(e){e.scene.getComponent(ii)||e.scene.addComponent(ii)}static get(e){return this.createIfNoneExists(e),e.scene.getComponent(ii)}static get instance(){return this.get(J.Current)}register(e){var t;e&&this.raycaster&&!this.raycaster.includes(e)&&((t=this.raycaster)==null||t.push(e))}unregister(e){var t,s;const o=(t=this.raycaster)==null?void 0:t.indexOf(e);o!==void 0&&o!==-1&&((s=this.raycaster)==null||s.splice(o,1))}get hasActiveUI(){return this.currentActiveMeshUIComponents.length>0}get isHoveringObjects(){return this.hoveredByID.size>0}awake(){this.gameObject!==this.context.scene&&(console.debug(`[Needle Engine] EventSystem is only allowed on the scene root. Disabling EventSystem on '${this.gameObject.name}'`),this.enabled=!1)}start(){this.context.scene.getComponent(Ya)||this.context.scene.addComponent(ji)}onEnable(){this.context.input.addEventListener(Be.PointerDown,this.onPointerEvent),this.context.input.addEventListener(Be.PointerUp,this.onPointerEvent),this.context.input.addEventListener(Be.PointerMove,this.onPointerEvent)}onDisable(){this.context.input.removeEventListener(Be.PointerDown,this.onPointerEvent),this.context.input.removeEventListener(Be.PointerUp,this.onPointerEvent),this.context.input.removeEventListener(Be.PointerMove,this.onPointerEvent)}onBeforeRender(){this.resetMeshUIStates()}shouldRaycastObject_AddToYesCache(e){this._testObjectsCache.set(e,!0);for(const t of e.children)this.shouldRaycastObject_AddToYesCache(t)}performRaycast(e){if(!this.raycaster)return null;this._testObjectsCache.clear(),this._sortedHits.length=0,e||(e=new Qs),e.testObject=this.shouldRaycastObject;for(const t of this.raycaster){if(!t.activeAndEnabled)continue;this._currentlyActiveRaycaster=t;const s=t.performRaycast(e);this._currentlyActiveRaycaster=null,s&&s.length>0&&this._sortedHits.push(...s)}return this._sortedHits.sort((t,s)=>t.distance-s.distance),this._sortedHits}assignHitInformation(e,t){t?(e.intersection=t,e.point=t.point,e.normal=t.normal,e.face=t.face,e.distance=t.distance,e.instanceId=t.instanceId):(e.intersection=void 0,e.point=void 0,e.normal=void 0,e.face=void 0,e.distance=void 0,e.instanceId=void 0)}handleIntersections(e,t){var s;if(e!=null&&e.length){e=this.sortCandidates(e);for(const r of e){if(t.event.immediatePropagationStopped)return!1;if(this.assignHitInformation(t,r),this.handleEventOnObject(r.object,t))return!0}}this.assignHitInformation(t,e?.[0]),this.invokePointerCapture(t);const o=this.hoveredByID.get(t.pointerId);return o&&this.propagatePointerExit(o.obj,o.data,null),this.hoveredByID.delete(t.pointerId),t.isUp&&((s=this.pressedByID.get(t.pointerId))==null||s.handlers.forEach(r=>this.invokeOnPointerUp(t,r)),this.pressedByID.delete(t.pointerId)),!1}sortCandidates(e){this._sortingBuffer.length=0,this._noDepthTestingResults.length=0;for(let t=0;t<e.length;t++){const s=e[t],o=s.object;if(o.material&&o.material.depthTest===!1){this._noDepthTestingResults.push(s);continue}this._sortingBuffer.push(s)}for(const t of this._sortingBuffer)this._noDepthTestingResults.push(t);return this._noDepthTestingResults}handleEventOnObject(e,t){if(!this.testIsVisible(e))return t.isClick&&Eo&&console.log("not allowed",e),!1;if(t.pointerId===void 0)return Eo&&console.error("Event without pointer can't be handled",t),!1;t.object=e;const s=e.parent,o=t.isClick??!1;let r=null;if(s&&s.isUI){const d=(t.isPressed||t.isClick)??!1;if(s[Mi]){const u=s[Mi].gameObject;if(u){if(!zf.isInteractable(u,this.out))return!1;r=this.out.canvasGroup??null,this.handleMeshUIIntersection(e,d),e=u}}}o&&Eo&&console.log(this.context.time.frame,e);const l=this.hoveredByID.get(t.pointerId),c=l?.obj;c!==e&&c&&this.propagatePointerExit(c,l.data,e);const h=this.hoveredByID.get(t.pointerId);if(h?(h.obj=e,h.data=t):this.hoveredByID.set(t.pointerId,{obj:e,data:t}),t.isDown){const d=this.pressedByID.get(t.pointerId);d?(d.obj=e,d.data=t):this.pressedByID.set(t.pointerId,{obj:e,data:t,handlers:new Set})}return(r===null||r.interactable)&&this.handleMainInteraction(e,t,c??null),!0}propagate(e,t){for(;e;)P.foreachComponent(e,s=>{t(s)},!1),e=e.parent}handleMainInteraction(e,t,s){const o=this.pressedByID.get(t.pointerId),r=s!==e;let l=!0;switch(t.event.pointerType){case"mouse":case"touch":const c=this.context.input.getPointerPositionLastFrame(t.pointerId),h=this.context.input.getPointerPosition(t.pointerId);l=c&&!W.approximately(c,h);break}this.propagate(e,c=>{var h;const d=c;d.interactable!==!1&&(!d.activeAndEnabled||!d.enabled||(d.onPointerEnter&&r&&this.handlePointerEnter(d,t),t.isDown&&d.onPointerDown&&(d.onPointerDown(t),o?.handlers.add(d),this.handlePointerCapture(t,d)),d.onPointerMove&&(l&&d.onPointerMove(t),this.handlePointerCapture(t,d)),t.isUp&&(d.onPointerUp&&(this.invokeOnPointerUp(t,d),o?.handlers.delete(d)),d.onPointerExit&&((h=t.event)==null?void 0:h.pointerType)===Ud.Touch&&(this.handlePointerExit(d,t),this.hoveredByID.delete(t.pointerId))),t.isClick&&d.onPointerClick&&d.onPointerClick(t)))}),t.isUp&&(o?.handlers.forEach(c=>{this.invokeOnPointerUp(t,c)}),this.pressedByID.delete(t.pointerId))}propagatePointerExit(e,t,s){this.propagate(e,o=>{if(!o.gameObject||o.destroyed)return;const r=o;if(r.onPointerExit||r.onPointerEnter){if(s&&this.isChild(s,o.gameObject))return;this.handlePointerExit(r,t)}})}invokeOnPointerUp(e,t){var s;(s=t.onPointerUp)==null||s.call(t,e),this.releasePointerCapture(e,t)}handlePointerEnter(e,t){e.onPointerEnter&&this.updatePointerState(e,t.pointerId,this.pointerEnterSymbol,!0)&&e.onPointerEnter(t),this.updatePointerState(e,t.pointerId,this.pointerExitSymbol,!1)}handlePointerExit(e,t){e.onPointerExit&&this.updatePointerState(e,t.pointerId,this.pointerExitSymbol,!0)&&e.onPointerExit(t),this.updatePointerState(e,t.pointerId,this.pointerEnterSymbol,!1)}updatePointerState(e,t,s,o){let r=e[s];if(o)return r&&r.includes(t)?!1:(r=r||[],r.push(t),e[s]=r,!0);{if(!r||!r.includes(t))return!1;const l=r.indexOf(t);return l!==-1&&r.splice(l,1),!0}}handlePointerCapture(e,t){if(e.z__pointer_ctured){e.z__pointer_ctured=!1;const s=e.pointerId;if(t.onPointerMove){const o=this._capturedPointer[s]||[];o.push(t),this._capturedPointer[s]=o}else F()&&!t.z__warned_no_pointermove&&(t.z__warned_no_pointermove=!0,console.warn("PointerCapture was requested but the component doesn't implement onPointerMove. It will not receive any pointer events"))}else e.z__pointer_cture_rleased&&(e.z__pointer_cture_rleased=!1,this.releasePointerCapture(e,t))}releasePointerCapture(e,t){const s=e.pointerId;if(this._capturedPointer[s]){const o=this._capturedPointer[s].indexOf(t);o!==-1&&(this._capturedPointer[s].splice(o,1),Eo&&console.log("released pointer capture",s,t,this._capturedPointer))}}invokePointerCapture(e){var t;if(e.event.type===Be.PointerMove){const s=e.pointerId,o=this._capturedPointer[s];if(o){Eo&&console.log("Captured",s,o);for(let r=0;r<o.length;r++){const l=o[r];if(l.destroyed){o.splice(r,1),r--;continue}(t=l.onPointerMove)==null||t.call(l,e)}}}}isChild(e,t){return!e||!t?!1:e===t?!0:e.parent?this.isChild(e.parent,t):!1}handleMeshUiObjectWithoutShadowDom(e,t){return!e||!e.isUI?!0:this.handleMeshUIIntersection(e,t)}handleMeshUIIntersection(e,t){const s=Ao.updateState(e,t);return s&&this.currentActiveMeshUIComponents.push(s),s!==null}resetMeshUIStates(){if(this.context.input.getPointerPressedCount()>0&&Ao.resetLastSelected(),!(!this.currentActiveMeshUIComponents||this.currentActiveMeshUIComponents.length<=0)){for(let e=0;e<this.currentActiveMeshUIComponents.length;e++){const t=this.currentActiveMeshUIComponents[e];Ao.resetState(t)}this.currentActiveMeshUIComponents.length=0}}testIsVisible(e){return e?P.isActiveSelf(e)?this.testIsVisible(e.parent):!1:!0}}class Ao{static markDirty(){this.needsUpdate=!0}static update(e,t,s=!1){if(s){e.update();return}const o=t.time.frameCount;for(const r of this.lastUpdateFrame)if(r.context===t){if(o===r.frame)return;r.frame=o;let l=this.needsUpdate||o<1;r.nextUpdate<=o&&(l=!0),l&&(Eo&&console.log("Update threemeshui"),this.needsUpdate=!1,r.nextUpdate=o+60,e.update());return}this.lastUpdateFrame=[{context:t,frame:o,nextUpdate:o+60}],e.update(),this.needsUpdate=!1}static updateState(e,t){let s=null;if(e&&(s=this.findBlockOrTextInParent(e),s&&s!==this.lastSelected)){if(s.interactable===!1)return null;this.needsUpdate=!0}return s}static resetLastSelected(){const e=this.lastSelected;e&&(this.lastSelected=null,this.resetState(e))}static resetState(e){e&&(this.needsUpdate=!0)}static findBlockOrTextInParent(e){return e?e.isBlock||e.isText?e:this.findBlockOrTextInParent(e.parent):null}}a(Ao,"lastSelected",null),a(Ao,"lastUpdateFrame",[]),a(Ao,"needsUpdate",!1);var TT=Object.defineProperty,Ue=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&TT(e,t,o),o};const is=C("debugorbit"),Vf=C("freecam"),Bc=C("debugcamerafit"),Lu=C("smoothcam"),ET={LEFT:"",UP:"",RIGHT:"",BOTTOM:""};let $f;class Fc extends CustomEvent{constructor(e,t){super("target-reached",{detail:{controls:e,type:t}})}}class _e extends I{constructor(){super(...arguments),a(this,"autoTarget",!0),a(this,"autoFit",!1),a(this,"enableRotate",!0),a(this,"autoRotate",!1),a(this,"autoRotateSpeed",1),a(this,"minAzimuthAngle",1/0),a(this,"maxAzimuthAngle",1/0),a(this,"minPolarAngle",0),a(this,"maxPolarAngle",Math.PI),a(this,"enableKeys",!1),a(this,"enableDamping",!0),a(this,"dampingFactor",.1),a(this,"enableZoom",!0),a(this,"minZoom",0),a(this,"maxZoom",1/0),a(this,"zoomSpeed",1),a(this,"zoomToCursor",!1),a(this,"enablePan",!0),a(this,"lookAtConstraint",null),a(this,"lookAtConstraint01",1),a(this,"allowInterrupt",!0),a(this,"middleClickToFocus",!0),a(this,"doubleClickToFocus",!0),a(this,"clickBackgroundToFitScene",2),a(this,"debugLog",!1),a(this,"targetLerpDuration",1),a(this,"_controls",null),a(this,"_cameraObject",null),a(this,"_lookTargetLerpActive",!1),a(this,"_lookTargetStartPosition",new S),a(this,"_lookTargetEndPosition",new S),a(this,"_lookTargetLerp01",0),a(this,"_lookTargetLerpDuration",0),a(this,"_cameraLerpActive",!1),a(this,"_cameraStartPosition",new S),a(this,"_cameraEndPosition",new S),a(this,"_cameraLerp01",0),a(this,"_cameraLerpDuration",0),a(this,"_fovLerpActive",!1),a(this,"_fovLerpStartValue",0),a(this,"_fovLerpEndValue",0),a(this,"_fovLerp01",0),a(this,"_fovLerpDuration",0),a(this,"_inputs",0),a(this,"_enableTime",0),a(this,"_startedListeningToKeyEvents",!1),a(this,"_eventSystem"),a(this,"_afterHandleInputFn"),a(this,"_camera",null),a(this,"_syncedTransform"),a(this,"_didSetTarget",0),a(this,"targetElement",null),a(this,"_activePointerEvents"),a(this,"_lastTimeClickOnBackground",-1),a(this,"_clickOnBackgroundCount",0),a(this,"_onPointerDown",e=>{this._activePointerEvents.push(e)}),a(this,"_onPointerDownLate",e=>{e.used&&this._controls&&(this._controls.enabled=!1)}),a(this,"_onPointerUp",e=>{for(let t=this._activePointerEvents.length-1;t>=0;t--){const s=this._activePointerEvents[t];if(s.pointerId===e.pointerId&&s.button===e.button){this._activePointerEvents.splice(t,1);break}}if(this.clickBackgroundToFitScene>0&&e.isClick&&e.button===0){if(e.hasRay||e.intersections.push(...this.context.physics.raycast()),e.intersections.length<=0){const t=this.context.time.time-this._lastTimeClickOnBackground;this._lastTimeClickOnBackground=this.context.time.time,this.clickBackgroundToFitScene<=1||t<this.clickBackgroundToFitScene*.15?(this._clickOnBackgroundCount+=1,this._clickOnBackgroundCount>=this.clickBackgroundToFitScene-1&&this.fitCamera(this.context.scene.children,{immediate:!1})):this._clickOnBackgroundCount=0}is&&console.log(this.clickBackgroundToFitScene,e.intersections.length,this._clickOnBackgroundCount)}}),a(this,"_onPointerUpLate",e=>{this.doubleClickToFocus&&e.isDoubleClick&&!e.used&&this.setTargetFromRaycast()}),a(this,"_orbitStartAngle",0),a(this,"onControlsChangeStarted",()=>{this._controls&&(this._orbitStartAngle=this._controls.getAzimuthalAngle()+this._controls.getPolarAngle()),this._syncedTransform&&this._syncedTransform.requestOwnership()}),a(this,"onControlsChangeEnded",()=>{if(this._controls&&this.autoTarget){const e=this._controls.getAzimuthalAngle()+this._controls.getPolarAngle()-this._orbitStartAngle;Math.abs(e)<.01?(is&&console.debug("OrbitControls: No movement detected, updating target now"),this.updateTargetNow()):is&&console.debug("OrbitControls: Movement detected",e)}}),a(this,"_shouldDisable",!1),a(this,"__onPreRender",()=>{const e=this.context.pre_render_callbacks.indexOf(this.__onPreRender);e>=0&&this.context.pre_render_callbacks.splice(e,1),this.autoFit&&(this.autoFit=!1,this.fitCamera({centerCamera:"y",immediate:!0,objects:this.scene.children}))}),a(this,"_haveAttachedKeyboardEvents",!1)}get isCameraController(){return!0}get controls(){return this._controls}get controllerObject(){return this._cameraObject}onStartInteraction(e){var t;(t=this.controls)==null||t.addEventListener("start",e)}get targetLerpSpeed(){return 5}set targetLerpSpeed(e){this.targetLerpDuration=1/e}awake(){is&&console.debug("OrbitControls",this),this._didSetTarget=0,this._startedListeningToKeyEvents=!1}start(){this._eventSystem=ii.get(this.context)??void 0,this._eventSystem&&(this._afterHandleInputFn=this.afterHandleInput.bind(this),this._eventSystem.addEventListener(Wf.AfterHandleInput,this._afterHandleInputFn))}onDestroy(){var e,t;(e=this._controls)==null||e.dispose(),(t=this._eventSystem)==null||t.removeEventListener(Wf.AfterHandleInput,this._afterHandleInputFn)}onEnable(){this._didSetTarget=0,this._enableTime=this.context.time.time;const e=P.getComponent(this.gameObject,ci);this._camera=e;let t=e?.threeCamera;if(!t&&this.gameObject instanceof we&&(t=this.gameObject),t&&rg(t,this,!0),!this._controls&&t instanceof E){this._cameraObject=t;const s=this.targetElement??this.context.renderer.domElement,o=t?.quaternion.clone();this._controls=new $v(t,s),t?.quaternion.copy(o),$f===void 0&&($f={...this._controls.keys});const r=ee(t),l=this.gameObject.worldForward,c=r.clone().sub(l.multiplyScalar(2.5));this._controls.target.copy(c)}if(this._controls)if(Vf&&(this.enablePan=!0,this.enableZoom=!0,this.middleClickToFocus=!0,X.isMobileDevice()&&(this.doubleClickToFocus=!0)),this._controls.addEventListener("start",this.onControlsChangeStarted),this._controls.addEventListener("end",this.onControlsChangeEnded),!this._startedListeningToKeyEvents&&this.enableKeys)this._startedListeningToKeyEvents=!0,this._controls.listenToKeyEvents(this.context.domElement);else try{this._controls.stopListenToKeyEvents()}catch{}this._syncedTransform=P.getComponent(this.gameObject,sn)??void 0,this.context.pre_render_callbacks.push(this.__onPreRender),this._activePointerEvents=[],this.context.input.addEventListener("pointerdown",this._onPointerDown,{queue:oi.Early}),this.context.input.addEventListener("pointerdown",this._onPointerDownLate,{queue:oi.Late}),this.context.input.addEventListener("pointerup",this._onPointerUp,{queue:oi.Early}),this.context.input.addEventListener("pointerup",this._onPointerUpLate,{queue:oi.Late})}onDisable(){var e;if((e=this._camera)!=null&&e.threeCamera&&rg(this._camera.threeCamera,this,!1),this._controls){this._controls.enabled=!1,this._controls.autoRotate=!1,this._controls.removeEventListener("start",this.onControlsChangeStarted),this._controls.removeEventListener("end",this.onControlsChangeEnded);try{this._controls.stopListenToKeyEvents()}catch{}this._startedListeningToKeyEvents=!1}this._activePointerEvents.length=0,this.context.input.removeEventListener("pointerdown",this._onPointerDown),this.context.input.removeEventListener("pointerdown",this._onPointerDownLate),this.context.input.removeEventListener("pointerup",this._onPointerUp),this.context.input.removeEventListener("pointerup",this._onPointerUpLate)}updateTargetNow(){var e,t,s;const o=new po((e=this._cameraObject)==null?void 0:e.worldPosition,(t=this._cameraObject)==null?void 0:t.worldForward.multiplyScalar(-1)),r=this.context.physics.raycastFromRay(o),l=r.length>0?r[0]:void 0;l&&l.distance>this.minZoom&&l.distance<this.maxZoom&&(is&&$.DrawWireSphere(l.point,.1,16711680,2),(s=this._controls)==null||s.target.copy(r[0].point))}afterHandleInput(e){e.detail.args.pointerId===0&&(e.detail.args.isDown?this._controls&&this._eventSystem&&(this._shouldDisable=this._eventSystem.hasActiveUI):(!e.detail.args.isPressed||e.detail.args.isUp)&&(this._shouldDisable=!1))}onBeforeRender(){var e,t,s,o;if(!!this._controls){if(this._cameraObject!==this.context.mainCamera){this._controls.enabled=!1;return}if(this._controls.enabled=!0,(this.context.input.getPointerDown(1)||this.context.input.getPointerDown(2)||this.context.input.mouseWheelChanged||this.context.input.getPointerPressed(0)&&(e=this.context.input.getPointerPositionDelta(0))!=null&&e.length())&&(this._inputs+=1),this._inputs>0&&this.allowInterrupt&&(this.enableRotate&&(this.autoRotate=!1),this._cameraLerpActive=!1,this._lookTargetLerpActive=!1),this._inputs=0,this.autoTarget&&this._didSetTarget++===0){const r=P.getComponent(this.gameObject,ci);if(r&&!this.setLookTargetFromConstraint()){this.debugLog&&console.log("NO TARGET");const l=ee(r.threeCamera),c=Math.max(.01,l.length()),h=new S(0,0,-c).applyMatrix4(r.threeCamera.matrixWorld);is&&$.DrawLine(l,h,5592575,10),this.setLookTargetPosition(h,!0)}if(!this.setLookTargetFromConstraint()){const l=new Qs;l.screenPoint=new re(0,0),l.lineThreshold=.1;const c=this.context.physics.raycast(l);c.length>0&&this.setLookTargetPosition(c[0].point,!0),Bc&&console.log("OrbitControls hits",...c)}}if(this.middleClickToFocus&&this.context.input.getPointerClicked(1)&&this.setTargetFromRaycast(),this._lookTargetLerpActive||this._cameraLerpActive||this._fovLerpActive){if(this._cameraLerpActive&&this._cameraObject)if(this._cameraLerp01+=this.context.time.deltaTime/this._cameraLerpDuration,this._cameraLerp01>=1)this._cameraObject.position.copy(this._cameraEndPosition),this._cameraLerpActive=!1,this.dispatchEvent(new Fc(this,"camera"));else{const r=W.easeInOutCubic(this._cameraLerp01);this._cameraObject.position.lerpVectors(this._cameraStartPosition,this._cameraEndPosition,r)}if(this._lookTargetLerpActive)if(this._lookTargetLerp01+=this.context.time.deltaTime/this._lookTargetLerpDuration,this._lookTargetLerp01>=1)this._controls.target.copy(this._lookTargetEndPosition),this._lookTargetLerpActive=!1,this.dispatchEvent(new Fc(this,"lookat"));else{const r=W.easeInOutCubic(this._lookTargetLerp01);this._controls.target.lerpVectors(this._lookTargetStartPosition,this._lookTargetEndPosition,r)}if(this._fovLerpActive&&this._cameraObject){const r=this._cameraObject;if(this._fovLerp01+=this.context.time.deltaTime/this._fovLerpDuration,this._fovLerp01>=1)r.fov=this._fovLerpEndValue,this._fovLerpActive=!1;else{const l=W.easeInOutCubic(this._fovLerp01);r.fov=W.lerp(this._fovLerpStartValue,this._fovLerpEndValue,l)}r.updateProjectionMatrix()}}if(this._controls){if(this.debugLog&&(this._controls.domElement=this.context.renderer.domElement),this._controls.enabled=!this._shouldDisable&&this._camera===this.context.mainCameraComponent&&!this.context.isInXR&&!this._activePointerEvents.some(r=>r.used),this._controls.keys=this.enableKeys?$f:ET,this._controls.autoRotate=this.autoRotate,this._controls.autoRotateSpeed=this.autoRotateSpeed,this._controls.enableZoom=this.enableZoom,this._controls.zoomSpeed=this.zoomSpeed,this._controls.zoomToCursor=this.zoomToCursor,this._controls.enableDamping=this.enableDamping,this._controls.dampingFactor=this.dampingFactor,this._controls.enablePan=this.enablePan,this._controls.enableRotate=this.enableRotate,this._controls.minAzimuthAngle=this.minAzimuthAngle,this._controls.maxAzimuthAngle=this.maxAzimuthAngle,this._controls.minPolarAngle=this.minPolarAngle,this._controls.maxPolarAngle=this.maxPolarAngle,Vf||(((s=(t=this._camera)==null?void 0:t.threeCamera)==null?void 0:s.type)==="PerspectiveCamera"?(this._controls.minDistance=this.minZoom,this._controls.maxDistance=this.maxZoom,this._controls.minZoom=0,this._controls.maxZoom=1/0):(this._controls.minDistance=0,this._controls.maxDistance=1/0,this._controls.minZoom=this.minZoom,this._controls.maxZoom=this.maxZoom)),typeof Lu=="number"||Lu===!0){this._controls.enableDamping=!0;const r=typeof Lu=="number"?Lu:.99;this._controls.dampingFactor=Math.max(.001,1-Math.min(1,r))}this.allowInterrupt||(this._lookTargetLerpActive&&(this._controls.enablePan=!1),this._cameraLerpActive&&(this._controls.enableRotate=!1,this._controls.autoRotate=!1),(this._lookTargetLerpActive||this._cameraLerpActive)&&(this._controls.enableZoom=!1)),this.context.isInXR||(!Vf&&(o=this.lookAtConstraint)!=null&&o.locked&&this.setLookTargetFromConstraint(0,this.lookAtConstraint01),this._controls.update(this.context.time.deltaTime),is&&$.DrawWireSphere(this._controls.target,.1,65280))}}}setCameraAndLookTarget(e,t=!1){if(!e)return(F()||is)&&console.warn("[OrbitControls] setCameraAndLookTarget target is null"),!1;if(!(e instanceof E)&&!(e instanceof ci))return(F()||is)&&console.warn("[OrbitControls] setCameraAndLookTarget target is not an Object3D or Camera"),!1;e instanceof ci&&(e=e.gameObject);const s=e.worldPosition,o=e.worldForward;e instanceof QC&&(is&&console.debug("[OrbitControls] setCameraAndLookTarget flip forward direction for camera"),o.multiplyScalar(-1));const r=new po(s,o);return is&&$.DrawRay(r.origin,r.direction,16711680,10),this.setTargetFromRaycast(r,t)||this.setLookTargetPosition(r.at(2,q()),t),this.setCameraTargetPosition(s,t),!0}setCameraTargetPosition(e,t=!1){var s;e&&(e instanceof E&&(e=ee(e)),this._cameraEndPosition||(this._cameraEndPosition=new S),this._cameraEndPosition.copy(e),t===!0?(this._cameraLerpActive=!1,this._cameraObject&&this._cameraObject.position.copy(this._cameraEndPosition)):this._cameraObject&&(this._cameraLerpActive=!0,this._cameraLerp01=0,this._cameraStartPosition.copy((s=this._cameraObject)==null?void 0:s.position),typeof t=="number"?this._cameraLerpDuration=t:this._cameraLerpDuration=this.targetLerpDuration))}get cameraLerpActive(){return this._cameraLerpActive}stopCameraLerp(){this._cameraLerpActive=!1}setFieldOfView(e,t=!1){var s;if(!this._controls||typeof e!="number")return;const o=(s=this._camera)==null?void 0:s.threeCamera;o&&(t===!0?o.fov=e:(this._fovLerpActive=!0,this._fovLerp01=0,this._fovLerpStartValue=o.fov,this._fovLerpEndValue=e,typeof t=="number"?this._fovLerpDuration=t:this._fovLerpDuration=this.targetLerpDuration))}setLookTargetPosition(e=null,t=!1){this._controls&&e&&(e instanceof E&&(e=ee(e)),this._lookTargetEndPosition.copy(e),this._didSetTarget++,is&&(console.warn("OrbitControls: setLookTargetPosition",e,t),$.DrawWireSphere(this._lookTargetEndPosition,.2,16711680,2)),t===!0?this._controls.target.copy(this._lookTargetEndPosition):(this._lookTargetLerpActive=!0,this._lookTargetLerp01=0,this._lookTargetStartPosition.copy(this._controls.target),typeof t=="number"?this._lookTargetLerpDuration=t:this._lookTargetLerpDuration=this.targetLerpDuration))}get lookTargetLerpActive(){return this._lookTargetLerpActive}stopLookTargetLerp(){this._lookTargetLerpActive=!1}setLookTargetFromConstraint(e=0,t=1){var s,o;if(!this._controls||((s=this.lookAtConstraint)==null?void 0:s.enabled)===!1)return!1;const r=(o=this.lookAtConstraint)==null?void 0:o.sources;if(r&&r.length>0){const l=r[e];if(l)return l.getWorldPosition(this._lookTargetEndPosition),this.lerpLookTarget(this._lookTargetEndPosition,t),!0}return!1}lerpTarget(e,t){return this.lerpLookTarget(e,t)}lerpLookTarget(e,t){this._controls&&(t>=1?this._controls.target.copy(e):this._controls.target.lerp(e,t))}setTargetFromRaycast(e,t=!1){if(!this.controls)return!1;const s=e?this.context.physics.raycastFromRay(e):this.context.physics.raycast();for(const o of s)if(o.distance>0&&P.isActiveInHierarchy(o.object)){const r=Nf(o.object);if(r){const l=r.canvas;if(l!=null&&l.screenspace)break}return this.setLookTargetPosition(o.point,t),!0}return!1}fitCamera(e,t){var s,o;if(this.context.isInXR)return;let r;if(Array.isArray(e)?r=e:e&&"type"in e?r=e.children:e&&typeof e=="object"&&!(e instanceof E)&&!Array.isArray(e)&&(t=e,r=t.objects),r&&!Array.isArray(r)&&(r=r.children),(!Array.isArray(r)||r&&r.length<=0)&&(r=this.context.scene.children),!Array.isArray(r)||r.length<=0){console.warn("No objects to fit camera to...");return}const l=this._cameraObject,c=this._controls;if(!l||!c){console.warn("No camera or controls found to fit camera to objects...");return}t||(t={});const{immediate:h=!1,centerCamera:d="y",cameraNearFar:u="auto",fitOffset:p=1.1,fov:g=l?.fov}=t,f=new S,y=new S,v=si(r,void 0,(o=(s=this._camera)==null?void 0:s.threeCamera)==null?void 0:o.layers),b=v.clone();l.updateMatrixWorld(),l.updateProjectionMatrix(),v.getCenter(y);const _=new S;if(v.getSize(_),v.applyMatrix4(l.matrixWorldInverse),v.getSize(f),v.setFromCenterAndSize(y,f),Number.isNaN(f.x)||Number.isNaN(f.y)||Number.isNaN(f.z)){console.warn("Camera fit size resultet in NaN",l,v,[...r]);return}if(f.length()<=1e-10){Bc&&console.warn("Camera fit size is zero",v,[...r]);return}const w=t.fov||l.fov,x=2*Math.atan(Math.tan(w*Math.PI/360/2)*l.aspect)/Math.PI*360,k=f.y/(2*Math.atan(Math.PI*w/360)),M=f.x/(2*Math.atan(Math.PI*x/360)),T=p*Math.max(k,M)+f.z/2;Bc&&console.log("Fit camera to objects",{fitHeightDistance:k,fitWidthDistance:M,distance:T,verticalFov:w,horizontalFov:x}),this.maxZoom=T*10,this.minZoom=T*.01;const L=.05,D=y.clone();if(D.y-=f.y*L,this.setLookTargetPosition(D,h),this.setFieldOfView(t.fov,h),u==null||u=="auto"){const U=P.findObjectOfType(en),B=U?U.radius:0,Q=Math.max(_.x,_.y,_.z,B);l.near=T/100,l.far=Q+T*10,U&&(this.maxZoom=Math.max(Math.min(this.maxZoom,B*.5),T))}const z=c.getDistance();z<this.minZoom&&(this.minZoom=z*.9),z>this.maxZoom&&(this.maxZoom=z*1.1),l.updateMatrixWorld(),l.updateProjectionMatrix();const j=ee(l),H=y.clone();H.sub(j),d==="y"&&(H.y=0),H.normalize(),H.multiplyScalar(T),d==="y"&&(H.y+=-L*4*T);let K=y.clone().sub(H);l.parent&&(K=l.parent.worldToLocal(K)),this.setCameraTargetPosition(K,h),(Bc||t.debug)&&($.DrawWireBox3(v,16777011,10),$.DrawWireBox3(b,65280,10),!this._haveAttachedKeyboardEvents&&Bc&&(this._haveAttachedKeyboardEvents=!0,document.body.addEventListener("keydown",U=>{if(U.code==="KeyF"){let B;this._cameraObject instanceof we&&(B=Math.random()*Math.random()*170+10),this.fitCamera({objects:r,fitOffset:p,immediate:!1,fov:B})}U.code==="KeyV"&&this._cameraObject instanceof we&&(this._cameraObject.fov=60)}))),this.onBeforeRender()}}Ue([m()],_e.prototype,"autoTarget"),Ue([m()],_e.prototype,"autoFit"),Ue([m()],_e.prototype,"enableRotate"),Ue([m()],_e.prototype,"autoRotate"),Ue([m()],_e.prototype,"autoRotateSpeed"),Ue([m()],_e.prototype,"minAzimuthAngle"),Ue([m()],_e.prototype,"maxAzimuthAngle"),Ue([m()],_e.prototype,"minPolarAngle"),Ue([m()],_e.prototype,"maxPolarAngle"),Ue([m()],_e.prototype,"enableKeys"),Ue([m()],_e.prototype,"enableDamping"),Ue([m()],_e.prototype,"dampingFactor"),Ue([m()],_e.prototype,"enableZoom"),Ue([m()],_e.prototype,"minZoom"),Ue([m()],_e.prototype,"maxZoom"),Ue([m()],_e.prototype,"zoomSpeed"),Ue([m()],_e.prototype,"enablePan"),Ue([m(Fr)],_e.prototype,"lookAtConstraint"),Ue([m()],_e.prototype,"lookAtConstraint01"),Ue([m()],_e.prototype,"allowInterrupt"),Ue([m()],_e.prototype,"middleClickToFocus"),Ue([m()],_e.prototype,"doubleClickToFocus"),Ue([m()],_e.prototype,"clickBackgroundToFitScene"),Ue([m()],_e.prototype,"targetLerpDuration");var AT=Object.defineProperty,IT=Object.getOwnPropertyDescriptor,Yt=(n,e,t,s)=>{for(var o=s>1?void 0:s?IT(e,t):e,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=(s?l(e,t,o):l(o))||o);return s&&o&&AT(e,t,o),o},Io=(n=>(n[n.None=0]="None",n[n.Skybox=1]="Skybox",n[n.SolidColor=2]="SolidColor",n[n.Uninitialized=4]="Uninitialized",n))(Io||{});const Lo=C("debugcam"),Mx=C("debugscreenpointtoray");var jo;const Ut=(jo=class extends I{constructor(){super(...arguments),a(this,"_nearClipPlane",.1),a(this,"_farClipPlane",1e3),a(this,"orthographic",!1),a(this,"orthographicSize",5),a(this,"ARBackgroundAlpha",0),a(this,"_cullingMask",4294967295),a(this,"_backgroundBlurriness"),a(this,"_backgroundIntensity"),a(this,"_backgroundRotation"),a(this,"_environmentIntensity"),a(this,"_targetTexture",null),a(this,"_backgroundColor"),a(this,"_fov"),a(this,"_cam",null),a(this,"_clearFlags",2),a(this,"_skybox"),a(this,"_frustum"),a(this,"_projScreenMatrix",new se)}get isCamera(){return!0}get aspect(){return this._cam instanceof we?this._cam.aspect:this.context.domWidth/this.context.domHeight}set aspect(n){this._cam instanceof we&&this._cam.aspect!==n&&(this._cam.aspect=n,this._cam.updateProjectionMatrix())}get fieldOfView(){return this._cam instanceof we?this._cam.fov:this._fov}set fieldOfView(n){const e=this.fieldOfView!=n;if(this._fov=n,e&&this._cam&&this._cam instanceof we){if(this._fov===void 0){console.warn("Can not set undefined fov on PerspectiveCamera");return}this._cam.fov=this._fov,this._cam.updateProjectionMatrix()}}get nearClipPlane(){return this._nearClipPlane}set nearClipPlane(n){const e=this._nearClipPlane!=n;this._nearClipPlane=n,this._cam&&(e||this._cam.near!=n)&&(this._cam.near=n,this._cam.updateProjectionMatrix())}get farClipPlane(){return this._farClipPlane}set farClipPlane(n){const e=this._farClipPlane!=n;this._farClipPlane=n,this._cam&&(e||this._cam.far!=n)&&(this._cam.far=n,this._cam.updateProjectionMatrix())}applyClippingPlane(){this._cam&&(this._cam.near=this._nearClipPlane,this._cam.far=this._farClipPlane,this._cam.updateProjectionMatrix())}get clearFlags(){return this._clearFlags}set clearFlags(n){if(typeof n=="string")switch(n){case"skybox":n=1;break;case"solidcolor":n=2;break;default:n=0;break}n!==this._clearFlags&&(this._clearFlags=n,this.applyClearFlagsIfIsActiveCamera())}set cullingMask(n){this._cullingMask=n,this._cam&&(this._cam.layers.mask=n)}get cullingMask(){return this._cam?this._cam.layers.mask:this._cullingMask}set cullingLayer(n){this.cullingMask=(1<<n|0)>>>0}set backgroundBlurriness(n){n!==this._backgroundBlurriness&&(n===void 0?this._backgroundBlurriness=void 0:this._backgroundBlurriness=Math.min(Math.max(n,0),1),this.applyClearFlagsIfIsActiveCamera())}get backgroundBlurriness(){return this._backgroundBlurriness}set backgroundIntensity(n){n!==this._backgroundIntensity&&(n===void 0?this._backgroundIntensity=void 0:this._backgroundIntensity=Math.min(Math.max(n,0),10),this.applyClearFlagsIfIsActiveCamera())}get backgroundIntensity(){return this._backgroundIntensity}set backgroundRotation(n){n!==this._backgroundRotation&&(n===void 0?this._backgroundRotation=void 0:this._backgroundRotation=n,this.applyClearFlagsIfIsActiveCamera())}get backgroundRotation(){return this._backgroundRotation}set environmentIntensity(n){this._environmentIntensity=n}get environmentIntensity(){return this._environmentIntensity}get backgroundColor(){return this._backgroundColor??null}set backgroundColor(n){n&&(this._backgroundColor||(this._backgroundColor=new he(1,1,1,1)),this._backgroundColor.copy(n),(!("alpha"in n)||n.alpha===void 0)&&(this._backgroundColor.alpha=1),this.applyClearFlagsIfIsActiveCamera())}set targetTexture(n){this._targetTexture=n}get targetTexture(){return this._targetTexture}get cam(){return this.threeCamera}get threeCamera(){return this.activeAndEnabled&&this.buildCamera(),this._cam}screenPointToRay(n,e,t){const s=this.threeCamera,o=jo._origin;o.set(n,e,-1),this.context.input.convertScreenspaceToRaycastSpace(o),Mx&&console.log("screenPointToRay",n.toFixed(2),e.toFixed(2),"now:",o.x.toFixed(2),o.y.toFixed(2),"isInXR:"+this.context.isInXR),o.z=-1,o.unproject(s);const r=jo._direction.set(o.x,o.y,o.z),l=ee(s);return r.sub(l),r.normalize(),t?(t.set(l,r),t):new po(l.clone(),r.clone())}getFrustum(){return this._frustum||(this._frustum=new jv,this.updateFrustum()),this._frustum}updateFrustum(){this._frustum||(this._frustum=new jv),this._frustum.setFromProjectionMatrix(this.getProjectionScreenMatrix(this._projScreenMatrix,!0),this.context.renderer.coordinateSystem)}getProjectionScreenMatrix(n,e){return e&&this._projScreenMatrix.multiplyMatrices(this.threeCamera.projectionMatrix,this.threeCamera.matrixWorldInverse),n===this._projScreenMatrix?n:n.copy(this._projScreenMatrix)}awake(){Mx&&window.addEventListener("pointerdown",n=>{const e=n.clientX,t=n.clientY;console.log("touch",e.toFixed(2),t.toFixed(2));const s=this.screenPointToRay(e,t),o="#"+Math.floor(Math.random()*16777215).toString(16);$.DrawRay(s.origin,s.direction,o,10)})}onEnable(){Lo&&console.log(`Camera enabled: "${this.name}". ClearFlags=${Io[this._clearFlags]}`,this),this.buildCamera(),(this.tag=="MainCamera"||!this.context.mainCameraComponent)&&(this.context.setCurrentCamera(this),jT(this)),this.applyClearFlagsIfIsActiveCamera({applySkybox:!0})}onDisable(){this.context.removeCamera(this)}onBeforeRender(){if(this._cam&&(this._frustum&&this.updateFrustum(),this._clearFlags===2&&this.applyClearFlagsIfIsActiveCamera(),this._targetTexture)){this.context.isManagedExternally&&(this._warnedAboutExternalRenderer||(this._warnedAboutExternalRenderer=!0,console.warn("Rendering with external renderer is not supported yet. This may not work or throw errors. Please remove the the target texture from your camera: "+this.name,this.targetTexture))),this.context.composer;const n=this.context.renderer;if(n){const e=this.context.mainCameraComponent;this.applyClearFlags(),this._targetTexture.render(this.context.scene,this._cam,n),e?.applyClearFlags()}}}buildCamera(){if(this._cam)return;const n=this.gameObject.isCamera;let e=null;if(n?(e=this.gameObject,e?.layers.enableAll(),e instanceof we&&(this._fov=e.fov)):e=this.gameObject.children[0],e&&e.isCamera)e instanceof we&&(this._fov&&(e.fov=this._fov),e.near=this._nearClipPlane,e.far=this._farClipPlane,e.updateProjectionMatrix());else if(!this.orthographic)e=new we(this.fieldOfView,window.innerWidth/window.innerHeight,this._nearClipPlane,this._farClipPlane),this.fieldOfView&&(e.fov=this.fieldOfView),this.gameObject.add(e);else{const t=this.orthographicSize*100;e=new ud(window.innerWidth/-t,window.innerWidth/t,window.innerHeight/t,window.innerHeight/-t,this._nearClipPlane,this._farClipPlane),this.gameObject.add(e)}this._cam=e,this._cam.layers.mask=this._cullingMask,this.tag=="MainCamera"&&this.context.setCurrentCamera(this)}applyClearFlagsIfIsActiveCamera(n){this.context.mainCameraComponent===this&&this.applyClearFlags(n)}applyClearFlags(n){var e;if(!this._cam){Lo&&console.log("Camera does not exist (apply clear flags)");return}if(this.fieldOfView=this._fov,Lo){const s=`[Camera] Apply ClearFlags: ${Io[this._clearFlags]} - "${this.name}"`;console.debug(s)}const t=this.context.domElement.getAttribute("background-image")||this.context.domElement.getAttribute("background-color")||this.context.domElement.getAttribute("skybox-image");switch(this._clearFlags){case 0:return;case 1:if(jo.backgroundShouldBeTransparent(this.context)&&(!this.ARBackgroundAlpha||this.ARBackgroundAlpha<.001)){this.context.scene.background=null,this.context.renderer.setClearColor(0,0);return}(!this.scene.background||!this._skybox||n?.applySkybox===!0)&&this.applySceneSkybox(),this._backgroundBlurriness!==void 0&&!this.context.domElement.getAttribute("background-blurriness")?this.context.scene.backgroundBlurriness=this._backgroundBlurriness:Lo&&console.warn(`Camera "${this.name}" has no background blurriness`),this._backgroundIntensity!==void 0&&!this.context.domElement.getAttribute("background-intensity")&&(this.context.scene.backgroundIntensity=this._backgroundIntensity),this._backgroundRotation!==void 0&&!this.context.domElement.getAttribute("background-rotation")?this.context.scene.backgroundRotation=this._backgroundRotation:Lo&&console.warn(`Camera "${this.name}" has no background intensity`);break;case 2:if(this._backgroundColor&&!t){let s=this._backgroundColor.alpha;jo.backgroundShouldBeTransparent(this.context)&&(s=this.ARBackgroundAlpha??0),this.context.scene.background=null,(e=this.context.xr)!=null&&e.isVR?this.context.renderer.setClearColor(kb(this._backgroundColor).convertLinearToSRGB()):this.context.renderer.setClearColor(this._backgroundColor,s)}else this._backgroundColor||Lo&&console.warn(`[Camera] has no background color "${this.name}" `);break;case 4:t||(this.context.scene.background=null,this.context.renderer.setClearColor(0,0));break}}applySceneSkybox(){this._skybox||(this._skybox=new LT(this)),this._skybox.apply()}static backgroundShouldBeTransparent(n){var e,t,s,o;const r=(e=n.renderer.xr)==null?void 0:e.getSession();if(!r)return!1;if(typeof r._transparent=="boolean")return r._transparent;const l=r.environmentBlendMode;Lo&&De("Environment blend mode: "+l+" on "+navigator.userAgent);let c=l==="additive"||l==="alpha-blend";return n.isInAR&&l==="opaque"&&((t=navigator.userAgent)!=null&&t.includes("OculusBrowser")||(s=navigator.userAgent)!=null&&s.includes("Mozilla")&&(o=navigator.userAgent)!=null&&o.includes("Mobile WebXRViewer/v2"))&&(c=!0),r._transparent=c,c}},a(jo,"_origin",new S),a(jo,"_direction",new S),jo);Yt([m()],Ut.prototype,"aspect",1),Yt([m()],Ut.prototype,"fieldOfView",1),Yt([m()],Ut.prototype,"nearClipPlane",1),Yt([m()],Ut.prototype,"farClipPlane",1),Yt([m()],Ut.prototype,"clearFlags",1),Yt([m()],Ut.prototype,"orthographic",2),Yt([m()],Ut.prototype,"orthographicSize",2),Yt([m()],Ut.prototype,"ARBackgroundAlpha",2),Yt([m()],Ut.prototype,"cullingMask",1),Yt([m()],Ut.prototype,"backgroundBlurriness",1),Yt([m()],Ut.prototype,"backgroundIntensity",1),Yt([m(Dt)],Ut.prototype,"backgroundRotation",1),Yt([m()],Ut.prototype,"environmentIntensity",1),Yt([m(he)],Ut.prototype,"backgroundColor",1),Yt([m(Ac)],Ut.prototype,"targetTexture",1);let ci=Ut;class LT{constructor(e){a(this,"_camera"),a(this,"_skybox"),this._camera=e}get context(){var e;return(e=this._camera)==null?void 0:e.context}apply(){var e;if(this._skybox=this.context.lightmaps.tryGetSkybox(this._camera.sourceId),!this._skybox)this._did_log_failed_to_find_skybox||(this._did_log_failed_to_find_skybox=!0,console.warn(`Camera "${this._camera.name}" has no skybox texture. ${this._camera.sourceId}`));else if(this.context.scene.background!==this._skybox){const t=this.context.domElement.getAttribute("background-image")||this.context.domElement.getAttribute("background-color")||this.context.domElement.getAttribute("skybox-image");Lo&&console.debug(`[Camera] Apply Skybox ${(e=this._skybox)==null?void 0:e.name} ${t} - "${this._camera.name}"`),t!=null&&t.length||(this._skybox.mapping=kn,this.context.scene.background=this._skybox)}}}function jT(n){C("freecam")&&n.context.mainCameraComponent===n&&P.getOrAddComponent(n.gameObject,_e)}class zn extends I{constructor(){super(...arguments),a(this,"_listener",null),a(this,"onInteraction",()=>{this.destroyed||this.listener==null||this.addListenerIfItExists()})}get listener(){return this._listener==null&&(this._listener=new YC),this._listener}onEnable(){Ln.registerWaitForInteraction(this.onInteraction),this.addListenerIfItExists()}onDisable(){Ln.unregisterWaitForInteraction(this.onInteraction),this.removeListenerIfItExists()}addListenerIfItExists(){const e=this._listener;if(!e||e!=null&&e.parent)return;const t=this.context.mainCameraComponent||P.getComponentInParent(this.gameObject,ci);t!=null&&t.threeCamera?t.threeCamera.add(e):this.gameObject.add(e),e.filter?(e.gain.connect(e.filter),e.filter.connect(e.context.destination)):e.gain.connect(e.context.destination)}removeListenerIfItExists(){const e=this._listener;e&&(e.removeFromParent(),e.filter&&e.filter.disconnect(),e.gain&&e.gain.disconnect())}}var DT=Object.defineProperty,BT=Object.getOwnPropertyDescriptor,Os=(n,e,t,s)=>{for(var o=s>1?void 0:s?BT(e,t):e,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=(s?l(e,t,o):l(o))||o);return s&&o&&DT(e,t,o),o};const Et=C("debugaudio"),ss=class ur extends I{constructor(){super(...arguments),a(this,"clip",""),a(this,"playOnAwake",!1),a(this,"preload",!0),a(this,"playInBackground",!0),a(this,"_spatialBlend",0),a(this,"_minDistance",1),a(this,"_maxDistance",100),a(this,"_volume",1),a(this,"rollOffMode",0),a(this,"_loop",!1),a(this,"sound",null),a(this,"helper",null),a(this,"wasPlaying",!1),a(this,"audioLoader",null),a(this,"shouldPlay",!1),a(this,"_lastClipStartedLoading",null),a(this,"_audioElement",null),a(this,"onVisibilityChanged",()=>{switch(document.visibilityState){case"hidden":(this.playInBackground===!1||X.isMobileDevice())&&(this.wasPlaying=this.isPlaying,this.isPlaying&&this.pause());break;case"visible":Et&&console.log("visible",this.enabled,this.playOnAwake,!this.isPlaying,ur.userInteractionRegistered,this.wasPlaying),this.enabled&&this.playOnAwake&&!this.isPlaying&&ur.userInteractionRegistered&&this.wasPlaying&&this.play();break}}),a(this,"onApplicationMuteChanged",()=>{var e,t;this.context.application.muted?(e=this.sound)==null||e.setVolume(0):(t=this.sound)==null||t.setVolume(this.volume)}),a(this,"createAudio",e=>{if(this.destroyed){Et&&console.warn("AudioSource destroyed, not creating audio",this.name);return}Et&&console.log("AudioBuffer finished loading",e);const t=this.Sound;if(!t){Et&&console.warn("Failed getting sound?",this.name);return}t.isPlaying&&t.stop(),e&&t.setBuffer(e),t.loop=this._loop,this.context.application.muted?t.setVolume(0):t.setVolume(this.volume),t.autoplay=this.shouldPlay&&ur.userInteractionRegistered,this.applySpatialDistanceSettings(),t.isPlaying&&t.stop(),ur.registerWaitForAllowAudio(this.__onAllowAudioCallback)}),a(this,"__onAllowAudioCallback",()=>{this.shouldPlay&&this.play()}),a(this,"_lastContextTime",0),a(this,"_hasEnded",!0),a(this,"_needUpdateSpatialDistanceSettings",!1)}static get userInteractionRegistered(){return Ln.userInteractionRegistered}static registerWaitForAllowAudio(e){Ln.registerWaitForInteraction(e)}get isPlaying(){var e;return((e=this.sound)==null?void 0:e.isPlaying)??!1}get duration(){var e,t;return(t=(e=this.sound)==null?void 0:e.buffer)==null?void 0:t.duration}get time01(){var e;const t=this.duration;return t&&this.sound?((e=this.sound)==null?void 0:e.context.currentTime)/t:0}set time01(e){const t=this.duration;t&&this.sound&&(this.time=e*t)}get time(){var e,t;return(e=this.sound)!=null&&e.source?((t=this.sound.source)==null?void 0:t.context.currentTime)-this._lastContextTime+this.sound.offset:0}set time(e){if(this.sound){if(e===this.sound.offset)return;const t=this.isPlaying;this.stop(),this.sound.offset=e,t&&this.play()}}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)}get volume(){return this._volume}set volume(e){this._volume=e,this.sound&&!this.context.application.muted&&(Et&&console.log(this.name,"audio set volume",e),this.sound.setVolume(e))}set pitch(e){this.sound&&this.sound.setPlaybackRate(e)}get pitch(){return this.sound?this.sound.getPlaybackRate():1}get Sound(){var e;if(!this.sound&&ur.userInteractionRegistered){let t=this.gameObject.getComponent(zn)??this.context.mainCamera.getComponent(zn)??xc(zn,this.context,!1);!t&&this.context.mainCamera&&(t=this.context.mainCamera.addComponent(zn)),t!=null&&t.listener?(this.sound=new KC(t.listener),(e=this.gameObject)==null||e.add(this.sound)):Et&&console.warn("No audio listener found in scene - can not play audio")}return this.sound}get ShouldPlay(){return this.shouldPlay}get audioContext(){var e;return(e=this.sound)==null?void 0:e.context}awake(){Et&&console.log("[AudioSource]",this),this.audioLoader=new jm,this.playOnAwake&&(this.shouldPlay=!0),this.preload&&typeof this.clip=="string"&&this.audioLoader.load(this.clip,this.createAudio,()=>{},console.error)}onEnable(){this.sound&&this.gameObject.add(this.sound),ur.userInteractionRegistered?this.playOnAwake&&this.context.application.isVisible&&this.play():ur.registerWaitForAllowAudio(()=>{this.enabled&&!this.destroyed&&this.shouldPlay&&this.onNewClip(this.clip)}),globalThis.addEventListener("visibilitychange",this.onVisibilityChanged),this.context.application.addEventListener(Og.MuteChanged,this.onApplicationMuteChanged)}onDisable(){globalThis.removeEventListener("visibilitychange",this.onVisibilityChanged),this.context.application.removeEventListener(Og.MuteChanged,this.onApplicationMuteChanged),this.pause()}applySpatialDistanceSettings(){const e=this.sound;if(!e)return;this._needUpdateSpatialDistanceSettings=!1;const t=W.lerp(10*this._maxDistance/Math.max(1e-4,this.spatialBlend),this._minDistance,this.spatialBlend);switch(Et&&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:console.warn("Custom rolloff for AudioSource is not supported: "+this.name);break}this.spatialBlend>0?Et&&!this.helper&&(this.helper=new tO(e,e.getRefDistance()),e.add(this.helper)):this.helper&&this.helper.parent&&this.helper.removeFromParent()}async onNewClip(e){if(e&&(this.clip=e),typeof e=="string")if(Et&&console.log(e),e.endsWith(".mp3")||e.endsWith(".wav")){if(this.audioLoader||(this.audioLoader=new jm),this.shouldPlay=!0,this._lastClipStartedLoading===e){Et&&console.log("Is currently loading:",this._lastClipStartedLoading,this);return}this._lastClipStartedLoading=e,Et&&console.log("load audio",e);const t=await this.audioLoader.loadAsync(e).catch(console.error);if(this.destroyed)return;this._lastClipStartedLoading===e&&(this._lastClipStartedLoading=null),t&&this.createAudio(t)}else console.warn("Unsupported audio clip type",e);else this.shouldPlay=!0,this.createAudio()}play(e=void 0){var t,s,o;!e&&this.clip&&(e=this.clip),e!==void 0&&typeof e!="string"&&!(e instanceof MediaStream)&&(F()&&console.warn("Called play on AudioSource with unknown argument type:",e+`
|
|
939
|
+
Could not find method ${d.method} on object ${p.name}`,p,typeof p[d.method])};if(typeof p[d.method]!="function"){let y=!1,v=p;for(;v;){const b=Object.getOwnPropertyDescriptor(v,d.method);if(b&&(b.writable===!0||b.set)){y=!0;break}v=Object.getPrototypeOf(v)}!y&&(F()||wt)&&f()}}if(p){let f=d.argument;if(f!==void 0?f=u(f):d.arguments!==void 0&&(f=d.arguments.map(u)),!p[d.method])console.warn(`EventList method not found: "${d.method}" on ${p?.name}`);else{f!==void 0&&!Array.isArray(f)&&(f=[f]);const y=new Un(p,d.method,f,d.enabled);l.push(y)}}else F()&&console.warn("[Debug] EventList: Could not find event listener in scene",d,t.object,e)}const c=new xe(l);wt&&console.log(c);const h=t.target;return h!==void 0&&t.path!==void 0&&c.setEventTarget(t.path,h),c}}}const CT=new ST,Eu=new WeakMap,PT=je.prototype.clone;je.prototype.clone=function(){const n=PT.call(this);return Eu.has(n)||Eu.set(n,this),n};class Cx extends es{constructor(){super([Ac,$s])}onSerialize(e,t){}onDeserialize(e,t){if(e instanceof je&&t.type===Ac){let s=e;Eu.has(s)&&(s=Eu.get(s)),s.isRenderTargetTexture=!0,s.flipY=!0,s.offset.y=1,s.repeat.y=-1,s.needsUpdate=!0,s.mipmaps=[],s instanceof XC&&(s.isCompressedTexture=!1,s.format=fd);const o=new Ac(s.image.width,s.image.height,{colorSpace:On});return o.texture=s,o}}}new Cx;class Px extends es{constructor(){super([URL])}onSerialize(e,t){return null}onDeserialize(e,t){if(typeof e=="string"&&e.length>0)return yo(t.gltfId,e)}}new Px;var OT=Object.defineProperty,kT=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&OT(e,t,o),o};class Ya extends I{awake(){ii.createIfNoneExists(this.context)}onEnable(){var e;(e=ii.get(this.context))==null||e.register(this)}onDisable(){var e;(e=ii.get(this.context))==null||e.unregister(this)}}class ji extends Ya{constructor(){super(...arguments),a(this,"targets",null),a(this,"raycastHits",[]),a(this,"ignoreSkinnedMeshes",!1)}start(){this.targets=[this.gameObject]}performRaycast(e=null){if(!this.targets)return null;e??(e=new Qs),e.targets=this.targets,e.results=this.raycastHits,e.useAcceleratedRaycast=!0;const t=e.testObject;this.ignoreSkinnedMeshes&&(e.testObject=o=>o instanceof Pn?"continue in children":t?t(o):!0);const s=this.context.physics.raycast(e);return e.testObject=t,s}}kT([m()],ji.prototype,"ignoreSkinnedMeshes");class Au extends ji{constructor(){super(),this.ignoreSkinnedMeshes=!0}}const Ox=class yC extends Ya{performRaycast(e){if(!ne.active||!yC.allow||!(e!=null&&e.ray))return null;const t=e.ray.origin;return this.context.physics.sphereOverlap(t,.015,!1,!0)}};a(Ox,"allow",!0);let Dc=Ox;class zf{static getObject(e){const t=e[Mi];return t&&(t.isComponent===!0?e=t.gameObject:e=t),e}static isInteractable(e,t){if(t&&(t.canvasGroup=void 0,t.graphic=void 0),e==null||!e.visible||(e=this.getObject(e),!e.visible))return!1;const s=this.tryFindCanvasGroup(e);if(s?.isCanvasGroup===!0&&(t&&(t.canvasGroup=s),s.blocksRaycasts===!1||s.interactable===!1))return!1;const o=Ar(e,r=>{if(r.isGraphic===!0)return r},!1);return t&&o?.isGraphic===!0&&(t.graphic=o),!(o?.raycastTarget===!1||o?.layer===2)}static tryFindCanvasGroup(e){if(!e)return null;const t=Ar(e,s=>{const o=s;if(o.blocksRaycasts!==void 0&&o.interactable!==void 0)return o},!1);return t!==void 0?t:this.tryFindCanvasGroup(e.parent)}}function Nf(n){return n[Mi]||(n.parent?Nf(n.parent):null)}function MT(n){return n.isUI===!0||typeof n[Mi]=="object"}function Iu(n,e){if(!n)return;const t=n.material;if(t?.isMaterial===!0){const s=n.parent;s&&s.isText,t.side=e.doubleSided??!0?Pi:fo,t.shadowSide=e.doubleSided?Pi:fo,n.castShadow=e.castShadows?e.castShadows:!1,n.receiveShadow=e.receiveShadows?e.receiveShadows:!1}for(const s of n.children)Iu(s,e)}function Ka(n,e,t){n[e]===void 0&&console.warn("Field",e,"is undefined on",n);const s=Proxy.revocable(n[e],{set(l,c,h,d){const u=l[c],p=Reflect.set(l,c,h,d);return t(h,u),p}}),o=s.revoke,r=n[e];return s.revoke=()=>{n[e]=r,o()},n[e]=s.proxy,s}const kx=Symbol("Scheduled action");function RT(n,e,t=Oe.OnBeforeRender){let s=n[kx];s||(s=n[kx]={});const o=e.name;s[t]||(s[t]={});const r=s[t];if(r[o])return;function*l(){e?.call(n),r[o]=null}const c=n.startCoroutine(l(),t);r[o]=c}const Eo=C("debugeventsystem");var Wf=(n=>(n.BeforeHandleInput="BeforeHandleInput",n.AfterHandleInput="AfterHandleInput",n))(Wf||{});vx(n=>{ii.createIfNoneExists(n)});class ii extends I{constructor(){super(...arguments),a(this,"raycaster",[]),a(this,"pressedByID",new Map),a(this,"hoveredByID",new Map),a(this,"onPointerEvent",e=>{if(e===void 0||e.propagationStopped||e.defaultPrevented||e.used)return;const t=new cd(this.context.input,e);this._currentPointerEventName=e.type,t.inputSource=this.context.input,t.isClick=e.isClick,t.isDoubleClick=e.isDoubleClick,t.isDown=e.type==Be.PointerDown,t.isUp=e.type==Be.PointerUp,t.isPressed=this.context.input.getPointerPressed(e.pointerId),Eo&&(t.isDown?console.log("DOWN",t.pointerId):t.isUp&&console.log("UP",t.pointerId),t.isClick&&console.log("CLICK",t.pointerId));const s=new Qs;e.hasRay?s.ray=e.ray:s.screenPoint=this.context.input.getPointerPositionRC(e.pointerId);const o=this.performRaycast(s);if(o){for(const l of o)l.event=e,e.intersections.push(l);e.origin.onPointerHits&&e.origin.onPointerHits({sender:this,event:e,hits:o})}Eo&&t.isClick&&De("EventSystem: "+t.pointerId+" - "+this.context.time.frame+" - Up:"+t.isUp+", Down:"+t.isDown);const r={sender:this,args:t,hasActiveUI:this.currentActiveMeshUIComponents.length>0};this.dispatchEvent(new CustomEvent("BeforeHandleInput",{detail:r})),this.handleIntersections(o,t),this.dispatchEvent(new CustomEvent("AfterHandleInput",{detail:r}))}),a(this,"_sortedHits",[]),a(this,"_testObjectsCache",new Map),a(this,"_currentlyActiveRaycaster",null),a(this,"_currentPointerEventName",null),a(this,"shouldRaycastObject",e=>{var t;const s=e&&"getComponent"in e?e.getComponent(Ya):null;if(s&&s!=this._currentlyActiveRaycaster)return!1;let o=null;if(MT(e)&&(o=(t=e[Mi])==null?void 0:t.gameObject),this._testObjectsCache.has(e)||o&&this._testObjectsCache.has(o))return this._testObjectsCache.get(e)===!1?"continue in children":!0;{let r=Mu(e,this._currentPointerEventName);if(!r&&o&&(r=Mu(o,this._currentPointerEventName)),r){this._testObjectsCache.set(e,!0);for(const l of e.children)this.shouldRaycastObject_AddToYesCache(l);return!0}return this._testObjectsCache.set(e,!1),"continue in children"}}),a(this,"_sortingBuffer",[]),a(this,"_noDepthTestingResults",[]),a(this,"out",{}),a(this,"_capturedPointer",{}),a(this,"pointerEnterSymbol",Symbol("pointerEnter")),a(this,"pointerExitSymbol",Symbol("pointerExit")),a(this,"currentActiveMeshUIComponents",[])}static ensureUpdateMeshUI(e,t,s=!1){Ao.update(e,t,s)}static markUIDirty(e){Ao.markDirty()}static createIfNoneExists(e){e.scene.getComponent(ii)||e.scene.addComponent(ii)}static get(e){return this.createIfNoneExists(e),e.scene.getComponent(ii)}static get instance(){return this.get(J.Current)}register(e){var t;e&&this.raycaster&&!this.raycaster.includes(e)&&((t=this.raycaster)==null||t.push(e))}unregister(e){var t,s;const o=(t=this.raycaster)==null?void 0:t.indexOf(e);o!==void 0&&o!==-1&&((s=this.raycaster)==null||s.splice(o,1))}get hasActiveUI(){return this.currentActiveMeshUIComponents.length>0}get isHoveringObjects(){return this.hoveredByID.size>0}awake(){this.gameObject!==this.context.scene&&(console.debug(`[Needle Engine] EventSystem is only allowed on the scene root. Disabling EventSystem on '${this.gameObject.name}'`),this.enabled=!1)}start(){this.context.scene.getComponent(Ya)||this.context.scene.addComponent(ji)}onEnable(){this.context.input.addEventListener(Be.PointerDown,this.onPointerEvent),this.context.input.addEventListener(Be.PointerUp,this.onPointerEvent),this.context.input.addEventListener(Be.PointerMove,this.onPointerEvent)}onDisable(){this.context.input.removeEventListener(Be.PointerDown,this.onPointerEvent),this.context.input.removeEventListener(Be.PointerUp,this.onPointerEvent),this.context.input.removeEventListener(Be.PointerMove,this.onPointerEvent)}onBeforeRender(){this.resetMeshUIStates()}shouldRaycastObject_AddToYesCache(e){this._testObjectsCache.set(e,!0);for(const t of e.children)this.shouldRaycastObject_AddToYesCache(t)}performRaycast(e){if(!this.raycaster)return null;this._testObjectsCache.clear(),this._sortedHits.length=0,e||(e=new Qs),e.testObject=this.shouldRaycastObject;for(const t of this.raycaster){if(!t.activeAndEnabled)continue;this._currentlyActiveRaycaster=t;const s=t.performRaycast(e);this._currentlyActiveRaycaster=null,s&&s.length>0&&this._sortedHits.push(...s)}return this._sortedHits.sort((t,s)=>t.distance-s.distance),this._sortedHits}assignHitInformation(e,t){t?(e.intersection=t,e.point=t.point,e.normal=t.normal,e.face=t.face,e.distance=t.distance,e.instanceId=t.instanceId):(e.intersection=void 0,e.point=void 0,e.normal=void 0,e.face=void 0,e.distance=void 0,e.instanceId=void 0)}handleIntersections(e,t){var s;if(e!=null&&e.length){e=this.sortCandidates(e);for(const r of e){if(t.event.immediatePropagationStopped)return!1;if(this.assignHitInformation(t,r),this.handleEventOnObject(r.object,t))return!0}}this.assignHitInformation(t,e?.[0]),this.invokePointerCapture(t);const o=this.hoveredByID.get(t.pointerId);return o&&this.propagatePointerExit(o.obj,o.data,null),this.hoveredByID.delete(t.pointerId),t.isUp&&((s=this.pressedByID.get(t.pointerId))==null||s.handlers.forEach(r=>this.invokeOnPointerUp(t,r)),this.pressedByID.delete(t.pointerId)),!1}sortCandidates(e){this._sortingBuffer.length=0,this._noDepthTestingResults.length=0;for(let t=0;t<e.length;t++){const s=e[t],o=s.object;if(o.material&&o.material.depthTest===!1){this._noDepthTestingResults.push(s);continue}this._sortingBuffer.push(s)}for(const t of this._sortingBuffer)this._noDepthTestingResults.push(t);return this._noDepthTestingResults}handleEventOnObject(e,t){if(!this.testIsVisible(e))return t.isClick&&Eo&&console.log("not allowed",e),!1;if(t.pointerId===void 0)return Eo&&console.error("Event without pointer can't be handled",t),!1;t.object=e;const s=e.parent,o=t.isClick??!1;let r=null;if(s&&s.isUI){const d=(t.isPressed||t.isClick)??!1;if(s[Mi]){const u=s[Mi].gameObject;if(u){if(!zf.isInteractable(u,this.out))return!1;r=this.out.canvasGroup??null,this.handleMeshUIIntersection(e,d),e=u}}}o&&Eo&&console.log(this.context.time.frame,e);const l=this.hoveredByID.get(t.pointerId),c=l?.obj;c!==e&&c&&this.propagatePointerExit(c,l.data,e);const h=this.hoveredByID.get(t.pointerId);if(h?(h.obj=e,h.data=t):this.hoveredByID.set(t.pointerId,{obj:e,data:t}),t.isDown){const d=this.pressedByID.get(t.pointerId);d?(d.obj=e,d.data=t):this.pressedByID.set(t.pointerId,{obj:e,data:t,handlers:new Set})}return(r===null||r.interactable)&&this.handleMainInteraction(e,t,c??null),!0}propagate(e,t){for(;e;)P.foreachComponent(e,s=>{t(s)},!1),e=e.parent}handleMainInteraction(e,t,s){const o=this.pressedByID.get(t.pointerId),r=s!==e;let l=!0;switch(t.event.pointerType){case"mouse":case"touch":const c=this.context.input.getPointerPositionLastFrame(t.pointerId),h=this.context.input.getPointerPosition(t.pointerId);l=c&&!W.approximately(c,h);break}this.propagate(e,c=>{var h;const d=c;d.interactable!==!1&&(!d.activeAndEnabled||!d.enabled||(d.onPointerEnter&&r&&this.handlePointerEnter(d,t),t.isDown&&d.onPointerDown&&(d.onPointerDown(t),o?.handlers.add(d),this.handlePointerCapture(t,d)),d.onPointerMove&&(l&&d.onPointerMove(t),this.handlePointerCapture(t,d)),t.isUp&&(d.onPointerUp&&(this.invokeOnPointerUp(t,d),o?.handlers.delete(d)),d.onPointerExit&&((h=t.event)==null?void 0:h.pointerType)===Ud.Touch&&(this.handlePointerExit(d,t),this.hoveredByID.delete(t.pointerId))),t.isClick&&d.onPointerClick&&d.onPointerClick(t)))}),t.isUp&&(o?.handlers.forEach(c=>{this.invokeOnPointerUp(t,c)}),this.pressedByID.delete(t.pointerId))}propagatePointerExit(e,t,s){this.propagate(e,o=>{if(!o.gameObject||o.destroyed)return;const r=o;if(r.onPointerExit||r.onPointerEnter){if(s&&this.isChild(s,o.gameObject))return;this.handlePointerExit(r,t)}})}invokeOnPointerUp(e,t){var s;(s=t.onPointerUp)==null||s.call(t,e),this.releasePointerCapture(e,t)}handlePointerEnter(e,t){e.onPointerEnter&&this.updatePointerState(e,t.pointerId,this.pointerEnterSymbol,!0)&&e.onPointerEnter(t),this.updatePointerState(e,t.pointerId,this.pointerExitSymbol,!1)}handlePointerExit(e,t){e.onPointerExit&&this.updatePointerState(e,t.pointerId,this.pointerExitSymbol,!0)&&e.onPointerExit(t),this.updatePointerState(e,t.pointerId,this.pointerEnterSymbol,!1)}updatePointerState(e,t,s,o){let r=e[s];if(o)return r&&r.includes(t)?!1:(r=r||[],r.push(t),e[s]=r,!0);{if(!r||!r.includes(t))return!1;const l=r.indexOf(t);return l!==-1&&r.splice(l,1),!0}}handlePointerCapture(e,t){if(e.z__pointer_ctured){e.z__pointer_ctured=!1;const s=e.pointerId;if(t.onPointerMove){const o=this._capturedPointer[s]||[];o.push(t),this._capturedPointer[s]=o}else F()&&!t.z__warned_no_pointermove&&(t.z__warned_no_pointermove=!0,console.warn("PointerCapture was requested but the component doesn't implement onPointerMove. It will not receive any pointer events"))}else e.z__pointer_cture_rleased&&(e.z__pointer_cture_rleased=!1,this.releasePointerCapture(e,t))}releasePointerCapture(e,t){const s=e.pointerId;if(this._capturedPointer[s]){const o=this._capturedPointer[s].indexOf(t);o!==-1&&(this._capturedPointer[s].splice(o,1),Eo&&console.log("released pointer capture",s,t,this._capturedPointer))}}invokePointerCapture(e){var t;if(e.event.type===Be.PointerMove){const s=e.pointerId,o=this._capturedPointer[s];if(o){Eo&&console.log("Captured",s,o);for(let r=0;r<o.length;r++){const l=o[r];if(l.destroyed){o.splice(r,1),r--;continue}(t=l.onPointerMove)==null||t.call(l,e)}}}}isChild(e,t){return!e||!t?!1:e===t?!0:e.parent?this.isChild(e.parent,t):!1}handleMeshUiObjectWithoutShadowDom(e,t){return!e||!e.isUI?!0:this.handleMeshUIIntersection(e,t)}handleMeshUIIntersection(e,t){const s=Ao.updateState(e,t);return s&&this.currentActiveMeshUIComponents.push(s),s!==null}resetMeshUIStates(){if(this.context.input.getPointerPressedCount()>0&&Ao.resetLastSelected(),!(!this.currentActiveMeshUIComponents||this.currentActiveMeshUIComponents.length<=0)){for(let e=0;e<this.currentActiveMeshUIComponents.length;e++){const t=this.currentActiveMeshUIComponents[e];Ao.resetState(t)}this.currentActiveMeshUIComponents.length=0}}testIsVisible(e){return e?P.isActiveSelf(e)?this.testIsVisible(e.parent):!1:!0}}class Ao{static markDirty(){this.needsUpdate=!0}static update(e,t,s=!1){if(s){e.update();return}const o=t.time.frameCount;for(const r of this.lastUpdateFrame)if(r.context===t){if(o===r.frame)return;r.frame=o;let l=this.needsUpdate||o<1;r.nextUpdate<=o&&(l=!0),l&&(Eo&&console.log("Update threemeshui"),this.needsUpdate=!1,r.nextUpdate=o+60,e.update());return}this.lastUpdateFrame=[{context:t,frame:o,nextUpdate:o+60}],e.update(),this.needsUpdate=!1}static updateState(e,t){let s=null;if(e&&(s=this.findBlockOrTextInParent(e),s&&s!==this.lastSelected)){if(s.interactable===!1)return null;this.needsUpdate=!0}return s}static resetLastSelected(){const e=this.lastSelected;e&&(this.lastSelected=null,this.resetState(e))}static resetState(e){e&&(this.needsUpdate=!0)}static findBlockOrTextInParent(e){return e?e.isBlock||e.isText?e:this.findBlockOrTextInParent(e.parent):null}}a(Ao,"lastSelected",null),a(Ao,"lastUpdateFrame",[]),a(Ao,"needsUpdate",!1);var TT=Object.defineProperty,Ue=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&TT(e,t,o),o};const is=C("debugorbit"),Vf=C("freecam"),Bc=C("debugcamerafit"),Lu=C("smoothcam"),ET={LEFT:"",UP:"",RIGHT:"",BOTTOM:""};let $f;class Fc extends CustomEvent{constructor(e,t){super("target-reached",{detail:{controls:e,type:t}})}}class _e extends I{constructor(){super(...arguments),a(this,"autoTarget",!0),a(this,"autoFit",!1),a(this,"enableRotate",!0),a(this,"autoRotate",!1),a(this,"autoRotateSpeed",1),a(this,"minAzimuthAngle",1/0),a(this,"maxAzimuthAngle",1/0),a(this,"minPolarAngle",0),a(this,"maxPolarAngle",Math.PI),a(this,"enableKeys",!1),a(this,"enableDamping",!0),a(this,"dampingFactor",.1),a(this,"enableZoom",!0),a(this,"minZoom",0),a(this,"maxZoom",1/0),a(this,"zoomSpeed",1),a(this,"zoomToCursor",!1),a(this,"enablePan",!0),a(this,"lookAtConstraint",null),a(this,"lookAtConstraint01",1),a(this,"allowInterrupt",!0),a(this,"middleClickToFocus",!0),a(this,"doubleClickToFocus",!0),a(this,"clickBackgroundToFitScene",2),a(this,"debugLog",!1),a(this,"targetLerpDuration",1),a(this,"_controls",null),a(this,"_cameraObject",null),a(this,"_lookTargetLerpActive",!1),a(this,"_lookTargetStartPosition",new S),a(this,"_lookTargetEndPosition",new S),a(this,"_lookTargetLerp01",0),a(this,"_lookTargetLerpDuration",0),a(this,"_cameraLerpActive",!1),a(this,"_cameraStartPosition",new S),a(this,"_cameraEndPosition",new S),a(this,"_cameraLerp01",0),a(this,"_cameraLerpDuration",0),a(this,"_fovLerpActive",!1),a(this,"_fovLerpStartValue",0),a(this,"_fovLerpEndValue",0),a(this,"_fovLerp01",0),a(this,"_fovLerpDuration",0),a(this,"_inputs",0),a(this,"_enableTime",0),a(this,"_startedListeningToKeyEvents",!1),a(this,"_eventSystem"),a(this,"_afterHandleInputFn"),a(this,"_camera",null),a(this,"_syncedTransform"),a(this,"_didSetTarget",0),a(this,"targetElement",null),a(this,"_activePointerEvents"),a(this,"_lastTimeClickOnBackground",-1),a(this,"_clickOnBackgroundCount",0),a(this,"_onPointerDown",e=>{this._activePointerEvents.push(e)}),a(this,"_onPointerDownLate",e=>{e.used&&this._controls&&(this._controls.enabled=!1)}),a(this,"_onPointerUp",e=>{for(let t=this._activePointerEvents.length-1;t>=0;t--){const s=this._activePointerEvents[t];if(s.pointerId===e.pointerId&&s.button===e.button){this._activePointerEvents.splice(t,1);break}}if(this.clickBackgroundToFitScene>0&&e.isClick&&e.button===0){if(e.hasRay||e.intersections.push(...this.context.physics.raycast()),e.intersections.length<=0){const t=this.context.time.time-this._lastTimeClickOnBackground;this._lastTimeClickOnBackground=this.context.time.time,this.clickBackgroundToFitScene<=1||t<this.clickBackgroundToFitScene*.15?(this._clickOnBackgroundCount+=1,this._clickOnBackgroundCount>=this.clickBackgroundToFitScene-1&&this.fitCamera(this.context.scene.children,{immediate:!1})):this._clickOnBackgroundCount=0}is&&console.log(this.clickBackgroundToFitScene,e.intersections.length,this._clickOnBackgroundCount)}}),a(this,"_onPointerUpLate",e=>{this.doubleClickToFocus&&e.isDoubleClick&&!e.used&&this.setTargetFromRaycast()}),a(this,"_orbitStartAngle",0),a(this,"onControlsChangeStarted",()=>{this._controls&&(this._orbitStartAngle=this._controls.getAzimuthalAngle()+this._controls.getPolarAngle()),this._syncedTransform&&this._syncedTransform.requestOwnership()}),a(this,"onControlsChangeEnded",()=>{if(this._controls&&this.autoTarget){const e=this._controls.getAzimuthalAngle()+this._controls.getPolarAngle()-this._orbitStartAngle;Math.abs(e)<.01?(is&&console.debug("OrbitControls: No movement detected, updating target now"),this.updateTargetNow()):is&&console.debug("OrbitControls: Movement detected",e)}}),a(this,"_shouldDisable",!1),a(this,"__onPreRender",()=>{const e=this.context.pre_render_callbacks.indexOf(this.__onPreRender);e>=0&&this.context.pre_render_callbacks.splice(e,1),this.autoFit&&(this.autoFit=!1,this.fitCamera({centerCamera:"y",immediate:!0,objects:this.scene.children}))}),a(this,"_haveAttachedKeyboardEvents",!1)}get isCameraController(){return!0}get controls(){return this._controls}get controllerObject(){return this._cameraObject}onStartInteraction(e){var t;(t=this.controls)==null||t.addEventListener("start",e)}get targetLerpSpeed(){return 5}set targetLerpSpeed(e){this.targetLerpDuration=1/e}awake(){is&&console.debug("OrbitControls",this),this._didSetTarget=0,this._startedListeningToKeyEvents=!1}start(){this._eventSystem=ii.get(this.context)??void 0,this._eventSystem&&(this._afterHandleInputFn=this.afterHandleInput.bind(this),this._eventSystem.addEventListener(Wf.AfterHandleInput,this._afterHandleInputFn))}onDestroy(){var e,t;(e=this._controls)==null||e.dispose(),(t=this._eventSystem)==null||t.removeEventListener(Wf.AfterHandleInput,this._afterHandleInputFn)}onEnable(){this._didSetTarget=0,this._enableTime=this.context.time.time;const e=P.getComponent(this.gameObject,ci);this._camera=e;let t=e?.threeCamera;if(!t&&this.gameObject instanceof we&&(t=this.gameObject),t&&rg(t,this,!0),!this._controls&&t instanceof E){this._cameraObject=t;const s=this.targetElement??this.context.renderer.domElement,o=t?.quaternion.clone();this._controls=new $v(t,s),t?.quaternion.copy(o),$f===void 0&&($f={...this._controls.keys});const r=ee(t),l=this.gameObject.worldForward,c=r.clone().sub(l.multiplyScalar(2.5));this._controls.target.copy(c)}if(this._controls)if(Vf&&(this.enablePan=!0,this.enableZoom=!0,this.middleClickToFocus=!0,X.isMobileDevice()&&(this.doubleClickToFocus=!0)),this._controls.addEventListener("start",this.onControlsChangeStarted),this._controls.addEventListener("end",this.onControlsChangeEnded),!this._startedListeningToKeyEvents&&this.enableKeys)this._startedListeningToKeyEvents=!0,this._controls.listenToKeyEvents(this.context.domElement);else try{this._controls.stopListenToKeyEvents()}catch{}this._syncedTransform=P.getComponent(this.gameObject,sn)??void 0,this.context.pre_render_callbacks.push(this.__onPreRender),this._activePointerEvents=[],this.context.input.addEventListener("pointerdown",this._onPointerDown,{queue:oi.Early}),this.context.input.addEventListener("pointerdown",this._onPointerDownLate,{queue:oi.Late}),this.context.input.addEventListener("pointerup",this._onPointerUp,{queue:oi.Early}),this.context.input.addEventListener("pointerup",this._onPointerUpLate,{queue:oi.Late})}onDisable(){var e;if((e=this._camera)!=null&&e.threeCamera&&rg(this._camera.threeCamera,this,!1),this._controls){this._controls.enabled=!1,this._controls.autoRotate=!1,this._controls.removeEventListener("start",this.onControlsChangeStarted),this._controls.removeEventListener("end",this.onControlsChangeEnded);try{this._controls.stopListenToKeyEvents()}catch{}this._startedListeningToKeyEvents=!1}this._activePointerEvents.length=0,this.context.input.removeEventListener("pointerdown",this._onPointerDown),this.context.input.removeEventListener("pointerdown",this._onPointerDownLate),this.context.input.removeEventListener("pointerup",this._onPointerUp),this.context.input.removeEventListener("pointerup",this._onPointerUpLate)}updateTargetNow(){var e,t,s;const o=new po((e=this._cameraObject)==null?void 0:e.worldPosition,(t=this._cameraObject)==null?void 0:t.worldForward.multiplyScalar(-1)),r=this.context.physics.raycastFromRay(o),l=r.length>0?r[0]:void 0;l&&l.distance>this.minZoom&&l.distance<this.maxZoom&&(is&&$.DrawWireSphere(l.point,.1,16711680,2),(s=this._controls)==null||s.target.copy(r[0].point))}afterHandleInput(e){e.detail.args.pointerId===0&&(e.detail.args.isDown?this._controls&&this._eventSystem&&(this._shouldDisable=this._eventSystem.hasActiveUI):(!e.detail.args.isPressed||e.detail.args.isUp)&&(this._shouldDisable=!1))}onBeforeRender(){var e,t,s,o;if(!!this._controls){if(this._cameraObject!==this.context.mainCamera){this._controls.enabled=!1;return}if(this._controls.enabled=!0,(this.context.input.getPointerDown(1)||this.context.input.getPointerDown(2)||this.context.input.mouseWheelChanged||this.context.input.getPointerPressed(0)&&(e=this.context.input.getPointerPositionDelta(0))!=null&&e.length())&&(this._inputs+=1),this._inputs>0&&this.allowInterrupt&&(this.enableRotate&&(this.autoRotate=!1),this._cameraLerpActive=!1,this._lookTargetLerpActive=!1),this._inputs=0,this.autoTarget&&this._didSetTarget++===0){const r=P.getComponent(this.gameObject,ci);if(r&&!this.setLookTargetFromConstraint()){this.debugLog&&console.log("NO TARGET");const l=ee(r.threeCamera),c=Math.max(.01,l.length()),h=new S(0,0,-c).applyMatrix4(r.threeCamera.matrixWorld);is&&$.DrawLine(l,h,5592575,10),this.setLookTargetPosition(h,!0)}if(!this.setLookTargetFromConstraint()){const l=new Qs;l.screenPoint=new re(0,0),l.lineThreshold=.1;const c=this.context.physics.raycast(l);c.length>0&&this.setLookTargetPosition(c[0].point,!0),Bc&&console.log("OrbitControls hits",...c)}}if(this.middleClickToFocus&&this.context.input.getPointerClicked(1)&&this.setTargetFromRaycast(),this._lookTargetLerpActive||this._cameraLerpActive||this._fovLerpActive){if(this._cameraLerpActive&&this._cameraObject)if(this._cameraLerp01+=this.context.time.deltaTime/this._cameraLerpDuration,this._cameraLerp01>=1)this._cameraObject.position.copy(this._cameraEndPosition),this._cameraLerpActive=!1,this.dispatchEvent(new Fc(this,"camera"));else{const r=W.easeInOutCubic(this._cameraLerp01);this._cameraObject.position.lerpVectors(this._cameraStartPosition,this._cameraEndPosition,r)}if(this._lookTargetLerpActive)if(this._lookTargetLerp01+=this.context.time.deltaTime/this._lookTargetLerpDuration,this._lookTargetLerp01>=1)this._controls.target.copy(this._lookTargetEndPosition),this._lookTargetLerpActive=!1,this.dispatchEvent(new Fc(this,"lookat"));else{const r=W.easeInOutCubic(this._lookTargetLerp01);this._controls.target.lerpVectors(this._lookTargetStartPosition,this._lookTargetEndPosition,r)}if(this._fovLerpActive&&this._cameraObject){const r=this._cameraObject;if(this._fovLerp01+=this.context.time.deltaTime/this._fovLerpDuration,this._fovLerp01>=1)r.fov=this._fovLerpEndValue,this._fovLerpActive=!1;else{const l=W.easeInOutCubic(this._fovLerp01);r.fov=W.lerp(this._fovLerpStartValue,this._fovLerpEndValue,l)}r.updateProjectionMatrix()}}if(this._controls){if(this.debugLog&&(this._controls.domElement=this.context.renderer.domElement),this._controls.enabled=!this._shouldDisable&&this._camera===this.context.mainCameraComponent&&!this.context.isInXR&&!this._activePointerEvents.some(r=>r.used),this._controls.keys=this.enableKeys?$f:ET,this._controls.autoRotate=this.autoRotate,this._controls.autoRotateSpeed=this.autoRotateSpeed,this._controls.enableZoom=this.enableZoom,this._controls.zoomSpeed=this.zoomSpeed,this._controls.zoomToCursor=this.zoomToCursor,this._controls.enableDamping=this.enableDamping,this._controls.dampingFactor=this.dampingFactor,this._controls.enablePan=this.enablePan,this._controls.enableRotate=this.enableRotate,this._controls.minAzimuthAngle=this.minAzimuthAngle,this._controls.maxAzimuthAngle=this.maxAzimuthAngle,this._controls.minPolarAngle=this.minPolarAngle,this._controls.maxPolarAngle=this.maxPolarAngle,Vf||(((s=(t=this._camera)==null?void 0:t.threeCamera)==null?void 0:s.type)==="PerspectiveCamera"?(this._controls.minDistance=this.minZoom,this._controls.maxDistance=this.maxZoom,this._controls.minZoom=0,this._controls.maxZoom=1/0):(this._controls.minDistance=0,this._controls.maxDistance=1/0,this._controls.minZoom=this.minZoom,this._controls.maxZoom=this.maxZoom)),typeof Lu=="number"||Lu===!0){this._controls.enableDamping=!0;const r=typeof Lu=="number"?Lu:.99;this._controls.dampingFactor=Math.max(.001,1-Math.min(1,r))}this.allowInterrupt||(this._lookTargetLerpActive&&(this._controls.enablePan=!1),this._cameraLerpActive&&(this._controls.enableRotate=!1,this._controls.autoRotate=!1),(this._lookTargetLerpActive||this._cameraLerpActive)&&(this._controls.enableZoom=!1)),this.context.isInXR||(!Vf&&(o=this.lookAtConstraint)!=null&&o.locked&&this.setLookTargetFromConstraint(0,this.lookAtConstraint01),this._controls.update(this.context.time.deltaTime),is&&$.DrawWireSphere(this._controls.target,.1,65280))}}}setCameraAndLookTarget(e,t=!1){if(!e)return(F()||is)&&console.warn("[OrbitControls] setCameraAndLookTarget target is null"),!1;if(!(e instanceof E)&&!(e instanceof ci))return(F()||is)&&console.warn("[OrbitControls] setCameraAndLookTarget target is not an Object3D or Camera"),!1;e instanceof ci&&(e=e.gameObject);const s=e.worldPosition,o=e.worldForward;e instanceof QC&&(is&&console.debug("[OrbitControls] setCameraAndLookTarget flip forward direction for camera"),o.multiplyScalar(-1));const r=new po(s,o);return is&&$.DrawRay(r.origin,r.direction,16711680,10),this.setTargetFromRaycast(r,t)||this.setLookTargetPosition(r.at(2,q()),t),this.setCameraTargetPosition(s,t),!0}setCameraTargetPosition(e,t=!1){var s;e&&(e instanceof E&&(e=ee(e)),this._cameraEndPosition||(this._cameraEndPosition=new S),this._cameraEndPosition.copy(e),t===!0?(this._cameraLerpActive=!1,this._cameraObject&&this._cameraObject.position.copy(this._cameraEndPosition)):this._cameraObject&&(this._cameraLerpActive=!0,this._cameraLerp01=0,this._cameraStartPosition.copy((s=this._cameraObject)==null?void 0:s.position),typeof t=="number"?this._cameraLerpDuration=t:this._cameraLerpDuration=this.targetLerpDuration))}get cameraLerpActive(){return this._cameraLerpActive}stopCameraLerp(){this._cameraLerpActive=!1}setFieldOfView(e,t=!1){var s;if(!this._controls||typeof e!="number")return;const o=(s=this._camera)==null?void 0:s.threeCamera;o&&(t===!0?o.fov=e:(this._fovLerpActive=!0,this._fovLerp01=0,this._fovLerpStartValue=o.fov,this._fovLerpEndValue=e,typeof t=="number"?this._fovLerpDuration=t:this._fovLerpDuration=this.targetLerpDuration))}setLookTargetPosition(e=null,t=!1){this._controls&&e&&(e instanceof E&&(e=ee(e)),this._lookTargetEndPosition.copy(e),this._didSetTarget++,is&&(console.warn("OrbitControls: setLookTargetPosition",e,t),$.DrawWireSphere(this._lookTargetEndPosition,.2,16711680,2)),t===!0?this._controls.target.copy(this._lookTargetEndPosition):(this._lookTargetLerpActive=!0,this._lookTargetLerp01=0,this._lookTargetStartPosition.copy(this._controls.target),typeof t=="number"?this._lookTargetLerpDuration=t:this._lookTargetLerpDuration=this.targetLerpDuration))}get lookTargetLerpActive(){return this._lookTargetLerpActive}stopLookTargetLerp(){this._lookTargetLerpActive=!1}setLookTargetFromConstraint(e=0,t=1){var s,o;if(!this._controls||((s=this.lookAtConstraint)==null?void 0:s.enabled)===!1)return!1;const r=(o=this.lookAtConstraint)==null?void 0:o.sources;if(r&&r.length>0){const l=r[e];if(l)return l.getWorldPosition(this._lookTargetEndPosition),this.lerpLookTarget(this._lookTargetEndPosition,t),!0}return!1}lerpTarget(e,t){return this.lerpLookTarget(e,t)}lerpLookTarget(e,t){this._controls&&(t>=1?this._controls.target.copy(e):this._controls.target.lerp(e,t))}setTargetFromRaycast(e,t=!1){if(!this.controls)return!1;const s=e?this.context.physics.raycastFromRay(e):this.context.physics.raycast();for(const o of s)if(o.distance>0&&P.isActiveInHierarchy(o.object)){const r=Nf(o.object);if(r){const l=r.canvas;if(l!=null&&l.screenspace)break}return this.setLookTargetPosition(o.point,t),!0}return!1}fitCamera(e,t){var s,o;if(this.context.isInXR)return;let r;if(Array.isArray(e)?r=e:e&&"type"in e?r=e.children:e&&typeof e=="object"&&!(e instanceof E)&&!Array.isArray(e)&&(t=e,r=t.objects),r&&!Array.isArray(r)&&(r=r.children),(!Array.isArray(r)||r&&r.length<=0)&&(r=this.context.scene.children),!Array.isArray(r)||r.length<=0){console.warn("No objects to fit camera to...");return}const l=this._cameraObject,c=this._controls;if(!l||!c){console.warn("No camera or controls found to fit camera to objects...");return}t||(t={});const{immediate:h=!1,centerCamera:d="y",cameraNearFar:u="auto",fitOffset:p=1.1,fov:g=l?.fov}=t,f=new S,y=new S,v=si(r,void 0,(o=(s=this._camera)==null?void 0:s.threeCamera)==null?void 0:o.layers),b=v.clone();l.updateMatrixWorld(),l.updateProjectionMatrix(),v.getCenter(y);const _=new S;if(v.getSize(_),v.applyMatrix4(l.matrixWorldInverse),v.getSize(f),v.setFromCenterAndSize(y,f),Number.isNaN(f.x)||Number.isNaN(f.y)||Number.isNaN(f.z)){console.warn("Camera fit size resultet in NaN",l,v,[...r]);return}if(f.length()<=1e-10){Bc&&console.warn("Camera fit size is zero",v,[...r]);return}const w=t.fov||l.fov,x=2*Math.atan(Math.tan(w*Math.PI/360/2)*l.aspect)/Math.PI*360,k=f.y/(2*Math.atan(Math.PI*w/360)),M=f.x/(2*Math.atan(Math.PI*x/360)),T=p*Math.max(k,M)+f.z/2;Bc&&console.log("Fit camera to objects",{fitHeightDistance:k,fitWidthDistance:M,distance:T,verticalFov:w,horizontalFov:x}),this.maxZoom=T*10,this.minZoom=T*.01;const L=.05,D=y.clone();if(D.y-=f.y*L,this.setLookTargetPosition(D,h),this.setFieldOfView(t.fov,h),u==null||u=="auto"){const U=P.findObjectOfType(en),B=U?U.radius:0,Q=Math.max(_.x,_.y,_.z,B);l.near=T/100,l.far=Q+T*10,U&&(this.maxZoom=Math.max(Math.min(this.maxZoom,B*.5),T))}const z=c.getDistance();z<this.minZoom&&(this.minZoom=z*.9),z>this.maxZoom&&(this.maxZoom=z*1.1),l.updateMatrixWorld(),l.updateProjectionMatrix();const j=ee(l),H=y.clone();H.sub(j),d==="y"&&(H.y=0),H.normalize(),H.multiplyScalar(T),d==="y"&&(H.y+=-L*4*T);let K=y.clone().sub(H);l.parent&&(K=l.parent.worldToLocal(K)),this.setCameraTargetPosition(K,h),(Bc||t.debug)&&($.DrawWireBox3(v,16777011,10),$.DrawWireBox3(b,65280,10),!this._haveAttachedKeyboardEvents&&Bc&&(this._haveAttachedKeyboardEvents=!0,document.body.addEventListener("keydown",U=>{if(U.code==="KeyF"){let B;this._cameraObject instanceof we&&(B=Math.random()*Math.random()*170+10),this.fitCamera({objects:r,fitOffset:p,immediate:!1,fov:B})}U.code==="KeyV"&&this._cameraObject instanceof we&&(this._cameraObject.fov=60)}))),this.onBeforeRender()}}Ue([m()],_e.prototype,"autoTarget"),Ue([m()],_e.prototype,"autoFit"),Ue([m()],_e.prototype,"enableRotate"),Ue([m()],_e.prototype,"autoRotate"),Ue([m()],_e.prototype,"autoRotateSpeed"),Ue([m()],_e.prototype,"minAzimuthAngle"),Ue([m()],_e.prototype,"maxAzimuthAngle"),Ue([m()],_e.prototype,"minPolarAngle"),Ue([m()],_e.prototype,"maxPolarAngle"),Ue([m()],_e.prototype,"enableKeys"),Ue([m()],_e.prototype,"enableDamping"),Ue([m()],_e.prototype,"dampingFactor"),Ue([m()],_e.prototype,"enableZoom"),Ue([m()],_e.prototype,"minZoom"),Ue([m()],_e.prototype,"maxZoom"),Ue([m()],_e.prototype,"zoomSpeed"),Ue([m()],_e.prototype,"enablePan"),Ue([m(Fr)],_e.prototype,"lookAtConstraint"),Ue([m()],_e.prototype,"lookAtConstraint01"),Ue([m()],_e.prototype,"allowInterrupt"),Ue([m()],_e.prototype,"middleClickToFocus"),Ue([m()],_e.prototype,"doubleClickToFocus"),Ue([m()],_e.prototype,"clickBackgroundToFitScene"),Ue([m()],_e.prototype,"targetLerpDuration");var AT=Object.defineProperty,IT=Object.getOwnPropertyDescriptor,Yt=(n,e,t,s)=>{for(var o=s>1?void 0:s?IT(e,t):e,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=(s?l(e,t,o):l(o))||o);return s&&o&&AT(e,t,o),o},Io=(n=>(n[n.None=0]="None",n[n.Skybox=1]="Skybox",n[n.SolidColor=2]="SolidColor",n[n.Uninitialized=4]="Uninitialized",n))(Io||{});const Lo=C("debugcam"),Mx=C("debugscreenpointtoray");var jo;const Ut=(jo=class extends I{constructor(){super(...arguments),a(this,"_nearClipPlane",.1),a(this,"_farClipPlane",1e3),a(this,"orthographic",!1),a(this,"orthographicSize",5),a(this,"ARBackgroundAlpha",0),a(this,"_cullingMask",4294967295),a(this,"_backgroundBlurriness"),a(this,"_backgroundIntensity"),a(this,"_backgroundRotation"),a(this,"_environmentIntensity"),a(this,"_targetTexture",null),a(this,"_backgroundColor"),a(this,"_fov"),a(this,"_cam",null),a(this,"_clearFlags",2),a(this,"_skybox"),a(this,"_frustum"),a(this,"_projScreenMatrix",new se)}get isCamera(){return!0}get aspect(){return this._cam instanceof we?this._cam.aspect:this.context.domWidth/this.context.domHeight}set aspect(n){this._cam instanceof we&&this._cam.aspect!==n&&(this._cam.aspect=n,this._cam.updateProjectionMatrix())}get fieldOfView(){return this._cam instanceof we?this._cam.fov:this._fov}set fieldOfView(n){const e=this.fieldOfView!=n;if(this._fov=n,e&&this._cam&&this._cam instanceof we){if(this._fov===void 0){console.warn("Can not set undefined fov on PerspectiveCamera");return}this._cam.fov=this._fov,this._cam.updateProjectionMatrix()}}get nearClipPlane(){return this._nearClipPlane}set nearClipPlane(n){const e=this._nearClipPlane!=n;this._nearClipPlane=n,this._cam&&(e||this._cam.near!=n)&&(this._cam.near=n,this._cam.updateProjectionMatrix())}get farClipPlane(){return this._farClipPlane}set farClipPlane(n){const e=this._farClipPlane!=n;this._farClipPlane=n,this._cam&&(e||this._cam.far!=n)&&(this._cam.far=n,this._cam.updateProjectionMatrix())}applyClippingPlane(){this._cam&&(this._cam.near=this._nearClipPlane,this._cam.far=this._farClipPlane,this._cam.updateProjectionMatrix())}get clearFlags(){return this._clearFlags}set clearFlags(n){if(typeof n=="string")switch(n){case"skybox":n=1;break;case"solidcolor":n=2;break;default:n=0;break}n!==this._clearFlags&&(this._clearFlags=n,this.applyClearFlagsIfIsActiveCamera())}set cullingMask(n){this._cullingMask=n,this._cam&&(this._cam.layers.mask=n)}get cullingMask(){return this._cam?this._cam.layers.mask:this._cullingMask}set cullingLayer(n){this.cullingMask=(1<<n|0)>>>0}set backgroundBlurriness(n){n!==this._backgroundBlurriness&&(n===void 0?this._backgroundBlurriness=void 0:this._backgroundBlurriness=Math.min(Math.max(n,0),1),this.applyClearFlagsIfIsActiveCamera())}get backgroundBlurriness(){return this._backgroundBlurriness}set backgroundIntensity(n){n!==this._backgroundIntensity&&(n===void 0?this._backgroundIntensity=void 0:this._backgroundIntensity=Math.min(Math.max(n,0),10),this.applyClearFlagsIfIsActiveCamera())}get backgroundIntensity(){return this._backgroundIntensity}set backgroundRotation(n){n!==this._backgroundRotation&&(n===void 0?this._backgroundRotation=void 0:this._backgroundRotation=n,this.applyClearFlagsIfIsActiveCamera())}get backgroundRotation(){return this._backgroundRotation}set environmentIntensity(n){this._environmentIntensity=n}get environmentIntensity(){return this._environmentIntensity}get backgroundColor(){return this._backgroundColor??null}set backgroundColor(n){n&&(this._backgroundColor||(this._backgroundColor=new he(1,1,1,1)),this._backgroundColor.copy(n),(!("alpha"in n)||n.alpha===void 0)&&(this._backgroundColor.alpha=1),this.applyClearFlagsIfIsActiveCamera())}set targetTexture(n){this._targetTexture=n}get targetTexture(){return this._targetTexture}get cam(){return this.threeCamera}get threeCamera(){return this.activeAndEnabled&&this.buildCamera(),this._cam}screenPointToRay(n,e,t){const s=this.threeCamera,o=jo._origin;o.set(n,e,-1),this.context.input.convertScreenspaceToRaycastSpace(o),Mx&&console.log("screenPointToRay",n.toFixed(2),e.toFixed(2),"now:",o.x.toFixed(2),o.y.toFixed(2),"isInXR:"+this.context.isInXR),o.z=-1,o.unproject(s);const r=jo._direction.set(o.x,o.y,o.z),l=ee(s);return r.sub(l),r.normalize(),t?(t.set(l,r),t):new po(l.clone(),r.clone())}getFrustum(){return this._frustum||(this._frustum=new jv,this.updateFrustum()),this._frustum}updateFrustum(){this._frustum||(this._frustum=new jv),this._frustum.setFromProjectionMatrix(this.getProjectionScreenMatrix(this._projScreenMatrix,!0),this.context.renderer.coordinateSystem)}getProjectionScreenMatrix(n,e){return e&&this._projScreenMatrix.multiplyMatrices(this.threeCamera.projectionMatrix,this.threeCamera.matrixWorldInverse),n===this._projScreenMatrix?n:n.copy(this._projScreenMatrix)}awake(){Mx&&window.addEventListener("pointerdown",n=>{const e=n.clientX,t=n.clientY;console.log("touch",e.toFixed(2),t.toFixed(2));const s=this.screenPointToRay(e,t),o="#"+Math.floor(Math.random()*16777215).toString(16);$.DrawRay(s.origin,s.direction,o,10)})}onEnable(){Lo&&console.log(`Camera enabled: "${this.name}". ClearFlags=${Io[this._clearFlags]}`,this),this.buildCamera(),(this.tag=="MainCamera"||!this.context.mainCameraComponent)&&(this.context.setCurrentCamera(this),jT(this)),this.applyClearFlagsIfIsActiveCamera({applySkybox:!0})}onDisable(){this.context.removeCamera(this)}onBeforeRender(){if(this._cam&&(this._frustum&&this.updateFrustum(),this._clearFlags===2&&this.applyClearFlagsIfIsActiveCamera(),this._targetTexture)){this.context.isManagedExternally&&(this._warnedAboutExternalRenderer||(this._warnedAboutExternalRenderer=!0,console.warn("Rendering with external renderer is not supported yet. This may not work or throw errors. Please remove the the target texture from your camera: "+this.name,this.targetTexture))),this.context.composer;const n=this.context.renderer;if(n){const e=this.context.mainCameraComponent;this.applyClearFlags(),this._targetTexture.render(this.context.scene,this._cam,n),e?.applyClearFlags()}}}buildCamera(){if(this._cam)return;const n=this.gameObject.isCamera;let e=null;if(n?(e=this.gameObject,e?.layers.enableAll(),e instanceof we&&(this._fov=e.fov)):e=this.gameObject.children[0],e&&e.isCamera)e instanceof we&&(this._fov&&(e.fov=this._fov),e.near=this._nearClipPlane,e.far=this._farClipPlane,e.updateProjectionMatrix());else if(!this.orthographic)e=new we(this.fieldOfView,window.innerWidth/window.innerHeight,this._nearClipPlane,this._farClipPlane),this.fieldOfView&&(e.fov=this.fieldOfView),this.gameObject.add(e);else{const t=this.orthographicSize*100;e=new ud(window.innerWidth/-t,window.innerWidth/t,window.innerHeight/t,window.innerHeight/-t,this._nearClipPlane,this._farClipPlane),this.gameObject.add(e)}this._cam=e,this._cam.layers.mask=this._cullingMask,this.tag=="MainCamera"&&this.context.setCurrentCamera(this)}applyClearFlagsIfIsActiveCamera(n){this.context.mainCameraComponent===this&&this.applyClearFlags(n)}applyClearFlags(n){var e;if(!this._cam){Lo&&console.log("Camera does not exist (apply clear flags)");return}if(this.fieldOfView=this._fov,Lo){const s=`[Camera] Apply ClearFlags: ${Io[this._clearFlags]} - "${this.name}"`;console.debug(s)}const t=this.context.domElement.getAttribute("background-image")||this.context.domElement.getAttribute("background-color");switch(this._clearFlags){case 0:return;case 1:if(jo.backgroundShouldBeTransparent(this.context)&&(!this.ARBackgroundAlpha||this.ARBackgroundAlpha<.001)){this.context.scene.background=null,this.context.renderer.setClearColor(0,0);return}(!this.scene.background||!this._skybox||n?.applySkybox===!0)&&this.applySceneSkybox(),this._backgroundBlurriness!==void 0&&!this.context.domElement.getAttribute("background-blurriness")?this.context.scene.backgroundBlurriness=this._backgroundBlurriness:Lo&&console.warn(`Camera "${this.name}" has no background blurriness`),this._backgroundIntensity!==void 0&&!this.context.domElement.getAttribute("background-intensity")&&(this.context.scene.backgroundIntensity=this._backgroundIntensity),this._backgroundRotation!==void 0&&!this.context.domElement.getAttribute("background-rotation")?this.context.scene.backgroundRotation=this._backgroundRotation:Lo&&console.warn(`Camera "${this.name}" has no background intensity`);break;case 2:if(this._backgroundColor&&!t){let s=this._backgroundColor.alpha;jo.backgroundShouldBeTransparent(this.context)&&(s=this.ARBackgroundAlpha??0),this.context.scene.background=null,(e=this.context.xr)!=null&&e.isVR?this.context.renderer.setClearColor(kb(this._backgroundColor).convertLinearToSRGB()):this.context.renderer.setClearColor(this._backgroundColor,s)}else this._backgroundColor||Lo&&console.warn(`[Camera] has no background color "${this.name}" `);break;case 4:t||(this.context.scene.background=null,this.context.renderer.setClearColor(0,0));break}}applySceneSkybox(){this._skybox||(this._skybox=new LT(this)),this._skybox.apply()}static backgroundShouldBeTransparent(n){var e,t,s,o;const r=(e=n.renderer.xr)==null?void 0:e.getSession();if(!r)return!1;if(typeof r._transparent=="boolean")return r._transparent;const l=r.environmentBlendMode;Lo&&De("Environment blend mode: "+l+" on "+navigator.userAgent);let c=l==="additive"||l==="alpha-blend";return n.isInAR&&l==="opaque"&&((t=navigator.userAgent)!=null&&t.includes("OculusBrowser")||(s=navigator.userAgent)!=null&&s.includes("Mozilla")&&(o=navigator.userAgent)!=null&&o.includes("Mobile WebXRViewer/v2"))&&(c=!0),r._transparent=c,c}},a(jo,"_origin",new S),a(jo,"_direction",new S),jo);Yt([m()],Ut.prototype,"aspect",1),Yt([m()],Ut.prototype,"fieldOfView",1),Yt([m()],Ut.prototype,"nearClipPlane",1),Yt([m()],Ut.prototype,"farClipPlane",1),Yt([m()],Ut.prototype,"clearFlags",1),Yt([m()],Ut.prototype,"orthographic",2),Yt([m()],Ut.prototype,"orthographicSize",2),Yt([m()],Ut.prototype,"ARBackgroundAlpha",2),Yt([m()],Ut.prototype,"cullingMask",1),Yt([m()],Ut.prototype,"backgroundBlurriness",1),Yt([m()],Ut.prototype,"backgroundIntensity",1),Yt([m(Dt)],Ut.prototype,"backgroundRotation",1),Yt([m()],Ut.prototype,"environmentIntensity",1),Yt([m(he)],Ut.prototype,"backgroundColor",1),Yt([m(Ac)],Ut.prototype,"targetTexture",1);let ci=Ut;class LT{constructor(e){a(this,"_camera"),a(this,"_skybox"),this._camera=e}get context(){var e;return(e=this._camera)==null?void 0:e.context}apply(){var e;if(this._skybox=this.context.lightmaps.tryGetSkybox(this._camera.sourceId),!this._skybox)this._did_log_failed_to_find_skybox||(this._did_log_failed_to_find_skybox=!0,console.warn(`Camera "${this._camera.name}" has no skybox texture. ${this._camera.sourceId}`));else if(this.context.scene.background!==this._skybox){const t=this.context.domElement.getAttribute("background-image")||this.context.domElement.getAttribute("background-color")||this.context.domElement.getAttribute("skybox-image");Lo&&console.debug(`[Camera] Apply Skybox ${(e=this._skybox)==null?void 0:e.name} ${t} - "${this._camera.name}"`),t!=null&&t.length||(this._skybox.mapping=kn,this.context.scene.background=this._skybox)}}}function jT(n){C("freecam")&&n.context.mainCameraComponent===n&&P.getOrAddComponent(n.gameObject,_e)}class zn extends I{constructor(){super(...arguments),a(this,"_listener",null),a(this,"onInteraction",()=>{this.destroyed||this.listener==null||this.addListenerIfItExists()})}get listener(){return this._listener==null&&(this._listener=new YC),this._listener}onEnable(){Ln.registerWaitForInteraction(this.onInteraction),this.addListenerIfItExists()}onDisable(){Ln.unregisterWaitForInteraction(this.onInteraction),this.removeListenerIfItExists()}addListenerIfItExists(){const e=this._listener;if(!e||e!=null&&e.parent)return;const t=this.context.mainCameraComponent||P.getComponentInParent(this.gameObject,ci);t!=null&&t.threeCamera?t.threeCamera.add(e):this.gameObject.add(e),e.filter?(e.gain.connect(e.filter),e.filter.connect(e.context.destination)):e.gain.connect(e.context.destination)}removeListenerIfItExists(){const e=this._listener;e&&(e.removeFromParent(),e.filter&&e.filter.disconnect(),e.gain&&e.gain.disconnect())}}var DT=Object.defineProperty,BT=Object.getOwnPropertyDescriptor,Os=(n,e,t,s)=>{for(var o=s>1?void 0:s?BT(e,t):e,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=(s?l(e,t,o):l(o))||o);return s&&o&&DT(e,t,o),o};const Et=C("debugaudio"),ss=class ur extends I{constructor(){super(...arguments),a(this,"clip",""),a(this,"playOnAwake",!1),a(this,"preload",!0),a(this,"playInBackground",!0),a(this,"_spatialBlend",0),a(this,"_minDistance",1),a(this,"_maxDistance",100),a(this,"_volume",1),a(this,"rollOffMode",0),a(this,"_loop",!1),a(this,"sound",null),a(this,"helper",null),a(this,"wasPlaying",!1),a(this,"audioLoader",null),a(this,"shouldPlay",!1),a(this,"_lastClipStartedLoading",null),a(this,"_audioElement",null),a(this,"onVisibilityChanged",()=>{switch(document.visibilityState){case"hidden":(this.playInBackground===!1||X.isMobileDevice())&&(this.wasPlaying=this.isPlaying,this.isPlaying&&this.pause());break;case"visible":Et&&console.log("visible",this.enabled,this.playOnAwake,!this.isPlaying,ur.userInteractionRegistered,this.wasPlaying),this.enabled&&this.playOnAwake&&!this.isPlaying&&ur.userInteractionRegistered&&this.wasPlaying&&this.play();break}}),a(this,"onApplicationMuteChanged",()=>{var e,t;this.context.application.muted?(e=this.sound)==null||e.setVolume(0):(t=this.sound)==null||t.setVolume(this.volume)}),a(this,"createAudio",e=>{if(this.destroyed){Et&&console.warn("AudioSource destroyed, not creating audio",this.name);return}Et&&console.log("AudioBuffer finished loading",e);const t=this.Sound;if(!t){Et&&console.warn("Failed getting sound?",this.name);return}t.isPlaying&&t.stop(),e&&t.setBuffer(e),t.loop=this._loop,this.context.application.muted?t.setVolume(0):t.setVolume(this.volume),t.autoplay=this.shouldPlay&&ur.userInteractionRegistered,this.applySpatialDistanceSettings(),t.isPlaying&&t.stop(),ur.registerWaitForAllowAudio(this.__onAllowAudioCallback)}),a(this,"__onAllowAudioCallback",()=>{this.shouldPlay&&this.play()}),a(this,"_lastContextTime",0),a(this,"_hasEnded",!0),a(this,"_needUpdateSpatialDistanceSettings",!1)}static get userInteractionRegistered(){return Ln.userInteractionRegistered}static registerWaitForAllowAudio(e){Ln.registerWaitForInteraction(e)}get isPlaying(){var e;return((e=this.sound)==null?void 0:e.isPlaying)??!1}get duration(){var e,t;return(t=(e=this.sound)==null?void 0:e.buffer)==null?void 0:t.duration}get time01(){var e;const t=this.duration;return t&&this.sound?((e=this.sound)==null?void 0:e.context.currentTime)/t:0}set time01(e){const t=this.duration;t&&this.sound&&(this.time=e*t)}get time(){var e,t;return(e=this.sound)!=null&&e.source?((t=this.sound.source)==null?void 0:t.context.currentTime)-this._lastContextTime+this.sound.offset:0}set time(e){if(this.sound){if(e===this.sound.offset)return;const t=this.isPlaying;this.stop(),this.sound.offset=e,t&&this.play()}}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)}get volume(){return this._volume}set volume(e){this._volume=e,this.sound&&!this.context.application.muted&&(Et&&console.log(this.name,"audio set volume",e),this.sound.setVolume(e))}set pitch(e){this.sound&&this.sound.setPlaybackRate(e)}get pitch(){return this.sound?this.sound.getPlaybackRate():1}get Sound(){var e;if(!this.sound&&ur.userInteractionRegistered){let t=this.gameObject.getComponent(zn)??this.context.mainCamera.getComponent(zn)??xc(zn,this.context,!1);!t&&this.context.mainCamera&&(t=this.context.mainCamera.addComponent(zn)),t!=null&&t.listener?(this.sound=new KC(t.listener),(e=this.gameObject)==null||e.add(this.sound)):Et&&console.warn("No audio listener found in scene - can not play audio")}return this.sound}get ShouldPlay(){return this.shouldPlay}get audioContext(){var e;return(e=this.sound)==null?void 0:e.context}awake(){Et&&console.log("[AudioSource]",this),this.audioLoader=new jm,this.playOnAwake&&(this.shouldPlay=!0),this.preload&&typeof this.clip=="string"&&this.audioLoader.load(this.clip,this.createAudio,()=>{},console.error)}onEnable(){this.sound&&this.gameObject.add(this.sound),ur.userInteractionRegistered?this.playOnAwake&&this.context.application.isVisible&&this.play():ur.registerWaitForAllowAudio(()=>{this.enabled&&!this.destroyed&&this.shouldPlay&&this.onNewClip(this.clip)}),globalThis.addEventListener("visibilitychange",this.onVisibilityChanged),this.context.application.addEventListener(Og.MuteChanged,this.onApplicationMuteChanged)}onDisable(){globalThis.removeEventListener("visibilitychange",this.onVisibilityChanged),this.context.application.removeEventListener(Og.MuteChanged,this.onApplicationMuteChanged),this.pause()}applySpatialDistanceSettings(){const e=this.sound;if(!e)return;this._needUpdateSpatialDistanceSettings=!1;const t=W.lerp(10*this._maxDistance/Math.max(1e-4,this.spatialBlend),this._minDistance,this.spatialBlend);switch(Et&&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:console.warn("Custom rolloff for AudioSource is not supported: "+this.name);break}this.spatialBlend>0?Et&&!this.helper&&(this.helper=new tO(e,e.getRefDistance()),e.add(this.helper)):this.helper&&this.helper.parent&&this.helper.removeFromParent()}async onNewClip(e){if(e&&(this.clip=e),typeof e=="string")if(Et&&console.log(e),e.endsWith(".mp3")||e.endsWith(".wav")){if(this.audioLoader||(this.audioLoader=new jm),this.shouldPlay=!0,this._lastClipStartedLoading===e){Et&&console.log("Is currently loading:",this._lastClipStartedLoading,this);return}this._lastClipStartedLoading=e,Et&&console.log("load audio",e);const t=await this.audioLoader.loadAsync(e).catch(console.error);if(this.destroyed)return;this._lastClipStartedLoading===e&&(this._lastClipStartedLoading=null),t&&this.createAudio(t)}else console.warn("Unsupported audio clip type",e);else this.shouldPlay=!0,this.createAudio()}play(e=void 0){var t,s,o;!e&&this.clip&&(e=this.clip),e!==void 0&&typeof e!="string"&&!(e instanceof MediaStream)&&(F()&&console.warn("Called play on AudioSource with unknown argument type:",e+`
|
|
940
940
|
Using the assigned clip instead:`,this.clip),e=this.clip);let r=!this.sound||e&&e!==this.clip;if(typeof e=="string"&&!this.audioLoader&&(r=!0),(e instanceof MediaStream||typeof e=="string")&&(this.clip=e),r){this.shouldPlay=!0,this.onNewClip(e);return}if(this.shouldPlay=!0,this._hasEnded=!1,Et&&console.log("play",(t=this.sound)==null?void 0:t.getVolume(),this.sound),this.sound&&!this.sound.isPlaying){const l=this.context.application.muted;l&&this.sound.setVolume(0),(s=this.gameObject)==null||s.add(this.sound),this.clip instanceof MediaStream?(this.sound.setMediaStreamSource(this.clip),this._audioElement||(this._audioElement=document.createElement("audio"),this._audioElement.style.display="none"),this._audioElement.parentNode||(o=this.context.domElement.shadowRoot)==null||o.append(this._audioElement),this._audioElement.srcObject=this.clip,this._audioElement.autoplay=!1):(this._audioElement&&this._audioElement.remove(),this.sound.play(l?.1:0))}}pause(){var e,t;Et&&console.log("Pause",this),this._hasEnded=!0,this.shouldPlay=!1,this.sound&&this.sound.isPlaying&&this.sound.source&&(this._lastContextTime=(e=this.sound)==null?void 0:e.context.currentTime,this.sound.pause()),(t=this._audioElement)==null||t.remove()}stop(){var e,t;Et&&console.log("Pause",this),this._hasEnded=!0,this.shouldPlay=!1,this.sound&&this.sound.source&&(this._lastContextTime=(e=this.sound)==null?void 0:e.context.currentTime,Et&&console.log(this._lastContextTime),this.sound.stop()),(t=this._audioElement)==null||t.remove()}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,Et&&console.log("Audio clip ended",this.clip),this.dispatchEvent(new CustomEvent("ended",{detail:this})))}};Os([m(URL)],ss.prototype,"clip",2),Os([m()],ss.prototype,"playOnAwake",2),Os([m()],ss.prototype,"preload",2),Os([m()],ss.prototype,"playInBackground",2),Os([m()],ss.prototype,"loop",1),Os([m()],ss.prototype,"spatialBlend",1),Os([m()],ss.prototype,"minDistance",1),Os([m()],ss.prototype,"maxDistance",1),Os([m()],ss.prototype,"volume",1),Os([m()],ss.prototype,"pitch",1),Os([m()],ss.prototype,"rollOffMode",2);let ns=ss;const FT=C("debugavatar"),ju=class wn extends I{constructor(){super(...arguments),a(this,"connectionId"),a(this,"avatar")}static getAvatar(e){return e>=0&&e<wn.instances.length?wn.instances[e]:null}static onAvatarMarkerCreated(e){return wn._onNewAvatarMarkerAdded.push(e),e}static onAvatarMarkerDestroyed(e){return wn._onAvatarMarkerDestroyed.push(e),e}awake(){wn.instances.push(this),FT&&console.log(this);for(const e of wn._onNewAvatarMarkerAdded)e({avatarMarker:this,gameObject:this.gameObject})}onDestroy(){wn.instances.splice(wn.instances.indexOf(this),1);for(const e of wn._onAvatarMarkerDestroyed)e({avatarMarker:this,gameObject:this.gameObject})}isLocalAvatar(){return this.connectionId===this.context.connection.connectionId}};a(ju,"instances",[]),a(ju,"_onNewAvatarMarkerAdded",[]),a(ju,"_onAvatarMarkerDestroyed",[]);let hi=ju;class Nn{static Add(e,t,s=null){if(t){for(const o of this.Pois)if(o.obj===t)return;this.Pois.push({obj:t,avatar:s}),this.LastChangeTime=e.time.time}}static Remove(e,t){var s;if(t){for(const o of this.Pois)if(o.obj===t){this.Pois.splice(this.Pois.indexOf(o),1),this.LastChangeTime=e?.time.time??((s=J.Current)==null?void 0:s.time.time);return}}}}a(Nn,"Pois",[]),a(Nn,"LastChangeTime",0);class UT{constructor(){a(this,"guid"),a(this,"position",new S)}}class Uc extends I{constructor(){super(...arguments),a(this,"target",null),a(this,"avatar",null),a(this,"_model",null),a(this,"_targetModel",new UT),a(this,"_currentTargetObject",null),a(this,"_lastUpdateTime",0),a(this,"_lookDuration",0),a(this,"_lastPoiChangedTime",0)}set controlledTarget(e){this.target=e;const t=R.get("MoveRandom");if(t&&this.target){const s=P.getComponent(this.target,t);s&&s.destroy()}}awake(){if(this.avatar=P.getComponentInParent(this.gameObject,hi),this.avatar){const e=P.getComponentInParent(this.gameObject,hi);this._model=new Ag(this.context.connection,this.guid),e!=null&&e.isLocalAvatar&&this._model.requestOwnership()}this.context.connection.beginListen("avatar-look-target-changed",e=>{var t;this.target&&e&&e.guid===((t=this.avatar)==null?void 0:t.guid)&<(this.target,e.position)})}update(){var e;if((!this.context.connection.isConnected||(e=this._model)!=null&&e.hasOwnership)&&(Nn.LastChangeTime!==this._lastPoiChangedTime&&(this._lastPoiChangedTime=Nn.LastChangeTime,this._lookDuration=0),this.selectTarget(),this._currentTargetObject&&this.context.time.frameCount%10===0&&this.target)){const t=ee(this._currentTargetObject);lt(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;const e=Nn.Pois;if(e.length>0){const t=e[Math.floor(Math.random()*e.length)];if(t&&t.obj){if(t.avatar&&t.avatar===this.avatar)return;this._currentTargetObject=t.obj}}}}}function Rx(n){const e=n;return!!(e.parser&&e.parser.json)}var Du=(n=>(n[n.None=0]="None",n[n.DontExport=1]="DontExport",n))(Du||{});function Tx(n){return n&&n.isComponent}const zT=Symbol("object"),Hf=new Oi(()=>new S,20);class Ex{constructor(e,t,s,o,r,l){a(this,"_point"),a(this,"_normal"),a(this,"_tangentVelocity"),a(this,"distance"),a(this,"impulse"),a(this,"friction"),this._point=e,this.distance=t,this._normal=s,this.impulse=o,this.friction=r,this._tangentVelocity=l}get point(){return Hf.get().set(this._point.x,this._point.y,this._point.z)}get normal(){return Hf.get().set(this._normal.x,this._normal.y,this._normal.z)}get tangentVelocity(){return Hf.get().set(this._tangentVelocity.x,this._tangentVelocity.y,this._tangentVelocity.z)}}class Ax{constructor(e,t,s){a(this,"contacts"),a(this,"me"),a(this,"_collider"),a(this,"_gameObject"),this.me=e,this._collider=t,this._gameObject=t.gameObject,this.contacts=s}get collider(){return this._collider}get gameObject(){return this._gameObject}get rigidBody(){var e;return(e=this.collider)==null?void 0:e.attachedRigidbody}}class Ix{constructor(e,t){a(this,"object"),a(this,"collider"),this.object=e,this.collider=t}}const Ye=C("debugnetworkingstreams");var nn=(n=>(n.Connected="peer-user-connected",n.StreamReceived="receive-stream",n.StreamEnded="call-ended",n.Disconnected="peer-user-disconnected",n.UserJoined="user-joined",n))(nn||{});class Gf{constructor(e,t){a(this,"type","call-ended"),a(this,"userId"),a(this,"direction"),this.userId=e,this.direction=t}}class Lx{constructor(e,t,s){a(this,"type","receive-stream"),a(this,"userId"),a(this,"stream"),a(this,"target"),this.userId=e,this.stream=t,this.target=s}}class NT{constructor(e,t){a(this,"guid"),a(this,"peerId"),a(this,"dontSave",!0),this.guid=e.id,this.peerId=t}}var jx=(n=>(n.Incoming="incoming",n.Outgoing="outgoing",n))(jx||{});class WT extends Dm{constructor(e,t,s,o=null){super(),a(this,"peerId"),a(this,"userId"),a(this,"direction"),a(this,"call"),a(this,"_stream",null),a(this,"_isDisposed",!1),this.peerId=t.peer,this.userId=e,this.call=t,this.direction=s,this._stream=o,t.on("stream",r=>{if(Ye&&console.log("Receive stream",`
|
|
941
941
|
Audio:`,r.getAudioTracks(),`
|
|
942
942
|
Video:`,r.getVideoTracks()),this._stream=r,s==="incoming"){const l=new Lx(e,r,this);this.dispatchEvent(l)}}),t.on("close",()=>{this.dispatchEvent(new Gf(e,s))})}get stream(){return this._stream}close(){this._isDisposed||(this._isDisposed=!0,this.call.close(),on(this._stream))}get isOpen(){var e;return((e=this.call.peerConnection)==null?void 0:e.connectionState)==="connected"}get isOpening(){var e;return((e=this.call.peerConnection)==null?void 0:e.connectionState)==="connecting"}get isClosed(){return!this.isOpen||this._isDisposed}}function Dx(n){return n=n.replace("a=fmtp:111 minptime=10;useinbandfec=1","a=fmtp:111 ptime=5;useinbandfec=1;stereo=1;maxplaybackrate=48000;maxaveragebitrat=128000;sprop-stereo=1"),n}const Bx=class nd extends Dm{constructor(e,t){super(),a(this,"updateCalls",()=>{var s;for(let o=this._incomingCalls.length-1;o>=0;o--){const r=this._incomingCalls[o];r.isClosed&&!r.isOpening&&this._incomingCalls.splice(o,1)}for(let o=this._outgoingCalls.length-1;o>=0;o--){const r=this._outgoingCalls[o];let l=!1;r.isClosed&&!r.isOpening&&((s=r.stream)!=null&&s.active?Ye&&console.warn("!!! Stream is still active, don't remove call",r.userId,"Your id: "+this.context.connection.connectionId):(Ye&&console.warn("!!! Remove closed call",r.userId),l=!0)),this.context.connection.userIsInRoom(r.userId)===!1&&(Ye&&console.warn("!!! User is not in room anymore, remove call",r.userId),l=!0),l&&(r.close(),this._outgoingCalls.splice(o,1))}}),a(this,"id"),a(this,"context"),a(this,"_incomingCalls",[]),a(this,"_outgoingCalls",[]),a(this,"_peer"),a(this,"_enabled",!1),a(this,"_enabledPeer",!1),a(this,"onConnectRoomFn",this.onConnectRoom.bind(this)),a(this,"onPeerConnect",s=>{if(Ye&&console.log("PEER opened as",s),s===null){console.error("Peer connection failed",s);return}this.context.connection.send("peer-user-connected",new NT(this,s))}),a(this,"onPeerClose",()=>{Ye&&console.log("PEER closed"),this.updateCalls()}),a(this,"onPeerDisconnected",()=>{Ye&&console.log("PEER disconnected"),this.updateCalls()}),a(this,"onPeerError",s=>{Ye&&console.error("PEER error",s)}),a(this,"onPeerReceivingCall",s=>{s.answer(void 0,{sdpTransform:o=>Dx(o)}),this.registerCall(s,"incoming",null)}),this.context=e,this.id=t,this.setupPeer(),navigator.getUserMedia=navigator.getUserMedia||navigator.webkitGetUserMedia||navigator.mozGetUserMedia||navigator.msGetUserMedia}static getOrCreate(e,t){if(nd.instances.has(t))return nd.instances.get(t);const s=new nd(e,t);return nd.instances.set(t,s),s}getMyPeerId(){if(this.context.connection.connectionId)return this.getPeerIdFromUserId(this.context.connection.connectionId)}getPeerIdFromUserId(e){return this.id+"-"+e}getUserIdFromPeerId(e){return e.substring(this.id.length+1)}makeCall(e,t){var s;if(!(t!=null&&t.id)){Ye?console.warn("Can not make a call: mediastream has no id or is undefined"):console.debug("Can not make a call: mediastream has no id or is undefined");return}const o={metadata:{userId:this.context.connection.connectionId,streamId:t.id},sdpTransform:l=>Dx(l)},r=(s=this._peer)==null?void 0:s.call(e,t,o);if(r){const l=this.registerCall(r,"outgoing",t);return Ye&&console.warn(`\u{1F4DE} CALL ${e}`,`
|
|
@@ -954,7 +954,7 @@ Incoming:`,this._incomingCalls),l}else Ye&&console.error("Failed to make call",e
|
|
|
954
954
|
|
|
955
955
|
Device: ${this._deviceMode}
|
|
956
956
|
|
|
957
|
-
`,.03);const k=this._bottomCenter.clone(),M=this._backCenter.clone(),T=this._backBottomCenter.clone();t.localToWorld(k),t.localToWorld(M),t.localToWorld(T),$.DrawSphere(k,.01,65280,0,!1),$.DrawSphere(M,.01,255,0,!1),$.DrawSphere(T,.01,16711935,0,!1),$.DrawLine(k,T,65535,0,!1),$.DrawLine(T,M,65535,0,!1)}}onDragEnd(e){console.assert(this._followObject.parent===e.event.space,"Drag end: _followObject is not parented to the space object"),this._followObject.removeFromParent(),this._followObject.destroy(),this._lastDragPosRigSpace=void 0}setPlaneViewAligned(e,t){if(!this._followObject.parent)return!1;const s=this._followObject.parent.worldForward,o=q(0,1,0),r=s,l=o.angleTo(r),c=.5;return t&&(l>Math.PI/2+c||l<Math.PI/2-c)?this._dragPlane.setFromNormalAndCoplanarPoint(o,e):this._dragPlane.setFromNormalAndCoplanarPoint(s,e),!0}}const Hx=class bC{constructor(e){a(this,"showGizmo",!0),a(this,"useViewAngle",!0),a(this,"_selected",null),a(this,"_context",null),a(this,"_camera"),a(this,"_cameraPlane",new yr),a(this,"_hasGroundPlane",!1),a(this,"_groundPlane",new yr),a(this,"_groundOffset",new S),a(this,"_groundOffsetFactor",0),a(this,"_groundDistance",0),a(this,"_groundPlanePoint",new S),a(this,"_raycaster",new md),a(this,"_cameraPlaneOffset",new S),a(this,"_intersection",new S),a(this,"_worldPosition",new S),a(this,"_inverseMatrix",new se),a(this,"_rbs",[]),a(this,"_groundLine"),a(this,"_groundMarker"),a(this,"_groundOffsetVector",new S(0,1,0)),a(this,"_requireUpdateGroundPlane",!0),a(this,"_didDragOnGroundPlaneLastFrame",!1),this._camera=e;const t=new $l(bC.geometry),s=t.material;s.color=new oe(.4,.4,.4),t.layers.set(2),t.name="line",t.scale.y=1,this._groundLine=t;const o=new pd(.5,22,22),r=new Me({color:s.color}),l=new G(o,r);l.visible=!1,l.layers.set(2),this._groundMarker=l}get hasSelected(){return this._selected!==null&&this._selected!==void 0}get selected(){return this._selected}setSelected(e,t){if(this._selected&&t)for(const s of this._rbs)s.wakeUp(),s.setVelocity(0,0,0);if(this._selected&&Nn.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}Nn.Add(t,this._selected,null),this._groundOffsetFactor=0,this._hasGroundPlane=!0,this._groundOffset.set(0,0,0),this._requireUpdateGroundPlane=!0,this.onUpdateScreenSpacePlane()}}onUpdate(e){this._selected}onUpdateWorldPosition(e,t,s){if(this._selected){if(s){const o=ee(this._selected);o.y=e.y,e=o}if(lt(this._selected,e),lt(this._groundLine,e),this._hasGroundPlane?this._groundLine.scale.y=this._groundDistance:this._groundLine.scale.y=1e3,this._groundLine.visible=this.showGizmo,this._groundMarker.visible=t!==null&&this.showGizmo,t){const o=ee(this._camera).distanceTo(t)*.01;this._groundMarker.scale.set(o,o,o),lt(this._groundMarker,t)}}}onUpdateScreenSpacePlane(){if(!this._selected||!this._context)return;const 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;const e=ee(this._selected),t=new po(q(0,.1,0).add(e),q(0,-1,0)),s=new Qs;s.testObject=r=>r!==this._selected;const o=this._context.physics.raycastFromRay(t,s);for(let r=0;r<o.length;r++){const l=o[r];if(!l.face||this.contains(this._selected,l.object))continue;const c=q(0,1,0);this._groundPlane.setFromNormalAndCoplanarPoint(c,l.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)}contains(e,t){if(e===t)return!0;if(e.children){for(const s of e.children)if(this.contains(s,t))return!0}return!1}};a(Hx,"geometry",new Vs().setFromPoints([new S(0,0,0),new S(0,-1,0)]));let
|
|
957
|
+
`,.03);const k=this._bottomCenter.clone(),M=this._backCenter.clone(),T=this._backBottomCenter.clone();t.localToWorld(k),t.localToWorld(M),t.localToWorld(T),$.DrawSphere(k,.01,65280,0,!1),$.DrawSphere(M,.01,255,0,!1),$.DrawSphere(T,.01,16711935,0,!1),$.DrawLine(k,T,65535,0,!1),$.DrawLine(T,M,65535,0,!1)}}onDragEnd(e){console.assert(this._followObject.parent===e.event.space,"Drag end: _followObject is not parented to the space object"),this._followObject.removeFromParent(),this._followObject.destroy(),this._lastDragPosRigSpace=void 0}setPlaneViewAligned(e,t){if(!this._followObject.parent)return!1;const s=this._followObject.parent.worldForward,o=q(0,1,0),r=s,l=o.angleTo(r),c=.5;return t&&(l>Math.PI/2+c||l<Math.PI/2-c)?this._dragPlane.setFromNormalAndCoplanarPoint(o,e):this._dragPlane.setFromNormalAndCoplanarPoint(s,e),!0}}const Hx=class bC{constructor(e){a(this,"showGizmo",!0),a(this,"useViewAngle",!0),a(this,"_selected",null),a(this,"_context",null),a(this,"_camera"),a(this,"_cameraPlane",new yr),a(this,"_hasGroundPlane",!1),a(this,"_groundPlane",new yr),a(this,"_groundOffset",new S),a(this,"_groundOffsetFactor",0),a(this,"_groundDistance",0),a(this,"_groundPlanePoint",new S),a(this,"_raycaster",new md),a(this,"_cameraPlaneOffset",new S),a(this,"_intersection",new S),a(this,"_worldPosition",new S),a(this,"_inverseMatrix",new se),a(this,"_rbs",[]),a(this,"_groundLine"),a(this,"_groundMarker"),a(this,"_groundOffsetVector",new S(0,1,0)),a(this,"_requireUpdateGroundPlane",!0),a(this,"_didDragOnGroundPlaneLastFrame",!1),this._camera=e;const t=new $l(bC.geometry),s=t.material;s.color=new oe(.4,.4,.4),t.layers.set(2),t.name="line",t.scale.y=1,this._groundLine=t;const o=new pd(.5,22,22),r=new Me({color:s.color}),l=new G(o,r);l.visible=!1,l.layers.set(2),this._groundMarker=l}get hasSelected(){return this._selected!==null&&this._selected!==void 0}get selected(){return this._selected}setSelected(e,t){if(this._selected&&t)for(const s of this._rbs)s.wakeUp(),s.setVelocity(0,0,0);if(this._selected&&Nn.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}Nn.Add(t,this._selected,null),this._groundOffsetFactor=0,this._hasGroundPlane=!0,this._groundOffset.set(0,0,0),this._requireUpdateGroundPlane=!0,this.onUpdateScreenSpacePlane()}}onUpdate(e){this._selected}onUpdateWorldPosition(e,t,s){if(this._selected){if(s){const o=ee(this._selected);o.y=e.y,e=o}if(lt(this._selected,e),lt(this._groundLine,e),this._hasGroundPlane?this._groundLine.scale.y=this._groundDistance:this._groundLine.scale.y=1e3,this._groundLine.visible=this.showGizmo,this._groundMarker.visible=t!==null&&this.showGizmo,t){const o=ee(this._camera).distanceTo(t)*.01;this._groundMarker.scale.set(o,o,o),lt(this._groundMarker,t)}}}onUpdateScreenSpacePlane(){if(!this._selected||!this._context)return;const 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;const e=ee(this._selected),t=new po(q(0,.1,0).add(e),q(0,-1,0)),s=new Qs;s.testObject=r=>r!==this._selected;const o=this._context.physics.raycastFromRay(t,s);for(let r=0;r<o.length;r++){const l=o[r];if(!l.face||this.contains(this._selected,l.object))continue;const c=q(0,1,0);this._groundPlane.setFromNormalAndCoplanarPoint(c,l.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)}contains(e,t){if(e===t)return!0;if(e.children){for(const s of e.children)if(this.contains(s,t))return!0}return!1}};a(Hx,"geometry",new Vs().setFromPoints([new S(0,0,0),new S(0,-1,0)]));let oj=Hx;var Gx=(n=>(n.File_Spawned="file-spawned",n))(Gx||{});class cE{constructor(e,t,s,o,r,l,c,h,d){a(this,"guid"),a(this,"file_name"),a(this,"file_hash"),a(this,"file_size"),a(this,"position"),a(this,"scale"),a(this,"seed"),a(this,"sender"),a(this,"downloadUrl"),a(this,"parentGuid"),a(this,"boundsSize"),this.seed=t,this.guid=s,this.file_name=o,this.file_hash=r,this.file_size=l,this.position=c,this.scale=h,this.sender=e,this.downloadUrl=d}}var zo;(n=>{const e=new Map;function t(o){var r;e.has(o.guid)&&s(o.guid);const l=new E;e.set(o.guid,l);const c=new E;c.position.y=-.5,l.add(c);const h=new G(new xa(1,1,1,1,1,1),new Me({color:14540253,wireframe:!0,transparent:!0,opacity:.3}));h.position.y=.5,c.add(h);const d=new E;c.add(d);const u=new G(new xa(1,1,1,1,1,1),new Me({color:12307660,transparent:!0,opacity:.4}));u.position.y=.5,d.scale.y=.01,d.add(u);const p=new G(new Ns(1,1,1,1),new Me({color:34,transparent:!0,opacity:.05,depthTest:!1}));return p.rotateX(-Math.PI/2),p.position.y=.51,u.add(p),o.parent.add(l),l.rotateY(Math.PI/2),o.position&&((r=l.position)==null||r.copy(o.position)),o.size&&(l.worldScale=new S().copy(o.size)),l.position.y=l.scale.y/2,{object:l,onProgress:g=>{d instanceof E&&d.scale.set(1,g,1)}}}n.addPreview=t;function s(o){const r=e.get(o);r&&(e.delete(o),r.removeFromParent())}n.removePreview=s})(zo||(zo={}));const il=[],$u=[];var l0;(n=>{function e(s,o){const r={name:o?.name,priority:o?.priority??0,callback:s};return il.push(r),il.sort((l,c)=>l.priority===c.priority?0:l.priority>c.priority?-1:1),()=>{const l=il.indexOf(r);l>=0&&il.splice(l,1)}}n.onCreateCustomModelLoader=e;function t(s){return $u.push(s),()=>{const o=$u.indexOf(s);o>=0&&$u.splice(o,1)}}n.onDetermineModelMimetype=t})(l0||(l0={}));const Hc=C("debugfileformat");function qx(n){switch((n.split(".").pop()||n).toUpperCase()){case"GLTF":return"model/gltf+json";case"VRM":return"model/vrm";case"GLB":return"model/gltf-binary";case"FBX":return"model/fbx";case"USD":return"model/vnd.usd+zip";case"USDA":return"model/vnd.usda+zip";case"USDZ":return"model/vnd.usdz+zip";case"OBJ":return"model/obj";default:return null}}async function Xx(n,e){var t;const{useExtension:s=!0}=e;if(s){const l=n,c=new URL(l,globalThis.location.href);let h=null;const d=c.searchParams.get("filetype");switch(d&&(h=d.toUpperCase()),h!=null&&h.length||(h=(t=c.pathname.split(".").pop())==null?void 0:t.toUpperCase()),Hc&&console.warn(`[Needle Engine] Try to use file extension to determine type: '${h}'`),h){case"GLTF":return"model/gltf+json";case"VRM":return"model/vrm";case"GLB":return"model/gltf-binary";case"FBX":return"model/fbx";case"USD":return"model/vnd.usd+zip";case"USDA":return"model/vnd.usda+zip";case"USDZ":return"model/vnd.usdz+zip";case"OBJ":return"model/obj"}}const o=n;if(!n.startsWith("blob:")){const l=new URL(n,globalThis.location.href);l.searchParams.append("range","true"),n=l.toString()}const r=await fetch(n,{method:"GET",headers:{range:"bytes=0-32"}}).catch(l=>null);if(r!=null&&r.ok){const l=await r.arrayBuffer(),c=Qx(o,l,r);return Hc&&console.log("[Needle Engine] Determined file type from header: "+c),c}return"unknown"}function Qx(n,e,t){if(e.byteLength<4)return"unknown";const s=new Uint8Array(e);if(Hc&&console.warn(`[Needle Engine] Trying to determine file type from binary data
|
|
958
958
|
`,'"'+new TextDecoder().decode(e)+`"
|
|
959
959
|
`,s),s[0]==103&&s[1]==108&&s[2]==84&&s[3]==70&&(s[4]==10||s[4]===2))return console.debug("GLTF detected"),"model/gltf+json";if(s[0]==103&&s[1]==108&&s[2]==84&&s[3]==70&&s[4]==98)return console.debug("GLB detected"),"model/gltf-binary";if(s[0]==80&&s[1]==75&&s[2]==3&&s[3]==4)return console.debug("USDZ detected"),"model/vnd.usdz+zip";if(s[0]==80&&s[1]==88&&s[2]==82&&s[3]==45&&s[4]==85&&s[5]==83&&s[6]==68&&s[7]==67)return console.debug("Binary USD detected"),"model/vnd.usd";if(s[0]==35&&s[1]==117&&s[2]==115&&s[3]==100&&s[4]==97)return console.debug("ASCII USD detected"),"model/vnd.usda";if(s[0]==75&&s[1]==97&&s[2]==121&&s[3]==100&&s[4]==97&&s[5]==114&&s[6]==97&&s[7]==32)return console.debug("Binary FBX detected"),"model/fbx";if(s[0]==59&&s[1]==32&&s[2]==70&&s[3]==66&&s[4]==88&&s[5]==32)return console.debug("ASCII FBX detected"),"model/fbx";if(s[0]==35&&s[1]==32&&s[2]==66&&s[3]==108&&s[4]==101&&s[5]==110&&s[6]==100&&s[7]==101&&s[8]==114&&s[9]==32||s[0]==35&&s[1]==32&&s[2]==65&&s[3]==108&&s[4]==105&&s[5]==97&&s[6]==115&&s[7]==32&&s[8]==79&&s[9]==66&&s[10]==74)return console.debug("OBJ detected"),"model/obj";if(t.headers.has("content-type")){const o=t.headers.get("content-type");if(o!=null&&o.startsWith("image/"))return console.debug("Image detected, not a model file"),"unsupported";switch(console.debug("Content-Type: "+o),o){case"model/gltf+json":case"model/gltf-binary":case"model/vrm":case"model/vnd.usdz+zip":case"model/vnd.usd+zip":case"model/vnd.usd":case"model/vnd.usda+zip":case"model/vnd.usda":case"model/vnd.usdc":case"model/fbx":case"model/vnd.autodesk.fbx":case"model/obj":return o}}if(s[0]==118&&s[1]==32||s[0]==102&&s[1]==32)return console.debug("OBJ detected (the file has no header and starts with vertex or face)"),"obj";if(s[0]==35&&s[1]==32&&s[2]==70&&s[3]==105&&s[4]==108&&s[5]==101&&s[6]==32&&s[7]==101&&s[8]==120&&s[9]==112&&s[10]==111&&s[11]==114&&s[12]==116&&s[13]==101&&s[14]==100&&s[15]==32&&s[16]==98&&s[17]==121&&s[18]==32&&s[19]==90&&s[20]==66&&s[21]==114&&s[22]==117&&s[23]==115&&s[24]==104)return console.debug("OBJ detected (exported by ZBrush)"),"obj";if(s[0]==109&&s[1]==116&&s[2]==108&&s[3]==108&&s[4]==105&&s[5]==98)return console.debug("OBJ detected (mtllib)"),"obj";for(const o of $u){const r=o({url:n,response:t,contentType:t.headers.get("content-type"),bytes:s});if(r)return Hc&&console.debug(`Mimetype callback returned: ${r}`),r}if(F()||Hc){const o=new TextDecoder().decode(e.slice(0,Math.min(e.byteLength,32)));console.warn(`Could not determine file type.
|
|
960
960
|
|
|
@@ -1270,7 +1270,7 @@ dateFormat X
|
|
|
1270
1270
|
axisFormat %s
|
|
1271
1271
|
`;const g=Array.from(r),f=new Set;for(const _ of g)if(_.affectedObjects&&typeof _.affectedObjects!="string"){if(Array.isArray(_.affectedObjects))for(const w of _.affectedObjects)f.add(w);else f.add(_.affectedObjects);l&&(p+=`section ${_.animationName} (${_.id})
|
|
1272
1272
|
`,p+=`${_.id} : ${_.start}, ${_.duration}s
|
|
1273
|
-
`)}l&&r.size&&console.log(p);const y=new Set;for(const _ of f){_.getPath||console.error("USDZExporter: Animation target object has no getPath method. This is likely a bug",_);let w=_.getPath();w.startsWith("<")&&(w=w.substring(1)),w.endsWith(">")&&(w=w.substring(0,w.length-1)),y.add({path:w,obj:_})}const v=Array.from(y).sort((_,w)=>_.path.length-w.path.length),b=new Array;for(let _=0;_<v.length;_++)for(let w=_+1;w<v.length;w++)if(v[w].path.startsWith(v[_].path)){const x=v[w],k=v[_];b.push({child:x.obj.displayName+" ("+x.path+")",parent:k.obj.displayName+" ("+k.path+")"})}b.length&&console.warn("USDZExporter: There are overlapping PlayAnimation actions. This can lead to undefined runtime behaviour when playing multiple animations. Please restructure the hierarchy so that animations don't overlap.",{overlappingTargets:b,playAnimationActions:r})}for(const p of new Set([...t,...s]))if(Array.isArray(p))for(const g of p)o.add(g.uuid);else o.add(p.uuid);xp&&console.log("All Behavior trigger sources and action targets",t,s,o),this.targetUuids=new Set(o)}onAfterHierarchy(e,t){var s;if((s=this.behaviours)!=null&&s.length){t.beginBlock('def Scope "Behaviors"');for(const o of this.behaviours)o.writeTo(this,e.document,t);t.closeBlock()}}async onAfterSerialize(e){xp&&console.log("onAfterSerialize behaviours",this.behaviourComponentsCopy);for(const t of this.behaviourComponentsCopy)typeof t.afterSerialize=="function"&&(t.afterSerialize.constructor.name==="AsyncFunction"?await t.afterSerialize(this,e):t.afterSerialize(this,e));for(const{clipUrl:t,filesKey:s}of this.audioClipsCopy){if(e.files[s])return;const o=await(await(await fetch(t)).blob()).arrayBuffer(),r=new Uint8Array(o);e.files[s]=r}this.behaviourComponentsCopy.length=0,this.audioClipsCopy.length=0}}class J0{get extensionName(){return"Physics"}onExportObject(e,t,s){const o=P.getComponents(e,dt).filter(h=>h.enabled),r=P.getComponents(e,ui).filter(h=>h.enabled&&!h.isTrigger);let l=o.length>0?o[0]:null;const c=r.length>0?r[0]:null;c&&!l&&(l=new dt,l.isKinematic=!0),l&&t.addEventListener("serialize",(h,d)=>{var u,p,g;if(l){if(h.appendLine(),h.beginBlock('def RealityKitComponent "RigidBody"',"{",!0),l.useGravity||h.appendLine("bool gravityEnabled = 0"),h.appendLine('uniform token info:id = "RealityKit.RigidBody"'),l.isKinematic&&h.appendLine('token motionType = "Kinematic"'),h.beginBlock('def RealityKitStruct "massFrame"',"{",!0),h.appendLine(`float m_mass = ${l.mass}`),h.beginBlock('def RealityKitStruct "m_pose"',"{",!0),h.appendLine(`float3 position = (${l.centerOfMass.x}, ${l.centerOfMass.y}, ${l.centerOfMass.z})`),h.closeBlock("}"),h.closeBlock("}"),r.length>0){const f=r[0];h.beginBlock('def RealityKitStruct "material"',"{",!0);const y=f.sharedMaterial;y&&y.dynamicFriction!==void 0&&h.appendLine(`double dynamicFriction = ${(u=f.sharedMaterial)==null?void 0:u.dynamicFriction}`),y&&y.bounciness!==void 0&&h.appendLine(`double restitution = ${(p=f.sharedMaterial)==null?void 0:p.bounciness}`),y&&y.staticFriction!==void 0&&h.appendLine(`double staticFriction = ${(g=f.sharedMaterial)==null?void 0:g.staticFriction}`),h.closeBlock("}")}h.closeBlock("}")}}),c&&(t.addEventListener("serialize",(h,d)=>{var u;h.beginBlock('def RealityKitComponent "Collider"',"{",!0),h.appendLine("uint group = 1"),h.appendLine('uniform token info:id = "RealityKit.Collider"'),h.appendLine("uint mask = 4294967295");const p=c.isTrigger?"Trigger":"Default";if(h.appendLine(`token type = "${p}"`),h.beginBlock('def RealityKitStruct "Shape"',"{",!0),c instanceof el){const g=c;h.appendLine('token shapeType = "Sphere"'),h.appendLine(`float radius = ${g.radius}`)}else if(c instanceof Nu){const g=c;h.appendLine('token shapeType = "Box"'),h.appendLine(`float3 extent = (${g.size.x}, ${g.size.y}, ${g.size.z})`)}else if(c instanceof Wn){const g=c;h.appendLine('token shapeType = "Capsule"'),h.appendLine(`float radius = ${g.radius}`),h.appendLine(`float height = ${g.height}`)}else if(c instanceof Fo&&(u=c.sharedMesh)!=null&&u.geometry){const g=c.sharedMesh.geometry;g.boundingBox||g.computeBoundingBox();const f=c.sharedMesh.geometry.boundingBox;f&&(h.appendLine('token shapeType = "Box"'),h.appendLine(`float3 extent = (${f.max.x-f.min.x}, ${f.max.y-f.min.y}, ${f.max.z-f.min.z})`),console.log("[USDZ] Only Box, Sphere, and Capsule colliders are supported in visionOS/iOS. MeshCollider will be exported as Box",c))}else console.warn("[USDZ] Only Box, Sphere, and Capsule colliders are supported in visionOS/iOS. Ignoring collider:",c);h.beginBlock('def RealityKitStruct "pose"',"{",!0),h.closeBlock("}"),h.closeBlock("}"),h.closeBlock("}")}),r.length>1&&console.log("WARNING: Multiple colliders detected. visionOS / iOS can only support objects with a single collider, only exporting the first collider: ",c))}}const RA=C("debugshadowcomponents");eb.prototype.interactable={get(){return this.interactive},set(n){this.interactable=n}};class ps extends I{constructor(){super(...arguments),a(this,"_shadowComponent",null),a(this,"_controlsChildLayout",!0),a(this,"_root"),a(this,"_parentComponent")}isRoot(){var e;return((e=this.Root)==null?void 0:e.gameObject)===this.gameObject}get canvas(){const e=this.Root;return e!=null&&e.isCanvas?e:null}get Canvas(){return this.canvas}markDirty(){ii.markUIDirty(this.context)}get shadowComponent(){return this._shadowComponent}set shadowComponent(e){this._shadowComponent=e}get controlsChildLayout(){return this._controlsChildLayout}set controlsChildLayout(e){this._controlsChildLayout=e,this.shadowComponent&&(this.shadowComponent.autoLayout=e)}get Root(){return this._root===void 0&&(this._root=P.getComponentInParent(this.gameObject,oh)),this._root}__internalNewInstanceCreated(e){return super.__internalNewInstanceCreated(e),this.shadowComponent=null,this._root=void 0,this._parentComponent=void 0,this}onEnable(){super.onEnable()}addShadowComponent(e,t){var s;if(!e)return;this.removeShadowComponent();const o=this.isRoot()?this.gameObject:this.gameObject.parent;if(this._parentComponent=P.getComponentInParent(o,ps),!this._parentComponent){console.warn(`Component "${this.name}" doesn't have a UI parent anywhere. Do you have an UI element outside a Canvas? UI components must be a child of a Canvas component`,this);return}e.name=this.name+" ("+(this.constructor.name??"UI")+")",e.autoLayout=this._parentComponent.controlsChildLayout,e[Mi]=this,this.setShadowComponentOwner(e);let r=!1;if(((s=this.Root)==null?void 0:s.gameObject)===this.gameObject)this.gameObject.add(e);else{const l=this._parentComponent.shadowComponent;l&&(l?.add(e),r=!0)}this.shadowComponent=e,t&&t.shadowComponent&&this.shadowComponent&&t.shadowComponent.add(this.shadowComponent),yc&&e.add(new Ci(.5)),this.onAfterAddedToScene(),r&&kO(),RA&&console.warn("Added shadow component",this.shadowComponent)}setShadowComponentOwner(e){if(e&&(e[Mi]===void 0||e[Mi]===this)&&(e[Mi]=this,e.children))for(const t of e.children)this.setShadowComponentOwner(t)}traverseOwnedShadowComponents(e,t,s){if(e&&e[Mi]===t){s(e);for(const o of e.children)this.traverseOwnedShadowComponents(o,t,s)}}removeShadowComponent(){this.shadowComponent&&this.shadowComponent.removeFromParent()}onAfterAddedToScene(){}setInteractable(e){this.shadowComponent&&(this.shadowComponent.interactable=e)}}class oh extends ps{awake(){super.awake()}}var TA=Object.defineProperty,EA=Object.getOwnPropertyDescriptor,rh=(n,e,t,s)=>{for(var o=s>1?void 0:s?EA(e,t):e,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=(s?l(e,t,o):l(o))||o);return s&&o&&TA(e,t,o),o};const ey=C("debugui"),ty=C("debuguilayout");class K1{constructor(){a(this,"width"),a(this,"height")}}class Z1{constructor(){a(this,"x"),a(this,"y"),a(this,"width"),a(this,"height")}}const Rs=new S,ah=new se,Sp=new V,vl=class OC extends ps{constructor(){super(...arguments),a(this,"_anchoredPosition"),a(this,"sizeDelta",new re(100,100)),a(this,"pivot",new re(.5,.5)),a(this,"anchorMin",new re(0,0)),a(this,"anchorMax",new re(1,1)),a(this,"minWidth"),a(this,"minHeight"),a(this,"lastMatrix"),a(this,"rectBlock"),a(this,"_transformNeedsUpdate",!1),a(this,"_initialPosition"),a(this,"_parentRectTransform"),a(this,"_lastUpdateFrame",-1),a(this,"_lastAnchoring"),a(this,"_createdBlocks",[]),a(this,"_createdTextBlocks",[])}get parent(){return this._parentRectTransform}get translation(){return this.gameObject.position}get rotation(){return this.gameObject.quaternion}get scale(){return this.gameObject.scale}get anchoredPosition(){return this._anchoredPosition||(this._anchoredPosition=new re),this._anchoredPosition}set anchoredPosition(e){this._anchoredPosition=e}get width(){let e=this.sizeDelta.x;if(this.anchorMin.x!==this.anchorMax.x&&this._parentRectTransform){const t=this._parentRectTransform.width,s=this.anchorMax.x-this.anchorMin.x;e=t*s,e+=this.sizeDelta.x}return this.minWidth!==void 0&&e<this.minWidth?this.minWidth:e}get height(){let e=this.sizeDelta.y;if(this.anchorMin.y!==this.anchorMax.y&&this._parentRectTransform){const t=this._parentRectTransform.height,s=this.anchorMax.y-this.anchorMin.y;e=t*s,e+=this.sizeDelta.y}return this.minHeight!==void 0&&e<this.minHeight?this.minHeight:e}awake(){super.awake(),this._lastUpdateFrame=-1,this._parentRectTransform=void 0,this.rectBlock=new E,this.rectBlock.name=this.name,this.lastMatrix=new se,this._lastAnchoring=null,this._initialPosition=this.gameObject.position.clone(),this._initialPosition.z=0,this._anchoredPosition||(this._anchoredPosition=new re),Ka(this,"_anchoredPosition",()=>{this.markDirty()}),Ka(this,"sizeDelta",()=>{this.markDirty()}),Ka(this,"pivot",()=>{this.markDirty()}),Ka(this,"anchorMin",()=>{this.markDirty()}),Ka(this,"anchorMax",()=>{this.markDirty()})}onEnable(){var e;super.onEnable(),this.rectBlock||(this.rectBlock=new E),this.lastMatrix||(this.lastMatrix=new se),this._lastAnchoring||(this._lastAnchoring=new re),this._initialPosition||(this._initialPosition=new S),this._anchoredPosition||(this._anchoredPosition=new re),this.addShadowComponent(this.rectBlock),this._transformNeedsUpdate=!0,(e=this.canvas)==null||e.registerTransform(this)}onDisable(){var e;super.onDisable(),this.removeShadowComponent(),(e=this.canvas)==null||e.unregisterTransform(this)}onParentRectTransformChanged(e){this._transformNeedsUpdate||this.onApplyTransform(ty?`${e.name} changed`:void 0)}get isDirty(){return this._transformNeedsUpdate||(this._transformNeedsUpdate=!this.lastMatrix.equals(this.gameObject.matrix)),this._transformNeedsUpdate}markDirty(){this._transformNeedsUpdate||(ty&&console.warn("RectTransform markDirty()",this.name),this._transformNeedsUpdate=!0,this._lastUpdateFrame=-1)}updateTransform(){(this._transformNeedsUpdate||!this.lastMatrix.equals(this.gameObject.matrix))&&this.canUpdate()&&this.onApplyTransform(this._transformNeedsUpdate?"Marked dirty":"Matrix changed")}canUpdate(){return this._transformNeedsUpdate&&this.activeAndEnabled&&this._lastUpdateFrame!==this.context.time.frame}onApplyTransform(e){var t;if(this.context.time.frameCount===this._lastUpdateFrame)return;this._lastUpdateFrame=this.context.time.frameCount;const s=this.shadowComponent;if(!s)return;this.gameObject.parent?this._parentRectTransform=P.getComponentInParent(this.gameObject.parent,OC):this._parentRectTransform=void 0,this._transformNeedsUpdate=!1,ty&&console.warn("RectTransform \u2192 ApplyTransform",this.name+" because "+e),this.isRoot()?this.Root.screenspace||(s.rotation.y=Math.PI):(s.matrix.identity(),s.matrixAutoUpdate=!1,Rs.set(0,0,0),this.applyPivot(Rs),s.matrix.setPosition(Rs.x,Rs.y,0),(this.gameObject.quaternion.x||this.gameObject.quaternion.y||this.gameObject.quaternion.z)&&(Sp.copy(this.gameObject.quaternion),Sp.x*=-1,Sp.z*=-1,ah.makeRotationFromQuaternion(Sp),s.matrix.premultiply(ah)),Rs.set(0,0,0),this.applyAnchoring(Rs),(t=this.canvas)!=null&&t.screenspace?Rs.z+=.1:Rs.z+=.01,ah.identity(),ah.setPosition(Rs.x,Rs.y,Rs.z),s.matrix.premultiply(ah),s.matrix.scale(this.gameObject.scale)),this.lastMatrix.copy(this.gameObject.matrix);const o=!0;for(const r of hu(this.gameObject,ps,o,1)){if(r===this||!r.activeAndEnabled)continue;const l=r;l.onParentRectTransformChanged&&l.onParentRectTransformChanged(this)}}applyAnchoring(e){this._lastAnchoring||(this._lastAnchoring=new re);const t=this._lastAnchoring.sub(this._anchoredPosition);this.gameObject.position.x+=t.x,this.gameObject.position.y+=t.y,this._lastAnchoring.copy(this._anchoredPosition),e.x+=this._initialPosition.x-this.gameObject.position.x,e.y+=this._initialPosition.y-this.gameObject.position.y,e.z+=this._initialPosition.z-this.gameObject.position.z;const s=this._parentRectTransform;if(s){let o=0;const r=1-this.anchorMax.y-this.anchorMin.y;o-=s.height*.5*r,e.y+=o;let l=0;const c=1-this.anchorMax.x-this.anchorMin.x;l-=s.width*.5*c,e.x+=l}}applyPivot(e){if(this.pivot&&!this.isRoot()){const t=this.pivot.x-.5;e.x-=t*this.sizeDelta.x*this.gameObject.scale.x;const s=this.pivot.y-.5;e.y-=s*this.sizeDelta.y*this.gameObject.scale.y}}getBasicOptions(){const e={width:this.sizeDelta.x,height:this.sizeDelta.y,offset:0,backgroundOpacity:0,borderWidth:0,borderRadius:0,borderOpacity:0,letterSpacing:-.03};return this.ensureValidSize(e),e}ensureValidSize(e,t=1e-4){return e.width<=0&&(e.width=t),e.height<=0&&(e.height=1e-4),e}createNewBlock(e){e={...this.getBasicOptions(),...e},ey&&console.log(this.name,e);const t=new eb(e);return this._createdBlocks.push(t),t}createNewText(e){ey&&console.log(e),e={...this.getBasicOptions(),...e},ey&&console.log(this.name,e);const t=new Jv(e);return this._createdTextBlocks.push(t),t}};rh([m(re)],vl.prototype,"anchoredPosition",1),rh([m(re)],vl.prototype,"sizeDelta",2),rh([m(re)],vl.prototype,"pivot",2),rh([m(re)],vl.prototype,"anchorMin",2),rh([m(re)],vl.prototype,"anchorMax",2);let Ts=vl;var AA=Object.defineProperty,J1=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&AA(e,t,o),o};class bl extends I{constructor(){super(...arguments),a(this,"effectColor"),a(this,"effectDistance")}}J1([m(he)],bl.prototype,"effectColor"),J1([m(re)],bl.prototype,"effectDistance");var IA=Object.defineProperty,LA=Object.getOwnPropertyDescriptor,eS=(n,e,t,s)=>{for(var o=s>1?void 0:s?LA(e,t):e,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=(s?l(e,t,o):l(o))||o);return s&&o&&IA(e,t,o),o};const Cp={backgroundColor:new oe(1,1,1),backgroundOpacity:1,borderColor:new oe(1,1,1),borderOpacity:1};var Qr;const iy=(Qr=class extends ps{constructor(){super(...arguments),a(this,"_alphaFactor",1),a(this,"sRGBColor",new oe(1,0,1)),a(this,"raycastTarget",!0),a(this,"uiObject",null),a(this,"_color",null),a(this,"_rect",null),a(this,"_stateManager",null),a(this,"_currentlyCreatingPanel",!1)}get isGraphic(){return!0}get color(){return this._color||(this._color=new he(1,1,1,1)),this._color}set color(n){(!this._color||this._color.r!==n.r||this._color.g!==n.g||this._color.b!==n.b||this._color.alpha!==n.alpha)&&(this._color||(this._color=new he(1,1,1,1)),this._color.copy(n),this.onColorChanged())}setAlphaFactor(n){this._alphaFactor=n,this.onColorChanged()}get alphaFactor(){return this._alphaFactor}onColorChanged(){this.uiObject&&(this.sRGBColor.copy(this._color),this.sRGBColor.convertLinearToSRGB(),Cp.backgroundColor=this.sRGBColor,Cp.backgroundOpacity=this._color.alpha*this._alphaFactor,this.applyEffects(Cp,this._alphaFactor),this.uiObject.set(Cp),this.markDirty())}get m_Color(){return this._color}get rectTransform(){if(this._rect||(this._rect=P.getComponent(this.gameObject,Ts)),!this._rect)throw new Error("Not Supported: Make sure to add a RectTransform component before adding a UI Graphic component.");return this._rect}onParentRectTransformChanged(){var n;(n=this.uiObject)==null||n.set({width:this.rectTransform.width,height:this.rectTransform.height}),this.markDirty()}__internalNewInstanceCreated(n){return super.__internalNewInstanceCreated(n),this._rect=null,this.uiObject=null,this._stateManager=null,this._color&&(this._color=this._color.clone()),this}setState(n){this.makePanel(),this.uiObject&&(this.uiObject.setState(n),this==null||this.markDirty())}setupState(n){this.makePanel(),this.uiObject&&(this._stateManager||(this._stateManager=new MO(this.uiObject)),this.uiObject.setupState(n.state,n.attributes))}setOptions(n){this.makePanel(),this.uiObject&&this.uiObject.set(n)}awake(){super.awake(),this.makePanel(),Ka(this,"_color",()=>RT(this,this.onColorChanged))}onEnable(){var n;super.onEnable(),this.uiObject&&((n=this.rectTransform.shadowComponent)==null||n.add(this.uiObject),this.addShadowComponent(this.uiObject,this.rectTransform))}onDisable(){super.onDisable(),this.uiObject&&this.removeShadowComponent()}makePanel(){if(this.uiObject||this._currentlyCreatingPanel)return;this._currentlyCreatingPanel=!0;const n={backgroundColor:this.color,backgroundOpacity:this.color.alpha,offset:.015};this.onBeforeCreate(n),this.applyEffects(n),this.onCreate(n),this.controlsChildLayout=!1,this._currentlyCreatingPanel=!1,this.onAfterCreated(),this.onColorChanged()}onBeforeCreate(n){}onCreate(n){this.uiObject=this.rectTransform.createNewBlock(n),this.uiObject.name=this.name}onAfterCreated(){}applyEffects(n,e=1){var t;const s=(t=this.gameObject)==null?void 0:t.getComponent(bl);s&&(s.effectDistance&&(n.borderWidth=Math.max(Math.abs(s.effectDistance.x),Math.abs(s.effectDistance.y))),s.effectColor&&(n.borderColor=s.effectColor,n.borderOpacity=s.effectColor.alpha*e))}async setTexture(n){if(this.setOptions({backgroundOpacity:0}),n){if(Qr.textureCache.has(n))n=Qr.textureCache.get(n);else if(!n.isRenderTargetTexture){const e=n.clone();e.colorSpace=On,Qr.textureCache.set(n,e),n=e}this.setOptions({backgroundImage:n,borderRadius:0,backgroundOpacity:this.color.alpha,backgroundSize:"stretch"}),Xe.assignTextureLOD(n,0).then(e=>{e instanceof je&&(n&&Qr.textureCache.set(n,e),this.setOptions({backgroundImage:e}),this.markDirty())})}else this.setOptions({backgroundImage:void 0,borderRadius:0,backgroundOpacity:this.color.alpha});this.markDirty()}onAfterAddedToScene(){super.onAfterAddedToScene(),this.shadowComponent&&(this.shadowComponent.offset=this.shadowComponent.position.z)}},a(Qr,"textureCache",new Map),Qr);eS([m(he)],iy.prototype,"color",1),eS([m()],iy.prototype,"raycastTarget",2);let lh=iy;class ch extends lh{constructor(){super(...arguments),a(this,"_flippedObject",!1)}onAfterCreated(){this.uiObject&&!this._flippedObject&&(this._flippedObject=!0,this.uiObject.scale.y*=-1)}}var jA=Object.defineProperty,DA=Object.getOwnPropertyDescriptor,Kn=(n,e,t,s)=>{for(var o=s>1?void 0:s?DA(e,t):e,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=(s?l(e,t,o):l(o))||o);return s&&o&&jA(e,t,o),o};const Yr=C("debugtext");var mt=(n=>(n[n.UpperLeft=0]="UpperLeft",n[n.UpperCenter=1]="UpperCenter",n[n.UpperRight=2]="UpperRight",n[n.MiddleLeft=3]="MiddleLeft",n[n.MiddleCenter=4]="MiddleCenter",n[n.MiddleRight=5]="MiddleRight",n[n.LowerLeft=6]="LowerLeft",n[n.LowerCenter=7]="LowerCenter",n[n.LowerRight=8]="LowerRight",n))(mt||{}),tS=(n=>(n[n.Normal=0]="Normal",n[n.Bold=1]="Bold",n[n.Italic=2]="Italic",n[n.BoldAndItalic=3]="BoldAndItalic",n))(tS||{});class Nt extends lh{constructor(){super(...arguments),a(this,"alignment",0),a(this,"verticalOverflow",0),a(this,"horizontalOverflow",0),a(this,"lineSpacing",1),a(this,"supportRichText",!1),a(this,"font"),a(this,"fontStyle",0),a(this,"sRGBTextColor",new oe(1,0,1)),a(this,"_text",""),a(this,"_fontSize",12),a(this,"_textMeshUi",null),a(this,"_didHandleTextRenderOnTop",!1)}setAlphaFactor(e){var t;super.setAlphaFactor(e),(t=this.uiObject)==null||t.set({fontOpacity:this.color.alpha*this.alphaFactor}),this.markDirty()}get text(){return this._text}set text(e){e!==this._text&&(this._text=e,this.feedText(this.text,this.supportRichText),this.markDirty())}set_text(e){this.text=e}get fontSize(){return this._fontSize}set fontSize(e){var t;this._fontSize=e,(t=this.uiObject)==null||t.set({fontSize:e})}onColorChanged(){var e;this.sRGBTextColor.copy(this.color),this.sRGBTextColor.convertLinearToSRGB(),(e=this.uiObject)==null||e.set({color:this.sRGBTextColor,fontOpacity:this.color.alpha})}onParentRectTransformChanged(){super.onParentRectTransformChanged(),this.uiObject&&this.updateOverflow()}onBeforeCanvasRender(e){this.updateOverflow()}updateOverflow(){var e;const t=(e=this.uiObject)==null?void 0:e._overflow;t&&(t._needsUpdate=!0)}onCreate(e){Yr&&console.log(this),this.horizontalOverflow==1&&(e.whiteSpace="pre"),this.verticalOverflow==0&&(this.context.renderer.localClippingEnabled=!0,e.overflow="hidden"),this.horizontalOverflow==1&&this.verticalOverflow==0,e.lineHeight=this.lineSpacing,delete e.backgroundOpacity,delete e.backgroundColor,Yr&&(e.backgroundColor=16750848,e.backgroundOpacity=.5);const t=this.rectTransform;e={...e,...this.getTextOpts()},this.getAlignment(e),Yr&&(e.backgroundColor=Math.random()*16777215,e.backgroundOpacity=.1),this.uiObject=t.createNewText(e),this.feedText(this.text,this.supportRichText)}onAfterAddedToScene(){super.onAfterAddedToScene(),this.handleTextRenderOnTop()}getTextOpts(){const e=this.fontSize,t={color:this.color,fontOpacity:this.color.alpha,fontSize:e,fontKerning:"normal"};return this.setFont(t,this.fontStyle),t}onEnable(){var e;super.onEnable(),this._didHandleTextRenderOnTop=!1,this.uiObject&&this.uiObject.addAfterUpdate(()=>{this.setShadowComponentOwner(this.uiObject),this.markDirty()}),setTimeout(()=>this.markDirty(),10),(e=this.canvas)==null||e.registerEventReceiver(this)}onDisable(){var e;super.onDisable(),(e=this.canvas)==null||e.unregisterEventReceiver(this)}getAlignment(e){switch(e.flexDirection="column",this.alignment){case 0:case 3:case 6:e.textAlign="left";break;case 1:case 4:case 7:e.textAlign="center";break;case 2:case 5:case 8:e.textAlign="right";break}switch(this.alignment){default:case 0:case 1:case 2:e.alignItems="start";break;case 3:case 4:case 5:e.alignItems="center";break;case 6:case 7:case 8:e.alignItems="end";break}return e}feedText(e,t){var s,o,r;if(Yr&&console.log("feedText",this.uiObject,e,t),!!this.uiObject)if(this._textMeshUi||(this._textMeshUi=[]),this.uiObject.children.length=0,!t||e.length===0)this.uiObject.textContent=e;else{let l=this.getNextTag(e);if(l){if(l.startIndex>0){for(let d=this.uiObject.children.length-1;d>=0;d--){const u=this.uiObject.children[d];u.isUI&&(this.uiObject.remove(u),u.clear())}const h=new Gm({textContent:e.substring(0,l.startIndex),color:"inherit"});this.uiObject.add(h)}}else{this.uiObject.textContent="",this.setOptions({textContent:e});return}const c=[];for(;l;){const h=this.getNextTag(e,l.endIndex),d={fontFamily:(s=this.uiObject)==null?void 0:s.get("fontFamily"),color:"inherit",textContent:""};if(h){d.textContent=this.getText(e,l,h),this.handleTag(l,d,c);const u=new Gm(d);(o=this.uiObject)==null||o.add(u)}else{d.textContent=e.substring(l.endIndex),this.handleTag(l,d,c);const u=new Gm(d);(r=this.uiObject)==null||r.add(u)}l=h}}}handleTextRenderOnTop(){this._didHandleTextRenderOnTop||(this._didHandleTextRenderOnTop=!0,this.startCoroutine(this.renderOnTopCoroutine()))}*renderOnTopCoroutine(){if(!this.canvas)return;const e=[],t=this.canvas,s={renderOnTop:t.renderOnTop,depthWrite:t.depthWrite,doubleSided:t.doubleSided};for(;;){let o=!1;if(this._textMeshUi)for(let r=0;r<this._textMeshUi.length;r++){if(e[r]===!0)continue;o=!0;const l=this._textMeshUi[r];l.textContent&&(Iu(l,s),e[r]=!0)}if(!o)break;yield}}handleTag(e,t,s){if(!e.isEndTag){if(e.type.includes("color")){const o=new sy(e,{color:t.color});if(s.push(o),e.type.length>6){const r=parseInt("0x"+e.type.substring(7));t.color=r}else t.color=new oe(1,1,1)}else if(e.type=="b"){this.setFont(t,1);const o=new sy(e,{fontWeight:700});s.push(o)}else if(e.type=="i"){this.setFont(t,2);const o=new sy(e,{fontStyle:"italic"});s.push(o)}}}getText(e,t,s){return e.substring(t.endIndex,s.startIndex)}getNextTag(e,t=0){const s=e.indexOf("<",t),o=e.indexOf(">",s);if(s>=0&&o>=0){const r=e.substring(s+1,o);return{type:r,startIndex:s,endIndex:o+1,isEndTag:r.startsWith("/")}}return null}setFont(e,t){if(!this.font)return;const s=this.font,o=this.getFamilyNameWithCorrectSuffix(s,t);Yr&&console.log("Selected font family:"+o);let r=tb.getFontFamily(o);switch(r||(r=tb.addFontFamily(o)),e.fontFamily=r,t){default:case 0:e.fontWeight=400,e.fontStyle="normal";break;case 1:e.fontWeight=700,e.fontStyle="normal";break;case 2:e.fontWeight=400,e.fontStyle="italic";break;case 3:e.fontStyle="italic",e.fontWeight=400}let l=r.getVariant(e.fontWeight,e.fontStyle);if(!l){let c=o;c!=null&&c.endsWith("-msdf.json")||(c+="-msdf.json");let h=o;h!=null&&h.endsWith(".png")||(h+=".png"),l=r.addVariant(e.fontWeight,e.fontStyle,c,h),l?.addEventListener("ready",()=>{this.markDirty()})}}getFamilyNameWithCorrectSuffix(e,t){var s;const o=e.lastIndexOf("-");if(o<0)return e;const r=(s=e.substring(o+1))==null?void 0:s.toLowerCase();if(BA.includes(r))return Yr&&console.warn("Unsupported font style: "+r),e;const l=e.lastIndexOf("/");let c=e;l>=0&&(c=c.substring(l+1));const h=c[0]===c[0].toUpperCase(),d=e.substring(0,o);switch(Yr&&console.log("Select font: ",e,tS[t],c,h,d),t){case 0:return h?d+"-Regular":d+"-regular";case 1:return h?d+"-Bold":d+"-bold";case 2:return h?d+"-Italic":d+"-italic";case 3:return h?d+"-BoldItalic":d+"-bolditalic";default:return e}}}Kn([m()],Nt.prototype,"alignment",2),Kn([m()],Nt.prototype,"verticalOverflow",2),Kn([m()],Nt.prototype,"horizontalOverflow",2),Kn([m()],Nt.prototype,"lineSpacing",2),Kn([m()],Nt.prototype,"supportRichText",2),Kn([m(URL)],Nt.prototype,"font",2),Kn([m()],Nt.prototype,"fontStyle",2),Kn([m()],Nt.prototype,"text",1),Kn([m()],Nt.prototype,"fontSize",1);class sy{constructor(e,t){a(this,"tag"),a(this,"previousValues"),this.tag=e,this.previousValues=t}}const BA=["medium","mediumitalic","black","blackitalic","thin","thinitalic","extrabold","light","lightitalic","semibold"];class Kr{constructor(e){a(this,"id"),a(this,"content",""),a(this,"font",[]),a(this,"pointSize",144),a(this,"width"),a(this,"height"),a(this,"depth"),a(this,"wrapMode"),a(this,"horizontalAlignment"),a(this,"verticalAlignment"),a(this,"material"),this.id=e}static getId(){return this.global_id++}setDepth(e){return this.depth=e,this}setPointSize(e){return this.pointSize=e,this}setHorizontalAlignment(e){return this.horizontalAlignment=e,this}setVerticalAlignment(e){return this.verticalAlignment=e,this}writeTo(e,t){var s;t.beginBlock(`def Preliminary_Text "${this.id}"`,"(",!1),t.appendLine('prepend apiSchemas = ["MaterialBindingAPI"]'),t.closeBlock(")"),t.beginBlock(),this.content&&t.appendLine(`string content = "${this.content}"`),(!this.font||this.font.length<=0)&&(this.font||(this.font=[]),(s=this.font)==null||s.push("sans-serif"));const o=this.font.map(r=>`"${r}"`).join(", ");t.appendLine(`string[] font = [ ${o} ]`),t.appendLine(`double pointSize = ${this.pointSize}`),typeof this.width=="number"&&t.appendLine(`double width = ${this.width}`),typeof this.height=="number"&&t.appendLine(`double height = ${this.height}`),typeof this.depth=="number"&&t.appendLine(`double depth = ${this.depth}`),this.wrapMode&&t.appendLine(`token wrapMode = "${this.wrapMode}"`),this.horizontalAlignment&&t.appendLine(`token horizontalAlignment = "${this.horizontalAlignment}"`),this.verticalAlignment&&t.appendLine(`token verticalAlignment = "${this.verticalAlignment}"`),this.material!==void 0&&t.appendLine(`rel material:binding = </StageRoot/Materials/${ap(this.material)}>`),t.closeBlock()}}a(Kr,"global_id",0);class ny{static singleLine(e,t,s){const o=new Kr("text_"+Kr.getId());return o.content=e,t&&(o.pointSize=t),s&&(o.depth=s),o}static multiLine(e,t,s,o,r,l){const c=new Kr("text_"+Kr.getId());return c.content=e,c.width=t,c.height=s,c.horizontalAlignment=o,c.verticalAlignment=r,l!==void 0&&(c.wrapMode=l),c}}const FA=new se().makeRotationY(Math.PI),UA=new se().makeScale(-1,1,-1);class Pp{get extensionName(){return"text"}exportText(e,t,s){const o=P.getComponent(e,Nt);if(!o)return;const r=P.getComponent(e,Ts);let l=100,c=100;r&&(l=r.width,c=r.height);const h=FA.clone();r&&h.premultiply(UA),t.setMatrix(h);const d=o.color.clone();t.material=new bt({color:d,emissive:d}),t.addEventListener("serialize",(u,p)=>{let g=o.text;g=g.replace(/\r/g,""),g=g.replace(/\n/g,"\\n");const f=ny.multiLine(g,l,c,"center","bottom","flowing");this.setTextAlignment(f,o.alignment),this.setOverflow(f,o),t.material&&(f.material=t.material),f.pointSize=this.convertToTextSize(o.fontSize),f.depth=.001,f.writeTo(void 0,u)})}convertToTextSize(e){return 1/.0502*144*e}setOverflow(e,t){t.horizontalOverflow?e.wrapMode="singleLine":e.wrapMode="flowing"}setTextAlignment(e,t){switch(t){case mt.LowerLeft:case mt.MiddleLeft:case mt.UpperLeft:e.horizontalAlignment="left";break;case mt.LowerCenter:case mt.MiddleCenter:case mt.UpperCenter:e.horizontalAlignment="center";break;case mt.LowerRight:case mt.MiddleRight:case mt.UpperRight:e.horizontalAlignment="right";break}switch(t){case mt.LowerLeft:case mt.LowerCenter:case mt.LowerRight:e.verticalAlignment="bottom";break;case mt.MiddleLeft:case mt.MiddleCenter:case mt.MiddleRight:e.verticalAlignment="middle";break;case mt.UpperLeft:case mt.UpperCenter:case mt.UpperRight:e.verticalAlignment="top";break}}}var zA=Object.defineProperty,it=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&zA(e,t,o),o};const iS=C("debuguilayout");class Zr{constructor(){a(this,"left",0),a(this,"right",0),a(this,"top",0),a(this,"bottom",0)}get vertical(){return this.top+this.bottom}get horizontal(){return this.left+this.right}}it([m()],Zr.prototype,"left"),it([m()],Zr.prototype,"right"),it([m()],Zr.prototype,"top"),it([m()],Zr.prototype,"bottom");class Wi extends I{constructor(){super(...arguments),a(this,"_rectTransform",null),a(this,"_needsUpdate",!1),a(this,"childAlignment",0),a(this,"reverseArrangement",!1),a(this,"spacing",0),a(this,"padding"),a(this,"minWidth",0),a(this,"minHeight",0),a(this,"flexibleHeight",0),a(this,"flexibleWidth",0),a(this,"preferredHeight",0),a(this,"preferredWidth",0)}get rectTransform(){return this._rectTransform}onParentRectTransformChanged(e){this._needsUpdate=!0}get isDirty(){return this._needsUpdate}get isLayoutGroup(){return!0}updateLayout(){this._rectTransform&&(iS&&console.warn("Layout Update",this.context.time.frame,this.name),this._needsUpdate=!1,this.onCalculateLayout(this._rectTransform))}start(){this._needsUpdate=!0}onEnable(){iS&&console.log(this.name,this),this._rectTransform=this.gameObject.getComponent(Ts);const e=this.gameObject.getComponentInParent(_l);e&&e.registerLayoutGroup(this),this._needsUpdate=!0}onDisable(){const e=this.gameObject.getComponentInParent(_l);e&&e.unregisterLayoutGroup(this)}set m_Spacing(e){e!==this.spacing&&(this._needsUpdate=!0,this.spacing=e)}get m_Spacing(){return this.spacing}}it([m()],Wi.prototype,"childAlignment"),it([m()],Wi.prototype,"reverseArrangement"),it([m()],Wi.prototype,"spacing"),it([m(Zr)],Wi.prototype,"padding"),it([m()],Wi.prototype,"minWidth"),it([m()],Wi.prototype,"minHeight"),it([m()],Wi.prototype,"flexibleHeight"),it([m()],Wi.prototype,"flexibleWidth"),it([m()],Wi.prototype,"preferredHeight"),it([m()],Wi.prototype,"preferredWidth");class Yo extends Wi{constructor(){super(...arguments),a(this,"childControlHeight",!0),a(this,"childControlWidth",!0),a(this,"childForceExpandHeight",!1),a(this,"childForceExpandWidth",!1),a(this,"childScaleHeight",!1),a(this,"childScaleWidth",!1)}onCalculateLayout(e){var t;const s=this.primaryAxis,o=e.width;let r=o;const l=e.height;let c=l;r-=this.padding.horizontal,c-=this.padding.vertical,s==="x"?this.padding.horizontal:this.padding.vertical;const h=s==="x",d=h?"y":"x",u=h?this.childControlWidth:this.childControlHeight,p=h?this.childControlHeight:this.childControlWidth,g=h?this.childForceExpandWidth:this.childForceExpandHeight,f=h?this.childForceExpandHeight:this.childForceExpandWidth,y=h?c:r,v=h?o:l,b=.5*(h?this.childAlignment%3:Math.floor(this.childAlignment/3));let _=0;h?_+=this.padding.left:_+=this.padding.top;let w=0,x=0;for(let D=0;D<this.gameObject.children.length;D++){const z=this.gameObject.children[D],j=P.getComponent(z,Ts);j!=null&&j.activeAndEnabled&&(x+=1,h?w+=j.width:w+=j.height)}let k=0;const M=this.spacing*(x-1);if(g||u){let D=0;h?D=r-=M:D=c-=M,x>0&&(k=D/x)}let T=0;T+=this.padding.left,T-=this.padding.right,b!==0&&(_=v-w,_*=b,_-=M*b,h?(_-=this.padding.right*b,_+=this.padding.left*(1-b),_<this.padding.left&&(_=this.padding.left)):(_-=this.padding.bottom*b,_+=this.padding.top*(1-b),_<this.padding.top&&(_=this.padding.top)));let L=1;for(let D=0;D<this.gameObject.children.length;D++){const z=this.gameObject.children[D],j=P.getComponent(z,Ts);if(j!=null&&j.activeAndEnabled){(t=j.pivot)==null||t.set(.5,.5),j.anchorMin.set(0,1),j.anchorMax.set(0,1);const H=o*.5+T*.5;j.anchoredPosition.x!==H&&(j.anchoredPosition.x=H);const K=l*-.5;j.anchoredPosition.y!==K&&(j.anchoredPosition.y=K),f&&p&&j.sizeDelta[d]!==y&&(j.sizeDelta[d]=y),g&&u&&j.sizeDelta[s]!==k&&(j.sizeDelta[s]=k);const U=h?j.width:j.height,B=U*.5;if(_+=B,g){const te=k*L-k*.5;te>_&&(_=te-k*.5+U+this.padding.left,_-=B)}let Q=_;s==="y"&&(Q=-Q),j.anchoredPosition[s]!==Q&&(j.anchoredPosition[s]=Q),_+=B,_+=this.spacing,L+=1}}}}it([m()],Yo.prototype,"childControlHeight"),it([m()],Yo.prototype,"childControlWidth"),it([m()],Yo.prototype,"childForceExpandHeight"),it([m()],Yo.prototype,"childForceExpandWidth"),it([m()],Yo.prototype,"childScaleHeight"),it([m()],Yo.prototype,"childScaleWidth");class oy extends Yo{get primaryAxis(){return"y"}}class ry extends Yo{get primaryAxis(){return"x"}}class ay extends Wi{onCalculateLayout(){}}var NA=Object.defineProperty,WA=Object.getOwnPropertyDescriptor,mn=(n,e,t,s)=>{for(var o=s>1?void 0:s?WA(e,t):e,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=(s?l(e,t,o):l(o))||o);return s&&o&&NA(e,t,o),o},sS=(n=>(n[n.ScreenSpaceOverlay=0]="ScreenSpaceOverlay",n[n.ScreenSpaceCamera=1]="ScreenSpaceCamera",n[n.WorldSpace=2]="WorldSpace",n[n.Undefined=-1]="Undefined",n))(sS||{});const ly=C("debuguilayout"),cs=class kC extends oh{constructor(){super(...arguments),a(this,"_renderOnTop"),a(this,"_depthWrite",!1),a(this,"_doubleSided",!0),a(this,"_castShadows",!1),a(this,"_receiveShadows",!1),a(this,"_renderMode",-1),a(this,"_rootCanvas"),a(this,"_scaleFactor",1),a(this,"worldCamera"),a(this,"planeDistance",-1),a(this,"_boundRenderSettingsChanged",this.onRenderSettingsChanged.bind(this)),a(this,"previousParent",null),a(this,"_lastMatrixWorld",null),a(this,"_rectTransforms",[]),a(this,"_layoutGroups",new Map),a(this,"_receivers",[]),a(this,"onBeforeRenderRoutine",()=>{var e,t,s,o;if(this.previousParent=this.gameObject.parent,((e=this.context.xr)!=null&&e.isVR||(t=this.context.xr)!=null&&t.isPassThrough)&&this.screenspace){this.gameObject.visible=!1,this.gameObject.removeFromParent();return}this.renderOnTop||this.screenspace?this.gameObject.removeFromParent():(this.onUpdateRenderMode(),this.handleLayoutUpdates(),(s=this.shadowComponent)==null||s.updateMatrixWorld(!0),(o=this.shadowComponent)==null||o.updateWorldMatrix(!0,!0),this.invokeBeforeRenderEvents(),ii.ensureUpdateMeshUI(ib,this.context))}),a(this,"onAfterRenderRoutine",()=>{var e,t,s,o,r;if(((e=this.context.xr)!=null&&e.isVR||(t=this.context.xr)!=null&&t.isPassThrough)&&this.screenspace){(s=this.previousParent)==null||s.add(this.gameObject);return}if((this.screenspace||this.renderOnTop)&&this.previousParent&&this.context.mainCamera){if(this.screenspace){const h=this.context.mainCamera;h?.add(this.gameObject)}else this.previousParent.add(this.gameObject);const l=this.context.renderer.autoClear,c=this.context.renderer.autoClearColor;this.context.renderer.autoClear=!1,this.context.renderer.autoClearColor=!1,this.context.renderer.clearDepth(),this.onUpdateRenderMode(!0),this.handleLayoutUpdates(),(o=this.shadowComponent)==null||o.updateMatrixWorld(!0),this.invokeBeforeRenderEvents(),ii.ensureUpdateMeshUI(ib,this.context,!0),this.context.renderer.render(this.gameObject,this.context.mainCamera),this.context.renderer.autoClear=l,this.context.renderer.autoClearColor=c,this.previousParent.add(this.gameObject)}(r=this._lastMatrixWorld)==null||r.copy(this.gameObject.matrixWorld)}),a(this,"_updateRenderSettingsRoutine"),a(this,"_activeRenderMode",-1),a(this,"_lastWidth",-1),a(this,"_lastHeight",-1)}get isCanvas(){return!0}get screenspace(){return this.renderMode!==2}set renderOnTop(e){e!==this._renderOnTop&&(this._renderOnTop=e,this.onRenderSettingsChanged())}get renderOnTop(){return this._renderOnTop!==void 0?this._renderOnTop:!!(this.screenspace&&this._renderMode===0)}set depthWrite(e){this._depthWrite!==e&&(this._depthWrite=e,this.onRenderSettingsChanged())}get depthWrite(){return this._depthWrite}set doubleSided(e){this._doubleSided!==e&&(this._doubleSided=e,this.onRenderSettingsChanged())}get doubleSided(){return this._doubleSided}set castShadows(e){this._castShadows!==e&&(this._castShadows=e,this.onRenderSettingsChanged())}get castShadows(){return this._castShadows}set receiveShadows(e){this._receiveShadows!==e&&(this._receiveShadows=e,this.onRenderSettingsChanged())}get receiveShadows(){return this._receiveShadows}get renderMode(){return this._renderMode}set renderMode(e){this._renderMode!==e&&(this._renderMode=e,this.onRenderSettingsChanged())}set rootCanvas(e){this._rootCanvas instanceof kC||(this._rootCanvas=e)}get rootCanvas(){return this._rootCanvas}get scaleFactor(){return this._scaleFactor}set scaleFactor(e){this._scaleFactor=e}awake(){var e;this.shadowComponent=this.gameObject,this.previousParent=this.gameObject.parent,ly&&console.log("Canvas.Awake()",((e=this.previousParent)==null?void 0:e.name)+"/"+this.gameObject.name),super.awake()}start(){this.applyRenderSettings()}onEnable(){super.onEnable(),this._updateRenderSettingsRoutine=void 0,this._lastMatrixWorld=new se,this.applyRenderSettings(),document.addEventListener("resize",this._boundRenderSettingsChanged),this.context.pre_render_callbacks.push(this.onBeforeRenderRoutine),this.context.post_render_callbacks.push(this.onAfterRenderRoutine)}onDisable(){super.onDisable(),document.removeEventListener("resize",this._boundRenderSettingsChanged);const e=this.context.pre_render_callbacks.indexOf(this.onBeforeRenderRoutine);e!==-1&&this.context.pre_render_callbacks.splice(e,1);const t=this.context.post_render_callbacks.indexOf(this.onAfterRenderRoutine);t!==-1&&this.context.post_render_callbacks.splice(t,1)}registerTransform(e){this._rectTransforms.push(e)}unregisterTransform(e){const t=this._rectTransforms.indexOf(e);t!==-1&&this._rectTransforms.splice(t,1)}registerLayoutGroup(e){const t=e.gameObject;this._layoutGroups.set(t,e)}unregisterLayoutGroup(e){const t=e.gameObject;this._layoutGroups.delete(t)}registerEventReceiver(e){this._receivers.push(e)}unregisterEventReceiver(e){const t=this._receivers.indexOf(e);t!==-1&&this._receivers.splice(t,1)}async onEnterXR(e){this.screenspace?(e.xr.isVR||e.xr.isPassThrough)&&(this.gameObject.visible=!1):(this.gameObject.visible=!1,await Xl(1).then(()=>{this.gameObject.visible=!0}))}onLeaveXR(e){this.screenspace&&(e.xr.isVR||e.xr.isPassThrough)&&(this.gameObject.visible=!0)}invokeBeforeRenderEvents(){var e;for(const t of this._receivers)(e=t.onBeforeCanvasRender)==null||e.call(t,this)}handleLayoutUpdates(){this._lastMatrixWorld===null&&(this._lastMatrixWorld=new se);const e=!this._lastMatrixWorld.equals(this.gameObject.matrixWorld);ly&&e&&console.log("Canvas Layout changed",this.context.time.frameCount,this.name);for(const t of this._rectTransforms){e&&t.markDirty();let s=this._layoutGroups.get(t.gameObject);t.isDirty&&!s&&(s=t.gameObject.getComponentInParent(Wi)),(t.isDirty||s!=null&&s.isDirty)&&(ly&&console.log("CANVAS UPDATE ### "+t.name+" ##################################### "+this.context.time.frame),s?.updateLayout(),t.updateTransform())}}applyRenderSettings(){this.onRenderSettingsChanged()}onRenderSettingsChanged(){this._updateRenderSettingsRoutine||(this._updateRenderSettingsRoutine=this.startCoroutine(this._updateRenderSettingsDelayed(),Oe.OnBeforeRender))}*_updateRenderSettingsDelayed(){if(yield,this._updateRenderSettingsRoutine=void 0,this.shadowComponent){this.onUpdateRenderMode(),Iu(this.shadowComponent,this);for(const e of P.getComponentsInChildren(this.gameObject,ps))Iu(e.shadowComponent,this)}}onUpdateRenderMode(e=!1){if(!e&&this._renderMode===this._activeRenderMode&&this._lastWidth===this.context.domWidth&&this._lastHeight===this.context.domHeight)return;this._activeRenderMode=this._renderMode;let t=this.context.mainCameraComponent,s=10;switch(t&&t.nearClipPlane>0&&t.farClipPlane>0&&(s=W.lerp(t.nearClipPlane,t.farClipPlane,.01)),this._renderMode===1&&(this.worldCamera&&(t=this.worldCamera),this.planeDistance>0&&(s=this.planeDistance)),this._renderMode){case 0:case 1:if(this._lastWidth=this.context.domWidth,this._lastHeight=this.context.domHeight,!t)return;const o=s+.01;this.gameObject.position.x=0,this.gameObject.position.y=0,this.gameObject.position.z=-o,this.gameObject.quaternion.identity();const r=this.gameObject.getComponent(Ts);let l=!1;r.sizeDelta.x!==this.context.domWidth&&(l=!0),r.sizeDelta.y!==this.context.domHeight&&(l=!0);const c=t.fieldOfView*Math.PI/180,h=2*Math.tan(c/2)*Math.abs(o);this.gameObject.scale.x=h/this.context.domHeight,this.gameObject.scale.y=h/this.context.domHeight,this.gameObject.scale.z=.01,l&&(r.sizeDelta.x=this.context.domWidth,r.sizeDelta.y=this.context.domHeight,r?.markDirty());break;case 2:this._lastWidth=-1,this._lastHeight=-1;break}}};mn([m()],cs.prototype,"renderOnTop",1),mn([m()],cs.prototype,"depthWrite",1),mn([m()],cs.prototype,"doubleSided",1),mn([m()],cs.prototype,"castShadows",1),mn([m()],cs.prototype,"receiveShadows",1),mn([m()],cs.prototype,"renderMode",1),mn([m(cs)],cs.prototype,"rootCanvas",1),mn([m()],cs.prototype,"scaleFactor",1),mn([m(ci)],cs.prototype,"worldCamera",2),mn([m()],cs.prototype,"planeDistance",2);let _l=cs;var VA=Object.defineProperty,$A=Object.getOwnPropertyDescriptor,cy=(n,e,t,s)=>{for(var o=s>1?void 0:s?$A(e,t):e,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=(s?l(e,t,o):l(o))||o);return s&&o&&VA(e,t,o),o};class Ko extends I{constructor(){super(...arguments),a(this,"_alpha",1),a(this,"interactable",!0),a(this,"blocksRaycasts",!0),a(this,"_isDirty",!1),a(this,"_buffer",[])}get alpha(){return this._alpha}set alpha(e){e!==this._alpha&&(this._alpha=e,this.markDirty())}get isCanvasGroup(){return!0}markDirty(){this._isDirty||(this._isDirty=!0,this.startCoroutine(this.applyChangesDelayed(),Oe.OnBeforeRender))}*applyChangesDelayed(){this._isDirty=!1,this.applyChangesNow()}applyChangesNow(){this._buffer.length=0;for(const e of P.getComponentsInChildren(this.gameObject,ps,this._buffer)){const t=e;t.setAlphaFactor&&t.setAlphaFactor(this._alpha)}}}cy([m()],Ko.prototype,"alpha",1),cy([m()],Ko.prototype,"interactable",2),cy([m()],Ko.prototype,"blocksRaycasts",2);class hy{get extensionName(){return"tmui"}onExportObject(e,t,s){const o=P.getComponent(e,_l);if(o&&o.enabled&&o.renderMode===sS.WorldSpace){const r=new Pp,l=P.getComponent(e,Ts),c=P.getComponent(e,Ko),h=new Array;if(l){if(!P.isActiveSelf(e)){const p=P.isActiveSelf(e);P.setActive(e,!0),l.onEnable(),l.updateTransform(),h.push(()=>{l.onDisable(),P.setActive(e,p)})}e.traverse(p=>{if(!P.isActiveInHierarchy(p)){const g=P.isActiveSelf(p);P.setActive(p,!0);const f=P.getComponent(p,ps);f&&(f.onEnable(),h.push(()=>{f.onDisable()}));const y=P.getComponent(p,Ts);y&&(y.onEnable(),y.updateTransform(),y.onApplyTransform(),h.push(()=>{y.onDisable()}));const v=P.getComponent(p,Nt);v&&(v.onEnable(),h.push(()=>{v.onDisable()})),h.push(()=>{P.setActive(p,g)})}}),l.width,l.height;const d=mi.createEmpty(),u=l.shadowComponent;if(t.add(d),u){const p=u.matrix;d.setMatrix(p);const g=new Map,f=new Map;g.set(u,d),f.set(u,c?c.alpha:1),u.traverse(y=>{if(y===u)return;const v=mi.createEmpty();v.setMatrix(y.matrix);const b=y.parent,_=!!b&&typeof b.textContent=="string"&&b.textContent.length>0;let w=f.get(b)||1;const x=P.getComponent(y,Ko);if(x&&(w*=x.alpha),y instanceof G&&_){const M=y[Mi];M?r.exportText(M.gameObject,v,s):console.error("Error when exporting UI: shadow component owner not found. This is likely a bug.",y)}if(y instanceof G&&!_){const M=y.geometry.clone();M.scale(1,1,-1),this.flipWindingOrder(M),v.geometry=M;const T=new oe,L=y.material.opacity;T.copy(y.material.color),v.material=new Me({color:T,opacity:L*w,map:y.material.map,transparent:!0})}g.set(y,v),f.set(y,w);const k=g.get(b);if(!k){console.error("Error when exporting UI: shadow component parent not found!",y,y.parent);return}k.add(v)})}}for(const d of h)d()}}flipWindingOrder(e){const t=e.index.array;for(let s=0,o=t.length/3;s<o;s++){const r=t[s*3];t[s*3]=t[s*3+2],t[s*3+2]=r}e.index.needsUpdate=!0}}const hh=C("debugusdz");function HA(n,e){var t;const s=[],o=P.getComponentsInChildren(n,Rt),r=P.getComponentsInChildren(n,Ft),l=new Array,c=new Array;if(e.injectImplicitBehaviours)for(const h of o){if(!h||!h.runtimeAnimatorController||!h.enabled)continue;const d=h.runtimeAnimatorController.activeState;if(!d||!d.motion||!d.motion.clip||((t=d.motion.clip.tracks)==null?void 0:t.length)<1||l.includes(h))continue;const u=new Jc;u.animator=h,u.stateName=d.name,u.trigger="start",u.name="PlayAnimationOnClick_implicitAtStart_"+u.stateName;const p=new E;P.addComponent(p,u),c.push(p),l.push(h),n.add(p)}else for(const h of o){if(!h||!h.runtimeAnimatorController||!h.enabled)continue;hh&&console.log(h);const d=[];for(const u of h.runtimeAnimatorController.enumerateActions()){hh&&console.log(u);const p=u.getClip();d.includes(p)||d.push(p)}s.push({root:h.gameObject,clips:d})}if(e.injectImplicitBehaviours)for(const h of r){if(!h||!h.clip||!h.enabled||!h.playAutomatically||l.includes(h))continue;const d=new Jc;d.animation=h,d.stateName=h.clip.name,d.trigger="start",d.name="PlayAnimationOnClick_implicitAtStart_"+d.stateName;const u=new E;P.addComponent(u,d),c.push(u),l.push(h),n.add(u)}else for(const h of r){hh&&console.log(h);const d=[];for(const u of h.animations)d.includes(u)||d.push(u);s.push({root:h.gameObject,clips:d})}hh&&s?.length>0&&console.log("USDZ Animation Clips without behaviours",s);for(const h of s)for(const d of h.clips)e.registerAnimation(h.root,d);return c}function GA(n,e){const t=P.getComponentsInChildren(n,ns),s=P.getComponentsInChildren(n,Vo),o=new Array,r=new Array;hh&&console.log({audioSources:t,playAudioOnClicks:s});for(const l of s){if(!l.target)continue;const c=t.indexOf(l.target);c>-1&&t.splice(c,1)}for(const l of t){if(!l||!l.clip||l.volume<=0||o.includes(l))continue;const c=new Vo;c.target=l,c.name="PlayAudioOnClick_implicitAtStart_",c.trigger="start";const h=new E;P.addComponent(h,c),console.log("implicit PlayAudioOnStart",h,c),r.push(h),o.push(l),n.add(h)}return r}function qA(n){return new Jt("DisableAtStart",At.sceneStartTrigger(),ve.fadeAction(n,0,!1))}function nS(n,e){const t=n.domElement.shadowRoot.querySelector("link[rel='ar']");if(t)return t;const s=document.createElement("div");s.classList.add("menu"),s.classList.add("quicklook-menu"),s.style.display="none",s.style.visibility="hidden";const o=document.createElement("button");o.id="open-in-ar",e?(o.innerText="View in AR",o.title="View this scene in AR. The scene will be exported to USDZ and opened with Apple's QuickLook."):(o.innerText="View in AR",o.title="Download this scene for AR. Open the downloaded USDZ file to view it in AR using Apple's QuickLook."),s.appendChild(o);const r=document.createElement("a");r.id="needle-usdz-link",r.style.display="none",r.rel="ar",r.href="",r.target="_blank",s.appendChild(r);const l=document.createElement("img");return l.id="button",r.appendChild(l),n.domElement.shadowRoot.appendChild(s),r}var XA=Object.defineProperty,It=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&XA(e,t,o),o};const Vi=C("debugusdz"),QA=C("debugusdzpruning");class Jr{constructor(){a(this,"callToAction"),a(this,"checkoutTitle"),a(this,"checkoutSubtitle"),a(this,"callToActionURL")}}It([m()],Jr.prototype,"callToAction"),It([m()],Jr.prototype,"checkoutTitle"),It([m()],Jr.prototype,"checkoutSubtitle"),It([m()],Jr.prototype,"callToActionURL");var wl;const fi=(wl=class extends I{constructor(){super(...arguments),a(this,"objectToExport"),a(this,"autoExportAnimations",!0),a(this,"autoExportAudioSources",!0),a(this,"exportFileName"),a(this,"customUsdzFile"),a(this,"customBranding"),a(this,"anchoringType","plane"),a(this,"maxTextureSize",2048),a(this,"planeAnchoringAlignment","horizontal"),a(this,"interactive",!0),a(this,"physics",!0),a(this,"allowCreateQuicklookButton",!0),a(this,"quickLookCompatible",!0),a(this,"extensions",[]),a(this,"link"),a(this,"button"),a(this,"onClickedOpenInARElement",n=>{n.preventDefault(),this.exportAndOpen()}),a(this,"_currentExportTasks",new Map),a(this,"_previousTimeScale",1),a(this,"lastCallback"),a(this,"_rootSessionRootWasAppliedTo",null),a(this,"_rootPositionBeforeExport",new S),a(this,"_rootRotationBeforeExport",new V),a(this,"_rootScaleBeforeExport",new S)}start(){var n,e,t;Vi&&(console.log("USDZExporter",this),console.log("Debug USDZ Mode. Press 'T' to export"),window.addEventListener("keydown",s=>{switch(s.key){case"t":this.exportAndOpen();break}})),this.objectToExport||(this.objectToExport=this.gameObject),!((e=(n=this.objectToExport)==null?void 0:n.children)!=null&&e.length)&&!((t=this.objectToExport)!=null&&t.isMesh)&&(this.objectToExport=this.context.scene)}onEnable(){var n;const e=X.supportsQuickLookAR(),t=X.isiOS()||X.isiPad();!this.button&&(Vi||e||t)&&(this.allowCreateQuicklookButton&&(this.button=this.createQuicklookButton()),this.lastCallback=this.quicklookCallback.bind(this),this.link=nS(this.context,e),this.link.addEventListener("message",this.lastCallback)),Vi&&De("USDZ Exporter enabled: "+this.name),(n=document.getElementById("open-in-ar"))==null||n.addEventListener("click",this.onClickedOpenInARElement),cc.registerExporter(this)}onDisable(){var n,e,t;(n=this.button)==null||n.remove(),(e=this.link)==null||e.removeEventListener("message",this.lastCallback),Vi&&De("USDZ Exporter disabled: "+this.name),(t=document.getElementById("open-in-ar"))==null||t.removeEventListener("click",this.onClickedOpenInARElement),cc.unregisterExporter(this)}async exportAsync(){return this.exportAndOpen()}async exportAndOpen(){var n;let e=this.exportFileName??((n=this.objectToExport)==null?void 0:n.name)??this.name;if(e+="-"+b1(),Zs()||(e!==""&&(e+="-"),e+="MadeWithNeedle"),this.link||(this.link=nS(this.context,X.supportsQuickLookAR())),this.customUsdzFile)return Vi&&console.log("Exporting custom usdz",this.customUsdzFile),this.openInQuickLook(this.customUsdzFile,e),null;if(!this.objectToExport)return console.warn("No object to export",this),null;const t=await this.export(this.objectToExport);return t?(Vi&&console.log("USDZ generation done. Downloading as "+e),this.openInQuickLook(t,e),t):(console.error("USDZ generation failed. Please report a bug",this),null)}async export(n){if(!n)return console.warn("No object to export"),null;const e=this._currentExportTasks.get(n);if(e)return e;const t=this.internalExport(n);return t instanceof Promise?(this._currentExportTasks.set(n,t),t.then(s=>(this._currentExportTasks.delete(n),s)).catch(s=>(this._currentExportTasks.delete(n),console.error("Error during USDZ export \u2013 please report a bug!",s),null))):t}async internalExport(n){de.start("export-usdz",{onProgress:x=>{this.dispatchEvent(new CustomEvent("export-progress",{detail:{progress:x}}))}}),de.report("export-usdz",{message:"Starting export",totalSteps:40,currentStep:0}),de.report("export-usdz",{message:"Load progressive textures",autoStep:5}),de.start("export-usdz-textures","export-usdz");const e=P.getComponentsInChildren(n,gi);for(const x of e)x&&x.enabled&&x.updateSprite(!0);const t=P.getComponentsInChildren(n,Ui),s=new Array;let o=0;for(const x of t){for(const k of x.sharedMeshes)if(k){const M=Xe.assignMeshLOD(k,0);M instanceof Promise&&s.push(new Promise((T,L)=>{M.then(()=>{o++,de.report("export-usdz-textures",{message:"Loaded progressive mesh",currentStep:o,totalSteps:s.length}),T()}).catch(D=>L(D))}))}for(const k of x.sharedMaterials)if(k){const M=Xe.assignTextureLOD(k,0);M instanceof Promise&&s.push(new Promise((T,L)=>{M.then(()=>{o++,de.report("export-usdz-textures",{message:"Loaded progressive texture",currentStep:o,totalSteps:s.length}),T()}).catch(D=>L(D))}))}}Vi&&De("Progressive Loading: "+s.length),await Promise.all(s),Vi&&De("Progressive Loading: done"),de.end("export-usdz-textures");const r=Di.Global.Mask;Di.Global.Set(rn.AR);const l=new P1,c=new dp(this.quickLookCompatible);let h;const d=[];this.interactive&&(d.push(new Z0),d.push(new _a),globalThis.NEEDLE_USE_RAPIER&&P.getComponentsInChildren(n,dt).length>0&&(this.physics?(h=new J0,d.push(h)):F()&&console.warn("USDZExporter: Physics export is disabled, but there are active Rigidbody components in the scene. They will not be exported.")),d.push(new Pp),d.push(new hy));const u=[c,...d,...this.extensions],p={self:this,exporter:l,extensions:u,object:n};de.report("export-usdz","Invoking before-export"),this.dispatchEvent(new CustomEvent("before-export",{detail:p})),this.applyWebARSessionRoot(),this._previousTimeScale=this.context.time.timeScale,this.context.time.timeScale=0,de.report("export-usdz","auto export animations and audio sources");const g=new Array;this.autoExportAnimations&&g.push(...HA(n,c)),u.find(x=>x.extensionName==="Audio")&&this.autoExportAudioSources&&g.push(...GA(n)),l.debug=Vi,l.pruneUnusedNodes=!QA;const f=Ju.instance.objs.map(x=>x.batchedMesh);l.keepObject=x=>{let k=!0;const M=P.getComponent(x,Ui);return M&&!M.enabled&&(k=!1),k&&f.includes(x)&&(k=!1),k&&P.getComponentInParent(x,Vc)&&(k=!1),k&&P.getComponentInParent(x,en)&&(k=!1),Vi&&!k&&console.log("USDZExporter: Discarding object",x),k},l.beforeWritingDocument=()=>{if(F()&&c&&h){const x=c.animatedRoots;for(const k of x){const M=P.getComponentsInChildren(k,dt).filter(L=>L.enabled),T=P.getComponents(k,ui).filter(L=>L.enabled&&!L.isTrigger);(M.length>0||T.length>0)&&console.error("An animated object has physics components in its child hierarchy. This can lead to undefined behaviour due to a bug in Apple's QuickLook (FB15925487). Remove the physics components from child objects or verify that you get the expected results.",k)}}};const y=new Array;this.objectToExport&&this.quickLookCompatible&&this.interactive&&this.objectToExport.traverse(x=>{x.visible||y.push(x)});const v=u.find(x=>x.extensionName==="Behaviour");this.interactive&&v&&y.length>0&&v.addBehavior(qA(y));let b=!0;this.quickLookCompatible&&!this.interactive&&(b=!1),this.anchoringType!=="plane"&&this.anchoringType!=="none"&&this.anchoringType!=="image"&&this.anchoringType!=="face"&&(this.anchoringType="plane"),this.planeAnchoringAlignment!=="horizontal"&&this.planeAnchoringAlignment!=="vertical"&&this.planeAnchoringAlignment!=="any"&&(this.planeAnchoringAlignment="horizontal"),de.report("export-usdz","Invoking exporter.parse");const _=await l.parse(this.objectToExport,{ar:{anchoring:{type:this.anchoringType},planeAnchoring:{alignment:this.planeAnchoringAlignment}},extensions:u,quickLookCompatible:this.quickLookCompatible,maxTextureSize:this.maxTextureSize,exportInvisible:b}),w=new Blob([_],{type:"model/vnd.usdz+zip"});this.revertWebARSessionRoot(),this.context.time.timeScale=this._previousTimeScale,de.report("export-usdz","Invoking after-export"),this.dispatchEvent(new CustomEvent("after-export",{detail:p}));for(const x of g)P.destroy(x);return Di.Global.Set(r),de.end("export-usdz"),w}openInQuickLook(n,e){const t=n instanceof Blob?URL.createObjectURL(n):n,s=this.buildQuicklookOverlay();Vi&&console.log("QuickLook Overlay",s);const o=s.callToAction?encodeURIComponent(s.callToAction):"",r=s.checkoutTitle?encodeURIComponent(s.checkoutTitle):"",l=s.checkoutSubtitle?encodeURIComponent(s.checkoutSubtitle):"";this.link.href=t+`#callToAction=${o}&checkoutTitle=${r}&checkoutSubtitle=${l}&callToActionURL=${s.callToActionURL}`,this.lastCallback||(this.lastCallback=this.quicklookCallback.bind(this),this.link.addEventListener("message",this.lastCallback)),this.link.download=e+".usdz",this.link.click()}download(n,e){wl.save(n,e)}static save(n,e){const t=document.createElement("a");t.style.display="none",document.body.appendChild(t),typeof n=="string"?t.href=n:t.href=URL.createObjectURL(n),t.download=e,t.click(),t.remove()}quicklookCallback(n){if(n?.data=="_apple_ar_quicklook_button_tapped"){Vi&&be("Quicklook closed via call to action button");var e=new CustomEvent("quicklook-button-tapped",{detail:this});if(this.dispatchEvent(e),!e.defaultPrevented){const t=new URLSearchParams(this.link.href);if(t){const s=t.get("callToActionURL");Vi&&De("Quicklook url: "+s),s&&(Zs()?globalThis.open(s,"_blank"):console.warn("Quicklook closed: custom redirects require a Needle Engine Pro license: https://needle.tools/pricing",s))}}}}buildQuicklookOverlay(){var n,e,t,s,o,r;const l={};return this.customBranding&&Object.assign(l,this.customBranding),Zs()||(console.log("Custom Quicklook banner text requires pro license: https://needle.tools/pricing"),l.callToAction="Close",l.checkoutTitle="\u{1F335} Made with Needle",l.checkoutSubtitle="_"),(((n=l.callToAction)==null?void 0:n.length)||((e=l.checkoutTitle)==null?void 0:e.length)||((t=l.checkoutSubtitle)==null?void 0:t.length))&&((s=l.callToAction)!=null&&s.length||(l.callToAction="\0"),(o=l.checkoutTitle)!=null&&o.length||(l.checkoutTitle="\0"),(r=l.checkoutSubtitle)!=null&&r.length||(l.checkoutSubtitle="\0")),this.dispatchEvent(new CustomEvent("quicklook-overlay",{detail:l})),l}getARScaleAndTarget(){if(!this.objectToExport)return{scale:1,_invertForward:!1,target:this.gameObject,sessionRoot:null};const n=P.findObjectOfType(wp);let e=P.getComponentInParent(this.objectToExport,$o);e||(e=P.getComponentInChildren(this.objectToExport,$o));let t=1,s=!1;const o=this.objectToExport;return n?t=n.arScale:e&&(t=e.arScale,s=e.invertForward),{scale:1/t,_invertForward:s,target:o,sessionRoot:e?.gameObject??null}}applyWebARSessionRoot(){if(!this.objectToExport)return;const{scale:n,_invertForward:e,target:t,sessionRoot:s}=this.getARScaleAndTarget(),o=s?.matrixWorld.clone().invert();this._rootSessionRootWasAppliedTo=t,this._rootPositionBeforeExport.copy(t.position),this._rootRotationBeforeExport.copy(t.quaternion),this._rootScaleBeforeExport.copy(t.scale),t.scale.multiplyScalar(n),e&&t.quaternion.multiply(wl.invertForwardQuaternion),t.updateMatrix(),t.updateMatrixWorld(!0),s&&o&&t.matrix.premultiply(o)}revertWebARSessionRoot(){if(!this.objectToExport||!this._rootSessionRootWasAppliedTo)return;const n=this._rootSessionRootWasAppliedTo;n.position.copy(this._rootPositionBeforeExport),n.quaternion.copy(this._rootRotationBeforeExport),n.scale.copy(this._rootScaleBeforeExport),n.updateMatrix(),n.updateMatrixWorld(!0),this._rootSessionRootWasAppliedTo=null}createQuicklookButton(){const n=ml.getOrCreate().createQuicklookButton();return n.parentNode||this.context.menu.appendChild(n),n}},a(wl,"invertForwardMatrix",new se().makeRotationY(Math.PI)),a(wl,"invertForwardQuaternion",new V().setFromEuler(new Dt(0,Math.PI,0))),wl);It([m(E)],fi.prototype,"objectToExport"),It([m()],fi.prototype,"autoExportAnimations"),It([m()],fi.prototype,"autoExportAudioSources"),It([m()],fi.prototype,"exportFileName"),It([m(URL)],fi.prototype,"customUsdzFile"),It([m(Jr)],fi.prototype,"customBranding"),It([m()],fi.prototype,"anchoringType"),It([m()],fi.prototype,"maxTextureSize"),It([m()],fi.prototype,"planeAnchoringAlignment"),It([m()],fi.prototype,"interactive"),It([m()],fi.prototype,"physics"),It([m()],fi.prototype,"allowCreateQuicklookButton"),It([m()],fi.prototype,"quickLookCompatible");let gn=fi;var YA=Object.defineProperty,KA=Object.getOwnPropertyDescriptor,dy=(n,e,t,s)=>{for(var o=KA(e,t),r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&YA(e,t,o),o};class xl extends I{constructor(){super(...arguments),a(this,"_fog")}get fog(){return this._fog||(this._fog=new Tv(0,0,50)),this._fog}get mode(){return 1}set near(e){this.fog.near=e}get near(){return this.fog.near}set far(e){this.fog.far=e}get far(){return this.fog.far}set color(e){this.fog.color.copy(e)}get color(){return this.fog.color}onEnable(){this.scene.fog=this.fog}onDisable(){this.scene.fog===this._fog&&(this.scene.fog=null)}}dy([m()],xl.prototype,"near"),dy([m()],xl.prototype,"far"),dy([m(oe)],xl.prototype,"color");var ZA=Object.defineProperty,uy=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&ZA(e,t,o),o};class ea extends I{constructor(){super(...arguments),a(this,"objectBounds",!1),a(this,"color"),a(this,"isGizmo",!0),a(this,"_gizmoObject",null),a(this,"_boxHelper",null)}onEnable(){this.isGizmo&&!yc||(this._gizmoObject||(this.objectBounds?this._gizmoObject=new RP(this.gameObject,this.color??16776960):(this.objectBounds=!1,this._gizmoObject=Vg(this.color??16776960))),this.objectBounds?(this.scene.add(this._gizmoObject),this._boxHelper=this._gizmoObject,this.startCoroutine(this.syncObjectBounds(),Oe.OnBeforeRender)):this.gameObject.add(this._gizmoObject))}onDisable(){this._gizmoObject&&this.gameObject.remove(this._gizmoObject)}*syncObjectBounds(){for(var e;this._boxHelper;)(e=this._boxHelper)==null||e.update(),yield}}uy([m()],ea.prototype,"objectBounds"),uy([m(oe)],ea.prototype,"color"),uy([m()],ea.prototype,"isGizmo");var JA=Object.defineProperty,py=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&JA(e,t,o),o};class Sl extends I{constructor(){super(...arguments),a(this,"isGizmo",!1),a(this,"color0"),a(this,"color1"),a(this,"gridHelper"),a(this,"size"),a(this,"divisions"),a(this,"offset")}onEnable(){if(this.isGizmo&&!yc)return;const e=this.size,t=this.divisions;this.gridHelper||(this.gridHelper=new Mm(e,t,this.color0??new oe(.4,.4,.4),this.color1??new oe(.6,.6,.6)),this.offset!==void 0&&(this.gridHelper.position.y+=this.offset)),this.gridHelper&&this.gameObject.add(this.gridHelper)}onDisable(){this.gridHelper&&(this.gameObject.remove(this.gridHelper),this.gridHelper=null)}}py([m()],Sl.prototype,"isGizmo"),py([m(oe)],Sl.prototype,"color0"),py([m(oe)],Sl.prototype,"color1");var e2=Object.defineProperty,my=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&e2(e,t,o),o};class gy extends I{constructor(){super(...arguments),a(this,"connectedBody"),a(this,"_rigidBody",null)}get rigidBody(){return this._rigidBody}onEnable(){this._rigidBody||(this._rigidBody=this.gameObject.getComponent(dt)),this.rigidBody&&this.connectedBody&&this.startCoroutine(this.create())}*create(){yield,this.rigidBody&&this.connectedBody&&this.activeAndEnabled&&this.createJoint(this.rigidBody,this.connectedBody)}}my([m(dt)],gy.prototype,"connectedBody");class fy extends gy{createJoint(e,t){var s;(s=this.context.physics.engine)==null||s.addFixedJoint(e,t)}}class dh extends gy{constructor(){super(...arguments),a(this,"anchor"),a(this,"axis")}createJoint(e,t){var s;this.axis&&this.anchor&&((s=this.context.physics.engine)==null||s.addHingeJoint(e,t,this.anchor,this.axis))}}my([m(S)],dh.prototype,"anchor"),my([m(S)],dh.prototype,"axis");var t2=Object.defineProperty,i2=Object.getOwnPropertyDescriptor,fn=(n,e,t,s)=>{for(var o=s>1?void 0:s?i2(e,t):e,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=(s?l(e,t,o):l(o))||o);return s&&o&&t2(e,t,o),o};function yy(n){return n*Math.PI/180}const oS=300,Zo=C("debuglights");class yi extends I{constructor(){super(...arguments),a(this,"type",0),a(this,"range",1),a(this,"spotAngle",1),a(this,"innerSpotAngle",1),a(this,"_color",new oe(16777215)),a(this,"_shadowNearPlane",.1),a(this,"_shadowBias",0),a(this,"_shadowNormalBias",0),a(this,"_overrideShadowBiasSettings",!1),a(this,"_shadows",1),a(this,"lightmapBakeType",4),a(this,"_intensity",-1),a(this,"_shadowDistance"),a(this,"shadowWidth"),a(this,"shadowHeight"),a(this,"_shadowResolution"),a(this,"light"),a(this,"_webXRStartedListener"),a(this,"_webXREndedListener"),a(this,"_webARRoot")}set color(e){this._color=e,this.light!==void 0&&(this.light.color=e)}get color(){return this.light?this.light.color:this._color}set shadowNearPlane(e){var t,s;if(e!==this._shadowNearPlane&&(this._shadowNearPlane=e,((s=(t=this.light)==null?void 0:t.shadow)==null?void 0:s.camera)!==void 0)){const o=this.light.shadow.camera;o.near=e}}get shadowNearPlane(){return this._shadowNearPlane}set shadowBias(e){var t,s;e!==this._shadowBias&&(this._shadowBias=e,((s=(t=this.light)==null?void 0:t.shadow)==null?void 0:s.bias)!==void 0&&(this.light.shadow.bias=e,this.light.shadow.needsUpdate=!0))}get shadowBias(){return this._shadowBias}set shadowNormalBias(e){var t,s;e!==this._shadowNormalBias&&(this._shadowNormalBias=e,((s=(t=this.light)==null?void 0:t.shadow)==null?void 0:s.normalBias)!==void 0&&(this.light.shadow.normalBias=e,this.light.shadow.needsUpdate=!0))}get shadowNormalBias(){return this._shadowNormalBias}set shadows(e){this._shadows=e,this.light&&(this.light.castShadow=e!==0,this.updateShadowSoftHard())}get shadows(){return this._shadows}set intensity(e){var t;if(this._intensity=e,this.light){let s=1;if(this.context.isInXR&&this._webARRoot){const o=(t=this._webARRoot)==null?void 0:t.arScale;typeof o=="number"&&o>0&&(s/=o)}this.light.intensity=e*s}Zo&&console.log("Set light intensity to "+this._intensity,e,this)}get intensity(){return this._intensity}get shadowDistance(){const e=this.light;return e!=null&&e.shadow?e.shadow.camera.far:-1}set shadowDistance(e){this._shadowDistance=e;const t=this.light;if(t!=null&&t.shadow){const s=t.shadow.camera;s.far=e,s.updateProjectionMatrix()}}get shadowResolution(){const e=this.light;return e!=null&&e.shadow?e.shadow.mapSize.x:-1}set shadowResolution(e){if(e===this._shadowResolution)return;this._shadowResolution=e;const t=this.light;t!=null&&t.shadow&&(t.shadow.mapSize.set(e,e),t.shadow.needsUpdate=!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}getWorldPosition(e){return this.light?this.type===1?this.light.getWorldPosition(e).multiplyScalar(1):this.light.getWorldPosition(e):e}awake(){this.color=new oe(this.color??16777215),Zo&&console.log(this.name,this)}onEnable(){Zo&&console.log("ENABLE LIGHT",this.name),this.createLight(),!this.isBaked&&(this.light&&(this.light.visible=!0,this.light.intensity=this._intensity,Zo&&console.log("Set light intensity to "+this.light.intensity,this.name),this.selfIsLight||this.light.parent!==this.gameObject&&this.gameObject.add(this.light)),this.type===1&&this.startCoroutine(this.updateMainLightRoutine(),Oe.LateUpdate))}onDisable(){Zo&&console.log("DISABLE LIGHT",this.name),this.light&&(this.selfIsLight?this.light.intensity=0:this.light.visible=!1)}onEnterXR(e){this._webARRoot=P.getComponentInParent(this.gameObject,$o)??void 0}onLeaveXR(e){}createLight(){const e=this.selfIsLight;if(e&&!this.light)switch(this.light=this.gameObject,this.light.name=this.name,this._intensity=this.light.intensity,this.type){case 1:this.setDirectionalLight(this.light);break}else if(!this.light)switch(this.type){case 1:const t=new Rm(this.color,this.intensity*Math.PI);if(t.position.set(0,0,-oS*.5).applyQuaternion(this.gameObject.quaternion),this.gameObject.add(t.target),br(t.target,0,0,0),this.light=t,this.gameObject.position.set(0,0,0),this.gameObject.rotation.set(0,0,0),Zo){const l=new EP(this.light,.2,this.color);this.context.scene.add(l)}break;case 0:const s=new TP(this.color,this.intensity*Math.PI,this.range,yy(this.spotAngle/2),1-yy(this.innerSpotAngle/2)/yy(this.spotAngle/2),2);s.position.set(0,0,0),s.rotation.set(0,0,0),this.light=s;const o=s.target;s.add(o),o.position.set(0,0,this.range),o.rotation.set(0,0,0);break;case 2:const r=new Tm(this.color,this.intensity*Math.PI,this.range);this.light=r;break}if(this.light){if(this._intensity>=0?this.light.intensity=this._intensity:this._intensity=this.light.intensity,this.shadows!==0?this.light.castShadow=!0:this.light.castShadow=!1,this.light.shadow){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),Zo&&console.log("Override shadow bias?",this._overrideShadowBiasSettings,this.shadowBias,this.shadowNormalBias),this.light.shadow.bias=this.shadowBias,this.light.shadow.normalBias=this.shadowNormalBias,this.updateShadowSoftHard();const t=this.light.shadow.camera;if(t.near=this.shadowNearPlane,this._shadowDistance!==void 0&&typeof this._shadowDistance=="number"?t.far=this._shadowDistance:t.far=oS*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{const s=this.gameObject.scale.x;t.left*=s,t.right*=s}if(this.shadowHeight!==void 0)t.top=this.shadowHeight/2,t.bottom=-this.shadowHeight/2;else{const s=this.gameObject.scale.y;t.top*=s,t.bottom*=s}this.light.shadow.needsUpdate=!0,Zo&&this.context.scene.add(new AP(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}}updateShadowSoftHard(){this.light&&this.light.shadow&&(this.shadows===2||(this.light.shadow.radius=1,this.light.shadow.blurSamples=1))}setDirectionalLight(e){e.add(e.target),e.target.position.set(0,0,-1)}}a(yi,"allowChangingRendererShadowMapType",!0),fn([m()],yi.prototype,"type",2),fn([m(oe)],yi.prototype,"color",1),fn([m()],yi.prototype,"shadowNearPlane",1),fn([m()],yi.prototype,"shadowBias",1),fn([m()],yi.prototype,"shadowNormalBias",1),fn([m()],yi.prototype,"shadows",1),fn([m()],yi.prototype,"lightmapBakeType",2),fn([m()],yi.prototype,"intensity",1),fn([m()],yi.prototype,"shadowDistance",1),fn([m()],yi.prototype,"shadowResolution",1),new S(0,0,0);var s2=Object.defineProperty,uh=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&s2(e,t,o),o};const vy=C("debuglods"),n2=C("nolods");class Cl{constructor(){a(this,"screenRelativeTransitionHeight"),a(this,"distance"),a(this,"renderers")}}uh([m()],Cl.prototype,"screenRelativeTransitionHeight"),uh([m()],Cl.prototype,"distance"),uh([m(Ui)],Cl.prototype,"renderers");class o2{constructor(e){a(this,"model"),this.model=e}get renderers(){return this.model.renderers}}class ph extends I{constructor(){super(...arguments),a(this,"fadeMode",0),a(this,"localReferencePoint"),a(this,"lodCount",0),a(this,"size",0),a(this,"animateCrossFading",!1),a(this,"lodModels"),a(this,"_lods",[]),a(this,"_settings",[]),a(this,"_lodsHandler"),a(this,"_distanceFactor",1)}start(){if(vy&&console.log("LODGROUP",this.name,this.lodModels,this),!n2&&!this._lodsHandler&&this.gameObject&&this.lodModels&&Array.isArray(this.lodModels)){const e=[];for(const s of this.lodModels){const o=new o2(s);this._lods.push(o);for(const r of o.renderers)e.includes(r)||e.push(r)}this._lodsHandler=new Array;for(let s=0;s<e.length;s++){const o=new IP;this._lodsHandler.push(o),this.gameObject.add(o)}const t=new E;t.name="Cull "+this.name;for(let s=0;s<e.length;s++){const o=e[s],r=this._lodsHandler[s],l=o.gameObject;vy&&console.log(s,l.name);for(const c of this._lods){const h=c.model.distance;let d=null;if(c.renderers.includes(o)?d=l:d=t,d.type==="Group"){console.warn(`LODGroup ${this.name}: Group or MultiMaterial object's are not supported as LOD object: ${d.name}`);continue}vy&&console.log("LEVEL",d.name,h),r.autoUpdate=!1,this.onAddLodLevel(r,d,c.model.distance)}}}}onAfterRender(){if(!this.gameObject||!this._lodsHandler)return;const e=this.context.mainCamera;if(e)for(const t of this._lodsHandler){t.update(e);const s=t.getCurrentLevel(),o=t.levels[s];t.layers.mask=o.object.layers.mask}}onAddLodLevel(e,t,s){if(t===this.gameObject){console.warn("LODGroup component must be on parent object and not mesh directly at the moment",t.name,t);return}e.addLevel(t,s*this._distanceFactor,.01);const o={lod:e,levelIndex:e.levels.length-1,distance:s};this._settings.push(o)}distanceFactor(e){if(e!==this._distanceFactor){this._distanceFactor=e;for(const t of this._settings){const s=t.lod.levels[t.levelIndex];s.distance=t.distance*e}}}}uh([m(S)],ph.prototype,"localReferencePoint"),uh([m(Cl)],ph.prototype,"lodModels");var r2=Object.defineProperty,a2=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&r2(e,t,o),o};const Op=C("debugnestedgltf");class kp extends I{constructor(){super(...arguments),a(this,"filePath"),a(this,"loadAssetInParent",!0),a(this,"_isLoadingOrDoneLoading",!1)}listenToProgress(e){var t;(t=this.filePath)==null||t.beginListenDownload(e)}preload(){var e;(e=this.filePath)==null||e.preload()}async start(){var e,t,s,o,r;if(this._isLoadingOrDoneLoading)return;Op&&console.log(this,this.guid);const l=this.gameObject.parent;if(l){this._isLoadingOrDoneLoading=!0;const c=new Fs;c.idProvider=new jt(this.hash(this.guid)),c.parent=this.loadAssetInParent!==!1?l:this.gameObject,this.gameObject.updateMatrix();const h=this.gameObject.matrix;Op&&console.log("Load nested:",((e=this.filePath)==null?void 0:e.url)??this.filePath,this.gameObject.position);const d=await((s=(t=this.filePath)==null?void 0:t.instantiate)==null?void 0:s.call(this.filePath,c));Op&&console.log("Nested loaded:",((o=this.filePath)==null?void 0:o.url)??this.filePath,d),d&&this.loadAssetInParent!==!1&&(d.matrixAutoUpdate=!1,d.matrix.identity(),d.applyMatrix4(h),d.matrixAutoUpdate=!0,d.layers.disableAll(),d.layers.set(this.layer),this.dispatchEvent(new CustomEvent("loaded",{detail:{instance:d,assetReference:this.filePath}}))),Op&&console.log("Nested loading done:",((r=this.filePath)==null?void 0:r.url)??this.filePath,d)}}onDestroy(){var e;(e=this.filePath)==null||e.unload()}hash(e){let t=0;for(let s=0;s<e.length;s++)t=e.charCodeAt(s)+((t<<5)-t);return t}}a2([m(ce)],kp.prototype,"filePath");var l2=Object.defineProperty,by=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&l2(e,t,o),o};const c2=C("debugnet"),Mp=class Sv extends I{constructor(){super(...arguments),a(this,"url",null),a(this,"urlParameterName",null),a(this,"localhost",null)}awake(){c2&&console.log(this),this.context.connection.registerProvider(this)}getWebsocketUrl(){let e=this.url?Sv.GetUrl(this.url,this.localhost):null;if(this.urlParameterName){const s=C(this.urlParameterName);s&&typeof s=="string"&&(e=s)}if(!e)return null;const t=new RegExp("(((https?)|(?<socket_prefix>wss?))://)?(www.)?(?<url>.+)","gm").exec(e);return t!=null&&t.groups?t?.groups.socket_prefix?e:"wss://"+t?.groups.url:null}static GetUrl(e,t){let s=e;const o=Sv.IsLocalNetwork()&&t;if(o&&(s=t),e!=null&&e.startsWith("/")){const r=o?s:window.location.origin;r!=null&&r.endsWith("/")&&e.startsWith("/")&&(e=e.substring(1)),s=r+e}return s}static IsLocalNetwork(e=window.location.hostname){return Xt(e)}};by([m()],Mp.prototype,"url"),by([m()],Mp.prototype,"urlParameterName"),by([m()],Mp.prototype,"localhost");let _y=Mp;var h2=Object.defineProperty,Rp=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&h2(e,t,o),o};class ta extends I{constructor(){super(...arguments),a(this,"referenceSpace"),a(this,"from"),a(this,"affectPosition",!1),a(this,"affectRotation",!1),a(this,"alignLookDirection",!1),a(this,"levelLookDirection",!1),a(this,"levelPosition",!1),a(this,"positionOffset",new S(0,0,0)),a(this,"rotationOffset",new S(0,0,0)),a(this,"offset",new S(0,0,0))}update(){if(!this.from)return;var e=ee(this.from),t=Se(this.from);this.offset.copy(this.positionOffset);const s=this.offset.length();if(this.referenceSpace&&this.offset.transformDirection(this.referenceSpace.matrixWorld).multiplyScalar(s),e.add(this.offset),this.levelPosition&&this.referenceSpace){const c=new yr(this.gameObject.up,0),h=ee(this.referenceSpace);c.setFromNormalAndCoplanarPoint(this.gameObject.up,h);const d=new S(0,0,0);c.projectPoint(e,d),e.copy(d)}this.affectPosition&<(this.gameObject,e);const o=new Dt(this.rotationOffset.x,this.rotationOffset.y,this.rotationOffset.z),r=new V().setFromEuler(o);this.affectRotation&&Yi(this.gameObject,t.multiply(r));const l=new S;this.from.getWorldDirection(l).multiplyScalar(50),this.levelLookDirection&&(l.y=0),this.alignLookDirection&&this.gameObject.lookAt(l)}}Rp([m(P)],ta.prototype,"referenceSpace"),Rp([m(P)],ta.prototype,"from"),Rp([m(S)],ta.prototype,"positionOffset"),Rp([m(S)],ta.prototype,"rotationOffset");var d2=Object.defineProperty,Jo=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&d2(e,t,o),o};class vi{constructor(e=0,t=0){a(this,"time",0),a(this,"value",0),a(this,"inTangent",1/0),a(this,"inWeight"),a(this,"outTangent",1/0),a(this,"outWeight"),a(this,"weightedMode"),this.time=e,this.value=t}}Jo([m()],vi.prototype,"time"),Jo([m()],vi.prototype,"value"),Jo([m()],vi.prototype,"inTangent"),Jo([m()],vi.prototype,"inWeight"),Jo([m()],vi.prototype,"outTangent"),Jo([m()],vi.prototype,"outWeight"),Jo([m()],vi.prototype,"weightedMode");const rS=class rd{constructor(){a(this,"keys",[])}static linearFromTo(e,t,s){const o=new rd,r=new vi;r.time=0,r.value=e;const l=new vi;return l.time=s,l.value=t,o.keys.push(r,l),o}static constant(e){const t=new rd,s=new vi;return s.time=0,s.value=e,t.keys.push(s),t}clone(){var e;const t=new rd;return t.keys=((e=this.keys)==null?void 0:e.map(s=>{const o=new vi;return o.time=s.time,o.value=s.value,o.inTangent=s.inTangent,o.inWeight=s.inWeight,o.outTangent=s.outTangent,o.outWeight=s.outWeight,o.weightedMode=s.weightedMode,o}))||[],t}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;if(this.keys.length===1)return this.keys[0].value;if(this.keys[0].time>=e)return this.keys[0].value;for(let t=0;t<this.keys.length;t++){const s=this.keys[t];if(s.time<=e)if(t+1<this.keys.length){const o=this.keys[t+1];if(o.time<e)continue;return!isFinite(s.outTangent)||!isFinite(o.inTangent)?s.value:rd.interpolateValue(e,s,o)}else return s.value}return this.keys[this.keys.length-1].value}static interpolateValue(e,t,s){const o=t.time,r=t.value,l=t.outTangent,c=s.time,h=s.value,d=s.inTangent,u=c-o,p=u*u,g=p*u,f=((l+d)*u-2*(h-r))/g,y=(3*(h-r)-(d+2*l)*u)/p,v=l,b=r,_=e-o,w=_*_,x=w*_;return f*x+y*w+v*_+b}};Jo([m(vi)],rS.prototype,"keys");let mh=rS;var u2=Object.defineProperty,O=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&u2(e,t,o),o};const Tp=C("debugparticles");var Zn=(n=>(n[n.Billboard=0]="Billboard",n[n.Stretch=1]="Stretch",n[n.HorizontalBillboard=2]="HorizontalBillboard",n[n.VerticalBillboard=3]="VerticalBillboard",n[n.Mesh=4]="Mesh",n))(Zn||{});class ia{constructor(){a(this,"alphaKeys",[]),a(this,"colorKeys",[])}get duration(){return 1}evaluate(e,t){let s,o=0,r=null,l=0;for(let c=0;c<this.alphaKeys.length;c++){const h=this.alphaKeys[c];(h.time<e||!s)&&(s=h,o=c)}for(let c=0;c<this.colorKeys.length;c++){const h=this.colorKeys[c];(h.time<e||!r)&&(r=h,l=c)}if(r)if(l+1<this.colorKeys.length){const c=this.colorKeys[l+1],h=W.remap(e,r.time,c.time,0,1);t.r=W.lerp(r.color.r,c.color.r,h),t.g=W.lerp(r.color.g,c.color.g,h),t.b=W.lerp(r.color.b,c.color.b,h)}else t.r=r.color.r,t.g=r.color.g,t.b=r.color.b;if(s)if(o+1<this.alphaKeys.length){const c=this.alphaKeys[o+1],h=W.remap(e,s.time,c.time,0,1);t.alpha=W.lerp(s.alpha,c.alpha,h)}else t.alpha=s.alpha;return t}}O([m()],ia.prototype,"alphaKeys"),O([m()],ia.prototype,"colorKeys");var gh=(n=>(n[n.Local=0]="Local",n[n.World=1]="World",n[n.Custom=2]="Custom",n))(gh||{}),Ep=(n=>(n[n.Sphere=0]="Sphere",n[n.SphereShell=1]="SphereShell",n[n.Hemisphere=2]="Hemisphere",n[n.HemisphereShell=3]="HemisphereShell",n[n.Cone=4]="Cone",n[n.Box=5]="Box",n[n.Mesh=6]="Mesh",n[n.ConeShell=7]="ConeShell",n[n.ConeVolume=8]="ConeVolume",n[n.ConeVolumeShell=9]="ConeVolumeShell",n[n.Circle=10]="Circle",n[n.CircleEdge=11]="CircleEdge",n[n.SingleSidedEdge=12]="SingleSidedEdge",n[n.MeshRenderer=13]="MeshRenderer",n[n.SkinnedMeshRenderer=14]="SkinnedMeshRenderer",n[n.BoxShell=15]="BoxShell",n[n.BoxEdge=16]="BoxEdge",n[n.Donut=17]="Donut",n[n.Rectangle=18]="Rectangle",n[n.Sprite=19]="Sprite",n[n.SpriteRenderer=20]="SpriteRenderer",n))(Ep||{});const Jn=class ad{constructor(){a(this,"mode","Constant"),a(this,"constant"),a(this,"constantMin"),a(this,"constantMax"),a(this,"curve"),a(this,"curveMin"),a(this,"curveMax"),a(this,"curveMultiplier")}static constant(e){const t=new ad;return t.setConstant(e),t}static betweenTwoConstants(e,t){const s=new ad;return s.setMinMaxConstant(e,t),s}static curve(e,t=1){const s=new ad;return s.setCurve(e,t),s}setConstant(e){this.mode=0,this.constant=e}setMinMaxConstant(e,t){this.mode=3,this.constantMin=e,this.constantMax=t}setCurve(e,t=1){this.mode=1,this.curve=e,this.curveMultiplier=t}clone(){var e,t,s;const o=new ad;return o.mode=this.mode,o.constant=this.constant,o.constantMin=this.constantMin,o.constantMax=this.constantMax,o.curve=(e=this.curve)==null?void 0:e.clone(),o.curveMin=(t=this.curveMin)==null?void 0:t.clone(),o.curveMax=(s=this.curveMax)==null?void 0:s.clone(),o.curveMultiplier=this.curveMultiplier,o}evaluate(e,t){const s=t===void 0?Math.random():t;switch(this.mode){case 0:case"Constant":return this.constant;case 1:case"Curve":return e=W.clamp01(e),this.curve.evaluate(e)*this.curveMultiplier;case 2:case"TwoCurves":const o=e*this.curveMin.duration,r=e*this.curveMax.duration;return W.lerp(this.curveMin.evaluate(o),this.curveMax.evaluate(r),s%1)*this.curveMultiplier;case 3:case"TwoConstants":return W.lerp(this.constantMin,this.constantMax,s%1);default:this.curveMax.evaluate(e)*this.curveMultiplier;break}return 0}getMax(){switch(this.mode){case 0:case"Constant":return this.constant;case 1:case"Curve":return this.getMaxFromCurve(this.curve)*this.curveMultiplier;case 2:case"TwoCurves":return Math.max(this.getMaxFromCurve(this.curveMin),this.getMaxFromCurve(this.curveMax))*this.curveMultiplier;case 3:case"TwoConstants":return Math.max(this.constantMin,this.constantMax);default:return 0}}getMaxFromCurve(e){if(!e)return 0;let t=Number.MIN_VALUE;for(let s=0;s<e.keys.length;s++){const o=e.keys[s];o.value>t&&(t=o.value)}return t}};O([m()],Jn.prototype,"mode"),O([m()],Jn.prototype,"constant"),O([m()],Jn.prototype,"constantMin"),O([m()],Jn.prototype,"constantMax"),O([m(mh)],Jn.prototype,"curve"),O([m(mh)],Jn.prototype,"curveMin"),O([m(mh)],Jn.prototype,"curveMax"),O([m()],Jn.prototype,"curveMultiplier");let Z=Jn;var st;const er=(st=class{constructor(){a(this,"mode",0),a(this,"color"),a(this,"colorMin"),a(this,"colorMax"),a(this,"gradient"),a(this,"gradientMin"),a(this,"gradientMax")}static constant(n){const e=new st;return e.constant(n),e}static betweenTwoColors(n,e){const t=new st;return t.betweenTwoColors(n,e),t}constant(n){return this.mode=0,this.color=n,this}betweenTwoColors(n,e){return this.mode=2,this.colorMin=n,this.colorMax=e,this}evaluate(n,e){const t=e===void 0?Math.random():e;switch(this.mode){case 0:case"Color":return this.color;case 1:case"Gradient":return this.gradient.evaluate(n,st._temp),st._temp;case 2:case"TwoColors":return st._temp.lerpColors(this.colorMin,this.colorMax,t);case 3:case"TwoGradients":return this.gradientMin.evaluate(n,st._temp),this.gradientMax.evaluate(n,st._temp2),st._temp.lerp(st._temp2,t);case 4:case"RandomColor":const s=Math.random();return this.gradientMin.evaluate(n,st._temp),this.gradientMax.evaluate(n,st._temp2),st._temp.lerp(st._temp2,s)}return st._temp.set(16777215),st._temp.alpha=1,st._temp}},a(st,"_temp",new he(0,0,0,1)),a(st,"_temp2",new he(0,0,0,1)),st);O([m()],er.prototype,"mode"),O([m(he)],er.prototype,"color"),O([m(he)],er.prototype,"colorMin"),O([m(he)],er.prototype,"colorMax"),O([m(ia)],er.prototype,"gradient"),O([m(ia)],er.prototype,"gradientMin"),O([m(ia)],er.prototype,"gradientMax");let sa=er;var wy=(n=>(n[n.Hierarchy=0]="Hierarchy",n[n.Local=1]="Local",n[n.Shape=2]="Shape",n))(wy||{});class Wt{constructor(){a(this,"cullingMode"),a(this,"duration"),a(this,"emitterVelocityMode"),a(this,"flipRotation"),a(this,"gravityModifier"),a(this,"gravityModifierMultiplier"),a(this,"loop"),a(this,"maxParticles"),a(this,"playOnAwake"),a(this,"prewarm"),a(this,"ringBufferLoopRange"),a(this,"ringBufferMode"),a(this,"scalingMode"),a(this,"simulationSpace"),a(this,"simulationSpeed"),a(this,"startColor"),a(this,"startDelay"),a(this,"startDelayMultiplier"),a(this,"startLifetime"),a(this,"startLifetimeMultiplier"),a(this,"startRotation"),a(this,"startRotationMultiplier"),a(this,"startRotation3D"),a(this,"startRotationX"),a(this,"startRotationXMultiplier"),a(this,"startRotationY"),a(this,"startRotationYMultiplier"),a(this,"startRotationZ"),a(this,"startRotationZMultiplier"),a(this,"startSize"),a(this,"startSize3D"),a(this,"startSizeMultiplier"),a(this,"startSizeX"),a(this,"startSizeXMultiplier"),a(this,"startSizeY"),a(this,"startSizeYMultiplier"),a(this,"startSizeZ"),a(this,"startSizeZMultiplier"),a(this,"startSpeed"),a(this,"startSpeedMultiplier"),a(this,"stopAction"),a(this,"useUnscaledTime")}}O([m(Z)],Wt.prototype,"gravityModifier"),O([m(sa)],Wt.prototype,"startColor"),O([m(Z)],Wt.prototype,"startDelay"),O([m(Z)],Wt.prototype,"startLifetime"),O([m(Z)],Wt.prototype,"startRotation"),O([m(Z)],Wt.prototype,"startRotationX"),O([m(Z)],Wt.prototype,"startRotationY"),O([m(Z)],Wt.prototype,"startRotationZ"),O([m(Z)],Wt.prototype,"startSize"),O([m(Z)],Wt.prototype,"startSizeX"),O([m(Z)],Wt.prototype,"startSizeY"),O([m(Z)],Wt.prototype,"startSizeZ"),O([m(Z)],Wt.prototype,"startSpeed");class Ap{constructor(){a(this,"cycleCount"),a(this,"maxCount"),a(this,"minCount"),a(this,"probability"),a(this,"repeatInterval"),a(this,"time"),a(this,"count"),a(this,"_performed",0)}reset(){this._performed=0}run(e){if(e<=this.time)return 0;let t=0;if(this.cycleCount===0||this._performed<this.cycleCount){const s=this.time+this.repeatInterval*this._performed;if(e>=s&&(this._performed+=1,Math.random()<this.probability))switch(this.count.mode){case 0:t=this.count.constant;break;case 3:t=W.lerp(this.count.constantMin,this.count.constantMax,Math.random());break;case 1:t=this.count.curve.evaluate(Math.random());break;case 2:const o=Math.random();t=W.lerp(this.count.curveMin.evaluate(o),this.count.curveMax.evaluate(o),Math.random());break}}return t}}class eo{constructor(){a(this,"enabled"),a(this,"bursts"),a(this,"rateOverTime"),a(this,"rateOverTimeMultiplier"),a(this,"rateOverDistance"),a(this,"rateOverDistanceMultiplier"),a(this,"system")}get burstCount(){var e;return((e=this.bursts)==null?void 0:e.length)??0}reset(){var e;(e=this.bursts)==null||e.forEach(t=>t.reset())}getBurst(){let e=0;if(this.burstCount>0)for(let t=0;t<this.burstCount;t++){const s=this.bursts[t];this.system.main.loop&&s.time>=this.system.time&&s.reset(),e+=Math.round(s.run(this.system.time))}return e}}O([m()],eo.prototype,"enabled"),O([m()],eo.prototype,"bursts"),O([m(Z)],eo.prototype,"rateOverTime"),O([m()],eo.prototype,"rateOverTimeMultiplier"),O([m(Z)],eo.prototype,"rateOverDistance"),O([m()],eo.prototype,"rateOverDistanceMultiplier");class Ip{constructor(){a(this,"enabled"),a(this,"color")}}O([m(sa)],Ip.prototype,"color");class na{constructor(){a(this,"enabled"),a(this,"separateAxes"),a(this,"size"),a(this,"sizeMultiplier"),a(this,"x"),a(this,"xMultiplier"),a(this,"y"),a(this,"yMultiplier"),a(this,"z"),a(this,"zMultiplier"),a(this,"_time",0),a(this,"_temp",new S)}evaluate(e,t,s){if(t||(t=this._temp),!this.enabled)return t.x=t.y=t.z=1,t;if(this.separateAxes)t.x=this.x.evaluate(e,s)*this.xMultiplier,t.y=this.y.evaluate(e,s)*this.yMultiplier,t.z=this.z.evaluate(e,s)*this.zMultiplier;else{const o=this.size.evaluate(e,s)*this.sizeMultiplier;t.x=o}return t}}O([m(Z)],na.prototype,"size"),O([m(Z)],na.prototype,"x"),O([m(Z)],na.prototype,"y"),O([m(Z)],na.prototype,"z");var tr;const nt=(tr=class{constructor(){a(this,"shapeType",5),a(this,"enabled",!0),a(this,"alignToDirection",!1),a(this,"angle",0),a(this,"arc",360),a(this,"arcSpread"),a(this,"arcSpeedMultiplier"),a(this,"arcMode"),a(this,"boxThickness"),a(this,"position"),a(this,"rotation"),a(this,"_rotation",new Dt),a(this,"scale"),a(this,"radius"),a(this,"radiusThickness"),a(this,"sphericalDirectionAmount"),a(this,"randomDirectionAmount"),a(this,"randomPositionAmount"),a(this,"meshShapeType"),a(this,"meshRenderer"),a(this,"_meshObj"),a(this,"_meshGeometry"),a(this,"system"),a(this,"_space"),a(this,"_worldSpaceMatrix",new se),a(this,"_worldSpaceMatrixInverse",new se),a(this,"_vector",new S(0,0,0)),a(this,"_temp",new S(0,0,0)),a(this,"_triangle",new LP),a(this,"_dir",new S),a(this,"_loopTime",0),a(this,"_loopDirection",1),Tp&&console.log(this)}get type(){return Ep[this.shapeType]}initialize(n){this.onInitialize(n),n.position.x=this._vector.x,n.position.y=this._vector.y,n.position.z=this._vector.z}toJSON(){return this}clone(){return new tr}setMesh(n){this.meshRenderer=n,n?(this._meshObj=n.sharedMeshes[Math.floor(Math.random()*n.sharedMeshes.length)],this._meshGeometry=this._meshObj.geometry):(this._meshObj=void 0,this._meshGeometry=void 0)}update(n,e){}onUpdate(n,e,t,s){this.system=n,this._space=t,t===1&&(this._worldSpaceMatrix.copy(s.matrixWorld),this._worldSpaceMatrix.elements[0]=1,this._worldSpaceMatrix.elements[5]=1,this._worldSpaceMatrix.elements[10]=1,this._worldSpaceMatrixInverse.copy(this._worldSpaceMatrix).invert())}applyRotation(n){const e=this.rotation.x!==0||this.rotation.y!==0||this.rotation.z!==0;return e&&(this._rotation.x=W.toRadians(this.rotation.x),this._rotation.y=W.toRadians(this.rotation.y),this._rotation.z=W.toRadians(this.rotation.z),this._rotation.order="ZYX",n.applyEuler(this._rotation)),e}onInitialize(n){this._vector.set(0,0,0),n.mesh=void 0,n.mesh_geometry=void 0;const e=this._temp.copy(this.position),t=this._space===1;t&&e.applyQuaternion(this.system.worldQuaternion);let s=this.radius;if(t&&(s*=this.system.worldScale.x),this.enabled){switch(this.shapeType){case 5:Tp&&$.DrawWireBox(this.position,this.scale,14540253,1),this._vector.x=Math.random()*this.scale.x-this.scale.x/2,this._vector.y=Math.random()*this.scale.y-this.scale.y/2,this._vector.z=Math.random()*this.scale.z-this.scale.z/2,this._vector.add(e);break;case 4:this.randomConePoint(this.position,this.angle,s,this.radiusThickness,this.arc,this.arcMode,this._vector);break;case 0:this.randomSpherePoint(this.position,s,this.radiusThickness,this.arc,this._vector);break;case 10:this.randomCirclePoint(this.position,s,this.radiusThickness,this.arc,this._vector);break;case 13:const o=this.meshRenderer;o?.destroyed==!1&&this.setMesh(o);const r=n.mesh=this._meshObj,l=n.mesh_geometry=this._meshGeometry;if(r&&l)switch(this.meshShapeType){case 0:{const c=l.getAttribute("position"),h=Math.floor(Math.random()*c.count);this._vector.fromBufferAttribute(c,h),this._vector.applyMatrix4(r.matrixWorld),n.mesh_normal=h}break;case 1:break;case 2:{const c=l.index;if(c){let h=Math.random(),d=Math.random();h+d>1&&(h=1-h,d=1-d);const u=Math.floor(Math.random()*(c.count/3));let p=u*3,g=u*3+1,f=u*3+2;p=c.getX(p),g=c.getX(g),f=c.getX(f);const y=l.getAttribute("position");this._triangle.a.fromBufferAttribute(y,p),this._triangle.b.fromBufferAttribute(y,g),this._triangle.c.fromBufferAttribute(y,f),this._vector.set(0,0,0).addScaledVector(this._triangle.a,h).addScaledVector(this._triangle.b,d).addScaledVector(this._triangle.c,1-(h+d)),this._vector.applyMatrix4(r.matrixWorld),n.mesh_normal=u}}break}break;default:this._vector.set(0,0,0),F()&&!globalThis.__particlesystem_shapetype_unsupported&&(console.warn("ParticleSystem ShapeType is not supported:",Ep[this.shapeType]),globalThis.__particlesystem_shapetype_unsupported=!0);break}this.randomizePosition(this._vector,this.randomPositionAmount)}this.applyRotation(this._vector),t&&(this._vector.applyQuaternion(this.system.worldQuaternion),this._vector.add(this.system.worldPos)),Tp&&$.DrawSphere(this._vector,.03,16711680,.5,!0)}getDirection(n,e){var t;if(!this.enabled)return this._dir.set(0,0,1),this._dir;switch(this.shapeType){case 5:this._dir.set(0,0,1);break;case 4:this._dir.set(0,0,1);break;case 10:case 0:const s=e.x,o=e.y,r=e.z;this._dir.set(s,o,r),(t=this.system)!=null&&t.worldspace?this._dir.sub(this.system.worldPos):this._dir.sub(this.position);break;case 13:const l=n.mesh,c=n.mesh_geometry;if(l&&c)switch(this.meshShapeType){case 0:{const h=c.getAttribute("normal"),d=n.mesh_normal;this._dir.fromBufferAttribute(h,d)}break;case 1:break;case 2:{const h=c.index;if(h){const d=n.mesh_normal,u=h.getX(d*3),p=h.getX(d*3+1),g=h.getX(d*3+2),f=c.getAttribute("position"),y=q(),v=q(),b=q();y.fromBufferAttribute(f,u),v.fromBufferAttribute(f,p),b.fromBufferAttribute(f,g),y.sub(v),b.sub(v),y.cross(b),this._dir.copy(y).multiplyScalar(-1);const _=Se(l);this._dir.applyQuaternion(_)}}break}break;default:this._dir.set(0,0,1);break}return this._space===1&&this._dir.applyQuaternion(this.system.worldQuaternion),this.applyRotation(this._dir),this._dir.normalize(),this.spherizeDirection(this._dir,this.sphericalDirectionAmount),this.randomizeDirection(this._dir,this.randomDirectionAmount),Tp&&($.DrawSphere(e,.01,8925952,.5,!0),$.DrawDirection(e,this._dir,8925952,.5,!0)),this._dir}randomizePosition(n,e){if(e<=0)return;const t=tr._tempVec;t.set(Math.random()*2-1,Math.random()*2-1,Math.random()*2-1),t.x*=e*this.scale.x,t.y*=e*this.scale.y,t.z*=e*this.scale.z,n.add(t)}randomizeDirection(n,e){if(e===0)return;const t=tr._randomQuat,s=tr._tempVec;s.set(Math.random()-.5,Math.random()-.5,Math.random()-.5).normalize(),t.setFromAxisAngle(s,e*Math.random()*Math.PI),n.applyQuaternion(t)}spherizeDirection(n,e){if(e===0)return;const t=Math.random()*Math.PI*2,s=Math.acos(1-Math.random()*2),o=Math.sin(s)*Math.cos(t),r=Math.sin(s)*Math.sin(t),l=Math.cos(s),c=new S(o,r,l);n.lerp(c,e)}randomSpherePoint(n,e,t,s,o){const r=Math.random(),l=Math.random(),c=2*Math.PI*r*(s/360),h=Math.acos(2*l-1),d=W.lerp(1,1-Math.pow(1-Math.random(),Math.PI),t)*e,u=n.x+this.scale.x*(-d*Math.sin(h)*Math.cos(c)),p=n.y+this.scale.y*(d*Math.sin(h)*Math.sin(c)),g=n.z+this.scale.z*(d*Math.cos(h));o.x=u,o.y=p,o.z=g}randomCirclePoint(n,e,t,s,o){const r=Math.random(),l=2*Math.PI*r*(s/360),c=W.lerp(1,1-Math.pow(1-Math.random(),Math.PI),t)*e,h=n.x+this.scale.x*c*Math.cos(l),d=n.y+this.scale.y*c*Math.sin(l),u=n.z;o.x=h,o.y=d,o.z=u}randomConePoint(n,e,t,s,o,r,l){let c=0,h=0;switch(r){case 0:c=Math.random(),h=Math.random();break;case 2:this._loopTime>1&&(this._loopDirection=-1),this._loopTime<0&&(this._loopDirection=1);case 1:c=.5,h=Math.random(),this._loopTime+=this.system.deltaTime*this._loopDirection;break}let d=2*Math.PI*c*(o/360);switch(r){case 2:case 1:d+=Math.PI+.5,d+=this._loopTime*Math.PI*2,d%=W.toRadians(o);break}const u=Math.acos(2*h-1),p=W.lerp(1,1-Math.pow(1-Math.random(),Math.PI),s)*t,g=n.x+-p*Math.sin(u)*Math.cos(d),f=n.y+p*Math.sin(u)*Math.sin(d),y=n.z;l.x=g*this.scale.x,l.y=f*this.scale.y,l.z=y*this.scale.z}},a(tr,"_randomQuat",new V),a(tr,"_tempVec",new S),tr);O([m()],nt.prototype,"shapeType"),O([m()],nt.prototype,"enabled"),O([m()],nt.prototype,"alignToDirection"),O([m()],nt.prototype,"angle"),O([m()],nt.prototype,"arc"),O([m()],nt.prototype,"arcSpread"),O([m()],nt.prototype,"arcSpeedMultiplier"),O([m()],nt.prototype,"arcMode"),O([m(S)],nt.prototype,"boxThickness"),O([m(S)],nt.prototype,"position"),O([m(S)],nt.prototype,"rotation"),O([m(S)],nt.prototype,"scale"),O([m()],nt.prototype,"radius"),O([m()],nt.prototype,"radiusThickness"),O([m()],nt.prototype,"sphericalDirectionAmount"),O([m()],nt.prototype,"randomDirectionAmount"),O([m()],nt.prototype,"randomPositionAmount"),O([m()],nt.prototype,"meshShapeType"),O([m(Qc)],nt.prototype,"meshRenderer");let xy=nt;class Ce{constructor(){a(this,"damping"),a(this,"enabled"),a(this,"frequency"),a(this,"octaveCount"),a(this,"octaveMultiplier"),a(this,"octaveScale"),a(this,"positionAmount"),a(this,"quality"),a(this,"remap"),a(this,"remapEnabled"),a(this,"remapMultiplier"),a(this,"remapX"),a(this,"remapXMultiplier"),a(this,"remapY"),a(this,"remapYMultiplier"),a(this,"remapZ"),a(this,"remapZMultiplier"),a(this,"scrollSpeedMultiplier"),a(this,"separateAxes"),a(this,"strengthMultiplier"),a(this,"strengthX"),a(this,"strengthXMultiplier"),a(this,"strengthY"),a(this,"strengthYMultiplier"),a(this,"strengthZ"),a(this,"strengthZMultiplier"),a(this,"_noise"),a(this,"_time",0),a(this,"_temp",new S)}update(e){this._time+=e.time.deltaTime*this.scrollSpeedMultiplier}apply(e,t,s,o,r,l){if(!this.enabled)return;this._noise||(this._noise=bO(()=>0));const c=this._temp.set(t.x,t.y,t.z).multiplyScalar(this.frequency),h=this._noise(c.x,c.y,c.z,this._time),d=this._noise(c.x,c.y,c.z,this._time+1e3*this.frequency),u=this._noise(c.x,c.y,c.z,this._time+2e3*this.frequency);this._temp.set(h,d,u).normalize();const p=r/l;let g=this.positionAmount.evaluate(p);this.separateAxes?(this._temp.x*=g*this.strengthXMultiplier,this._temp.y*=g*this.strengthYMultiplier,this._temp.z*=g*this.strengthZMultiplier):(this.strengthX&&(g*=this.strengthX.evaluate(p)*1.5),this._temp.multiplyScalar(g)),s.x+=this._temp.x,s.y+=this._temp.y,s.z+=this._temp.z}}O([m()],Ce.prototype,"damping"),O([m()],Ce.prototype,"enabled"),O([m()],Ce.prototype,"frequency"),O([m()],Ce.prototype,"octaveCount"),O([m()],Ce.prototype,"octaveMultiplier"),O([m()],Ce.prototype,"octaveScale"),O([m(Z)],Ce.prototype,"positionAmount"),O([m()],Ce.prototype,"quality"),O([m(Z)],Ce.prototype,"remap"),O([m()],Ce.prototype,"remapEnabled"),O([m()],Ce.prototype,"remapMultiplier"),O([m(Z)],Ce.prototype,"remapX"),O([m()],Ce.prototype,"remapXMultiplier"),O([m(Z)],Ce.prototype,"remapY"),O([m()],Ce.prototype,"remapYMultiplier"),O([m(Z)],Ce.prototype,"remapZ"),O([m()],Ce.prototype,"remapZMultiplier"),O([m()],Ce.prototype,"scrollSpeedMultiplier"),O([m()],Ce.prototype,"separateAxes"),O([m()],Ce.prototype,"strengthMultiplier"),O([m(Z)],Ce.prototype,"strengthX"),O([m()],Ce.prototype,"strengthXMultiplier"),O([m(Z)],Ce.prototype,"strengthY"),O([m()],Ce.prototype,"strengthYMultiplier"),O([m(Z)],Ce.prototype,"strengthZ"),O([m()],Ce.prototype,"strengthZMultiplier");class We{constructor(){a(this,"enabled"),a(this,"attachRibbonToTransform",!1),a(this,"colorOverLifetime"),a(this,"colorOverTrail"),a(this,"dieWithParticles",!0),a(this,"inheritParticleColor",!0),a(this,"lifetime"),a(this,"lifetimeMultiplier"),a(this,"minVertexDistance",.2),a(this,"mode",0),a(this,"ratio",1),a(this,"ribbonCount",1),a(this,"shadowBias",0),a(this,"sizeAffectsLifetime",!1),a(this,"sizeAffectsWidth",!1),a(this,"splitSubEmitterRibbons",!1),a(this,"textureMode",0),a(this,"widthOverTrail"),a(this,"widthOverTrailMultiplier"),a(this,"worldSpace",!1)}getWidth(e,t,s,o){const r=this.widthOverTrail.evaluate(s,o);return e*=r,e}getColor(e,t,s){const o=this.colorOverTrail.evaluate(s),r=this.colorOverLifetime.evaluate(t);e.x*=o.r*r.r,e.y*=o.g*r.g,e.z*=o.b*r.b,"alpha"in o&&"alpha"in r&&(e.w*=o.alpha*r.alpha)}}O([m()],We.prototype,"enabled"),O([m()],We.prototype,"attachRibbonToTransform"),O([m(sa)],We.prototype,"colorOverLifetime"),O([m(sa)],We.prototype,"colorOverTrail"),O([m()],We.prototype,"dieWithParticles"),O([m()],We.prototype,"inheritParticleColor"),O([m(Z)],We.prototype,"lifetime"),O([m()],We.prototype,"lifetimeMultiplier"),O([m()],We.prototype,"minVertexDistance"),O([m()],We.prototype,"mode"),O([m()],We.prototype,"ratio"),O([m()],We.prototype,"ribbonCount"),O([m()],We.prototype,"shadowBias"),O([m()],We.prototype,"sizeAffectsLifetime"),O([m()],We.prototype,"sizeAffectsWidth"),O([m()],We.prototype,"splitSubEmitterRibbons"),O([m()],We.prototype,"textureMode"),O([m(Z)],We.prototype,"widthOverTrail"),O([m()],We.prototype,"widthOverTrailMultiplier"),O([m()],We.prototype,"worldSpace");class qe{constructor(){a(this,"enabled"),a(this,"space",0),a(this,"orbitalX"),a(this,"orbitalY"),a(this,"orbitalZ"),a(this,"orbitalXMultiplier"),a(this,"orbitalYMultiplier"),a(this,"orbitalZMultiplier"),a(this,"orbitalOffsetX"),a(this,"orbitalOffsetY"),a(this,"orbitalOffsetZ"),a(this,"speedModifier"),a(this,"speedModifierMultiplier"),a(this,"x"),a(this,"xMultiplier"),a(this,"y"),a(this,"yMultiplier"),a(this,"z"),a(this,"zMultiplier"),a(this,"_system"),a(this,"_temp",new S),a(this,"_temp2",new S),a(this,"_temp3",new S),a(this,"_hasOrbital",!1),a(this,"_index",0),a(this,"_orbitalMatrix",new se)}update(e){this._system=e}init(e){this._index==0&&(e.debug=!0),this._index+=1,e.orbitx=this.orbitalX.evaluate(Math.random()),e.orbity=this.orbitalY.evaluate(Math.random()),e.orbitz=this.orbitalZ.evaluate(Math.random()),this._hasOrbital=e.orbitx!=0||e.orbity!=0||e.orbitz!=0}apply(e,t,s,o,r,l,c){var h;if(!this.enabled)return;const d=l/c,u=this.speedModifier.evaluate(d)*this.speedModifierMultiplier,p=this.x.evaluate(d),g=this.y.evaluate(d),f=this.z.evaluate(d);if(this._temp.set(-p,g,f),this._system&&this._system.main.simulationSpace===1&&this._temp.applyQuaternion(this._system.worldQuaternion),this._hasOrbital&&((h=this._system)==null?void 0:h.worldPos)){const y=this._temp2.set(s.x,s.y,s.z),v=this.orbitalXMultiplier,b=this.orbitalYMultiplier,_=this.orbitalZMultiplier,w=u*Math.PI*2*10,x=Math.cos(w*v),k=Math.sin(w*v),M=Math.cos(w*b),T=Math.sin(w*b),L=Math.cos(w*_),D=Math.sin(w*_),z=y.x*(M*L)+y.y*(M*D)+y.z*-T,j=y.x*(k*T*L-x*D)+y.y*(k*T*D+x*L)+y.z*(k*M),H=y.x*(x*T*L+k*D)+y.y*(x*T*D-k*L)+y.z*(x*M),K=this._temp3.set(y.x-z,y.y-j,y.z-H);K.normalize(),K.multiplyScalar(.2/r*Math.max(this.orbitalXMultiplier,this.orbitalYMultiplier,this.orbitalZMultiplier)),o.x+=K.x,o.y+=K.y,o.z+=K.z}o.x+=this._temp.x,o.y+=this._temp.y,o.z+=this._temp.z,o.x*=u,o.y*=u,o.z*=u}}O([m()],qe.prototype,"enabled"),O([m()],qe.prototype,"space"),O([m(Z)],qe.prototype,"orbitalX"),O([m(Z)],qe.prototype,"orbitalY"),O([m(Z)],qe.prototype,"orbitalZ"),O([m()],qe.prototype,"orbitalXMultiplier"),O([m()],qe.prototype,"orbitalYMultiplier"),O([m()],qe.prototype,"orbitalZMultiplier"),O([m()],qe.prototype,"orbitalOffsetX"),O([m()],qe.prototype,"orbitalOffsetY"),O([m()],qe.prototype,"orbitalOffsetZ"),O([m(Z)],qe.prototype,"speedModifier"),O([m()],qe.prototype,"speedModifierMultiplier"),O([m(Z)],qe.prototype,"x"),O([m()],qe.prototype,"xMultiplier"),O([m(Z)],qe.prototype,"y"),O([m()],qe.prototype,"yMultiplier"),O([m(Z)],qe.prototype,"z"),O([m()],qe.prototype,"zMultiplier");class Vt{constructor(){a(this,"animation"),a(this,"enabled"),a(this,"cycleCount"),a(this,"frameOverTime"),a(this,"frameOverTimeMultiplier"),a(this,"numTilesX"),a(this,"numTilesY"),a(this,"startFrame"),a(this,"startFrameMultiplier"),a(this,"rowMode"),a(this,"rowIndex"),a(this,"spriteCount"),a(this,"timeMode")}sampleOnceAtStart(){if(this.timeMode===0)switch(this.frameOverTime.mode){case 0:case 3:case 2:case 1:return!0}return!1}getStartIndex(){return this.sampleOnceAtStart()?Math.random()*(this.numTilesX*this.numTilesY):0}evaluate(e){if(!this.sampleOnceAtStart())return this.getIndex(e)}getIndex(e){const t=this.numTilesX*this.numTilesY;e=e*this.cycleCount;let s=this.frameOverTime.evaluate(e%1);return s*=this.frameOverTimeMultiplier,s*=t,s=s%t,s=Math.floor(s),s}}O([m()],Vt.prototype,"animation"),O([m()],Vt.prototype,"enabled"),O([m()],Vt.prototype,"cycleCount"),O([m(Z)],Vt.prototype,"frameOverTime"),O([m()],Vt.prototype,"frameOverTimeMultiplier"),O([m()],Vt.prototype,"numTilesX"),O([m()],Vt.prototype,"numTilesY"),O([m(Z)],Vt.prototype,"startFrame"),O([m()],Vt.prototype,"startFrameMultiplier"),O([m()],Vt.prototype,"rowMode"),O([m()],Vt.prototype,"rowIndex"),O([m()],Vt.prototype,"spriteCount"),O([m()],Vt.prototype,"timeMode");class Es{constructor(){a(this,"enabled"),a(this,"separateAxes"),a(this,"x"),a(this,"xMultiplier"),a(this,"y"),a(this,"yMultiplier"),a(this,"z"),a(this,"zMultiplier")}evaluate(e,t){return this.enabled?this.separateAxes?0:this.z.evaluate(e,t)*-1:0}}O([m()],Es.prototype,"enabled"),O([m()],Es.prototype,"separateAxes"),O([m(Z)],Es.prototype,"x"),O([m()],Es.prototype,"xMultiplier"),O([m(Z)],Es.prototype,"y"),O([m()],Es.prototype,"yMultiplier"),O([m(Z)],Es.prototype,"z"),O([m()],Es.prototype,"zMultiplier");class hs{constructor(){a(this,"enabled"),a(this,"range"),a(this,"separateAxes"),a(this,"x"),a(this,"xMultiplier"),a(this,"y"),a(this,"yMultiplier"),a(this,"z"),a(this,"zMultiplier")}evaluate(e,t){if(!this.enabled)return 0;if(!this.separateAxes){const s=W.lerp(this.range.x,this.range.y,t);return this.z.evaluate(s)*-1}return 0}}O([m()],hs.prototype,"enabled"),O([m()],hs.prototype,"range"),O([m()],hs.prototype,"separateAxes"),O([m(Z)],hs.prototype,"x"),O([m()],hs.prototype,"xMultiplier"),O([m(Z)],hs.prototype,"y"),O([m()],hs.prototype,"yMultiplier"),O([m(Z)],hs.prototype,"z"),O([m()],hs.prototype,"zMultiplier");class gt{constructor(){a(this,"enabled"),a(this,"dampen"),a(this,"drag"),a(this,"dragMultiplier"),a(this,"limit"),a(this,"limitMultiplier"),a(this,"separateAxes"),a(this,"limitX"),a(this,"limitXMultiplier"),a(this,"limitY"),a(this,"limitYMultiplier"),a(this,"limitZ"),a(this,"limitZMultiplier"),a(this,"multiplyDragByParticleSize",!1),a(this,"multiplyDragByParticleVelocity",!1),a(this,"space"),a(this,"_temp",new S),a(this,"_temp2",new S)}apply(e,t,s,o,r,l,c){if(this.enabled){const h=this.limit.evaluate(r)*this.limitMultiplier;if(t.length()>h){this._temp.copy(t).normalize().multiplyScalar(h);const d=this.dampen*.5;t.x=W.lerp(t.x,this._temp.x,d),t.y=W.lerp(t.y,this._temp.y,d),t.z=W.lerp(t.z,this._temp.z,d),s.x=W.lerp(s.x,this._temp.x,d),s.y=W.lerp(s.y,this._temp.y,d),s.z=W.lerp(s.z,this._temp.z,d)}}}}O([m()],gt.prototype,"enabled"),O([m()],gt.prototype,"dampen"),O([m(Z)],gt.prototype,"drag"),O([m()],gt.prototype,"dragMultiplier"),O([m(Z)],gt.prototype,"limit"),O([m()],gt.prototype,"limitMultiplier"),O([m()],gt.prototype,"separateAxes"),O([m(Z)],gt.prototype,"limitX"),O([m()],gt.prototype,"limitXMultiplier"),O([m(Z)],gt.prototype,"limitY"),O([m()],gt.prototype,"limitYMultiplier"),O([m(Z)],gt.prototype,"limitZ"),O([m()],gt.prototype,"limitZMultiplier"),O([m()],gt.prototype,"multiplyDragByParticleSize"),O([m()],gt.prototype,"multiplyDragByParticleVelocity"),O([m()],gt.prototype,"space");const fh=class MC{constructor(){a(this,"enabled"),a(this,"curve"),a(this,"curveMultiplier"),a(this,"mode"),a(this,"system"),a(this,"_temp",new S),a(this,"_firstUpdate",!0),a(this,"_frames",0)}clone(){var e;const t=new MC;return t.enabled=this.enabled,t.curve=(e=this.curve)==null?void 0:e.clone(),t.curveMultiplier=this.curveMultiplier,t.mode=this.mode,t}get _lastWorldPosition(){return this.system._iv_lastWorldPosition||(this.system._iv_lastWorldPosition=new S),this.system._iv_lastWorldPosition}get _velocity(){return this.system._iv_velocity||(this.system._iv_velocity=new S),this.system._iv_velocity}awake(e){this.system=e,this.reset()}reset(){this._firstUpdate=!0}update(e){this.enabled&&this.system.worldspace!==!1&&(this._firstUpdate?(this._firstUpdate=!1,this._velocity.set(0,0,0),this._lastWorldPosition.copy(this.system.worldPos)):this._lastWorldPosition&&(this._velocity.copy(this.system.worldPos).sub(this._lastWorldPosition).multiplyScalar(1/this.system.deltaTime),this._lastWorldPosition.copy(this.system.worldPos)))}applyInitial(e){if(this.enabled&&this.system.worldspace!==!1&&this.mode===0){const t=this.curve.evaluate(Math.random(),Math.random());this._temp.copy(this._velocity).multiplyScalar(t),e.x+=this._temp.x,e.y+=this._temp.y,e.z+=this._temp.z}}applyCurrent(e,t,s){if(this.enabled&&this.system&&this.system.worldspace!==!1&&this.mode===1){const o=this.curve.evaluate(t,s);this._temp.copy(this._velocity).multiplyScalar(o),e.x+=this._temp.x,e.y+=this._temp.y,e.z+=this._temp.z}}};O([m()],fh.prototype,"enabled"),O([m(Z)],fh.prototype,"curve"),O([m()],fh.prototype,"curveMultiplier"),O([m()],fh.prototype,"mode");let Sy=fh;class bi{constructor(){a(this,"enabled"),a(this,"range"),a(this,"separateAxes"),a(this,"size"),a(this,"sizeMultiplier"),a(this,"x"),a(this,"xMultiplier"),a(this,"y"),a(this,"yMultiplier"),a(this,"z"),a(this,"zMultiplier")}evaluate(e,t,s,o){const r=e.length(),l=W.remap(r,this.range.x,this.range.y,0,1),c=this.size.evaluate(l,s);return o.x*=c,o.y*=c,o.z*=c,o}}O([m()],bi.prototype,"enabled"),O([m(re)],bi.prototype,"range"),O([m()],bi.prototype,"separateAxes"),O([m(Z)],bi.prototype,"size"),O([m()],bi.prototype,"sizeMultiplier"),O([m(Z)],bi.prototype,"x"),O([m()],bi.prototype,"xMultiplier"),O([m(Z)],bi.prototype,"y"),O([m()],bi.prototype,"yMultiplier"),O([m(Z)],bi.prototype,"z"),O([m()],bi.prototype,"zMultiplier");class Pl{constructor(){a(this,"enabled"),a(this,"range"),a(this,"color")}evaluate(e,t,s){const o=e.length(),r=W.remap(o,this.range.x,this.range.y,0,1),l=this.color.evaluate(r,t);s.x*=l.r,s.y*=l.g,s.z*=l.b,"alpha"in l&&(s.w*=l.alpha)}}O([m()],Pl.prototype,"enabled"),O([m(re)],Pl.prototype,"range"),O([m(sa)],Pl.prototype,"color"),new S(1,1,1),new S(0,0,1);class Cy{constructor(e,t,s,o){a(this,"type","NeedleParticleSubEmitter"),a(this,"emitterType"),a(this,"emitterProbability"),a(this,"q_",new V),a(this,"v_",new S),a(this,"v2_",new S),a(this,"_emitterMatrix",new Hm),a(this,"_circularBuffer"),this.system=e,this.particleSystem=t,this.subSystem=s,this.subParticleSystem=o,this.subParticleSystem&&this.subParticleSystem&&(this.subParticleSystem.onlyUsedByOther=!0);const r=1e3;this._circularBuffer=new Oi(()=>new Hm,r)}clone(){throw new Error("Method not implemented.")}initialize(e){e.emissionState={burstIndex:0,burstWaveIndex:0,time:0,waitEmiting:0},this._emitterMatrix.copy(this.subSystem.matrixWorld).invert().premultiply(this.system.matrixWorld),this._emitterMatrix.setPosition(0,0,0),this.emitterType===Py.Birth&&this.run(e)}update(e,t){this.run(e)}frameUpdate(e){}toJSON(){}reset(){}run(e){if(this.subSystem.currentParticles>=this.subSystem.main.maxParticles||!this.subParticleSystem||!e.emissionState||this.emitterProbability&&Math.random()>this.emitterProbability)return;const t=this.system.deltaTime;if(this.emitterType===Py.Death){let o=e.life;if(e[Ol]!==void 0&&(o=e[Ol]),!(e.age+t*1.2>=o))return;const r=this.subSystem.main.maxParticles-this.subSystem.currentParticles;e.emissionState.waitEmiting=r}const s=new Hm;s.set(1,0,0,e.position.x,0,1,0,e.position.y,0,0,1,e.position.z,0,0,0,1),this.particleSystem.worldSpace||s.multiplyMatrices(this._emitterMatrix,s),this.subParticleSystem.emit(t,e.emissionState,s)}}var p2=Object.defineProperty,Ve=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&p2(e,t,o),o};const ir=C("debugparticles"),m2=C("noprogressive"),g2=C("debugprogressive");var Py=(n=>(n[n.Birth=0]="Birth",n[n.Collision=1]="Collision",n[n.Death=2]="Death",n[n.Trigger=3]="Trigger",n[n.Manual=4]="Manual",n))(Py||{});class ds extends I{constructor(){super(...arguments),a(this,"renderMode"),a(this,"particleMaterial"),a(this,"trailMaterial"),a(this,"particleMesh"),a(this,"maxParticleSize"),a(this,"minParticleSize"),a(this,"velocityScale"),a(this,"cameraVelocityScale"),a(this,"lengthScale")}start(){if(this.maxParticleSize!==.5&&this.minParticleSize!==0&&F()){const e=`ParticleSystem "${this.name}" has non-default min/max particle size. This may not render correctly. Please set min size to 0 and the max size to 0.5 and use the "StartSize" setting instead`;console.warn(e)}}get transparent(){var e;return((e=this.particleMaterial)==null?void 0:e.transparent)??!1}getMaterial(e=!1){let t=e===!0&&this.trailMaterial?this.trailMaterial:this.particleMaterial;if(t){if(t.type==="MeshStandardMaterial"){ir&&console.debug("ParticleSystemRenderer.getMaterial: MeshStandardMaterial detected, converting to MeshBasicMaterial. See https://github.com/Alchemist0823/three.quarks/issues/101"),"map"in t&&t.map&&(t.map.colorSpace=On,t.map.premultiplyAlpha=!1);const s=new Me;s.copy(t),e?this.trailMaterial=s:this.particleMaterial=s}t.map&&(t.map.colorSpace=On,t.map.premultiplyAlpha=!1),e&&t.side===fo&&(t=t.clone(),t.side=wd,e?this.trailMaterial=t:this.particleMaterial=t)}return t&&!m2&&t._didRequestTextureLOD===void 0&&(t._didRequestTextureLOD=0,g2&&console.log("Load material LOD",t.name),Xe.assignTextureLOD(t,0)),t}getMesh(e){let t=null;if(!t&&(this.particleMesh instanceof G&&(t=this.particleMesh.geometry),t===null)){t=new Ns(1,1);const s=t.attributes.uv;for(let o=0;o<s.count;o++)s.setX(o,1-s.getX(o))}return new G(t,this.getMaterial())}}Ve([m()],ds.prototype,"renderMode"),Ve([m(Pe)],ds.prototype,"particleMaterial"),Ve([m(Pe)],ds.prototype,"trailMaterial"),Ve([m()],ds.prototype,"maxParticleSize"),Ve([m()],ds.prototype,"minParticleSize"),Ve([m()],ds.prototype,"velocityScale"),Ve([m()],ds.prototype,"cameraVelocityScale"),Ve([m()],ds.prototype,"lengthScale");class Lp{constructor(e,t=1){a(this,"_curve"),a(this,"_factor"),a(this,"type","function"),this._curve=e,this._factor=t}startGen(e){}genValue(e,t){return this._curve.evaluate(t,Math.random())*this._factor}toJSON(){throw new Error("Method not implemented.")}clone(){throw new Error("Method not implemented.")}}class Oy{constructor(e){a(this,"type","value"),a(this,"system"),this.system=e}toJSON(){throw new Error("Method not implemented.")}clone(){throw new Error("Method not implemented.")}startGen(e){}}class f2 extends Oy{genValue(){return this.system.textureSheetAnimation.getStartIndex()}}class y2 extends Oy{constructor(){super(...arguments),a(this,"_lastPosition",new S),a(this,"_lastDistance",0)}update(){const e=ee(this.system.gameObject);this._lastDistance=this._lastPosition.distanceTo(e),this._lastPosition.copy(e)}genValue(){if(!this.system.isPlaying||!this.system.emission.enabled||this.system.currentParticles>=this.system.maxParticles)return 0;let e=this.system.emission.rateOverTime.evaluate(this.system.time/this.system.duration,Math.random());if(this.system.deltaTime>0){const o=this.system.emission.rateOverDistance.evaluate(this.system.time/this.system.duration,Math.random());let r=this._lastDistance/this.system.deltaTime*o;Number.isFinite(r)||(r=0),e+=r}const t=this.system.emission.getBurst();t>0&&(e+=t/this.system.deltaTime);const s=this.system.maxParticles-this.system.currentParticles;return W.clamp(e,0,s/this.system.deltaTime)}}class v2 extends Oy{genValue(){return this.system.isPlaying,0}}class sr{constructor(e){a(this,"system"),a(this,"type"),this.type=Object.getPrototypeOf(this).constructor.name||"ParticleSystemBaseBehaviour",e&&(this.system=e)}get context(){return this.system.context}initialize(e){}update(e,t){}frameUpdate(e){}toJSON(){throw new Error("Method not implemented.")}clone(){throw new Error("Method not implemented.")}reset(){}}class b2 extends sr{constructor(){super(...arguments),a(this,"type","NeedleTextureSheet")}update(e,t){const s=this.system.textureSheetAnimation;if(s.enabled){const o=e.age/e.life,r=s.evaluate(o);r!==void 0&&(e.uvTile=r)}}}const aS=Symbol("particleRotation");class _2 extends sr{constructor(){super(...arguments),a(this,"type","NeedleRotation")}initialize(e){e[aS]=Math.random()}update(e,t){if(e.rotation===void 0)return;const s=e.age/e.life;if(typeof e.rotation=="number"&&(this.system.rotationOverLifetime.enabled?e.rotation+=this.system.rotationOverLifetime.evaluate(s,e[aS])*t:this.system.renderer.renderMode===Zn.Billboard&&(e.rotation=Math.PI),this.system.rotationBySpeed.enabled)){const o=e.velocity.length();e.rotation+=this.system.rotationBySpeed.evaluate(s,o)*t}}}const lS=Symbol("sizeLerpFactor"),w2=new S;class x2 extends sr{constructor(){super(...arguments),a(this,"type","NeedleSize"),a(this,"_minSize",0),a(this,"_maxSize",1)}initialize(e){e[lS]=Math.random(),this._minSize=this.system.renderer.minParticleSize,this._maxSize=this.system.renderer.maxParticleSize}update(e,t){const s=e.age/e.life;let o=1;this.system.sizeOverLifetime.enabled&&(o*=this.system.sizeOverLifetime.evaluate(s,void 0,e[lS]).x);let r=1;this.system.renderer.renderMode!==Zn.Mesh&&(r=this.system.worldScale.x/this.system.cameraScale);const l=q(e.startSize).multiplyScalar(o*r);if(e.size.set(l.x,l.y,l.z),this.system.localspace){const c=pS(this.system,w2);e.size.x*=c.x,e.size.y*=c.y,e.size.z*=c.z}}}const Ol=Symbol("particleLife"),ky=Symbol("trailLifetime"),cS=Symbol("trailStartLength"),My=Symbol("trailWidthRandom");class S2 extends sr{constructor(){super(...arguments),a(this,"type","NeedleTrail")}initialize(e){e instanceof Zv&&(e[Ol]=e.life,this.system.trails.enabled&&this.system.trails.dieWithParticles===!1&&(e[ky]=this.system.trails.lifetime.evaluate(Math.random(),Math.random()),e.life+=e[ky]),e[cS]=e.length,e[My]=Math.random())}update(e){var t;if((t=this.system.trails)!=null&&t.enabled&&e instanceof Zv){const s=e,o=e.age/e[Ol],r=e.previous.values(),l=e.previous.length;for(let c=0;c<l;c++){const h=r.next().value,d=1-c/(l-1),u=e.size;if(u.x<=0&&!this.system.trails.sizeAffectsWidth){const p=20*this.system.trails.widthOverTrail.evaluate(.5,s[My]);u.x=p,u.y=p,u.z=p}h.size=this.system.trails.getWidth(u.x,o,d,s[My]),h.color.copy(e.color),this.system.trails.getColor(h.color,o,d)}if(e.age>e[Ol]){e.velocity.set(0,0,0);const c=(e.age-e[Ol])/e[ky];s.length=W.lerp(e[cS],0,c)}}}}const jp=Symbol("startVelocity"),hS=Symbol("gravityModifier"),Ry=Symbol("gravitySpeed"),Dp=Symbol("velocity lerp factor"),Ty=new S;class C2 extends sr{constructor(){super(...arguments),a(this,"type","NeedleVelocity"),a(this,"_gravityDirection",new S)}initialize(e){var t,s;const o=this.system.main.simulationSpeed;e.startSpeed=this.system.main.startSpeed.evaluate(Math.random(),Math.random());const r=this.system.shape.getDirection(e,e.position);e.velocity.x=r.x*e.startSpeed,e.velocity.y=r.y*e.startSpeed,e.velocity.z=r.z*e.startSpeed,(t=this.system.inheritVelocity)!=null&&t.enabled&&this.system.inheritVelocity.applyInitial(e.velocity),e[jp]?e[jp].copy(e.velocity):e[jp]=e.velocity.clone();const l=this.system.main.gravityModifier.evaluate(Math.random(),Math.random());e[hS]=l*o,e[Ry]=l*o*.5,e[Dp]=Math.random(),(s=this.system.velocityOverLifetime)==null||s.init(e),this._gravityDirection.set(0,-1,0),this.system.main.simulationSpace===gh.Local&&this._gravityDirection.applyQuaternion(this.system.worldQuaternionInverted).normalize()}update(e,t){var s;const o=e[jp],r=e[hS];if(r!==0){const g=r*e[Ry];Ty.copy(this._gravityDirection).multiplyScalar(g),e[Ry]+=t*.05,o.add(Ty)}e.velocity.copy(o);const l=e.age/e.life;(s=this.system.inheritVelocity)!=null&&s.enabled&&this.system.inheritVelocity.applyCurrent(e.velocity,l,e[Dp]);const c=this.system.noise;c.enabled&&c.apply(0,e.position,e.velocity,t,e.age,e.life);const h=this.system.sizeBySpeed;h!=null&&h.enabled&&(e.size=h.evaluate(e.velocity,l,e[Dp],e.size));const d=this.system.colorBySpeed;d!=null&&d.enabled&&d.evaluate(e.velocity,e[Dp],e.color);const u=this.system.velocityOverLifetime;u.enabled&&u.apply(e,0,e.position,e.velocity,t,e.age,e.life);const p=this.system.limitVelocityOverLifetime;if(p.enabled&&p.apply(e.position,o,e.velocity,e.size,l,t,1),this.system.worldspace){const g=this.system.worldScale;e.velocity.x*=g.x,e.velocity.y*=g.y,e.velocity.z*=g.z}}}const dS=Symbol("colorLerpFactor"),uS=new he(1,1,1,1),oa=new he(1,1,1,1);class P2 extends sr{constructor(){super(...arguments),a(this,"type","NeedleColor")}initialize(e){}_init(e){const t=this.system.renderer.particleMaterial;oa.copy(this.system.main.startColor.evaluate(Math.random())),t!=null&&t.color&&(uS.copy(t.color),oa.multiply(uS)),oa.convertLinearToSRGB(),e.startColor.set(oa.r,oa.g,oa.b,oa.alpha),e.color.copy(e.startColor),e[dS]=Math.random()}update(e,t){if(e.age===0&&this._init(e),this.system.colorOverLifetime.enabled){const s=e.age/e.life,o=this.system.colorOverLifetime.color.evaluate(s,e[dS]);e.color.set(o.r,o.g,o.b,"alpha"in o?o.alpha:1).multiply(e.startColor)}else e.color.copy(e.startColor)}}class O2{constructor(e){a(this,"system"),a(this,"emission"),a(this,"autoDestroy"),a(this,"startLength"),a(this,"emissionBursts"),a(this,"onlyUsedByOther"),a(this,"behaviors",[]),a(this,"rendererEmitterSettings",{startLength:new CO(220),followLocalOrigin:!1}),a(this,"flatWhiteTexture"),a(this,"clonedTexture",{original:void 0,clone:void 0}),this.system=e,this.emission=new y2(this.system)}get anim(){return this.system.textureSheetAnimation}get prewarm(){return!1}get material(){return this.system.renderer.getMaterial(this.system.trails.enabled)}get layers(){return this.system.gameObject.layers}update(){this.emission.update()}get looping(){return this.system.main.loop}get duration(){return this.system.duration}get shape(){return this.system.shape}get startLife(){return new Lp(this.system.main.startLifetime)}get startSpeed(){return new Lp(this.system.main.startSpeed)}get startRotation(){return new Lp(this.system.main.startRotation)}get startSize(){return new Lp(this.system.main.startSize)}get startColor(){return new xO(new SO(1,1,1,1))}get emissionOverTime(){return this.emission}get emissionOverDistance(){return new v2(this.system)}get instancingGeometry(){return this.system.renderer.getMesh(this.system.renderer.renderMode).geometry}get renderMode(){if(this.system.trails.enabled===!0)return Tn.Trail;switch(this.system.renderer.renderMode){case Zn.Billboard:return Tn.BillBoard;case Zn.Stretch:return Tn.StretchedBillBoard;case Zn.HorizontalBillboard:return Tn.HorizontalBillBoard;case Zn.VerticalBillboard:return Tn.VerticalBillBoard;case Zn.Mesh:return Tn.Mesh}return Tn.BillBoard}get speedFactor(){var e;let t=this.system.main.simulationSpeed;return((e=this.system.renderer)==null?void 0:e.renderMode)===Zn.Stretch&&(t*=this.system.renderer.velocityScale??1),t}get texture(){const e=this.material;if(e&&e.map){const t=e.map;if(this.clonedTexture.original!==t||!this.clonedTexture.clone){const s=t.clone();s.premultiplyAlpha=!1,s.colorSpace=On,this.clonedTexture.original=t,this.clonedTexture.clone=s}return this.clonedTexture.clone}return this.flatWhiteTexture||(this.flatWhiteTexture=Sf(new he(1,1,1,1),1)),this.flatWhiteTexture}get startTileIndex(){return new f2(this.system)}get uTileCount(){var e;return this.anim.enabled?(e=this.anim)==null?void 0:e.numTilesX:void 0}get vTileCount(){var e;return this.anim.enabled?(e=this.anim)==null?void 0:e.numTilesY:void 0}get renderOrder(){return 1}get blending(){var e;return((e=this.system.renderer.particleMaterial)==null?void 0:e.blending)??jP}get transparent(){return this.system.renderer.transparent}get worldSpace(){return this.system.main.simulationSpace===gh.World}}class k2{constructor(){a(this,"burstParticleIndex",0),a(this,"burstParticleCount",0),a(this,"isBursting",!1),a(this,"travelDistance",0),a(this,"previousWorldPos"),a(this,"burstIndex",0),a(this,"burstWaveIndex",0),a(this,"time",0),a(this,"waitEmiting",0)}}const $t=class Cm extends I{constructor(){super(...arguments),a(this,"_state"),a(this,"colorOverLifetime"),a(this,"main"),a(this,"emission"),a(this,"sizeOverLifetime"),a(this,"shape"),a(this,"noise"),a(this,"trails"),a(this,"velocityOverLifetime"),a(this,"limitVelocityOverLifetime"),a(this,"inheritVelocity"),a(this,"colorBySpeed"),a(this,"textureSheetAnimation"),a(this,"rotationOverLifetime"),a(this,"rotationBySpeed"),a(this,"sizeBySpeed"),a(this,"_cameraScale",1),a(this,"__worldQuaternion",new V),a(this,"_worldQuaternionInverted",new V),a(this,"_worldScale",new S),a(this,"_worldPositionFrame",-1),a(this,"_worldPos",new S),a(this,"_renderer"),a(this,"_batchSystem"),a(this,"_particleSystem"),a(this,"_interface"),a(this,"_container"),a(this,"_time",0),a(this,"_isPlaying",!0),a(this,"_isUsedAsSubsystem",!1),a(this,"_didPreWarm",!1),a(this,"_bursts"),a(this,"_subEmitterSystems"),a(this,"_lastBatchesCount",-1)}play(e=!1){var t;e&&P.foreachComponent(this.gameObject,s=>{s instanceof Cm&&s!==this&&s.play(!1)},!0),this._isPlaying=!0,this._particleSystem&&(this._particleSystem.emissionState.time=0,this._particleSystem.emitEnded=!1),(t=this.emission)==null||t.reset()}pause(e=!0){e&&P.foreachComponent(this.gameObject,t=>{t instanceof Cm&&t!==this&&t.pause(!1)},!0),this._isPlaying=!1}stop(e=!0,t=!1){e&&P.foreachComponent(this.gameObject,s=>{s instanceof Cm&&s!==this&&s.stop(!1,t)},!0),this._isPlaying=!1,this._time=0,t&&this.reset()}reset(){var e;this._time=0,this._particleSystem&&(this._particleSystem.particleNum=0,this._particleSystem.emissionState.time=0,this._particleSystem.emitEnded=!1,(e=this.emission)==null||e.reset())}emit(e){if(this._particleSystem){this.onUpdate(),e=Math.min(e,this.maxParticles-this.currentParticles),this._state||(this._state=new k2),this._state.waitEmiting=e,this._state.time=0;const t=this._particleSystem.emitEnded;this._particleSystem.emitEnded=!1,this._particleSystem.emit(this.deltaTime,this._state,this._particleSystem.emitter.matrixWorld),this._particleSystem.emitEnded=t}}get playOnAwake(){return this.main.playOnAwake}set playOnAwake(e){this.main.playOnAwake=e}get renderer(){return this._renderer}get isPlaying(){return this._isPlaying}get currentParticles(){var e;return((e=this._particleSystem)==null?void 0:e.particleNum)??0}get maxParticles(){return this.main.maxParticles}get time(){return this._time}get duration(){return this.main.duration}get deltaTime(){return this.context.time.deltaTime*this.main.simulationSpeed}get scale(){return this.gameObject.scale.x}get cameraScale(){return this._cameraScale}get container(){return this._container}get worldspace(){return this.main.simulationSpace===gh.World}get localspace(){return this.main.simulationSpace===gh.Local}get worldQuaternion(){return this.__worldQuaternion}get worldQuaternionInverted(){return this._worldQuaternionInverted}get worldScale(){return this._worldScale}get worldPos(){return this._worldPositionFrame!==this.context.time.frame&&(this._worldPositionFrame=this.context.time.frame,ee(this.gameObject,this._worldPos)),this._worldPos}get matrixWorld(){return this._container.matrixWorld}get isSubsystem(){return this._isUsedAsSubsystem}addBehaviour(e){return this._particleSystem?(e instanceof sr&&(e.system=this),ir&&console.debug("Add custom ParticleSystem Behaviour",e),this._particleSystem.addBehavior(e),!0):!1}removeBehaviour(e){if(!this._particleSystem)return!1;const t=this._particleSystem.behaviors,s=t.indexOf(e);return s!==-1&&((F()||ir)&&console.debug("Remove custom ParticleSystem Behaviour",s,e),t.splice(s,1)),!0}removeAllBehaviours(){return this._particleSystem?(this._particleSystem.behaviors.length=0,!0):!1}get behaviours(){return this._particleSystem?this._particleSystem.behaviors:null}get particleSystem(){return this._particleSystem??null}set bursts(e){for(let t=0;t<e.length;t++){const s=e[t];if(!(s instanceof Ap)){const o=new Ap;Na(o,s),e[t]=o}}this._bursts=e}set subEmitterSystems(e){for(let t=0;t<e.length;t++){const s=e[t];if(!(s instanceof Bp)){const o=new Bp;Na(o,s),e[t]=o}}ir&&e.length>0&&console.log("SubEmitters: ",e,this),this._subEmitterSystems=e}onAfterDeserialize(e){if(this._subEmitterSystems&&Array.isArray(this._subEmitterSystems))for(const t of this._subEmitterSystems)t._deserialize(this.context,this.gameObject)}awake(){if(this._worldPositionFrame=-1,this._renderer=this.gameObject.getComponent(ds),!this.main)throw new Error("Not Supported: ParticleSystem needs a serialized MainModule. Creating new particle systems at runtime is currently not supported.");this._container=new E,this._container.matrixAutoUpdate=!1,this.context.scene.add(this._container),this._batchSystem=new _O,this._batchSystem.name=this.gameObject.name,this._container.add(this._batchSystem),this._interface=new O2(this),this._particleSystem=new wO(this._interface),this._particleSystem.addBehavior(new x2(this)),this._particleSystem.addBehavior(new P2(this)),this._particleSystem.addBehavior(new b2(this)),this._particleSystem.addBehavior(new _2(this)),this._particleSystem.addBehavior(new C2(this)),this._particleSystem.addBehavior(new S2(this)),this._batchSystem.addSystem(this._particleSystem);const e=this._particleSystem.emitter;this.context.scene.add(e),this.inheritVelocity.system&&this.inheritVelocity.system!==this&&(this.inheritVelocity=this.inheritVelocity.clone()),this.inheritVelocity.awake(this),ir&&(console.log(this),this.gameObject.add(new Ci(1)))}start(){this.addSubParticleSystems(),this.updateLayers(),this.renderer.particleMesh instanceof G&&this._interface.renderMode==Tn.Mesh&&Xe.assignMeshLOD(this.renderer.particleMesh,0).then(e=>{e&&this.particleSystem&&this._interface.renderMode==Tn.Mesh&&(this.particleSystem.instancingGeometry=e)})}onDestroy(){var e,t,s,o;(e=this._container)==null||e.removeFromParent(),(t=this._batchSystem)==null||t.removeFromParent(),(s=this._particleSystem)==null||s.emitter.removeFromParent(),(o=this._particleSystem)==null||o.dispose()}onEnable(){this.main&&(this.inheritVelocity&&(this.inheritVelocity.system=this),this._batchSystem&&(this._batchSystem.visible=!0),this.playOnAwake&&this.play(),this._isPlaying=this.playOnAwake)}onDisable(){this._batchSystem&&(this._batchSystem.visible=!1)}onBeforeRender(){var e;this.main&&(this._didPreWarm===!1&&((e=this.main)==null?void 0:e.prewarm)===!0&&(this._didPreWarm=!0,this.preWarm()),this.onUpdate(),this.onSimulate(this.deltaTime))}preWarm(){var e;if(!((e=this.emission)!=null&&e.enabled)||this.emission.rateOverTime.getMax()<=0)return;const t=1/60,s=this.main.duration,o=this.main.startLifetime.getMax(),r=Math.min(Math.max(s,o)/Math.max(.01,this.main.simulationSpeed),1e3),l=Math.ceil(r/t),c=Date.now();ir&&console.log(`Particles ${this.name} - Prewarm for ${l} frames (${r} sec). Duration: ${s}, Lifetime: ${o}`);for(let h=0;h<l&&!(this.currentParticles>=this.maxParticles);h++){const d=Date.now()-c;if(d>2e3){console.warn(`Particles ${this.name} - Prewarm took too long. Aborting: ${d}`);break}this.onUpdate(),this.onSimulate(t)}}onSimulate(e){if(this._batchSystem){let t=this.context.time.frameCount%60===0;this._lastBatchesCount!==this._batchSystem.batches.length&&(this._lastBatchesCount=this._batchSystem.batches.length,t=!0),t&&this.updateLayers(),this._batchSystem.update(e)}this._time+=e,this._time>this.duration&&(this._time=0)}updateLayers(){if(this._batchSystem)for(let e=0;e<this._batchSystem.batches.length;e++){const t=this._batchSystem.batches[e];t.layers.disableAll();const s=this.layer;t.layers.mask=1<<s}}onUpdate(){var e,t;if(this._bursts&&(this.emission.bursts=this._bursts,delete this._bursts),!this._isPlaying)return;const s=this.context.mainCamera;if(s){const l=Ge(s);this._cameraScale=l.x}const o=!this.worldspace,r=this.gameObject;if(Se(r,this.__worldQuaternion),this._worldQuaternionInverted.copy(this.__worldQuaternion).invert(),Ge(this.gameObject,this._worldScale),o&&this._container&&(e=this.gameObject)!=null&&e.parent){const l=pS(this,Ty);this._container.matrix.makeScale(l.x,l.y,l.z),this._container.matrix.makeRotationFromQuaternion(this.__worldQuaternion),this._container.matrix.setPosition(this.worldPos),this._container.matrix.scale(this.gameObject.scale)}this.emission.system=this,this._interface.update(),this.shape.onUpdate(this,this.context,this.main.simulationSpace,this.gameObject),this.noise.update(this.context),(t=this.inheritVelocity)==null||t.update(this.context),this.velocityOverLifetime.update(this)}addSubParticleSystems(){var e;if(this._subEmitterSystems&&this._particleSystem)for(const t of this._subEmitterSystems){t.particleSystem&&(t.particleSystem.__internalAwake?t.particleSystem.__internalAwake():F()&&console.warn("SubParticleSystem serialization issue(?)",t.particleSystem,t));const s=(e=t.particleSystem)==null?void 0:e._particleSystem;if(s){t.particleSystem._isUsedAsSubsystem=!0;const o=new Cy(this,this._particleSystem,t.particleSystem,s);o.emitterType=t.type,o.emitterProbability=t.emitProbability,this._particleSystem.addBehavior(o)}else ir&&console.warn("Could not add SubParticleSystem",t,this)}}};Ve([m(Ip)],$t.prototype,"colorOverLifetime"),Ve([m(Wt)],$t.prototype,"main"),Ve([m(eo)],$t.prototype,"emission"),Ve([m(na)],$t.prototype,"sizeOverLifetime"),Ve([m(xy)],$t.prototype,"shape"),Ve([m(Ce)],$t.prototype,"noise"),Ve([m(We)],$t.prototype,"trails"),Ve([m(qe)],$t.prototype,"velocityOverLifetime"),Ve([m(gt)],$t.prototype,"limitVelocityOverLifetime"),Ve([m(Sy)],$t.prototype,"inheritVelocity"),Ve([m(Pl)],$t.prototype,"colorBySpeed"),Ve([m(Vt)],$t.prototype,"textureSheetAnimation"),Ve([m(Es)],$t.prototype,"rotationOverLifetime"),Ve([m(hs)],$t.prototype,"rotationBySpeed"),Ve([m(bi)],$t.prototype,"sizeBySpeed");let yh=$t;class Bp{constructor(){a(this,"particleSystem"),a(this,"emitProbability",1),a(this,"properties"),a(this,"type")}_deserialize(e,t){const s=this.particleSystem;if(s instanceof yh)return;let o="";s&&typeof s.guid=="string"&&(o=s.guid,this.particleSystem=P.findByGuid(o,t)),ir&&!(this.particleSystem instanceof yh)&&console.warn("Could not find particle system for sub emitter",o,t,this)}}function pS(n,e){if(e.set(1,1,1),n.gameObject.parent&&n.localspace)switch(n.main.scalingMode){case wy.Local:e=Ge(n.gameObject.parent,e),e.x=1/e.x,e.y=1/e.y,e.z=1/e.z;break;default:if(!n.unsupported_scaling_mode){n.unsupported_scaling_mode=!0;const t="ParticleSystem scale mode "+wy[n.main.scalingMode]+" is not supported";F()&&be(t),console.warn(t,n.name,n)}e=Ge(n.gameObject,e);break}return e}class Nl extends I{constructor(){super(...arguments),a(this,"_didAssignPlayerColor",!1),a(this,"tryAssignColor",()=>{const e=P.getComponentInParent(this.gameObject,Ms);if(e&&e.owner)return this._didAssignPlayerColor=!0,this.assignUserColor(e.owner),!0;const t=P.getComponentInParent(this.gameObject,hi);return t!=null&&t.connectionId?(this._didAssignPlayerColor=!0,this.assignUserColor(t.connectionId),!0):!1})}onEnable(){this.context.connection.beginListen(ie.JoinedRoom,this.tryAssignColor),this._didAssignPlayerColor||this.startCoroutine(this.waitForConnection())}onDisable(){this.context.connection.stopListen(ie.JoinedRoom,this.tryAssignColor)}*waitForConnection(){for(;!this.destroyed&&this.activeAndEnabled&&(yield wf(.2),!this.tryAssignColor()););}assignUserColor(e){const t=Nl.hashCode(e),s=Nl.colorFromHashCode(t);if(this.gameObject.type==="Mesh"){const o=this.gameObject;this.assignColor(s,e,o)}else if(this.gameObject.children)for(const o of this.gameObject.children){const r=o;r.material&&r.material.color&&this.assignColor(s,e,r)}}assignColor(e,t,s){let o=s.material;o&&(o._playerMaterial!==t&&(o=o.clone(),o._playerMaterial=t,s.material=o),o.color=e)}static hashCode(e){var t=0,s,o;if(e.length===0)return t;for(s=0;s<e.length;s++)o=e.charCodeAt(s),t=(t<<5)-t+o,t|=0;return t}static colorFromHashCode(e){const t=(e&16711680)>>16,s=(e&65280)>>8,o=e&255;return new oe(t/255,s/255,o/255)}}const vh=C("debugpost");let Ey=null;function M2(n){Ey=n}function mS(n){let e=n.gameObject;for(;e;){for(const t of hu(e))if(t.isPostProcessingManager===!0)return t;e=e.parent}return null}function R2(n){let e=mS(n);if(!e)if(Ey){vh&&console.warn("Adding postprocessing manager to the scene.");const t=n.scene;e=Ei(t,Ey)}else F()&&console.warn("No post processing manager found");return e}const ft={AT_START:-1e4,NormalPass:0,DepthDownsamplingPass:10,SSAO:20,SMAA:30,TiltShift:40,DepthOfField:50,ChromaticAberration:60,Bloom:70,Vignette:80,Pixelation:90,ToneMapping:100,HueSaturation:110,BrightnessContrast:120,Sharpening:130,AT_END:1e4};let ot=null;function T2(n){vh==="verbose"&&console.debug("Before ordering effects",[...n]),ot||(ot=new Map,ot.set(A.POSTPROCESSING.MODULE.NormalPass,ft.NormalPass),ot.set(A.POSTPROCESSING.MODULE.DepthDownsamplingPass,ft.DepthDownsamplingPass),ot.set(A.POSTPROCESSING.MODULE.SMAAEffect,ft.SMAA),ot.set(A.POSTPROCESSING.MODULE.SSAOEffect,ft.SSAO),ot.set(A.POSTPROCESSING_AO.MODULE.N8AOPostPass,ft.SSAO),ot.set(A.POSTPROCESSING_AO.MODULE.N8AOPass,ft.SSAO),ot.set(A.POSTPROCESSING.MODULE.TiltShiftEffect,ft.TiltShift),ot.set(A.POSTPROCESSING.MODULE.DepthOfFieldEffect,ft.DepthOfField),ot.set(A.POSTPROCESSING.MODULE.ChromaticAberrationEffect,ft.ChromaticAberration),ot.set(A.POSTPROCESSING.MODULE.BloomEffect,ft.Bloom),ot.set(A.POSTPROCESSING.MODULE.SelectiveBloomEffect,ft.Bloom),ot.set(A.POSTPROCESSING.MODULE.VignetteEffect,ft.Vignette),ot.set(A.POSTPROCESSING.MODULE.PixelationEffect,ft.Pixelation),ot.set(A.POSTPROCESSING.MODULE.ToneMappingEffect,ft.ToneMapping),ot.set(A.POSTPROCESSING.MODULE.HueSaturationEffect,ft.HueSaturation),ot.set(A.POSTPROCESSING.MODULE.BrightnessContrastEffect,ft.BrightnessContrast)),n.sort((e,t)=>{const s=typeof e.priority=="number"?e.priority:ot.get(e.effect.constructor)??Number.NEGATIVE_INFINITY,o=typeof t.priority=="number"?t.priority:ot.get(t.effect.constructor)??Number.NEGATIVE_INFINITY;return s===Number.NEGATIVE_INFINITY?(vh&&console.warn("Unknown effect found: ",e.constructor.name,e),1):o===Number.NEGATIVE_INFINITY?(vh&&console.warn("Unknown effect found: ",t.constructor.name,t),-1):s-o}),vh==="verbose"&&console.debug("After ordering effects",[...n])}var E2=Object.defineProperty,A2=Object.getOwnPropertyDescriptor,gS=(n,e,t,s)=>{for(var o=A2(e,t),r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&E2(e,t,o),o};const I2=C("debugpost");class N{constructor(e){a(this,"isVolumeParameter",!0),a(this,"_isInitialized",!1),a(this,"_active",!0),a(this,"_value"),a(this,"_valueRaw"),a(this,"_defaultValue"),a(this,"valueProcessor"),a(this,"onValueChanged"),e!==void 0&&this.initialize(e)}get isInitialized(){return this._isInitialized}initialize(e){e!==void 0&&(this._value=e,this._defaultValue=e,this._valueRaw=e,this._isInitialized=!0)}get overrideState(){return this._active}set overrideState(e){if(this._active===e)return;this._active=e;const t=e?this._valueRaw:this._defaultValue;this.processValue(t,!0)}get value(){return this._valueRaw}set value(e){this.isInitialized||this.initialize(e),this.processValue(e,!1)}set defaultValue(e){this._defaultValue=e}__init(){this.processValue(this._valueRaw,!0)}processValue(e,t){if(e==null||!t&&this.testIfValueChanged(e)===!1)return;const s=this._value;I2&&typeof s=="number"&&typeof e=="number"&&(s?.toFixed(4),e?.toFixed(4)),!this._active&&this._defaultValue!==void 0?(this._value=this._defaultValue,e=this._defaultValue,this._valueRaw=e):(this._valueRaw=e,this._active&&this.valueProcessor&&(e=this.valueProcessor(e)),this._value=e),this.onValueChanged&&this.onValueChanged(e,s,this)}testIfValueChanged(e){return this._valueRaw!==e}}gS([m()],N.prototype,"overrideState"),gS([m()],N.prototype,"value");class L2 extends es{constructor(){super([N])}onSerialize(e,t){}onDeserialize(e,t){const s=t.target,o=t.path;let r;if(s&&o&&(r=s[o]),(typeof r!="object"||typeof r=="object"&&r.isVolumeParameter!==!0)&&(r=new N),typeof e=="object"&&"value"in e){const l=e.value;r.initialize(l),r.overrideState=e.overrideState}else r.value=e;return r}}new L2;var j2=Object.defineProperty,D2=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&j2(e,t,o),o};const Ay=C("debugpost");class rt extends I{constructor(e=void 0){if(super(),a(this,"order"),a(this,"active",!0),a(this,"_manager",null),a(this,"_result"),a(this,"_postprocessingContext",null),e)for(const t of Object.keys(e)){const s=e[t],o=this[t];o instanceof N?o.initialize(s):o!==void 0&&(this[t]=s)}}get isPostProcessingEffect(){return!0}onEnable(){super.onEnable(),Ay&&console.warn("Enable",this.constructor.name+(this.__internalDidAwakeAndStart?"":" (awake)")),this.__internalDidAwakeAndStart&&(this.active=!0),this.onEffectEnabled()}onDisable(){var e;super.onDisable(),Ay&&console.warn("Disable",this.constructor.name),(e=this._manager)==null||e.removeEffect(this),this.active=!1}onEffectEnabled(e){e&&e.isPostProcessingManager===!0?this._manager=e:this._manager||(this._manager=R2(this)),this._manager.addEffect(this),this._manager.dirty=!0}init(){}get postprocessingContext(){return this._postprocessingContext}apply(e){var t;return this._postprocessingContext=e,this._result||(this.initParameters(),this._result=(t=this.onCreateEffect)==null?void 0:t.call(this)),this._result&&this.initParameters(),this._result}unapply(){}dispose(){Ay&&console.warn("DISPOSE",this),this._result&&(Array.isArray(this._result)?this._result.forEach(e=>e.dispose()):this._result.dispose()),this._result=void 0}initParameters(){const e=Object.keys(this);for(const t of e){const s=this[t];s instanceof N&&s.__init()}}onEditorModification(e){const t=e.propertyName;if(this[t]instanceof N){const s=e.value;return this[t].value=s,!0}}}D2([m()],rt.prototype,"active");var B2=Object.defineProperty,F2=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&B2(e,t,o),o};const U2=C("debugpost"),Iy={};function us(n,e){Iy[n]=e}function z2(n){return n.__type in Iy?Iy[n.__type]:(U2&&n.__type&&console.warn("Unknown postprocessing type",n.__type,n),rt)}class Fp{constructor(){a(this,"components",[])}__init(e){var t;(t=this.components)==null||t.forEach(s=>{s.gameObject===void 0&&e.gameObject.addComponent(s),s.init()})}addEffect(e){this.components.push(e)}removeEffect(e){const t=this.components.indexOf(e);t>=0&&this.components.splice(t,1)}}F2([Dr([n=>z2(n),rt])],Fp.prototype,"components");var N2=Object.defineProperty,W2=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&N2(e,t,o),o};class bh extends rt{constructor(){super(...arguments),a(this,"preset",new N(2))}get typeName(){return"Antialiasing"}onCreateEffect(){const e=new A.POSTPROCESSING.MODULE.SMAAEffect({preset:A.POSTPROCESSING.MODULE.SMAAPreset.HIGH,edgeDetectionMode:A.POSTPROCESSING.MODULE.EdgeDetectionMode.LUMA});return this.preset.onValueChanged=t=>{e.applyPreset(t)},e}}W2([m(N)],bh.prototype,"preset"),us("Antialiasing",bh);var V2=Object.defineProperty,Ly=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&V2(e,t,o),o},Up;const zp=(Up=class extends rt{constructor(){super(...arguments),a(this,"threshold",new N(.9)),a(this,"intensity",new N(1)),a(this,"scatter",new N(.7)),a(this,"selectiveBloom")}get typeName(){return"Bloom"}init(){this.threshold.valueProcessor=n=>n,this.intensity.valueProcessor=n=>n,this.scatter.valueProcessor=n=>n}onCreateEffect(){let n;if(this.selectiveBloom==null&&(this.selectiveBloom=Up.useSelectiveBloom),this.selectiveBloom){const e=n=new A.POSTPROCESSING.MODULE.SelectiveBloomEffect(this.context.scene,this.context.mainCamera,{blendFunction:A.POSTPROCESSING.MODULE.BlendFunction.ADD,mipmapBlur:!0,luminanceThreshold:this.threshold.value,luminanceSmoothing:this.scatter.value,radius:.85,intensity:this.intensity.value});e.inverted=!0}else n=new A.POSTPROCESSING.MODULE.BloomEffect({blendFunction:A.POSTPROCESSING.MODULE.BlendFunction.ADD,mipmapBlur:!0,luminanceThreshold:this.threshold.value,luminanceSmoothing:this.scatter.value,radius:.85,intensity:this.intensity.value});return this.intensity.onValueChanged=e=>{n.intensity=e},this.threshold.onValueChanged=e=>{n.luminanceMaterial.threshold=Math.pow(e,2.2)},this.scatter.onValueChanged=e=>{n.luminancePass.enabled=!0,n.luminanceMaterial.smoothing=e,n.mipmapBlurPass&&(n.mipmapBlurPass.radius=Cn.lerp(.1,.9,e))},n}},a(Up,"useSelectiveBloom",!1),Up);Ly([m(N)],zp.prototype,"threshold"),Ly([m(N)],zp.prototype,"intensity"),Ly([m(N)],zp.prototype,"scatter");let Np=zp;us("Bloom",Np);var $2=Object.defineProperty,H2=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&$2(e,t,o),o};class _h extends rt{constructor(){super(...arguments),a(this,"intensity",new N(0))}get typeName(){return"ChromaticAberration"}onCreateEffect(){const e=new A.POSTPROCESSING.MODULE.ChromaticAberrationEffect;return e.offset=new re(0,0),e.radialModulation=!0,e.modulationOffset=.15,this.intensity.valueProcessor=t=>t*.02,this.intensity.onValueChanged=t=>{e.offset.x=-t,e.offset.y=t},e}}H2([m(N)],_h.prototype,"intensity"),us("ChromaticAberration",_h);var wh=(n=>(n[n.None=0]="None",n[n.Neutral=1]="Neutral",n[n.ACES=2]="ACES",n[n.AgX=3]="AgX",n[n.KhronosNeutral=4]="KhronosNeutral",n))(wh||{});const fS=new Map;function jy(n){switch(n){case 0:return Um;case 1:return Fm;case 2:return vd;case 3:return yd;case 4:return Pa;default:return fS.has(n)||(fS.set(n,!0),console.warn("[Postprocessing] Unknown tone mapping mode",n)),Pa}}function G2(n){switch(n){case Um:return 0;case vd:return 2;case yd:return 3;case Pa:return 1;case Fm:return 1;default:return 0}}function Wp(n){switch(n){case Um:return A.POSTPROCESSING.MODULE.ToneMappingMode.LINEAR;case vd:return A.POSTPROCESSING.MODULE.ToneMappingMode.ACES_FILMIC;case yd:return A.POSTPROCESSING.MODULE.ToneMappingMode.AGX;case Pa:return A.POSTPROCESSING.MODULE.ToneMappingMode.NEUTRAL;case Fm:return A.POSTPROCESSING.MODULE.ToneMappingMode.REINHARD;default:return A.POSTPROCESSING.MODULE.ToneMappingMode.LINEAR}}var q2=Object.defineProperty,yS=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&q2(e,t,o),o};const Dy=C("debugpost");class nr extends rt{constructor(){super(...arguments),a(this,"mode",new N(void 0)),a(this,"exposure",new N(1)),a(this,"_tonemappingEffect",null)}get typeName(){return"ToneMapping"}setMode(e){const t=wh[e];return t===void 0?(console.error("[PostProcessing] Invalid ToneMapping mode",e),this):(this.mode.value=t,this)}get isToneMapping(){return!0}onEffectEnabled(){const e=mS(this);e&&super.onEffectEnabled(e)}onCreateEffect(){var e;if(this.mode.isInitialized==!1){const o=G2(this.context.renderer.toneMapping);Dy&&console.log("[PostProcessing] Initializing ToneMapping mode to renderer.toneMapping",this.context.renderer.toneMapping+" \u2192 "+o),this.mode.initialize(o)}(e=this._tonemappingEffect)==null||e.dispose();const t=jy(this.mode.value),s=this._tonemappingEffect=new A.POSTPROCESSING.MODULE.ToneMappingEffect({mode:Wp(t)});return this.mode.onValueChanged=o=>{if(typeof o=="string")o=Gw(o),s.mode=Wp(o);else{const r=jy(o);s.mode=Wp(r)}s.name="ToneMapping ("+wh[o]+")",Dy&&console.log("[PostProcessing] ToneMapping mode changed to",wh[o],t,s.mode)},Dy&&console.log("[PostProcessing] Use ToneMapping",wh[this.mode.value],t,s.mode,"renderer.tonemapping: "+this.context.renderer.toneMapping),s}onBeforeRender(){var e;if(this._tonemappingEffect&&(e=this.postprocessingContext)!=null&&e.handler.getEffectIsActive(this._tonemappingEffect)&&(this.mode.overrideState&&(this.context.renderer.toneMapping=jy(this.mode.value)),this.exposure.overrideState&&this.exposure.value!==void 0)){const t=Math.max(.01,this.exposure.value);this.context.renderer.toneMappingExposure=t}}}yS([m(N)],nr.prototype,"mode"),yS([m(N)],nr.prototype,"exposure"),us("Tonemapping",nr);var X2=Object.defineProperty,Vp=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&X2(e,t,o),o};class or extends rt{constructor(){super(...arguments),a(this,"remap",!0),a(this,"postExposure",new N(1)),a(this,"contrast",new N(0)),a(this,"hueShift",new N(0)),a(this,"saturation",new N(0))}get typeName(){return"ColorAdjustments"}init(){this.postExposure.valueProcessor=e=>(this.remap&&(e=Math.pow(2,e)),e),this.contrast.valueProcessor=e=>{if(!this.remap)return e;let t=1;return e>0?t=200:e<0&&(t=100),e/t},this.contrast.defaultValue=0,this.hueShift.valueProcessor=e=>this.remap?Math.PI*e/180:e,this.hueShift.defaultValue=0,this.saturation.valueProcessor=e=>this.remap?e<0?e/100:e/(100*Math.PI):e,this.saturation.defaultValue=0}onCreateEffect(){var e,t;const s=[];let o=(e=this.postprocessingContext)==null?void 0:e.components.find(c=>c instanceof nr);o||(o=new nr,(t=this.postprocessingContext)==null||t.components.push(o)),this.postExposure.onValueChanged=c=>{this.postExposure.overrideState&&o?o.exposure.value=c:console.warn("[PostProcessing] PostExposure is set to override but no ToneMappingEffect found in the postprocessing stack. Please add a ToneMappingEffect to your postprocessing stack to use PostExposure.")};const r=new A.POSTPROCESSING.MODULE.BrightnessContrastEffect;this.contrast.onValueChanged=c=>r.contrast=c;const l=new A.POSTPROCESSING.MODULE.HueSaturationEffect;return this.hueShift.onValueChanged=c=>l.hue=c,this.saturation.onValueChanged=c=>l.saturation=c,s.push(r),s.push(l),s}}Vp([m(N)],or.prototype,"postExposure"),Vp([m(N)],or.prototype,"contrast"),Vp([m(N)],or.prototype,"hueShift"),Vp([m(N)],or.prototype,"saturation"),us("ColorAdjustments",or);var Q2=Object.defineProperty,ra=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&Q2(e,t,o),o};const Y2=C("debugpost");class As extends rt{constructor(){super(...arguments),a(this,"mode"),a(this,"focusDistance",new N(1)),a(this,"focalLength",new N(.2)),a(this,"aperture",new N(20)),a(this,"gaussianMaxRadius",new N),a(this,"resolutionScale",new N(1/window.devicePixelRatio)),a(this,"bokehScale",new N)}get typeName(){return"DepthOfField"}init(){this.focalLength.valueProcessor=t=>{const s=t/300;return W.lerp(2,.01,s)};const e=20;this.aperture.valueProcessor=t=>{const s=1-t/32;return W.lerp(1,e,s)}}onCreateEffect(){if(this.mode===0){Y2&&console.warn("DepthOfField: Mode is set to Off");return}const e=new A.POSTPROCESSING.MODULE.DepthOfFieldEffect(this.context.mainCamera,{worldFocusRange:.2,focalLength:1,bokehScale:20,resolutionScale:this.resolutionScale.value});return this.focusDistance.onValueChanged=t=>{e.cocMaterial.worldFocusDistance=t},this.focalLength.onValueChanged=t=>e.cocMaterial.worldFocusRange=t,this.aperture.onValueChanged=t=>e.bokehScale=t,this.resolutionScale&&(this.resolutionScale.onValueChanged=t=>e.resolution.scale=t),[e]}unapply(){}}ra([m()],As.prototype,"mode"),ra([m(N)],As.prototype,"focusDistance"),ra([m(N)],As.prototype,"focalLength"),ra([m(N)],As.prototype,"aperture"),ra([m(N)],As.prototype,"gaussianMaxRadius"),ra([m(N)],As.prototype,"resolutionScale"),ra([m(N)],As.prototype,"bokehScale"),us("DepthOfField",As);class xh extends rt{constructor(e){super(),a(this,"effect"),this.effect=e}get typeName(){return this.effect.constructor.name}onCreateEffect(){return this.effect}}var K2=Object.defineProperty,Z2=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&K2(e,t,o),o};class Sh extends rt{constructor(){super(...arguments),a(this,"granularity",new N(10))}get typeName(){return"PixelationEffect"}onCreateEffect(){const e=new A.POSTPROCESSING.MODULE.PixelationEffect;return this.granularity.onValueChanged=t=>{e.granularity=t},e}}Z2([m(N)],Sh.prototype,"granularity"),us("PixelationEffect",Sh);var J2=Object.defineProperty,Ch=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&J2(e,t,o),o};class to extends rt{constructor(){super(...arguments),a(this,"intensity",new N(2)),a(this,"falloff",new N(1)),a(this,"samples",new N(9)),a(this,"color",new N(new oe(0,0,0))),a(this,"luminanceInfluence",new N(.7)),a(this,"_ssao")}get typeName(){return"ScreenSpaceAmbientOcclusion"}onBeforeRender(){if(this._ssao&&this.context.mainCamera instanceof we){const e=this.context.mainCamera.far-this.context.mainCamera.near;this._ssao.ssaoMaterial.worldDistanceFalloff=e*.01,this._ssao.ssaoMaterial.worldDistanceThreshold=this.context.mainCamera.far}}onCreateEffect(){const e=this.context.mainCamera,t=new A.POSTPROCESSING.MODULE.NormalPass(this.context.scene,e),s=new A.POSTPROCESSING.MODULE.DepthDownsamplingPass({normalBuffer:t.texture,resolutionScale:.5}),o=this._ssao=new A.POSTPROCESSING.MODULE.SSAOEffect(e,t.texture,{normalDepthBuffer:s.texture,worldDistanceThreshold:1,worldDistanceFalloff:1,worldProximityThreshold:.1,worldProximityFalloff:2,intensity:1,blendFunction:A.POSTPROCESSING.MODULE.BlendFunction.MULTIPLY,luminanceInfluence:.5});this.intensity.onValueChanged=l=>{o.intensity=l},this.falloff.onValueChanged=l=>{o.ssaoMaterial.radius=l*.1},this.samples.onValueChanged=l=>{o.ssaoMaterial.samples=l},this.color.onValueChanged=l=>{o.color||(o.color=new oe),o.color.copy(l)},this.luminanceInfluence.onValueChanged=l=>{o.luminanceInfluence=l};const r=new Array;return r.push(t),r.push(s),r.push(o),r}}Ch([m(N)],to.prototype,"intensity"),Ch([m(N)],to.prototype,"falloff"),Ch([m(N)],to.prototype,"samples"),Ch([m(N)],to.prototype,"color"),Ch([m(N)],to.prototype,"luminanceInfluence"),us("ScreenSpaceAmbientOcclusion",to);var eI=Object.defineProperty,aa=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&eI(e,t,o),o};const tI=C("debugN8AO");var By=(n=>(n[n.Performance=0]="Performance",n[n.Low=1]="Low",n[n.Medium=2]="Medium",n[n.High=3]="High",n[n.Ultra=4]="Ultra",n))(By||{});class Is extends rt{constructor(){super(...arguments),a(this,"gammaCorrection",!0),a(this,"aoRadius",new N(1)),a(this,"falloff",new N(1)),a(this,"intensity",new N(1)),a(this,"color",new N(new oe(0,0,0))),a(this,"screenspaceRadius",!1),a(this,"quality",2),a(this,"_ssao")}get typeName(){return"ScreenSpaceAmbientOcclusionN8"}get pass(){return this._ssao}onValidate(){this._ssao&&(this._ssao.setQualityMode(By[this.quality]),this._ssao.configuration.gammaCorrection=this.gammaCorrection,this._ssao.configuration.screenSpaceRadius=this.screenspaceRadius)}onCreateEffect(){const e=this.context.mainCamera,t=this.context.domWidth,s=this.context.domHeight,o=this._ssao=new A.POSTPROCESSING_AO.MODULE.N8AOPostPass(this.context.scene,e,t,s);o.name="SSAO N8";const r=By[this.quality];o.setQualityMode(r),o.configuration.transparencyAware=!1;const l=new $s(t,s);return o.configuration.beautyRenderTarget=l,o.configuration.autoRenderBeauty=!1,o.configuration.gammaCorrection=this.gammaCorrection,o.configuration.screenSpaceRadius=this.screenspaceRadius,tI&&(o.enableDebugMode(),console.log(o),setInterval(()=>{console.log("SSAO",o.lastTime)},1e3),setInterval(()=>{console.log("SSAO",o.enabled,{ssao:o,autoRenderBeauty:o.configuration.autoRenderBeauty})},4e3)),this.intensity.onValueChanged=c=>{o.configuration.intensity=c},this.falloff.onValueChanged=c=>{o.configuration.distanceFalloff=c},this.aoRadius.onValueChanged=c=>{o.configuration.aoRadius=c},this.color.onValueChanged=c=>{o.color||(o.color=new oe),o.configuration.color.copy(c)},o}}aa([Tt(),m()],Is.prototype,"gammaCorrection"),aa([m(N)],Is.prototype,"aoRadius"),aa([m(N)],Is.prototype,"falloff"),aa([m(N)],Is.prototype,"intensity"),aa([m(N)],Is.prototype,"color"),aa([Tt(),m()],Is.prototype,"screenspaceRadius"),aa([Tt(),m()],Is.prototype,"quality"),us("ScreenSpaceAmbientOcclusionN8",Is);var iI=Object.defineProperty,sI=Object.getOwnPropertyDescriptor,vS=(n,e,t,s)=>{for(var o=sI(e,t),r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&iI(e,t,o),o};class Ph extends rt{constructor(){super(...arguments),a(this,"order",ft.Sharpening),a(this,"_effect"),a(this,"_amount",1),a(this,"_radius",1)}get typeName(){return"Sharpening"}onCreateEffect(){return this._effect??(this._effect=new(nI())),this.effect}get effect(){return this._effect}set amount(e){this._amount=e,this._effect&&(this._effect.uniforms.get("amount").value=e)}get amount(){return this._effect?this._effect.uniforms.get("amount").value:this._amount}set radius(e){this._radius=e,this._effect&&(this._effect.uniforms.get("radius").value=e)}get radius(){return this._effect?this._effect.uniforms.get("radius").value:this._radius}}vS([m()],Ph.prototype,"amount"),vS([m()],Ph.prototype,"radius");function nI(){const n=`
|
|
1273
|
+
`)}l&&r.size&&console.log(p);const y=new Set;for(const _ of f){_.getPath||console.error("USDZExporter: Animation target object has no getPath method. This is likely a bug",_);let w=_.getPath();w.startsWith("<")&&(w=w.substring(1)),w.endsWith(">")&&(w=w.substring(0,w.length-1)),y.add({path:w,obj:_})}const v=Array.from(y).sort((_,w)=>_.path.length-w.path.length),b=new Array;for(let _=0;_<v.length;_++)for(let w=_+1;w<v.length;w++)if(v[w].path.startsWith(v[_].path)){const x=v[w],k=v[_];b.push({child:x.obj.displayName+" ("+x.path+")",parent:k.obj.displayName+" ("+k.path+")"})}b.length&&console.warn("USDZExporter: There are overlapping PlayAnimation actions. This can lead to undefined runtime behaviour when playing multiple animations. Please restructure the hierarchy so that animations don't overlap.",{overlappingTargets:b,playAnimationActions:r})}for(const p of new Set([...t,...s]))if(Array.isArray(p))for(const g of p)o.add(g.uuid);else o.add(p.uuid);xp&&console.log("All Behavior trigger sources and action targets",t,s,o),this.targetUuids=new Set(o)}onAfterHierarchy(e,t){var s;if((s=this.behaviours)!=null&&s.length){t.beginBlock('def Scope "Behaviors"');for(const o of this.behaviours)o.writeTo(this,e.document,t);t.closeBlock()}}async onAfterSerialize(e){xp&&console.log("onAfterSerialize behaviours",this.behaviourComponentsCopy);for(const t of this.behaviourComponentsCopy)typeof t.afterSerialize=="function"&&(t.afterSerialize.constructor.name==="AsyncFunction"?await t.afterSerialize(this,e):t.afterSerialize(this,e));for(const{clipUrl:t,filesKey:s}of this.audioClipsCopy){if(e.files[s])return;const o=await(await(await fetch(t)).blob()).arrayBuffer(),r=new Uint8Array(o);e.files[s]=r}this.behaviourComponentsCopy.length=0,this.audioClipsCopy.length=0}}class J0{get extensionName(){return"Physics"}onExportObject(e,t,s){const o=P.getComponents(e,dt).filter(h=>h.enabled),r=P.getComponents(e,ui).filter(h=>h.enabled&&!h.isTrigger);let l=o.length>0?o[0]:null;const c=r.length>0?r[0]:null;c&&!l&&(l=new dt,l.isKinematic=!0),l&&t.addEventListener("serialize",(h,d)=>{var u,p,g;if(l){if(h.appendLine(),h.beginBlock('def RealityKitComponent "RigidBody"',"{",!0),l.useGravity||h.appendLine("bool gravityEnabled = 0"),h.appendLine('uniform token info:id = "RealityKit.RigidBody"'),l.isKinematic&&h.appendLine('token motionType = "Kinematic"'),h.beginBlock('def RealityKitStruct "massFrame"',"{",!0),h.appendLine(`float m_mass = ${l.mass}`),h.beginBlock('def RealityKitStruct "m_pose"',"{",!0),h.appendLine(`float3 position = (${l.centerOfMass.x}, ${l.centerOfMass.y}, ${l.centerOfMass.z})`),h.closeBlock("}"),h.closeBlock("}"),r.length>0){const f=r[0];h.beginBlock('def RealityKitStruct "material"',"{",!0);const y=f.sharedMaterial;y&&y.dynamicFriction!==void 0&&h.appendLine(`double dynamicFriction = ${(u=f.sharedMaterial)==null?void 0:u.dynamicFriction}`),y&&y.bounciness!==void 0&&h.appendLine(`double restitution = ${(p=f.sharedMaterial)==null?void 0:p.bounciness}`),y&&y.staticFriction!==void 0&&h.appendLine(`double staticFriction = ${(g=f.sharedMaterial)==null?void 0:g.staticFriction}`),h.closeBlock("}")}h.closeBlock("}")}}),c&&(t.addEventListener("serialize",(h,d)=>{var u;h.beginBlock('def RealityKitComponent "Collider"',"{",!0),h.appendLine("uint group = 1"),h.appendLine('uniform token info:id = "RealityKit.Collider"'),h.appendLine("uint mask = 4294967295");const p=c.isTrigger?"Trigger":"Default";if(h.appendLine(`token type = "${p}"`),h.beginBlock('def RealityKitStruct "Shape"',"{",!0),c instanceof el){const g=c;h.appendLine('token shapeType = "Sphere"'),h.appendLine(`float radius = ${g.radius}`)}else if(c instanceof Nu){const g=c;h.appendLine('token shapeType = "Box"'),h.appendLine(`float3 extent = (${g.size.x}, ${g.size.y}, ${g.size.z})`)}else if(c instanceof Wn){const g=c;h.appendLine('token shapeType = "Capsule"'),h.appendLine(`float radius = ${g.radius}`),h.appendLine(`float height = ${g.height}`)}else if(c instanceof Fo&&(u=c.sharedMesh)!=null&&u.geometry){const g=c.sharedMesh.geometry;g.boundingBox||g.computeBoundingBox();const f=c.sharedMesh.geometry.boundingBox;f&&(h.appendLine('token shapeType = "Box"'),h.appendLine(`float3 extent = (${f.max.x-f.min.x}, ${f.max.y-f.min.y}, ${f.max.z-f.min.z})`),console.log("[USDZ] Only Box, Sphere, and Capsule colliders are supported in visionOS/iOS. MeshCollider will be exported as Box",c))}else console.warn("[USDZ] Only Box, Sphere, and Capsule colliders are supported in visionOS/iOS. Ignoring collider:",c);h.beginBlock('def RealityKitStruct "pose"',"{",!0),h.closeBlock("}"),h.closeBlock("}"),h.closeBlock("}")}),r.length>1&&console.log("WARNING: Multiple colliders detected. visionOS / iOS can only support objects with a single collider, only exporting the first collider: ",c))}}const RA=C("debugshadowcomponents");eb.prototype.interactable={get(){return this.interactive},set(n){this.interactable=n}};class ps extends I{constructor(){super(...arguments),a(this,"_shadowComponent",null),a(this,"_controlsChildLayout",!0),a(this,"_root"),a(this,"_parentComponent")}isRoot(){var e;return((e=this.Root)==null?void 0:e.gameObject)===this.gameObject}get canvas(){const e=this.Root;return e!=null&&e.isCanvas?e:null}get Canvas(){return this.canvas}markDirty(){ii.markUIDirty(this.context)}get shadowComponent(){return this._shadowComponent}set shadowComponent(e){this._shadowComponent=e}get controlsChildLayout(){return this._controlsChildLayout}set controlsChildLayout(e){this._controlsChildLayout=e,this.shadowComponent&&(this.shadowComponent.autoLayout=e)}get Root(){return this._root===void 0&&(this._root=P.getComponentInParent(this.gameObject,oh)),this._root}__internalNewInstanceCreated(e){return super.__internalNewInstanceCreated(e),this.shadowComponent=null,this._root=void 0,this._parentComponent=void 0,this}onEnable(){super.onEnable()}addShadowComponent(e,t){var s;if(!e)return;this.removeShadowComponent();const o=this.isRoot()?this.gameObject:this.gameObject.parent;if(this._parentComponent=P.getComponentInParent(o,ps),!this._parentComponent){console.warn(`Component "${this.name}" doesn't have a UI parent anywhere. Do you have an UI element outside a Canvas? UI components must be a child of a Canvas component`,this);return}e.name=this.name+" ("+(this.constructor.name??"UI")+")",e.autoLayout=this._parentComponent.controlsChildLayout,e[Mi]=this,this.setShadowComponentOwner(e);let r=!1;if(((s=this.Root)==null?void 0:s.gameObject)===this.gameObject)this.gameObject.add(e);else{const l=this._parentComponent.shadowComponent;l&&(l?.add(e),r=!0)}this.shadowComponent=e,t&&t.shadowComponent&&this.shadowComponent&&t.shadowComponent.add(this.shadowComponent),yc&&e.add(new Ci(.5)),this.onAfterAddedToScene(),r&&kO(),RA&&console.warn("Added shadow component",this.shadowComponent)}setShadowComponentOwner(e){if(e&&(e[Mi]===void 0||e[Mi]===this)&&(e[Mi]=this,e.children))for(const t of e.children)this.setShadowComponentOwner(t)}traverseOwnedShadowComponents(e,t,s){if(e&&e[Mi]===t){s(e);for(const o of e.children)this.traverseOwnedShadowComponents(o,t,s)}}removeShadowComponent(){this.shadowComponent&&this.shadowComponent.removeFromParent()}onAfterAddedToScene(){}setInteractable(e){this.shadowComponent&&(this.shadowComponent.interactable=e)}}class oh extends ps{awake(){super.awake()}}var TA=Object.defineProperty,EA=Object.getOwnPropertyDescriptor,rh=(n,e,t,s)=>{for(var o=s>1?void 0:s?EA(e,t):e,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=(s?l(e,t,o):l(o))||o);return s&&o&&TA(e,t,o),o};const ey=C("debugui"),ty=C("debuguilayout");class K1{constructor(){a(this,"width"),a(this,"height")}}class Z1{constructor(){a(this,"x"),a(this,"y"),a(this,"width"),a(this,"height")}}const Rs=new S,ah=new se,Sp=new V,vl=class OC extends ps{constructor(){super(...arguments),a(this,"_anchoredPosition"),a(this,"sizeDelta",new re(100,100)),a(this,"pivot",new re(.5,.5)),a(this,"anchorMin",new re(0,0)),a(this,"anchorMax",new re(1,1)),a(this,"minWidth"),a(this,"minHeight"),a(this,"lastMatrix"),a(this,"rectBlock"),a(this,"_transformNeedsUpdate",!1),a(this,"_initialPosition"),a(this,"_parentRectTransform"),a(this,"_lastUpdateFrame",-1),a(this,"_lastAnchoring"),a(this,"_createdBlocks",[]),a(this,"_createdTextBlocks",[])}get parent(){return this._parentRectTransform}get translation(){return this.gameObject.position}get rotation(){return this.gameObject.quaternion}get scale(){return this.gameObject.scale}get anchoredPosition(){return this._anchoredPosition||(this._anchoredPosition=new re),this._anchoredPosition}set anchoredPosition(e){this._anchoredPosition=e}get width(){let e=this.sizeDelta.x;if(this.anchorMin.x!==this.anchorMax.x&&this._parentRectTransform){const t=this._parentRectTransform.width,s=this.anchorMax.x-this.anchorMin.x;e=t*s,e+=this.sizeDelta.x}return this.minWidth!==void 0&&e<this.minWidth?this.minWidth:e}get height(){let e=this.sizeDelta.y;if(this.anchorMin.y!==this.anchorMax.y&&this._parentRectTransform){const t=this._parentRectTransform.height,s=this.anchorMax.y-this.anchorMin.y;e=t*s,e+=this.sizeDelta.y}return this.minHeight!==void 0&&e<this.minHeight?this.minHeight:e}awake(){super.awake(),this._lastUpdateFrame=-1,this._parentRectTransform=void 0,this.rectBlock=new E,this.rectBlock.name=this.name,this.lastMatrix=new se,this._lastAnchoring=null,this._initialPosition=this.gameObject.position.clone(),this._initialPosition.z=0,this._anchoredPosition||(this._anchoredPosition=new re),Ka(this,"_anchoredPosition",()=>{this.markDirty()}),Ka(this,"sizeDelta",()=>{this.markDirty()}),Ka(this,"pivot",()=>{this.markDirty()}),Ka(this,"anchorMin",()=>{this.markDirty()}),Ka(this,"anchorMax",()=>{this.markDirty()})}onEnable(){var e;super.onEnable(),this.rectBlock||(this.rectBlock=new E),this.lastMatrix||(this.lastMatrix=new se),this._lastAnchoring||(this._lastAnchoring=new re),this._initialPosition||(this._initialPosition=new S),this._anchoredPosition||(this._anchoredPosition=new re),this.addShadowComponent(this.rectBlock),this._transformNeedsUpdate=!0,(e=this.canvas)==null||e.registerTransform(this)}onDisable(){var e;super.onDisable(),this.removeShadowComponent(),(e=this.canvas)==null||e.unregisterTransform(this)}onParentRectTransformChanged(e){this._transformNeedsUpdate||this.onApplyTransform(ty?`${e.name} changed`:void 0)}get isDirty(){return this._transformNeedsUpdate||(this._transformNeedsUpdate=!this.lastMatrix.equals(this.gameObject.matrix)),this._transformNeedsUpdate}markDirty(){this._transformNeedsUpdate||(ty&&console.warn("RectTransform markDirty()",this.name),this._transformNeedsUpdate=!0,this._lastUpdateFrame=-1)}updateTransform(){(this._transformNeedsUpdate||!this.lastMatrix.equals(this.gameObject.matrix))&&this.canUpdate()&&this.onApplyTransform(this._transformNeedsUpdate?"Marked dirty":"Matrix changed")}canUpdate(){return this._transformNeedsUpdate&&this.activeAndEnabled&&this._lastUpdateFrame!==this.context.time.frame}onApplyTransform(e){var t;if(this.context.time.frameCount===this._lastUpdateFrame)return;this._lastUpdateFrame=this.context.time.frameCount;const s=this.shadowComponent;if(!s)return;this.gameObject.parent?this._parentRectTransform=P.getComponentInParent(this.gameObject.parent,OC):this._parentRectTransform=void 0,this._transformNeedsUpdate=!1,ty&&console.warn("RectTransform \u2192 ApplyTransform",this.name+" because "+e),this.isRoot()?this.Root.screenspace||(s.rotation.y=Math.PI):(s.matrix.identity(),s.matrixAutoUpdate=!1,Rs.set(0,0,0),this.applyPivot(Rs),s.matrix.setPosition(Rs.x,Rs.y,0),(this.gameObject.quaternion.x||this.gameObject.quaternion.y||this.gameObject.quaternion.z)&&(Sp.copy(this.gameObject.quaternion),Sp.x*=-1,Sp.z*=-1,ah.makeRotationFromQuaternion(Sp),s.matrix.premultiply(ah)),Rs.set(0,0,0),this.applyAnchoring(Rs),(t=this.canvas)!=null&&t.screenspace?Rs.z+=.1:Rs.z+=.01,ah.identity(),ah.setPosition(Rs.x,Rs.y,Rs.z),s.matrix.premultiply(ah),s.matrix.scale(this.gameObject.scale)),this.lastMatrix.copy(this.gameObject.matrix);const o=!0;for(const r of hu(this.gameObject,ps,o,1)){if(r===this||!r.activeAndEnabled)continue;const l=r;l.onParentRectTransformChanged&&l.onParentRectTransformChanged(this)}}applyAnchoring(e){this._lastAnchoring||(this._lastAnchoring=new re);const t=this._lastAnchoring.sub(this._anchoredPosition);this.gameObject.position.x+=t.x,this.gameObject.position.y+=t.y,this._lastAnchoring.copy(this._anchoredPosition),e.x+=this._initialPosition.x-this.gameObject.position.x,e.y+=this._initialPosition.y-this.gameObject.position.y,e.z+=this._initialPosition.z-this.gameObject.position.z;const s=this._parentRectTransform;if(s){let o=0;const r=1-this.anchorMax.y-this.anchorMin.y;o-=s.height*.5*r,e.y+=o;let l=0;const c=1-this.anchorMax.x-this.anchorMin.x;l-=s.width*.5*c,e.x+=l}}applyPivot(e){if(this.pivot&&!this.isRoot()){const t=this.pivot.x-.5;e.x-=t*this.sizeDelta.x*this.gameObject.scale.x;const s=this.pivot.y-.5;e.y-=s*this.sizeDelta.y*this.gameObject.scale.y}}getBasicOptions(){const e={width:this.sizeDelta.x,height:this.sizeDelta.y,offset:0,backgroundOpacity:0,borderWidth:0,borderRadius:0,borderOpacity:0,letterSpacing:-.03};return this.ensureValidSize(e),e}ensureValidSize(e,t=1e-4){return e.width<=0&&(e.width=t),e.height<=0&&(e.height=1e-4),e}createNewBlock(e){e={...this.getBasicOptions(),...e},ey&&console.log(this.name,e);const t=new eb(e);return this._createdBlocks.push(t),t}createNewText(e){ey&&console.log(e),e={...this.getBasicOptions(),...e},ey&&console.log(this.name,e);const t=new Jv(e);return this._createdTextBlocks.push(t),t}};rh([m(re)],vl.prototype,"anchoredPosition",1),rh([m(re)],vl.prototype,"sizeDelta",2),rh([m(re)],vl.prototype,"pivot",2),rh([m(re)],vl.prototype,"anchorMin",2),rh([m(re)],vl.prototype,"anchorMax",2);let Ts=vl;var AA=Object.defineProperty,J1=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&AA(e,t,o),o};class bl extends I{constructor(){super(...arguments),a(this,"effectColor"),a(this,"effectDistance")}}J1([m(he)],bl.prototype,"effectColor"),J1([m(re)],bl.prototype,"effectDistance");var IA=Object.defineProperty,LA=Object.getOwnPropertyDescriptor,eS=(n,e,t,s)=>{for(var o=s>1?void 0:s?LA(e,t):e,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=(s?l(e,t,o):l(o))||o);return s&&o&&IA(e,t,o),o};const Cp={backgroundColor:new oe(1,1,1),backgroundOpacity:1,borderColor:new oe(1,1,1),borderOpacity:1};var Qr;const iy=(Qr=class extends ps{constructor(){super(...arguments),a(this,"_alphaFactor",1),a(this,"sRGBColor",new oe(1,0,1)),a(this,"raycastTarget",!0),a(this,"uiObject",null),a(this,"_color",null),a(this,"_rect",null),a(this,"_stateManager",null),a(this,"_currentlyCreatingPanel",!1)}get isGraphic(){return!0}get color(){return this._color||(this._color=new he(1,1,1,1)),this._color}set color(n){(!this._color||this._color.r!==n.r||this._color.g!==n.g||this._color.b!==n.b||this._color.alpha!==n.alpha)&&(this._color||(this._color=new he(1,1,1,1)),this._color.copy(n),this.onColorChanged())}setAlphaFactor(n){this._alphaFactor=n,this.onColorChanged()}get alphaFactor(){return this._alphaFactor}onColorChanged(){this.uiObject&&(this.sRGBColor.copy(this._color),this.sRGBColor.convertLinearToSRGB(),Cp.backgroundColor=this.sRGBColor,Cp.backgroundOpacity=this._color.alpha*this._alphaFactor,this.applyEffects(Cp,this._alphaFactor),this.uiObject.set(Cp),this.markDirty())}get m_Color(){return this._color}get rectTransform(){if(this._rect||(this._rect=P.getComponent(this.gameObject,Ts)),!this._rect)throw new Error("Not Supported: Make sure to add a RectTransform component before adding a UI Graphic component.");return this._rect}onParentRectTransformChanged(){var n;(n=this.uiObject)==null||n.set({width:this.rectTransform.width,height:this.rectTransform.height}),this.markDirty()}__internalNewInstanceCreated(n){return super.__internalNewInstanceCreated(n),this._rect=null,this.uiObject=null,this._stateManager=null,this._color&&(this._color=this._color.clone()),this}setState(n){this.makePanel(),this.uiObject&&(this.uiObject.setState(n),this==null||this.markDirty())}setupState(n){this.makePanel(),this.uiObject&&(this._stateManager||(this._stateManager=new MO(this.uiObject)),this.uiObject.setupState(n.state,n.attributes))}setOptions(n){this.makePanel(),this.uiObject&&this.uiObject.set(n)}awake(){super.awake(),this.makePanel(),Ka(this,"_color",()=>RT(this,this.onColorChanged))}onEnable(){var n;super.onEnable(),this.uiObject&&((n=this.rectTransform.shadowComponent)==null||n.add(this.uiObject),this.addShadowComponent(this.uiObject,this.rectTransform))}onDisable(){super.onDisable(),this.uiObject&&this.removeShadowComponent()}makePanel(){if(this.uiObject||this._currentlyCreatingPanel)return;this._currentlyCreatingPanel=!0;const n={backgroundColor:this.color,backgroundOpacity:this.color.alpha,offset:.015};this.onBeforeCreate(n),this.applyEffects(n),this.onCreate(n),this.controlsChildLayout=!1,this._currentlyCreatingPanel=!1,this.onAfterCreated(),this.onColorChanged()}onBeforeCreate(n){}onCreate(n){this.uiObject=this.rectTransform.createNewBlock(n),this.uiObject.name=this.name}onAfterCreated(){}applyEffects(n,e=1){var t;const s=(t=this.gameObject)==null?void 0:t.getComponent(bl);s&&(s.effectDistance&&(n.borderWidth=Math.max(Math.abs(s.effectDistance.x),Math.abs(s.effectDistance.y))),s.effectColor&&(n.borderColor=s.effectColor,n.borderOpacity=s.effectColor.alpha*e))}async setTexture(n){if(this.setOptions({backgroundOpacity:0}),n){if(Qr.textureCache.has(n))n=Qr.textureCache.get(n);else if(!n.isRenderTargetTexture){const e=n.clone();e.colorSpace=On,Qr.textureCache.set(n,e),n=e}this.setOptions({backgroundImage:n,borderRadius:0,backgroundOpacity:this.color.alpha,backgroundSize:"stretch"}),Xe.assignTextureLOD(n,0).then(e=>{e instanceof je&&(n&&Qr.textureCache.set(n,e),this.setOptions({backgroundImage:e}),this.markDirty())})}else this.setOptions({backgroundImage:void 0,borderRadius:0,backgroundOpacity:this.color.alpha});this.markDirty()}onAfterAddedToScene(){super.onAfterAddedToScene(),this.shadowComponent&&(this.shadowComponent.offset=this.shadowComponent.position.z)}},a(Qr,"textureCache",new Map),Qr);eS([m(he)],iy.prototype,"color",1),eS([m()],iy.prototype,"raycastTarget",2);let lh=iy;class ch extends lh{constructor(){super(...arguments),a(this,"_flippedObject",!1)}onAfterCreated(){this.uiObject&&!this._flippedObject&&(this._flippedObject=!0,this.uiObject.scale.y*=-1)}}var jA=Object.defineProperty,DA=Object.getOwnPropertyDescriptor,Kn=(n,e,t,s)=>{for(var o=s>1?void 0:s?DA(e,t):e,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=(s?l(e,t,o):l(o))||o);return s&&o&&jA(e,t,o),o};const Yr=C("debugtext");var mt=(n=>(n[n.UpperLeft=0]="UpperLeft",n[n.UpperCenter=1]="UpperCenter",n[n.UpperRight=2]="UpperRight",n[n.MiddleLeft=3]="MiddleLeft",n[n.MiddleCenter=4]="MiddleCenter",n[n.MiddleRight=5]="MiddleRight",n[n.LowerLeft=6]="LowerLeft",n[n.LowerCenter=7]="LowerCenter",n[n.LowerRight=8]="LowerRight",n))(mt||{}),tS=(n=>(n[n.Normal=0]="Normal",n[n.Bold=1]="Bold",n[n.Italic=2]="Italic",n[n.BoldAndItalic=3]="BoldAndItalic",n))(tS||{});class Nt extends lh{constructor(){super(...arguments),a(this,"alignment",0),a(this,"verticalOverflow",0),a(this,"horizontalOverflow",0),a(this,"lineSpacing",1),a(this,"supportRichText",!1),a(this,"font"),a(this,"fontStyle",0),a(this,"sRGBTextColor",new oe(1,0,1)),a(this,"_text",""),a(this,"_fontSize",12),a(this,"_textMeshUi",null),a(this,"_didHandleTextRenderOnTop",!1)}setAlphaFactor(e){var t;super.setAlphaFactor(e),(t=this.uiObject)==null||t.set({fontOpacity:this.color.alpha*this.alphaFactor}),this.markDirty()}get text(){return this._text}set text(e){e!==this._text&&(this._text=e,this.feedText(this.text,this.supportRichText),this.markDirty())}set_text(e){this.text=e}get fontSize(){return this._fontSize}set fontSize(e){var t;this._fontSize=e,(t=this.uiObject)==null||t.set({fontSize:e})}onColorChanged(){var e;this.sRGBTextColor.copy(this.color),this.sRGBTextColor.convertLinearToSRGB(),(e=this.uiObject)==null||e.set({color:this.sRGBTextColor,fontOpacity:this.color.alpha})}onParentRectTransformChanged(){super.onParentRectTransformChanged(),this.uiObject&&this.updateOverflow()}onBeforeCanvasRender(e){this.updateOverflow()}updateOverflow(){var e;const t=(e=this.uiObject)==null?void 0:e._overflow;t&&(t._needsUpdate=!0)}onCreate(e){Yr&&console.log(this),this.horizontalOverflow==1&&(e.whiteSpace="pre"),this.verticalOverflow==0&&(this.context.renderer.localClippingEnabled=!0,e.overflow="hidden"),this.horizontalOverflow==1&&this.verticalOverflow==0,e.lineHeight=this.lineSpacing,delete e.backgroundOpacity,delete e.backgroundColor,Yr&&(e.backgroundColor=16750848,e.backgroundOpacity=.5);const t=this.rectTransform;e={...e,...this.getTextOpts()},this.getAlignment(e),Yr&&(e.backgroundColor=Math.random()*16777215,e.backgroundOpacity=.1),this.uiObject=t.createNewText(e),this.feedText(this.text,this.supportRichText)}onAfterAddedToScene(){super.onAfterAddedToScene(),this.handleTextRenderOnTop()}getTextOpts(){const e=this.fontSize,t={color:this.color,fontOpacity:this.color.alpha,fontSize:e,fontKerning:"normal"};return this.setFont(t,this.fontStyle),t}onEnable(){var e;super.onEnable(),this._didHandleTextRenderOnTop=!1,this.uiObject&&this.uiObject.addAfterUpdate(()=>{this.setShadowComponentOwner(this.uiObject),this.markDirty()}),setTimeout(()=>this.markDirty(),10),(e=this.canvas)==null||e.registerEventReceiver(this)}onDisable(){var e;super.onDisable(),(e=this.canvas)==null||e.unregisterEventReceiver(this)}getAlignment(e){switch(e.flexDirection="column",this.alignment){case 0:case 3:case 6:e.textAlign="left";break;case 1:case 4:case 7:e.textAlign="center";break;case 2:case 5:case 8:e.textAlign="right";break}switch(this.alignment){default:case 0:case 1:case 2:e.alignItems="start";break;case 3:case 4:case 5:e.alignItems="center";break;case 6:case 7:case 8:e.alignItems="end";break}return e}feedText(e,t){var s,o,r;if(Yr&&console.log("feedText",this.uiObject,e,t),!!this.uiObject)if(this._textMeshUi||(this._textMeshUi=[]),this.uiObject.children.length=0,!t||e.length===0)this.uiObject.textContent=e;else{let l=this.getNextTag(e);if(l){if(l.startIndex>0){for(let d=this.uiObject.children.length-1;d>=0;d--){const u=this.uiObject.children[d];u.isUI&&(this.uiObject.remove(u),u.clear())}const h=new Gm({textContent:e.substring(0,l.startIndex),color:"inherit"});this.uiObject.add(h)}}else{this.uiObject.textContent="",this.setOptions({textContent:e});return}const c=[];for(;l;){const h=this.getNextTag(e,l.endIndex),d={fontFamily:(s=this.uiObject)==null?void 0:s.get("fontFamily"),color:"inherit",textContent:""};if(h){d.textContent=this.getText(e,l,h),this.handleTag(l,d,c);const u=new Gm(d);(o=this.uiObject)==null||o.add(u)}else{d.textContent=e.substring(l.endIndex),this.handleTag(l,d,c);const u=new Gm(d);(r=this.uiObject)==null||r.add(u)}l=h}}}handleTextRenderOnTop(){this._didHandleTextRenderOnTop||(this._didHandleTextRenderOnTop=!0,this.startCoroutine(this.renderOnTopCoroutine()))}*renderOnTopCoroutine(){if(!this.canvas)return;const e=[],t=this.canvas,s={renderOnTop:t.renderOnTop,depthWrite:t.depthWrite,doubleSided:t.doubleSided};for(;;){let o=!1;if(this._textMeshUi)for(let r=0;r<this._textMeshUi.length;r++){if(e[r]===!0)continue;o=!0;const l=this._textMeshUi[r];l.textContent&&(Iu(l,s),e[r]=!0)}if(!o)break;yield}}handleTag(e,t,s){if(!e.isEndTag){if(e.type.includes("color")){const o=new sy(e,{color:t.color});if(s.push(o),e.type.length>6){const r=parseInt("0x"+e.type.substring(7));t.color=r}else t.color=new oe(1,1,1)}else if(e.type=="b"){this.setFont(t,1);const o=new sy(e,{fontWeight:700});s.push(o)}else if(e.type=="i"){this.setFont(t,2);const o=new sy(e,{fontStyle:"italic"});s.push(o)}}}getText(e,t,s){return e.substring(t.endIndex,s.startIndex)}getNextTag(e,t=0){const s=e.indexOf("<",t),o=e.indexOf(">",s);if(s>=0&&o>=0){const r=e.substring(s+1,o);return{type:r,startIndex:s,endIndex:o+1,isEndTag:r.startsWith("/")}}return null}setFont(e,t){if(!this.font)return;const s=this.font,o=this.getFamilyNameWithCorrectSuffix(s,t);Yr&&console.log("Selected font family:"+o);let r=tb.getFontFamily(o);switch(r||(r=tb.addFontFamily(o)),e.fontFamily=r,t){default:case 0:e.fontWeight=400,e.fontStyle="normal";break;case 1:e.fontWeight=700,e.fontStyle="normal";break;case 2:e.fontWeight=400,e.fontStyle="italic";break;case 3:e.fontStyle="italic",e.fontWeight=400}let l=r.getVariant(e.fontWeight,e.fontStyle);if(!l){let c=o;c!=null&&c.endsWith("-msdf.json")||(c+="-msdf.json");let h=o;h!=null&&h.endsWith(".png")||(h+=".png"),l=r.addVariant(e.fontWeight,e.fontStyle,c,h),l?.addEventListener("ready",()=>{this.markDirty()})}}getFamilyNameWithCorrectSuffix(e,t){var s;const o=e.lastIndexOf("-");if(o<0)return e;const r=(s=e.substring(o+1))==null?void 0:s.toLowerCase();if(BA.includes(r))return Yr&&console.warn("Unsupported font style: "+r),e;const l=e.lastIndexOf("/");let c=e;l>=0&&(c=c.substring(l+1));const h=c[0]===c[0].toUpperCase(),d=e.substring(0,o);switch(Yr&&console.log("Select font: ",e,tS[t],c,h,d),t){case 0:return h?d+"-Regular":d+"-regular";case 1:return h?d+"-Bold":d+"-bold";case 2:return h?d+"-Italic":d+"-italic";case 3:return h?d+"-BoldItalic":d+"-bolditalic";default:return e}}}Kn([m()],Nt.prototype,"alignment",2),Kn([m()],Nt.prototype,"verticalOverflow",2),Kn([m()],Nt.prototype,"horizontalOverflow",2),Kn([m()],Nt.prototype,"lineSpacing",2),Kn([m()],Nt.prototype,"supportRichText",2),Kn([m(URL)],Nt.prototype,"font",2),Kn([m()],Nt.prototype,"fontStyle",2),Kn([m()],Nt.prototype,"text",1),Kn([m()],Nt.prototype,"fontSize",1);class sy{constructor(e,t){a(this,"tag"),a(this,"previousValues"),this.tag=e,this.previousValues=t}}const BA=["medium","mediumitalic","black","blackitalic","thin","thinitalic","extrabold","light","lightitalic","semibold"];class Kr{constructor(e){a(this,"id"),a(this,"content",""),a(this,"font",[]),a(this,"pointSize",144),a(this,"width"),a(this,"height"),a(this,"depth"),a(this,"wrapMode"),a(this,"horizontalAlignment"),a(this,"verticalAlignment"),a(this,"material"),this.id=e}static getId(){return this.global_id++}setDepth(e){return this.depth=e,this}setPointSize(e){return this.pointSize=e,this}setHorizontalAlignment(e){return this.horizontalAlignment=e,this}setVerticalAlignment(e){return this.verticalAlignment=e,this}writeTo(e,t){var s;t.beginBlock(`def Preliminary_Text "${this.id}"`,"(",!1),t.appendLine('prepend apiSchemas = ["MaterialBindingAPI"]'),t.closeBlock(")"),t.beginBlock(),this.content&&t.appendLine(`string content = "${this.content}"`),(!this.font||this.font.length<=0)&&(this.font||(this.font=[]),(s=this.font)==null||s.push("sans-serif"));const o=this.font.map(r=>`"${r}"`).join(", ");t.appendLine(`string[] font = [ ${o} ]`),t.appendLine(`double pointSize = ${this.pointSize}`),typeof this.width=="number"&&t.appendLine(`double width = ${this.width}`),typeof this.height=="number"&&t.appendLine(`double height = ${this.height}`),typeof this.depth=="number"&&t.appendLine(`double depth = ${this.depth}`),this.wrapMode&&t.appendLine(`token wrapMode = "${this.wrapMode}"`),this.horizontalAlignment&&t.appendLine(`token horizontalAlignment = "${this.horizontalAlignment}"`),this.verticalAlignment&&t.appendLine(`token verticalAlignment = "${this.verticalAlignment}"`),this.material!==void 0&&t.appendLine(`rel material:binding = </StageRoot/Materials/${ap(this.material)}>`),t.closeBlock()}}a(Kr,"global_id",0);class ny{static singleLine(e,t,s){const o=new Kr("text_"+Kr.getId());return o.content=e,t&&(o.pointSize=t),s&&(o.depth=s),o}static multiLine(e,t,s,o,r,l){const c=new Kr("text_"+Kr.getId());return c.content=e,c.width=t,c.height=s,c.horizontalAlignment=o,c.verticalAlignment=r,l!==void 0&&(c.wrapMode=l),c}}const FA=new se().makeRotationY(Math.PI),UA=new se().makeScale(-1,1,-1);class Pp{get extensionName(){return"text"}exportText(e,t,s){const o=P.getComponent(e,Nt);if(!o)return;const r=P.getComponent(e,Ts);let l=100,c=100;r&&(l=r.width,c=r.height);const h=FA.clone();r&&h.premultiply(UA),t.setMatrix(h);const d=o.color.clone();t.material=new bt({color:d,emissive:d}),t.addEventListener("serialize",(u,p)=>{let g=o.text;g=g.replace(/\r/g,""),g=g.replace(/\n/g,"\\n");const f=ny.multiLine(g,l,c,"center","bottom","flowing");this.setTextAlignment(f,o.alignment),this.setOverflow(f,o),t.material&&(f.material=t.material),f.pointSize=this.convertToTextSize(o.fontSize),f.depth=.001,f.writeTo(void 0,u)})}convertToTextSize(e){return 1/.0502*144*e}setOverflow(e,t){t.horizontalOverflow?e.wrapMode="singleLine":e.wrapMode="flowing"}setTextAlignment(e,t){switch(t){case mt.LowerLeft:case mt.MiddleLeft:case mt.UpperLeft:e.horizontalAlignment="left";break;case mt.LowerCenter:case mt.MiddleCenter:case mt.UpperCenter:e.horizontalAlignment="center";break;case mt.LowerRight:case mt.MiddleRight:case mt.UpperRight:e.horizontalAlignment="right";break}switch(t){case mt.LowerLeft:case mt.LowerCenter:case mt.LowerRight:e.verticalAlignment="bottom";break;case mt.MiddleLeft:case mt.MiddleCenter:case mt.MiddleRight:e.verticalAlignment="middle";break;case mt.UpperLeft:case mt.UpperCenter:case mt.UpperRight:e.verticalAlignment="top";break}}}var zA=Object.defineProperty,it=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&zA(e,t,o),o};const iS=C("debuguilayout");class Zr{constructor(){a(this,"left",0),a(this,"right",0),a(this,"top",0),a(this,"bottom",0)}get vertical(){return this.top+this.bottom}get horizontal(){return this.left+this.right}}it([m()],Zr.prototype,"left"),it([m()],Zr.prototype,"right"),it([m()],Zr.prototype,"top"),it([m()],Zr.prototype,"bottom");class Wi extends I{constructor(){super(...arguments),a(this,"_rectTransform",null),a(this,"_needsUpdate",!1),a(this,"childAlignment",0),a(this,"reverseArrangement",!1),a(this,"spacing",0),a(this,"padding"),a(this,"minWidth",0),a(this,"minHeight",0),a(this,"flexibleHeight",0),a(this,"flexibleWidth",0),a(this,"preferredHeight",0),a(this,"preferredWidth",0)}get rectTransform(){return this._rectTransform}onParentRectTransformChanged(e){this._needsUpdate=!0}get isDirty(){return this._needsUpdate}get isLayoutGroup(){return!0}updateLayout(){this._rectTransform&&(iS&&console.warn("Layout Update",this.context.time.frame,this.name),this._needsUpdate=!1,this.onCalculateLayout(this._rectTransform))}start(){this._needsUpdate=!0}onEnable(){iS&&console.log(this.name,this),this._rectTransform=this.gameObject.getComponent(Ts);const e=this.gameObject.getComponentInParent(_l);e&&e.registerLayoutGroup(this),this._needsUpdate=!0}onDisable(){const e=this.gameObject.getComponentInParent(_l);e&&e.unregisterLayoutGroup(this)}set m_Spacing(e){e!==this.spacing&&(this._needsUpdate=!0,this.spacing=e)}get m_Spacing(){return this.spacing}}it([m()],Wi.prototype,"childAlignment"),it([m()],Wi.prototype,"reverseArrangement"),it([m()],Wi.prototype,"spacing"),it([m(Zr)],Wi.prototype,"padding"),it([m()],Wi.prototype,"minWidth"),it([m()],Wi.prototype,"minHeight"),it([m()],Wi.prototype,"flexibleHeight"),it([m()],Wi.prototype,"flexibleWidth"),it([m()],Wi.prototype,"preferredHeight"),it([m()],Wi.prototype,"preferredWidth");class Yo extends Wi{constructor(){super(...arguments),a(this,"childControlHeight",!0),a(this,"childControlWidth",!0),a(this,"childForceExpandHeight",!1),a(this,"childForceExpandWidth",!1),a(this,"childScaleHeight",!1),a(this,"childScaleWidth",!1)}onCalculateLayout(e){var t;const s=this.primaryAxis,o=e.width;let r=o;const l=e.height;let c=l;r-=this.padding.horizontal,c-=this.padding.vertical,s==="x"?this.padding.horizontal:this.padding.vertical;const h=s==="x",d=h?"y":"x",u=h?this.childControlWidth:this.childControlHeight,p=h?this.childControlHeight:this.childControlWidth,g=h?this.childForceExpandWidth:this.childForceExpandHeight,f=h?this.childForceExpandHeight:this.childForceExpandWidth,y=h?c:r,v=h?o:l,b=.5*(h?this.childAlignment%3:Math.floor(this.childAlignment/3));let _=0;h?_+=this.padding.left:_+=this.padding.top;let w=0,x=0;for(let D=0;D<this.gameObject.children.length;D++){const z=this.gameObject.children[D],j=P.getComponent(z,Ts);j!=null&&j.activeAndEnabled&&(x+=1,h?w+=j.width:w+=j.height)}let k=0;const M=this.spacing*(x-1);if(g||u){let D=0;h?D=r-=M:D=c-=M,x>0&&(k=D/x)}let T=0;T+=this.padding.left,T-=this.padding.right,b!==0&&(_=v-w,_*=b,_-=M*b,h?(_-=this.padding.right*b,_+=this.padding.left*(1-b),_<this.padding.left&&(_=this.padding.left)):(_-=this.padding.bottom*b,_+=this.padding.top*(1-b),_<this.padding.top&&(_=this.padding.top)));let L=1;for(let D=0;D<this.gameObject.children.length;D++){const z=this.gameObject.children[D],j=P.getComponent(z,Ts);if(j!=null&&j.activeAndEnabled){(t=j.pivot)==null||t.set(.5,.5),j.anchorMin.set(0,1),j.anchorMax.set(0,1);const H=o*.5+T*.5;j.anchoredPosition.x!==H&&(j.anchoredPosition.x=H);const K=l*-.5;j.anchoredPosition.y!==K&&(j.anchoredPosition.y=K),f&&p&&j.sizeDelta[d]!==y&&(j.sizeDelta[d]=y),g&&u&&j.sizeDelta[s]!==k&&(j.sizeDelta[s]=k);const U=h?j.width:j.height,B=U*.5;if(_+=B,g){const te=k*L-k*.5;te>_&&(_=te-k*.5+U+this.padding.left,_-=B)}let Q=_;s==="y"&&(Q=-Q),j.anchoredPosition[s]!==Q&&(j.anchoredPosition[s]=Q),_+=B,_+=this.spacing,L+=1}}}}it([m()],Yo.prototype,"childControlHeight"),it([m()],Yo.prototype,"childControlWidth"),it([m()],Yo.prototype,"childForceExpandHeight"),it([m()],Yo.prototype,"childForceExpandWidth"),it([m()],Yo.prototype,"childScaleHeight"),it([m()],Yo.prototype,"childScaleWidth");class oy extends Yo{get primaryAxis(){return"y"}}class ry extends Yo{get primaryAxis(){return"x"}}class ay extends Wi{onCalculateLayout(){}}var NA=Object.defineProperty,WA=Object.getOwnPropertyDescriptor,mn=(n,e,t,s)=>{for(var o=s>1?void 0:s?WA(e,t):e,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=(s?l(e,t,o):l(o))||o);return s&&o&&NA(e,t,o),o},sS=(n=>(n[n.ScreenSpaceOverlay=0]="ScreenSpaceOverlay",n[n.ScreenSpaceCamera=1]="ScreenSpaceCamera",n[n.WorldSpace=2]="WorldSpace",n[n.Undefined=-1]="Undefined",n))(sS||{});const ly=C("debuguilayout"),cs=class kC extends oh{constructor(){super(...arguments),a(this,"_renderOnTop"),a(this,"_depthWrite",!1),a(this,"_doubleSided",!0),a(this,"_castShadows",!1),a(this,"_receiveShadows",!1),a(this,"_renderMode",-1),a(this,"_rootCanvas"),a(this,"_scaleFactor",1),a(this,"worldCamera"),a(this,"planeDistance",-1),a(this,"_boundRenderSettingsChanged",this.onRenderSettingsChanged.bind(this)),a(this,"previousParent",null),a(this,"_lastMatrixWorld",null),a(this,"_rectTransforms",[]),a(this,"_layoutGroups",new Map),a(this,"_receivers",[]),a(this,"onBeforeRenderRoutine",()=>{var e,t,s,o;if(this.previousParent=this.gameObject.parent,((e=this.context.xr)!=null&&e.isVR||(t=this.context.xr)!=null&&t.isPassThrough)&&this.screenspace){this.gameObject.visible=!1,this.gameObject.removeFromParent();return}this.renderOnTop||this.screenspace?this.gameObject.removeFromParent():(this.onUpdateRenderMode(),this.handleLayoutUpdates(),(s=this.shadowComponent)==null||s.updateMatrixWorld(!0),(o=this.shadowComponent)==null||o.updateWorldMatrix(!0,!0),this.invokeBeforeRenderEvents(),ii.ensureUpdateMeshUI(ib,this.context))}),a(this,"onAfterRenderRoutine",()=>{var e,t,s,o,r;if(((e=this.context.xr)!=null&&e.isVR||(t=this.context.xr)!=null&&t.isPassThrough)&&this.screenspace){(s=this.previousParent)==null||s.add(this.gameObject);return}if((this.screenspace||this.renderOnTop)&&this.previousParent&&this.context.mainCamera){if(this.screenspace){const h=this.context.mainCamera;h?.add(this.gameObject)}else this.previousParent.add(this.gameObject);const l=this.context.renderer.autoClear,c=this.context.renderer.autoClearColor;this.context.renderer.autoClear=!1,this.context.renderer.autoClearColor=!1,this.context.renderer.clearDepth(),this.onUpdateRenderMode(!0),this.handleLayoutUpdates(),(o=this.shadowComponent)==null||o.updateMatrixWorld(!0),this.invokeBeforeRenderEvents(),ii.ensureUpdateMeshUI(ib,this.context,!0),this.context.renderer.render(this.gameObject,this.context.mainCamera),this.context.renderer.autoClear=l,this.context.renderer.autoClearColor=c,this.previousParent.add(this.gameObject)}(r=this._lastMatrixWorld)==null||r.copy(this.gameObject.matrixWorld)}),a(this,"_updateRenderSettingsRoutine"),a(this,"_activeRenderMode",-1),a(this,"_lastWidth",-1),a(this,"_lastHeight",-1)}get isCanvas(){return!0}get screenspace(){return this.renderMode!==2}set renderOnTop(e){e!==this._renderOnTop&&(this._renderOnTop=e,this.onRenderSettingsChanged())}get renderOnTop(){return this._renderOnTop!==void 0?this._renderOnTop:!!(this.screenspace&&this._renderMode===0)}set depthWrite(e){this._depthWrite!==e&&(this._depthWrite=e,this.onRenderSettingsChanged())}get depthWrite(){return this._depthWrite}set doubleSided(e){this._doubleSided!==e&&(this._doubleSided=e,this.onRenderSettingsChanged())}get doubleSided(){return this._doubleSided}set castShadows(e){this._castShadows!==e&&(this._castShadows=e,this.onRenderSettingsChanged())}get castShadows(){return this._castShadows}set receiveShadows(e){this._receiveShadows!==e&&(this._receiveShadows=e,this.onRenderSettingsChanged())}get receiveShadows(){return this._receiveShadows}get renderMode(){return this._renderMode}set renderMode(e){this._renderMode!==e&&(this._renderMode=e,this.onRenderSettingsChanged())}set rootCanvas(e){this._rootCanvas instanceof kC||(this._rootCanvas=e)}get rootCanvas(){return this._rootCanvas}get scaleFactor(){return this._scaleFactor}set scaleFactor(e){this._scaleFactor=e}awake(){var e;this.shadowComponent=this.gameObject,this.previousParent=this.gameObject.parent,ly&&console.log("Canvas.Awake()",((e=this.previousParent)==null?void 0:e.name)+"/"+this.gameObject.name),super.awake()}start(){this.applyRenderSettings()}onEnable(){super.onEnable(),this._updateRenderSettingsRoutine=void 0,this._lastMatrixWorld=new se,this.applyRenderSettings(),document.addEventListener("resize",this._boundRenderSettingsChanged),this.context.pre_render_callbacks.push(this.onBeforeRenderRoutine),this.context.post_render_callbacks.push(this.onAfterRenderRoutine)}onDisable(){super.onDisable(),document.removeEventListener("resize",this._boundRenderSettingsChanged);const e=this.context.pre_render_callbacks.indexOf(this.onBeforeRenderRoutine);e!==-1&&this.context.pre_render_callbacks.splice(e,1);const t=this.context.post_render_callbacks.indexOf(this.onAfterRenderRoutine);t!==-1&&this.context.post_render_callbacks.splice(t,1)}registerTransform(e){this._rectTransforms.push(e)}unregisterTransform(e){const t=this._rectTransforms.indexOf(e);t!==-1&&this._rectTransforms.splice(t,1)}registerLayoutGroup(e){const t=e.gameObject;this._layoutGroups.set(t,e)}unregisterLayoutGroup(e){const t=e.gameObject;this._layoutGroups.delete(t)}registerEventReceiver(e){this._receivers.push(e)}unregisterEventReceiver(e){const t=this._receivers.indexOf(e);t!==-1&&this._receivers.splice(t,1)}async onEnterXR(e){this.screenspace?(e.xr.isVR||e.xr.isPassThrough)&&(this.gameObject.visible=!1):(this.gameObject.visible=!1,await Xl(1).then(()=>{this.gameObject.visible=!0}))}onLeaveXR(e){this.screenspace&&(e.xr.isVR||e.xr.isPassThrough)&&(this.gameObject.visible=!0)}invokeBeforeRenderEvents(){var e;for(const t of this._receivers)(e=t.onBeforeCanvasRender)==null||e.call(t,this)}handleLayoutUpdates(){this._lastMatrixWorld===null&&(this._lastMatrixWorld=new se);const e=!this._lastMatrixWorld.equals(this.gameObject.matrixWorld);ly&&e&&console.log("Canvas Layout changed",this.context.time.frameCount,this.name);for(const t of this._rectTransforms){e&&t.markDirty();let s=this._layoutGroups.get(t.gameObject);t.isDirty&&!s&&(s=t.gameObject.getComponentInParent(Wi)),(t.isDirty||s!=null&&s.isDirty)&&(ly&&console.log("CANVAS UPDATE ### "+t.name+" ##################################### "+this.context.time.frame),s?.updateLayout(),t.updateTransform())}}applyRenderSettings(){this.onRenderSettingsChanged()}onRenderSettingsChanged(){this._updateRenderSettingsRoutine||(this._updateRenderSettingsRoutine=this.startCoroutine(this._updateRenderSettingsDelayed(),Oe.OnBeforeRender))}*_updateRenderSettingsDelayed(){if(yield,this._updateRenderSettingsRoutine=void 0,this.shadowComponent){this.onUpdateRenderMode(),Iu(this.shadowComponent,this);for(const e of P.getComponentsInChildren(this.gameObject,ps))Iu(e.shadowComponent,this)}}onUpdateRenderMode(e=!1){if(!e&&this._renderMode===this._activeRenderMode&&this._lastWidth===this.context.domWidth&&this._lastHeight===this.context.domHeight)return;this._activeRenderMode=this._renderMode;let t=this.context.mainCameraComponent,s=10;switch(t&&t.nearClipPlane>0&&t.farClipPlane>0&&(s=W.lerp(t.nearClipPlane,t.farClipPlane,.01)),this._renderMode===1&&(this.worldCamera&&(t=this.worldCamera),this.planeDistance>0&&(s=this.planeDistance)),this._renderMode){case 0:case 1:if(this._lastWidth=this.context.domWidth,this._lastHeight=this.context.domHeight,!t)return;const o=s+.01;this.gameObject.position.x=0,this.gameObject.position.y=0,this.gameObject.position.z=-o,this.gameObject.quaternion.identity();const r=this.gameObject.getComponent(Ts);let l=!1;r.sizeDelta.x!==this.context.domWidth&&(l=!0),r.sizeDelta.y!==this.context.domHeight&&(l=!0);const c=t.fieldOfView*Math.PI/180,h=2*Math.tan(c/2)*Math.abs(o);this.gameObject.scale.x=h/this.context.domHeight,this.gameObject.scale.y=h/this.context.domHeight,this.gameObject.scale.z=.01,l&&(r.sizeDelta.x=this.context.domWidth,r.sizeDelta.y=this.context.domHeight,r?.markDirty());break;case 2:this._lastWidth=-1,this._lastHeight=-1;break}}};mn([m()],cs.prototype,"renderOnTop",1),mn([m()],cs.prototype,"depthWrite",1),mn([m()],cs.prototype,"doubleSided",1),mn([m()],cs.prototype,"castShadows",1),mn([m()],cs.prototype,"receiveShadows",1),mn([m()],cs.prototype,"renderMode",1),mn([m(cs)],cs.prototype,"rootCanvas",1),mn([m()],cs.prototype,"scaleFactor",1),mn([m(ci)],cs.prototype,"worldCamera",2),mn([m()],cs.prototype,"planeDistance",2);let _l=cs;var VA=Object.defineProperty,$A=Object.getOwnPropertyDescriptor,cy=(n,e,t,s)=>{for(var o=s>1?void 0:s?$A(e,t):e,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=(s?l(e,t,o):l(o))||o);return s&&o&&VA(e,t,o),o};class Ko extends I{constructor(){super(...arguments),a(this,"_alpha",1),a(this,"interactable",!0),a(this,"blocksRaycasts",!0),a(this,"_isDirty",!1),a(this,"_buffer",[])}get alpha(){return this._alpha}set alpha(e){e!==this._alpha&&(this._alpha=e,this.markDirty())}get isCanvasGroup(){return!0}markDirty(){this._isDirty||(this._isDirty=!0,this.startCoroutine(this.applyChangesDelayed(),Oe.OnBeforeRender))}*applyChangesDelayed(){this._isDirty=!1,this.applyChangesNow()}applyChangesNow(){this._buffer.length=0;for(const e of P.getComponentsInChildren(this.gameObject,ps,this._buffer)){const t=e;t.setAlphaFactor&&t.setAlphaFactor(this._alpha)}}}cy([m()],Ko.prototype,"alpha",1),cy([m()],Ko.prototype,"interactable",2),cy([m()],Ko.prototype,"blocksRaycasts",2);class hy{get extensionName(){return"tmui"}onExportObject(e,t,s){const o=P.getComponent(e,_l);if(o&&o.enabled&&o.renderMode===sS.WorldSpace){const r=new Pp,l=P.getComponent(e,Ts),c=P.getComponent(e,Ko),h=new Array;if(l){if(!P.isActiveSelf(e)){const p=P.isActiveSelf(e);P.setActive(e,!0),l.onEnable(),l.updateTransform(),h.push(()=>{l.onDisable(),P.setActive(e,p)})}e.traverse(p=>{if(!P.isActiveInHierarchy(p)){const g=P.isActiveSelf(p);P.setActive(p,!0);const f=P.getComponent(p,ps);f&&(f.onEnable(),h.push(()=>{f.onDisable()}));const y=P.getComponent(p,Ts);y&&(y.onEnable(),y.updateTransform(),y.onApplyTransform(),h.push(()=>{y.onDisable()}));const v=P.getComponent(p,Nt);v&&(v.onEnable(),h.push(()=>{v.onDisable()})),h.push(()=>{P.setActive(p,g)})}}),l.width,l.height;const d=mi.createEmpty(),u=l.shadowComponent;if(t.add(d),u){const p=u.matrix;d.setMatrix(p);const g=new Map,f=new Map;g.set(u,d),f.set(u,c?c.alpha:1),u.traverse(y=>{if(y===u)return;const v=mi.createEmpty();v.setMatrix(y.matrix);const b=y.parent,_=!!b&&typeof b.textContent=="string"&&b.textContent.length>0;let w=f.get(b)||1;const x=P.getComponent(y,Ko);if(x&&(w*=x.alpha),y instanceof G&&_){const M=y[Mi];M?r.exportText(M.gameObject,v,s):console.error("Error when exporting UI: shadow component owner not found. This is likely a bug.",y)}if(y instanceof G&&!_){const M=y.geometry.clone();M.scale(1,1,-1),this.flipWindingOrder(M),v.geometry=M;const T=new oe,L=y.material.opacity;T.copy(y.material.color),v.material=new Me({color:T,opacity:L*w,map:y.material.map,transparent:!0})}g.set(y,v),f.set(y,w);const k=g.get(b);if(!k){console.error("Error when exporting UI: shadow component parent not found!",y,y.parent);return}k.add(v)})}}for(const d of h)d()}}flipWindingOrder(e){const t=e.index.array;for(let s=0,o=t.length/3;s<o;s++){const r=t[s*3];t[s*3]=t[s*3+2],t[s*3+2]=r}e.index.needsUpdate=!0}}const hh=C("debugusdz");function HA(n,e){var t;const s=[],o=P.getComponentsInChildren(n,Rt),r=P.getComponentsInChildren(n,Ft),l=new Array,c=new Array;if(e.injectImplicitBehaviours)for(const h of o){if(!h||!h.runtimeAnimatorController||!h.enabled)continue;const d=h.runtimeAnimatorController.activeState;if(!d||!d.motion||!d.motion.clip||((t=d.motion.clip.tracks)==null?void 0:t.length)<1||l.includes(h))continue;const u=new Jc;u.animator=h,u.stateName=d.name,u.trigger="start",u.name="PlayAnimationOnClick_implicitAtStart_"+u.stateName;const p=new E;P.addComponent(p,u),c.push(p),l.push(h),n.add(p)}else for(const h of o){if(!h||!h.runtimeAnimatorController||!h.enabled)continue;hh&&console.log(h);const d=[];for(const u of h.runtimeAnimatorController.enumerateActions()){hh&&console.log(u);const p=u.getClip();d.includes(p)||d.push(p)}s.push({root:h.gameObject,clips:d})}if(e.injectImplicitBehaviours)for(const h of r){if(!h||!h.clip||!h.enabled||!h.playAutomatically||l.includes(h))continue;const d=new Jc;d.animation=h,d.stateName=h.clip.name,d.trigger="start",d.name="PlayAnimationOnClick_implicitAtStart_"+d.stateName;const u=new E;P.addComponent(u,d),c.push(u),l.push(h),n.add(u)}else for(const h of r){hh&&console.log(h);const d=[];for(const u of h.animations)d.includes(u)||d.push(u);s.push({root:h.gameObject,clips:d})}hh&&s?.length>0&&console.log("USDZ Animation Clips without behaviours",s);for(const h of s)for(const d of h.clips)e.registerAnimation(h.root,d);return c}function GA(n,e){const t=P.getComponentsInChildren(n,ns),s=P.getComponentsInChildren(n,Vo),o=new Array,r=new Array;hh&&console.log({audioSources:t,playAudioOnClicks:s});for(const l of s){if(!l.target)continue;const c=t.indexOf(l.target);c>-1&&t.splice(c,1)}for(const l of t){if(!l||!l.clip||l.volume<=0||o.includes(l))continue;const c=new Vo;c.target=l,c.name="PlayAudioOnClick_implicitAtStart_",c.trigger="start";const h=new E;P.addComponent(h,c),console.log("implicit PlayAudioOnStart",h,c),r.push(h),o.push(l),n.add(h)}return r}function qA(n){return new Jt("DisableAtStart",At.sceneStartTrigger(),ve.fadeAction(n,0,!1))}function nS(n,e){const t=n.domElement.shadowRoot.querySelector("link[rel='ar']");if(t)return t;const s=document.createElement("div");s.classList.add("menu"),s.classList.add("quicklook-menu"),s.style.display="none",s.style.visibility="hidden";const o=document.createElement("button");o.id="open-in-ar",e?(o.innerText="View in AR",o.title="View this scene in AR. The scene will be exported to USDZ and opened with Apple's QuickLook."):(o.innerText="View in AR",o.title="Download this scene for AR. Open the downloaded USDZ file to view it in AR using Apple's QuickLook."),s.appendChild(o);const r=document.createElement("a");r.id="needle-usdz-link",r.style.display="none",r.rel="ar",r.href="",r.target="_blank",s.appendChild(r);const l=document.createElement("img");return l.id="button",r.appendChild(l),n.domElement.shadowRoot.appendChild(s),r}var XA=Object.defineProperty,It=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&XA(e,t,o),o};const Vi=C("debugusdz"),QA=C("debugusdzpruning");class Jr{constructor(){a(this,"callToAction"),a(this,"checkoutTitle"),a(this,"checkoutSubtitle"),a(this,"callToActionURL")}}It([m()],Jr.prototype,"callToAction"),It([m()],Jr.prototype,"checkoutTitle"),It([m()],Jr.prototype,"checkoutSubtitle"),It([m()],Jr.prototype,"callToActionURL");var wl;const fi=(wl=class extends I{constructor(){super(...arguments),a(this,"objectToExport"),a(this,"autoExportAnimations",!0),a(this,"autoExportAudioSources",!0),a(this,"exportFileName"),a(this,"customUsdzFile"),a(this,"customBranding"),a(this,"anchoringType","plane"),a(this,"maxTextureSize",2048),a(this,"planeAnchoringAlignment","horizontal"),a(this,"interactive",!0),a(this,"physics",!0),a(this,"allowCreateQuicklookButton",!0),a(this,"quickLookCompatible",!0),a(this,"extensions",[]),a(this,"link"),a(this,"button"),a(this,"onClickedOpenInARElement",n=>{n.preventDefault(),this.exportAndOpen()}),a(this,"_currentExportTasks",new Map),a(this,"_previousTimeScale",1),a(this,"lastCallback"),a(this,"_rootSessionRootWasAppliedTo",null),a(this,"_rootPositionBeforeExport",new S),a(this,"_rootRotationBeforeExport",new V),a(this,"_rootScaleBeforeExport",new S)}start(){var n,e,t;Vi&&(console.log("USDZExporter",this),console.log("Debug USDZ Mode. Press 'T' to export"),window.addEventListener("keydown",s=>{switch(s.key){case"t":this.exportAndOpen();break}})),this.objectToExport||(this.objectToExport=this.gameObject),!((e=(n=this.objectToExport)==null?void 0:n.children)!=null&&e.length)&&!((t=this.objectToExport)!=null&&t.isMesh)&&(this.objectToExport=this.context.scene)}onEnable(){var n;const e=X.supportsQuickLookAR(),t=X.isiOS()||X.isiPad();!this.button&&(Vi||e||t)&&(this.allowCreateQuicklookButton&&(this.button=this.createQuicklookButton()),this.lastCallback=this.quicklookCallback.bind(this),this.link=nS(this.context,e),this.link.addEventListener("message",this.lastCallback)),Vi&&De("USDZ Exporter enabled: "+this.name),(n=document.getElementById("open-in-ar"))==null||n.addEventListener("click",this.onClickedOpenInARElement),cc.registerExporter(this)}onDisable(){var n,e,t;(n=this.button)==null||n.remove(),(e=this.link)==null||e.removeEventListener("message",this.lastCallback),Vi&&De("USDZ Exporter disabled: "+this.name),(t=document.getElementById("open-in-ar"))==null||t.removeEventListener("click",this.onClickedOpenInARElement),cc.unregisterExporter(this)}async exportAsync(){return this.exportAndOpen()}async exportAndOpen(){var n;let e=this.exportFileName??((n=this.objectToExport)==null?void 0:n.name)??this.name;if(e+="-"+b1(),Zs()||(e!==""&&(e+="-"),e+="MadeWithNeedle"),this.link||(this.link=nS(this.context,X.supportsQuickLookAR())),this.customUsdzFile)return Vi&&console.log("Exporting custom usdz",this.customUsdzFile),this.openInQuickLook(this.customUsdzFile,e),null;if(!this.objectToExport)return console.warn("No object to export",this),null;const t=await this.export(this.objectToExport);return t?(Vi&&console.log("USDZ generation done. Downloading as "+e),this.openInQuickLook(t,e),t):(console.error("USDZ generation failed. Please report a bug",this),null)}async export(n){if(!n)return console.warn("No object to export"),null;const e=this._currentExportTasks.get(n);if(e)return e;const t=this.internalExport(n);return t instanceof Promise?(this._currentExportTasks.set(n,t),t.then(s=>(this._currentExportTasks.delete(n),s)).catch(s=>(this._currentExportTasks.delete(n),console.error("Error during USDZ export \u2013 please report a bug!",s),null))):t}async internalExport(n){de.start("export-usdz",{onProgress:x=>{this.dispatchEvent(new CustomEvent("export-progress",{detail:{progress:x}}))}}),de.report("export-usdz",{message:"Starting export",totalSteps:40,currentStep:0}),de.report("export-usdz",{message:"Load progressive textures",autoStep:5}),de.start("export-usdz-textures","export-usdz");const e=P.getComponentsInChildren(n,gi);for(const x of e)x&&x.enabled&&x.updateSprite(!0);const t=P.getComponentsInChildren(n,Ui),s=new Array;let o=0;for(const x of t){for(const k of x.sharedMeshes)if(k){const M=Xe.assignMeshLOD(k,0);M instanceof Promise&&s.push(new Promise((T,L)=>{M.then(()=>{o++,de.report("export-usdz-textures",{message:"Loaded progressive mesh",currentStep:o,totalSteps:s.length}),T()}).catch(D=>L(D))}))}for(const k of x.sharedMaterials)if(k){const M=Xe.assignTextureLOD(k,0);M instanceof Promise&&s.push(new Promise((T,L)=>{M.then(()=>{o++,de.report("export-usdz-textures",{message:"Loaded progressive texture",currentStep:o,totalSteps:s.length}),T()}).catch(D=>L(D))}))}}Vi&&De("Progressive Loading: "+s.length),await Promise.all(s),Vi&&De("Progressive Loading: done"),de.end("export-usdz-textures");const r=Di.Global.Mask;Di.Global.Set(rn.AR);const l=new P1,c=new dp(this.quickLookCompatible);let h;const d=[];this.interactive&&(d.push(new Z0),d.push(new _a),globalThis.NEEDLE_USE_RAPIER&&P.getComponentsInChildren(n,dt).length>0&&(this.physics?(h=new J0,d.push(h)):F()&&console.warn("USDZExporter: Physics export is disabled, but there are active Rigidbody components in the scene. They will not be exported.")),d.push(new Pp),d.push(new hy));const u=[c,...d,...this.extensions],p={self:this,exporter:l,extensions:u,object:n};de.report("export-usdz","Invoking before-export"),this.dispatchEvent(new CustomEvent("before-export",{detail:p})),this.applyWebARSessionRoot(),this._previousTimeScale=this.context.time.timeScale,this.context.time.timeScale=0,de.report("export-usdz","auto export animations and audio sources");const g=new Array;this.autoExportAnimations&&g.push(...HA(n,c)),u.find(x=>x.extensionName==="Audio")&&this.autoExportAudioSources&&g.push(...GA(n)),l.debug=Vi,l.pruneUnusedNodes=!QA;const f=Ju.instance.objs.map(x=>x.batchedMesh);l.keepObject=x=>{let k=!0;const M=P.getComponent(x,Ui);return M&&!M.enabled&&(k=!1),k&&f.includes(x)&&(k=!1),k&&P.getComponentInParent(x,Vc)&&(k=!1),k&&P.getComponentInParent(x,en)&&(k=!1),Vi&&!k&&console.log("USDZExporter: Discarding object",x),k},l.beforeWritingDocument=()=>{if(F()&&c&&h){const x=c.animatedRoots;for(const k of x){const M=P.getComponentsInChildren(k,dt).filter(L=>L.enabled),T=P.getComponents(k,ui).filter(L=>L.enabled&&!L.isTrigger);(M.length>0||T.length>0)&&console.error("An animated object has physics components in its child hierarchy. This can lead to undefined behaviour due to a bug in Apple's QuickLook (FB15925487). Remove the physics components from child objects or verify that you get the expected results.",k)}}};const y=new Array;this.objectToExport&&this.quickLookCompatible&&this.interactive&&this.objectToExport.traverse(x=>{x.visible||y.push(x)});const v=u.find(x=>x.extensionName==="Behaviour");this.interactive&&v&&y.length>0&&v.addBehavior(qA(y));let b=!0;this.quickLookCompatible&&!this.interactive&&(b=!1),this.anchoringType!=="plane"&&this.anchoringType!=="none"&&this.anchoringType!=="image"&&this.anchoringType!=="face"&&(this.anchoringType="plane"),this.planeAnchoringAlignment!=="horizontal"&&this.planeAnchoringAlignment!=="vertical"&&this.planeAnchoringAlignment!=="any"&&(this.planeAnchoringAlignment="horizontal"),de.report("export-usdz","Invoking exporter.parse");const _=await l.parse(this.objectToExport,{ar:{anchoring:{type:this.anchoringType},planeAnchoring:{alignment:this.planeAnchoringAlignment}},extensions:u,quickLookCompatible:this.quickLookCompatible,maxTextureSize:this.maxTextureSize,exportInvisible:b}),w=new Blob([_],{type:"model/vnd.usdz+zip"});this.revertWebARSessionRoot(),this.context.time.timeScale=this._previousTimeScale,de.report("export-usdz","Invoking after-export"),this.dispatchEvent(new CustomEvent("after-export",{detail:p}));for(const x of g)P.destroy(x);return Di.Global.Set(r),de.end("export-usdz"),w}openInQuickLook(n,e){const t=n instanceof Blob?URL.createObjectURL(n):n,s=this.buildQuicklookOverlay();Vi&&console.log("QuickLook Overlay",s);const o=s.callToAction?encodeURIComponent(s.callToAction):"",r=s.checkoutTitle?encodeURIComponent(s.checkoutTitle):"",l=s.checkoutSubtitle?encodeURIComponent(s.checkoutSubtitle):"";this.link.href=t+`#callToAction=${o}&checkoutTitle=${r}&checkoutSubtitle=${l}&callToActionURL=${s.callToActionURL}`,this.lastCallback||(this.lastCallback=this.quicklookCallback.bind(this),this.link.addEventListener("message",this.lastCallback)),this.link.download=e+".usdz",this.link.click()}download(n,e){wl.save(n,e)}static save(n,e){const t=document.createElement("a");t.style.display="none",document.body.appendChild(t),typeof n=="string"?t.href=n:t.href=URL.createObjectURL(n),t.download=e,t.click(),t.remove()}quicklookCallback(n){if(n?.data=="_apple_ar_quicklook_button_tapped"){Vi&&be("Quicklook closed via call to action button");var e=new CustomEvent("quicklook-button-tapped",{detail:this});if(this.dispatchEvent(e),!e.defaultPrevented){const t=new URLSearchParams(this.link.href);if(t){const s=t.get("callToActionURL");Vi&&De("Quicklook url: "+s),s&&(Zs()?globalThis.open(s,"_blank"):console.warn("Quicklook closed: custom redirects require a Needle Engine Pro license: https://needle.tools/pricing",s))}}}}buildQuicklookOverlay(){var n,e,t,s,o,r;const l={};return this.customBranding&&Object.assign(l,this.customBranding),Zs()||(console.log("Custom Quicklook banner text requires pro license: https://needle.tools/pricing"),l.callToAction="Close",l.checkoutTitle="\u{1F335} Made with Needle",l.checkoutSubtitle="_"),(((n=l.callToAction)==null?void 0:n.length)||((e=l.checkoutTitle)==null?void 0:e.length)||((t=l.checkoutSubtitle)==null?void 0:t.length))&&((s=l.callToAction)!=null&&s.length||(l.callToAction="\0"),(o=l.checkoutTitle)!=null&&o.length||(l.checkoutTitle="\0"),(r=l.checkoutSubtitle)!=null&&r.length||(l.checkoutSubtitle="\0")),this.dispatchEvent(new CustomEvent("quicklook-overlay",{detail:l})),l}getARScaleAndTarget(){if(!this.objectToExport)return{scale:1,_invertForward:!1,target:this.gameObject,sessionRoot:null};const n=P.findObjectOfType(wp);let e=P.getComponentInParent(this.objectToExport,$o);e||(e=P.getComponentInChildren(this.objectToExport,$o));let t=1,s=!1;const o=this.objectToExport;return n?t=n.arScale:e&&(t=e.arScale,s=e.invertForward),{scale:1/t,_invertForward:s,target:o,sessionRoot:e?.gameObject??null}}applyWebARSessionRoot(){if(!this.objectToExport)return;const{scale:n,_invertForward:e,target:t,sessionRoot:s}=this.getARScaleAndTarget(),o=s?.matrixWorld.clone().invert();this._rootSessionRootWasAppliedTo=t,this._rootPositionBeforeExport.copy(t.position),this._rootRotationBeforeExport.copy(t.quaternion),this._rootScaleBeforeExport.copy(t.scale),t.scale.multiplyScalar(n),e&&t.quaternion.multiply(wl.invertForwardQuaternion),t.updateMatrix(),t.updateMatrixWorld(!0),s&&o&&t.matrix.premultiply(o)}revertWebARSessionRoot(){if(!this.objectToExport||!this._rootSessionRootWasAppliedTo)return;const n=this._rootSessionRootWasAppliedTo;n.position.copy(this._rootPositionBeforeExport),n.quaternion.copy(this._rootRotationBeforeExport),n.scale.copy(this._rootScaleBeforeExport),n.updateMatrix(),n.updateMatrixWorld(!0),this._rootSessionRootWasAppliedTo=null}createQuicklookButton(){const n=ml.getOrCreate().createQuicklookButton();return n.parentNode||this.context.menu.appendChild(n),n}},a(wl,"invertForwardMatrix",new se().makeRotationY(Math.PI)),a(wl,"invertForwardQuaternion",new V().setFromEuler(new Dt(0,Math.PI,0))),wl);It([m(E)],fi.prototype,"objectToExport"),It([m()],fi.prototype,"autoExportAnimations"),It([m()],fi.prototype,"autoExportAudioSources"),It([m()],fi.prototype,"exportFileName"),It([m(URL)],fi.prototype,"customUsdzFile"),It([m(Jr)],fi.prototype,"customBranding"),It([m()],fi.prototype,"anchoringType"),It([m()],fi.prototype,"maxTextureSize"),It([m()],fi.prototype,"planeAnchoringAlignment"),It([m()],fi.prototype,"interactive"),It([m()],fi.prototype,"physics"),It([m()],fi.prototype,"allowCreateQuicklookButton"),It([m()],fi.prototype,"quickLookCompatible");let gn=fi;var YA=Object.defineProperty,KA=Object.getOwnPropertyDescriptor,dy=(n,e,t,s)=>{for(var o=KA(e,t),r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&YA(e,t,o),o};class xl extends I{constructor(){super(...arguments),a(this,"_fog")}get fog(){return this._fog||(this._fog=new Tv(0,0,50)),this._fog}get mode(){return 1}set near(e){this.fog.near=e}get near(){return this.fog.near}set far(e){this.fog.far=e}get far(){return this.fog.far}set color(e){this.fog.color.copy(e)}get color(){return this.fog.color}onEnable(){this.scene.fog=this.fog}onDisable(){this.scene.fog===this._fog&&(this.scene.fog=null)}}dy([m()],xl.prototype,"near"),dy([m()],xl.prototype,"far"),dy([m(oe)],xl.prototype,"color");var ZA=Object.defineProperty,uy=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&ZA(e,t,o),o};class ea extends I{constructor(){super(...arguments),a(this,"objectBounds",!1),a(this,"color"),a(this,"isGizmo",!0),a(this,"_gizmoObject",null),a(this,"_boxHelper",null)}onEnable(){this.isGizmo&&!yc||(this._gizmoObject||(this.objectBounds?this._gizmoObject=new RP(this.gameObject,this.color??16776960):(this.objectBounds=!1,this._gizmoObject=Vg(this.color??16776960))),this.objectBounds?(this.scene.add(this._gizmoObject),this._boxHelper=this._gizmoObject,this.startCoroutine(this.syncObjectBounds(),Oe.OnBeforeRender)):this.gameObject.add(this._gizmoObject))}onDisable(){this._gizmoObject&&this.gameObject.remove(this._gizmoObject)}*syncObjectBounds(){for(var e;this._boxHelper;)(e=this._boxHelper)==null||e.update(),yield}}uy([m()],ea.prototype,"objectBounds"),uy([m(oe)],ea.prototype,"color"),uy([m()],ea.prototype,"isGizmo");var JA=Object.defineProperty,py=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&JA(e,t,o),o};class Sl extends I{constructor(){super(...arguments),a(this,"isGizmo",!1),a(this,"color0"),a(this,"color1"),a(this,"gridHelper"),a(this,"size"),a(this,"divisions"),a(this,"offset")}onEnable(){if(this.isGizmo&&!yc)return;const e=this.size,t=this.divisions;this.gridHelper||(this.gridHelper=new Mm(e,t,this.color0??new oe(.4,.4,.4),this.color1??new oe(.6,.6,.6)),this.offset!==void 0&&(this.gridHelper.position.y+=this.offset)),this.gridHelper&&this.gameObject.add(this.gridHelper)}onDisable(){this.gridHelper&&(this.gameObject.remove(this.gridHelper),this.gridHelper=null)}}py([m()],Sl.prototype,"isGizmo"),py([m(oe)],Sl.prototype,"color0"),py([m(oe)],Sl.prototype,"color1");var e2=Object.defineProperty,my=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&e2(e,t,o),o};class gy extends I{constructor(){super(...arguments),a(this,"connectedBody"),a(this,"_rigidBody",null)}get rigidBody(){return this._rigidBody}onEnable(){this._rigidBody||(this._rigidBody=this.gameObject.getComponent(dt)),this.rigidBody&&this.connectedBody&&this.startCoroutine(this.create())}*create(){yield,this.rigidBody&&this.connectedBody&&this.activeAndEnabled&&this.createJoint(this.rigidBody,this.connectedBody)}}my([m(dt)],gy.prototype,"connectedBody");class fy extends gy{createJoint(e,t){var s;(s=this.context.physics.engine)==null||s.addFixedJoint(e,t)}}class dh extends gy{constructor(){super(...arguments),a(this,"anchor"),a(this,"axis")}createJoint(e,t){var s;this.axis&&this.anchor&&((s=this.context.physics.engine)==null||s.addHingeJoint(e,t,this.anchor,this.axis))}}my([m(S)],dh.prototype,"anchor"),my([m(S)],dh.prototype,"axis");var t2=Object.defineProperty,i2=Object.getOwnPropertyDescriptor,fn=(n,e,t,s)=>{for(var o=s>1?void 0:s?i2(e,t):e,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=(s?l(e,t,o):l(o))||o);return s&&o&&t2(e,t,o),o};function yy(n){return n*Math.PI/180}const oS=300,Zo=C("debuglights");class yi extends I{constructor(){super(...arguments),a(this,"type",0),a(this,"range",1),a(this,"spotAngle",1),a(this,"innerSpotAngle",1),a(this,"_color",new oe(16777215)),a(this,"_shadowNearPlane",.1),a(this,"_shadowBias",0),a(this,"_shadowNormalBias",0),a(this,"_overrideShadowBiasSettings",!1),a(this,"_shadows",1),a(this,"lightmapBakeType",4),a(this,"_intensity",-1),a(this,"_shadowDistance"),a(this,"shadowWidth"),a(this,"shadowHeight"),a(this,"_shadowResolution"),a(this,"light"),a(this,"_webXRStartedListener"),a(this,"_webXREndedListener"),a(this,"_webARRoot")}set color(e){this._color=e,this.light!==void 0&&(this.light.color=e)}get color(){return this.light?this.light.color:this._color}set shadowNearPlane(e){var t,s;if(e!==this._shadowNearPlane&&(this._shadowNearPlane=e,((s=(t=this.light)==null?void 0:t.shadow)==null?void 0:s.camera)!==void 0)){const o=this.light.shadow.camera;o.near=e}}get shadowNearPlane(){return this._shadowNearPlane}set shadowBias(e){var t,s;e!==this._shadowBias&&(this._shadowBias=e,((s=(t=this.light)==null?void 0:t.shadow)==null?void 0:s.bias)!==void 0&&(this.light.shadow.bias=e,this.light.shadow.needsUpdate=!0))}get shadowBias(){return this._shadowBias}set shadowNormalBias(e){var t,s;e!==this._shadowNormalBias&&(this._shadowNormalBias=e,((s=(t=this.light)==null?void 0:t.shadow)==null?void 0:s.normalBias)!==void 0&&(this.light.shadow.normalBias=e,this.light.shadow.needsUpdate=!0))}get shadowNormalBias(){return this._shadowNormalBias}set shadows(e){this._shadows=e,this.light&&(this.light.castShadow=e!==0,this.updateShadowSoftHard())}get shadows(){return this._shadows}set intensity(e){var t;if(this._intensity=e,this.light){let s=1;if(this.context.isInXR&&this._webARRoot){const o=(t=this._webARRoot)==null?void 0:t.arScale;typeof o=="number"&&o>0&&(s/=o)}this.light.intensity=e*s}Zo&&console.log("Set light intensity to "+this._intensity,e,this)}get intensity(){return this._intensity}get shadowDistance(){const e=this.light;return e!=null&&e.shadow?e.shadow.camera.far:-1}set shadowDistance(e){this._shadowDistance=e;const t=this.light;if(t!=null&&t.shadow){const s=t.shadow.camera;s.far=e,s.updateProjectionMatrix()}}get shadowResolution(){const e=this.light;return e!=null&&e.shadow?e.shadow.mapSize.x:-1}set shadowResolution(e){if(e===this._shadowResolution)return;this._shadowResolution=e;const t=this.light;t!=null&&t.shadow&&(t.shadow.mapSize.set(e,e),t.shadow.needsUpdate=!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}getWorldPosition(e){return this.light?this.type===1?this.light.getWorldPosition(e).multiplyScalar(1):this.light.getWorldPosition(e):e}awake(){this.color=new oe(this.color??16777215),Zo&&console.log(this.name,this)}onEnable(){Zo&&console.log("ENABLE LIGHT",this.name),this.createLight(),!this.isBaked&&(this.light&&(this.light.visible=!0,this.light.intensity=this._intensity,Zo&&console.log("Set light intensity to "+this.light.intensity,this.name),this.selfIsLight||this.light.parent!==this.gameObject&&this.gameObject.add(this.light)),this.type===1&&this.startCoroutine(this.updateMainLightRoutine(),Oe.LateUpdate))}onDisable(){Zo&&console.log("DISABLE LIGHT",this.name),this.light&&(this.selfIsLight?this.light.intensity=0:this.light.visible=!1)}onEnterXR(e){this._webARRoot=P.getComponentInParent(this.gameObject,$o)??void 0}onLeaveXR(e){}createLight(){const e=this.selfIsLight;if(e&&!this.light)switch(this.light=this.gameObject,this.light.name=this.name,this._intensity=this.light.intensity,this.type){case 1:this.setDirectionalLight(this.light);break}else if(!this.light)switch(this.type){case 1:const t=new Rm(this.color,this.intensity*Math.PI);if(t.position.set(0,0,-oS*.5).applyQuaternion(this.gameObject.quaternion),this.gameObject.add(t.target),br(t.target,0,0,0),this.light=t,this.gameObject.position.set(0,0,0),this.gameObject.rotation.set(0,0,0),Zo){const l=new EP(this.light,.2,this.color);this.context.scene.add(l)}break;case 0:const s=new TP(this.color,this.intensity*Math.PI,this.range,yy(this.spotAngle/2),1-yy(this.innerSpotAngle/2)/yy(this.spotAngle/2),2);s.position.set(0,0,0),s.rotation.set(0,0,0),this.light=s;const o=s.target;s.add(o),o.position.set(0,0,this.range),o.rotation.set(0,0,0);break;case 2:const r=new Tm(this.color,this.intensity*Math.PI,this.range);this.light=r;break}if(this.light){if(this._intensity>=0?this.light.intensity=this._intensity:this._intensity=this.light.intensity,this.shadows!==0?this.light.castShadow=!0:this.light.castShadow=!1,this.light.shadow){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),Zo&&console.log("Override shadow bias?",this._overrideShadowBiasSettings,this.shadowBias,this.shadowNormalBias),this.light.shadow.bias=this.shadowBias,this.light.shadow.normalBias=this.shadowNormalBias,this.updateShadowSoftHard();const t=this.light.shadow.camera;if(t.near=this.shadowNearPlane,this._shadowDistance!==void 0&&typeof this._shadowDistance=="number"?t.far=this._shadowDistance:t.far=oS*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{const s=this.gameObject.scale.x;t.left*=s,t.right*=s}if(this.shadowHeight!==void 0)t.top=this.shadowHeight/2,t.bottom=-this.shadowHeight/2;else{const s=this.gameObject.scale.y;t.top*=s,t.bottom*=s}this.light.shadow.needsUpdate=!0,Zo&&this.context.scene.add(new AP(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}}updateShadowSoftHard(){this.light&&this.light.shadow&&(this.shadows===2||(this.light.shadow.radius=1,this.light.shadow.blurSamples=1))}setDirectionalLight(e){e.add(e.target),e.target.position.set(0,0,-1)}}a(yi,"allowChangingRendererShadowMapType",!0),fn([m()],yi.prototype,"type",2),fn([m(oe)],yi.prototype,"color",1),fn([m()],yi.prototype,"shadowNearPlane",1),fn([m()],yi.prototype,"shadowBias",1),fn([m()],yi.prototype,"shadowNormalBias",1),fn([m()],yi.prototype,"shadows",1),fn([m()],yi.prototype,"lightmapBakeType",2),fn([m()],yi.prototype,"intensity",1),fn([m()],yi.prototype,"shadowDistance",1),fn([m()],yi.prototype,"shadowResolution",1),new S(0,0,0);var s2=Object.defineProperty,uh=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&s2(e,t,o),o};const vy=C("debuglods"),n2=C("nolods");class Cl{constructor(){a(this,"screenRelativeTransitionHeight"),a(this,"distance"),a(this,"renderers")}}uh([m()],Cl.prototype,"screenRelativeTransitionHeight"),uh([m()],Cl.prototype,"distance"),uh([m(Ui)],Cl.prototype,"renderers");class o2{constructor(e){a(this,"model"),this.model=e}get renderers(){return this.model.renderers}}class ph extends I{constructor(){super(...arguments),a(this,"fadeMode",0),a(this,"localReferencePoint"),a(this,"lodCount",0),a(this,"size",0),a(this,"animateCrossFading",!1),a(this,"lodModels"),a(this,"_lods",[]),a(this,"_settings",[]),a(this,"_lodsHandler"),a(this,"_distanceFactor",1)}start(){if(vy&&console.log("LODGROUP",this.name,this.lodModels,this),!n2&&!this._lodsHandler&&this.gameObject&&this.lodModels&&Array.isArray(this.lodModels)){const e=[];for(const s of this.lodModels){const o=new o2(s);this._lods.push(o);for(const r of o.renderers)e.includes(r)||e.push(r)}this._lodsHandler=new Array;for(let s=0;s<e.length;s++){const o=new IP;this._lodsHandler.push(o),this.gameObject.add(o)}const t=new E;t.name="Cull "+this.name;for(let s=0;s<e.length;s++){const o=e[s],r=this._lodsHandler[s],l=o.gameObject;vy&&console.log(s,l.name);for(const c of this._lods){const h=c.model.distance;let d=null;if(c.renderers.includes(o)?d=l:d=t,d.type==="Group"){console.warn(`LODGroup ${this.name}: Group or MultiMaterial object's are not supported as LOD object: ${d.name}`);continue}vy&&console.log("LEVEL",d.name,h),r.autoUpdate=!1,this.onAddLodLevel(r,d,c.model.distance)}}}}onAfterRender(){if(!this.gameObject||!this._lodsHandler)return;const e=this.context.mainCamera;if(e)for(const t of this._lodsHandler){t.update(e);const s=t.getCurrentLevel(),o=t.levels[s];t.layers.mask=o.object.layers.mask}}onAddLodLevel(e,t,s){if(t===this.gameObject){console.warn("LODGroup component must be on parent object and not mesh directly at the moment",t.name,t);return}e.addLevel(t,s*this._distanceFactor,.01);const o={lod:e,levelIndex:e.levels.length-1,distance:s};this._settings.push(o)}distanceFactor(e){if(e!==this._distanceFactor){this._distanceFactor=e;for(const t of this._settings){const s=t.lod.levels[t.levelIndex];s.distance=t.distance*e}}}}uh([m(S)],ph.prototype,"localReferencePoint"),uh([m(Cl)],ph.prototype,"lodModels");var r2=Object.defineProperty,a2=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&r2(e,t,o),o};const Op=C("debugnestedgltf");class kp extends I{constructor(){super(...arguments),a(this,"filePath"),a(this,"loadAssetInParent",!0),a(this,"_isLoadingOrDoneLoading",!1)}listenToProgress(e){var t;(t=this.filePath)==null||t.beginListenDownload(e)}preload(){var e;(e=this.filePath)==null||e.preload()}async start(){var e,t,s,o,r;if(this._isLoadingOrDoneLoading)return;Op&&console.log(this,this.guid);const l=this.gameObject.parent;if(l){this._isLoadingOrDoneLoading=!0;const c=new Fs;c.idProvider=new jt(this.hash(this.guid)),c.parent=this.loadAssetInParent!==!1?l:this.gameObject,this.gameObject.updateMatrix();const h=this.gameObject.matrix;Op&&console.log("Load nested:",((e=this.filePath)==null?void 0:e.url)??this.filePath,this.gameObject.position);const d=await((s=(t=this.filePath)==null?void 0:t.instantiate)==null?void 0:s.call(this.filePath,c));Op&&console.log("Nested loaded:",((o=this.filePath)==null?void 0:o.url)??this.filePath,d),d&&this.loadAssetInParent!==!1&&(d.matrixAutoUpdate=!1,d.matrix.identity(),d.applyMatrix4(h),d.matrixAutoUpdate=!0,d.layers.disableAll(),d.layers.set(this.layer),this.dispatchEvent(new CustomEvent("loaded",{detail:{instance:d,assetReference:this.filePath}}))),Op&&console.log("Nested loading done:",((r=this.filePath)==null?void 0:r.url)??this.filePath,d)}}onDestroy(){var e;(e=this.filePath)==null||e.unload()}hash(e){let t=0;for(let s=0;s<e.length;s++)t=e.charCodeAt(s)+((t<<5)-t);return t}}a2([m(ce)],kp.prototype,"filePath");var l2=Object.defineProperty,by=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&l2(e,t,o),o};const c2=C("debugnet"),Mp=class Sv extends I{constructor(){super(...arguments),a(this,"url",null),a(this,"urlParameterName",null),a(this,"localhost",null)}awake(){c2&&console.log(this),this.context.connection.registerProvider(this)}getWebsocketUrl(){let e=this.url?Sv.GetUrl(this.url,this.localhost):null;if(this.urlParameterName){const s=C(this.urlParameterName);s&&typeof s=="string"&&(e=s)}if(!e)return null;const t=new RegExp("(((https?)|(?<socket_prefix>wss?))://)?(www.)?(?<url>.+)","gm").exec(e);return t!=null&&t.groups?t?.groups.socket_prefix?e:"wss://"+t?.groups.url:null}static GetUrl(e,t){let s=e;const o=Sv.IsLocalNetwork()&&t;if(o&&(s=t),e!=null&&e.startsWith("/")){const r=o?s:window.location.origin;r!=null&&r.endsWith("/")&&e.startsWith("/")&&(e=e.substring(1)),s=r+e}return s}static IsLocalNetwork(e=window.location.hostname){return Xt(e)}};by([m()],Mp.prototype,"url"),by([m()],Mp.prototype,"urlParameterName"),by([m()],Mp.prototype,"localhost");let _y=Mp;var h2=Object.defineProperty,Rp=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&h2(e,t,o),o};class ta extends I{constructor(){super(...arguments),a(this,"referenceSpace"),a(this,"from"),a(this,"affectPosition",!1),a(this,"affectRotation",!1),a(this,"alignLookDirection",!1),a(this,"levelLookDirection",!1),a(this,"levelPosition",!1),a(this,"positionOffset",new S(0,0,0)),a(this,"rotationOffset",new S(0,0,0)),a(this,"offset",new S(0,0,0))}update(){if(!this.from)return;var e=ee(this.from),t=Se(this.from);this.offset.copy(this.positionOffset);const s=this.offset.length();if(this.referenceSpace&&this.offset.transformDirection(this.referenceSpace.matrixWorld).multiplyScalar(s),e.add(this.offset),this.levelPosition&&this.referenceSpace){const c=new yr(this.gameObject.up,0),h=ee(this.referenceSpace);c.setFromNormalAndCoplanarPoint(this.gameObject.up,h);const d=new S(0,0,0);c.projectPoint(e,d),e.copy(d)}this.affectPosition&<(this.gameObject,e);const o=new Dt(this.rotationOffset.x,this.rotationOffset.y,this.rotationOffset.z),r=new V().setFromEuler(o);this.affectRotation&&Yi(this.gameObject,t.multiply(r));const l=new S;this.from.getWorldDirection(l).multiplyScalar(50),this.levelLookDirection&&(l.y=0),this.alignLookDirection&&this.gameObject.lookAt(l)}}Rp([m(P)],ta.prototype,"referenceSpace"),Rp([m(P)],ta.prototype,"from"),Rp([m(S)],ta.prototype,"positionOffset"),Rp([m(S)],ta.prototype,"rotationOffset");var d2=Object.defineProperty,Jo=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&d2(e,t,o),o};class vi{constructor(e=0,t=0){a(this,"time",0),a(this,"value",0),a(this,"inTangent",1/0),a(this,"inWeight"),a(this,"outTangent",1/0),a(this,"outWeight"),a(this,"weightedMode"),this.time=e,this.value=t}}Jo([m()],vi.prototype,"time"),Jo([m()],vi.prototype,"value"),Jo([m()],vi.prototype,"inTangent"),Jo([m()],vi.prototype,"inWeight"),Jo([m()],vi.prototype,"outTangent"),Jo([m()],vi.prototype,"outWeight"),Jo([m()],vi.prototype,"weightedMode");const rS=class rd{constructor(){a(this,"keys",[])}static linearFromTo(e,t,s){const o=new rd,r=new vi;r.time=0,r.value=e;const l=new vi;return l.time=s,l.value=t,o.keys.push(r,l),o}static constant(e){const t=new rd,s=new vi;return s.time=0,s.value=e,t.keys.push(s),t}clone(){var e;const t=new rd;return t.keys=((e=this.keys)==null?void 0:e.map(s=>{const o=new vi;return o.time=s.time,o.value=s.value,o.inTangent=s.inTangent,o.inWeight=s.inWeight,o.outTangent=s.outTangent,o.outWeight=s.outWeight,o.weightedMode=s.weightedMode,o}))||[],t}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;if(this.keys.length===1)return this.keys[0].value;if(this.keys[0].time>=e)return this.keys[0].value;for(let t=0;t<this.keys.length;t++){const s=this.keys[t];if(s.time<=e)if(t+1<this.keys.length){const o=this.keys[t+1];if(o.time<e)continue;return!isFinite(s.outTangent)||!isFinite(o.inTangent)?s.value:rd.interpolateValue(e,s,o)}else return s.value}return this.keys[this.keys.length-1].value}static interpolateValue(e,t,s){const o=t.time,r=t.value,l=t.outTangent,c=s.time,h=s.value,d=s.inTangent,u=c-o,p=u*u,g=p*u,f=((l+d)*u-2*(h-r))/g,y=(3*(h-r)-(d+2*l)*u)/p,v=l,b=r,_=e-o,w=_*_,x=w*_;return f*x+y*w+v*_+b}};Jo([m(vi)],rS.prototype,"keys");let mh=rS;var u2=Object.defineProperty,O=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&u2(e,t,o),o};const Tp=C("debugparticles");var Zn=(n=>(n[n.Billboard=0]="Billboard",n[n.Stretch=1]="Stretch",n[n.HorizontalBillboard=2]="HorizontalBillboard",n[n.VerticalBillboard=3]="VerticalBillboard",n[n.Mesh=4]="Mesh",n))(Zn||{});class ia{constructor(){a(this,"alphaKeys",[]),a(this,"colorKeys",[])}get duration(){return 1}evaluate(e,t){let s,o=0,r=null,l=0;for(let c=0;c<this.alphaKeys.length;c++){const h=this.alphaKeys[c];(h.time<e||!s)&&(s=h,o=c)}for(let c=0;c<this.colorKeys.length;c++){const h=this.colorKeys[c];(h.time<e||!r)&&(r=h,l=c)}if(r)if(l+1<this.colorKeys.length){const c=this.colorKeys[l+1],h=W.remap(e,r.time,c.time,0,1);t.r=W.lerp(r.color.r,c.color.r,h),t.g=W.lerp(r.color.g,c.color.g,h),t.b=W.lerp(r.color.b,c.color.b,h)}else t.r=r.color.r,t.g=r.color.g,t.b=r.color.b;if(s)if(o+1<this.alphaKeys.length){const c=this.alphaKeys[o+1],h=W.remap(e,s.time,c.time,0,1);t.alpha=W.lerp(s.alpha,c.alpha,h)}else t.alpha=s.alpha;return t}}O([m()],ia.prototype,"alphaKeys"),O([m()],ia.prototype,"colorKeys");var gh=(n=>(n[n.Local=0]="Local",n[n.World=1]="World",n[n.Custom=2]="Custom",n))(gh||{}),Ep=(n=>(n[n.Sphere=0]="Sphere",n[n.SphereShell=1]="SphereShell",n[n.Hemisphere=2]="Hemisphere",n[n.HemisphereShell=3]="HemisphereShell",n[n.Cone=4]="Cone",n[n.Box=5]="Box",n[n.Mesh=6]="Mesh",n[n.ConeShell=7]="ConeShell",n[n.ConeVolume=8]="ConeVolume",n[n.ConeVolumeShell=9]="ConeVolumeShell",n[n.Circle=10]="Circle",n[n.CircleEdge=11]="CircleEdge",n[n.SingleSidedEdge=12]="SingleSidedEdge",n[n.MeshRenderer=13]="MeshRenderer",n[n.SkinnedMeshRenderer=14]="SkinnedMeshRenderer",n[n.BoxShell=15]="BoxShell",n[n.BoxEdge=16]="BoxEdge",n[n.Donut=17]="Donut",n[n.Rectangle=18]="Rectangle",n[n.Sprite=19]="Sprite",n[n.SpriteRenderer=20]="SpriteRenderer",n))(Ep||{});const Jn=class ad{constructor(){a(this,"mode","Constant"),a(this,"constant"),a(this,"constantMin"),a(this,"constantMax"),a(this,"curve"),a(this,"curveMin"),a(this,"curveMax"),a(this,"curveMultiplier")}static constant(e){const t=new ad;return t.setConstant(e),t}static betweenTwoConstants(e,t){const s=new ad;return s.setMinMaxConstant(e,t),s}static curve(e,t=1){const s=new ad;return s.setCurve(e,t),s}setConstant(e){this.mode=0,this.constant=e}setMinMaxConstant(e,t){this.mode=3,this.constantMin=e,this.constantMax=t}setCurve(e,t=1){this.mode=1,this.curve=e,this.curveMultiplier=t}clone(){var e,t,s;const o=new ad;return o.mode=this.mode,o.constant=this.constant,o.constantMin=this.constantMin,o.constantMax=this.constantMax,o.curve=(e=this.curve)==null?void 0:e.clone(),o.curveMin=(t=this.curveMin)==null?void 0:t.clone(),o.curveMax=(s=this.curveMax)==null?void 0:s.clone(),o.curveMultiplier=this.curveMultiplier,o}evaluate(e,t){const s=t===void 0?Math.random():t;switch(this.mode){case 0:case"Constant":return this.constant;case 1:case"Curve":return e=W.clamp01(e),this.curve.evaluate(e)*this.curveMultiplier;case 2:case"TwoCurves":const o=e*this.curveMin.duration,r=e*this.curveMax.duration;return W.lerp(this.curveMin.evaluate(o),this.curveMax.evaluate(r),s%1)*this.curveMultiplier;case 3:case"TwoConstants":return W.lerp(this.constantMin,this.constantMax,s%1);default:this.curveMax.evaluate(e)*this.curveMultiplier;break}return 0}getMax(){switch(this.mode){case 0:case"Constant":return this.constant;case 1:case"Curve":return this.getMaxFromCurve(this.curve)*this.curveMultiplier;case 2:case"TwoCurves":return Math.max(this.getMaxFromCurve(this.curveMin),this.getMaxFromCurve(this.curveMax))*this.curveMultiplier;case 3:case"TwoConstants":return Math.max(this.constantMin,this.constantMax);default:return 0}}getMaxFromCurve(e){if(!e)return 0;let t=Number.MIN_VALUE;for(let s=0;s<e.keys.length;s++){const o=e.keys[s];o.value>t&&(t=o.value)}return t}};O([m()],Jn.prototype,"mode"),O([m()],Jn.prototype,"constant"),O([m()],Jn.prototype,"constantMin"),O([m()],Jn.prototype,"constantMax"),O([m(mh)],Jn.prototype,"curve"),O([m(mh)],Jn.prototype,"curveMin"),O([m(mh)],Jn.prototype,"curveMax"),O([m()],Jn.prototype,"curveMultiplier");let Z=Jn;var st;const er=(st=class{constructor(){a(this,"mode",0),a(this,"color"),a(this,"colorMin"),a(this,"colorMax"),a(this,"gradient"),a(this,"gradientMin"),a(this,"gradientMax")}static constant(n){const e=new st;return e.constant(n),e}static betweenTwoColors(n,e){const t=new st;return t.betweenTwoColors(n,e),t}constant(n){return this.mode=0,this.color=n,this}betweenTwoColors(n,e){return this.mode=2,this.colorMin=n,this.colorMax=e,this}evaluate(n,e){const t=e===void 0?Math.random():e;switch(this.mode){case 0:case"Color":return this.color;case 1:case"Gradient":return this.gradient.evaluate(n,st._temp),st._temp;case 2:case"TwoColors":return st._temp.lerpColors(this.colorMin,this.colorMax,t);case 3:case"TwoGradients":return this.gradientMin.evaluate(n,st._temp),this.gradientMax.evaluate(n,st._temp2),st._temp.lerp(st._temp2,t);case 4:case"RandomColor":const s=Math.random();return this.gradientMin.evaluate(n,st._temp),this.gradientMax.evaluate(n,st._temp2),st._temp.lerp(st._temp2,s)}return st._temp.set(16777215),st._temp.alpha=1,st._temp}},a(st,"_temp",new he(0,0,0,1)),a(st,"_temp2",new he(0,0,0,1)),st);O([m()],er.prototype,"mode"),O([m(he)],er.prototype,"color"),O([m(he)],er.prototype,"colorMin"),O([m(he)],er.prototype,"colorMax"),O([m(ia)],er.prototype,"gradient"),O([m(ia)],er.prototype,"gradientMin"),O([m(ia)],er.prototype,"gradientMax");let sa=er;var wy=(n=>(n[n.Hierarchy=0]="Hierarchy",n[n.Local=1]="Local",n[n.Shape=2]="Shape",n))(wy||{});class Wt{constructor(){a(this,"cullingMode"),a(this,"duration"),a(this,"emitterVelocityMode"),a(this,"flipRotation"),a(this,"gravityModifier"),a(this,"gravityModifierMultiplier"),a(this,"loop"),a(this,"maxParticles"),a(this,"playOnAwake"),a(this,"prewarm"),a(this,"ringBufferLoopRange"),a(this,"ringBufferMode"),a(this,"scalingMode"),a(this,"simulationSpace"),a(this,"simulationSpeed"),a(this,"startColor"),a(this,"startDelay"),a(this,"startDelayMultiplier"),a(this,"startLifetime"),a(this,"startLifetimeMultiplier"),a(this,"startRotation"),a(this,"startRotationMultiplier"),a(this,"startRotation3D"),a(this,"startRotationX"),a(this,"startRotationXMultiplier"),a(this,"startRotationY"),a(this,"startRotationYMultiplier"),a(this,"startRotationZ"),a(this,"startRotationZMultiplier"),a(this,"startSize"),a(this,"startSize3D"),a(this,"startSizeMultiplier"),a(this,"startSizeX"),a(this,"startSizeXMultiplier"),a(this,"startSizeY"),a(this,"startSizeYMultiplier"),a(this,"startSizeZ"),a(this,"startSizeZMultiplier"),a(this,"startSpeed"),a(this,"startSpeedMultiplier"),a(this,"stopAction"),a(this,"useUnscaledTime")}}O([m(Z)],Wt.prototype,"gravityModifier"),O([m(sa)],Wt.prototype,"startColor"),O([m(Z)],Wt.prototype,"startDelay"),O([m(Z)],Wt.prototype,"startLifetime"),O([m(Z)],Wt.prototype,"startRotation"),O([m(Z)],Wt.prototype,"startRotationX"),O([m(Z)],Wt.prototype,"startRotationY"),O([m(Z)],Wt.prototype,"startRotationZ"),O([m(Z)],Wt.prototype,"startSize"),O([m(Z)],Wt.prototype,"startSizeX"),O([m(Z)],Wt.prototype,"startSizeY"),O([m(Z)],Wt.prototype,"startSizeZ"),O([m(Z)],Wt.prototype,"startSpeed");class Ap{constructor(){a(this,"cycleCount"),a(this,"maxCount"),a(this,"minCount"),a(this,"probability"),a(this,"repeatInterval"),a(this,"time"),a(this,"count"),a(this,"_performed",0)}reset(){this._performed=0}run(e){if(e<=this.time)return 0;let t=0;if(this.cycleCount===0||this._performed<this.cycleCount){const s=this.time+this.repeatInterval*this._performed;if(e>=s&&(this._performed+=1,Math.random()<this.probability))switch(this.count.mode){case 0:t=this.count.constant;break;case 3:t=W.lerp(this.count.constantMin,this.count.constantMax,Math.random());break;case 1:t=this.count.curve.evaluate(Math.random());break;case 2:const o=Math.random();t=W.lerp(this.count.curveMin.evaluate(o),this.count.curveMax.evaluate(o),Math.random());break}}return t}}class eo{constructor(){a(this,"enabled"),a(this,"bursts"),a(this,"rateOverTime"),a(this,"rateOverTimeMultiplier"),a(this,"rateOverDistance"),a(this,"rateOverDistanceMultiplier"),a(this,"system")}get burstCount(){var e;return((e=this.bursts)==null?void 0:e.length)??0}reset(){var e;(e=this.bursts)==null||e.forEach(t=>t.reset())}getBurst(){let e=0;if(this.burstCount>0)for(let t=0;t<this.burstCount;t++){const s=this.bursts[t];this.system.main.loop&&s.time>=this.system.time&&s.reset(),e+=Math.round(s.run(this.system.time))}return e}}O([m()],eo.prototype,"enabled"),O([m()],eo.prototype,"bursts"),O([m(Z)],eo.prototype,"rateOverTime"),O([m()],eo.prototype,"rateOverTimeMultiplier"),O([m(Z)],eo.prototype,"rateOverDistance"),O([m()],eo.prototype,"rateOverDistanceMultiplier");class Ip{constructor(){a(this,"enabled"),a(this,"color")}}O([m(sa)],Ip.prototype,"color");class na{constructor(){a(this,"enabled"),a(this,"separateAxes"),a(this,"size"),a(this,"sizeMultiplier"),a(this,"x"),a(this,"xMultiplier"),a(this,"y"),a(this,"yMultiplier"),a(this,"z"),a(this,"zMultiplier"),a(this,"_time",0),a(this,"_temp",new S)}evaluate(e,t,s){if(t||(t=this._temp),!this.enabled)return t.x=t.y=t.z=1,t;if(this.separateAxes)t.x=this.x.evaluate(e,s)*this.xMultiplier,t.y=this.y.evaluate(e,s)*this.yMultiplier,t.z=this.z.evaluate(e,s)*this.zMultiplier;else{const o=this.size.evaluate(e,s)*this.sizeMultiplier;t.x=o}return t}}O([m(Z)],na.prototype,"size"),O([m(Z)],na.prototype,"x"),O([m(Z)],na.prototype,"y"),O([m(Z)],na.prototype,"z");var tr;const nt=(tr=class{constructor(){a(this,"shapeType",5),a(this,"enabled",!0),a(this,"alignToDirection",!1),a(this,"angle",0),a(this,"arc",360),a(this,"arcSpread"),a(this,"arcSpeedMultiplier"),a(this,"arcMode"),a(this,"boxThickness"),a(this,"position"),a(this,"rotation"),a(this,"_rotation",new Dt),a(this,"scale"),a(this,"radius"),a(this,"radiusThickness"),a(this,"sphericalDirectionAmount"),a(this,"randomDirectionAmount"),a(this,"randomPositionAmount"),a(this,"meshShapeType"),a(this,"meshRenderer"),a(this,"_meshObj"),a(this,"_meshGeometry"),a(this,"system"),a(this,"_space"),a(this,"_worldSpaceMatrix",new se),a(this,"_worldSpaceMatrixInverse",new se),a(this,"_vector",new S(0,0,0)),a(this,"_temp",new S(0,0,0)),a(this,"_triangle",new LP),a(this,"_dir",new S),a(this,"_loopTime",0),a(this,"_loopDirection",1),Tp&&console.log(this)}get type(){return Ep[this.shapeType]}initialize(n){this.onInitialize(n),n.position.x=this._vector.x,n.position.y=this._vector.y,n.position.z=this._vector.z}toJSON(){return this}clone(){return new tr}setMesh(n){this.meshRenderer=n,n?(this._meshObj=n.sharedMeshes[Math.floor(Math.random()*n.sharedMeshes.length)],this._meshGeometry=this._meshObj.geometry):(this._meshObj=void 0,this._meshGeometry=void 0)}update(n,e){}onUpdate(n,e,t,s){this.system=n,this._space=t,t===1&&(this._worldSpaceMatrix.copy(s.matrixWorld),this._worldSpaceMatrix.elements[0]=1,this._worldSpaceMatrix.elements[5]=1,this._worldSpaceMatrix.elements[10]=1,this._worldSpaceMatrixInverse.copy(this._worldSpaceMatrix).invert())}applyRotation(n){const e=this.rotation.x!==0||this.rotation.y!==0||this.rotation.z!==0;return e&&(this._rotation.x=W.toRadians(this.rotation.x),this._rotation.y=W.toRadians(this.rotation.y),this._rotation.z=W.toRadians(this.rotation.z),this._rotation.order="ZYX",n.applyEuler(this._rotation)),e}onInitialize(n){this._vector.set(0,0,0),n.mesh=void 0,n.mesh_geometry=void 0;const e=this._temp.copy(this.position),t=this._space===1;t&&e.applyQuaternion(this.system.worldQuaternion);let s=this.radius;if(t&&(s*=this.system.worldScale.x),this.enabled){switch(this.shapeType){case 5:Tp&&$.DrawWireBox(this.position,this.scale,14540253,1),this._vector.x=Math.random()*this.scale.x-this.scale.x/2,this._vector.y=Math.random()*this.scale.y-this.scale.y/2,this._vector.z=Math.random()*this.scale.z-this.scale.z/2,this._vector.add(e);break;case 4:this.randomConePoint(this.position,this.angle,s,this.radiusThickness,this.arc,this.arcMode,this._vector);break;case 0:this.randomSpherePoint(this.position,s,this.radiusThickness,this.arc,this._vector);break;case 10:this.randomCirclePoint(this.position,s,this.radiusThickness,this.arc,this._vector);break;case 13:const o=this.meshRenderer;o?.destroyed==!1&&this.setMesh(o);const r=n.mesh=this._meshObj,l=n.mesh_geometry=this._meshGeometry;if(r&&l)switch(this.meshShapeType){case 0:{const c=l.getAttribute("position"),h=Math.floor(Math.random()*c.count);this._vector.fromBufferAttribute(c,h),this._vector.applyMatrix4(r.matrixWorld),n.mesh_normal=h}break;case 1:break;case 2:{const c=l.index;if(c){let h=Math.random(),d=Math.random();h+d>1&&(h=1-h,d=1-d);const u=Math.floor(Math.random()*(c.count/3));let p=u*3,g=u*3+1,f=u*3+2;p=c.getX(p),g=c.getX(g),f=c.getX(f);const y=l.getAttribute("position");this._triangle.a.fromBufferAttribute(y,p),this._triangle.b.fromBufferAttribute(y,g),this._triangle.c.fromBufferAttribute(y,f),this._vector.set(0,0,0).addScaledVector(this._triangle.a,h).addScaledVector(this._triangle.b,d).addScaledVector(this._triangle.c,1-(h+d)),this._vector.applyMatrix4(r.matrixWorld),n.mesh_normal=u}}break}break;default:this._vector.set(0,0,0),F()&&!globalThis.__particlesystem_shapetype_unsupported&&(console.warn("ParticleSystem ShapeType is not supported:",Ep[this.shapeType]),globalThis.__particlesystem_shapetype_unsupported=!0);break}this.randomizePosition(this._vector,this.randomPositionAmount)}this.applyRotation(this._vector),t&&(this._vector.applyQuaternion(this.system.worldQuaternion),this._vector.add(this.system.worldPos)),Tp&&$.DrawSphere(this._vector,.03,16711680,.5,!0)}getDirection(n,e){var t;if(!this.enabled)return this._dir.set(0,0,1),this._dir;switch(this.shapeType){case 5:this._dir.set(0,0,1);break;case 4:this._dir.set(0,0,1);break;case 10:case 0:const s=e.x,o=e.y,r=e.z;this._dir.set(s,o,r),(t=this.system)!=null&&t.worldspace?this._dir.sub(this.system.worldPos):this._dir.sub(this.position);break;case 13:const l=n.mesh,c=n.mesh_geometry;if(l&&c)switch(this.meshShapeType){case 0:{const h=c.getAttribute("normal"),d=n.mesh_normal;this._dir.fromBufferAttribute(h,d)}break;case 1:break;case 2:{const h=c.index;if(h){const d=n.mesh_normal,u=h.getX(d*3),p=h.getX(d*3+1),g=h.getX(d*3+2),f=c.getAttribute("position"),y=q(),v=q(),b=q();y.fromBufferAttribute(f,u),v.fromBufferAttribute(f,p),b.fromBufferAttribute(f,g),y.sub(v),b.sub(v),y.cross(b),this._dir.copy(y).multiplyScalar(-1);const _=Se(l);this._dir.applyQuaternion(_)}}break}break;default:this._dir.set(0,0,1);break}return this._space===1&&this._dir.applyQuaternion(this.system.worldQuaternion),this.applyRotation(this._dir),this._dir.normalize(),this.spherizeDirection(this._dir,this.sphericalDirectionAmount),this.randomizeDirection(this._dir,this.randomDirectionAmount),Tp&&($.DrawSphere(e,.01,8925952,.5,!0),$.DrawDirection(e,this._dir,8925952,.5,!0)),this._dir}randomizePosition(n,e){if(e<=0)return;const t=tr._tempVec;t.set(Math.random()*2-1,Math.random()*2-1,Math.random()*2-1),t.x*=e*this.scale.x,t.y*=e*this.scale.y,t.z*=e*this.scale.z,n.add(t)}randomizeDirection(n,e){if(e===0)return;const t=tr._randomQuat,s=tr._tempVec;s.set(Math.random()-.5,Math.random()-.5,Math.random()-.5).normalize(),t.setFromAxisAngle(s,e*Math.random()*Math.PI),n.applyQuaternion(t)}spherizeDirection(n,e){if(e===0)return;const t=Math.random()*Math.PI*2,s=Math.acos(1-Math.random()*2),o=Math.sin(s)*Math.cos(t),r=Math.sin(s)*Math.sin(t),l=Math.cos(s),c=new S(o,r,l);n.lerp(c,e)}randomSpherePoint(n,e,t,s,o){const r=Math.random(),l=Math.random(),c=2*Math.PI*r*(s/360),h=Math.acos(2*l-1),d=W.lerp(1,1-Math.pow(1-Math.random(),Math.PI),t)*e,u=n.x+this.scale.x*(-d*Math.sin(h)*Math.cos(c)),p=n.y+this.scale.y*(d*Math.sin(h)*Math.sin(c)),g=n.z+this.scale.z*(d*Math.cos(h));o.x=u,o.y=p,o.z=g}randomCirclePoint(n,e,t,s,o){const r=Math.random(),l=2*Math.PI*r*(s/360),c=W.lerp(1,1-Math.pow(1-Math.random(),Math.PI),t)*e,h=n.x+this.scale.x*c*Math.cos(l),d=n.y+this.scale.y*c*Math.sin(l),u=n.z;o.x=h,o.y=d,o.z=u}randomConePoint(n,e,t,s,o,r,l){let c=0,h=0;switch(r){case 0:c=Math.random(),h=Math.random();break;case 2:this._loopTime>1&&(this._loopDirection=-1),this._loopTime<0&&(this._loopDirection=1);case 1:c=.5,h=Math.random(),this._loopTime+=this.system.deltaTime*this._loopDirection;break}let d=2*Math.PI*c*(o/360);switch(r){case 2:case 1:d+=Math.PI+.5,d+=this._loopTime*Math.PI*2,d%=W.toRadians(o);break}const u=Math.acos(2*h-1),p=W.lerp(1,1-Math.pow(1-Math.random(),Math.PI),s)*t,g=n.x+-p*Math.sin(u)*Math.cos(d),f=n.y+p*Math.sin(u)*Math.sin(d),y=n.z;l.x=g*this.scale.x,l.y=f*this.scale.y,l.z=y*this.scale.z}},a(tr,"_randomQuat",new V),a(tr,"_tempVec",new S),tr);O([m()],nt.prototype,"shapeType"),O([m()],nt.prototype,"enabled"),O([m()],nt.prototype,"alignToDirection"),O([m()],nt.prototype,"angle"),O([m()],nt.prototype,"arc"),O([m()],nt.prototype,"arcSpread"),O([m()],nt.prototype,"arcSpeedMultiplier"),O([m()],nt.prototype,"arcMode"),O([m(S)],nt.prototype,"boxThickness"),O([m(S)],nt.prototype,"position"),O([m(S)],nt.prototype,"rotation"),O([m(S)],nt.prototype,"scale"),O([m()],nt.prototype,"radius"),O([m()],nt.prototype,"radiusThickness"),O([m()],nt.prototype,"sphericalDirectionAmount"),O([m()],nt.prototype,"randomDirectionAmount"),O([m()],nt.prototype,"randomPositionAmount"),O([m()],nt.prototype,"meshShapeType"),O([m(Qc)],nt.prototype,"meshRenderer");let xy=nt;class Ce{constructor(){a(this,"damping"),a(this,"enabled"),a(this,"frequency"),a(this,"octaveCount"),a(this,"octaveMultiplier"),a(this,"octaveScale"),a(this,"positionAmount"),a(this,"quality"),a(this,"remap"),a(this,"remapEnabled"),a(this,"remapMultiplier"),a(this,"remapX"),a(this,"remapXMultiplier"),a(this,"remapY"),a(this,"remapYMultiplier"),a(this,"remapZ"),a(this,"remapZMultiplier"),a(this,"scrollSpeedMultiplier"),a(this,"separateAxes"),a(this,"strengthMultiplier"),a(this,"strengthX"),a(this,"strengthXMultiplier"),a(this,"strengthY"),a(this,"strengthYMultiplier"),a(this,"strengthZ"),a(this,"strengthZMultiplier"),a(this,"_noise"),a(this,"_time",0),a(this,"_temp",new S)}update(e){this._time+=e.time.deltaTime*this.scrollSpeedMultiplier}apply(e,t,s,o,r,l){if(!this.enabled)return;this._noise||(this._noise=bO(()=>0));const c=this._temp.set(t.x,t.y,t.z).multiplyScalar(this.frequency),h=this._noise(c.x,c.y,c.z,this._time),d=this._noise(c.x,c.y,c.z,this._time+1e3*this.frequency),u=this._noise(c.x,c.y,c.z,this._time+2e3*this.frequency);this._temp.set(h,d,u).normalize();const p=r/l;let g=this.positionAmount.evaluate(p);this.separateAxes?(this._temp.x*=g*this.strengthXMultiplier,this._temp.y*=g*this.strengthYMultiplier,this._temp.z*=g*this.strengthZMultiplier):(this.strengthX&&(g*=this.strengthX.evaluate(p)*1.5),this._temp.multiplyScalar(g)),s.x+=this._temp.x,s.y+=this._temp.y,s.z+=this._temp.z}}O([m()],Ce.prototype,"damping"),O([m()],Ce.prototype,"enabled"),O([m()],Ce.prototype,"frequency"),O([m()],Ce.prototype,"octaveCount"),O([m()],Ce.prototype,"octaveMultiplier"),O([m()],Ce.prototype,"octaveScale"),O([m(Z)],Ce.prototype,"positionAmount"),O([m()],Ce.prototype,"quality"),O([m(Z)],Ce.prototype,"remap"),O([m()],Ce.prototype,"remapEnabled"),O([m()],Ce.prototype,"remapMultiplier"),O([m(Z)],Ce.prototype,"remapX"),O([m()],Ce.prototype,"remapXMultiplier"),O([m(Z)],Ce.prototype,"remapY"),O([m()],Ce.prototype,"remapYMultiplier"),O([m(Z)],Ce.prototype,"remapZ"),O([m()],Ce.prototype,"remapZMultiplier"),O([m()],Ce.prototype,"scrollSpeedMultiplier"),O([m()],Ce.prototype,"separateAxes"),O([m()],Ce.prototype,"strengthMultiplier"),O([m(Z)],Ce.prototype,"strengthX"),O([m()],Ce.prototype,"strengthXMultiplier"),O([m(Z)],Ce.prototype,"strengthY"),O([m()],Ce.prototype,"strengthYMultiplier"),O([m(Z)],Ce.prototype,"strengthZ"),O([m()],Ce.prototype,"strengthZMultiplier");class We{constructor(){a(this,"enabled"),a(this,"attachRibbonToTransform",!1),a(this,"colorOverLifetime"),a(this,"colorOverTrail"),a(this,"dieWithParticles",!0),a(this,"inheritParticleColor",!0),a(this,"lifetime"),a(this,"lifetimeMultiplier"),a(this,"minVertexDistance",.2),a(this,"mode",0),a(this,"ratio",1),a(this,"ribbonCount",1),a(this,"shadowBias",0),a(this,"sizeAffectsLifetime",!1),a(this,"sizeAffectsWidth",!1),a(this,"splitSubEmitterRibbons",!1),a(this,"textureMode",0),a(this,"widthOverTrail"),a(this,"widthOverTrailMultiplier"),a(this,"worldSpace",!1)}getWidth(e,t,s,o){const r=this.widthOverTrail.evaluate(s,o);return e*=r,e}getColor(e,t,s){const o=this.colorOverTrail.evaluate(s),r=this.colorOverLifetime.evaluate(t);e.x*=o.r*r.r,e.y*=o.g*r.g,e.z*=o.b*r.b,"alpha"in o&&"alpha"in r&&(e.w*=o.alpha*r.alpha)}}O([m()],We.prototype,"enabled"),O([m()],We.prototype,"attachRibbonToTransform"),O([m(sa)],We.prototype,"colorOverLifetime"),O([m(sa)],We.prototype,"colorOverTrail"),O([m()],We.prototype,"dieWithParticles"),O([m()],We.prototype,"inheritParticleColor"),O([m(Z)],We.prototype,"lifetime"),O([m()],We.prototype,"lifetimeMultiplier"),O([m()],We.prototype,"minVertexDistance"),O([m()],We.prototype,"mode"),O([m()],We.prototype,"ratio"),O([m()],We.prototype,"ribbonCount"),O([m()],We.prototype,"shadowBias"),O([m()],We.prototype,"sizeAffectsLifetime"),O([m()],We.prototype,"sizeAffectsWidth"),O([m()],We.prototype,"splitSubEmitterRibbons"),O([m()],We.prototype,"textureMode"),O([m(Z)],We.prototype,"widthOverTrail"),O([m()],We.prototype,"widthOverTrailMultiplier"),O([m()],We.prototype,"worldSpace");class qe{constructor(){a(this,"enabled"),a(this,"space",0),a(this,"orbitalX"),a(this,"orbitalY"),a(this,"orbitalZ"),a(this,"orbitalXMultiplier"),a(this,"orbitalYMultiplier"),a(this,"orbitalZMultiplier"),a(this,"orbitalOffsetX"),a(this,"orbitalOffsetY"),a(this,"orbitalOffsetZ"),a(this,"speedModifier"),a(this,"speedModifierMultiplier"),a(this,"x"),a(this,"xMultiplier"),a(this,"y"),a(this,"yMultiplier"),a(this,"z"),a(this,"zMultiplier"),a(this,"_system"),a(this,"_temp",new S),a(this,"_temp2",new S),a(this,"_temp3",new S),a(this,"_hasOrbital",!1),a(this,"_index",0),a(this,"_orbitalMatrix",new se)}update(e){this._system=e}init(e){this._index==0&&(e.debug=!0),this._index+=1,e.orbitx=this.orbitalX.evaluate(Math.random()),e.orbity=this.orbitalY.evaluate(Math.random()),e.orbitz=this.orbitalZ.evaluate(Math.random()),this._hasOrbital=e.orbitx!=0||e.orbity!=0||e.orbitz!=0}apply(e,t,s,o,r,l,c){var h;if(!this.enabled)return;const d=l/c,u=this.speedModifier.evaluate(d)*this.speedModifierMultiplier,p=this.x.evaluate(d),g=this.y.evaluate(d),f=this.z.evaluate(d);if(this._temp.set(-p,g,f),this._system&&this._system.main.simulationSpace===1&&this._temp.applyQuaternion(this._system.worldQuaternion),this._hasOrbital&&((h=this._system)==null?void 0:h.worldPos)){const y=this._temp2.set(s.x,s.y,s.z),v=this.orbitalXMultiplier,b=this.orbitalYMultiplier,_=this.orbitalZMultiplier,w=u*Math.PI*2*10,x=Math.cos(w*v),k=Math.sin(w*v),M=Math.cos(w*b),T=Math.sin(w*b),L=Math.cos(w*_),D=Math.sin(w*_),z=y.x*(M*L)+y.y*(M*D)+y.z*-T,j=y.x*(k*T*L-x*D)+y.y*(k*T*D+x*L)+y.z*(k*M),H=y.x*(x*T*L+k*D)+y.y*(x*T*D-k*L)+y.z*(x*M),K=this._temp3.set(y.x-z,y.y-j,y.z-H);K.normalize(),K.multiplyScalar(.2/r*Math.max(this.orbitalXMultiplier,this.orbitalYMultiplier,this.orbitalZMultiplier)),o.x+=K.x,o.y+=K.y,o.z+=K.z}o.x+=this._temp.x,o.y+=this._temp.y,o.z+=this._temp.z,o.x*=u,o.y*=u,o.z*=u}}O([m()],qe.prototype,"enabled"),O([m()],qe.prototype,"space"),O([m(Z)],qe.prototype,"orbitalX"),O([m(Z)],qe.prototype,"orbitalY"),O([m(Z)],qe.prototype,"orbitalZ"),O([m()],qe.prototype,"orbitalXMultiplier"),O([m()],qe.prototype,"orbitalYMultiplier"),O([m()],qe.prototype,"orbitalZMultiplier"),O([m()],qe.prototype,"orbitalOffsetX"),O([m()],qe.prototype,"orbitalOffsetY"),O([m()],qe.prototype,"orbitalOffsetZ"),O([m(Z)],qe.prototype,"speedModifier"),O([m()],qe.prototype,"speedModifierMultiplier"),O([m(Z)],qe.prototype,"x"),O([m()],qe.prototype,"xMultiplier"),O([m(Z)],qe.prototype,"y"),O([m()],qe.prototype,"yMultiplier"),O([m(Z)],qe.prototype,"z"),O([m()],qe.prototype,"zMultiplier");class Vt{constructor(){a(this,"animation"),a(this,"enabled"),a(this,"cycleCount"),a(this,"frameOverTime"),a(this,"frameOverTimeMultiplier"),a(this,"numTilesX"),a(this,"numTilesY"),a(this,"startFrame"),a(this,"startFrameMultiplier"),a(this,"rowMode"),a(this,"rowIndex"),a(this,"spriteCount"),a(this,"timeMode")}sampleOnceAtStart(){if(this.timeMode===0)switch(this.frameOverTime.mode){case 0:case 3:case 2:case 1:return!0}return!1}getStartIndex(){return this.sampleOnceAtStart()?Math.random()*(this.numTilesX*this.numTilesY):0}evaluate(e){if(!this.sampleOnceAtStart())return this.getIndex(e)}getIndex(e){const t=this.numTilesX*this.numTilesY;e=e*this.cycleCount;let s=this.frameOverTime.evaluate(e%1);return s*=this.frameOverTimeMultiplier,s*=t,s=s%t,s=Math.floor(s),s}}O([m()],Vt.prototype,"animation"),O([m()],Vt.prototype,"enabled"),O([m()],Vt.prototype,"cycleCount"),O([m(Z)],Vt.prototype,"frameOverTime"),O([m()],Vt.prototype,"frameOverTimeMultiplier"),O([m()],Vt.prototype,"numTilesX"),O([m()],Vt.prototype,"numTilesY"),O([m(Z)],Vt.prototype,"startFrame"),O([m()],Vt.prototype,"startFrameMultiplier"),O([m()],Vt.prototype,"rowMode"),O([m()],Vt.prototype,"rowIndex"),O([m()],Vt.prototype,"spriteCount"),O([m()],Vt.prototype,"timeMode");class Es{constructor(){a(this,"enabled"),a(this,"separateAxes"),a(this,"x"),a(this,"xMultiplier"),a(this,"y"),a(this,"yMultiplier"),a(this,"z"),a(this,"zMultiplier")}evaluate(e,t){return this.enabled?this.separateAxes?0:this.z.evaluate(e,t)*-1:0}}O([m()],Es.prototype,"enabled"),O([m()],Es.prototype,"separateAxes"),O([m(Z)],Es.prototype,"x"),O([m()],Es.prototype,"xMultiplier"),O([m(Z)],Es.prototype,"y"),O([m()],Es.prototype,"yMultiplier"),O([m(Z)],Es.prototype,"z"),O([m()],Es.prototype,"zMultiplier");class hs{constructor(){a(this,"enabled"),a(this,"range"),a(this,"separateAxes"),a(this,"x"),a(this,"xMultiplier"),a(this,"y"),a(this,"yMultiplier"),a(this,"z"),a(this,"zMultiplier")}evaluate(e,t){if(!this.enabled)return 0;if(!this.separateAxes){const s=W.lerp(this.range.x,this.range.y,t);return this.z.evaluate(s)*-1}return 0}}O([m()],hs.prototype,"enabled"),O([m()],hs.prototype,"range"),O([m()],hs.prototype,"separateAxes"),O([m(Z)],hs.prototype,"x"),O([m()],hs.prototype,"xMultiplier"),O([m(Z)],hs.prototype,"y"),O([m()],hs.prototype,"yMultiplier"),O([m(Z)],hs.prototype,"z"),O([m()],hs.prototype,"zMultiplier");class gt{constructor(){a(this,"enabled"),a(this,"dampen"),a(this,"drag"),a(this,"dragMultiplier"),a(this,"limit"),a(this,"limitMultiplier"),a(this,"separateAxes"),a(this,"limitX"),a(this,"limitXMultiplier"),a(this,"limitY"),a(this,"limitYMultiplier"),a(this,"limitZ"),a(this,"limitZMultiplier"),a(this,"multiplyDragByParticleSize",!1),a(this,"multiplyDragByParticleVelocity",!1),a(this,"space"),a(this,"_temp",new S),a(this,"_temp2",new S)}apply(e,t,s,o,r,l,c){if(this.enabled){const h=this.limit.evaluate(r)*this.limitMultiplier;if(t.length()>h){this._temp.copy(t).normalize().multiplyScalar(h);const d=this.dampen*.5;t.x=W.lerp(t.x,this._temp.x,d),t.y=W.lerp(t.y,this._temp.y,d),t.z=W.lerp(t.z,this._temp.z,d),s.x=W.lerp(s.x,this._temp.x,d),s.y=W.lerp(s.y,this._temp.y,d),s.z=W.lerp(s.z,this._temp.z,d)}}}}O([m()],gt.prototype,"enabled"),O([m()],gt.prototype,"dampen"),O([m(Z)],gt.prototype,"drag"),O([m()],gt.prototype,"dragMultiplier"),O([m(Z)],gt.prototype,"limit"),O([m()],gt.prototype,"limitMultiplier"),O([m()],gt.prototype,"separateAxes"),O([m(Z)],gt.prototype,"limitX"),O([m()],gt.prototype,"limitXMultiplier"),O([m(Z)],gt.prototype,"limitY"),O([m()],gt.prototype,"limitYMultiplier"),O([m(Z)],gt.prototype,"limitZ"),O([m()],gt.prototype,"limitZMultiplier"),O([m()],gt.prototype,"multiplyDragByParticleSize"),O([m()],gt.prototype,"multiplyDragByParticleVelocity"),O([m()],gt.prototype,"space");const fh=class MC{constructor(){a(this,"enabled"),a(this,"curve"),a(this,"curveMultiplier"),a(this,"mode"),a(this,"system"),a(this,"_temp",new S),a(this,"_firstUpdate",!0),a(this,"_frames",0)}clone(){var e;const t=new MC;return t.enabled=this.enabled,t.curve=(e=this.curve)==null?void 0:e.clone(),t.curveMultiplier=this.curveMultiplier,t.mode=this.mode,t}get _lastWorldPosition(){return this.system._iv_lastWorldPosition||(this.system._iv_lastWorldPosition=new S),this.system._iv_lastWorldPosition}get _velocity(){return this.system._iv_velocity||(this.system._iv_velocity=new S),this.system._iv_velocity}awake(e){this.system=e,this.reset()}reset(){this._firstUpdate=!0}update(e){this.enabled&&this.system.worldspace!==!1&&(this._firstUpdate?(this._firstUpdate=!1,this._velocity.set(0,0,0),this._lastWorldPosition.copy(this.system.worldPos)):this._lastWorldPosition&&(this._velocity.copy(this.system.worldPos).sub(this._lastWorldPosition).multiplyScalar(1/this.system.deltaTime),this._lastWorldPosition.copy(this.system.worldPos)))}applyInitial(e){if(this.enabled&&this.system.worldspace!==!1&&this.mode===0){const t=this.curve.evaluate(Math.random(),Math.random());this._temp.copy(this._velocity).multiplyScalar(t),e.x+=this._temp.x,e.y+=this._temp.y,e.z+=this._temp.z}}applyCurrent(e,t,s){if(this.enabled&&this.system&&this.system.worldspace!==!1&&this.mode===1){const o=this.curve.evaluate(t,s);this._temp.copy(this._velocity).multiplyScalar(o),e.x+=this._temp.x,e.y+=this._temp.y,e.z+=this._temp.z}}};O([m()],fh.prototype,"enabled"),O([m(Z)],fh.prototype,"curve"),O([m()],fh.prototype,"curveMultiplier"),O([m()],fh.prototype,"mode");let Sy=fh;class bi{constructor(){a(this,"enabled"),a(this,"range"),a(this,"separateAxes"),a(this,"size"),a(this,"sizeMultiplier"),a(this,"x"),a(this,"xMultiplier"),a(this,"y"),a(this,"yMultiplier"),a(this,"z"),a(this,"zMultiplier")}evaluate(e,t,s,o){const r=e.length(),l=W.remap(r,this.range.x,this.range.y,0,1),c=this.size.evaluate(l,s);return o.x*=c,o.y*=c,o.z*=c,o}}O([m()],bi.prototype,"enabled"),O([m(re)],bi.prototype,"range"),O([m()],bi.prototype,"separateAxes"),O([m(Z)],bi.prototype,"size"),O([m()],bi.prototype,"sizeMultiplier"),O([m(Z)],bi.prototype,"x"),O([m()],bi.prototype,"xMultiplier"),O([m(Z)],bi.prototype,"y"),O([m()],bi.prototype,"yMultiplier"),O([m(Z)],bi.prototype,"z"),O([m()],bi.prototype,"zMultiplier");class Pl{constructor(){a(this,"enabled"),a(this,"range"),a(this,"color")}evaluate(e,t,s){const o=e.length(),r=W.remap(o,this.range.x,this.range.y,0,1),l=this.color.evaluate(r,t);s.x*=l.r,s.y*=l.g,s.z*=l.b,"alpha"in l&&(s.w*=l.alpha)}}O([m()],Pl.prototype,"enabled"),O([m(re)],Pl.prototype,"range"),O([m(sa)],Pl.prototype,"color"),new S(1,1,1),new S(0,0,1);class Cy{constructor(e,t,s,o){a(this,"type","NeedleParticleSubEmitter"),a(this,"emitterType"),a(this,"emitterProbability"),a(this,"q_",new V),a(this,"v_",new S),a(this,"v2_",new S),a(this,"_emitterMatrix",new Hm),a(this,"_circularBuffer"),this.system=e,this.particleSystem=t,this.subSystem=s,this.subParticleSystem=o,this.subParticleSystem&&this.subParticleSystem&&(this.subParticleSystem.onlyUsedByOther=!0);const r=1e3;this._circularBuffer=new Oi(()=>new Hm,r)}clone(){throw new Error("Method not implemented.")}initialize(e){e.emissionState={burstIndex:0,burstWaveIndex:0,time:0,waitEmiting:0},this._emitterMatrix.copy(this.subSystem.matrixWorld).invert().premultiply(this.system.matrixWorld),this._emitterMatrix.setPosition(0,0,0),this.emitterType===Py.Birth&&this.run(e)}update(e,t){this.run(e)}frameUpdate(e){}toJSON(){}reset(){}run(e){if(this.subSystem.currentParticles>=this.subSystem.main.maxParticles||!this.subParticleSystem||!e.emissionState||this.emitterProbability&&Math.random()>this.emitterProbability)return;const t=this.system.deltaTime;if(this.emitterType===Py.Death){let o=e.life;if(e[Ol]!==void 0&&(o=e[Ol]),!(e.age+t*1.2>=o))return;const r=this.subSystem.main.maxParticles-this.subSystem.currentParticles;e.emissionState.waitEmiting=r}const s=new Hm;s.set(1,0,0,e.position.x,0,1,0,e.position.y,0,0,1,e.position.z,0,0,0,1),this.particleSystem.worldSpace||s.multiplyMatrices(this._emitterMatrix,s),this.subParticleSystem.emit(t,e.emissionState,s)}}var p2=Object.defineProperty,Ve=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&p2(e,t,o),o};const ir=C("debugparticles"),m2=C("noprogressive"),g2=C("debugprogressive");var Py=(n=>(n[n.Birth=0]="Birth",n[n.Collision=1]="Collision",n[n.Death=2]="Death",n[n.Trigger=3]="Trigger",n[n.Manual=4]="Manual",n))(Py||{});class ds extends I{constructor(){super(...arguments),a(this,"renderMode"),a(this,"particleMaterial"),a(this,"trailMaterial"),a(this,"particleMesh"),a(this,"maxParticleSize"),a(this,"minParticleSize"),a(this,"velocityScale"),a(this,"cameraVelocityScale"),a(this,"lengthScale")}start(){if(this.maxParticleSize!==.5&&this.minParticleSize!==0&&F()){const e=`ParticleSystem "${this.name}" has non-default min/max particle size. This may not render correctly. Please set min size to 0 and the max size to 0.5 and use the "StartSize" setting instead`;console.warn(e)}}get transparent(){var e;return((e=this.particleMaterial)==null?void 0:e.transparent)??!1}getMaterial(e=!1){let t=e===!0&&this.trailMaterial?this.trailMaterial:this.particleMaterial;if(t){if(t.type==="MeshStandardMaterial"){ir&&console.debug("ParticleSystemRenderer.getMaterial: MeshStandardMaterial detected, converting to MeshBasicMaterial. See https://github.com/Alchemist0823/three.quarks/issues/101"),"map"in t&&t.map&&(t.map.colorSpace=On,t.map.premultiplyAlpha=!1);const s=new Me;s.copy(t),e?this.trailMaterial=s:this.particleMaterial=s}t.map&&(t.map.colorSpace=On,t.map.premultiplyAlpha=!1),e&&t.side===fo&&(t=t.clone(),t.side=wd,e?this.trailMaterial=t:this.particleMaterial=t)}return t&&!m2&&t._didRequestTextureLOD===void 0&&(t._didRequestTextureLOD=0,g2&&console.log("Load material LOD",t.name),Xe.assignTextureLOD(t,0)),t}getMesh(e){let t=null;if(!t&&(this.particleMesh instanceof G&&(t=this.particleMesh.geometry),t===null)){t=new Ns(1,1);const s=t.attributes.uv;for(let o=0;o<s.count;o++)s.setX(o,1-s.getX(o))}return new G(t,this.getMaterial())}}Ve([m()],ds.prototype,"renderMode"),Ve([m(Pe)],ds.prototype,"particleMaterial"),Ve([m(Pe)],ds.prototype,"trailMaterial"),Ve([m()],ds.prototype,"maxParticleSize"),Ve([m()],ds.prototype,"minParticleSize"),Ve([m()],ds.prototype,"velocityScale"),Ve([m()],ds.prototype,"cameraVelocityScale"),Ve([m()],ds.prototype,"lengthScale");class Lp{constructor(e,t=1){a(this,"_curve"),a(this,"_factor"),a(this,"type","function"),this._curve=e,this._factor=t}startGen(e){}genValue(e,t){return this._curve.evaluate(t,Math.random())*this._factor}toJSON(){throw new Error("Method not implemented.")}clone(){throw new Error("Method not implemented.")}}class Oy{constructor(e){a(this,"type","value"),a(this,"system"),this.system=e}toJSON(){throw new Error("Method not implemented.")}clone(){throw new Error("Method not implemented.")}startGen(e){}}class f2 extends Oy{genValue(){return this.system.textureSheetAnimation.getStartIndex()}}class y2 extends Oy{constructor(){super(...arguments),a(this,"_lastPosition",new S),a(this,"_lastDistance",0)}update(){const e=ee(this.system.gameObject);this._lastDistance=this._lastPosition.distanceTo(e),this._lastPosition.copy(e)}genValue(){if(!this.system.isPlaying||!this.system.emission.enabled||this.system.currentParticles>=this.system.maxParticles)return 0;let e=this.system.emission.rateOverTime.evaluate(this.system.time/this.system.duration,Math.random());if(this.system.deltaTime>0){const o=this.system.emission.rateOverDistance.evaluate(this.system.time/this.system.duration,Math.random());let r=this._lastDistance/this.system.deltaTime*o;Number.isFinite(r)||(r=0),e+=r}const t=this.system.emission.getBurst();t>0&&(e+=t/this.system.deltaTime);const s=this.system.maxParticles-this.system.currentParticles;return W.clamp(e,0,s/this.system.deltaTime)}}class v2 extends Oy{genValue(){return this.system.isPlaying,0}}class sr{constructor(e){a(this,"system"),a(this,"type"),this.type=Object.getPrototypeOf(this).constructor.name||"ParticleSystemBaseBehaviour",e&&(this.system=e)}get context(){return this.system.context}initialize(e){}update(e,t){}frameUpdate(e){}toJSON(){throw new Error("Method not implemented.")}clone(){throw new Error("Method not implemented.")}reset(){}}class b2 extends sr{constructor(){super(...arguments),a(this,"type","NeedleTextureSheet")}update(e,t){const s=this.system.textureSheetAnimation;if(s.enabled){const o=e.age/e.life,r=s.evaluate(o);r!==void 0&&(e.uvTile=r)}}}const aS=Symbol("particleRotation");class _2 extends sr{constructor(){super(...arguments),a(this,"type","NeedleRotation")}initialize(e){e[aS]=Math.random()}update(e,t){if(e.rotation===void 0)return;const s=e.age/e.life;if(typeof e.rotation=="number"&&(this.system.rotationOverLifetime.enabled?e.rotation+=this.system.rotationOverLifetime.evaluate(s,e[aS])*t:this.system.renderer.renderMode===Zn.Billboard&&(e.rotation=Math.PI),this.system.rotationBySpeed.enabled)){const o=e.velocity.length();e.rotation+=this.system.rotationBySpeed.evaluate(s,o)*t}}}const lS=Symbol("sizeLerpFactor"),w2=new S;class x2 extends sr{constructor(){super(...arguments),a(this,"type","NeedleSize"),a(this,"_minSize",0),a(this,"_maxSize",1)}initialize(e){e[lS]=Math.random(),this._minSize=this.system.renderer.minParticleSize,this._maxSize=this.system.renderer.maxParticleSize}update(e,t){const s=e.age/e.life;let o=1;this.system.sizeOverLifetime.enabled&&(o*=this.system.sizeOverLifetime.evaluate(s,void 0,e[lS]).x);let r=1;this.system.renderer.renderMode!==Zn.Mesh&&(r=this.system.worldScale.x/this.system.cameraScale);const l=q(e.startSize).multiplyScalar(o*r);if(e.size.set(l.x,l.y,l.z),this.system.localspace){const c=pS(this.system,w2);e.size.x*=c.x,e.size.y*=c.y,e.size.z*=c.z}}}const Ol=Symbol("particleLife"),ky=Symbol("trailLifetime"),cS=Symbol("trailStartLength"),My=Symbol("trailWidthRandom");class S2 extends sr{constructor(){super(...arguments),a(this,"type","NeedleTrail")}initialize(e){e instanceof Zv&&(e[Ol]=e.life,this.system.trails.enabled&&this.system.trails.dieWithParticles===!1&&(e[ky]=this.system.trails.lifetime.evaluate(Math.random(),Math.random()),e.life+=e[ky]),e[cS]=e.length,e[My]=Math.random())}update(e){var t;if((t=this.system.trails)!=null&&t.enabled&&e instanceof Zv){const s=e,o=e.age/e[Ol],r=e.previous.values(),l=e.previous.length;for(let c=0;c<l;c++){const h=r.next().value,d=1-c/(l-1),u=e.size;if(u.x<=0&&!this.system.trails.sizeAffectsWidth){const p=20*this.system.trails.widthOverTrail.evaluate(.5,s[My]);u.x=p,u.y=p,u.z=p}h.size=this.system.trails.getWidth(u.x,o,d,s[My]),h.color.copy(e.color),this.system.trails.getColor(h.color,o,d)}if(e.age>e[Ol]){e.velocity.set(0,0,0);const c=(e.age-e[Ol])/e[ky];s.length=W.lerp(e[cS],0,c)}}}}const jp=Symbol("startVelocity"),hS=Symbol("gravityModifier"),Ry=Symbol("gravitySpeed"),Dp=Symbol("velocity lerp factor"),Ty=new S;class C2 extends sr{constructor(){super(...arguments),a(this,"type","NeedleVelocity"),a(this,"_gravityDirection",new S)}initialize(e){var t,s;const o=this.system.main.simulationSpeed;e.startSpeed=this.system.main.startSpeed.evaluate(Math.random(),Math.random());const r=this.system.shape.getDirection(e,e.position);e.velocity.x=r.x*e.startSpeed,e.velocity.y=r.y*e.startSpeed,e.velocity.z=r.z*e.startSpeed,(t=this.system.inheritVelocity)!=null&&t.enabled&&this.system.inheritVelocity.applyInitial(e.velocity),e[jp]?e[jp].copy(e.velocity):e[jp]=e.velocity.clone();const l=this.system.main.gravityModifier.evaluate(Math.random(),Math.random());e[hS]=l*o,e[Ry]=l*o*.5,e[Dp]=Math.random(),(s=this.system.velocityOverLifetime)==null||s.init(e),this._gravityDirection.set(0,-1,0),this.system.main.simulationSpace===gh.Local&&this._gravityDirection.applyQuaternion(this.system.worldQuaternionInverted).normalize()}update(e,t){var s;const o=e[jp],r=e[hS];if(r!==0){const g=r*e[Ry];Ty.copy(this._gravityDirection).multiplyScalar(g),e[Ry]+=t*.05,o.add(Ty)}e.velocity.copy(o);const l=e.age/e.life;(s=this.system.inheritVelocity)!=null&&s.enabled&&this.system.inheritVelocity.applyCurrent(e.velocity,l,e[Dp]);const c=this.system.noise;c.enabled&&c.apply(0,e.position,e.velocity,t,e.age,e.life);const h=this.system.sizeBySpeed;h!=null&&h.enabled&&(e.size=h.evaluate(e.velocity,l,e[Dp],e.size));const d=this.system.colorBySpeed;d!=null&&d.enabled&&d.evaluate(e.velocity,e[Dp],e.color);const u=this.system.velocityOverLifetime;u.enabled&&u.apply(e,0,e.position,e.velocity,t,e.age,e.life);const p=this.system.limitVelocityOverLifetime;if(p.enabled&&p.apply(e.position,o,e.velocity,e.size,l,t,1),this.system.worldspace){const g=this.system.worldScale;e.velocity.x*=g.x,e.velocity.y*=g.y,e.velocity.z*=g.z}}}const dS=Symbol("colorLerpFactor"),uS=new he(1,1,1,1),oa=new he(1,1,1,1);class P2 extends sr{constructor(){super(...arguments),a(this,"type","NeedleColor")}initialize(e){}_init(e){const t=this.system.renderer.particleMaterial;oa.copy(this.system.main.startColor.evaluate(Math.random())),t!=null&&t.color&&(uS.copy(t.color),oa.multiply(uS)),oa.convertLinearToSRGB(),e.startColor.set(oa.r,oa.g,oa.b,oa.alpha),e.color.copy(e.startColor),e[dS]=Math.random()}update(e,t){if(e.age===0&&this._init(e),this.system.colorOverLifetime.enabled){const s=e.age/e.life,o=this.system.colorOverLifetime.color.evaluate(s,e[dS]);e.color.set(o.r,o.g,o.b,"alpha"in o?o.alpha:1).multiply(e.startColor)}else e.color.copy(e.startColor)}}class O2{constructor(e){a(this,"system"),a(this,"emission"),a(this,"autoDestroy"),a(this,"startLength"),a(this,"emissionBursts"),a(this,"onlyUsedByOther"),a(this,"behaviors",[]),a(this,"rendererEmitterSettings",{startLength:new CO(220),followLocalOrigin:!1}),a(this,"flatWhiteTexture"),a(this,"clonedTexture",{original:void 0,clone:void 0}),this.system=e,this.emission=new y2(this.system)}get anim(){return this.system.textureSheetAnimation}get prewarm(){return!1}get material(){return this.system.renderer.getMaterial(this.system.trails.enabled)}get layers(){return this.system.gameObject.layers}update(){this.emission.update()}get looping(){return this.system.main.loop}get duration(){return this.system.duration}get shape(){return this.system.shape}get startLife(){return new Lp(this.system.main.startLifetime)}get startSpeed(){return new Lp(this.system.main.startSpeed)}get startRotation(){return new Lp(this.system.main.startRotation)}get startSize(){return new Lp(this.system.main.startSize)}get startColor(){return new xO(new SO(1,1,1,1))}get emissionOverTime(){return this.emission}get emissionOverDistance(){return new v2(this.system)}get instancingGeometry(){return this.system.renderer.getMesh(this.system.renderer.renderMode).geometry}get renderMode(){if(this.system.trails.enabled===!0)return Tn.Trail;switch(this.system.renderer.renderMode){case Zn.Billboard:return Tn.BillBoard;case Zn.Stretch:return Tn.StretchedBillBoard;case Zn.HorizontalBillboard:return Tn.HorizontalBillBoard;case Zn.VerticalBillboard:return Tn.VerticalBillBoard;case Zn.Mesh:return Tn.Mesh}return Tn.BillBoard}get speedFactor(){var e;let t=this.system.main.simulationSpeed;return((e=this.system.renderer)==null?void 0:e.renderMode)===Zn.Stretch&&(t*=this.system.renderer.velocityScale??1),t}get texture(){const e=this.material;if(e&&e.map){const t=e.map;if(this.clonedTexture.original!==t||!this.clonedTexture.clone){const s=t.clone();s.premultiplyAlpha=!1,s.colorSpace=On,this.clonedTexture.original=t,this.clonedTexture.clone=s}return this.clonedTexture.clone}return this.flatWhiteTexture||(this.flatWhiteTexture=Sf(new he(1,1,1,1),1)),this.flatWhiteTexture}get startTileIndex(){return new f2(this.system)}get uTileCount(){var e;return this.anim.enabled?(e=this.anim)==null?void 0:e.numTilesX:void 0}get vTileCount(){var e;return this.anim.enabled?(e=this.anim)==null?void 0:e.numTilesY:void 0}get renderOrder(){return 1}get blending(){var e;return((e=this.system.renderer.particleMaterial)==null?void 0:e.blending)??jP}get transparent(){return this.system.renderer.transparent}get worldSpace(){return this.system.main.simulationSpace===gh.World}}class k2{constructor(){a(this,"burstParticleIndex",0),a(this,"burstParticleCount",0),a(this,"isBursting",!1),a(this,"travelDistance",0),a(this,"previousWorldPos"),a(this,"burstIndex",0),a(this,"burstWaveIndex",0),a(this,"time",0),a(this,"waitEmiting",0)}}const $t=class Cm extends I{constructor(){super(...arguments),a(this,"_state"),a(this,"colorOverLifetime"),a(this,"main"),a(this,"emission"),a(this,"sizeOverLifetime"),a(this,"shape"),a(this,"noise"),a(this,"trails"),a(this,"velocityOverLifetime"),a(this,"limitVelocityOverLifetime"),a(this,"inheritVelocity"),a(this,"colorBySpeed"),a(this,"textureSheetAnimation"),a(this,"rotationOverLifetime"),a(this,"rotationBySpeed"),a(this,"sizeBySpeed"),a(this,"_cameraScale",1),a(this,"__worldQuaternion",new V),a(this,"_worldQuaternionInverted",new V),a(this,"_worldScale",new S),a(this,"_worldPositionFrame",-1),a(this,"_worldPos",new S),a(this,"_renderer"),a(this,"_batchSystem"),a(this,"_particleSystem"),a(this,"_interface"),a(this,"_container"),a(this,"_time",0),a(this,"_isPlaying",!0),a(this,"_isUsedAsSubsystem",!1),a(this,"_didPreWarm",!1),a(this,"_bursts"),a(this,"_subEmitterSystems"),a(this,"_lastBatchesCount",-1)}play(e=!1){var t;e&&P.foreachComponent(this.gameObject,s=>{s instanceof Cm&&s!==this&&s.play(!1)},!0),this._isPlaying=!0,this._particleSystem&&(this._particleSystem.emissionState.time=0,this._particleSystem.emitEnded=!1),(t=this.emission)==null||t.reset()}pause(e=!0){e&&P.foreachComponent(this.gameObject,t=>{t instanceof Cm&&t!==this&&t.pause(!1)},!0),this._isPlaying=!1}stop(e=!0,t=!1){e&&P.foreachComponent(this.gameObject,s=>{s instanceof Cm&&s!==this&&s.stop(!1,t)},!0),this._isPlaying=!1,this._time=0,t&&this.reset()}reset(){var e;this._time=0,this._particleSystem&&(this._particleSystem.particleNum=0,this._particleSystem.emissionState.time=0,this._particleSystem.emitEnded=!1,(e=this.emission)==null||e.reset())}emit(e){if(this._particleSystem){this.onUpdate(),e=Math.min(e,this.maxParticles-this.currentParticles),this._state||(this._state=new k2),this._state.waitEmiting=e,this._state.time=0;const t=this._particleSystem.emitEnded;this._particleSystem.emitEnded=!1,this._particleSystem.emit(this.deltaTime,this._state,this._particleSystem.emitter.matrixWorld),this._particleSystem.emitEnded=t}}get playOnAwake(){return this.main.playOnAwake}set playOnAwake(e){this.main.playOnAwake=e}get renderer(){return this._renderer}get isPlaying(){return this._isPlaying}get currentParticles(){var e;return((e=this._particleSystem)==null?void 0:e.particleNum)??0}get maxParticles(){return this.main.maxParticles}get time(){return this._time}get duration(){return this.main.duration}get deltaTime(){return this.context.time.deltaTime*this.main.simulationSpeed}get scale(){return this.gameObject.scale.x}get cameraScale(){return this._cameraScale}get container(){return this._container}get worldspace(){return this.main.simulationSpace===gh.World}get localspace(){return this.main.simulationSpace===gh.Local}get worldQuaternion(){return this.__worldQuaternion}get worldQuaternionInverted(){return this._worldQuaternionInverted}get worldScale(){return this._worldScale}get worldPos(){return this._worldPositionFrame!==this.context.time.frame&&(this._worldPositionFrame=this.context.time.frame,ee(this.gameObject,this._worldPos)),this._worldPos}get matrixWorld(){return this._container.matrixWorld}get isSubsystem(){return this._isUsedAsSubsystem}addBehaviour(e){return this._particleSystem?(e instanceof sr&&(e.system=this),ir&&console.debug("Add custom ParticleSystem Behaviour",e),this._particleSystem.addBehavior(e),!0):!1}removeBehaviour(e){if(!this._particleSystem)return!1;const t=this._particleSystem.behaviors,s=t.indexOf(e);return s!==-1&&((F()||ir)&&console.debug("Remove custom ParticleSystem Behaviour",s,e),t.splice(s,1)),!0}removeAllBehaviours(){return this._particleSystem?(this._particleSystem.behaviors.length=0,!0):!1}get behaviours(){return this._particleSystem?this._particleSystem.behaviors:null}get particleSystem(){return this._particleSystem??null}set bursts(e){for(let t=0;t<e.length;t++){const s=e[t];if(!(s instanceof Ap)){const o=new Ap;Na(o,s),e[t]=o}}this._bursts=e}set subEmitterSystems(e){for(let t=0;t<e.length;t++){const s=e[t];if(!(s instanceof Bp)){const o=new Bp;Na(o,s),e[t]=o}}ir&&e.length>0&&console.log("SubEmitters: ",e,this),this._subEmitterSystems=e}onAfterDeserialize(e){if(this._subEmitterSystems&&Array.isArray(this._subEmitterSystems))for(const t of this._subEmitterSystems)t._deserialize(this.context,this.gameObject)}awake(){if(this._worldPositionFrame=-1,this._renderer=this.gameObject.getComponent(ds),!this.main)throw new Error("Not Supported: ParticleSystem needs a serialized MainModule. Creating new particle systems at runtime is currently not supported.");this._container=new E,this._container.matrixAutoUpdate=!1,this.context.scene.add(this._container),this._batchSystem=new _O,this._batchSystem.name=this.gameObject.name,this._container.add(this._batchSystem),this._interface=new O2(this),this._particleSystem=new wO(this._interface),this._particleSystem.addBehavior(new x2(this)),this._particleSystem.addBehavior(new P2(this)),this._particleSystem.addBehavior(new b2(this)),this._particleSystem.addBehavior(new _2(this)),this._particleSystem.addBehavior(new C2(this)),this._particleSystem.addBehavior(new S2(this)),this._batchSystem.addSystem(this._particleSystem);const e=this._particleSystem.emitter;this.context.scene.add(e),this.inheritVelocity.system&&this.inheritVelocity.system!==this&&(this.inheritVelocity=this.inheritVelocity.clone()),this.inheritVelocity.awake(this),ir&&(console.log(this),this.gameObject.add(new Ci(1)))}start(){this.addSubParticleSystems(),this.updateLayers(),this.renderer.particleMesh instanceof G&&this._interface.renderMode==Tn.Mesh&&Xe.assignMeshLOD(this.renderer.particleMesh,0).then(e=>{e&&this.particleSystem&&this._interface.renderMode==Tn.Mesh&&(this.particleSystem.instancingGeometry=e)})}onDestroy(){var e,t,s,o;(e=this._container)==null||e.removeFromParent(),(t=this._batchSystem)==null||t.removeFromParent(),(s=this._particleSystem)==null||s.emitter.removeFromParent(),(o=this._particleSystem)==null||o.dispose()}onEnable(){this.main&&(this.inheritVelocity&&(this.inheritVelocity.system=this),this._batchSystem&&(this._batchSystem.visible=!0),this.playOnAwake&&this.play(),this._isPlaying=this.playOnAwake)}onDisable(){this._batchSystem&&(this._batchSystem.visible=!1)}onBeforeRender(){var e;this.main&&(this._didPreWarm===!1&&((e=this.main)==null?void 0:e.prewarm)===!0&&(this._didPreWarm=!0,this.preWarm()),this.onUpdate(),this.onSimulate(this.deltaTime))}preWarm(){var e;if(!((e=this.emission)!=null&&e.enabled)||this.emission.rateOverTime.getMax()<=0)return;const t=1/60,s=this.main.duration,o=this.main.startLifetime.getMax(),r=Math.min(Math.max(s,o)/Math.max(.01,this.main.simulationSpeed),1e3),l=Math.ceil(r/t),c=Date.now();ir&&console.log(`Particles ${this.name} - Prewarm for ${l} frames (${r} sec). Duration: ${s}, Lifetime: ${o}`);for(let h=0;h<l&&!(this.currentParticles>=this.maxParticles);h++){const d=Date.now()-c;if(d>2e3){console.warn(`Particles ${this.name} - Prewarm took too long. Aborting: ${d}`);break}this.onUpdate(),this.onSimulate(t)}}onSimulate(e){if(this._batchSystem){let t=this.context.time.frameCount%60===0;this._lastBatchesCount!==this._batchSystem.batches.length&&(this._lastBatchesCount=this._batchSystem.batches.length,t=!0),t&&this.updateLayers(),this._batchSystem.update(e)}this._time+=e,this._time>this.duration&&(this._time=0)}updateLayers(){if(this._batchSystem)for(let e=0;e<this._batchSystem.batches.length;e++){const t=this._batchSystem.batches[e];t.layers.disableAll();const s=this.layer;t.layers.mask=1<<s}}onUpdate(){var e,t;if(this._bursts&&(this.emission.bursts=this._bursts,delete this._bursts),!this._isPlaying)return;const s=this.context.mainCamera;if(s){const l=Ge(s);this._cameraScale=l.x}const o=!this.worldspace,r=this.gameObject;if(Se(r,this.__worldQuaternion),this._worldQuaternionInverted.copy(this.__worldQuaternion).invert(),Ge(this.gameObject,this._worldScale),o&&this._container&&(e=this.gameObject)!=null&&e.parent){const l=pS(this,Ty);this._container.matrix.makeScale(l.x,l.y,l.z),this._container.matrix.makeRotationFromQuaternion(this.__worldQuaternion),this._container.matrix.setPosition(this.worldPos),this._container.matrix.scale(this.gameObject.scale)}this.emission.system=this,this._interface.update(),this.shape.onUpdate(this,this.context,this.main.simulationSpace,this.gameObject),this.noise.update(this.context),(t=this.inheritVelocity)==null||t.update(this.context),this.velocityOverLifetime.update(this)}addSubParticleSystems(){var e;if(this._subEmitterSystems&&this._particleSystem)for(const t of this._subEmitterSystems){t.particleSystem&&(t.particleSystem.__internalAwake?t.particleSystem.__internalAwake():F()&&console.warn("SubParticleSystem serialization issue(?)",t.particleSystem,t));const s=(e=t.particleSystem)==null?void 0:e._particleSystem;if(s){t.particleSystem._isUsedAsSubsystem=!0;const o=new Cy(this,this._particleSystem,t.particleSystem,s);o.emitterType=t.type,o.emitterProbability=t.emitProbability,this._particleSystem.addBehavior(o)}else ir&&console.warn("Could not add SubParticleSystem",t,this)}}};Ve([m(Ip)],$t.prototype,"colorOverLifetime"),Ve([m(Wt)],$t.prototype,"main"),Ve([m(eo)],$t.prototype,"emission"),Ve([m(na)],$t.prototype,"sizeOverLifetime"),Ve([m(xy)],$t.prototype,"shape"),Ve([m(Ce)],$t.prototype,"noise"),Ve([m(We)],$t.prototype,"trails"),Ve([m(qe)],$t.prototype,"velocityOverLifetime"),Ve([m(gt)],$t.prototype,"limitVelocityOverLifetime"),Ve([m(Sy)],$t.prototype,"inheritVelocity"),Ve([m(Pl)],$t.prototype,"colorBySpeed"),Ve([m(Vt)],$t.prototype,"textureSheetAnimation"),Ve([m(Es)],$t.prototype,"rotationOverLifetime"),Ve([m(hs)],$t.prototype,"rotationBySpeed"),Ve([m(bi)],$t.prototype,"sizeBySpeed");let yh=$t;class Bp{constructor(){a(this,"particleSystem"),a(this,"emitProbability",1),a(this,"properties"),a(this,"type")}_deserialize(e,t){const s=this.particleSystem;if(s instanceof yh)return;let o="";s&&typeof s.guid=="string"&&(o=s.guid,this.particleSystem=P.findByGuid(o,t)),ir&&!(this.particleSystem instanceof yh)&&console.warn("Could not find particle system for sub emitter",o,t,this)}}function pS(n,e){if(e.set(1,1,1),n.gameObject.parent&&n.localspace)switch(n.main.scalingMode){case wy.Local:e=Ge(n.gameObject.parent,e),e.x=1/e.x,e.y=1/e.y,e.z=1/e.z;break;default:if(!n.unsupported_scaling_mode){n.unsupported_scaling_mode=!0;const t="ParticleSystem scale mode "+wy[n.main.scalingMode]+" is not supported";F()&&be(t),console.warn(t,n.name,n)}e=Ge(n.gameObject,e);break}return e}class Nl extends I{constructor(){super(...arguments),a(this,"_didAssignPlayerColor",!1),a(this,"tryAssignColor",()=>{const e=P.getComponentInParent(this.gameObject,Ms);if(e&&e.owner)return this._didAssignPlayerColor=!0,this.assignUserColor(e.owner),!0;const t=P.getComponentInParent(this.gameObject,hi);return t!=null&&t.connectionId?(this._didAssignPlayerColor=!0,this.assignUserColor(t.connectionId),!0):!1})}onEnable(){this.context.connection.beginListen(ie.JoinedRoom,this.tryAssignColor),this._didAssignPlayerColor||this.startCoroutine(this.waitForConnection())}onDisable(){this.context.connection.stopListen(ie.JoinedRoom,this.tryAssignColor)}*waitForConnection(){for(;!this.destroyed&&this.activeAndEnabled&&(yield wf(.2),!this.tryAssignColor()););}assignUserColor(e){const t=Nl.hashCode(e),s=Nl.colorFromHashCode(t);if(this.gameObject.type==="Mesh"){const o=this.gameObject;this.assignColor(s,e,o)}else if(this.gameObject.children)for(const o of this.gameObject.children){const r=o;r.material&&r.material.color&&this.assignColor(s,e,r)}}assignColor(e,t,s){let o=s.material;o&&(o._playerMaterial!==t&&(o=o.clone(),o._playerMaterial=t,s.material=o),o.color=e)}static hashCode(e){var t=0,s,o;if(e.length===0)return t;for(s=0;s<e.length;s++)o=e.charCodeAt(s),t=(t<<5)-t+o,t|=0;return t}static colorFromHashCode(e){const t=(e&16711680)>>16,s=(e&65280)>>8,o=e&255;return new oe(t/255,s/255,o/255)}}const vh=C("debugpost");let Ey=null;function M2(n){Ey=n}function mS(n){let e=n.gameObject;for(;e;){for(const t of hu(e))if(t.isPostProcessingManager===!0)return t;e=e.parent}return null}function R2(n){let e=mS(n);if(!e)if(Ey){vh&&console.warn("Adding postprocessing manager to the scene.");const t=n.scene;e=Ei(t,Ey)}else F()&&console.warn("No post processing manager found");return e}const ft={AT_START:-1e4,NormalPass:0,DepthDownsamplingPass:10,SSAO:20,SMAA:30,TiltShift:40,DepthOfField:50,ChromaticAberration:60,Bloom:70,Vignette:80,Pixelation:90,ToneMapping:100,HueSaturation:110,BrightnessContrast:120,Sharpening:130,AT_END:1e4};let ot=null;function T2(n){vh==="verbose"&&console.debug("Before ordering effects",[...n]),ot||(ot=new Map,ot.set(A.POSTPROCESSING.MODULE.NormalPass,ft.NormalPass),ot.set(A.POSTPROCESSING.MODULE.DepthDownsamplingPass,ft.DepthDownsamplingPass),ot.set(A.POSTPROCESSING.MODULE.SMAAEffect,ft.SMAA),ot.set(A.POSTPROCESSING.MODULE.SSAOEffect,ft.SSAO),ot.set(A.POSTPROCESSING_AO.MODULE.N8AOPostPass,ft.SSAO),ot.set(A.POSTPROCESSING_AO.MODULE.N8AOPass,ft.SSAO),ot.set(A.POSTPROCESSING.MODULE.TiltShiftEffect,ft.TiltShift),ot.set(A.POSTPROCESSING.MODULE.DepthOfFieldEffect,ft.DepthOfField),ot.set(A.POSTPROCESSING.MODULE.ChromaticAberrationEffect,ft.ChromaticAberration),ot.set(A.POSTPROCESSING.MODULE.BloomEffect,ft.Bloom),ot.set(A.POSTPROCESSING.MODULE.SelectiveBloomEffect,ft.Bloom),ot.set(A.POSTPROCESSING.MODULE.VignetteEffect,ft.Vignette),ot.set(A.POSTPROCESSING.MODULE.PixelationEffect,ft.Pixelation),ot.set(A.POSTPROCESSING.MODULE.ToneMappingEffect,ft.ToneMapping),ot.set(A.POSTPROCESSING.MODULE.HueSaturationEffect,ft.HueSaturation),ot.set(A.POSTPROCESSING.MODULE.BrightnessContrastEffect,ft.BrightnessContrast)),n.sort((e,t)=>{const s=typeof e.priority=="number"?e.priority:ot.get(e.effect.constructor)??Number.NEGATIVE_INFINITY,o=typeof t.priority=="number"?t.priority:ot.get(t.effect.constructor)??Number.NEGATIVE_INFINITY;return s===Number.NEGATIVE_INFINITY?(vh&&console.warn("Unknown effect found: ",e.constructor.name,e),1):o===Number.NEGATIVE_INFINITY?(vh&&console.warn("Unknown effect found: ",t.constructor.name,t),-1):s-o}),vh==="verbose"&&console.debug("After ordering effects",[...n])}var E2=Object.defineProperty,A2=Object.getOwnPropertyDescriptor,gS=(n,e,t,s)=>{for(var o=A2(e,t),r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&E2(e,t,o),o};const I2=C("debugpost");class N{constructor(e){a(this,"isVolumeParameter",!0),a(this,"_isInitialized",!1),a(this,"_active",!0),a(this,"_value"),a(this,"_valueRaw"),a(this,"_defaultValue"),a(this,"valueProcessor"),a(this,"onValueChanged"),e!==void 0&&this.initialize(e)}get isInitialized(){return this._isInitialized}initialize(e){e!==void 0&&(this._value=e,this._defaultValue=e,this._valueRaw=e,this._isInitialized=!0)}get overrideState(){return this._active}set overrideState(e){if(this._active===e)return;this._active=e;const t=e?this._valueRaw:this._defaultValue;this.processValue(t,!0)}get value(){return this._valueRaw}set value(e){this.isInitialized||this.initialize(e),this.processValue(e,!1)}set defaultValue(e){this._defaultValue=e}__init(){this.processValue(this._valueRaw,!0)}processValue(e,t){if(e==null||!t&&this.testIfValueChanged(e)===!1)return;const s=this._value;I2&&typeof s=="number"&&typeof e=="number"&&(s?.toFixed(4),e?.toFixed(4)),!this._active&&this._defaultValue!==void 0?(this._value=this._defaultValue,e=this._defaultValue,this._valueRaw=e):(this._valueRaw=e,this._active&&this.valueProcessor&&(e=this.valueProcessor(e)),this._value=e),this.onValueChanged&&this.onValueChanged(e,s,this)}testIfValueChanged(e){return this._valueRaw!==e}}gS([m()],N.prototype,"overrideState"),gS([m()],N.prototype,"value");class L2 extends es{constructor(){super([N])}onSerialize(e,t){}onDeserialize(e,t){const s=t.target,o=t.path;let r;if(s&&o&&(r=s[o]),(typeof r!="object"||typeof r=="object"&&r.isVolumeParameter!==!0)&&(r=new N),typeof e=="object"&&"value"in e){const l=e.value;r.initialize(l),r.overrideState=e.overrideState}else r.value=e;return r}}new L2;var j2=Object.defineProperty,D2=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&j2(e,t,o),o};const Ay=C("debugpost");class rt extends I{constructor(e=void 0){if(super(),a(this,"order"),a(this,"active",!0),a(this,"_manager",null),a(this,"_result"),a(this,"_postprocessingContext",null),e)for(const t of Object.keys(e)){const s=e[t],o=this[t];o instanceof N?o.initialize(s):o!==void 0&&(this[t]=s)}}get isPostProcessingEffect(){return!0}onEnable(){super.onEnable(),Ay&&console.warn("Enable",this.constructor.name+(this.__internalDidAwakeAndStart?"":" (awake)")),this.__internalDidAwakeAndStart&&(this.active=!0),this.onEffectEnabled()}onDisable(){var e;super.onDisable(),Ay&&console.warn("Disable",this.constructor.name),(e=this._manager)==null||e.removeEffect(this),this.active=!1}onEffectEnabled(e){e&&e.isPostProcessingManager===!0?this._manager=e:this._manager||(this._manager=R2(this)),this._manager.addEffect(this),this._manager.dirty=!0}init(){}get postprocessingContext(){return this._postprocessingContext}apply(e){var t;return this._postprocessingContext=e,this._result||(this.initParameters(),this._result=(t=this.onCreateEffect)==null?void 0:t.call(this)),this._result&&this.initParameters(),this._result}unapply(){}dispose(){Ay&&console.warn("DISPOSE",this),this._result&&(Array.isArray(this._result)?this._result.forEach(e=>e.dispose()):this._result.dispose()),this._result=void 0}initParameters(){const e=Object.keys(this);for(const t of e){const s=this[t];s instanceof N&&s.__init()}}onEditorModification(e){const t=e.propertyName;if(this[t]instanceof N){const s=e.value;return this[t].value=s,!0}}}D2([m()],rt.prototype,"active");var B2=Object.defineProperty,F2=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&B2(e,t,o),o};const U2=C("debugpost"),Iy={};function us(n,e){Iy[n]=e}function z2(n){return n.__type in Iy?Iy[n.__type]:(U2&&n.__type&&console.warn("Unknown postprocessing type",n.__type,n),rt)}class Fp{constructor(){a(this,"components",[])}__init(e){var t;(t=this.components)==null||t.forEach(s=>{s.gameObject===void 0&&e.gameObject.addComponent(s),s.init()})}addEffect(e){this.components.push(e)}removeEffect(e){const t=this.components.indexOf(e);t>=0&&this.components.splice(t,1)}}F2([Dr([n=>z2(n),rt])],Fp.prototype,"components");var N2=Object.defineProperty,W2=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&N2(e,t,o),o};const V2=C("debugpost");class bh extends rt{constructor(){super(...arguments),a(this,"preset",new N(2))}get typeName(){return"Antialiasing"}onCreateEffect(){var e;const t=new A.POSTPROCESSING.MODULE.SMAAEffect({preset:((e=this.preset)==null?void 0:e.value)??A.POSTPROCESSING.MODULE.SMAAPreset.HIGH,edgeDetectionMode:A.POSTPROCESSING.MODULE.EdgeDetectionMode.LUMA});return this.preset.onValueChanged=s=>{V2&&console.log("Antialiasing preset changed to",s),t.applyPreset(s)},t}}W2([m(N)],bh.prototype,"preset"),us("Antialiasing",bh);var $2=Object.defineProperty,Ly=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&$2(e,t,o),o},Up;const zp=(Up=class extends rt{constructor(){super(...arguments),a(this,"threshold",new N(.9)),a(this,"intensity",new N(1)),a(this,"scatter",new N(.7)),a(this,"selectiveBloom")}get typeName(){return"Bloom"}init(){this.threshold.valueProcessor=n=>n,this.intensity.valueProcessor=n=>n,this.scatter.valueProcessor=n=>n}onCreateEffect(){let n;if(this.selectiveBloom==null&&(this.selectiveBloom=Up.useSelectiveBloom),this.selectiveBloom){const e=n=new A.POSTPROCESSING.MODULE.SelectiveBloomEffect(this.context.scene,this.context.mainCamera,{blendFunction:A.POSTPROCESSING.MODULE.BlendFunction.ADD,mipmapBlur:!0,luminanceThreshold:this.threshold.value,luminanceSmoothing:this.scatter.value,radius:.85,intensity:this.intensity.value});e.inverted=!0}else n=new A.POSTPROCESSING.MODULE.BloomEffect({blendFunction:A.POSTPROCESSING.MODULE.BlendFunction.ADD,mipmapBlur:!0,luminanceThreshold:this.threshold.value,luminanceSmoothing:this.scatter.value,radius:.85,intensity:this.intensity.value});return this.intensity.onValueChanged=e=>{n.intensity=e},this.threshold.onValueChanged=e=>{n.luminanceMaterial.threshold=Math.pow(e,2.2)},this.scatter.onValueChanged=e=>{n.luminancePass.enabled=!0,n.luminanceMaterial.smoothing=e,n.mipmapBlurPass&&(n.mipmapBlurPass.radius=Cn.lerp(.1,.9,e))},n}},a(Up,"useSelectiveBloom",!1),Up);Ly([m(N)],zp.prototype,"threshold"),Ly([m(N)],zp.prototype,"intensity"),Ly([m(N)],zp.prototype,"scatter");let Np=zp;us("Bloom",Np);var H2=Object.defineProperty,G2=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&H2(e,t,o),o};class _h extends rt{constructor(){super(...arguments),a(this,"intensity",new N(0))}get typeName(){return"ChromaticAberration"}onCreateEffect(){const e=new A.POSTPROCESSING.MODULE.ChromaticAberrationEffect;return e.offset=new re(0,0),e.radialModulation=!0,e.modulationOffset=.15,this.intensity.valueProcessor=t=>t*.02,this.intensity.onValueChanged=t=>{e.offset.x=-t,e.offset.y=t},e}}G2([m(N)],_h.prototype,"intensity"),us("ChromaticAberration",_h);var wh=(n=>(n[n.None=0]="None",n[n.Neutral=1]="Neutral",n[n.ACES=2]="ACES",n[n.AgX=3]="AgX",n[n.KhronosNeutral=4]="KhronosNeutral",n))(wh||{});const fS=new Map;function jy(n){switch(n){case 0:return Um;case 1:return Fm;case 2:return vd;case 3:return yd;case 4:return Pa;default:return fS.has(n)||(fS.set(n,!0),console.warn("[Postprocessing] Unknown tone mapping mode",n)),Pa}}function q2(n){switch(n){case Um:return 0;case vd:return 2;case yd:return 3;case Pa:return 1;case Fm:return 1;default:return 0}}function Wp(n){switch(n){case Um:return A.POSTPROCESSING.MODULE.ToneMappingMode.LINEAR;case vd:return A.POSTPROCESSING.MODULE.ToneMappingMode.ACES_FILMIC;case yd:return A.POSTPROCESSING.MODULE.ToneMappingMode.AGX;case Pa:return A.POSTPROCESSING.MODULE.ToneMappingMode.NEUTRAL;case Fm:return A.POSTPROCESSING.MODULE.ToneMappingMode.REINHARD;default:return A.POSTPROCESSING.MODULE.ToneMappingMode.LINEAR}}var X2=Object.defineProperty,yS=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&X2(e,t,o),o};const Dy=C("debugpost");class nr extends rt{constructor(){super(...arguments),a(this,"mode",new N(void 0)),a(this,"exposure",new N(1)),a(this,"_tonemappingEffect",null)}get typeName(){return"ToneMapping"}setMode(e){const t=wh[e];return t===void 0?(console.error("[PostProcessing] Invalid ToneMapping mode",e),this):(this.mode.value=t,this)}get isToneMapping(){return!0}onEffectEnabled(){const e=mS(this);e&&super.onEffectEnabled(e)}onCreateEffect(){var e;if(this.mode.isInitialized==!1){const o=q2(this.context.renderer.toneMapping);Dy&&console.log("[PostProcessing] Initializing ToneMapping mode to renderer.toneMapping",this.context.renderer.toneMapping+" \u2192 "+o),this.mode.initialize(o)}(e=this._tonemappingEffect)==null||e.dispose();const t=jy(this.mode.value),s=this._tonemappingEffect=new A.POSTPROCESSING.MODULE.ToneMappingEffect({mode:Wp(t)});return this.mode.onValueChanged=o=>{if(typeof o=="string")o=Gw(o),s.mode=Wp(o);else{const r=jy(o);s.mode=Wp(r)}s.name="ToneMapping ("+wh[o]+")",Dy&&console.log("[PostProcessing] ToneMapping mode changed to",wh[o],t,s.mode)},Dy&&console.log("[PostProcessing] Use ToneMapping",wh[this.mode.value],t,s.mode,"renderer.tonemapping: "+this.context.renderer.toneMapping),s}onBeforeRender(){var e;if(this._tonemappingEffect&&(e=this.postprocessingContext)!=null&&e.handler.getEffectIsActive(this._tonemappingEffect)&&(this.mode.overrideState&&(this.context.renderer.toneMapping=jy(this.mode.value)),this.exposure.overrideState&&this.exposure.value!==void 0)){const t=Math.max(.01,this.exposure.value);this.context.renderer.toneMappingExposure=t}}}yS([m(N)],nr.prototype,"mode"),yS([m(N)],nr.prototype,"exposure"),us("Tonemapping",nr);var Q2=Object.defineProperty,Vp=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&Q2(e,t,o),o};class or extends rt{constructor(){super(...arguments),a(this,"remap",!0),a(this,"postExposure",new N(1)),a(this,"contrast",new N(0)),a(this,"hueShift",new N(0)),a(this,"saturation",new N(0))}get typeName(){return"ColorAdjustments"}init(){this.postExposure.valueProcessor=e=>(this.remap&&(e=Math.pow(2,e)),e),this.contrast.valueProcessor=e=>{if(!this.remap)return e;let t=1;return e>0?t=200:e<0&&(t=100),e/t},this.contrast.defaultValue=0,this.hueShift.valueProcessor=e=>this.remap?Math.PI*e/180:e,this.hueShift.defaultValue=0,this.saturation.valueProcessor=e=>this.remap?e<0?e/100:e/(100*Math.PI):e,this.saturation.defaultValue=0}onCreateEffect(){var e,t;const s=[];let o=(e=this.postprocessingContext)==null?void 0:e.components.find(c=>c instanceof nr);o||(o=new nr,(t=this.postprocessingContext)==null||t.components.push(o)),this.postExposure.onValueChanged=c=>{this.postExposure.overrideState&&o?o.exposure.value=c:console.warn("[PostProcessing] PostExposure is set to override but no ToneMappingEffect found in the postprocessing stack. Please add a ToneMappingEffect to your postprocessing stack to use PostExposure.")};const r=new A.POSTPROCESSING.MODULE.BrightnessContrastEffect;this.contrast.onValueChanged=c=>r.contrast=c;const l=new A.POSTPROCESSING.MODULE.HueSaturationEffect;return this.hueShift.onValueChanged=c=>l.hue=c,this.saturation.onValueChanged=c=>l.saturation=c,s.push(r),s.push(l),s}}Vp([m(N)],or.prototype,"postExposure"),Vp([m(N)],or.prototype,"contrast"),Vp([m(N)],or.prototype,"hueShift"),Vp([m(N)],or.prototype,"saturation"),us("ColorAdjustments",or);var Y2=Object.defineProperty,ra=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&Y2(e,t,o),o};const K2=C("debugpost");class As extends rt{constructor(){super(...arguments),a(this,"mode"),a(this,"focusDistance",new N(1)),a(this,"focalLength",new N(.2)),a(this,"aperture",new N(20)),a(this,"gaussianMaxRadius",new N),a(this,"resolutionScale",new N(1/window.devicePixelRatio)),a(this,"bokehScale",new N)}get typeName(){return"DepthOfField"}init(){this.focalLength.valueProcessor=t=>{const s=t/300;return W.lerp(2,.01,s)};const e=20;this.aperture.valueProcessor=t=>{const s=1-t/32;return W.lerp(1,e,s)}}onCreateEffect(){if(this.mode===0){K2&&console.warn("DepthOfField: Mode is set to Off");return}const e=new A.POSTPROCESSING.MODULE.DepthOfFieldEffect(this.context.mainCamera,{worldFocusRange:.2,focalLength:1,bokehScale:20,resolutionScale:this.resolutionScale.value});return this.focusDistance.onValueChanged=t=>{e.cocMaterial.worldFocusDistance=t},this.focalLength.onValueChanged=t=>e.cocMaterial.worldFocusRange=t,this.aperture.onValueChanged=t=>e.bokehScale=t,this.resolutionScale&&(this.resolutionScale.onValueChanged=t=>e.resolution.scale=t),[e]}unapply(){}}ra([m()],As.prototype,"mode"),ra([m(N)],As.prototype,"focusDistance"),ra([m(N)],As.prototype,"focalLength"),ra([m(N)],As.prototype,"aperture"),ra([m(N)],As.prototype,"gaussianMaxRadius"),ra([m(N)],As.prototype,"resolutionScale"),ra([m(N)],As.prototype,"bokehScale"),us("DepthOfField",As);class xh extends rt{constructor(e){super(),a(this,"effect"),this.effect=e}get typeName(){return this.effect.constructor.name}onCreateEffect(){return this.effect}}var Z2=Object.defineProperty,J2=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&Z2(e,t,o),o};class Sh extends rt{constructor(){super(...arguments),a(this,"granularity",new N(10))}get typeName(){return"PixelationEffect"}onCreateEffect(){const e=new A.POSTPROCESSING.MODULE.PixelationEffect;return this.granularity.onValueChanged=t=>{e.granularity=t},e}}J2([m(N)],Sh.prototype,"granularity"),us("PixelationEffect",Sh);var eI=Object.defineProperty,Ch=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&eI(e,t,o),o};class to extends rt{constructor(){super(...arguments),a(this,"intensity",new N(2)),a(this,"falloff",new N(1)),a(this,"samples",new N(9)),a(this,"color",new N(new oe(0,0,0))),a(this,"luminanceInfluence",new N(.7)),a(this,"_ssao")}get typeName(){return"ScreenSpaceAmbientOcclusion"}onBeforeRender(){if(this._ssao&&this.context.mainCamera instanceof we){const e=this.context.mainCamera.far-this.context.mainCamera.near;this._ssao.ssaoMaterial.worldDistanceFalloff=e*.01,this._ssao.ssaoMaterial.worldDistanceThreshold=this.context.mainCamera.far}}onCreateEffect(){const e=this.context.mainCamera,t=new A.POSTPROCESSING.MODULE.NormalPass(this.context.scene,e),s=new A.POSTPROCESSING.MODULE.DepthDownsamplingPass({normalBuffer:t.texture,resolutionScale:.5}),o=this._ssao=new A.POSTPROCESSING.MODULE.SSAOEffect(e,t.texture,{normalDepthBuffer:s.texture,worldDistanceThreshold:1,worldDistanceFalloff:1,worldProximityThreshold:.1,worldProximityFalloff:2,intensity:1,blendFunction:A.POSTPROCESSING.MODULE.BlendFunction.MULTIPLY,luminanceInfluence:.5});this.intensity.onValueChanged=l=>{o.intensity=l},this.falloff.onValueChanged=l=>{o.ssaoMaterial.radius=l*.1},this.samples.onValueChanged=l=>{o.ssaoMaterial.samples=l},this.color.onValueChanged=l=>{o.color||(o.color=new oe),o.color.copy(l)},this.luminanceInfluence.onValueChanged=l=>{o.luminanceInfluence=l};const r=new Array;return r.push(t),r.push(s),r.push(o),r}}Ch([m(N)],to.prototype,"intensity"),Ch([m(N)],to.prototype,"falloff"),Ch([m(N)],to.prototype,"samples"),Ch([m(N)],to.prototype,"color"),Ch([m(N)],to.prototype,"luminanceInfluence"),us("ScreenSpaceAmbientOcclusion",to);var tI=Object.defineProperty,aa=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&tI(e,t,o),o};const iI=C("debugN8AO");var By=(n=>(n[n.Performance=0]="Performance",n[n.Low=1]="Low",n[n.Medium=2]="Medium",n[n.High=3]="High",n[n.Ultra=4]="Ultra",n))(By||{});class Is extends rt{constructor(){super(...arguments),a(this,"gammaCorrection",!0),a(this,"aoRadius",new N(1)),a(this,"falloff",new N(1)),a(this,"intensity",new N(1)),a(this,"color",new N(new oe(0,0,0))),a(this,"screenspaceRadius",!1),a(this,"quality",2),a(this,"_ssao")}get typeName(){return"ScreenSpaceAmbientOcclusionN8"}get pass(){return this._ssao}onValidate(){this._ssao&&(this._ssao.setQualityMode(By[this.quality]),this._ssao.configuration.gammaCorrection=this.gammaCorrection,this._ssao.configuration.screenSpaceRadius=this.screenspaceRadius)}onCreateEffect(){const e=this.context.mainCamera,t=this.context.domWidth,s=this.context.domHeight,o=this._ssao=new A.POSTPROCESSING_AO.MODULE.N8AOPostPass(this.context.scene,e,t,s);o.name="SSAO_N8";const r=By[this.quality];o.setQualityMode(r),o.configuration.transparencyAware=!1;const l=new $s(t,s);return o.configuration.beautyRenderTarget=l,o.configuration.autoRenderBeauty=!1,o.configuration.gammaCorrection=this.gammaCorrection,o.configuration.screenSpaceRadius=this.screenspaceRadius,iI&&(o.enableDebugMode(),console.log(o),setInterval(()=>{console.log("SSAO",o.lastTime)},1e3),setInterval(()=>{console.log("SSAO",o.enabled,{ssao:o,autoRenderBeauty:o.configuration.autoRenderBeauty})},4e3)),this.intensity.onValueChanged=c=>{o.configuration.intensity=c},this.falloff.onValueChanged=c=>{o.configuration.distanceFalloff=c},this.aoRadius.onValueChanged=c=>{o.configuration.aoRadius=c},this.color.onValueChanged=c=>{o.color||(o.color=new oe),o.configuration.color.copy(c)},o}}aa([Tt(),m()],Is.prototype,"gammaCorrection"),aa([m(N)],Is.prototype,"aoRadius"),aa([m(N)],Is.prototype,"falloff"),aa([m(N)],Is.prototype,"intensity"),aa([m(N)],Is.prototype,"color"),aa([Tt(),m()],Is.prototype,"screenspaceRadius"),aa([Tt(),m()],Is.prototype,"quality"),us("ScreenSpaceAmbientOcclusionN8",Is);var sI=Object.defineProperty,nI=Object.getOwnPropertyDescriptor,vS=(n,e,t,s)=>{for(var o=nI(e,t),r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&sI(e,t,o),o};class Ph extends rt{constructor(){super(...arguments),a(this,"order",ft.Sharpening),a(this,"_effect"),a(this,"_amount",1),a(this,"_radius",1)}get typeName(){return"Sharpening"}onCreateEffect(){return this._effect??(this._effect=new(oI())),this.effect}get effect(){return this._effect}set amount(e){this._amount=e,this._effect&&(this._effect.uniforms.get("amount").value=e)}get amount(){return this._effect?this._effect.uniforms.get("amount").value:this._amount}set radius(e){this._radius=e,this._effect&&(this._effect.uniforms.get("radius").value=e)}get radius(){return this._effect?this._effect.uniforms.get("radius").value:this._radius}}vS([m()],Ph.prototype,"amount"),vS([m()],Ph.prototype,"radius");function oI(){const n=`
|
|
1274
1274
|
void mainSupport() {
|
|
1275
1275
|
vUv = uv;
|
|
1276
1276
|
gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
|
|
@@ -1314,11 +1314,14 @@ axisFormat %s
|
|
|
1314
1314
|
outputColor = sharp;
|
|
1315
1315
|
}
|
|
1316
1316
|
|
|
1317
|
-
`;class t extends A.POSTPROCESSING.MODULE.Effect{constructor(){super("Sharpening",e,{vertexShader:n,blendFunction:A.POSTPROCESSING.MODULE.BlendFunction.NORMAL,uniforms:new Map([["amount",new Qi(1)],["radius",new Qi(1)]]),attributes:RO.CONVOLUTION})}}return t}var
|
|
1317
|
+
`;class t extends A.POSTPROCESSING.MODULE.Effect{constructor(){super("Sharpening",e,{vertexShader:n,blendFunction:A.POSTPROCESSING.MODULE.BlendFunction.NORMAL,uniforms:new Map([["amount",new Qi(1)],["radius",new Qi(1)]]),attributes:RO.CONVOLUTION})}}return t}var rI=Object.defineProperty,kl=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&rI(e,t,o),o};class yn extends rt{constructor(){super(...arguments),a(this,"offset",new N(0)),a(this,"rotation",new N(0)),a(this,"focusArea",new N(.4)),a(this,"feather",new N(.3)),a(this,"kernelSize",new N(2)),a(this,"resolutionScale",new N(1/window.devicePixelRatio))}get typeName(){return"TiltShiftEffect"}init(){this.offset.defaultValue=0,this.rotation.defaultValue=0,this.focusArea.defaultValue=.4,this.feather.defaultValue=.3,this.kernelSize.defaultValue=A.POSTPROCESSING.MODULE.KernelSize.MEDIUM,this.resolutionScale.defaultValue=1/window.devicePixelRatio}onCreateEffect(){const e=new A.POSTPROCESSING.MODULE.TiltShiftEffect({kernelSize:A.POSTPROCESSING.MODULE.KernelSize.VERY_LARGE,offset:this.offset.value,rotation:this.rotation.value,focusArea:this.focusArea.value,feather:this.feather.value});return this.offset.onValueChanged=t=>e.offset=t,this.rotation.onValueChanged=t=>e.rotation=t,this.focusArea.onValueChanged=t=>e.focusArea=t,this.feather.onValueChanged=t=>e.feather=t,this.kernelSize.onValueChanged=t=>e.blurPass.kernelSize=t,this.resolutionScale.onValueChanged=t=>e.resolution.scale=t/window.devicePixelRatio,e}}kl([m(N)],yn.prototype,"offset"),kl([m(N)],yn.prototype,"rotation"),kl([m(N)],yn.prototype,"focusArea"),kl([m(N)],yn.prototype,"feather"),kl([m(N)],yn.prototype,"kernelSize"),kl([m(N)],yn.prototype,"resolutionScale"),us("TiltShiftEffect",yn);var aI=Object.defineProperty,Fy=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&aI(e,t,o),o};class la extends rt{constructor(){super(...arguments),a(this,"color",new N({r:0,g:0,b:0,a:1})),a(this,"intensity",new N(0)),a(this,"center",new N({x:.5,y:.5}))}get typeName(){return"Vignette"}init(){this.color.defaultValue={r:0,g:0,b:0,a:1},this.intensity.defaultValue=0,this.center.defaultValue={x:.5,y:.5}}onCreateEffect(){const e=new A.POSTPROCESSING.MODULE.VignetteEffect;return this.intensity.onValueChanged=t=>{e.offset=t,this.updateDarkness(e)},this.color.onValueChanged=t=>{this.updateDarkness(e)},e}updateDarkness(e){const t=this.intensity.value;e.darkness=t}}Fy([m(N)],la.prototype,"color"),Fy([m(N)],la.prototype,"intensity"),Fy([m(N)],la.prototype,"center"),us("Vignette",la),globalThis.NEEDLE_USE_POSTPROCESSING=globalThis.NEEDLE_USE_POSTPROCESSING!==void 0?globalThis.NEEDLE_USE_POSTPROCESSING:!0;const io=C("debugpost"),Uy=Symbol("needle:postprocessing-handler"),Oh=Symbol("needle:previous-autoclear-state"),kh=Symbol("needle:previous-tone-mapping");class zy{constructor(e){a(this,"_composer",null),a(this,"_lastVolumeComponents"),a(this,"_effects",[]),a(this,"_isActive",!1),a(this,"context"),a(this,"_anyPassHasDepth",!1),a(this,"_anyPassHasNormal",!1),a(this,"_hasSmaaEffect",!1),a(this,"_customInputBuffer",null),a(this,"_customInputBufferId",0),a(this,"_multisampling",0),a(this,"_menuEntry",null),a(this,"_passIndices",null),this.context=e}getEffectIsActive(e){return e?this._isActive&&this._effects.some(t=>t.effect===e):!1}get isActive(){return this._isActive}get composer(){return this._composer}apply(e){return this._isActive=!0,this.onApply(this.context,e)}unapply(e=!0){var t,s;if(io&&console.log("Unapplying postprocessing effects"),this._isActive=!1,this._lastVolumeComponents){for(const r of this._lastVolumeComponents)r.unapply();this._lastVolumeComponents.length=0}const o=this.context;o[Uy]===this&&(delete o[Uy],typeof o.renderer[Oh]=="boolean"&&(o.renderer.autoClear=o.renderer[Oh]),typeof o.renderer[kh]=="number"&&(o.renderer.toneMapping=o.renderer[kh])),(t=this._composer)==null||t.removeAllPasses(),e&&((s=this._composer)==null||s.dispose()),o.composer===this._composer&&(o.composer=null)}dispose(){this.unapply(!0);for(const e of this._effects)e.effect.dispose();this._effects.length=0,this._composer=null}async onApply(e,t){if(!t)return;await Promise.all([A.POSTPROCESSING.load(),A.POSTPROCESSING_AO.load()]),e[Uy]=this,io&&console.log("Apply Postprocessing Effects",t),this._lastVolumeComponents=[...t],this._effects.length=0;const s={handler:this,components:this._lastVolumeComponents};for(let o=0;o<this._lastVolumeComponents.length;o++){const r=this._lastVolumeComponents[o];if(r.context=e,r.apply){if(r.active){let l=function(d,u){return u?(u instanceof A.POSTPROCESSING.MODULE.Effect||u instanceof A.POSTPROCESSING.MODULE.Pass||console.warn(`PostprocessingEffect ${d} created neither Effect nor Pass - this might be caused by a bundler error or false import. Below you find some possible solutions:
|
|
1318
|
+
- If you create custom effect try creating it like this: 'new NEEDLE_ENGINE_MODULES.POSTPROCESSING.MODULE.Effect(...)' instead of 'new Effect(...)'`),!0):!1};if(!e.mainCameraComponent){console.error("No camera in scene found or available yet - can not create postprocessing effects");return}const c=r.apply(s);if(!c)continue;const h=r.typeName||r.constructor.name;if(Array.isArray(c))for(const d of c)l(h,d)&&this._effects.push({effect:d,typeName:r.typeName,priority:r.order});else{if(!l(h,c))continue;this._effects.push({effect:c,typeName:r.typeName,priority:r.order})}}}else r.active&&be("Volume component is not a VolumeComponent: "+r.__type)}this.applyEffects(e)}get anyPassHasDepth(){return this._anyPassHasDepth}get anyPassHasNormal(){return this._anyPassHasNormal}get hasSmaaEffect(){return this._hasSmaaEffect}set multisampling(e){this._multisampling=e}get multisampling(){return this._multisampling}applyEffects(e){var t;if(this._anyPassHasDepth=!1,this._anyPassHasNormal=!1,this._hasSmaaEffect=!1,this._effects.length<=0)return;const s=e.mainCameraComponent,o=e.renderer,r=e.scene,l=s.threeCamera;if(typeof o[Oh]=="boolean"&&(o.autoClear=o[Oh]),o[Oh]=o.autoClear,typeof o[kh]=="number"&&(o.toneMapping=o[kh]),o[kh]=o.toneMapping,o.toneMapping!=bd&&!this._effects.find(p=>p instanceof A.POSTPROCESSING.MODULE.ToneMappingEffect)){const p=new A.POSTPROCESSING.MODULE.ToneMappingEffect;p.name=`ToneMapping (${o.toneMapping})`,p.mode=Wp(o.toneMapping),this._effects.push({typeName:"ToneMapping",effect:p,priority:ft.ToneMapping})}this._composer||(this._composer=new A.POSTPROCESSING.MODULE.EffectComposer(o,{frameBufferType:zm,stencilBuffer:!0})),e.composer&&e.composer!==this._composer&&console.warn("There's already an active EffectComposer in your scene: replacing it with a new one. This might cause unexpected behaviour. Make sure to only use one PostprocessingManager/Volume in your scene."),e.composer=this._composer;const c=e.composer;c.setMainCamera(l),c.setRenderer(o),c.setMainScene(r),c.autoRenderToScreen=!0,c.multisampling=0;for(const p of c.passes)p.dispose();c.removeAllPasses();const h=new A.POSTPROCESSING.MODULE.RenderPass(r,l);h.name="RenderPass",h.mainScene=r,c.addPass(h);const d=h.render;(t=this._customInputBuffer)==null||t.dispose(),this._customInputBuffer=null,h.render=(p,g,f,y,v)=>{var b;g&&(g.samples=0,f&&(f.samples=0),(!this._customInputBuffer||this._customInputBuffer.width!==g.width||this._customInputBuffer.height!==g.height||this._customInputBuffer.samples!==this._multisampling||this._customInputBuffer.texture.format!==g.texture.format||this._customInputBuffer.texture.type!==zm)&&((b=this._customInputBuffer)==null||b.dispose(),this._customInputBuffer=new $s(g.width,g.height,{format:g.texture.format,type:zm,depthBuffer:g.depthBuffer,depthTexture:g.depthTexture?new Lv(g.width,g.height):void 0,stencilBuffer:g.stencilBuffer,samples:Math.max(0,this._multisampling),minFilter:g.texture.minFilter??xd,magFilter:g.texture.magFilter??xd,generateMipmaps:g.texture.generateMipmaps}),this._customInputBufferId++,this._customInputBuffer.texture.name=`CustomInputBuffer-${this._customInputBufferId}`,this._customInputBuffer.depthTexture&&g.depthTexture&&(this._customInputBuffer.depthTexture.format=g.depthTexture.format,this._customInputBuffer.depthTexture.type=g.depthTexture.type),this._customInputBuffer.samples>0&&(this._customInputBuffer.ignoreDepthForMultisampleCopy=!1),io&&console.warn(`[PostProcessing] Input buffer created with size ${this._customInputBuffer.width}x${this._customInputBuffer.height} and samples ${this._customInputBuffer.samples}`)),d.call(h,p,this._customInputBuffer,f,y,v),Jl.blit(this._customInputBuffer.texture,g,{renderer:p,depthTexture:this._customInputBuffer.depthTexture,depthWrite:!0,depthTest:!0}))};try{T2(this._effects);let p=!1,g=null;for(let v=this._effects.length-1;v>=0;v--){const b=this._effects[v].effect;if(b instanceof A.POSTPROCESSING.MODULE.ToneMappingEffect){if(p){io&&console.warn(`[PostProcessing] Found multiple tonemapping effects in the scene: ${b.name} and ${g?.name}. Only the last one added will be used.`),this._effects.splice(v,1);continue}g=b,p=!0}}const f=[];let y=!1;for(let v=0;v<this._effects.length;v++){const b=this._effects[v].effect;if(b instanceof A.POSTPROCESSING.MODULE.SMAAEffect?this._hasSmaaEffect=!0:b instanceof A.POSTPROCESSING.MODULE.NormalPass&&(this._anyPassHasNormal=!0),!(b instanceof A.POSTPROCESSING.MODULE.ToneMappingEffect&&g!==b))if(b instanceof A.POSTPROCESSING.MODULE.Effect){const _=b.getAttributes(),w=A.POSTPROCESSING.MODULE.EffectAttribute.CONVOLUTION;_&w&&(io&&console.log("[PostProcessing] Convolution effect: "+b.name),y&&(io&&console.log("[PostProcessing] \u2192 Merging effects ["+f.map(x=>x.name).join(", ")+"]"),this.createPassForMergeableEffects(f,c,l,r)),y=!0),f.push(b)}else b instanceof A.POSTPROCESSING.MODULE.Pass?(y=!1,this.createPassForMergeableEffects(f,c,l,r),b.renderToScreen=!1,c.addPass(b)):(y=!1,this.createPassForMergeableEffects(f,c,l,r),c.addPass(b))}this.createPassForMergeableEffects(f,c,l,r)}catch(p){console.error("Error while applying postprocessing effects",p),c.passes.forEach(g=>g.dispose()),c.removeAllPasses()}let u=!1;for(let p=c.passes.length-1;p>=0;p--){const g=c.passes[p];let f=!1,y=!1;g.enabled&&(u||(f=!0,y=!0),u=!0),g.renderToScreen=y,g?.configuration!==void 0?g.configuration.gammaCorrection=f:"autosetGamma"in g&&(g.autosetGamma=f),this._anyPassHasDepth||(this._anyPassHasDepth=g.needsDepthTexture)}io&&console.log("[PostProcessing] Passes \u2192",[...c.passes],`
|
|
1318
1319
|
---------------------------------
|
|
1319
1320
|
\u2022 `+c.passes.map(p=>p.name).join(`
|
|
1320
1321
|
\u2022 `)+`
|
|
1321
|
-
`),io&&this._onCreateEffectsDebug(this._composer,l)}createPassForMergeableEffects(e,t,s,o){if(e.length>0){const r=new A.POSTPROCESSING.MODULE.EffectPass(s,...e);r.name=e.map(l=>l.name).join(", "),r.mainScene=o,r.enabled=!0,r.renderToScreen=!1,t.addPass(r),e.length=0}}_onCreateEffectsDebug(e,t){if(io==="passes"){const s=new A.POSTPROCESSING.MODULE.DepthEffect({blendFunction:A.POSTPROCESSING.MODULE.BlendFunction.NORMAL,inverted:!0});s.name="Depth Effect";const o=new A.POSTPROCESSING.MODULE.EffectPass(t,s);if(o.name="Depth Effect Pass",o.enabled=!1,e.passes.push(o),this._passIndices!==null){const l=[e.passes[0]];this._passIndices.length>0&&l.push(...this._passIndices.filter(c=>c!==0).map(c=>e.passes[c]).filter(c=>c)),l.length>0&&console.log("[PostProcessing] Passes (selected) \u2192",l),e.passes.length=0;for(const c of l)c.enabled=!0,c.renderToScreen=!1,e.addPass(c)}const r=this.context.menu;if(r&&this._passIndices===null){this._menuEntry&&this._menuEntry.remove();const l=document.createElement("select");l.multiple=!0;const c=document.createElement("option");c.innerText="Final Output",c.value="-1",l.appendChild(c);for(const h of e.passes){const d=document.createElement("option");d.innerText=h.name,d.value=`${e.passes.indexOf(h)}`,d.title=h.name,l.appendChild(d)}r.appendChild(l),this._menuEntry=l,l.addEventListener("change",()=>{const h=Array.from(l.selectedOptions).map(d=>parseInt(d.value));h.length===1&&h[0]===-1?this._passIndices=null:this._passIndices=h,this.applyEffects(this.context)})}}}}var aI=Object.defineProperty,bS=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&aI(e,t,o),o};const ca=C("debugpost");class Ml extends I{constructor(){super(...arguments),a(this,"sharedProfile"),a(this,"multisampling","auto"),a(this,"_postprocessing"),a(this,"_activeEffects",[]),a(this,"_effects",[]),a(this,"_componentEnabledTime",-1),a(this,"_multisampleAutoChangeTime",0),a(this,"_multisampleAutoDecreaseTime",0),a(this,"_lastApplyTime"),a(this,"_rapidApplyCount",0),a(this,"_isDirty",!1),a(this,"_modificationQueue"),a(this,"_recreateId",-1)}get isPostProcessingManager(){return!0}get effects(){return this._activeEffects}get dirty(){return this._isDirty}set dirty(e){this._isDirty=e}addEffect(e){let t=e;return t instanceof rt||(t=new xh(t)),t.gameObject===void 0&&this.gameObject.addComponent(t),this._effects.includes(t)||(this._effects.push(t),this._isDirty=!0),e}removeEffect(e){var t,s,o,r;let l=-1;if(e instanceof rt?l=this._effects.indexOf(e):l=this._effects.findIndex(c=>c instanceof xh&&c.effect===e),l!==-1)return this._effects.splice(l,1),this._isDirty=!0,e;if(e instanceof rt){const c=(s=(t=this.sharedProfile)==null?void 0:t.components)==null?void 0:s.indexOf(e);c!==void 0&&c!==-1&&(this._isDirty=!0,(r=(o=this.sharedProfile)==null?void 0:o.components)==null||r.splice(c,1))}return e}markDirty(){this._isDirty=!0}awake(){var e;ca&&(console.log("PostprocessingManager Awake",this),console.log("Press P to toggle post processing"),window.addEventListener("keydown",t=>{t.key==="p"&&(this.enabled=!this.enabled,De("Toggle PostProcessing "+this.name+": Enabled="+this.enabled),this.markDirty())})),(e=this.sharedProfile)==null||e.__init(this)}onEnable(){this._componentEnabledTime=this.context.time.realtimeSinceStartup,this._isDirty=!0}onDisable(){var e;(e=this._postprocessing)==null||e.unapply(),this._isDirty=!1}onBeforeRender(){if(!this.context.isInXR&&(this.context.mainCamera&&this._isDirty&&this.apply(),this.context.composer&&this._postprocessing&&this._postprocessing.composer===this.context.composer)){if(this.context.renderer.getContext().isContextLost()&&this.context.renderer.forceContextRestore(),this.context.composer.getRenderer()!==this.context.renderer&&this.context.composer.setRenderer(this.context.renderer),this.context.composer.setMainScene(this.context.scene),this.multisampling==="auto")if(this._postprocessing&&this._postprocessing.hasSmaaEffect)this._postprocessing.multisampling!==0&&(this._postprocessing.multisampling=0,(ca||F())&&console.warn("[PostProcessing] Disabling multisampling you're using SMAA and have set the 'multisampling: auto' on your PostprocessingManager/Volume component. If you need anti-aliasing, consider adding an Antialiasing component or SMAA effect to the PostprocessingManager."));else{const e=this.context.time.realtimeSinceStartup-this._multisampleAutoChangeTime;if(this.context.time.realtimeSinceStartup-this._componentEnabledTime>2&&e>.5){const t=this._postprocessing.multisampling;if(this._postprocessing.multisampling>0&&this.context.time.smoothedFps<=50){this._multisampleAutoChangeTime=this.context.time.realtimeSinceStartup,this._multisampleAutoDecreaseTime=this.context.time.realtimeSinceStartup;let s=this._postprocessing.multisampling*.5;s=Math.floor(s),s!=this._postprocessing.multisampling&&(this._postprocessing.multisampling=s),ca&&console.debug(`[PostProcessing] Reduced multisampling from ${t} to ${this._postprocessing.multisampling}`)}else if(e>1&&this.context.time.smoothedFps>=59&&this._postprocessing.multisampling<this.context.renderer.capabilities.maxSamples&&this.context.time.realtimeSinceStartup-this._multisampleAutoDecreaseTime>10){this._multisampleAutoChangeTime=this.context.time.realtimeSinceStartup;let s=this._postprocessing.multisampling<=0?1:this._postprocessing.multisampling*2;s=Math.floor(s),s!==this._postprocessing.multisampling&&(this._postprocessing.multisampling=s),ca&&console.debug(`[PostProcessing] Increased multisampling from ${t} to ${this._postprocessing.multisampling}`)}}}else{const e=Math.max(0,Math.min(this.multisampling,this.context.renderer.capabilities.maxSamples));e!==this._postprocessing.multisampling&&(this._postprocessing.multisampling=e)}if(this.context.mainCamera){const e=this.context.composer.passes;for(const t of e)if(t.mainCamera&&t.mainCamera!==this.context.mainCamera){this.context.composer.setMainCamera(this.context.mainCamera);break}}}}onDestroy(){var e;(e=this._postprocessing)==null||e.dispose()}apply(){var e,t,s;if(ca&&console.log(`Apply PostProcessing "${this.name||"unnamed"}"`),F()&&(this._lastApplyTime!==void 0&&Date.now()-this._lastApplyTime<100&&(this._rapidApplyCount++,this._rapidApplyCount===5&&console.warn("Detected rapid post processing modifications - this might be a bug",this)),this._lastApplyTime=Date.now()),this._isDirty=!1,this._activeEffects.length=0,(e=this.sharedProfile)!=null&&e.components){const o=this.sharedProfile.components;for(const r of o)r.active&&r.enabled&&!this._activeEffects.includes(r)&&this._activeEffects.push(r)}for(const o of this._effects)o.active&&o.enabled&&!this._activeEffects.includes(o)&&this._activeEffects.push(o);this._activeEffects.length>0?(this._postprocessing||(this._postprocessing=new zy(this.context)),(t=this._postprocessing.apply(this._activeEffects))==null||t.then(()=>{this.activeAndEnabled&&(this._applyPostQueue(),this._postprocessing?(this.multisampling==="auto"?this._postprocessing.multisampling=X.isMobileDevice()?2:4:this._postprocessing.multisampling=Math.max(0,Math.min(this.multisampling,this.context.renderer.capabilities.maxSamples)),ca&&console.debug(`[PostProcessing] Set multisampling to ${this._postprocessing.multisampling} (Is Mobile: ${X.isMobileDevice()})`)):ca&&console.warn("[PostProcessing] No composer found"))})):(s=this._postprocessing)==null||s.unapply(!1)}_applyPostQueue(){if(this._modificationQueue){for(const e of this._modificationQueue.values())this.onEditorModification(e);this._modificationQueue.clear()}}onEditorModification(e){var t,s;if(e.propertyName.startsWith("postprocessing.")){if(!this._postprocessing)return this._modificationQueue||(this._modificationQueue=new Map),this._modificationQueue.set(e.propertyName,e),!0;if(!((t=this._activeEffects)!=null&&t.length))return;const o=e.propertyName.split(".");if(o.length===3||o.length===4){const r=o[1],l=o[2];for(const c of this._activeEffects)if(((s=c.typeName)==null?void 0:s.toLowerCase())===r.toLowerCase()){if(l==="active"){c.active=e.value,this.scheduleRecreate();return}if(!$p.has(r)){const h=new Array;$p.set(r,h);const d=Object.keys(c);for(const u of d)c[u]instanceof N&&h.push(u)}if($p.has(r)){const h=l.toLowerCase(),d=$p.get(r);for(const u of d)if(u.toLowerCase()===h){const p=c[u];p instanceof N&&(o.length===4&&o[3]==="active"?(p.overrideState=e.value,this.scheduleRecreate()):p&&p.value!==void 0&&(p.value=e.value));return}}console.warn("Unknown modification",l);return}}return!0}return!1}scheduleRecreate(){const e=++this._recreateId;setTimeout(()=>{e===this._recreateId&&(this.onDisable(),this.onEnable())},200)}}bS([Dr(Fp)],Ml.prototype,"sharedProfile"),bS([Dr()],Ml.prototype,"multisampling");const $p=new Map;M2(Ml);async function Ny(n){const{NeedleEngineWebComponent:e}=await Promise.resolve().then(()=>DL);e.observedAttributes.includes(n)||e.observedAttributes.push(n)}var lI=Object.defineProperty,Pt=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&lI(e,t,o),o};const Ht=C("debugsceneswitcher"),cI=C("sceneswitcher:clearscene"),Hp="scene";Ny(Hp);const rr=Promise.resolve(!1);class Ze extends I{constructor(){super(...arguments),a(this,"autoLoadFirstScene",!0),a(this,"scenes",[]),a(this,"loadingScene"),a(this,"queryParameterName","scene"),a(this,"useSceneName",!0),a(this,"clamp",!0),a(this,"useHistory",!0),a(this,"useKeyboard",!0),a(this,"useSwipe",!0),a(this,"useSceneLighting",!0),a(this,"useSceneBackground",!0),a(this,"preloadNext",1),a(this,"preloadPrevious",1),a(this,"preloadConcurrent",2),a(this,"createMenuButtons",!1),a(this,"sceneLoadingStart",new xe),a(this,"sceneLoadingProgress",new xe),a(this,"sceneLoaded",new xe),a(this,"_currentIndex",-1),a(this,"_currentScene"),a(this,"_engineElementOverserver"),a(this,"_preloadScheduler"),a(this,"_menuButtons"),a(this,"onPopState",async e=>{if(!this.useHistory)return;const t=this.useHistory;try{this.useHistory=!1;let s=!1;if(this.queryParameterName&&(s=await this.tryLoadFromQueryParam()),!s){const o=e?.state;if(o&&o.startsWith(this.guid)){const r=o.substr(this.guid.length+2);Ht&&console.log("PopState",r),await this.trySelectSceneFromValue(r)}}}finally{this.useHistory=t}}),a(this,"normalizedSwipeThresholdX",.1),a(this,"_didSwipe",!1),a(this,"onInputPointerMove",e=>{if(this.useSwipe&&!this._didSwipe&&e.button===0&&e.pointerType==="touch"&&this.context.input.getPointerPressedCount()===1){const t=this.context.input.getPointerPositionDelta(e.button);if(t){const s=t.x/this.context.domWidth;s>=this.normalizedSwipeThresholdX?(this._didSwipe=!0,this.selectPrev()):s<=-this.normalizedSwipeThresholdX&&(this._didSwipe=!0,this.selectNext())}}}),a(this,"onInputPointerUp",e=>{e.button===0&&(this._didSwipe=!1)}),a(this,"onInputKeyDown",e=>{if(!this.useKeyboard||!this.scenes)return;const t=e.key.toLowerCase();if(!t)return;const s=parseInt(t)-1;if(s>=0){this.trySelectSceneFromValue(s);return}switch(t){case"arrowright":case"d":this.selectNext();break;case"arrowleft":case"a":this.selectPrev();break}}),a(this,"__lastSwitchScene"),a(this,"__lastSwitchScenePromise"),a(this,"_currentlyLoadingScene"),a(this,"_lastLoadingScene"),a(this,"_loadingScenePromise"),a(this,"_isCurrentlyLoading",!1),a(this,"_currentLoadingProgress")}get currentIndex(){return this._currentIndex}get currentLoadingProgress(){return this._currentLoadingProgress}get currentlyLoadingScene(){return this._currentlyLoadingScene}get currentlyLoadedScene(){return this._currentScene}awake(){this.scenes===void 0&&(this.scenes=[]);for(const e of this.scenes)e&&!e.hasUrl&&e.asset instanceof E?P.remove(e.asset):e instanceof E&&P.remove(e);Ht&&console.log("SceneSwitcher",this)}async onEnable(){if(globalThis.addEventListener("popstate",this.onPopState),this.context.input.addEventListener(Be.KeyDown,this.onInputKeyDown),this.context.input.addEventListener(Be.PointerMove,this.onInputPointerMove),this.context.input.addEventListener(Be.PointerUp,this.onInputPointerUp),this._engineElementOverserver||(this._engineElementOverserver=new MutationObserver(e=>{for(const t of e)if(t.type==="attributes"&&t.attributeName===Hp){const s=this.context.domElement.getAttribute(Hp);s!==null&&this.trySelectSceneFromValue(s)}})),this._engineElementOverserver.observe(this.context.domElement,{attributes:!0}),this._preloadScheduler||(this._preloadScheduler=new hI(this)),this._preloadScheduler.maxLoadAhead=this.preloadNext,this._preloadScheduler.maxLoadBehind=this.preloadPrevious,this._preloadScheduler.maxConcurrent=this.preloadConcurrent,this._preloadScheduler.begin(2e3),this.autoLoadFirstScene&&this._currentIndex===-1&&!await this.tryLoadFromQueryParam()){const e=this.context.domElement.getAttribute(Hp);try{(e===null||!await this.trySelectSceneFromValue(e))&&this._currentIndex===-1&&this.select(0)}finally{}}this.createMenuButtons&&(this._menuButtons??(this._menuButtons=[]),this._menuButtons.push(this.context.menu.appendChild({label:"Previous",icon:"arrow_back_ios",onClick:()=>this.selectPrev(),priority:-1005,class:"row2"})),this._menuButtons.push(this.context.menu.appendChild({label:"Next",icon:"arrow_forward_ios",iconSide:"right",onClick:()=>this.selectNext(),priority:-1e3,class:"row2"})))}onDisable(){var e;if(globalThis.removeEventListener("popstate",this.onPopState),this.context.input.removeEventListener(Be.KeyDown,this.onInputKeyDown),this.context.input.removeEventListener(Be.PointerMove,this.onInputPointerMove),this.context.input.removeEventListener(Be.PointerUp,this.onInputPointerUp),(e=this._preloadScheduler)==null||e.stop(),this._menuButtons){for(const t of this._menuButtons)t.remove();this._menuButtons=void 0}}addScene(e){if(typeof e=="string"){let t=this.context.addressables.findAssetReference(e);return t||(t=new ce(e),this.context.addressables.registerAssetReference(t)),this.scenes.push(t),t}return this.scenes.push(e),e}selectNext(){return this.select(this._currentIndex+1)}selectPrev(){return this.select(this._currentIndex-1)}select(e){var t,s,o;if(Ht&&console.log("select",e),typeof e=="object"&&console.warn('Switching to "'+e+'" might not work. Please either use an index or a AssetReference (not a scene reference)'),typeof e=="string"){const l=(t=this.scenes)==null?void 0:t.find(c=>c.url===e);if(!l){const c=ce.getOrCreate(this.sourceId??"",e,this.context);return this.switchScene(c)}if(l)e=(s=this.scenes)==null?void 0:s.indexOf(l);else return rr}if(!((o=this.scenes)!=null&&o.length))return rr;if(e<0){if(this.clamp)return rr;e=this.scenes.length-1}else if(e>=this.scenes.length){if(this.clamp)return rr;e=0}const r=this.scenes[e];return this.switchScene(r)}unload(){return this.__lastSwitchScene=void 0,this.__lastSwitchScenePromise=void 0,this.__unloadCurrentScene()}async reload(){if(this.__lastSwitchScene){const e=this.__lastSwitchScene;return this.__lastSwitchScene=void 0,this.switchScene(e)}return!1}async switchScene(e){var t;if(!(e instanceof ce)){const s=typeof e;if(s==="string")return this.select(e);if(s==="number")return this.select(e);if(e&&e instanceof E){const o=(t=this.scenes)==null?void 0:t.indexOf(e);e=new ce(e.name,void 0,e),o>=0&&(this.scenes[o]=e)}else return console.warn(`[SceneSwitcher] Can't switch to scene of type ${s}`),!1}return e.url===this.sourceId?(console.warn("[SceneSwitcher] Can't load own scene - prevent recursive loading",this.sourceId),!1):this.__lastSwitchScene===e&&this.__lastSwitchScenePromise?this.__lastSwitchScenePromise:(this.__lastSwitchScene=e,this.__lastSwitchScenePromise=this.__internalSwitchScene(e),await this.__lastSwitchScenePromise)}async __unloadCurrentScene(){const e=this._currentScene;if(this._currentScene=void 0,e){Ht&&console.log("UNLOAD",e.url,"HasURL?: "+e.hasUrl);const t=this.tryGetSceneEventListener(e.asset);if(t!=null&&t.sceneClosing){const s=t.sceneClosing();s instanceof Promise&&await s}e.hasUrl?e.unload():e.asset instanceof E&&P.remove(e.asset)}}async __internalSwitchScene(e){var t,s,o,r,l;await this.__unloadCurrentScene();const c=this._currentIndex=((t=this.scenes)==null?void 0:t.indexOf(e))??-1;try{this._currentlyLoadingScene=e,this._currentLoadingProgress=new ProgressEvent("progress",{loaded:0,total:1});const h=new CustomEvent("loadscene-start",{detail:{scene:e,switcher:this,index:c}});this.dispatchEvent(h),(s=this.sceneLoadingStart)==null||s.invoke(h.detail),await this.onStartLoading(),await e.loadAssetAsync((u,p)=>{var g;if(Ht){const f=p.loaded/p.total,y="["+"=".repeat(Math.floor(f*20))+"-".repeat(20-Math.floor(f*20))+"]";console.debug(`[SceneSwitcher] Download ${(f*100).toFixed(1)} % ${y}`,e.url)}this._currentLoadingProgress=p,this.dispatchEvent(p),(g=this.sceneLoadingProgress)==null||g.invoke(p)}).catch(console.error),await this.onEndLoading();const d=new CustomEvent("loadscene-finished",{detail:{scene:e,switcher:this,index:c}});if(this.dispatchEvent(d),this._currentLoadingProgress=void 0,this._currentlyLoadingScene=void 0,d.defaultPrevented)return Ht&&console.warn("Adding loaded scene prevented:",e,d),!1;if(!e.asset)return Ht&&console.warn("Failed loading scene:",e),!1;if(this._currentIndex===c){if(Ht&&console.log("ADD",e.url),this._currentScene=e,cI){const g=((o=this.context.mainCameraComponent)==null?void 0:o.gameObject)||this.context.mainCamera;g?.removeFromParent();const f=this.gameObject.removeFromParent();Ai(this.context.scene,!0,!0),this.context.scene=new xi,this.context.scene.add(f),g&&this.context.scene.add(g)}if(P.add(e.asset,this.gameObject),this.useSceneLighting&&this.context.sceneLighting.enable(e),this.useSceneBackground){const g=this.context.lightmaps.tryGetSkybox(e.url);g?(g.mapping=kn,this.context.scene.background=g):Ht&&console.warn("SceneSwitcher: Can't find skybox for scene "+e.url)}if(this.useHistory&&c>=0){let g=c.toString();if(this.useSceneName&&(e instanceof E?g=e.name:e.url&&(g=_S(e.url))),(r=this.queryParameterName)!=null&&r.length)Gl(this.queryParameterName,g,this.useHistory);else{const f=history.state,y=this.guid+"::"+c;f!==y&&history.pushState(y,"unused",location.href)}}const u=this.tryGetSceneEventListener(e.asset);if(u!=null&&u.sceneOpened){const g=u.sceneOpened(this);g instanceof Promise&&await g}const p=new CustomEvent("scene-opened",{detail:{scene:e,switcher:this,index:c}});return this.dispatchEvent(p),(l=this.sceneLoaded)==null||l.invoke(this),!0}}catch(h){console.error(h)}return!1}preload(e){if(e>=0&&e<this.scenes.length){const t=this.scenes[e];if(t instanceof ce)return t.preload()}return rr}tryLoadFromQueryParam(){var e;if(!((e=this.queryParameterName)!=null&&e.length))return rr;const t=C(this.queryParameterName);return typeof t=="boolean"?rr:this.trySelectSceneFromValue(t)}trySelectSceneFromValue(e){if(typeof e=="string"){const t=parseInt(e);if(t>=0&&t<this.scenes.length)return this.select(t);{const s=e.toLowerCase();for(let o=0;o<this.scenes.length;o++){const r=this.scenes[o];if(!!r&&(r instanceof E?r.name:_S(r.url)).toLowerCase().includes(s))return this.select(o)}}}else if(typeof e=="number"&&e>=0&&e<this.scenes.length)return this.select(e);return Xt()&&console.warn('Can not find scene: "'+e+'"',this),rr}async onStartLoading(){var e,t;if(this._isCurrentlyLoading=!0,this.loadingScene&&(this._lastLoadingScene!==this.loadingScene&&(this._loadingScenePromise=void 0),this._lastLoadingScene=this.loadingScene,this._loadingScenePromise||(this._loadingScenePromise=(e=this.loadingScene)==null?void 0:e.loadAssetAsync().then(s=>s!=null)),await this._loadingScenePromise,this._isCurrentlyLoading&&(t=this.loadingScene)!=null&&t.asset)){Ht&&console.log("Add loading scene",this.loadingScene.url,this.loadingScene.asset);const s=this.loadingScene.asset;P.add(s,this.gameObject);const o=this.tryGetSceneEventListener(s);if(o!=null&&o.sceneOpened){const r=o.sceneOpened(this);r instanceof Promise&&await r}}if(this._isCurrentlyLoading){const s=this.tryGetSceneEventListener(this.gameObject);if(s&&s.sceneOpened){const o=s.sceneOpened(this);o instanceof Promise&&await o}}}async onEndLoading(){var e;if(this._isCurrentlyLoading=!1,(e=this.loadingScene)!=null&&e.asset){Ht&&console.log("Remove loading scene",this.loadingScene.url);const t=this.loadingScene.asset,s=this.tryGetSceneEventListener(t);if(typeof s?.sceneClosing=="function"){const o=s.sceneClosing();o instanceof Promise&&await o}P.remove(t)}if(!this._isCurrentlyLoading){const t=this.tryGetSceneEventListener(this.gameObject);if(t&&t.sceneClosing){const s=t.sceneClosing();s instanceof Promise&&await s}}}tryGetSceneEventListener(e,t=0){if(!e)return null;const s=P.foreachComponent(e,o=>{const r=o;if(r.sceneClosing||r.sceneOpened)return r});if(t===0&&!s&&e.children.length)for(const o of e.children){const r=this.tryGetSceneEventListener(o,t+1);if(r)return r}return s||null}}Pt([m()],Ze.prototype,"autoLoadFirstScene"),Pt([m(ce)],Ze.prototype,"scenes"),Pt([m(ce)],Ze.prototype,"loadingScene"),Pt([m()],Ze.prototype,"queryParameterName"),Pt([m()],Ze.prototype,"useSceneName"),Pt([m()],Ze.prototype,"clamp"),Pt([m()],Ze.prototype,"useHistory"),Pt([m()],Ze.prototype,"useKeyboard"),Pt([m()],Ze.prototype,"useSwipe"),Pt([m()],Ze.prototype,"useSceneLighting"),Pt([m()],Ze.prototype,"useSceneBackground"),Pt([m()],Ze.prototype,"preloadNext"),Pt([m()],Ze.prototype,"preloadPrevious"),Pt([m()],Ze.prototype,"preloadConcurrent"),Pt([m()],Ze.prototype,"createMenuButtons"),Pt([m(xe)],Ze.prototype,"sceneLoadingStart"),Pt([m(xe)],Ze.prototype,"sceneLoadingProgress"),Pt([m(xe)],Ze.prototype,"sceneLoaded");function _S(n){const e=n.split("/").pop(),t=e?.split(".").shift();return t!=null&&t.length?t:n}class hI{constructor(e,t=1,s=1,o=2){a(this,"maxLoadAhead"),a(this,"maxLoadBehind"),a(this,"maxConcurrent"),a(this,"_isRunning",!1),a(this,"_switcher"),a(this,"_loadTasks",[]),a(this,"_maxConcurrentLoads",1),this._switcher=e,this.maxLoadAhead=t,this.maxLoadBehind=s,this.maxConcurrent=o}begin(e){if(this._isRunning)return;Ht&&console.log("Preload begin",{delay:e}),this._isRunning=!0;let t=-10,s,o;const r=this._switcher.scenes,l=Date.now()+e,c=setInterval(()=>{if(this.allLoaded()&&(Ht&&console.log("All scenes (pre-)loaded"),this.stop()),!this._isRunning){clearInterval(c);return}if(Date.now()<l||this.canLoadNewScene()===!1)return;(t===-10||t!==this._switcher.currentIndex)&&(t=this._switcher.currentIndex,o=0,s=0);const h=o%2===0;h&&(s+=1),o+=1;const d=h?this.maxLoadAhead:this.maxLoadBehind;if(s>d)return;const u=h?t+s:t-s;if(!(u<0)&&!(u<0||u>=r.length)&&!this._loadTasks.some(p=>p.index===u)){const p=r[u];Ht&&console.log("Preload scene",{roomIndex:u,searchForward:h,lastRoom:t,currentIndex:this._switcher.currentIndex,tasks:this._loadTasks.length},p?.url),new dI(u,p,this._loadTasks)}},200)}stop(){this._isRunning=!1}canLoadNewScene(){return this._loadTasks.length<this._maxConcurrentLoads}allLoaded(){if(this._switcher.scenes){for(const e of this._switcher.scenes)if(e!=null&&e.isLoaded&&e.isLoaded()===!1)return!1}return!0}}class dI{constructor(e,t,s){a(this,"index"),a(this,"asset"),a(this,"tasks"),this.index=e,this.asset=t,this.tasks=s,s.push(this),this.awaitLoading()}async awaitLoading(){this.asset&&!this.asset.isLoaded()&&(Ht&&console.log("Preload start: "+this.asset.url,this.index),await this.asset.preload(),Ht&&console.log("Preload finished: "+this.asset.url,this.index));const e=this.tasks.indexOf(this);e>=0&&this.tasks.splice(e,1)}}function uI(){return new Promise((n,e)=>{const t=()=>{t!=null&&(document.removeEventListener("pointerdown",t),document.removeEventListener("click",t),document.removeEventListener("dragstart",t),document.removeEventListener("touchstart",t),n())};document.addEventListener("pointerdown",t),document.addEventListener("click",t),document.addEventListener("dragstart",t),document.addEventListener("touchstart",t)})}async function pI(n){await uI(),n()}var mI=Object.defineProperty,gI=Object.getOwnPropertyDescriptor,$i=(n,e,t,s)=>{for(var o=s>1?void 0:s?gI(e,t):e,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=(s?l(e,t,o):l(o))||o);return s&&o&&mI(e,t,o),o};const Ot=C("debugvideo");var wS=(n=>(n[n.None=0]="None",n[n.AdjustHeight=1]="AdjustHeight",n[n.AdjustWidth=2]="AdjustWidth",n))(wS||{}),xS=(n=>(n[n.VideoClip=0]="VideoClip",n[n.Url=1]="Url",n))(xS||{}),SS=(n=>(n[n.CameraFarPlane=0]="CameraFarPlane",n[n.CameraNearPlane=1]="CameraNearPlane",n[n.RenderTexture=2]="RenderTexture",n[n.MaterialOverride=3]="MaterialOverride",n))(SS||{});class yt extends I{constructor(){super(),a(this,"playOnAwake",!0),a(this,"aspectMode",0),a(this,"clip",null),a(this,"source",1),a(this,"_url",null),a(this,"renderMode"),a(this,"targetMaterialProperty"),a(this,"targetMaterialRenderer"),a(this,"targetTexture"),a(this,"time",0),a(this,"_playbackSpeed",1),a(this,"_isLooping",!1),a(this,"_muted",!1),a(this,"_audioOutputMode",2),a(this,"playInBackground",!0),a(this,"_crossOrigin","anonymous"),a(this,"_videoElement",null),a(this,"_videoTexture",null),a(this,"_videoMaterial",null),a(this,"_isPlaying",!1),a(this,"wasPlaying",!1),a(this,"visibilityChanged",e=>{switch(document.visibilityState){case"hidden":this.playInBackground||(this.wasPlaying=this._isPlaying,this.pause());break;case"visible":this.wasPlaying&&!this._isPlaying&&this.play();break}}),a(this,"_receivedInput",!1),a(this,"_overlay",null),a(this,"_targetObjects"),a(this,"_updateAspectRoutineId",-1),a(this,"_hls"),a(this,"onHlsAvailable",()=>{var e;Ot&&console.log("HLS: available",this.clip),!(!this.shouldUseM3U||!this.url)&&(this._hls||(this._hls=new Hls),this.videoElement.autoplay=!0,this._hls.loadSource(this.url),this._hls.attachMedia(this.videoElement),(e=this._videoElement)==null||e.play(),Ot&&console.log("HLS: loaded",this.clip))}),pI(()=>{this._receivedInput=!0,this.updateVideoElementSettings()}),this._targetObjects=[],C("videoscreenspace")&&window.addEventListener("keydown",e=>{e.key==="f"&&(this.screenspace=!this.screenspace)})}get url(){return this._url}set url(e){const t=this._url!==e;this.__didAwake?t&&this.setClipURL(e??""):this._url=e}get playbackSpeed(){var e;return((e=this._videoElement)==null?void 0:e.playbackRate)??this._playbackSpeed}set playbackSpeed(e){this._playbackSpeed=e,this._videoElement&&(this._videoElement.playbackRate=e)}get isLooping(){var e;return((e=this._videoElement)==null?void 0:e.loop)??this._isLooping}set isLooping(e){this._isLooping=e,this._videoElement&&(this._videoElement.loop=e)}get currentTime(){var e;return((e=this._videoElement)==null?void 0:e.currentTime)??this.time}set currentTime(e){this._videoElement?this._videoElement.currentTime=e:this.time=e}get isPlaying(){const e=this._videoElement;return!!(e&&(e.currentTime>0&&!e.paused&&!e.ended&&e.readyState>e.HAVE_CURRENT_DATA||e.srcObject&&e.srcObject.active))}get crossOrigin(){var e;return((e=this._videoElement)==null?void 0:e.crossOrigin)??this._crossOrigin}set crossOrigin(e){this._crossOrigin=e,this._videoElement&&(e!==null?this._videoElement.setAttribute("crossorigin",e):this._videoElement.removeAttribute("crossorigin"))}get videoMaterial(){return!this._videoMaterial&&!this.create(!1)?null:this._videoMaterial}get videoTexture(){return!this._videoTexture&&!this.create(!1)?null:this._videoTexture}get videoElement(){return!this._videoElement&&!this.create(!1)?null:this._videoElement}requestPictureInPicture(){return this._videoElement?this._videoElement.requestPictureInPicture():null}get muted(){var e;return((e=this._videoElement)==null?void 0:e.muted)??this._muted}set muted(e){this._muted=e,this._videoElement&&(this._videoElement.muted=e)}get currentVideo(){return this.clip}set audioOutputMode(e){e!==this._audioOutputMode&&(e===1&&F()&&console.warn("VideoAudioOutputMode.AudioSource is not yet implemented"),this._audioOutputMode=e,this.updateVideoElementSettings())}get audioOutputMode(){return this._audioOutputMode}preloadVideo(){Ot&&console.log("Video Preload: "+this.name,this.clip),this.create(!1)}preload(){this.preloadVideo()}setVideo(e){this.clip=e,this.source=0,this._videoElement?(this._videoElement.srcObject=e,this._isPlaying&&this.play(),this.updateAspect()):this.create(this.playOnAwake)}setClipURL(e){this._url!==e&&(this._url=e,this.source=1,Ot&&console.log("set url",e),this._videoElement?e.endsWith(".m3u8")||e.includes(".m3u")?this.ensureM3UCanBePlayed():(this._videoElement.src=e,this._isPlaying&&(this.stop(),this.play())):this.create(this.playOnAwake))}onEnable(){var e,t;Ot&&console.log("VideoPlayer.onEnable",xS[this.source],this.clip,this.url,this),window.addEventListener("visibilitychange",this.visibilityChanged),this.playOnAwake===!0?this.create(!0):this.preloadVideo(),this.screenspace?(e=this._overlay)==null||e.start():(t=this._overlay)==null||t.stop()}onDisable(){var e;window.removeEventListener("visibilitychange",this.visibilityChanged),(e=this._overlay)==null||e.stop(),this.pause()}onDestroy(){var e;this._videoElement&&((e=this.videoElement)==null||e.remove(),this._videoElement=null),this._videoTexture&&(this._videoTexture.dispose(),this._videoTexture=null)}play(){var e,t;if(this._videoElement||this.create(!1),!this._videoElement){Ot&&console.warn("Can not play: no video element found",this);return}if(!(this._isPlaying&&!((e=this._videoElement)!=null&&e.ended)&&!((t=this._videoElement)!=null&&t.paused))){if(this._isPlaying=!0,this._receivedInput||(this._videoElement.muted=!0),this.handleBeginPlaying(!1),this.shouldUseM3U){this.ensureM3UCanBePlayed();return}Ot&&console.log("Video Play()",this.clip,this._videoElement,this.time),this._videoElement.currentTime=this.time,this._videoElement.play().catch(s=>{var o;console.log(s),Ot&&console.error("Error playing video",s,"CODE="+s.code,(o=this.videoElement)==null?void 0:o.src,this),setTimeout(()=>{this._isPlaying&&!this.destroyed&&this.activeAndEnabled&&this.play()},1e3)}),Ot&&console.log("play",this._videoElement,this.time)}}stop(){this._isPlaying=!1,this.time=0,this._videoElement&&(this._videoElement.currentTime=0,this._videoElement.pause(),Ot&&console.log("STOP",this))}pause(){var e,t;this.time=((e=this._videoElement)==null?void 0:e.currentTime)??0,this._isPlaying=!1,(t=this._videoElement)==null||t.pause(),Ot&&console.log("PAUSE",this,this.currentTime)}create(e){let t;switch(this.source){case 0:t=this.clip;break;case 1:t=this.url,!(t!=null&&t.length)&&typeof this.clip=="string"&&(t=this.clip);break}return t?(this._videoElement||(Ot&&console.warn("Create VideoElement",this),this._videoElement=this.createVideoElement(),this.context.domElement.shadowRoot.prepend(this._videoElement),this.updateVideoElementStyles()),typeof t=="string"?(Ot&&console.log("Set Video src",t),this._videoElement.src=t):(Ot&&console.log("Set Video srcObject",t),this._videoElement.srcObject=t),this._videoTexture||(this._videoTexture=new DP(this._videoElement)),this._videoTexture.flipY=!1,this._videoTexture.colorSpace=Mn,e&&this.handleBeginPlaying(e),Ot&&console.log("Video: handle playing done...",t,e),!0):(Ot&&console.warn("No video source set",this),!1)}updateAspect(){this.aspectMode!==0&&this.startCoroutine(this.updateAspectImpl())}get screenspace(){var e;return((e=this._overlay)==null?void 0:e.enabled)??!1}set screenspace(e){var t;if(e){if(!this._videoTexture)return;this._overlay||(this._overlay=new fI(this.context)),this._overlay.add(this._videoTexture)}else(t=this._overlay)==null||t.remove(this._videoTexture);this._overlay&&(this._overlay.enabled=e)}createVideoElement(){const e=document.createElement("video");return this._crossOrigin&&e.setAttribute("crossorigin",this._crossOrigin),Ot&&console.log("created video element",e),e}handleBeginPlaying(e){var t,s;if(!this.activeAndEnabled||!this._videoElement)return;this._targetObjects.length=0;let o=this.gameObject;switch(this.renderMode){case 3:o=(t=this.targetMaterialRenderer)==null?void 0:t.gameObject,o||(o=(s=P.getComponent(this.gameObject,Ui))==null?void 0:s.gameObject);break;case 2:console.error("VideoPlayer renderTexture not implemented yet. Please use material override instead");return}if(!o){console.error("Missing target for video material renderer",this.name,SS[this.renderMode],this);return}const r=o.material;if(r){this._targetObjects.push(o),r!==this._videoMaterial&&(this._videoMaterial=r.clone(),o.material=this._videoMaterial);const l="map",c=this._videoMaterial;if(!this.targetMaterialProperty)c[l]=this._videoTexture;else switch(this.targetMaterialProperty){default:c[l]=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.shouldUseM3U&&this.ensureM3UCanBePlayed(),this.play())}updateVideoElementSettings(){if(!this._videoElement)return;this._videoElement.loop=this._isLooping,this._videoElement.currentTime=this.currentTime,this._videoElement.playbackRate=this._playbackSpeed,this._videoElement.playsInline=!0;let e=!this._receivedInput||this.audioOutputMode===0;!e&&this._muted&&(e=!0),this._videoElement.muted=e,this.playOnAwake&&(this._videoElement.autoplay=!0)}updateVideoElementStyles(){this._videoElement&&(this._videoElement.style.userSelect="none",this._videoElement.style.visibility="hidden",this._videoElement.style.display="none",this.updateAspect())}*updateAspectImpl(){const e=++this._updateAspectRoutineId,t=void 0,s=this.clip;for(;e===this._updateAspectRoutineId&&this.aspectMode!==0&&this.clip&&s===this.clip&&this._isPlaying;){if(!s||typeof s=="string")return;let o;for(const r of s.getVideoTracks()){const l=r.getSettings();if(l&&l.width&&l.height){o=l.width/l.height;break}else o=this.context.renderer.domElement.clientWidth/this.context.renderer.domElement.clientHeight}if(o===void 0){for(let r=0;r<10;r++)yield;if(!this.isPlaying)break;continue}if(t===o){yield;continue}for(const r of this._targetObjects){let l=1;if(r.parent){const c=Ge(r.parent);l=c.x/c.y}switch(this.aspectMode){case 1:r.scale.y=1/o*r.scale.x*l;break;case 2:r.scale.x=o*r.scale.y*l;break}}for(let r=0;r<3;r++)yield}}get shouldUseM3U(){return this.url!=null&&(this.url.endsWith(".m3u8")||this.url.endsWith(".m3u"))&&this.source===1}ensureM3UCanBePlayed(){if(!this.shouldUseM3U)return;let e=document.head.querySelector("script[data-hls_library]");e?globalThis.Hls?this.onHlsAvailable():e.addEventListener("load",this.onHlsAvailable):(Ot&&console.log("HLS: load script"),e=document.createElement("script"),e.dataset.hls_library="hls.js",e.src="https://cdn.jsdelivr.net/npm/hls.js@1",e.addEventListener("load",this.onHlsAvailable),document.head.append(e))}}$i([m()],yt.prototype,"playOnAwake",2),$i([m()],yt.prototype,"aspectMode",2),$i([m(URL)],yt.prototype,"clip",2),$i([m()],yt.prototype,"source",2),$i([m(URL)],yt.prototype,"url",1),$i([m()],yt.prototype,"renderMode",2),$i([m()],yt.prototype,"targetMaterialProperty",2),$i([m(Ui)],yt.prototype,"targetMaterialRenderer",2),$i([m(je)],yt.prototype,"targetTexture",2),$i([m()],yt.prototype,"time",2),$i([m()],yt.prototype,"playbackSpeed",1),$i([m()],yt.prototype,"isLooping",1),$i([m()],yt.prototype,"audioOutputMode",1);class fI{constructor(e){a(this,"context"),a(this,"_videos",[]),a(this,"_screenspaceModeQuad"),a(this,"_isInScreenspaceMode",!1),a(this,"_input"),this.context=e,this._input=new yI(this)}get enabled(){return this._isInScreenspaceMode}set enabled(e){e?this.start():this.stop()}add(e){this._videos.indexOf(e)===-1&&this._videos.push(e)}remove(e){if(!e)return;const t=this._videos.indexOf(e);t>=0&&this._videos.splice(t,1)}start(){var e;if(this._isInScreenspaceMode||this._videos.length<0)return;const t=this._videos[this._videos.length-1];if(!t)return;if(this._isInScreenspaceMode=!0,!this._screenspaceModeQuad){if(this._screenspaceModeQuad=wo.createPrimitive(Cr.Quad,{material:new vI(t)}),!this._screenspaceModeQuad)return;this._screenspaceModeQuad.geometry.scale(2,2,2)}const s=this._screenspaceModeQuad;this.context.scene.add(s),this.updateScreenspaceMaterialUniforms();const o=s.material;o?.reset(),(e=this._input)==null||e.enable(o)}stop(){var e;this._isInScreenspaceMode=!1,this._screenspaceModeQuad&&((e=this._input)==null||e.disable(),this._screenspaceModeQuad.removeFromParent())}updateScreenspaceMaterialUniforms(){var e;const t=(e=this._screenspaceModeQuad)==null?void 0:e.material;t&&(t.screenAspect=this.context.domElement.clientWidth/this.context.domElement.clientHeight)}}class yI{constructor(e){a(this,"_onResizeScreenFn"),a(this,"_onKeyUpFn"),a(this,"_onMouseWheelFn"),a(this,"context"),a(this,"overlay"),a(this,"_material"),a(this,"_isPinching",!1),a(this,"_lastPinch",0),this.overlay=e,this.context=e.context}enable(e){this._material=e,window.addEventListener("resize",this._onResizeScreenFn=()=>{this.overlay.updateScreenspaceMaterialUniforms()}),window.addEventListener("keyup",this._onKeyUpFn=o=>{o.key==="Escape"&&this.overlay.stop()}),window.addEventListener("wheel",this._onMouseWheelFn=o=>{this.overlay.enabled&&(e.zoom+=o.deltaY*5e-4,o.preventDefault())},{passive:!1});const t=new re;window.addEventListener("mousemove",o=>{if(this.overlay.enabled&&this.context.input.getPointerPressed(0)){const r=new re(o.movementX,o.movementY);r.x/=this.context.domElement.clientWidth,r.y/=this.context.domElement.clientHeight,t.set(r.x,r.y),t.multiplyScalar(e.zoom/-this.context.time.deltaTime*.01),e.offset=e.offset.add(t)}}),window.addEventListener("pointermove",o=>{this.overlay.enabled&&this.context.input.getPointerPressed(0)&&this.context.input.getTouchesPressedCount()===1&&(t.set(o.movementX,o.movementY),t.multiplyScalar(e.zoom*-this.context.time.deltaTime*.05),e.offset=e.offset.add(t))});let s=0;window.addEventListener("touchstart",o=>{if(o.touches.length<2){this.context.time.time-s<.3&&this.overlay.stop(),s=this.context.time.time;return}this._isPinching=!0,this._lastPinch=0}),window.addEventListener("touchmove",o=>{if(!this._isPinching||!this._material)return;const r=o.touches[0],l=o.touches[1],c=r.clientX-l.clientX,h=r.clientY-l.clientY,d=Math.sqrt(c*c+h*h);if(this._lastPinch!==0){const u=d-this._lastPinch;this._material.zoom-=u*.004}this._lastPinch=d}),window.addEventListener("touchend",()=>{this._isPinching=!1})}disable(){this._onResizeScreenFn&&(window.removeEventListener("resize",this._onResizeScreenFn),this._onResizeScreenFn=void 0),this._onKeyUpFn&&(window.removeEventListener("keyup",this._onKeyUpFn),this._onKeyUpFn=void 0),this._onMouseWheelFn&&(window.removeEventListener("wheel",this._onMouseWheelFn),this._onMouseWheelFn=void 0)}}class vI extends Ws{constructor(e){super(),a(this,"_offset",new re),this.uniforms={map:{value:e},screenAspect:{value:1},offsetScale:{value:new fe(0,0,1,1)}},this.vertexShader=`
|
|
1322
|
+
`),io&&this._onCreateEffectsDebug(this._composer,l)}createPassForMergeableEffects(e,t,s,o){if(e.length>0){const r=new A.POSTPROCESSING.MODULE.EffectPass(s,...e);r.name=e.map(l=>l.name).join(", "),r.mainScene=o,r.enabled=!0,r.renderToScreen=!1,t.addPass(r),e.length=0}}_onCreateEffectsDebug(e,t){if(io==="passes"){const s=new A.POSTPROCESSING.MODULE.DepthEffect({blendFunction:A.POSTPROCESSING.MODULE.BlendFunction.NORMAL,inverted:!0});s.name="Depth Effect";const o=new A.POSTPROCESSING.MODULE.EffectPass(t,s);if(o.name="Depth Effect Pass",o.enabled=!1,e.passes.push(o),this._passIndices!==null){const l=[e.passes[0]];this._passIndices.length>0&&l.push(...this._passIndices.filter(c=>c!==0).map(c=>e.passes[c]).filter(c=>c)),l.length>0&&console.log("[PostProcessing] Passes (selected) \u2192",l),e.passes.length=0;for(const c of l)c.enabled=!0,c.renderToScreen=!1,e.addPass(c)}const r=this.context.menu;if(r&&this._passIndices===null){this._menuEntry&&this._menuEntry.remove();const l=document.createElement("select");l.multiple=!0;const c=document.createElement("option");c.innerText="Final Output",c.value="-1",l.appendChild(c);for(const h of e.passes){const d=document.createElement("option");d.innerText=h.name,d.value=`${e.passes.indexOf(h)}`,d.title=h.name,l.appendChild(d)}r.appendChild(l),this._menuEntry=l,l.addEventListener("change",()=>{const h=Array.from(l.selectedOptions).map(d=>parseInt(d.value));h.length===1&&h[0]===-1?this._passIndices=null:this._passIndices=h,this.applyEffects(this.context)})}}}}var lI=Object.defineProperty,bS=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&lI(e,t,o),o};const ca=C("debugpost");class Ml extends I{constructor(){super(...arguments),a(this,"sharedProfile"),a(this,"multisampling","auto"),a(this,"_postprocessing"),a(this,"_activeEffects",[]),a(this,"_effects",[]),a(this,"_componentEnabledTime",-1),a(this,"_multisampleAutoChangeTime",0),a(this,"_multisampleAutoDecreaseTime",0),a(this,"_lastApplyTime"),a(this,"_rapidApplyCount",0),a(this,"_isDirty",!1),a(this,"_modificationQueue"),a(this,"_recreateId",-1)}get isPostProcessingManager(){return!0}get effects(){return this._activeEffects}get dirty(){return this._isDirty}set dirty(e){this._isDirty=e}addEffect(e){let t=e;return t instanceof rt||(t=new xh(t)),t.gameObject===void 0&&this.gameObject.addComponent(t),this._effects.includes(t)||(this._effects.push(t),this._isDirty=!0),e}removeEffect(e){var t,s,o,r;let l=-1;if(e instanceof rt?l=this._effects.indexOf(e):l=this._effects.findIndex(c=>c instanceof xh&&c.effect===e),l!==-1)return this._effects.splice(l,1),this._isDirty=!0,e;if(e instanceof rt){const c=(s=(t=this.sharedProfile)==null?void 0:t.components)==null?void 0:s.indexOf(e);c!==void 0&&c!==-1&&(this._isDirty=!0,(r=(o=this.sharedProfile)==null?void 0:o.components)==null||r.splice(c,1))}return e}markDirty(){this._isDirty=!0}awake(){var e;ca&&(console.log("PostprocessingManager Awake",this),console.log("Press P to toggle post processing"),window.addEventListener("keydown",t=>{t.key==="p"&&(this.enabled=!this.enabled,De("Toggle PostProcessing "+this.name+": Enabled="+this.enabled),this.markDirty())})),(e=this.sharedProfile)==null||e.__init(this)}onEnable(){this._componentEnabledTime=this.context.time.realtimeSinceStartup,this._isDirty=!0}onDisable(){var e;(e=this._postprocessing)==null||e.unapply(),this._isDirty=!1}onBeforeRender(){if(!this.context.isInXR&&(this.context.mainCamera&&this._isDirty&&this.apply(),this.context.composer&&this._postprocessing&&this._postprocessing.composer===this.context.composer)){if(this.context.renderer.getContext().isContextLost()&&this.context.renderer.forceContextRestore(),this.context.composer.getRenderer()!==this.context.renderer&&this.context.composer.setRenderer(this.context.renderer),this.context.composer.setMainScene(this.context.scene),this.multisampling==="auto")if(this._postprocessing&&this._postprocessing.hasSmaaEffect)this._postprocessing.multisampling!==0&&(this._postprocessing.multisampling=0,(ca||F())&&console.log(`[PostProcessing] multisampling is disabled because it's set to 'auto' on your PostprocessingManager/Volume component that also has an SMAA effect.
|
|
1323
|
+
|
|
1324
|
+
If you need multisampling consider changing 'auto' to a fixed value (e.g. 4).`));else{const e=this.context.time.realtimeSinceStartup-this._multisampleAutoChangeTime;if(this.context.time.realtimeSinceStartup-this._componentEnabledTime>2&&e>.5){const t=this._postprocessing.multisampling;if(this._postprocessing.multisampling>0&&this.context.time.smoothedFps<=50){this._multisampleAutoChangeTime=this.context.time.realtimeSinceStartup,this._multisampleAutoDecreaseTime=this.context.time.realtimeSinceStartup;let s=this._postprocessing.multisampling*.5;s=Math.floor(s),s!=this._postprocessing.multisampling&&(this._postprocessing.multisampling=s),ca&&console.debug(`[PostProcessing] Reduced multisampling from ${t} to ${this._postprocessing.multisampling}`)}else if(e>1&&this.context.time.smoothedFps>=59&&this._postprocessing.multisampling<this.context.renderer.capabilities.maxSamples&&this.context.time.realtimeSinceStartup-this._multisampleAutoDecreaseTime>10){this._multisampleAutoChangeTime=this.context.time.realtimeSinceStartup;let s=this._postprocessing.multisampling<=0?1:this._postprocessing.multisampling*2;s=Math.floor(s),s!==this._postprocessing.multisampling&&(this._postprocessing.multisampling=s),ca&&console.debug(`[PostProcessing] Increased multisampling from ${t} to ${this._postprocessing.multisampling}`)}}}else{const e=Math.max(0,Math.min(this.multisampling,this.context.renderer.capabilities.maxSamples));e!==this._postprocessing.multisampling&&(this._postprocessing.multisampling=e)}if(this.context.mainCamera){const e=this.context.composer.passes;for(const t of e)if(t.mainCamera&&t.mainCamera!==this.context.mainCamera){this.context.composer.setMainCamera(this.context.mainCamera);break}}}}onDestroy(){var e;(e=this._postprocessing)==null||e.dispose()}apply(){var e,t,s;if(ca&&console.log(`Apply PostProcessing "${this.name||"unnamed"}"`),F()&&(this._lastApplyTime!==void 0&&Date.now()-this._lastApplyTime<100&&(this._rapidApplyCount++,this._rapidApplyCount===5&&console.warn("Detected rapid post processing modifications - this might be a bug",this)),this._lastApplyTime=Date.now()),this._isDirty=!1,this._activeEffects.length=0,(e=this.sharedProfile)!=null&&e.components){const o=this.sharedProfile.components;for(const r of o)r.active&&r.enabled&&!this._activeEffects.includes(r)&&this._activeEffects.push(r)}for(const o of this._effects)o.active&&o.enabled&&!this._activeEffects.includes(o)&&this._activeEffects.push(o);this._activeEffects.length>0?(this._postprocessing||(this._postprocessing=new zy(this.context)),(t=this._postprocessing.apply(this._activeEffects))==null||t.then(()=>{this.activeAndEnabled&&(this._applyPostQueue(),this._postprocessing?(this.multisampling==="auto"?this._postprocessing.multisampling=X.isMobileDevice()?2:4:this._postprocessing.multisampling=Math.max(0,Math.min(this.multisampling,this.context.renderer.capabilities.maxSamples)),ca&&console.debug(`[PostProcessing] Set multisampling to ${this._postprocessing.multisampling} (Is Mobile: ${X.isMobileDevice()})`)):ca&&console.warn("[PostProcessing] No composer found"))})):(s=this._postprocessing)==null||s.unapply(!1)}_applyPostQueue(){if(this._modificationQueue){for(const e of this._modificationQueue.values())this.onEditorModification(e);this._modificationQueue.clear()}}onEditorModification(e){var t,s;if(e.propertyName.startsWith("postprocessing.")){if(!this._postprocessing)return this._modificationQueue||(this._modificationQueue=new Map),this._modificationQueue.set(e.propertyName,e),!0;if(!((t=this._activeEffects)!=null&&t.length))return;const o=e.propertyName.split(".");if(o.length===3||o.length===4){const r=o[1],l=o[2];for(const c of this._activeEffects)if(((s=c.typeName)==null?void 0:s.toLowerCase())===r.toLowerCase()){if(l==="active"){c.active=e.value,this.scheduleRecreate();return}if(!$p.has(r)){const h=new Array;$p.set(r,h);const d=Object.keys(c);for(const u of d)c[u]instanceof N&&h.push(u)}if($p.has(r)){const h=l.toLowerCase(),d=$p.get(r);for(const u of d)if(u.toLowerCase()===h){const p=c[u];p instanceof N&&(o.length===4&&o[3]==="active"?(p.overrideState=e.value,this.scheduleRecreate()):p&&p.value!==void 0&&(p.value=e.value));return}}console.warn("Unknown modification",l);return}}return!0}return!1}scheduleRecreate(){const e=++this._recreateId;setTimeout(()=>{e===this._recreateId&&(this.onDisable(),this.onEnable())},200)}}bS([Dr(Fp)],Ml.prototype,"sharedProfile"),bS([Dr()],Ml.prototype,"multisampling");const $p=new Map;M2(Ml);async function Ny(n){const{NeedleEngineWebComponent:e}=await Promise.resolve().then(()=>BL);e.observedAttributes.includes(n)||e.observedAttributes.push(n)}var cI=Object.defineProperty,Pt=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&cI(e,t,o),o};const Ht=C("debugsceneswitcher"),hI=C("sceneswitcher:clearscene"),Hp="scene";Ny(Hp);const rr=Promise.resolve(!1);class Ze extends I{constructor(){super(...arguments),a(this,"autoLoadFirstScene",!0),a(this,"scenes",[]),a(this,"loadingScene"),a(this,"queryParameterName","scene"),a(this,"useSceneName",!0),a(this,"clamp",!0),a(this,"useHistory",!0),a(this,"useKeyboard",!0),a(this,"useSwipe",!0),a(this,"useSceneLighting",!0),a(this,"useSceneBackground",!0),a(this,"preloadNext",1),a(this,"preloadPrevious",1),a(this,"preloadConcurrent",2),a(this,"createMenuButtons",!1),a(this,"sceneLoadingStart",new xe),a(this,"sceneLoadingProgress",new xe),a(this,"sceneLoaded",new xe),a(this,"_currentIndex",-1),a(this,"_currentScene"),a(this,"_engineElementOverserver"),a(this,"_preloadScheduler"),a(this,"_menuButtons"),a(this,"onPopState",async e=>{if(!this.useHistory)return;const t=this.useHistory;try{this.useHistory=!1;let s=!1;if(this.queryParameterName&&(s=await this.tryLoadFromQueryParam()),!s){const o=e?.state;if(o&&o.startsWith(this.guid)){const r=o.substr(this.guid.length+2);Ht&&console.log("PopState",r),await this.trySelectSceneFromValue(r)}}}finally{this.useHistory=t}}),a(this,"normalizedSwipeThresholdX",.1),a(this,"_didSwipe",!1),a(this,"onInputPointerMove",e=>{if(this.useSwipe&&!this._didSwipe&&e.button===0&&e.pointerType==="touch"&&this.context.input.getPointerPressedCount()===1){const t=this.context.input.getPointerPositionDelta(e.button);if(t){const s=t.x/this.context.domWidth;s>=this.normalizedSwipeThresholdX?(this._didSwipe=!0,this.selectPrev()):s<=-this.normalizedSwipeThresholdX&&(this._didSwipe=!0,this.selectNext())}}}),a(this,"onInputPointerUp",e=>{e.button===0&&(this._didSwipe=!1)}),a(this,"onInputKeyDown",e=>{if(!this.useKeyboard||!this.scenes)return;const t=e.key.toLowerCase();if(!t)return;const s=parseInt(t)-1;if(s>=0){this.trySelectSceneFromValue(s);return}switch(t){case"arrowright":case"d":this.selectNext();break;case"arrowleft":case"a":this.selectPrev();break}}),a(this,"__lastSwitchScene"),a(this,"__lastSwitchScenePromise"),a(this,"_currentlyLoadingScene"),a(this,"_lastLoadingScene"),a(this,"_loadingScenePromise"),a(this,"_isCurrentlyLoading",!1),a(this,"_currentLoadingProgress")}get currentIndex(){return this._currentIndex}get currentLoadingProgress(){return this._currentLoadingProgress}get currentlyLoadingScene(){return this._currentlyLoadingScene}get currentlyLoadedScene(){return this._currentScene}awake(){this.scenes===void 0&&(this.scenes=[]);for(const e of this.scenes)e&&!e.hasUrl&&e.asset instanceof E?P.remove(e.asset):e instanceof E&&P.remove(e);Ht&&console.log("SceneSwitcher",this)}async onEnable(){if(globalThis.addEventListener("popstate",this.onPopState),this.context.input.addEventListener(Be.KeyDown,this.onInputKeyDown),this.context.input.addEventListener(Be.PointerMove,this.onInputPointerMove),this.context.input.addEventListener(Be.PointerUp,this.onInputPointerUp),this._engineElementOverserver||(this._engineElementOverserver=new MutationObserver(e=>{for(const t of e)if(t.type==="attributes"&&t.attributeName===Hp){const s=this.context.domElement.getAttribute(Hp);s!==null&&this.trySelectSceneFromValue(s)}})),this._engineElementOverserver.observe(this.context.domElement,{attributes:!0}),this._preloadScheduler||(this._preloadScheduler=new dI(this)),this._preloadScheduler.maxLoadAhead=this.preloadNext,this._preloadScheduler.maxLoadBehind=this.preloadPrevious,this._preloadScheduler.maxConcurrent=this.preloadConcurrent,this._preloadScheduler.begin(2e3),this.autoLoadFirstScene&&this._currentIndex===-1&&!await this.tryLoadFromQueryParam()){const e=this.context.domElement.getAttribute(Hp);try{(e===null||!await this.trySelectSceneFromValue(e))&&this._currentIndex===-1&&this.select(0)}finally{}}this.createMenuButtons&&(this._menuButtons??(this._menuButtons=[]),this._menuButtons.push(this.context.menu.appendChild({label:"Previous",icon:"arrow_back_ios",onClick:()=>this.selectPrev(),priority:-1005,class:"row2"})),this._menuButtons.push(this.context.menu.appendChild({label:"Next",icon:"arrow_forward_ios",iconSide:"right",onClick:()=>this.selectNext(),priority:-1e3,class:"row2"})))}onDisable(){var e;if(globalThis.removeEventListener("popstate",this.onPopState),this.context.input.removeEventListener(Be.KeyDown,this.onInputKeyDown),this.context.input.removeEventListener(Be.PointerMove,this.onInputPointerMove),this.context.input.removeEventListener(Be.PointerUp,this.onInputPointerUp),(e=this._preloadScheduler)==null||e.stop(),this._menuButtons){for(const t of this._menuButtons)t.remove();this._menuButtons=void 0}}addScene(e){if(typeof e=="string"){let t=this.context.addressables.findAssetReference(e);return t||(t=new ce(e),this.context.addressables.registerAssetReference(t)),this.scenes.push(t),t}return this.scenes.push(e),e}selectNext(){return this.select(this._currentIndex+1)}selectPrev(){return this.select(this._currentIndex-1)}select(e){var t,s,o;if(Ht&&console.log("select",e),typeof e=="object"&&console.warn('Switching to "'+e+'" might not work. Please either use an index or a AssetReference (not a scene reference)'),typeof e=="string"){const l=(t=this.scenes)==null?void 0:t.find(c=>c.url===e);if(!l){const c=ce.getOrCreate(this.sourceId??"",e,this.context);return this.switchScene(c)}if(l)e=(s=this.scenes)==null?void 0:s.indexOf(l);else return rr}if(!((o=this.scenes)!=null&&o.length))return rr;if(e<0){if(this.clamp)return rr;e=this.scenes.length-1}else if(e>=this.scenes.length){if(this.clamp)return rr;e=0}const r=this.scenes[e];return this.switchScene(r)}unload(){return this.__lastSwitchScene=void 0,this.__lastSwitchScenePromise=void 0,this.__unloadCurrentScene()}async reload(){if(this.__lastSwitchScene){const e=this.__lastSwitchScene;return this.__lastSwitchScene=void 0,this.switchScene(e)}return!1}async switchScene(e){var t;if(!(e instanceof ce)){const s=typeof e;if(s==="string")return this.select(e);if(s==="number")return this.select(e);if(e&&e instanceof E){const o=(t=this.scenes)==null?void 0:t.indexOf(e);e=new ce(e.name,void 0,e),o>=0&&(this.scenes[o]=e)}else return console.warn(`[SceneSwitcher] Can't switch to scene of type ${s}`),!1}return e.url===this.sourceId?(console.warn("[SceneSwitcher] Can't load own scene - prevent recursive loading",this.sourceId),!1):this.__lastSwitchScene===e&&this.__lastSwitchScenePromise?this.__lastSwitchScenePromise:(this.__lastSwitchScene=e,this.__lastSwitchScenePromise=this.__internalSwitchScene(e),await this.__lastSwitchScenePromise)}async __unloadCurrentScene(){const e=this._currentScene;if(this._currentScene=void 0,e){Ht&&console.log("UNLOAD",e.url,"HasURL?: "+e.hasUrl);const t=this.tryGetSceneEventListener(e.asset);if(t!=null&&t.sceneClosing){const s=t.sceneClosing();s instanceof Promise&&await s}e.hasUrl?e.unload():e.asset instanceof E&&P.remove(e.asset)}}async __internalSwitchScene(e){var t,s,o,r,l;await this.__unloadCurrentScene();const c=this._currentIndex=((t=this.scenes)==null?void 0:t.indexOf(e))??-1;try{this._currentlyLoadingScene=e,this._currentLoadingProgress=new ProgressEvent("progress",{loaded:0,total:1});const h=new CustomEvent("loadscene-start",{detail:{scene:e,switcher:this,index:c}});this.dispatchEvent(h),(s=this.sceneLoadingStart)==null||s.invoke(h.detail),await this.onStartLoading(),await e.loadAssetAsync((u,p)=>{var g;if(Ht){const f=p.loaded/p.total,y="["+"=".repeat(Math.floor(f*20))+"-".repeat(20-Math.floor(f*20))+"]";console.debug(`[SceneSwitcher] Download ${(f*100).toFixed(1)} % ${y}`,e.url)}this._currentLoadingProgress=p,this.dispatchEvent(p),(g=this.sceneLoadingProgress)==null||g.invoke(p)}).catch(console.error),await this.onEndLoading();const d=new CustomEvent("loadscene-finished",{detail:{scene:e,switcher:this,index:c}});if(this.dispatchEvent(d),this._currentLoadingProgress=void 0,this._currentlyLoadingScene=void 0,d.defaultPrevented)return Ht&&console.warn("Adding loaded scene prevented:",e,d),!1;if(!e.asset)return Ht&&console.warn("Failed loading scene:",e),!1;if(this._currentIndex===c){if(Ht&&console.log("ADD",e.url),this._currentScene=e,hI){const g=((o=this.context.mainCameraComponent)==null?void 0:o.gameObject)||this.context.mainCamera;g?.removeFromParent();const f=this.gameObject.removeFromParent();Ai(this.context.scene,!0,!0),this.context.scene=new xi,this.context.scene.add(f),g&&this.context.scene.add(g)}if(P.add(e.asset,this.gameObject),this.useSceneLighting&&this.context.sceneLighting.enable(e),this.useSceneBackground){const g=this.context.lightmaps.tryGetSkybox(e.url);g?(g.mapping=kn,this.context.scene.background=g):Ht&&console.warn("SceneSwitcher: Can't find skybox for scene "+e.url)}if(this.useHistory&&c>=0){let g=c.toString();if(this.useSceneName&&(e instanceof E?g=e.name:e.url&&(g=_S(e.url))),(r=this.queryParameterName)!=null&&r.length)Gl(this.queryParameterName,g,this.useHistory);else{const f=history.state,y=this.guid+"::"+c;f!==y&&history.pushState(y,"unused",location.href)}}const u=this.tryGetSceneEventListener(e.asset);if(u!=null&&u.sceneOpened){const g=u.sceneOpened(this);g instanceof Promise&&await g}const p=new CustomEvent("scene-opened",{detail:{scene:e,switcher:this,index:c}});return this.dispatchEvent(p),(l=this.sceneLoaded)==null||l.invoke(this),!0}}catch(h){console.error(h)}return!1}preload(e){if(e>=0&&e<this.scenes.length){const t=this.scenes[e];if(t instanceof ce)return t.preload()}return rr}tryLoadFromQueryParam(){var e;if(!((e=this.queryParameterName)!=null&&e.length))return rr;const t=C(this.queryParameterName);return typeof t=="boolean"?rr:this.trySelectSceneFromValue(t)}trySelectSceneFromValue(e){if(typeof e=="string"){const t=parseInt(e);if(t>=0&&t<this.scenes.length)return this.select(t);{const s=e.toLowerCase();for(let o=0;o<this.scenes.length;o++){const r=this.scenes[o];if(!!r&&(r instanceof E?r.name:_S(r.url)).toLowerCase().includes(s))return this.select(o)}}}else if(typeof e=="number"&&e>=0&&e<this.scenes.length)return this.select(e);return Xt()&&console.warn('Can not find scene: "'+e+'"',this),rr}async onStartLoading(){var e,t;if(this._isCurrentlyLoading=!0,this.loadingScene&&(this._lastLoadingScene!==this.loadingScene&&(this._loadingScenePromise=void 0),this._lastLoadingScene=this.loadingScene,this._loadingScenePromise||(this._loadingScenePromise=(e=this.loadingScene)==null?void 0:e.loadAssetAsync().then(s=>s!=null)),await this._loadingScenePromise,this._isCurrentlyLoading&&(t=this.loadingScene)!=null&&t.asset)){Ht&&console.log("Add loading scene",this.loadingScene.url,this.loadingScene.asset);const s=this.loadingScene.asset;P.add(s,this.gameObject);const o=this.tryGetSceneEventListener(s);if(o!=null&&o.sceneOpened){const r=o.sceneOpened(this);r instanceof Promise&&await r}}if(this._isCurrentlyLoading){const s=this.tryGetSceneEventListener(this.gameObject);if(s&&s.sceneOpened){const o=s.sceneOpened(this);o instanceof Promise&&await o}}}async onEndLoading(){var e;if(this._isCurrentlyLoading=!1,(e=this.loadingScene)!=null&&e.asset){Ht&&console.log("Remove loading scene",this.loadingScene.url);const t=this.loadingScene.asset,s=this.tryGetSceneEventListener(t);if(typeof s?.sceneClosing=="function"){const o=s.sceneClosing();o instanceof Promise&&await o}P.remove(t)}if(!this._isCurrentlyLoading){const t=this.tryGetSceneEventListener(this.gameObject);if(t&&t.sceneClosing){const s=t.sceneClosing();s instanceof Promise&&await s}}}tryGetSceneEventListener(e,t=0){if(!e)return null;const s=P.foreachComponent(e,o=>{const r=o;if(r.sceneClosing||r.sceneOpened)return r});if(t===0&&!s&&e.children.length)for(const o of e.children){const r=this.tryGetSceneEventListener(o,t+1);if(r)return r}return s||null}}Pt([m()],Ze.prototype,"autoLoadFirstScene"),Pt([m(ce)],Ze.prototype,"scenes"),Pt([m(ce)],Ze.prototype,"loadingScene"),Pt([m()],Ze.prototype,"queryParameterName"),Pt([m()],Ze.prototype,"useSceneName"),Pt([m()],Ze.prototype,"clamp"),Pt([m()],Ze.prototype,"useHistory"),Pt([m()],Ze.prototype,"useKeyboard"),Pt([m()],Ze.prototype,"useSwipe"),Pt([m()],Ze.prototype,"useSceneLighting"),Pt([m()],Ze.prototype,"useSceneBackground"),Pt([m()],Ze.prototype,"preloadNext"),Pt([m()],Ze.prototype,"preloadPrevious"),Pt([m()],Ze.prototype,"preloadConcurrent"),Pt([m()],Ze.prototype,"createMenuButtons"),Pt([m(xe)],Ze.prototype,"sceneLoadingStart"),Pt([m(xe)],Ze.prototype,"sceneLoadingProgress"),Pt([m(xe)],Ze.prototype,"sceneLoaded");function _S(n){const e=n.split("/").pop(),t=e?.split(".").shift();return t!=null&&t.length?t:n}class dI{constructor(e,t=1,s=1,o=2){a(this,"maxLoadAhead"),a(this,"maxLoadBehind"),a(this,"maxConcurrent"),a(this,"_isRunning",!1),a(this,"_switcher"),a(this,"_loadTasks",[]),a(this,"_maxConcurrentLoads",1),this._switcher=e,this.maxLoadAhead=t,this.maxLoadBehind=s,this.maxConcurrent=o}begin(e){if(this._isRunning)return;Ht&&console.log("Preload begin",{delay:e}),this._isRunning=!0;let t=-10,s,o;const r=this._switcher.scenes,l=Date.now()+e,c=setInterval(()=>{if(this.allLoaded()&&(Ht&&console.log("All scenes (pre-)loaded"),this.stop()),!this._isRunning){clearInterval(c);return}if(Date.now()<l||this.canLoadNewScene()===!1)return;(t===-10||t!==this._switcher.currentIndex)&&(t=this._switcher.currentIndex,o=0,s=0);const h=o%2===0;h&&(s+=1),o+=1;const d=h?this.maxLoadAhead:this.maxLoadBehind;if(s>d)return;const u=h?t+s:t-s;if(!(u<0)&&!(u<0||u>=r.length)&&!this._loadTasks.some(p=>p.index===u)){const p=r[u];Ht&&console.log("Preload scene",{roomIndex:u,searchForward:h,lastRoom:t,currentIndex:this._switcher.currentIndex,tasks:this._loadTasks.length},p?.url),new uI(u,p,this._loadTasks)}},200)}stop(){this._isRunning=!1}canLoadNewScene(){return this._loadTasks.length<this._maxConcurrentLoads}allLoaded(){if(this._switcher.scenes){for(const e of this._switcher.scenes)if(e!=null&&e.isLoaded&&e.isLoaded()===!1)return!1}return!0}}class uI{constructor(e,t,s){a(this,"index"),a(this,"asset"),a(this,"tasks"),this.index=e,this.asset=t,this.tasks=s,s.push(this),this.awaitLoading()}async awaitLoading(){this.asset&&!this.asset.isLoaded()&&(Ht&&console.log("Preload start: "+this.asset.url,this.index),await this.asset.preload(),Ht&&console.log("Preload finished: "+this.asset.url,this.index));const e=this.tasks.indexOf(this);e>=0&&this.tasks.splice(e,1)}}function pI(){return new Promise((n,e)=>{const t=()=>{t!=null&&(document.removeEventListener("pointerdown",t),document.removeEventListener("click",t),document.removeEventListener("dragstart",t),document.removeEventListener("touchstart",t),n())};document.addEventListener("pointerdown",t),document.addEventListener("click",t),document.addEventListener("dragstart",t),document.addEventListener("touchstart",t)})}async function mI(n){await pI(),n()}var gI=Object.defineProperty,fI=Object.getOwnPropertyDescriptor,$i=(n,e,t,s)=>{for(var o=s>1?void 0:s?fI(e,t):e,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=(s?l(e,t,o):l(o))||o);return s&&o&&gI(e,t,o),o};const Ot=C("debugvideo");var wS=(n=>(n[n.None=0]="None",n[n.AdjustHeight=1]="AdjustHeight",n[n.AdjustWidth=2]="AdjustWidth",n))(wS||{}),xS=(n=>(n[n.VideoClip=0]="VideoClip",n[n.Url=1]="Url",n))(xS||{}),SS=(n=>(n[n.CameraFarPlane=0]="CameraFarPlane",n[n.CameraNearPlane=1]="CameraNearPlane",n[n.RenderTexture=2]="RenderTexture",n[n.MaterialOverride=3]="MaterialOverride",n))(SS||{});class yt extends I{constructor(){super(),a(this,"playOnAwake",!0),a(this,"aspectMode",0),a(this,"clip",null),a(this,"source",1),a(this,"_url",null),a(this,"renderMode"),a(this,"targetMaterialProperty"),a(this,"targetMaterialRenderer"),a(this,"targetTexture"),a(this,"time",0),a(this,"_playbackSpeed",1),a(this,"_isLooping",!1),a(this,"_muted",!1),a(this,"_audioOutputMode",2),a(this,"playInBackground",!0),a(this,"_crossOrigin","anonymous"),a(this,"_videoElement",null),a(this,"_videoTexture",null),a(this,"_videoMaterial",null),a(this,"_isPlaying",!1),a(this,"wasPlaying",!1),a(this,"visibilityChanged",e=>{switch(document.visibilityState){case"hidden":this.playInBackground||(this.wasPlaying=this._isPlaying,this.pause());break;case"visible":this.wasPlaying&&!this._isPlaying&&this.play();break}}),a(this,"_receivedInput",!1),a(this,"_overlay",null),a(this,"_targetObjects"),a(this,"_updateAspectRoutineId",-1),a(this,"_hls"),a(this,"onHlsAvailable",()=>{var e;Ot&&console.log("HLS: available",this.clip),!(!this.shouldUseM3U||!this.url)&&(this._hls||(this._hls=new Hls),this.videoElement.autoplay=!0,this._hls.loadSource(this.url),this._hls.attachMedia(this.videoElement),(e=this._videoElement)==null||e.play(),Ot&&console.log("HLS: loaded",this.clip))}),mI(()=>{this._receivedInput=!0,this.updateVideoElementSettings()}),this._targetObjects=[],C("videoscreenspace")&&window.addEventListener("keydown",e=>{e.key==="f"&&(this.screenspace=!this.screenspace)})}get url(){return this._url}set url(e){const t=this._url!==e;this.__didAwake?t&&this.setClipURL(e??""):this._url=e}get playbackSpeed(){var e;return((e=this._videoElement)==null?void 0:e.playbackRate)??this._playbackSpeed}set playbackSpeed(e){this._playbackSpeed=e,this._videoElement&&(this._videoElement.playbackRate=e)}get isLooping(){var e;return((e=this._videoElement)==null?void 0:e.loop)??this._isLooping}set isLooping(e){this._isLooping=e,this._videoElement&&(this._videoElement.loop=e)}get currentTime(){var e;return((e=this._videoElement)==null?void 0:e.currentTime)??this.time}set currentTime(e){this._videoElement?this._videoElement.currentTime=e:this.time=e}get isPlaying(){const e=this._videoElement;return!!(e&&(e.currentTime>0&&!e.paused&&!e.ended&&e.readyState>e.HAVE_CURRENT_DATA||e.srcObject&&e.srcObject.active))}get crossOrigin(){var e;return((e=this._videoElement)==null?void 0:e.crossOrigin)??this._crossOrigin}set crossOrigin(e){this._crossOrigin=e,this._videoElement&&(e!==null?this._videoElement.setAttribute("crossorigin",e):this._videoElement.removeAttribute("crossorigin"))}get videoMaterial(){return!this._videoMaterial&&!this.create(!1)?null:this._videoMaterial}get videoTexture(){return!this._videoTexture&&!this.create(!1)?null:this._videoTexture}get videoElement(){return!this._videoElement&&!this.create(!1)?null:this._videoElement}requestPictureInPicture(){return this._videoElement?this._videoElement.requestPictureInPicture():null}get muted(){var e;return((e=this._videoElement)==null?void 0:e.muted)??this._muted}set muted(e){this._muted=e,this._videoElement&&(this._videoElement.muted=e)}get currentVideo(){return this.clip}set audioOutputMode(e){e!==this._audioOutputMode&&(e===1&&F()&&console.warn("VideoAudioOutputMode.AudioSource is not yet implemented"),this._audioOutputMode=e,this.updateVideoElementSettings())}get audioOutputMode(){return this._audioOutputMode}preloadVideo(){Ot&&console.log("Video Preload: "+this.name,this.clip),this.create(!1)}preload(){this.preloadVideo()}setVideo(e){this.clip=e,this.source=0,this._videoElement?(this._videoElement.srcObject=e,this._isPlaying&&this.play(),this.updateAspect()):this.create(this.playOnAwake)}setClipURL(e){this._url!==e&&(this._url=e,this.source=1,Ot&&console.log("set url",e),this._videoElement?e.endsWith(".m3u8")||e.includes(".m3u")?this.ensureM3UCanBePlayed():(this._videoElement.src=e,this._isPlaying&&(this.stop(),this.play())):this.create(this.playOnAwake))}onEnable(){var e,t;Ot&&console.log("VideoPlayer.onEnable",xS[this.source],this.clip,this.url,this),window.addEventListener("visibilitychange",this.visibilityChanged),this.playOnAwake===!0?this.create(!0):this.preloadVideo(),this.screenspace?(e=this._overlay)==null||e.start():(t=this._overlay)==null||t.stop()}onDisable(){var e;window.removeEventListener("visibilitychange",this.visibilityChanged),(e=this._overlay)==null||e.stop(),this.pause()}onDestroy(){var e;this._videoElement&&((e=this.videoElement)==null||e.remove(),this._videoElement=null),this._videoTexture&&(this._videoTexture.dispose(),this._videoTexture=null)}play(){var e,t;if(this._videoElement||this.create(!1),!this._videoElement){Ot&&console.warn("Can not play: no video element found",this);return}if(!(this._isPlaying&&!((e=this._videoElement)!=null&&e.ended)&&!((t=this._videoElement)!=null&&t.paused))){if(this._isPlaying=!0,this._receivedInput||(this._videoElement.muted=!0),this.handleBeginPlaying(!1),this.shouldUseM3U){this.ensureM3UCanBePlayed();return}Ot&&console.log("Video Play()",this.clip,this._videoElement,this.time),this._videoElement.currentTime=this.time,this._videoElement.play().catch(s=>{var o;console.log(s),Ot&&console.error("Error playing video",s,"CODE="+s.code,(o=this.videoElement)==null?void 0:o.src,this),setTimeout(()=>{this._isPlaying&&!this.destroyed&&this.activeAndEnabled&&this.play()},1e3)}),Ot&&console.log("play",this._videoElement,this.time)}}stop(){this._isPlaying=!1,this.time=0,this._videoElement&&(this._videoElement.currentTime=0,this._videoElement.pause(),Ot&&console.log("STOP",this))}pause(){var e,t;this.time=((e=this._videoElement)==null?void 0:e.currentTime)??0,this._isPlaying=!1,(t=this._videoElement)==null||t.pause(),Ot&&console.log("PAUSE",this,this.currentTime)}create(e){let t;switch(this.source){case 0:t=this.clip;break;case 1:t=this.url,!(t!=null&&t.length)&&typeof this.clip=="string"&&(t=this.clip);break}return t?(this._videoElement||(Ot&&console.warn("Create VideoElement",this),this._videoElement=this.createVideoElement(),this.context.domElement.shadowRoot.prepend(this._videoElement),this.updateVideoElementStyles()),typeof t=="string"?(Ot&&console.log("Set Video src",t),this._videoElement.src=t):(Ot&&console.log("Set Video srcObject",t),this._videoElement.srcObject=t),this._videoTexture||(this._videoTexture=new DP(this._videoElement)),this._videoTexture.flipY=!1,this._videoTexture.colorSpace=Mn,e&&this.handleBeginPlaying(e),Ot&&console.log("Video: handle playing done...",t,e),!0):(Ot&&console.warn("No video source set",this),!1)}updateAspect(){this.aspectMode!==0&&this.startCoroutine(this.updateAspectImpl())}get screenspace(){var e;return((e=this._overlay)==null?void 0:e.enabled)??!1}set screenspace(e){var t;if(e){if(!this._videoTexture)return;this._overlay||(this._overlay=new yI(this.context)),this._overlay.add(this._videoTexture)}else(t=this._overlay)==null||t.remove(this._videoTexture);this._overlay&&(this._overlay.enabled=e)}createVideoElement(){const e=document.createElement("video");return this._crossOrigin&&e.setAttribute("crossorigin",this._crossOrigin),Ot&&console.log("created video element",e),e}handleBeginPlaying(e){var t,s;if(!this.activeAndEnabled||!this._videoElement)return;this._targetObjects.length=0;let o=this.gameObject;switch(this.renderMode){case 3:o=(t=this.targetMaterialRenderer)==null?void 0:t.gameObject,o||(o=(s=P.getComponent(this.gameObject,Ui))==null?void 0:s.gameObject);break;case 2:console.error("VideoPlayer renderTexture not implemented yet. Please use material override instead");return}if(!o){console.error("Missing target for video material renderer",this.name,SS[this.renderMode],this);return}const r=o.material;if(r){this._targetObjects.push(o),r!==this._videoMaterial&&(this._videoMaterial=r.clone(),o.material=this._videoMaterial);const l="map",c=this._videoMaterial;if(!this.targetMaterialProperty)c[l]=this._videoTexture;else switch(this.targetMaterialProperty){default:c[l]=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.shouldUseM3U&&this.ensureM3UCanBePlayed(),this.play())}updateVideoElementSettings(){if(!this._videoElement)return;this._videoElement.loop=this._isLooping,this._videoElement.currentTime=this.currentTime,this._videoElement.playbackRate=this._playbackSpeed,this._videoElement.playsInline=!0;let e=!this._receivedInput||this.audioOutputMode===0;!e&&this._muted&&(e=!0),this._videoElement.muted=e,this.playOnAwake&&(this._videoElement.autoplay=!0)}updateVideoElementStyles(){this._videoElement&&(this._videoElement.style.userSelect="none",this._videoElement.style.visibility="hidden",this._videoElement.style.display="none",this.updateAspect())}*updateAspectImpl(){const e=++this._updateAspectRoutineId,t=void 0,s=this.clip;for(;e===this._updateAspectRoutineId&&this.aspectMode!==0&&this.clip&&s===this.clip&&this._isPlaying;){if(!s||typeof s=="string")return;let o;for(const r of s.getVideoTracks()){const l=r.getSettings();if(l&&l.width&&l.height){o=l.width/l.height;break}else o=this.context.renderer.domElement.clientWidth/this.context.renderer.domElement.clientHeight}if(o===void 0){for(let r=0;r<10;r++)yield;if(!this.isPlaying)break;continue}if(t===o){yield;continue}for(const r of this._targetObjects){let l=1;if(r.parent){const c=Ge(r.parent);l=c.x/c.y}switch(this.aspectMode){case 1:r.scale.y=1/o*r.scale.x*l;break;case 2:r.scale.x=o*r.scale.y*l;break}}for(let r=0;r<3;r++)yield}}get shouldUseM3U(){return this.url!=null&&(this.url.endsWith(".m3u8")||this.url.endsWith(".m3u"))&&this.source===1}ensureM3UCanBePlayed(){if(!this.shouldUseM3U)return;let e=document.head.querySelector("script[data-hls_library]");e?globalThis.Hls?this.onHlsAvailable():e.addEventListener("load",this.onHlsAvailable):(Ot&&console.log("HLS: load script"),e=document.createElement("script"),e.dataset.hls_library="hls.js",e.src="https://cdn.jsdelivr.net/npm/hls.js@1",e.addEventListener("load",this.onHlsAvailable),document.head.append(e))}}$i([m()],yt.prototype,"playOnAwake",2),$i([m()],yt.prototype,"aspectMode",2),$i([m(URL)],yt.prototype,"clip",2),$i([m()],yt.prototype,"source",2),$i([m(URL)],yt.prototype,"url",1),$i([m()],yt.prototype,"renderMode",2),$i([m()],yt.prototype,"targetMaterialProperty",2),$i([m(Ui)],yt.prototype,"targetMaterialRenderer",2),$i([m(je)],yt.prototype,"targetTexture",2),$i([m()],yt.prototype,"time",2),$i([m()],yt.prototype,"playbackSpeed",1),$i([m()],yt.prototype,"isLooping",1),$i([m()],yt.prototype,"audioOutputMode",1);class yI{constructor(e){a(this,"context"),a(this,"_videos",[]),a(this,"_screenspaceModeQuad"),a(this,"_isInScreenspaceMode",!1),a(this,"_input"),this.context=e,this._input=new vI(this)}get enabled(){return this._isInScreenspaceMode}set enabled(e){e?this.start():this.stop()}add(e){this._videos.indexOf(e)===-1&&this._videos.push(e)}remove(e){if(!e)return;const t=this._videos.indexOf(e);t>=0&&this._videos.splice(t,1)}start(){var e;if(this._isInScreenspaceMode||this._videos.length<0)return;const t=this._videos[this._videos.length-1];if(!t)return;if(this._isInScreenspaceMode=!0,!this._screenspaceModeQuad){if(this._screenspaceModeQuad=wo.createPrimitive(Cr.Quad,{material:new bI(t)}),!this._screenspaceModeQuad)return;this._screenspaceModeQuad.geometry.scale(2,2,2)}const s=this._screenspaceModeQuad;this.context.scene.add(s),this.updateScreenspaceMaterialUniforms();const o=s.material;o?.reset(),(e=this._input)==null||e.enable(o)}stop(){var e;this._isInScreenspaceMode=!1,this._screenspaceModeQuad&&((e=this._input)==null||e.disable(),this._screenspaceModeQuad.removeFromParent())}updateScreenspaceMaterialUniforms(){var e;const t=(e=this._screenspaceModeQuad)==null?void 0:e.material;t&&(t.screenAspect=this.context.domElement.clientWidth/this.context.domElement.clientHeight)}}class vI{constructor(e){a(this,"_onResizeScreenFn"),a(this,"_onKeyUpFn"),a(this,"_onMouseWheelFn"),a(this,"context"),a(this,"overlay"),a(this,"_material"),a(this,"_isPinching",!1),a(this,"_lastPinch",0),this.overlay=e,this.context=e.context}enable(e){this._material=e,window.addEventListener("resize",this._onResizeScreenFn=()=>{this.overlay.updateScreenspaceMaterialUniforms()}),window.addEventListener("keyup",this._onKeyUpFn=o=>{o.key==="Escape"&&this.overlay.stop()}),window.addEventListener("wheel",this._onMouseWheelFn=o=>{this.overlay.enabled&&(e.zoom+=o.deltaY*5e-4,o.preventDefault())},{passive:!1});const t=new re;window.addEventListener("mousemove",o=>{if(this.overlay.enabled&&this.context.input.getPointerPressed(0)){const r=new re(o.movementX,o.movementY);r.x/=this.context.domElement.clientWidth,r.y/=this.context.domElement.clientHeight,t.set(r.x,r.y),t.multiplyScalar(e.zoom/-this.context.time.deltaTime*.01),e.offset=e.offset.add(t)}}),window.addEventListener("pointermove",o=>{this.overlay.enabled&&this.context.input.getPointerPressed(0)&&this.context.input.getTouchesPressedCount()===1&&(t.set(o.movementX,o.movementY),t.multiplyScalar(e.zoom*-this.context.time.deltaTime*.05),e.offset=e.offset.add(t))});let s=0;window.addEventListener("touchstart",o=>{if(o.touches.length<2){this.context.time.time-s<.3&&this.overlay.stop(),s=this.context.time.time;return}this._isPinching=!0,this._lastPinch=0}),window.addEventListener("touchmove",o=>{if(!this._isPinching||!this._material)return;const r=o.touches[0],l=o.touches[1],c=r.clientX-l.clientX,h=r.clientY-l.clientY,d=Math.sqrt(c*c+h*h);if(this._lastPinch!==0){const u=d-this._lastPinch;this._material.zoom-=u*.004}this._lastPinch=d}),window.addEventListener("touchend",()=>{this._isPinching=!1})}disable(){this._onResizeScreenFn&&(window.removeEventListener("resize",this._onResizeScreenFn),this._onResizeScreenFn=void 0),this._onKeyUpFn&&(window.removeEventListener("keyup",this._onKeyUpFn),this._onKeyUpFn=void 0),this._onMouseWheelFn&&(window.removeEventListener("wheel",this._onMouseWheelFn),this._onMouseWheelFn=void 0)}}class bI extends Ws{constructor(e){super(),a(this,"_offset",new re),this.uniforms={map:{value:e},screenAspect:{value:1},offsetScale:{value:new fe(0,0,1,1)}},this.vertexShader=`
|
|
1322
1325
|
uniform sampler2D map;
|
|
1323
1326
|
uniform float screenAspect;
|
|
1324
1327
|
uniform vec4 offsetScale;
|
|
@@ -1371,8 +1374,8 @@ axisFormat %s
|
|
|
1371
1374
|
gl_FragColor = texcolor;
|
|
1372
1375
|
}
|
|
1373
1376
|
}
|
|
1374
|
-
`}set screenAspect(e){this.uniforms.screenAspect.value=e,this.needsUpdate=!0}set offset(e){const t=this.uniforms.offsetScale.value;t.x=e.x,t.y=e.y,this.uniforms.offsetScale.value=t,this.needsUpdate=!0}get offset(){const e=this.uniforms.offsetScale.value;return this._offset.set(e.x,e.y),this._offset}set zoom(e){const t=this.uniforms.offsetScale.value;e<.001&&(e=.001),t.z=e,this.needsUpdate=!0}get zoom(){return this.uniforms.offsetScale.value.z}reset(){this.offset=this.offset.set(0,0),this.zoom=1,this.needsUpdate=!0}}var
|
|
1375
|
-
`,s);let o=!1;for(const r of s)try{if(!this._requestOpen){Lt&&console.log("Camera selection cancelled");break}if(r.kind!=="videoinput"){Lt&&console.log("Skipping non-video device",r);continue}const l=r.deviceId;if(t?.deviceId!=null||t?.deviceFilter!=null){if(t?.deviceId!==void 0&&l!==t.deviceId){Lt&&console.log("Skipping device due to options.deviceId: "+r.label+"; "+r.deviceId);continue}if(t!=null&&t.deviceFilter&&t.deviceFilter(r)===!1){Lt&&console.log("Skipping device due to options.deviceFilter: "+r.label+"; "+r.deviceId);continue}}else if(this.deviceFilter)if(this.deviceFilter(r)===!1){Lt&&console.log("Skipping device due to ScreenShare.deviceFilter: "+r.label+"; "+r.deviceId);continue}else Lt&&console.log("Selected device by filter",r);else if(this.deviceName){const h=r.label.toLowerCase(),d=this.deviceName.toLowerCase(),u=h.includes(d),p=r.deviceId===this.deviceName;if(!u&&!p){Lt&&console.log("Skipping device due to ScreenShare.deviceName: "+r.label+"; "+r.deviceId);continue}else Lt&&console.log("Selected device by name",r)}e.video!==!1&&((typeof e.video>"u"||typeof e.video=="boolean")&&(e.video={}),e.video.deviceId=l),o=!0;const c=await navigator.mediaDevices.getUserMedia(e).catch(h=>(console.error("Failed to get user media",h),null));if(c===null)continue;this._requestOpen?(this.setStream(c,1),Lt&&console.log("Selected camera",r)):(on(c),Lt&&console.log("Camera selection cancelled"));break}catch(l){if(l.message==="Failed to allocate videosource"||l.message==="Could not start video source"){be("Failed to start video: Try another camera (Code "+l.code+")"),console.warn(l);continue}else console.error("Failed to get user media",l.message,l.code,l)}!o&&F()&&(be("No camera found for sharing. Please connect a camera (see console for more information)"),console.warn("No camera found for sharing. Please connect a camera",s,this.deviceName,"Using deviceFilter? "+this.deviceFilter!=null,"Using options? "+t!=null,"Using deviceName? "+this.deviceName!=null,"Using options.deviceId? "+t?.deviceId!=null,"Using options.deviceFilter? "+t?.deviceFilter!=null))}}Mh([m()],ar.prototype,"allowStartOnClick",2),Mh([m()],ar.prototype,"autoConnect",2),Mh([m(yt)],ar.prototype,"videoPlayer",1),Mh([m()],ar.prototype,"device",2),Mh([m()],ar.prototype,"deviceName",2);var
|
|
1377
|
+
`}set screenAspect(e){this.uniforms.screenAspect.value=e,this.needsUpdate=!0}set offset(e){const t=this.uniforms.offsetScale.value;t.x=e.x,t.y=e.y,this.uniforms.offsetScale.value=t,this.needsUpdate=!0}get offset(){const e=this.uniforms.offsetScale.value;return this._offset.set(e.x,e.y),this._offset}set zoom(e){const t=this.uniforms.offsetScale.value;e<.001&&(e=.001),t.z=e,this.needsUpdate=!0}get zoom(){return this.uniforms.offsetScale.value.z}reset(){this.offset=this.offset.set(0,0),this.zoom=1,this.needsUpdate=!0}}var _I=Object.defineProperty,wI=Object.getOwnPropertyDescriptor,Mh=(n,e,t,s)=>{for(var o=s>1?void 0:s?wI(e,t):e,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=(s?l(e,t,o):l(o))||o);return s&&o&&_I(e,t,o),o};const Lt=C("debugscreensharing");var CS=(n=>(n[n.Screen=0]="Screen",n[n.Camera=1]="Camera",n[n.Canvas=2]="Canvas",n[n.Microphone=3]="Microphone",n))(CS||{});class ar extends I{constructor(){super(...arguments),a(this,"allowStartOnClick",!0),a(this,"autoConnect",!1),a(this,"_videoPlayer"),a(this,"_audioSource"),a(this,"device","Screen"),a(this,"deviceName"),a(this,"deviceFilter"),a(this,"_net"),a(this,"_requestOpen",!1),a(this,"_currentStream",null),a(this,"_currentMode",0),a(this,"onJoinedRoom",async()=>{await vs(1e3),this.autoConnect&&!this.isSending&&!this.isReceiving&&this.context.connection.isInRoom&&this.share()}),a(this,"_activeShareRequest",null),a(this,"onReceiveStream",e=>{var t;((t=e.stream)==null?void 0:t.active)===!0&&this.setStream(e.stream,2)}),a(this,"onCallEnded",e=>{Lt&&console.log("CALL ENDED",this.isReceiving,this==null?void 0:this.screenspace),this.isReceiving&&(this.screenspace=!1)})}onPointerEnter(){this.context.connection.allowEditing!=!1&&this.allowStartOnClick&&this.context.input.setCursor("pointer")}onPointerExit(){this.context.connection.allowEditing!=!1&&this.allowStartOnClick&&this.context.input.unsetCursor("pointer")}onPointerClick(e){var t;if(this.context.connection.allowEditing!=!1&&this.allowStartOnClick&&!(e&&e.pointerId!==0)){if(this.isReceiving&&(t=this.videoPlayer)!=null&&t.isPlaying){this.videoPlayer&&(this.videoPlayer.screenspace=!this.videoPlayer.screenspace);return}if(this.isSending){this.close();return}this.share()}}set videoPlayer(e){this._videoPlayer&&(this.isSending||this.isReceiving)&&this._videoPlayer.stop(),this._videoPlayer=e,this._videoPlayer&&this._currentStream&&(this.isSending||this.isReceiving)&&this._videoPlayer.setVideo(this._currentStream)}get videoPlayer(){return this._videoPlayer}get screenspace(){var e;return((e=this.videoPlayer)==null?void 0:e.screenspace)??!1}set screenspace(e){this.videoPlayer&&(this.videoPlayer.screenspace=e)}get currentScream(){return this._currentStream}get currentMode(){return this._currentMode}get isSending(){var e;return((e=this._currentStream)==null?void 0:e.active)&&this._currentMode===1}get isReceiving(){if(this._currentMode===2){if(!this._currentStream||this._currentStream.active===!1)return!1;const e=this._currentStream.getTracks();for(const t of e)if(t.readyState==="live")return!0}return!1}get requiresVideoPlayer(){return this.device!=="Microphone"}awake(){typeof this.device=="number"&&(this.device=CS[this.device]),Lt&&console.log("Screensharing",this.name,this),ns.registerWaitForAllowAudio(()=>{this._videoPlayer&&this._currentStream&&this._currentMode===2&&(this._videoPlayer.playInBackground=!0,this._videoPlayer.setVideo(this._currentStream))}),this._net=new hd(this)}onEnable(){var e,t,s;(e=this._net)==null||e.enable(),(t=this._net)==null||t.addEventListener(nn.StreamReceived,this.onReceiveStream),(s=this._net)==null||s.addEventListener(nn.StreamEnded,this.onCallEnded),this.context.connection.beginListen(ie.JoinedRoom,this.onJoinedRoom),this.autoConnect&&vs(1e3).then(()=>(this.enabled&&this.autoConnect&&!this.isReceiving&&!this.isSending&&this.context.connection.isInRoom&&this.share(),0))}onDisable(){var e,t,s;(e=this._net)==null||e.removeEventListener(nn.StreamReceived,this.onReceiveStream),(t=this._net)==null||t.removeEventListener(nn.StreamEnded,this.onCallEnded),this.context.connection.stopListen(ie.JoinedRoom,this.onJoinedRoom),(s=this._net)==null||s.disable(),this.close()}_ensureVideoPlayer(){const e=new yt;e.aspectMode=wS.AdjustWidth,P.addComponent(this.gameObject,e),this._videoPlayer=e}async share(e){return this._activeShareRequest?this._activeShareRequest:(this._activeShareRequest=this.internalShare(e),this._activeShareRequest.then(()=>this._activeShareRequest=null))}async internalShare(e){if(this.context.connection.isInRoom===!1){console.warn("Can not start screensharing: requires network connection"),F()&&be("Can not start screensharing: requires network connection. Add a SyncedRoom component or join a room first.");return}if(e!=null&&e.device&&(this.device=e.device),!this.videoPlayer&&this.requiresVideoPlayer&&(this._videoPlayer||(this._videoPlayer=P.getComponent(this.gameObject,yt)??void 0),this.videoPlayer||this._ensureVideoPlayer(),!this.videoPlayer)){console.warn("Can not share video without a videoPlayer assigned");return}this._requestOpen=!0;try{const t=e?.constraints??{echoCancellation:!0,autoGainControl:!1},s={video:t,audio:t},o=s.video;switch(o!==void 0&&typeof o!="boolean"&&(o.width||(o.width={max:1920}),o.height||(o.height={max:1920}),o.aspectRatio||(o.aspectRatio={ideal:1.7777777778}),o.frameRate||(o.frameRate={ideal:24}),o.facingMode||(o.facingMode={ideal:"user"})),this.device){case"Camera":this.tryShareUserCamera(s,e);break;case"Screen":{if(!navigator.mediaDevices.getDisplayMedia){console.error("No getDisplayMedia support");return}const l=await navigator.mediaDevices.getDisplayMedia(s);this._requestOpen?this.setStream(l,1):on(l)}break;case"Canvas":const r=this.context.renderer.domElement.captureStream(0);this.setStream(r,1);break;case"Microphone":{if(!navigator.mediaDevices.getUserMedia){console.error("No getDisplayMedia support");return}s.video=!1;const l=await navigator.mediaDevices.getUserMedia(s);this._requestOpen?this.setStream(l,1):on(l)}break;default:console.error("Can not start screen sharing: Unknown device type",this.device)}}catch(t){if(t.name==="NotAllowedError"){console.log("Selection cancelled"),this._requestOpen=!1;return}console.error("Error opening video",t)}}close(){var e;this._requestOpen=!1,this._currentStream&&(Lt&&console.warn("Close current stream / disposing resources, stream was active?",this._currentStream.active),(e=this._net)==null||e.stopSendingStream(this._currentStream),on(this._currentStream),this._currentMode=0,this._currentStream=null)}setStream(e,t){var s,o,r;if(e===this._currentStream||(this.close(),!e))return;this._currentStream=e,this._requestOpen=!0,this._currentMode=t;const l=this.device!=="Microphone",c=t===1;l?(this._videoPlayer||this._ensureVideoPlayer(),this._videoPlayer?this._videoPlayer.setVideo(e):console.error("No video player assigned for video stream")):(this._audioSource||(this._audioSource=new ns,this._audioSource.spatialBlend=0,this._audioSource.volume=1,this.gameObject.addComponent(this._audioSource)),c||(Lt&&console.log("PLAY",e.getAudioTracks()),this._audioSource.volume=1,(s=this._audioSource)==null||s.play(e))),c&&((o=this._net)==null||o.startSendingStream(e)),c&&(this._videoPlayer&&(this._videoPlayer.muted=!0),(r=this._audioSource)==null||r.stop());for(const h of e.getTracks())h.addEventListener("ended",()=>{Lt&&console.log("Track ended",h),this.close()}),Lt&&h.kind==="video"&&console.log(c?"Video \u2192":"Video \u2190",h.getSettings())}async tryShareUserCamera(e,t){const s=(await navigator.mediaDevices.enumerateDevices()).filter(r=>r.kind==="videoinput");Lt&&console.log(`Request camera. These are your kind:videoinput devices:
|
|
1378
|
+
`,s);let o=!1;for(const r of s)try{if(!this._requestOpen){Lt&&console.log("Camera selection cancelled");break}if(r.kind!=="videoinput"){Lt&&console.log("Skipping non-video device",r);continue}const l=r.deviceId;if(t?.deviceId!=null||t?.deviceFilter!=null){if(t?.deviceId!==void 0&&l!==t.deviceId){Lt&&console.log("Skipping device due to options.deviceId: "+r.label+"; "+r.deviceId);continue}if(t!=null&&t.deviceFilter&&t.deviceFilter(r)===!1){Lt&&console.log("Skipping device due to options.deviceFilter: "+r.label+"; "+r.deviceId);continue}}else if(this.deviceFilter)if(this.deviceFilter(r)===!1){Lt&&console.log("Skipping device due to ScreenShare.deviceFilter: "+r.label+"; "+r.deviceId);continue}else Lt&&console.log("Selected device by filter",r);else if(this.deviceName){const h=r.label.toLowerCase(),d=this.deviceName.toLowerCase(),u=h.includes(d),p=r.deviceId===this.deviceName;if(!u&&!p){Lt&&console.log("Skipping device due to ScreenShare.deviceName: "+r.label+"; "+r.deviceId);continue}else Lt&&console.log("Selected device by name",r)}e.video!==!1&&((typeof e.video>"u"||typeof e.video=="boolean")&&(e.video={}),e.video.deviceId=l),o=!0;const c=await navigator.mediaDevices.getUserMedia(e).catch(h=>(console.error("Failed to get user media",h),null));if(c===null)continue;this._requestOpen?(this.setStream(c,1),Lt&&console.log("Selected camera",r)):(on(c),Lt&&console.log("Camera selection cancelled"));break}catch(l){if(l.message==="Failed to allocate videosource"||l.message==="Could not start video source"){be("Failed to start video: Try another camera (Code "+l.code+")"),console.warn(l);continue}else console.error("Failed to get user media",l.message,l.code,l)}!o&&F()&&(be("No camera found for sharing. Please connect a camera (see console for more information)"),console.warn("No camera found for sharing. Please connect a camera",s,this.deviceName,"Using deviceFilter? "+this.deviceFilter!=null,"Using options? "+t!=null,"Using deviceName? "+this.deviceName!=null,"Using options.deviceId? "+t?.deviceId!=null,"Using options.deviceFilter? "+t?.deviceFilter!=null))}}Mh([m()],ar.prototype,"allowStartOnClick",2),Mh([m()],ar.prototype,"autoConnect",2),Mh([m(yt)],ar.prototype,"videoPlayer",1),Mh([m()],ar.prototype,"device",2),Mh([m()],ar.prototype,"deviceName",2);var xI=Object.defineProperty,PS=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&xI(e,t,o),o};class Rh extends I{constructor(){super(...arguments),a(this,"mode",0),a(this,"shadowColor",new he(0,0,0,1)),a(this,"targetMesh")}start(){if(this.gameObject instanceof G)this.gameObject instanceof G&&this.gameObject.material&&(this.gameObject.material=this.gameObject.material.clone(),this.targetMesh=this.gameObject,this.targetMesh.receiveShadow=!0);else{const e=wo.createPrimitive(Cr.Quad,{name:"ShadowCatcher",material:new bt({color:10066329,roughness:1,metalness:0,transparent:!0})});e.receiveShadow=!0,e.geometry.rotateX(-Math.PI/2),this.gameObject.add(e),this.targetMesh=e}if(!this.targetMesh){console.warn("ShadowCatcher: no mesh to apply shadow catching to. Groups are currently not supported.");return}switch(this.targetMesh.layers.set(2),this.mode){case 0:this.applyShadowMaterial();break;case 1:this.applyLightBlendMaterial();break;case 2:this.applyOccluderMaterial();break}}applyLightBlendMaterial(){if(!this.targetMesh)return;const e=this.targetMesh.material;e.blending=Uv,this.applyMaterialOptions(e),e.onBeforeCompile=t=>{t.fragmentShader=t.fragmentShader.replace("vec3 outgoingLight = totalDiffuse + totalSpecular + totalEmissiveRadiance;",`vec3 outgoingLight = totalDiffuse + totalSpecular + totalEmissiveRadiance;
|
|
1376
1379
|
// diffuse-only lighting with overdrive to somewhat compensate
|
|
1377
1380
|
// for the loss of indirect lighting and to make it more visible.
|
|
1378
1381
|
vec3 direct = (reflectedLight.directDiffuse + reflectedLight.directSpecular) * 6.6;
|
|
@@ -1382,12 +1385,12 @@ axisFormat %s
|
|
|
1382
1385
|
// be blended onto the scene.
|
|
1383
1386
|
gl_FragColor = vec4(direct, max);
|
|
1384
1387
|
return;
|
|
1385
|
-
`)},e.userData.isLightBlendMaterial=!0}applyShadowMaterial(){if(this.targetMesh)if(this.targetMesh.material.type!=="ShadowMaterial"){const e=new kv;e.color=this.shadowColor,e.opacity=this.shadowColor.alpha,this.applyMaterialOptions(e),this.targetMesh.material=e,e.userData.isShadowCatcherMaterial=!0}else{const e=this.targetMesh.material;e.color=this.shadowColor,e.opacity=this.shadowColor.alpha,this.applyMaterialOptions(e),e.userData.isShadowCatcherMaterial=!0}}applyOccluderMaterial(){if(this.targetMesh){let e=this.targetMesh.material;if(!e){const t=new Me;this.targetMesh.material=t,e=t}e.depthWrite=!0,e.stencilWrite=!0,e.colorWrite=!1,this.gameObject.renderOrder=-100}}applyMaterialOptions(e){e&&(e.depthWrite=!1,e.stencilWrite=!1)}}PS([m()],Rh.prototype,"mode"),PS([m(he)],Rh.prototype,"shadowColor");var xI=Object.defineProperty,Th=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&xI(e,t,o),o};const Gt=C("debugskybox");Ny("skybox-image"),Ny("environment-image");function OS(n,e,t,s,o){const r=new qp;r.allowDrop=!1,r.allowNetworking=!1,r.background=t,r.environment=s,P.addComponent(n.scene,r);const l=c=>{typeof c=="string"&&(Gt&&console.log(o,"CHANGED TO",c),r.setSkybox(c))};return pb(n.domElement,o,l),r.addEventListener("destroy",()=>{Gt&&console.log("Destroyed attribute remote skybox",o),mb(n.domElement,o,l)}),r.setSkybox(e)}const Gp=new Array;pe.registerCallback(me.ContextCreationStart,n=>{var e;const t=n.context,s=t.domElement.getAttribute("skybox-image")||t.domElement.getAttribute("background-image"),o=t.domElement.getAttribute("environment-image");if(s){Gt&&console.log("Creating remote skybox to load "+s),((e=t.mainCameraComponent)==null?void 0:e.clearFlags)!==Io.Skybox&&console.warn('"skybox-image"/"background-image" attribute has no effect: camera clearflags are not set to "Skybox"');const r=OS(t,s,!0,!1,"skybox-image");Gp.push(r)}if(o){Gt&&console.log("Creating remote environment to load "+o);const r=OS(t,o,!1,!0,"environment-image");Gp.push(r)}}),pe.registerCallback(me.ContextCreationStart,()=>Promise.all(Gp).finally(()=>{Gp.length=0}));function kS(){return globalThis.NEEDLE_ENGINE_SKYBOX_TEXTURES||(globalThis.NEEDLE_ENGINE_SKYBOX_TEXTURES=new Array),globalThis.NEEDLE_ENGINE_SKYBOX_TEXTURES}function MS(n){const e=kS().find(t=>t.src===n);return e?(Gt&&console.log("Skybox: Found previously loaded texture for "+n),e.texture):null}async function SI(n){const e=await n;qg(e,!0),Te(e)}function CI(n,e){const t=kS();for(;t.length>5;){const s=t.shift();s&&SI(s.texture)}e.then(s=>qg(s,!1)),t.push({src:n,texture:e})}const ha=class extends I{constructor(){super(...arguments),a(this,"url"),a(this,"allowDrop",!0),a(this,"background",!0),a(this,"environment",!0),a(this,"allowNetworking",!0),a(this,"_loader"),a(this,"_prevUrl"),a(this,"_prevLoadedEnvironment"),a(this,"_prevEnvironment",null),a(this,"_prevBackground",null),a(this,"validTextureTypes",[".ktx2",".hdr",".exr",".jpg",".jpeg",".png"]),a(this,"onDragOverEvent",n=>{if(this.allowDrop&&n.dataTransfer)for(const e of n.dataTransfer.types)(e==="text/uri-list"||e==="Files")&&n.preventDefault()}),a(this,"onDrop",n=>{var e,t,s,o;if(this.allowDrop&&n.dataTransfer){for(const r of n.dataTransfer.types)if(Gt&&console.log(r),r==="text/uri-list"){const l=n.dataTransfer.getData(r);Gt&&console.log(r,l);let c=(t=(e=new RegExp(/polyhaven.com\/asset_img\/.+?\/(?<name>.+)\.png/).exec(l))==null?void 0:e.groups)==null?void 0:t.name;if(c||(c=(o=(s=new RegExp(/polyhaven\.com\/a\/(?<name>.+)/).exec(l))==null?void 0:s.groups)==null?void 0:o.name),Gt&&console.log(c),c){const h="https://dl.polyhaven.org/file/ph-assets/HDRIs/exr/1k/"+c+"_1k.exr";console.log(`[Remote Skybox] Setting skybox from url: ${h}`),n.preventDefault(),this.setSkybox(h);break}else if(this.isValidTextureType(l)){console.log("[Remote Skybox] Setting skybox from url: "+l),n.preventDefault(),this.setSkybox(l);break}else{console.warn(`[RemoteSkybox] Unknown url ${l}. If you want to load a skybox from a url, make sure it is a valid image url. Url must end with${this.validTextureTypes.join(", ")}.`);const h=new CustomEvent("dropped-unknown-url",{detail:{sender:this,event:n,url:l,apply:d=>{n.preventDefault(),this.setSkybox(d)}}});this.dispatchEvent(h)}}else if(r=="Files"){const l=n.dataTransfer.files.item(0);if(Gt&&console.log(r,l),!l)continue;if(!this.isValidTextureType(l.name)){console.warn(`[RemoteSkybox]: File "${l.name}" is not supported. Supported files are ${this.validTextureTypes.join(", ")}`);return}if(MS(l.name)===null){const c=new Blob([l]),h=URL.createObjectURL(c);n.preventDefault(),this.setSkybox(h,l.name)}else n.preventDefault(),this.setSkybox(l.name);break}}})}onEnable(){this.setSkybox(this.url),this.registerDropEvents()}onDisable(){var n;this.context.scene.environment===this._prevLoadedEnvironment&&(this.context.scene.environment=this._prevEnvironment,ci.backgroundShouldBeTransparent(this.context)||(this.context.scene.background=this._prevBackground),this._prevLoadedEnvironment=void 0),this.unregisterDropEvents(),(n=this.context.mainCameraComponent)==null||n.applyClearFlags()}urlChangedSyncField(){this.allowNetworking&&this.url&&(this.isRemoteTexture(this.url)?this.setSkybox(this.url):Gt&&console.warn(`RemoteSkybox: Not setting skybox: ${this.url} is not a remote texture. If you want to set a local texture, set allowNetworking to false.`))}async setSkybox(n,e){var t;if(!this.activeAndEnabled||(n=PI(n,this.environment,this.background),!n))return!1;if(e??(e=n),this.isValidTextureType(e)||console.warn("Potentially invalid skybox url",e,"on",this.name),Gt&&console.log("Set remote skybox url: "+n),this._prevUrl===n&&this._prevLoadedEnvironment)return this.apply(),!0;(t=this._prevLoadedEnvironment)==null||t.dispose(),this._prevLoadedEnvironment=void 0,this._prevUrl=n;const s=await this.loadTexture(n,e);if(!s)return Gt&&console.warn("RemoteSkybox: Failed to load texture from url",n),!1;if(!this.enabled)return Gt&&console.warn("RemoteSkybox: Component is not enabled, aborting setSkybox"),!1;if(this._prevUrl!==n)return Gt&&console.warn("RemoteSkybox: URL changed while loading texture, aborting setSkybox"),!1;this.url=n;const o=n.lastIndexOf("/");return s.name=n.substring(o>=0?o+1:0),this._loader instanceof Sa&&(s.colorSpace=Mn),this._prevLoadedEnvironment=s,this.apply(),!0}async loadTexture(n,e){var t,s,o,r,l;if(!n)return Promise.resolve(null);e??(e=n);const c=MS(e);if(c){const g=await c;if(((s=(t=g.source)==null?void 0:t.data)==null?void 0:s.length)>0||(l=(r=(o=g.source)==null?void 0:o.data)==null?void 0:r.data)!=null&&l.length)return g}const h=e.endsWith(".exr"),d=e.endsWith(".hdr"),u=e.endsWith(".ktx2");if(h)this._loader instanceof Cd||(this._loader=new Cd);else if(d)this._loader instanceof Wm||(this._loader=new Wm);else if(u){if(!(this._loader instanceof hO)){const{ktx2Loader:g}=Nm(this.context.renderer);this._loader=g}}else this._loader instanceof Sa||(this._loader=new Sa);Gt&&console.log("Loading skybox: "+n);const p=this._loader.loadAsync(n);return CI(e,p),await p}apply(){var n;const e=this._prevLoadedEnvironment;e&&(e instanceof BP||e instanceof FP||(e.mapping=UP,e.needsUpdate=!0),this.context.scene.background!==e&&(this._prevBackground=this.context.scene.background),this.context.scene.environment!==e&&(this._prevEnvironment=this.context.scene.environment),Gt&&console.log("Set remote skybox",this.url,!ci.backgroundShouldBeTransparent(this.context)),this.environment&&(this.context.scene.environment=e),this.background&&!ci.backgroundShouldBeTransparent(this.context)&&(this.context.scene.background=e),((n=this.context.mainCameraComponent)==null?void 0:n.backgroundBlurriness)!==void 0&&(this.context.scene.backgroundBlurriness=this.context.mainCameraComponent.backgroundBlurriness))}isRemoteTexture(n){return n.startsWith("http://")||n.startsWith("https://")}isValidTextureType(n){for(const e of this.validTextureTypes)if(n.endsWith(e))return!0;return!1}registerDropEvents(){this.unregisterDropEvents(),this.context.domElement.addEventListener("dragover",this.onDragOverEvent),this.context.domElement.addEventListener("drop",this.onDrop)}unregisterDropEvents(){this.context.domElement.removeEventListener("dragover",this.onDragOverEvent),this.context.domElement.removeEventListener("drop",this.onDrop)}};Th([q0(ha.prototype.urlChangedSyncField),m(URL)],ha.prototype,"url"),Th([m()],ha.prototype,"allowDrop"),Th([m()],ha.prototype,"background"),Th([m()],ha.prototype,"environment"),Th([m()],ha.prototype,"allowNetworking");let qp=ha;function PI(n,e,t){const s=e&&!t;switch(n?.toLowerCase()){case"studio":return s?"https://cdn.needle.tools/static/skybox/modelviewer-Neutral-small.hdr":"https://cdn.needle.tools/static/skybox/modelviewer-Neutral.hdr";case"blurred-skybox":return s?"https://cdn.needle.tools/static/skybox/blurred-skybox-small.exr":"https://cdn.needle.tools/static/skybox/blurred-skybox.exr";case"quicklook-ar":return s?"https://cdn.needle.tools/static/skybox/QuickLook-ARMode-small.exr":"https://cdn.needle.tools/static/skybox/QuickLook-ARMode.exr";case"quicklook":return s?"https://cdn.needle.tools/static/skybox/QuickLook-ObjectMode-small.exr":"https://cdn.needle.tools/static/skybox/QuickLook-ObjectMode.exr"}return n===void 0?null:n}var OI=Object.defineProperty,Xp=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&OI(e,t,o),o},Qp;const Eh=(Qp=class extends I{constructor(){super(...arguments),a(this,"target",null),a(this,"followFactor",.1),a(this,"rotateFactor",.1),a(this,"positionAxes",Xa.All),a(this,"flipForward",!1),a(this,"_firstUpdate",!0)}onBeforeRender(){this.updateNow(!1)}updateNow(n){if(!(!this.target||this.target===this.gameObject)){if(this.followFactor>0){const e=ee(this.target),t=this._firstUpdate||n?1:W.clamp01(this.context.time.deltaTime*this.followFactor),s=this.worldPosition;this.positionAxes&Xa.X&&(s.x=W.lerp(s.x,e.x,t)),this.positionAxes&Xa.Y&&(s.y=W.lerp(s.y,e.y,t)),this.positionAxes&Xa.Z&&(s.z=W.lerp(s.z,e.z,t)),this.worldPosition=s}if(this.rotateFactor>0){const e=Se(this.target);this.flipForward&&e.premultiply(Qp._invertForward);const t=this._firstUpdate||n?1:W.clamp01(this.context.time.deltaTime*this.rotateFactor);this.worldQuaternion=this.worldQuaternion.slerp(e,t)}this._firstUpdate=!1}}},a(Qp,"_invertForward",new V().setFromAxisAngle(new S(0,1,0),Math.PI)),Qp);Xp([m(E)],Eh.prototype,"target"),Xp([m()],Eh.prototype,"followFactor"),Xp([m()],Eh.prototype,"rotateFactor"),Xp([m()],Eh.prototype,"positionAxes");let Yp=Eh;var kI=Object.defineProperty,Ah=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&kI(e,t,o),o};const Ih=C("debugspatialtrigger"),RS=new uo,TS=new uo;function MI(n,e){return RS.mask=n,TS.mask=e,RS.test(TS)}class vn extends I{constructor(){super(...arguments),a(this,"triggerMask",0),a(this,"onEnter"),a(this,"onStay"),a(this,"onExit"),a(this,"currentIntersected",[]),a(this,"lastIntersected",[])}start(){Ih&&console.log(this.name,this.triggerMask,this)}update(){this.currentIntersected.length=0;for(const e of Kp.triggers)MI(e.triggerMask,this.triggerMask)&&e.test(this.gameObject)&&this.currentIntersected.push(e);for(let e=this.lastIntersected.length-1;e>=0;e--){const t=this.lastIntersected[e];this.currentIntersected.indexOf(t)<0&&(this.onExitTrigger(t),this.lastIntersected.splice(e,1))}for(const e of this.currentIntersected)this.lastIntersected.indexOf(e)<0&&this.onEnterTrigger(e),this.onStayTrigger(e);this.lastIntersected.length=0,this.lastIntersected.push(...this.currentIntersected)}onEnterTrigger(e){var t;Ih&&console.log("ENTER TRIGGER",this.name,e.name,this,e),e.raiseOnEnterEvent(this),(t=this.onEnter)==null||t.invoke()}onExitTrigger(e){var t;Ih&&console.log("EXIT TRIGGER",this.name,e.name),e.raiseOnExitEvent(this),(t=this.onExit)==null||t.invoke()}onStayTrigger(e){var t;e.raiseOnStayEvent(this),(t=this.onStay)==null||t.invoke()}}Ah([m()],vn.prototype,"triggerMask"),Ah([m(xe)],vn.prototype,"onEnter"),Ah([m(xe)],vn.prototype,"onStay"),Ah([m(xe)],vn.prototype,"onExit");var Rl;const ES=(Rl=class extends I{constructor(){super(...arguments),a(this,"triggerMask"),a(this,"boxHelper")}start(){Ih&&console.log(this.name,this.triggerMask,this)}onEnable(){var n;Rl.triggers.push(this),this.boxHelper||(this.boxHelper=P.addComponent(this.gameObject,Bo),(n=this.boxHelper)==null||n.showHelper(null,Ih))}onDisable(){Rl.triggers.splice(Rl.triggers.indexOf(this),1)}test(n){return this.boxHelper?this.boxHelper.isInBox(n)??!1:!1}raiseOnEnterEvent(n){P.foreachComponent(this.gameObject,e=>{e!==n&&e instanceof vn&&e.onEnterTrigger(this)},!1)}raiseOnStayEvent(n){P.foreachComponent(this.gameObject,e=>{e!==n&&e instanceof vn&&e.onStayTrigger(this)},!1)}raiseOnExitEvent(n){P.foreachComponent(this.gameObject,e=>{e!==n&&e instanceof vn&&e.onExitTrigger(this)},!1)}},a(Rl,"triggers",[]),Rl);Ah([m()],ES.prototype,"triggerMask");let Kp=ES;var RI=Object.defineProperty,TI=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&RI(e,t,o),o};const Hi=C("debugspectator");class Zp extends I{constructor(){super(...arguments),a(this,"cam",null),a(this,"useKeys",!0),a(this,"_mode",0),a(this,"orbit",null),a(this,"_handler"),a(this,"eventSub_WebXRRequestStartEvent",null),a(this,"eventSub_WebXRStartEvent",null),a(this,"eventSub_WebXREndEvent",null),a(this,"_debug"),a(this,"_networking")}get mode(){return this._mode}set mode(e){this._mode=e}get isSpectating(){var e;return((e=this._handler)==null?void 0:e.currentTarget)!==void 0}isSpectatingUser(e){var t;return((t=this.target)==null?void 0:t.userId)===e}isFollowedBy(e){var t;return(t=this.followers)==null?void 0:t.includes(e)}get followers(){return this._networking.followers}stopSpectating(){if(this.context.isInXR){this.followSelf();return}this.target=void 0}get localId(){return this.context.connection.connectionId??"local"}set target(e){var t;if(this._handler){const s=(t=this._handler.currentTarget)==null?void 0:t.userId,o=this.context.players.getPlayerView(this.localId);e===void 0||this.context.isInXR===!1&&o?.currentObject===e.currentObject?this._handler.currentTarget!==void 0&&(this._handler.disable(),P.setActive(this.gameObject,!1),this.orbit&&(this.orbit.enabled=!0),this._networking.onSpectatedObjectChanged(e,s)):this._handler.currentTarget!==e&&(this._handler.set(e),P.setActive(this.gameObject,!0),this.orbit&&(this.orbit.enabled=!1),this._networking.onSpectatedObjectChanged(e,s))}}get target(){var e;return(e=this._handler)==null?void 0:e.currentTarget}requestAllFollowMe(){this._networking.onRequestFollowMe()}get isSpectatingSelf(){var e,t;return this.isSpectating&&((e=this.target)==null?void 0:e.currentObject)===((t=this.context.players.getPlayerView(this.localId))==null?void 0:t.currentObject)}awake(){if(this._debug=new II(this.context,this),this._networking=new DI(this.context,this),this._networking.awake(),P.setActive(this.gameObject,!1),this.cam=P.getComponent(this.gameObject,ci),!this.cam){console.warn("SpectatorCamera: Spectator camera needs camera component on the same object.",this);return}!this._handler&&this.cam&&(this._handler=new EI(this.context,this.cam,this)),this.orbit=P.getComponent(this.context.mainCamera,_e)}onDestroy(){var e,t;this.stopSpectating(),(e=this._handler)==null||e.destroy(),(t=this._networking)==null||t.destroy()}isSupportedPlatform(){const e=window.navigator.userAgent,t=/Windows|MacOS/.test(e),s=/Windows NT/.test(e)&&/Edg/.test(e)&&!/Win64/.test(e);return t&&!s}onBeforeXR(e){this.isSupportedPlatform()&&P.setActive(this.gameObject,!0)}onEnterXR(e){this.isSupportedPlatform()&&(Hi&&console.log(this.context.mainCamera),this.context.mainCamera&&this.followSelf())}onLeaveXR(e){var t,s;this.context.removeCamera(this.cam),P.setActive(this.gameObject,!1),this.orbit&&(this.orbit.enabled=!0),(t=this._handler)==null||t.set(void 0),(s=this._handler)==null||s.disable(),this.isSpectatingSelf&&this.stopSpectating()}followSelf(){this.target=this.context.players.getPlayerView(this.context.connection.connectionId),this.target||(this.context.players.setPlayerView(this.localId,this.context.mainCamera,Co.Headset),this.target=this.context.players.getPlayerView(this.localId)),Hi&&console.log("Follow self",this.target)}onAfterRender(){var e,t,s;if(!this.cam)return;const o=this.context.renderer,r=o.xr.enabled;if(!o.xr.isPresenting&&!((e=this._handler)!=null&&e.currentTarget))return;(t=this._handler)==null||t.update(this._mode);const l=o.getRenderTarget();let c=null;const h=o.state;if(!l){if(!o.state.bindFramebuffer||!h.bindXRFramebuffer)return;c=o._framebuffer,h.bindXRFramebuffer(null)}this.setAvatarFlagsBeforeRender();const d=this.context.mainCameraComponent;if(d){const g=d.backgroundColor;g&&o.setClearColor(g,g.alpha),this.cam.backgroundColor=g,this.cam.clearFlags=d.clearFlags,this.cam.nearClipPlane=d.nearClipPlane,this.cam.farClipPlane=d.farClipPlane}else o.setClearColor(new oe(1,1,1));o.setRenderTarget(null),o.xr.enabled=!1;const u=(s=this.cam)==null?void 0:s.threeCamera;this.context.updateAspect(u);const p=o.xr.isPresenting;o.xr.isPresenting=!1,o.setSize(this.context.domWidth,this.context.domHeight),o.render(this.context.scene,u),o.xr.isPresenting=p,o.xr.enabled=r,l?o.setRenderTarget(l):h.bindXRFramebuffer&&h.bindXRFramebuffer(c),this.resetAvatarFlags()}setAvatarFlagsBeforeRender(){const e=this._mode===0;for(const t of hi.instances)if(t.avatar&&"isLocalAvatar"in t.avatar&&"flags"in t.avatar){let s=rn.All;this.isSpectatingSelf&&(s=e&&t.avatar.isLocalAvatar?rn.FirstPerson:rn.ThirdPerson);const o=t.avatar.flags;if(!o)continue;for(const r of o)r.UpdateVisible(s)}}resetAvatarFlags(){var e;for(const t of hi.instances)if(t.avatar&&"flags"in t.avatar){const s=t.avatar.flags;if(!s)continue;for(const o of s)"isLocalAvatar"in t.avatar&&(e=t.avatar)!=null&&e.isLocalAvatar?o.UpdateVisible(rn.FirstPerson):o.UpdateVisible(rn.ThirdPerson)}}}TI([m()],Zp.prototype,"useKeys");class EI{constructor(e,t,s){a(this,"context"),a(this,"cam"),a(this,"spectator"),a(this,"follow"),a(this,"target"),a(this,"view"),a(this,"currentObject"),this.context=e,this.cam=t,this.spectator=s}get currentTarget(){return this.view}set(e){const t=e?.currentObject;if(!t){this.spectator.stopSpectating();return}t!==this.currentObject&&(this.currentObject=t,this.view=e,this.follow||(this.follow=P.addComponent(this.cam.gameObject,Yp)),this.target||(this.target=new E),t.add(this.target),this.follow.enabled=!0,this.follow.target=this.target,Hi&&console.log("FOLLOW",t),this.context.isInXR?this.context.removeCamera(this.cam):this.context.setCurrentCamera(this.cam))}disable(){Hi&&console.log("STOP FOLLOW",this.currentObject),this.view=void 0,this.currentObject=void 0,this.context.removeCamera(this.cam),this.follow&&(this.follow.enabled=!1)}destroy(){var e;(e=this.target)==null||e.removeFromParent(),this.follow&&P.destroy(this.follow)}update(e){var t,s,o,r,l,c;if(((t=this.currentTarget)==null?void 0:t.isConnected)===!1||((s=this.currentTarget)==null?void 0:s.removed)===!0){Hi&&console.log("Target disconnected or timeout",this.currentTarget),this.spectator.stopSpectating();return}this.currentTarget&&((o=this.currentTarget)==null?void 0:o.currentObject)!==this.currentObject&&(Hi&&console.log("Target changed",this.currentObject,"to",this.currentTarget.currentObject),this.set(this.currentTarget));const h=this.context.mainCamera;if(h){const u=this.cam.threeCamera;(u.near!==h.near||u.far!==h.far)&&(u.near=h.near,u.far=h.far,u.updateProjectionMatrix())}const d=(r=this.follow)==null?void 0:r.target;if(!(!d||!this.follow)){switch(e){case 0:((l=this.view)==null?void 0:l.viewDevice)!==Co.Browser?(this.follow.followFactor=5,this.follow.rotateFactor=5):(this.follow.followFactor=50,this.follow.rotateFactor=50),d.position.set(0,0,0);break;case 1:this.follow.followFactor=3,this.follow.rotateFactor=2,d.position.set(0,.5,1.5);break}this.follow.flipForward=!1,((c=this.view)==null?void 0:c.viewDevice)!==Co.Browser?d.quaternion.copy(AI):d.quaternion.identity()}}}const AI=new V().setFromAxisAngle(new S(0,1,0),Math.PI);class II{constructor(e,t){a(this,"context"),a(this,"spectator"),this.context=e,this.spectator=t,console.log("[Spectator Camera] Click other avatars or cameras to follow them. Press ESC to exit spectator mode."),this.context.domElement.addEventListener("keydown",o=>{!this.spectator.useKeys||o.key==="Escape"&&this.spectator.stopSpectating()});let s=0;this.context.input.addEventListener(Be.PointerDown,o=>{s=this.context.time.time}),this.context.input.addEventListener(Be.PointerUp,o=>{const r=this.context.time.time-s;r>1?this.spectator.stopSpectating():this.context.input.getPointerClicked(0)&&r<.3&&this.trySelectObject()})}trySelectObject(){const e=new Qs;e.setMask(16777215);const t=this.context.physics.raycast(e);if(Hi&&console.log(...t),t!=null&&t.length)for(const s of t){if(s.distance<.2)continue;const o=s.object,r=P.getComponentInParent(o,hi),l=r?.connectionId;if(l){const c=this.context.players.getPlayerView(l);this.spectator.target=c,Hi&&console.log("spectate",l,r);break}}}}class LI{constructor(e,t,s){a(this,"guid"),a(this,"dontSave",!0),a(this,"targetUserId"),a(this,"stoppedFollowing"),this.guid=e,this.targetUserId=t,this.stoppedFollowing=s}}class jI{constructor(e,t){a(this,"guid"),a(this,"userId"),this.guid=e.guid,this.userId=t}}class DI{constructor(e,t){a(this,"followers",[]),a(this,"context"),a(this,"spectator"),a(this,"_followerEventMethod"),a(this,"_requestFollowMethod"),a(this,"_joinedRoomMethod"),a(this,"_lastRequestFollowUser"),a(this,"_enforceFollowInterval"),this.context=e,this.spectator=t,this._followerEventMethod=this.onFollowerEvent.bind(this),this._requestFollowMethod=this.onRequestFollowEvent.bind(this),this._joinedRoomMethod=this.onUserJoinedRoom.bind(this)}awake(){this.context.connection.beginListen("spectator-follower-changed",this._followerEventMethod),this.context.connection.beginListen("spectator-request-follow",this._requestFollowMethod),this.context.connection.beginListen(ie.JoinedRoom,this._joinedRoomMethod),this.context.domElement.addEventListener("keydown",e=>{this.spectator.useKeys&&(e.key==="f"?this.onRequestFollowMe():e.key==="Escape"&&this.onRequestFollowMe(!0))})}destroy(){this.context.connection.stopListen("spectator-follower-changed",this._followerEventMethod),this.context.connection.stopListen("spectator-request-follow",this._requestFollowMethod),this.context.connection.stopListen(ie.JoinedRoom,this._joinedRoomMethod)}onSpectatedObjectChanged(e,t){if(Hi&&console.log(this.context.connection.connectionId,"onSpectatedObjectChanged",e,t),this.context.connection.connectionId){const s=e?.userId===void 0,o=s?t:e?.userId,r=new LI(this.context.connection.connectionId,o,s);this.context.connection.send("spectator-follower-changed",r)}}onRequestFollowMe(e=!1){if(Hi&&console.log("Request follow",this.context.connection.connectionId),this.context.connection.connectionId){this.spectator.stopSpectating();const t=e?void 0:this.context.connection.connectionId,s=new jI(this.spectator,t);this.context.connection.send("spectator-request-follow",s)}}onUserJoinedRoom(){C("followme")&&this.onRequestFollowMe()}onFollowerEvent(e){const t=e.targetUserId,s=e.guid;if(Hi&&console.log(e),t===this.context.connection.connectionId)if(e.stoppedFollowing){const o=this.followers.indexOf(s);o!==-1&&(this.followers.splice(o,1),this.removeDisconnectedFollowers(),console.log(s,"unfollows you",this.followers.length))}else this.followers.includes(s)||(this.followers.push(s),this.removeDisconnectedFollowers(),console.log(s,"follows you",this.followers.length))}removeDisconnectedFollowers(){for(let e=this.followers.length-1;e>=0;e--){const t=this.followers[e];this.context.connection.userIsInRoom(t)===!1&&this.followers.splice(e,1)}}onRequestFollowEvent(e){if(this._lastRequestFollowUser=e,e.userId===this.context.connection.connectionId)this.spectator.stopSpectating();else if(e.userId===void 0)this.spectator.stopSpectating();else{const t=this.context.players.getPlayerView(e.userId);if(t)this.spectator.target=t;else return Hi&&console.warn("Could not find view",e.userId),this.enforceFollow(),!1}return!0}enforceFollow(){this._enforceFollowInterval||(this._enforceFollowInterval=setInterval(()=>{this._lastRequestFollowUser===void 0||this._lastRequestFollowUser.userId&&this.spectator.isFollowedBy(this._lastRequestFollowUser.userId)?(clearInterval(this._enforceFollowInterval),this._enforceFollowInterval=void 0):(Hi&&console.log("REQUEST FOLLOW AGAIN",this._lastRequestFollowUser.userId),this.onRequestFollowEvent(this._lastRequestFollowUser))},1e3))}}class Sn{constructor(){a(this,"bb",null),a(this,"bb_pos",0)}__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsSyncedCameraModel(e,t){return(t||new Sn).__init(e.readInt32(e.position())+e.position(),e)}static getSizePrefixedRootAsSyncedCameraModel(e,t){return e.setPosition(e.position()+Kv),(t||new Sn).__init(e.readInt32(e.position())+e.position(),e)}userId(e){const t=this.bb.__offset(this.bb_pos,4);return t?this.bb.__string(this.bb_pos+t,e):null}guid(e){const t=this.bb.__offset(this.bb_pos,6);return t?this.bb.__string(this.bb_pos+t,e):null}dontSave(){const e=this.bb.__offset(this.bb_pos,8);return e?!!this.bb.readInt8(this.bb_pos+e):!1}pos(e){const t=this.bb.__offset(this.bb_pos,10);return t?(e||new Ur).__init(this.bb_pos+t,this.bb):null}rot(e){const t=this.bb.__offset(this.bb_pos,12);return t?(e||new Ur).__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)}}var BI=Object.defineProperty,FI=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&BI(e,t,o),o};const Jp="SCAM";Tg(Jp,Sn.getRootAsSyncedCameraModel);const Gi=new $m;class UI{constructor(e,t){a(this,"userId"),a(this,"guid"),this.guid=t,this.userId=e}send(e,t){if(e){Gi.clear();const s=Gi.createString(this.guid),o=Gi.createString(this.userId);Sn.startSyncedCameraModel(Gi),Sn.addGuid(Gi,s),Sn.addUserId(Gi,o);const r=ee(e),l=Ad(e);Sn.addPos(Gi,Ur.createVec3(Gi,r.x,r.y,r.z)),Sn.addRot(Gi,Ur.createVec3(Gi,l.x,l.y,l.z));const c=Sn.endSyncedCameraModel(Gi);Gi.finish(c,Jp),t.sendBinary(Gi.asUint8Array())}}}var Lh;const AS=(Lh=class extends I{constructor(){super(...arguments),a(this,"cameraPrefab",null),a(this,"_lastWorldPosition"),a(this,"_lastWorldQuaternion"),a(this,"_model",null),a(this,"_needsUpdate",!0),a(this,"_lastUpdateTime",0),a(this,"remoteCams",{}),a(this,"userToCamMap",{}),a(this,"_camTimeoutInSeconds",10),a(this,"_receiveCallback",null)}getCameraObject(n){const e=this.userToCamMap[n];return e?this.remoteCams[e].obj: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))}onEnable(){this._receiveCallback=this.context.connection.beginListenBinary(Jp,this.onReceivedRemoteCameraInfoBin.bind(this))}onDisable(){this.context.connection.stopListenBinary(Jp,this._receiveCallback)}update(){for(const s in this.remoteCams){const o=this.remoteCams[s],r=this.context.time.realtimeSinceStartup-o.lastUpdate;if(!o||r>this._camTimeoutInSeconds){F()&&console.log("Remote cam timeout",s),o!=null&&o.obj&&P.destroy(o.obj),delete this.remoteCams[s],o&&delete this.userToCamMap[o.userId],Lh.instances.push(o),this.context.players.removePlayerView(o.userId,Co.Browser);continue}}if(this.context.isInXR)return;const n=this.context.mainCamera;if(n===null){this.enabled=!1;return}if(!this.context.connection.isConnected||this.context.connection.connectionId===null)return;this._model===null&&(this._model=new UI(this.context.connection.connectionId,this.context.connection.connectionId+"_camera"));const e=ee(n),t=Se(n);(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(n,this.context.connection),this.context.isInXR||this.context.players.setPlayerView(this.context.connection.connectionId,n,Co.Browser))}onReceivedRemoteCameraInfoBin(n){const e=n.guid();if(!e)return;const t=n.userId();if(!t||!this.context.connection.userIsInRoom(t)||!this.cameraPrefab)return;let s=this.remoteCams[e];if(!s)if("isObject3D"in this.cameraPrefab){const c=new Fs;c.context=this.context;const h=P.instantiate(this.cameraPrefab,c);s=this.remoteCams[e]={obj:h,lastUpdate:this.context.time.realtimeSinceStartup,userId:t},s.obj.visible=!0,this.gameObject.add(h),this.userToCamMap[t]=e,Lh.instances.push(s);const d=P.getOrAddComponent(h,hi);d.connectionId=t,d.avatar=h}else return;const o=s.obj;this.context.players.setPlayerView(t,o,Co.Browser),s.lastUpdate=this.context.time.realtimeSinceStartup,ms.markDirty(o);const r=n.pos();r&&br(o,r.x(),r.y(),r.z());const l=n.rot();l&&Zl(o,l.x(),l.y(),l.z())}},a(Lh,"instances",[]),Lh);FI([m([E,ce])],AS.prototype,"cameraPrefab");let Wy=AS;var zI=Object.defineProperty,NI=Object.getOwnPropertyDescriptor,lr=(n,e,t,s)=>{for(var o=s>1?void 0:s?NI(e,t):e,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=(s?l(e,t,o):l(o))||o);return s&&o&&zI(e,t,o),o};const Vy="view",$y=C("debugsyncedroom");class Ls extends I{constructor(){super(...arguments),a(this,"roomName",""),a(this,"urlParameterName","room"),a(this,"joinRandomRoom"),a(this,"requireRoomParameter",!1),a(this,"autoRejoin",!0),a(this,"createJoinButton",!0),a(this,"createViewOnlyButton",!1),a(this,"_lastJoinedRoom"),a(this,"_roomPrefix",""),a(this,"_lastPingTime",0),a(this,"_lastRoomTime",-1),a(this,"_userWantsToBeInARoom",!1),a(this,"_roomButton"),a(this,"_roomButtonIconJoin"),a(this,"_roomButtonIconLeave"),a(this,"updateRoomButtonState",()=>{var e,t;this._roomButton&&(this.context.connection.isInRoom?(this._roomButton.title="Leave the networked room",this._roomButton.textContent="Leave Room",(e=this._roomButtonIconJoin)==null||e.remove(),this._roomButton.prepend(this._roomButtonIconLeave)):(this._roomButton.title="Create or join a networked room",this._roomButton.textContent="Join Room",(t=this._roomButtonIconLeave)==null||t.remove(),this._roomButton.prepend(this._roomButtonIconJoin)))}),a(this,"_viewOnlyButton"),a(this,"onCreateViewOnlyButton",()=>{if(!this._viewOnlyButton){const e=document.createElement("button");this._viewOnlyButton=e,e.classList.add("view-only-button"),e.setAttribute("priority","90"),e.onclick=()=>{var t;const s=this.getViewOnlyUrl();s!=null&&s.length?navigator.canShare({url:s})?(t=navigator.share({url:s}))==null||t.catch(o=>{console.warn(o)}):(navigator.clipboard.writeText(s),De("View only URL copied to clipboard")):be("Could not create view only URL")},e.title="Copy the view only URL: A page accessed by the view only URL can not be modified by visiting users.",e.textContent="Share View URL",e.prepend(Mt("visibility"))}this.context.menu.appendChild(this._viewOnlyButton)})}get currentRoomName(){return C(Vy)||C(this.urlParameterName)}set roomPrefix(e){this._roomPrefix=e}get roomPrefix(){return this._roomPrefix}awake(){var e;this.joinRandomRoom===void 0&&((e=this.roomName)==null?void 0:e.length)<=0&&(this.joinRandomRoom=!0),$y&&console.log(`SyncedRoom roomName:${this.roomName}, urlParamName:${this.urlParameterName}, joinRandomRoom:${this.joinRandomRoom}`)}onEnable(){const e=C(Vy);if(e&&typeof e=="string"&&e.length>0){console.log("Join as viewer"),this.context.connection.joinRoom(e,!0);return}if(this.tryJoinRoom(),this.createJoinButton){const t=this.createRoomButton();this.context.menu.appendChild(t)}this.createViewOnlyButton&&this.onEnableViewOnlyButton()}onDisable(){var e;(e=this._roomButton)==null||e.remove(),this.onDisableViewOnlyButton(),this.roomName&&this.roomName.length>0&&this.context.connection.leaveRoom(this.roomName)}onDestroy(){this.destroyRoomButton()}tryJoinRandomRoom(){this.setRandomRoomUrlParameter(),this.tryJoinRoom()}tryJoinRoom(e=0){var t;e===void 0&&(e=0);let s=!1;if(((t=this.urlParameterName)==null?void 0:t.length)>0){const o=C(this.urlParameterName);if(o&&(typeof o=="string"||typeof o=="number")){s=!0;const r=db(o.toString());this.roomName=r}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)&&(this.roomName=this.generateRoomName());return this.requireRoomParameter&&!s?(($y||F())&&console.warn('[SyncedRoom] Missing required room parameter "'+this.urlParameterName+`" in url - will not connect.
|
|
1388
|
+
`)},e.userData.isLightBlendMaterial=!0}applyShadowMaterial(){if(this.targetMesh)if(this.targetMesh.material.type!=="ShadowMaterial"){const e=new kv;e.color=this.shadowColor,e.opacity=this.shadowColor.alpha,this.applyMaterialOptions(e),this.targetMesh.material=e,e.userData.isShadowCatcherMaterial=!0}else{const e=this.targetMesh.material;e.color=this.shadowColor,e.opacity=this.shadowColor.alpha,this.applyMaterialOptions(e),e.userData.isShadowCatcherMaterial=!0}}applyOccluderMaterial(){if(this.targetMesh){let e=this.targetMesh.material;if(!e){const t=new Me;this.targetMesh.material=t,e=t}e.depthWrite=!0,e.stencilWrite=!0,e.colorWrite=!1,this.gameObject.renderOrder=-100}}applyMaterialOptions(e){e&&(e.depthWrite=!1,e.stencilWrite=!1)}}PS([m()],Rh.prototype,"mode"),PS([m(he)],Rh.prototype,"shadowColor");var SI=Object.defineProperty,Th=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&SI(e,t,o),o};const Gt=C("debugskybox");Ny("background-image"),Ny("environment-image");function OS(n,e,t,s,o){const r=new qp;r.allowDrop=!1,r.allowNetworking=!1,r.background=t,r.environment=s,P.addComponent(n.scene,r);const l=c=>{typeof c=="string"&&(Gt&&console.log(o,"CHANGED TO",c),r.setSkybox(c))};return pb(n.domElement,o,l),r.addEventListener("destroy",()=>{Gt&&console.log("Destroyed attribute remote skybox",o),mb(n.domElement,o,l)}),r.setSkybox(e)}const Gp=new Array;pe.registerCallback(me.ContextCreationStart,n=>{var e;const t=n.context,s=t.domElement.getAttribute("background-image"),o=t.domElement.getAttribute("environment-image");if(s){Gt&&console.log("Creating remote skybox to load "+s),((e=t.mainCameraComponent)==null?void 0:e.clearFlags)!==Io.Skybox&&console.warn('"background-image" attribute has no effect: camera clear flags are not set to "Skybox"');const r=OS(t,s,!0,!1,"background-image");Gp.push(r)}if(o){Gt&&console.log("Creating remote environment to load "+o);const r=OS(t,o,!1,!0,"environment-image");Gp.push(r)}}),pe.registerCallback(me.ContextCreationStart,()=>Promise.all(Gp).finally(()=>{Gp.length=0}));function kS(){return globalThis.NEEDLE_ENGINE_SKYBOX_TEXTURES||(globalThis.NEEDLE_ENGINE_SKYBOX_TEXTURES=new Array),globalThis.NEEDLE_ENGINE_SKYBOX_TEXTURES}function MS(n){const e=kS().find(t=>t.src===n);return e?(Gt&&console.log("Skybox: Found previously loaded texture for "+n),e.texture):null}async function CI(n){const e=await n;qg(e,!0),Te(e)}function PI(n,e){const t=kS();for(;t.length>5;){const s=t.shift();s&&CI(s.texture)}e.then(s=>qg(s,!1)),t.push({src:n,texture:e})}const ha=class extends I{constructor(){super(...arguments),a(this,"url"),a(this,"allowDrop",!0),a(this,"background",!0),a(this,"environment",!0),a(this,"allowNetworking",!0),a(this,"_loader"),a(this,"_prevUrl"),a(this,"_prevLoadedEnvironment"),a(this,"_prevEnvironment",null),a(this,"_prevBackground",null),a(this,"validTextureTypes",[".ktx2",".hdr",".exr",".jpg",".jpeg",".png"]),a(this,"onDragOverEvent",n=>{if(this.allowDrop&&n.dataTransfer)for(const e of n.dataTransfer.types)(e==="text/uri-list"||e==="Files")&&n.preventDefault()}),a(this,"onDrop",n=>{var e,t,s,o;if(this.allowDrop&&n.dataTransfer){for(const r of n.dataTransfer.types)if(Gt&&console.log(r),r==="text/uri-list"){const l=n.dataTransfer.getData(r);Gt&&console.log(r,l);let c=(t=(e=new RegExp(/polyhaven.com\/asset_img\/.+?\/(?<name>.+)\.png/).exec(l))==null?void 0:e.groups)==null?void 0:t.name;if(c||(c=(o=(s=new RegExp(/polyhaven\.com\/a\/(?<name>.+)/).exec(l))==null?void 0:s.groups)==null?void 0:o.name),Gt&&console.log(c),c){const h="https://dl.polyhaven.org/file/ph-assets/HDRIs/exr/1k/"+c+"_1k.exr";console.log(`[Remote Skybox] Setting skybox from url: ${h}`),n.preventDefault(),this.setSkybox(h);break}else if(this.isValidTextureType(l)){console.log("[Remote Skybox] Setting skybox from url: "+l),n.preventDefault(),this.setSkybox(l);break}else{console.warn(`[RemoteSkybox] Unknown url ${l}. If you want to load a skybox from a url, make sure it is a valid image url. Url must end with${this.validTextureTypes.join(", ")}.`);const h=new CustomEvent("dropped-unknown-url",{detail:{sender:this,event:n,url:l,apply:d=>{n.preventDefault(),this.setSkybox(d)}}});this.dispatchEvent(h)}}else if(r=="Files"){const l=n.dataTransfer.files.item(0);if(Gt&&console.log(r,l),!l)continue;if(!this.isValidTextureType(l.name)){console.warn(`[RemoteSkybox]: File "${l.name}" is not supported. Supported files are ${this.validTextureTypes.join(", ")}`);return}if(MS(l.name)===null){const c=new Blob([l]),h=URL.createObjectURL(c);n.preventDefault(),this.setSkybox(h,l.name)}else n.preventDefault(),this.setSkybox(l.name);break}}})}onEnable(){this.setSkybox(this.url),this.registerDropEvents()}onDisable(){var n;this.context.scene.environment===this._prevLoadedEnvironment&&(this.context.scene.environment=this._prevEnvironment,ci.backgroundShouldBeTransparent(this.context)||(this.context.scene.background=this._prevBackground),this._prevLoadedEnvironment=void 0),this.unregisterDropEvents(),(n=this.context.mainCameraComponent)==null||n.applyClearFlags()}urlChangedSyncField(){this.allowNetworking&&this.url&&(this.isRemoteTexture(this.url)?this.setSkybox(this.url):Gt&&console.warn(`RemoteSkybox: Not setting skybox: ${this.url} is not a remote texture. If you want to set a local texture, set allowNetworking to false.`))}async setSkybox(n,e){var t;if(!this.activeAndEnabled||(n=OI(n,this.environment,this.background),!n))return!1;if(e??(e=n),this.isValidTextureType(e)||console.warn("Potentially invalid skybox url",e,"on",this.name),Gt&&console.log("Set remote skybox url: "+n),this._prevUrl===n&&this._prevLoadedEnvironment)return this.apply(),!0;(t=this._prevLoadedEnvironment)==null||t.dispose(),this._prevLoadedEnvironment=void 0,this._prevUrl=n;const s=await this.loadTexture(n,e);if(!s)return Gt&&console.warn("RemoteSkybox: Failed to load texture from url",n),!1;if(!this.enabled)return Gt&&console.warn("RemoteSkybox: Component is not enabled, aborting setSkybox"),!1;if(this._prevUrl!==n)return Gt&&console.warn("RemoteSkybox: URL changed while loading texture, aborting setSkybox"),!1;this.url=n;const o=n.lastIndexOf("/");return s.name=n.substring(o>=0?o+1:0),this._loader instanceof Sa&&(s.colorSpace=Mn),this._prevLoadedEnvironment=s,this.apply(),!0}async loadTexture(n,e){var t,s,o,r,l;if(!n)return Promise.resolve(null);e??(e=n);const c=MS(e);if(c){const g=await c;if(((s=(t=g.source)==null?void 0:t.data)==null?void 0:s.length)>0||(l=(r=(o=g.source)==null?void 0:o.data)==null?void 0:r.data)!=null&&l.length)return g}const h=e.endsWith(".exr"),d=e.endsWith(".hdr"),u=e.endsWith(".ktx2");if(h)this._loader instanceof Cd||(this._loader=new Cd);else if(d)this._loader instanceof Wm||(this._loader=new Wm);else if(u){if(!(this._loader instanceof hO)){const{ktx2Loader:g}=Nm(this.context.renderer);this._loader=g}}else this._loader instanceof Sa||(this._loader=new Sa);Gt&&console.log("Loading skybox: "+n);const p=this._loader.loadAsync(n);return PI(e,p),await p}apply(){var n;const e=this._prevLoadedEnvironment;e&&(e instanceof BP||e instanceof FP||(e.mapping=UP,e.needsUpdate=!0),this.context.scene.background!==e&&(this._prevBackground=this.context.scene.background),this.context.scene.environment!==e&&(this._prevEnvironment=this.context.scene.environment),Gt&&console.log("Set remote skybox",this.url,!ci.backgroundShouldBeTransparent(this.context)),this.environment&&(this.context.scene.environment=e),this.background&&!ci.backgroundShouldBeTransparent(this.context)&&(this.context.scene.background=e),((n=this.context.mainCameraComponent)==null?void 0:n.backgroundBlurriness)!==void 0&&(this.context.scene.backgroundBlurriness=this.context.mainCameraComponent.backgroundBlurriness))}isRemoteTexture(n){return n.startsWith("http://")||n.startsWith("https://")}isValidTextureType(n){for(const e of this.validTextureTypes)if(n.endsWith(e))return!0;return!1}registerDropEvents(){this.unregisterDropEvents(),this.context.domElement.addEventListener("dragover",this.onDragOverEvent),this.context.domElement.addEventListener("drop",this.onDrop)}unregisterDropEvents(){this.context.domElement.removeEventListener("dragover",this.onDragOverEvent),this.context.domElement.removeEventListener("drop",this.onDrop)}};Th([q0(ha.prototype.urlChangedSyncField),m(URL)],ha.prototype,"url"),Th([m()],ha.prototype,"allowDrop"),Th([m()],ha.prototype,"background"),Th([m()],ha.prototype,"environment"),Th([m()],ha.prototype,"allowNetworking");let qp=ha;function OI(n,e,t){const s=e&&!t;switch(n?.toLowerCase()){case"studio":return s?"https://cdn.needle.tools/static/skybox/modelviewer-Neutral-small.hdr":"https://cdn.needle.tools/static/skybox/modelviewer-Neutral.hdr";case"blurred-skybox":return s?"https://cdn.needle.tools/static/skybox/blurred-skybox-small.exr":"https://cdn.needle.tools/static/skybox/blurred-skybox.exr";case"quicklook-ar":return s?"https://cdn.needle.tools/static/skybox/QuickLook-ARMode-small.exr":"https://cdn.needle.tools/static/skybox/QuickLook-ARMode.exr";case"quicklook":return s?"https://cdn.needle.tools/static/skybox/QuickLook-ObjectMode-small.exr":"https://cdn.needle.tools/static/skybox/QuickLook-ObjectMode.exr"}return n===void 0?null:n}var kI=Object.defineProperty,Xp=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&kI(e,t,o),o},Qp;const Eh=(Qp=class extends I{constructor(){super(...arguments),a(this,"target",null),a(this,"followFactor",.1),a(this,"rotateFactor",.1),a(this,"positionAxes",Xa.All),a(this,"flipForward",!1),a(this,"_firstUpdate",!0)}onBeforeRender(){this.updateNow(!1)}updateNow(n){if(!(!this.target||this.target===this.gameObject)){if(this.followFactor>0){const e=ee(this.target),t=this._firstUpdate||n?1:W.clamp01(this.context.time.deltaTime*this.followFactor),s=this.worldPosition;this.positionAxes&Xa.X&&(s.x=W.lerp(s.x,e.x,t)),this.positionAxes&Xa.Y&&(s.y=W.lerp(s.y,e.y,t)),this.positionAxes&Xa.Z&&(s.z=W.lerp(s.z,e.z,t)),this.worldPosition=s}if(this.rotateFactor>0){const e=Se(this.target);this.flipForward&&e.premultiply(Qp._invertForward);const t=this._firstUpdate||n?1:W.clamp01(this.context.time.deltaTime*this.rotateFactor);this.worldQuaternion=this.worldQuaternion.slerp(e,t)}this._firstUpdate=!1}}},a(Qp,"_invertForward",new V().setFromAxisAngle(new S(0,1,0),Math.PI)),Qp);Xp([m(E)],Eh.prototype,"target"),Xp([m()],Eh.prototype,"followFactor"),Xp([m()],Eh.prototype,"rotateFactor"),Xp([m()],Eh.prototype,"positionAxes");let Yp=Eh;var MI=Object.defineProperty,Ah=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&MI(e,t,o),o};const Ih=C("debugspatialtrigger"),RS=new uo,TS=new uo;function RI(n,e){return RS.mask=n,TS.mask=e,RS.test(TS)}class vn extends I{constructor(){super(...arguments),a(this,"triggerMask",0),a(this,"onEnter"),a(this,"onStay"),a(this,"onExit"),a(this,"currentIntersected",[]),a(this,"lastIntersected",[])}start(){Ih&&console.log(this.name,this.triggerMask,this)}update(){this.currentIntersected.length=0;for(const e of Kp.triggers)RI(e.triggerMask,this.triggerMask)&&e.test(this.gameObject)&&this.currentIntersected.push(e);for(let e=this.lastIntersected.length-1;e>=0;e--){const t=this.lastIntersected[e];this.currentIntersected.indexOf(t)<0&&(this.onExitTrigger(t),this.lastIntersected.splice(e,1))}for(const e of this.currentIntersected)this.lastIntersected.indexOf(e)<0&&this.onEnterTrigger(e),this.onStayTrigger(e);this.lastIntersected.length=0,this.lastIntersected.push(...this.currentIntersected)}onEnterTrigger(e){var t;Ih&&console.log("ENTER TRIGGER",this.name,e.name,this,e),e.raiseOnEnterEvent(this),(t=this.onEnter)==null||t.invoke()}onExitTrigger(e){var t;Ih&&console.log("EXIT TRIGGER",this.name,e.name),e.raiseOnExitEvent(this),(t=this.onExit)==null||t.invoke()}onStayTrigger(e){var t;e.raiseOnStayEvent(this),(t=this.onStay)==null||t.invoke()}}Ah([m()],vn.prototype,"triggerMask"),Ah([m(xe)],vn.prototype,"onEnter"),Ah([m(xe)],vn.prototype,"onStay"),Ah([m(xe)],vn.prototype,"onExit");var Rl;const ES=(Rl=class extends I{constructor(){super(...arguments),a(this,"triggerMask"),a(this,"boxHelper")}start(){Ih&&console.log(this.name,this.triggerMask,this)}onEnable(){var n;Rl.triggers.push(this),this.boxHelper||(this.boxHelper=P.addComponent(this.gameObject,Bo),(n=this.boxHelper)==null||n.showHelper(null,Ih))}onDisable(){Rl.triggers.splice(Rl.triggers.indexOf(this),1)}test(n){return this.boxHelper?this.boxHelper.isInBox(n)??!1:!1}raiseOnEnterEvent(n){P.foreachComponent(this.gameObject,e=>{e!==n&&e instanceof vn&&e.onEnterTrigger(this)},!1)}raiseOnStayEvent(n){P.foreachComponent(this.gameObject,e=>{e!==n&&e instanceof vn&&e.onStayTrigger(this)},!1)}raiseOnExitEvent(n){P.foreachComponent(this.gameObject,e=>{e!==n&&e instanceof vn&&e.onExitTrigger(this)},!1)}},a(Rl,"triggers",[]),Rl);Ah([m()],ES.prototype,"triggerMask");let Kp=ES;var TI=Object.defineProperty,EI=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&TI(e,t,o),o};const Hi=C("debugspectator");class Zp extends I{constructor(){super(...arguments),a(this,"cam",null),a(this,"useKeys",!0),a(this,"_mode",0),a(this,"orbit",null),a(this,"_handler"),a(this,"eventSub_WebXRRequestStartEvent",null),a(this,"eventSub_WebXRStartEvent",null),a(this,"eventSub_WebXREndEvent",null),a(this,"_debug"),a(this,"_networking")}get mode(){return this._mode}set mode(e){this._mode=e}get isSpectating(){var e;return((e=this._handler)==null?void 0:e.currentTarget)!==void 0}isSpectatingUser(e){var t;return((t=this.target)==null?void 0:t.userId)===e}isFollowedBy(e){var t;return(t=this.followers)==null?void 0:t.includes(e)}get followers(){return this._networking.followers}stopSpectating(){if(this.context.isInXR){this.followSelf();return}this.target=void 0}get localId(){return this.context.connection.connectionId??"local"}set target(e){var t;if(this._handler){const s=(t=this._handler.currentTarget)==null?void 0:t.userId,o=this.context.players.getPlayerView(this.localId);e===void 0||this.context.isInXR===!1&&o?.currentObject===e.currentObject?this._handler.currentTarget!==void 0&&(this._handler.disable(),P.setActive(this.gameObject,!1),this.orbit&&(this.orbit.enabled=!0),this._networking.onSpectatedObjectChanged(e,s)):this._handler.currentTarget!==e&&(this._handler.set(e),P.setActive(this.gameObject,!0),this.orbit&&(this.orbit.enabled=!1),this._networking.onSpectatedObjectChanged(e,s))}}get target(){var e;return(e=this._handler)==null?void 0:e.currentTarget}requestAllFollowMe(){this._networking.onRequestFollowMe()}get isSpectatingSelf(){var e,t;return this.isSpectating&&((e=this.target)==null?void 0:e.currentObject)===((t=this.context.players.getPlayerView(this.localId))==null?void 0:t.currentObject)}awake(){if(this._debug=new LI(this.context,this),this._networking=new BI(this.context,this),this._networking.awake(),P.setActive(this.gameObject,!1),this.cam=P.getComponent(this.gameObject,ci),!this.cam){console.warn("SpectatorCamera: Spectator camera needs camera component on the same object.",this);return}!this._handler&&this.cam&&(this._handler=new AI(this.context,this.cam,this)),this.orbit=P.getComponent(this.context.mainCamera,_e)}onDestroy(){var e,t;this.stopSpectating(),(e=this._handler)==null||e.destroy(),(t=this._networking)==null||t.destroy()}isSupportedPlatform(){const e=window.navigator.userAgent,t=/Windows|MacOS/.test(e),s=/Windows NT/.test(e)&&/Edg/.test(e)&&!/Win64/.test(e);return t&&!s}onBeforeXR(e){this.isSupportedPlatform()&&P.setActive(this.gameObject,!0)}onEnterXR(e){this.isSupportedPlatform()&&(Hi&&console.log(this.context.mainCamera),this.context.mainCamera&&this.followSelf())}onLeaveXR(e){var t,s;this.context.removeCamera(this.cam),P.setActive(this.gameObject,!1),this.orbit&&(this.orbit.enabled=!0),(t=this._handler)==null||t.set(void 0),(s=this._handler)==null||s.disable(),this.isSpectatingSelf&&this.stopSpectating()}followSelf(){this.target=this.context.players.getPlayerView(this.context.connection.connectionId),this.target||(this.context.players.setPlayerView(this.localId,this.context.mainCamera,Co.Headset),this.target=this.context.players.getPlayerView(this.localId)),Hi&&console.log("Follow self",this.target)}onAfterRender(){var e,t,s;if(!this.cam)return;const o=this.context.renderer,r=o.xr.enabled;if(!o.xr.isPresenting&&!((e=this._handler)!=null&&e.currentTarget))return;(t=this._handler)==null||t.update(this._mode);const l=o.getRenderTarget();let c=null;const h=o.state;if(!l){if(!o.state.bindFramebuffer||!h.bindXRFramebuffer)return;c=o._framebuffer,h.bindXRFramebuffer(null)}this.setAvatarFlagsBeforeRender();const d=this.context.mainCameraComponent;if(d){const g=d.backgroundColor;g&&o.setClearColor(g,g.alpha),this.cam.backgroundColor=g,this.cam.clearFlags=d.clearFlags,this.cam.nearClipPlane=d.nearClipPlane,this.cam.farClipPlane=d.farClipPlane}else o.setClearColor(new oe(1,1,1));o.setRenderTarget(null),o.xr.enabled=!1;const u=(s=this.cam)==null?void 0:s.threeCamera;this.context.updateAspect(u);const p=o.xr.isPresenting;o.xr.isPresenting=!1,o.setSize(this.context.domWidth,this.context.domHeight),o.render(this.context.scene,u),o.xr.isPresenting=p,o.xr.enabled=r,l?o.setRenderTarget(l):h.bindXRFramebuffer&&h.bindXRFramebuffer(c),this.resetAvatarFlags()}setAvatarFlagsBeforeRender(){const e=this._mode===0;for(const t of hi.instances)if(t.avatar&&"isLocalAvatar"in t.avatar&&"flags"in t.avatar){let s=rn.All;this.isSpectatingSelf&&(s=e&&t.avatar.isLocalAvatar?rn.FirstPerson:rn.ThirdPerson);const o=t.avatar.flags;if(!o)continue;for(const r of o)r.UpdateVisible(s)}}resetAvatarFlags(){var e;for(const t of hi.instances)if(t.avatar&&"flags"in t.avatar){const s=t.avatar.flags;if(!s)continue;for(const o of s)"isLocalAvatar"in t.avatar&&(e=t.avatar)!=null&&e.isLocalAvatar?o.UpdateVisible(rn.FirstPerson):o.UpdateVisible(rn.ThirdPerson)}}}EI([m()],Zp.prototype,"useKeys");class AI{constructor(e,t,s){a(this,"context"),a(this,"cam"),a(this,"spectator"),a(this,"follow"),a(this,"target"),a(this,"view"),a(this,"currentObject"),this.context=e,this.cam=t,this.spectator=s}get currentTarget(){return this.view}set(e){const t=e?.currentObject;if(!t){this.spectator.stopSpectating();return}t!==this.currentObject&&(this.currentObject=t,this.view=e,this.follow||(this.follow=P.addComponent(this.cam.gameObject,Yp)),this.target||(this.target=new E),t.add(this.target),this.follow.enabled=!0,this.follow.target=this.target,Hi&&console.log("FOLLOW",t),this.context.isInXR?this.context.removeCamera(this.cam):this.context.setCurrentCamera(this.cam))}disable(){Hi&&console.log("STOP FOLLOW",this.currentObject),this.view=void 0,this.currentObject=void 0,this.context.removeCamera(this.cam),this.follow&&(this.follow.enabled=!1)}destroy(){var e;(e=this.target)==null||e.removeFromParent(),this.follow&&P.destroy(this.follow)}update(e){var t,s,o,r,l,c;if(((t=this.currentTarget)==null?void 0:t.isConnected)===!1||((s=this.currentTarget)==null?void 0:s.removed)===!0){Hi&&console.log("Target disconnected or timeout",this.currentTarget),this.spectator.stopSpectating();return}this.currentTarget&&((o=this.currentTarget)==null?void 0:o.currentObject)!==this.currentObject&&(Hi&&console.log("Target changed",this.currentObject,"to",this.currentTarget.currentObject),this.set(this.currentTarget));const h=this.context.mainCamera;if(h){const u=this.cam.threeCamera;(u.near!==h.near||u.far!==h.far)&&(u.near=h.near,u.far=h.far,u.updateProjectionMatrix())}const d=(r=this.follow)==null?void 0:r.target;if(!(!d||!this.follow)){switch(e){case 0:((l=this.view)==null?void 0:l.viewDevice)!==Co.Browser?(this.follow.followFactor=5,this.follow.rotateFactor=5):(this.follow.followFactor=50,this.follow.rotateFactor=50),d.position.set(0,0,0);break;case 1:this.follow.followFactor=3,this.follow.rotateFactor=2,d.position.set(0,.5,1.5);break}this.follow.flipForward=!1,((c=this.view)==null?void 0:c.viewDevice)!==Co.Browser?d.quaternion.copy(II):d.quaternion.identity()}}}const II=new V().setFromAxisAngle(new S(0,1,0),Math.PI);class LI{constructor(e,t){a(this,"context"),a(this,"spectator"),this.context=e,this.spectator=t,console.log("[Spectator Camera] Click other avatars or cameras to follow them. Press ESC to exit spectator mode."),this.context.domElement.addEventListener("keydown",o=>{!this.spectator.useKeys||o.key==="Escape"&&this.spectator.stopSpectating()});let s=0;this.context.input.addEventListener(Be.PointerDown,o=>{s=this.context.time.time}),this.context.input.addEventListener(Be.PointerUp,o=>{const r=this.context.time.time-s;r>1?this.spectator.stopSpectating():this.context.input.getPointerClicked(0)&&r<.3&&this.trySelectObject()})}trySelectObject(){const e=new Qs;e.setMask(16777215);const t=this.context.physics.raycast(e);if(Hi&&console.log(...t),t!=null&&t.length)for(const s of t){if(s.distance<.2)continue;const o=s.object,r=P.getComponentInParent(o,hi),l=r?.connectionId;if(l){const c=this.context.players.getPlayerView(l);this.spectator.target=c,Hi&&console.log("spectate",l,r);break}}}}class jI{constructor(e,t,s){a(this,"guid"),a(this,"dontSave",!0),a(this,"targetUserId"),a(this,"stoppedFollowing"),this.guid=e,this.targetUserId=t,this.stoppedFollowing=s}}class DI{constructor(e,t){a(this,"guid"),a(this,"userId"),this.guid=e.guid,this.userId=t}}class BI{constructor(e,t){a(this,"followers",[]),a(this,"context"),a(this,"spectator"),a(this,"_followerEventMethod"),a(this,"_requestFollowMethod"),a(this,"_joinedRoomMethod"),a(this,"_lastRequestFollowUser"),a(this,"_enforceFollowInterval"),this.context=e,this.spectator=t,this._followerEventMethod=this.onFollowerEvent.bind(this),this._requestFollowMethod=this.onRequestFollowEvent.bind(this),this._joinedRoomMethod=this.onUserJoinedRoom.bind(this)}awake(){this.context.connection.beginListen("spectator-follower-changed",this._followerEventMethod),this.context.connection.beginListen("spectator-request-follow",this._requestFollowMethod),this.context.connection.beginListen(ie.JoinedRoom,this._joinedRoomMethod),this.context.domElement.addEventListener("keydown",e=>{this.spectator.useKeys&&(e.key==="f"?this.onRequestFollowMe():e.key==="Escape"&&this.onRequestFollowMe(!0))})}destroy(){this.context.connection.stopListen("spectator-follower-changed",this._followerEventMethod),this.context.connection.stopListen("spectator-request-follow",this._requestFollowMethod),this.context.connection.stopListen(ie.JoinedRoom,this._joinedRoomMethod)}onSpectatedObjectChanged(e,t){if(Hi&&console.log(this.context.connection.connectionId,"onSpectatedObjectChanged",e,t),this.context.connection.connectionId){const s=e?.userId===void 0,o=s?t:e?.userId,r=new jI(this.context.connection.connectionId,o,s);this.context.connection.send("spectator-follower-changed",r)}}onRequestFollowMe(e=!1){if(Hi&&console.log("Request follow",this.context.connection.connectionId),this.context.connection.connectionId){this.spectator.stopSpectating();const t=e?void 0:this.context.connection.connectionId,s=new DI(this.spectator,t);this.context.connection.send("spectator-request-follow",s)}}onUserJoinedRoom(){C("followme")&&this.onRequestFollowMe()}onFollowerEvent(e){const t=e.targetUserId,s=e.guid;if(Hi&&console.log(e),t===this.context.connection.connectionId)if(e.stoppedFollowing){const o=this.followers.indexOf(s);o!==-1&&(this.followers.splice(o,1),this.removeDisconnectedFollowers(),console.log(s,"unfollows you",this.followers.length))}else this.followers.includes(s)||(this.followers.push(s),this.removeDisconnectedFollowers(),console.log(s,"follows you",this.followers.length))}removeDisconnectedFollowers(){for(let e=this.followers.length-1;e>=0;e--){const t=this.followers[e];this.context.connection.userIsInRoom(t)===!1&&this.followers.splice(e,1)}}onRequestFollowEvent(e){if(this._lastRequestFollowUser=e,e.userId===this.context.connection.connectionId)this.spectator.stopSpectating();else if(e.userId===void 0)this.spectator.stopSpectating();else{const t=this.context.players.getPlayerView(e.userId);if(t)this.spectator.target=t;else return Hi&&console.warn("Could not find view",e.userId),this.enforceFollow(),!1}return!0}enforceFollow(){this._enforceFollowInterval||(this._enforceFollowInterval=setInterval(()=>{this._lastRequestFollowUser===void 0||this._lastRequestFollowUser.userId&&this.spectator.isFollowedBy(this._lastRequestFollowUser.userId)?(clearInterval(this._enforceFollowInterval),this._enforceFollowInterval=void 0):(Hi&&console.log("REQUEST FOLLOW AGAIN",this._lastRequestFollowUser.userId),this.onRequestFollowEvent(this._lastRequestFollowUser))},1e3))}}class Sn{constructor(){a(this,"bb",null),a(this,"bb_pos",0)}__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsSyncedCameraModel(e,t){return(t||new Sn).__init(e.readInt32(e.position())+e.position(),e)}static getSizePrefixedRootAsSyncedCameraModel(e,t){return e.setPosition(e.position()+Kv),(t||new Sn).__init(e.readInt32(e.position())+e.position(),e)}userId(e){const t=this.bb.__offset(this.bb_pos,4);return t?this.bb.__string(this.bb_pos+t,e):null}guid(e){const t=this.bb.__offset(this.bb_pos,6);return t?this.bb.__string(this.bb_pos+t,e):null}dontSave(){const e=this.bb.__offset(this.bb_pos,8);return e?!!this.bb.readInt8(this.bb_pos+e):!1}pos(e){const t=this.bb.__offset(this.bb_pos,10);return t?(e||new Ur).__init(this.bb_pos+t,this.bb):null}rot(e){const t=this.bb.__offset(this.bb_pos,12);return t?(e||new Ur).__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)}}var FI=Object.defineProperty,UI=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&FI(e,t,o),o};const Jp="SCAM";Tg(Jp,Sn.getRootAsSyncedCameraModel);const Gi=new $m;class zI{constructor(e,t){a(this,"userId"),a(this,"guid"),this.guid=t,this.userId=e}send(e,t){if(e){Gi.clear();const s=Gi.createString(this.guid),o=Gi.createString(this.userId);Sn.startSyncedCameraModel(Gi),Sn.addGuid(Gi,s),Sn.addUserId(Gi,o);const r=ee(e),l=Ad(e);Sn.addPos(Gi,Ur.createVec3(Gi,r.x,r.y,r.z)),Sn.addRot(Gi,Ur.createVec3(Gi,l.x,l.y,l.z));const c=Sn.endSyncedCameraModel(Gi);Gi.finish(c,Jp),t.sendBinary(Gi.asUint8Array())}}}var Lh;const AS=(Lh=class extends I{constructor(){super(...arguments),a(this,"cameraPrefab",null),a(this,"_lastWorldPosition"),a(this,"_lastWorldQuaternion"),a(this,"_model",null),a(this,"_needsUpdate",!0),a(this,"_lastUpdateTime",0),a(this,"remoteCams",{}),a(this,"userToCamMap",{}),a(this,"_camTimeoutInSeconds",10),a(this,"_receiveCallback",null)}getCameraObject(n){const e=this.userToCamMap[n];return e?this.remoteCams[e].obj: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))}onEnable(){this._receiveCallback=this.context.connection.beginListenBinary(Jp,this.onReceivedRemoteCameraInfoBin.bind(this))}onDisable(){this.context.connection.stopListenBinary(Jp,this._receiveCallback)}update(){for(const s in this.remoteCams){const o=this.remoteCams[s],r=this.context.time.realtimeSinceStartup-o.lastUpdate;if(!o||r>this._camTimeoutInSeconds){F()&&console.log("Remote cam timeout",s),o!=null&&o.obj&&P.destroy(o.obj),delete this.remoteCams[s],o&&delete this.userToCamMap[o.userId],Lh.instances.push(o),this.context.players.removePlayerView(o.userId,Co.Browser);continue}}if(this.context.isInXR)return;const n=this.context.mainCamera;if(n===null){this.enabled=!1;return}if(!this.context.connection.isConnected||this.context.connection.connectionId===null)return;this._model===null&&(this._model=new zI(this.context.connection.connectionId,this.context.connection.connectionId+"_camera"));const e=ee(n),t=Se(n);(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(n,this.context.connection),this.context.isInXR||this.context.players.setPlayerView(this.context.connection.connectionId,n,Co.Browser))}onReceivedRemoteCameraInfoBin(n){const e=n.guid();if(!e)return;const t=n.userId();if(!t||!this.context.connection.userIsInRoom(t)||!this.cameraPrefab)return;let s=this.remoteCams[e];if(!s)if("isObject3D"in this.cameraPrefab){const c=new Fs;c.context=this.context;const h=P.instantiate(this.cameraPrefab,c);s=this.remoteCams[e]={obj:h,lastUpdate:this.context.time.realtimeSinceStartup,userId:t},s.obj.visible=!0,this.gameObject.add(h),this.userToCamMap[t]=e,Lh.instances.push(s);const d=P.getOrAddComponent(h,hi);d.connectionId=t,d.avatar=h}else return;const o=s.obj;this.context.players.setPlayerView(t,o,Co.Browser),s.lastUpdate=this.context.time.realtimeSinceStartup,ms.markDirty(o);const r=n.pos();r&&br(o,r.x(),r.y(),r.z());const l=n.rot();l&&Zl(o,l.x(),l.y(),l.z())}},a(Lh,"instances",[]),Lh);UI([m([E,ce])],AS.prototype,"cameraPrefab");let Wy=AS;var NI=Object.defineProperty,WI=Object.getOwnPropertyDescriptor,lr=(n,e,t,s)=>{for(var o=s>1?void 0:s?WI(e,t):e,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=(s?l(e,t,o):l(o))||o);return s&&o&&NI(e,t,o),o};const Vy="view",$y=C("debugsyncedroom");class Ls extends I{constructor(){super(...arguments),a(this,"roomName",""),a(this,"urlParameterName","room"),a(this,"joinRandomRoom"),a(this,"requireRoomParameter",!1),a(this,"autoRejoin",!0),a(this,"createJoinButton",!0),a(this,"createViewOnlyButton",!1),a(this,"_lastJoinedRoom"),a(this,"_roomPrefix",""),a(this,"_lastPingTime",0),a(this,"_lastRoomTime",-1),a(this,"_userWantsToBeInARoom",!1),a(this,"_roomButton"),a(this,"_roomButtonIconJoin"),a(this,"_roomButtonIconLeave"),a(this,"updateRoomButtonState",()=>{var e,t;this._roomButton&&(this.context.connection.isInRoom?(this._roomButton.title="Leave the networked room",this._roomButton.textContent="Leave Room",(e=this._roomButtonIconJoin)==null||e.remove(),this._roomButton.prepend(this._roomButtonIconLeave)):(this._roomButton.title="Create or join a networked room",this._roomButton.textContent="Join Room",(t=this._roomButtonIconLeave)==null||t.remove(),this._roomButton.prepend(this._roomButtonIconJoin)))}),a(this,"_viewOnlyButton"),a(this,"onCreateViewOnlyButton",()=>{if(!this._viewOnlyButton){const e=document.createElement("button");this._viewOnlyButton=e,e.classList.add("view-only-button"),e.setAttribute("priority","90"),e.onclick=()=>{var t;const s=this.getViewOnlyUrl();s!=null&&s.length?navigator.canShare({url:s})?(t=navigator.share({url:s}))==null||t.catch(o=>{console.warn(o)}):(navigator.clipboard.writeText(s),De("View only URL copied to clipboard")):be("Could not create view only URL")},e.title="Copy the view only URL: A page accessed by the view only URL can not be modified by visiting users.",e.textContent="Share View URL",e.prepend(Mt("visibility"))}this.context.menu.appendChild(this._viewOnlyButton)})}get currentRoomName(){return C(Vy)||C(this.urlParameterName)}set roomPrefix(e){this._roomPrefix=e}get roomPrefix(){return this._roomPrefix}awake(){var e;this.joinRandomRoom===void 0&&((e=this.roomName)==null?void 0:e.length)<=0&&(this.joinRandomRoom=!0),$y&&console.log(`SyncedRoom roomName:${this.roomName}, urlParamName:${this.urlParameterName}, joinRandomRoom:${this.joinRandomRoom}`)}onEnable(){const e=C(Vy);if(e&&typeof e=="string"&&e.length>0){console.log("Join as viewer"),this.context.connection.joinRoom(e,!0);return}if(this.tryJoinRoom(),this.createJoinButton){const t=this.createRoomButton();this.context.menu.appendChild(t)}this.createViewOnlyButton&&this.onEnableViewOnlyButton()}onDisable(){var e;(e=this._roomButton)==null||e.remove(),this.onDisableViewOnlyButton(),this.roomName&&this.roomName.length>0&&this.context.connection.leaveRoom(this.roomName)}onDestroy(){this.destroyRoomButton()}tryJoinRandomRoom(){this.setRandomRoomUrlParameter(),this.tryJoinRoom()}tryJoinRoom(e=0){var t;e===void 0&&(e=0);let s=!1;if(((t=this.urlParameterName)==null?void 0:t.length)>0){const o=C(this.urlParameterName);if(o&&(typeof o=="string"||typeof o=="number")){s=!0;const r=db(o.toString());this.roomName=r}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)&&(this.roomName=this.generateRoomName());return this.requireRoomParameter&&!s?(($y||F())&&console.warn('[SyncedRoom] Missing required room parameter "'+this.urlParameterName+`" in url - will not connect.
|
|
1386
1389
|
To allow joining a room without a query parameter you can set "requireRoomParameter" to false.`),!1):(this.context.connection.isConnected||this.context.connection.connect(),this._lastJoinedRoom=this.roomName,this._roomPrefix&&(this.roomName=this._roomPrefix+this.roomName),this.roomName.length<=0?(console.warn(`[SyncedRoom] Room name is not set so we can not join a networked room.
|
|
1387
1390
|
Please choose one of the following options to fix this:
|
|
1388
1391
|
A) Set a room name in the SyncedRoom component
|
|
1389
1392
|
B) Set a room name in the URL parameter "?`+this.urlParameterName+`=my_room"
|
|
1390
|
-
C) Set "joinRandomRoom" to true`),!1):($y&&console.log("Join "+this.roomName),this._userWantsToBeInARoom=!0,this.context.connection.joinRoom(this.roomName),!0))}update(){this.context.connection.isConnected&&(this.context.time.time-this._lastPingTime>3&&(this._lastPingTime=this.context.time.time,this.context.connection.sendPing()),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?this._userWantsToBeInARoom&&(console.log("Disconnected from networking backend - attempt reconnecting now"),this.tryJoinRoom()):F()&&console.warn("You are not connected to a room anymore (possibly because the tab was inactive for too long and the server kicked you?)"))}getViewOnlyUrl(){if(this.context.connection.isConnected&&this.context.connection.currentRoomViewId){const e=window.location.search,t=new URLSearchParams(e);return t.has(this.urlParameterName)&&t.delete(this.urlParameterName),t.set(Vy,this.context.connection.currentRoomViewId),window.location.origin+window.location.pathname+"?"+t.toString()}return null}setRandomRoomUrlParameter(){const e=Hl(),t=this.generateRoomName();C(this.urlParameterName)?e.set(this.urlParameterName,t):e.append(this.urlParameterName,t),Ym(t,e)}generateRoomName(){let e="";for(let t=0;t<6;t++)e+=Math.floor(Math.random()*10).toFixed(0);return e}createRoomButton(){if(this._roomButton)return this._roomButton;const e=document.createElement("button");return this._roomButton=e,e.classList.add("create-room-button"),e.setAttribute("priority","90"),e.onclick=()=>{if(this.context.connection.isInRoom)this.urlParameterName&&Gl(this.urlParameterName,null),this.context.connection.leaveRoom(),this._userWantsToBeInARoom=!1;else{if(this.urlParameterName){const t=C(this.urlParameterName);(!t||t===!0)&&(this._lastJoinedRoom?Gl(this.urlParameterName,this._lastJoinedRoom):this.setRandomRoomUrlParameter())}this.tryJoinRoom()}},this._roomButtonIconJoin=Mt("group"),this._roomButtonIconLeave=Mt("group_off"),this.updateRoomButtonState(),this.context.connection.beginListen(ie.JoinedRoom,this.updateRoomButtonState),this.context.connection.beginListen(ie.LeftRoom,this.updateRoomButtonState),e}destroyRoomButton(){this.context.connection.stopListen(ie.JoinedRoom,this.updateRoomButtonState),this.context.connection.stopListen(ie.LeftRoom,this.updateRoomButtonState)}onEnableViewOnlyButton(){this.context.connection.isConnected?this.onCreateViewOnlyButton():(this.context.connection.stopListen(ie.JoinedRoom,this.onCreateViewOnlyButton),this.context.connection.beginListen(ie.JoinedRoom,this.onCreateViewOnlyButton))}onDisableViewOnlyButton(){var e;this.context.connection.stopListen(ie.JoinedRoom,this.onCreateViewOnlyButton),(e=this._viewOnlyButton)==null||e.remove()}}lr([m()],Ls.prototype,"roomName",2),lr([m()],Ls.prototype,"urlParameterName",2),lr([m()],Ls.prototype,"joinRandomRoom",2),lr([m()],Ls.prototype,"requireRoomParameter",2),lr([m()],Ls.prototype,"autoRejoin",2),lr([m()],Ls.prototype,"createJoinButton",2),lr([m()],Ls.prototype,"createViewOnlyButton",2),lr([m()],Ls.prototype,"roomPrefix",1);function WI(){const n=C("testwindowcount")||0;n&&n>0&&VI(n)}function VI(n){if(C("testwindow"))return null;const e=new URL(window.location.href);Qm(e.searchParams,$T,1),Qm(e.searchParams,"testwindow",1);const t=e.toString(),s=[];window.onbeforeunload=()=>{for(const h of s)h.close()};const o=.05,r=128;let l=0,c=0;for(let h=0;h<n;h++){l*r+r*.01>=window.innerWidth&&(c+=1,l=0);const d=l*(r*(1+o))+window.screenLeft,u=c*(r*(1+o))+window.screenTop+90+60*c;l+=1;const p=window.open(t,"test window "+h,`popup=yes width=${r} height=${r} top=${u} left=${d}`);if(!p){console.warn("Failed to open window");continue}s.push(p),p.onload=()=>{p.onbeforeunload=()=>{for(let g=0;g<s.length;g++){const f=s[g];f!==p&&f.close()}s.length=0}}}return s}class Hy extends I{awake(){WI()}}class Gy extends I{constructor(){super(...arguments),a(this,"transformsPerFrame",10),a(this,"interval",0),a(this,"useFlatbuffers",!0),a(this,"builder",null),a(this,"models",null)}awake(){if(this.useFlatbuffers)this.context.connection.beginListenBinary(Lc,e=>{});else{this.models=[];for(let e=0;e<this.transformsPerFrame;e++)this.models.push(new IS(this.context.connection.connectionId+"_simulatedTransform_"+e,this))}}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 $m(1024));const e=this.builder;for(let t=0;t<this.transformsPerFrame;t++){e.clear();const s=xx(this.context.connection.connectionId,this);this.context.connection.sendBinary(s)}}else if(this.models)for(let e=0;e<this.models.length;e++){const t=this.models[e];t.dontSave=!0,t.update(this,null),this.context.connection.send("TestSimulateUserData-"+e,t)}}}}class IS{constructor(e,t){a(this,"guid"),a(this,"fast",!1),a(this,"position"),a(this,"rotation"),a(this,"velocity"),a(this,"dontSave"),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)}isValid(){return this.fast!==void 0||this.position!==void 0||this.rotation!==void 0||this.velocity!==void 0}update(e,t){const s=e.worldPosition;this.position.x=s.x,this.position.y=s.y,this.position.z=s.z;const o=e.worldQuaternion;if(this.rotation.x=o.x,this.rotation.y=o.y,this.rotation.z=o.z,this.rotation.w=o.w,this.fast=!1,t){const 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}}}a(IS,"temp",new S);var $I=Object.defineProperty,em=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&$I(e,t,o),o};const HI=C("debugsignals");class tm{constructor(){a(this,"guid")}}em([m()],tm.prototype,"guid");class jh{constructor(){a(this,"signal"),a(this,"reaction")}}em([m(tm)],jh.prototype,"signal"),em([m(xe)],jh.prototype,"reaction");var js;const LS=(js=class extends I{constructor(){super(...arguments),a(this,"events")}static invoke(n){if(js.receivers[n]){const e=js.receivers[n];if(!e)return;for(const t of e)t.invoke(n)}}awake(){HI&&console.log("SignalReceiver awake",this)}onEnable(){if(this.events)for(const n of this.events)js.receivers[n.signal.guid]||(js.receivers[n.signal.guid]=[]),js.receivers[n.signal.guid].push(this)}onDisable(){if(this.events){for(const n of this.events)if(js.receivers[n.signal.guid]){const e=js.receivers[n.signal.guid].indexOf(this);e>=0&&js.receivers[n.signal.guid].splice(e,1)}}}invoke(n){if(!this.events||!Array.isArray(this.events))return;const e=typeof n=="object"?n.guid:n;for(const t of this.events)if(t.signal.guid===e)try{if(t.reaction){if(!t.reaction.invoke){console.warn("Missing invoke - possibly a serialization error",t,this);continue}}else{console.warn("Missing reaction for signal",t,this);continue}t.reaction.invoke()}catch(s){console.error(s)}}},a(js,"receivers",{}),js);em([m(jh)],LS.prototype,"events");let Dh=LS;var qi=(n=>(n.Activation="ActivationTrack",n.Animation="AnimationTrack",n.Audio="AudioTrack",n.Control="ControlTrack",n.Marker="MarkerTrack",n.Signal="SignalTrack",n))(qi||{}),bn=(n=>(n[n.None=0]="None",n[n.Hold=1]="Hold",n[n.Loop=2]="Loop",n[n.PingPong=3]="PingPong",n[n.Continue=4]="Continue",n))(bn||{}),qy=(n=>(n.Signal="SignalEmitter",n))(qy||{});const _n=C("debugtimeline");class Bh{constructor(){a(this,"director"),a(this,"track")}get muted(){return this.track.muted}set muted(e){var t;e!==this.track.muted&&(this.track.muted=e,(t=this.onMuteChanged)==null||t.call(this))}*forEachClip(e=!1){var t;if((t=this.track)!=null&&t.clips)if(e)for(let s=this.track.clips.length-1;s>=0;s--)yield this.track.clips[s];else for(const s of this.track.clips)yield s}getClipTime(e,t){return t.clipIn+(e-t.start)*t.timeScale}getClipTimeNormalized(e,t){return(e-t.start)/t.duration}evaluateWeight(e,t,s,o=!0){if(t<0||t>=s.length)return 0;const r=s[t];if(o||e>=r.start&&e<=r.end){let l=1;if(r.easeInDuration>0){const c=Math.min((e-r.start)/r.easeInDuration,1);l*=c}if(r.easeOutDuration>0){const c=Math.min((r.end-e)/r.easeOutDuration,1);l*=c}return l}return 0}}class GI{constructor(e){a(this,"clip"),a(this,"rootPositionOffset"),a(this,"rootQuaternionOffset"),a(this,"rootStartPosition"),a(this,"rootEndPosition"),a(this,"rootStartQuaternion"),a(this,"rootEndQuaternion");const t=e.getClip();this.clip=t;const s=e.getRoot(),o=s.name+".position",r=s.name+".quaternion";_n&&console.log(t.name,t.tracks,o);for(const l of t.tracks)if(!(l.times.length<=0)){if(l.name.endsWith(o))this.rootStartPosition=new S().fromArray(l.values,0),this.rootEndPosition=new S().fromArray(l.values,l.values.length-3),this.rootPositionOffset=this.rootEndPosition.clone().sub(this.rootStartPosition),_n&&console.log(this.rootPositionOffset);else if(l.name.endsWith(r)&&(this.rootStartQuaternion=new V().fromArray(l.values,0),this.rootEndQuaternion=new V().fromArray(l.values,l.values.length-4),this.rootQuaternionOffset=this.rootEndQuaternion.clone().multiply(this.rootStartQuaternion),_n)){const c=new Dt().setFromQuaternion(this.rootQuaternionOffset);console.log("ROT",c)}}}get hasOffsets(){return this.rootPositionOffset!==void 0||this.rootQuaternionOffset!==void 0}}class im extends Bh{constructor(){super(...arguments),a(this,"models",[]),a(this,"trackOffset"),a(this,"target"),a(this,"mixer"),a(this,"clips",[]),a(this,"actions",[]),a(this,"weight",1),a(this,"_actionOffsets",[]),a(this,"_didBind",!1),a(this,"_animator",null),a(this,"_useclipOffsets",!0),a(this,"_totalOffsetPosition",new S),a(this,"_totalOffsetRotation",new V),a(this,"_totalOffsetPosition2",new S),a(this,"_totalOffsetRotation2",new V),a(this,"_summedPos",new S),a(this,"_tempPos",new S),a(this,"_summedRot",new V),a(this,"_tempRot",new V),a(this,"_clipRotQuat",new V)}onDisable(){var e;(e=this.mixer)==null||e.stopAllAction()}onDestroy(){this.director.context.animations.unregisterAnimationMixer(this.mixer)}onStateChanged(){this._animator&&px(this._animator.gameObject,this,this.director.isPlaying)}createHooks(e,t){var s,o;if(((s=t.tracks)==null?void 0:s.length)<=0){console.warn("No tracks in AnimationClip",t);return}const r=t.tracks[0].name.split("."),l=r[r.length-2],c=l+".position",h=l+".quaternion";let d=!1,u=!1;for(const p of t.tracks)p.name.endsWith(c)?(d=!0,this.createPositionInterpolant(t,e,p)):p.name.endsWith(h)&&(u=!0,this.createRotationInterpolant(t,e,p));if(!d||!u){const p=(o=this.mixer)==null?void 0:o.getRoot(),g=t.tracks[0],f=g.name.lastIndexOf("."),y=g.name.substring(0,f),v=y.substring(y.lastIndexOf(".")+1),b=p.getObjectByName(v);if(b)if(d){if(!u){const _=t.tracks[0].name.substring(0,f)+".quaternion";_n&&console.warn("Create quaternion track",v,b);const w=b.quaternion,x=new NP(_,[0,t.duration],[w.x,w.y,w.z,w.w,w.x,w.y,w.z,w.w]);t.tracks.push(x),this.createRotationInterpolant(t,e,x)}}else{const _=y+".position";_n&&console.warn("Create position track",v,b);const w=b.position,x=new zP(_,[0,t.duration],[w.x,w.y,w.z,w.x,w.y,w.z]);t.tracks.push(x),this.createPositionInterpolant(t,e,x)}}}bind(){if(!this._didBind){this._didBind=!0,_n&&console.log(this.models),this.mixer?this.target=this.mixer.getRoot():console.warn("No mixer was assigned to animation track");for(const e of this.actions){const t=new GI(e);this._actionOffsets.push(t)}this.target&&(this._animator=P.getComponent(this.target,Rt)??null,this._animator&&px(this._animator.gameObject,this,!0));for(const e of this.models){const t=e.asset,s=t.position,o=t.rotation;s&&s.x!==void 0&&(s.isVector3||(t.position=new S(s.x,s.y,s.z)),o.isQuaternion||(t.rotation=new V(o.x,o.y,o.z,o.w)))}this.ensureTrackOffsets()}}ensureTrackOffsets(){if(this.trackOffset){const e=this.trackOffset.position;e&&(e.isVector3||(this.trackOffset.position=new S(e.x,e.y,e.z)));const t=this.trackOffset.rotation;t&&(t.isQuaternion||(this.trackOffset.rotation=new V(t.x,t.y,t.z,t.w)))}}evaluate(e){var t,s,o,r,l,c,h;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 d=0,u=0,p=!1,g=!1,f=0;for(let y=0;y<this.clips.length;y++){const v=this.models[y],b=this.actions[y],_=v.asset;b.weight=0;const w=e>=v.start&&e<=v.end,x=v.preExtrapolationMode,k=v.postExtrapolationMode,M=y<this.clips.length-1?this.models[y+1]:null;let T=w,L=!1;if(!T&&!p&&v.end<e&&k!==bn.None?(!M||M.start>e)&&(T=!0,p=!0):y==0&&!T&&!g&&v.start>e&&x!==bn.None&&(!M||M.start<e)&&(T=!0,L=!0,g=!0),T){let D=this.weight;D*=this.evaluateWeight(e,y,this.models,T),D*=this.director.weight;let z=w;if(L)switch(x){case bn.Hold:break;case bn.Loop:e+=v.start,z=!0;break;default:e+=v.start,z=!0;break}let j=this.getClipTime(e,v),H=0;const K=_.duration;if(L&&x===bn.Hold&&(j=0),z){if(_.loop)for(H+=Math.floor(j/(K+1e-6));j>K;)j-=K}else if(!w&&p)switch(k){case bn.Hold:j=this.getClipTime(v.end,v);break;case bn.Loop:j%=K;break;case bn.PingPong:const B=Math.floor(j/K)%2!==0;j%=K,B&&(j=K-j);break}v.reversed===!0?b.time=b.getClip().duration-j:b.time=j,b.timeScale=0;const U=Math.max(0,D);if(b.weight=U,f+=U,b.clampWhenFinished=!1,b.isRunning()||b.play(),this._useclipOffsets){const B=d==0?this._totalOffsetPosition:this._totalOffsetPosition2,Q=d==0?this._totalOffsetRotation:this._totalOffsetRotation2;d<1&&(u=1-D),d+=1;const te=this._summedPos.set(0,0,0),ae=this._tempPos.set(0,0,0),le=this._summedRot.identity(),ye=this._tempRot.identity(),He=_.rotation;He&&(this._clipRotQuat.identity(),this._clipRotQuat.slerp(He,D));const vt=this._actionOffsets[y];if(vt.hasOffsets)for(let gr=0;gr<H;gr++)vt.rootPositionOffset?ae.copy(vt.rootPositionOffset):ae.set(0,0,0),ae.applyQuaternion(le),this._clipRotQuat&&ae.applyQuaternion(this._clipRotQuat),vt.rootQuaternionOffset&&(ye.copy(vt.rootQuaternionOffset),le.multiply(ye)),te.add(ae);this._clipRotQuat&&Q.multiply(this._clipRotQuat),Q.multiply(le),_.position&&te.add(_.position),B.add(te)}}}if(this._useclipOffsets&&(this._totalOffsetPosition.lerp(this._totalOffsetPosition2,u),this._totalOffsetRotation.slerp(this._totalOffsetRotation2,u)),this.__mixerError===void 0&&(_n||F())&&(s=(t=this._animator)==null?void 0:t.runtimeAnimatorController)!=null&&s.mixer&&this.mixer!==((r=(o=this._animator)==null?void 0:o.runtimeAnimatorController)==null?void 0:r.mixer)&&(this.__mixerError=!0,console.error("AnimationTrack mixer is not shared with the animator controller - this might result in the timeline to not animate properly. Please report a bug to the Needle Engine team!",this)),(l=this._animator)!=null&&l.runtimeAnimatorController){const y=Math.max(0,1-f);(h=(c=this._animator)==null?void 0:c.runtimeAnimatorController)==null||h.update(y)}else this.mixer.update(e)}createRotationInterpolant(e,t,s){var o;const r=s.createInterpolant.bind(s),l=new V;this.ensureTrackOffsets();const c=(o=this.trackOffset)==null?void 0:o.rotation;s.createInterpolant=()=>{const h=r(),d=h.evaluate.bind(h);return h.evaluate=u=>{var p;const g=d(u);if(l.set(g[0],g[1],g[2],g[3]),l.premultiply(this._totalOffsetRotation),c&&l.premultiply(c),this.director.animationCallbackReceivers)for(const f of this.director.animationCallbackReceivers)(p=f?.onTimelineRotation)==null||p.call(f,this.director,this.target,u,l);return g[0]=l.x,g[1]=l.y,g[2]=l.z,g[3]=l.w,g},h}}createPositionInterpolant(e,t,s){var o,r;const l=s.createInterpolant.bind(s),c=new S;this.ensureTrackOffsets();const h=(o=this.trackOffset)==null?void 0:o.rotation,d=(r=this.trackOffset)==null?void 0:r.position;let u;s.createInterpolant=()=>{const p=l(),g=p.evaluate.bind(p);return p.evaluate=f=>{var y,v,b;const _=g(f);if(c.set(_[0],_[1],_[2]),t.removeStartOffset&&(u===void 0?(u=null,u=(v=(y=this._actionOffsets.find(w=>w.clip===e))==null?void 0:y.rootStartPosition)==null?void 0:v.clone()):u!=null&&u.isVector3&&c.sub(u)),c.applyQuaternion(this._totalOffsetRotation),c.add(this._totalOffsetPosition),h&&c.applyQuaternion(h),d&&(c.x-=d.x,c.y+=d.y,c.z+=d.z),this.director.animationCallbackReceivers)for(const w of this.director.animationCallbackReceivers)(b=w?.onTimelinePosition)==null||b.call(w,this.director,this.target,f,c);return _[0]=c.x,_[1]=c.y,_[2]=c.z,_},p}}}const qI=C("mutetimeline"),jS=class ld extends Bh{constructor(){super(...arguments),a(this,"models",[]),a(this,"listener"),a(this,"audio",[]),a(this,"audioContextTimeOffset",[]),a(this,"lastTime",0),a(this,"audioSource"),a(this,"_audioLoader",null),a(this,"_playableDirectorResumed",!1)}getAudioFilePath(e){const t=this.director.sourceId;return yo(t,e)}onAllowAudioChanged(e){for(let t=0;t<this.models.length;t++){const s=this.models[t];this.audio[t].setVolume(e?s.asset.volume:0)}}addModel(e){const t=new WP(this.listener);this.audio.push(t);const s=e;s._didTriggerPlay=!1,this.models.push(s)}onDisable(){for(const e of this.audio)e.isPlaying&&e.stop();for(const e of this.models)e._didTriggerPlay=!1}onDestroy(){for(const e of this.audio)e.source&&e?.disconnect();this.audio.length=0}onMuteChanged(){if(this.muted)for(let e=0;e<this.audio.length;e++){const t=this.audio[e];t!=null&&t.isPlaying&&t.stop()}}stop(){for(let e=0;e<this.audio.length;e++){const t=this.audio[e];t!=null&&t.isPlaying&&t.stop()}for(const e of this.models)e._didTriggerPlay=!1}onPauseChanged(){for(let e=0;e<this.audio.length;e++){const t=this.audio[e];t!=null&&t.isPlaying&&t.stop()}this._playableDirectorResumed=this.director.isPlaying}evaluate(e){if(qI||this.track.muted||this.director.speed<0)return;const t=this.director.context.application.muted,s=this._playableDirectorResumed;this._playableDirectorResumed=!1;const o=t?.1:0;for(let r=0;r<this.models.length;r++){const l=this.models[r],c=this.audio[r],h=l.asset;if((!c||!c.buffer)&&this.isInTimeRange(l,e-1,e+1)&&this.handleAudioLoading(l,c),ns.userInteractionRegistered!==!1&&!(c===null||!c.buffer))if(c.playbackRate=this.director.context.time.timeScale*this.director.speed,c.loop=h.loop,e>=l.start&&e<=l.end&&e<this.director.duration){if(!c.isPlaying||!this.director.isPlaying)(s||!l._didTriggerPlay&&this.lastTime<e)&&(l.duration*l.timeScale>.3?c.offset=l.clipIn+(e-l.start)*l.timeScale:c.offset=0,_n&&console.log("Timeline Audio ("+this.track.name+") play with offset "+c.offset+" - "+l.asset.clip),c.play(o),l._didTriggerPlay=!0);else{const u=l.clipIn+(e-l.start)*l.timeScale,p=c.context.currentTime-c._startedAt+c.offset;Math.abs(u-p)>.3&&(c.offset=u,c.stop(),c.play(o))}let d=h.volume;if(this.track.volume!==void 0&&(d*=this.track.volume),t&&(d=0),l.easeInDuration>0){const u=Math.min((e-l.start)/l.easeInDuration,1);d*=u}if(l.easeOutDuration>0){const u=Math.min((l.end-e)/l.easeOutDuration,1);d*=u}c.setVolume(d*this.director.weight)}else l._didTriggerPlay=!1,this.director.isPlaying&&c.isPlaying&&c.stop()}this.lastTime=e}loadAudio(e,t=0,s=0){let o=null;const r=e-s,l=e+t;for(const c of this.models)if(this.isInTimeRange(c,r,l)){const h=this.audio[this.models.indexOf(c)],d=this.handleAudioLoading(c,h);d!==null&&(o===null&&(o=[]),o.push(d))}return o!==null?Promise.all(o):null}isInTimeRange(e,t,s){return t<=e.start&&s>=e.end||t>=e.start&&t<=e.end||s>=e.start&&s<=e.end}static dispose(){ld._audioBuffers.clear()}handleAudioLoading(e,t){this._audioLoader||(this._audioLoader=new jm);const s=this.getAudioFilePath(e.asset.clip);if(ld._audioBuffers.get(s)){const r=ld._audioBuffers.get(s);return r.then(l=>{l&&t.setBuffer(l)}),r}_n&&console.warn("LOAD audio track",s,this.director.sourceId);const o=new Promise((r,l)=>{this._audioLoader.load(s,c=>{t.setBuffer(c),r(c)},void 0,c=>{console.error("Error loading audio",c),r(null)})});return ld._audioBuffers.set(s,o),o}};a(jS,"_audioBuffers",new Map);let sm=jS;class Fh extends Bh{constructor(){super(...arguments),a(this,"models",[]),a(this,"didTrigger",[]),a(this,"receivers",[])}evaluate(e){var t;if(this.track.muted)return;const s=this.director.context.time.deltaTime*1.5;for(let o=0;o<this.models.length;o++){const r=this.models[o],l=this.didTrigger[o],c=r.time-e;let h=!1;if(r.retroActive)h=c<=1e-6;else{const d=Math.abs(c);(d===0||d>=1e-5&&d<s)&&(h=!0)}if(h){if(!l)if(_n&&console.log("Trigger signal",e,r.time,r),this.didTrigger[o]=!0,((t=this.receivers)==null?void 0:t.length)<=0)Dh.invoke(r.asset);else for(const d of this.receivers)d&&d.invoke(r.asset)}else r.emitOnce||(this.didTrigger[o]=!1)}}}class nm extends Bh{constructor(){super(...arguments),a(this,"models",[]),a(this,"timelines",[]),a(this,"_previousActiveModel",null)}resolveSourceObjects(e){for(let t=this.models.length-1;t>=0;t--){const s=this.models[t].asset;if(!s.sourceObject||typeof s.sourceObject!="object"){console.log("no source object, removing model",t,s),this.models.splice(t,1);continue}else{const o=P.getComponent(s.sourceObject,Tl);this.timelines.push(o),o&&s.updateDirector&&(o.playOnAwake=!1)}}}evaluate(e){var t;this._previousActiveModel=null;for(let s=0;s<this.models.length;s++){const o=this.models[s],r=o.asset;if(e>=o.start&&e<=o.end){this._previousActiveModel=o;const l=this.getClipTime(e,o);if(r.controlActivation){const c=r.sourceObject;c.visible=!0}if(r.updateDirector){const c=this.timelines[s];c&&(c.isPlaying&&c.pause(),c.time=l,c.evaluate())}}else{const l=(t=this._previousActiveModel)==null?void 0:t.asset;if(r.controlActivation){const c=r.sourceObject;l?.sourceObject!==c&&(c.visible=!1)}}}}}var XI=Object.defineProperty,DS=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&XI(e,t,o),o};const so=C("debugtimeline");var Uh;const Xy=(Uh=class extends I{constructor(){super(...arguments),a(this,"playableAsset"),a(this,"playOnAwake"),a(this,"extrapolationMode",1),a(this,"waitForAudio",!0),a(this,"_visibilityChangeEvt"),a(this,"_clonedPlayableAsset",!1),a(this,"_speed",1),a(this,"_guidsMap"),a(this,"_isPlaying",!1),a(this,"_internalUpdateRoutine"),a(this,"_isPaused",!1),a(this,"_isStopping",!1),a(this,"_time",0),a(this,"_duration",0),a(this,"_weight",1),a(this,"_animationTracks",[]),a(this,"_audioTracks",[]),a(this,"_signalTracks",[]),a(this,"_controlTracks",[]),a(this,"_customTracks",[]),a(this,"_allTracks",[this._animationTracks,this._audioTracks,this._signalTracks,this._controlTracks,this._customTracks]),a(this,"animationCallbackReceivers",[])}static registerCreateTrack(n,e){this.createTrackFunctions[n]=e}get isPlaying(){return this._isPlaying}get isPaused(){return this._isPaused}get time(){return this._time}set time(n){typeof n=="number"&&!Number.isNaN(n)?this._time=n:(so||Xt())&&console.error("INVALID TIMELINE.TIME VALUE",n,this.name)}get duration(){return this._duration}set duration(n){this._duration=n}get weight(){return this._weight}set weight(n){this._weight=n}get speed(){return this._speed}set speed(n){this._speed=n}awake(){var n,e,t,s,o;so&&console.log(this,(n=this.playableAsset)==null?void 0:n.tracks),this.rebuildGraph(),!this.isValid()&&(so||F())&&(so?console.warn("PlayableDirector is not valid","Asset?",this.playableAsset,"Tracks:",(e=this.playableAsset)==null?void 0:e.tracks,"IsArray?",Array.isArray((t=this.playableAsset)==null?void 0:t.tracks),this):(o=(s=this.playableAsset)==null?void 0:s.tracks)!=null&&o.length?console.warn("PlayableDirector is not valid"):console.warn("PlayableDirector has no tracks"))}onEnable(){var n,e,t;for(const s of this._audioTracks)(n=s.onEnable)==null||n.call(s);for(const s of this._customTracks)(e=s.onEnable)==null||e.call(s);for(const s of this._animationTracks)(t=s.onEnable)==null||t.call(s);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(){var n,e,t;this.stop();for(const s of this._audioTracks)(n=s.onDisable)==null||n.call(s);for(const s of this._customTracks)(e=s.onDisable)==null||e.call(s);for(const s of this._animationTracks)(t=s.onDisable)==null||t.call(s);this._visibilityChangeEvt&&window.removeEventListener("visibilitychange",this._visibilityChangeEvt)}onDestroy(){var n;for(const e of this._allTracks)for(const t of e)(n=t.onDestroy)==null||n.call(t)}rebuildGraph(){this.isValid()&&(this.resolveBindings(),this.updateTimelineDuration(),this.setupAndCreateTrackHandlers())}async play(){if(!this.isValid())return;const n=this._isPaused==!0;if(this._isPaused=!1,!this._isPlaying){if(this._isPlaying=!0,n&&this.invokePauseChangedMethodsOnTracks(),this.waitForAudio){const e=[];for(const t of this._audioTracks){const s=t.loadAudio(this._time,1,0);s&&e.push(s)}if(e.length>0&&(await Promise.all(e),!this._isPlaying))return;for(;this._audioTracks.length>0&&this._isPlaying&&!ns.userInteractionRegistered&&this.waitForAudio;)await vs(200)}this.invokeStateChangedMethodsOnTracks(),this._internalUpdateRoutine=this.startCoroutine(this.internalUpdate(),Oe.LateUpdate)}}pause(){this.isValid()&&(this._isPlaying=!1,!this._isPaused&&(this._isPaused=!0,this.internalEvaluate(),this.invokePauseChangedMethodsOnTracks(),this.invokeStateChangedMethodsOnTracks()))}stop(){this._isStopping=!0;for(const t of this._audioTracks)t.stop();const n=this._isPaused==!0,e=this._isPlaying;this._isPlaying&&(this._time=0,this._isPlaying=!1,this._isPaused=!1,this.internalEvaluate(),n&&this.invokePauseChangedMethodsOnTracks()),this._isPlaying=!1,this._isPaused=!1,n&&!e&&this.invokePauseChangedMethodsOnTracks(),e&&this.invokeStateChangedMethodsOnTracks(),this._internalUpdateRoutine&&this.stopCoroutine(this._internalUpdateRoutine),this._internalUpdateRoutine=null,this._isStopping=!1}evaluate(){this.internalEvaluate(!0)}isValid(){return this.playableAsset&&this.playableAsset.tracks&&Array.isArray(this.playableAsset.tracks)}*forEachTrack(){for(const n of this._allTracks)for(const e of n)yield e}get animationTracks(){return this._animationTracks}get audioTracks(){return this._audioTracks}resolveGuids(n){this._guidsMap=n}invokePauseChangedMethodsOnTracks(){var n;for(const e of this.forEachTrack())(n=e.onPauseChanged)==null||n.call(e)}invokeStateChangedMethodsOnTracks(){var n;for(const e of this.forEachTrack())(n=e.onStateChanged)==null||n.call(e,this._isPlaying)}*internalUpdate(){for(;this._isPlaying&&this.activeAndEnabled;)!this._isPaused&&this._isPlaying&&(this._time+=this.context.time.deltaTime*this.speed,this.internalEvaluate()),yield}internalEvaluate(n=!1){if(!this.isValid())return;let e=this._time;switch(this.extrapolationMode){case 0:this._speed>0?e=Math.min(e,this._duration):this._speed<0&&(e=Math.max(e,0)),this._time=e;break;case 1:e%=this._duration,this._time=e;break;case 2:if(e>this._duration){this.stop();return}break}const t=this._time;for(const s of this.playableAsset.tracks)if(!s.muted)switch(s.type){case qi.Activation:if(!n&&!this._isPlaying)continue;for(let o=0;o<s.outputs.length;o++){const r=s.outputs[o];if(typeof r=="object"){let l=!1;if(s.clips)for(const h of s.clips)h.start<=t&&t<=h.end&&(l=!0);const c=r;c.visible!==void 0&&c.visible!==l&&(c.visible=l,so&&console.warn(this.name,"set ActivationTrack-"+o,c.name,l,t))}}break}if(!this._isStopping)for(const s of this._animationTracks)s.evaluate(t);for(const s of this._audioTracks)s.evaluate(t);for(const s of this._signalTracks)s.evaluate(t);for(const s of this._controlTracks)s.evaluate(t);for(const s of this._customTracks)s.evaluate(t)}resolveBindings(){if(this._clonedPlayableAsset||(this._clonedPlayableAsset=!0,this.playableAsset=ql(this.playableAsset)),!this.playableAsset||!this.playableAsset.tracks)return;const n=this.findRoot(this.gameObject);for(const e of this.playableAsset.tracks){for(let t=e.outputs.length-1;t>=0;t--){let s=e.outputs[t];if(typeof s=="string"){this._guidsMap&&this._guidsMap[s]&&(s=this._guidsMap[s]);const o=P.findByGuid(s,n);o===null||typeof o!="object"?(e.outputs.splice(t,1),console.warn("Failed to resolve binding",s,e.name,e.type)):(so&&console.log("Resolved binding",s,"to",o),e.outputs[t]=o)}else if(s===null){if(e.outputs.splice(t,1),Uh.createTrackFunctions[e.type])continue;e.type!==qi.Audio&&e.type!==qi.Control&&e.type!==qi.Marker&&e.type!==qi.Signal&&console.warn("Missing binding",s,e.name,e.type,this.name,this.playableAsset.name)}}if(e.type===qi.Control&&e.clips)for(let t=0;t<e.clips.length;t++){const s=e.clips[t];let o=s.asset.sourceObject;if(typeof o=="string"){this._guidsMap&&this._guidsMap[o]&&(o=this._guidsMap[o]);const r=P.findByGuid(o,n);r===null||typeof r!="object"?console.warn("Failed to resolve sourceObject binding",o,e.name,s):(so&&console.log("Resolved binding",o,"to",r),s.asset.sourceObject=r)}}}}findRoot(n){return n.parent?this.findRoot(n.parent):n}updateTimelineDuration(){if(this._duration=0,!(!this.playableAsset||!this.playableAsset.tracks)){for(const n of this.playableAsset.tracks)if(n.muted!==!0){if(n.clips)for(const e of n.clips)e.end>this._duration&&(this._duration=e.end);if(n.markers)for(const e of n.markers)e.time>this._duration&&(this._duration=e.time+.001)}}}setupAndCreateTrackHandlers(){var n,e,t;if(this._animationTracks.length=0,this._audioTracks.length=0,this._signalTracks.length=0,!this.playableAsset)return;let s=P.findObjectOfType(zn,this.context);for(const o of this.playableAsset.tracks){const r=o.type,l=Uh.createTrackFunctions[r];if(l!=null){const c=l(this,o);if(typeof c.evaluate=="function"){c.director=this,c.track=o,this._customTracks.push(c);continue}}if(o.type===qi.Animation){if(!o.clips||o.clips.length<=0){so&&console.warn("Animation track has no clips",o);continue}for(let c=o.outputs.length-1;c>=0;c--){let h=o.outputs[c];if(h instanceof E){const u=P.getOrAddComponent(h,Rt);u&&(h=u)}const d=(n=h?.gameObject)==null?void 0:n.animations;if(d){const u=new im;u.trackOffset=o.trackOffset,u.director=this,u.track=o;for(let p=0;p<o.clips.length;p++){const g=o.clips[p],f=g.asset;if(!f){console.error(`Timeline ${this.name}: clip #${p} on track "${o.name}" has no animation data`);continue}const y=f.clip;let v=y;if((typeof v=="string"||typeof v=="number")&&(v=d.find(_=>_.name===y)),so&&console.log(f,y,"\u2192",v),!v){console.warn("Could not find animationClip for model",g,o.name,this.name,(e=this.playableAsset)==null?void 0:e.name,d,h);continue}h instanceof Rt&&h.runtimeAnimatorController&&(h.__internalDidAwakeAndStart||h.initializeRuntimeAnimatorController(),h.runtimeAnimatorController.mixer||h.runtimeAnimatorController.bind(h),u.mixer=h.runtimeAnimatorController.mixer),u.mixer||(u.mixer=new Lm(h.gameObject),this.context.animations.registerAnimationMixer(u.mixer)),u.clips.push(v),u.mixer.uncacheAction(v),u.createHooks(g.asset,v);const b=u.mixer.clipAction(v);u.actions.push(b),u.models.push(g)}this._animationTracks.push(u)}}}else if(o.type===qi.Audio){if(!o.clips||o.clips.length<=0)continue;const c=new sm;c.director=this,c.track=o,c.audioSource=o.outputs.find(h=>h instanceof ns),this._audioTracks.push(c),s||(s=(t=this.context.mainCameraComponent)==null?void 0:t.gameObject.addComponent(zn)),c.listener=s.listener;for(let h=0;h<o.clips.length;h++){const d=o.clips[h];c.addModel(d)}}else if(o.type===qi.Marker){const c=new Fh;if(c.director=this,c.track=o,o.markers)for(const h of o.markers)switch(h.type){case qy.Signal:c.models.push(h),c.didTrigger.push(!1);break}if(c!==null&&c.models.length>0){const h=P.getComponent(this.gameObject,Dh);h&&(c.receivers.push(h),this._signalTracks.push(c))}}else if(o.type===qi.Signal){const c=new Fh;if(c.director=this,c.track=o,o.markers)for(const h of o.markers)c.models.push(h),c.didTrigger.push(!1);for(const h of o.outputs)c.receivers.push(h);this._signalTracks.push(c)}else if(o.type===qi.Control){const c=new nm;if(c.director=this,c.track=o,o.clips)for(const h of o.clips)c.models.push(h);c.resolveSourceObjects(this.context),this._controlTracks.push(c)}}}setAudioTracksAllowPlaying(n){for(const e of this._audioTracks)e.onAllowAudioChanged(n)}registerAnimationCallback(n){this.animationCallbackReceivers.push(n)}unregisterAnimationCallback(n){const e=this.animationCallbackReceivers.indexOf(n);e!==-1&&this.animationCallbackReceivers.splice(e,1)}},a(Uh,"createTrackFunctions",{}),Uh);DS([m()],Xy.prototype,"playOnAwake"),DS([m()],Xy.prototype,"extrapolationMode");let Tl=Xy;var QI=Object.defineProperty,om=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&QI(e,t,o),o};class da extends I{constructor(){super(...arguments),a(this,"isGizmo",!1),a(this,"translationSnap",1),a(this,"rotationSnapAngle",15),a(this,"scaleSnap",.25),a(this,"_control"),a(this,"orbit"),a(this,"onControlChangedEvent",e=>{const t=this.orbit;if(t&&(t.enabled=!e.value),e.value){const s=P.getComponentInParent(this.gameObject,sn);s&&s.requestOwnership()}}),a(this,"windowKeyDownListener",e=>{if(this.enabled&&this._control)switch(e.keyCode){case 81:this._control.setSpace(this._control.space==="local"?"world":"local");break;case 16:this.enableSnapping();break;case 87:this._control.setMode("translate");break;case 69:this._control.setMode("rotate");break;case 82:this._control.setMode("scale");break;case 187:case 107:this._control.setSize(this._control.size+.1);break;case 189:case 109:this._control.setSize(Math.max(this._control.size-.1,.1));break;case 88:this._control.showX=!this._control.showX;break;case 89:this._control.showY=!this._control.showY;break;case 90:this._control.showZ=!this._control.showZ;break;case 32:this._control.enabled=!this._control.enabled;break}}),a(this,"windowKeyUpListener",e=>{if(this.enabled)switch(e.keyCode){case 16:this.disableSnapping();break}})}get control(){return this._control}onEnable(){var e;if(!(this.isGizmo&&!yc)&&this.context.mainCamera&&(this._control||(this._control=new dO(this.context.mainCamera,this.context.renderer.domElement),this._control.enabled=!0,this._control.getRaycaster().layers.set(2),this._control.size=1,("_root"in this._control?this._control._root:this._control).traverse(t=>{const s=t;if(s.layers.set(2),s){const o=s.material;o&&(o.opacity=.3)}}),this.orbit=P.getComponentInParent(this.context.mainCamera,_e)??void 0),this._control)){const t=this._control.getHelper();this.context.scene.add(t),this._control.attach(this.gameObject),(e=this._control)==null||e.addEventListener("dragging-changed",this.onControlChangedEvent),window.addEventListener("keydown",this.windowKeyDownListener),window.addEventListener("keyup",this.windowKeyUpListener)}}onDisable(){var e,t,s;(t=(e=this._control)==null?void 0:e.getHelper())==null||t.removeFromParent(),(s=this._control)==null||s.removeEventListener("dragging-changed",this.onControlChangedEvent),window.removeEventListener("keydown",this.windowKeyDownListener),window.removeEventListener("keyup",this.windowKeyUpListener)}enableSnapping(){this._control&&(this._control.setTranslationSnap(this.translationSnap),this._control.setRotationSnap(Cn.degToRad(this.rotationSnapAngle)),this._control.setScaleSnap(this.scaleSnap))}disableSnapping(){this._control&&(this._control.setTranslationSnap(null),this._control.setRotationSnap(null),this._control.setScaleSnap(null))}}om([m()],da.prototype,"isGizmo"),om([m()],da.prototype,"translationSnap"),om([m()],da.prototype,"rotationSnapAngle"),om([m()],da.prototype,"scaleSnap");var YI=Object.defineProperty,KI=Object.getOwnPropertyDescriptor,rm=(n,e,t,s)=>{for(var o=s>1?void 0:s?KI(e,t):e,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=(s?l(e,t,o):l(o))||o);return s&&o&&YI(e,t,o),o};class Qy{constructor(){a(this,"texture",null),a(this,"rect")}}rm([m(je)],Qy.prototype,"texture",2);let El=class extends ch{constructor(){super(...arguments),a(this,"_sprite"),a(this,"pixelsPerUnitMultiplier",1)}set image(n){this.sprite||(this.sprite=new Qy),this.sprite.texture=n,this.onAfterCreated()}get image(){return this.sprite?this.sprite.texture:null}get sprite(){return this._sprite}set sprite(n){this._sprite!==n&&(this._sprite=n,this.onAfterCreated())}isBuiltinSprite(){var n,e,t,s,o,r,l;const c=this.sprite;switch((n=c?.texture)==null?void 0:n.name){case"InputFieldBackground":case"UISprite":case"Background":case"Knob":return!0}return!((t=(e=c?.texture)==null?void 0:e.name)!=null&&t.length)&&((o=(s=c?.texture)==null?void 0:s.image)==null?void 0:o.width)===32&&((l=(r=c?.texture)==null?void 0:r.image)==null?void 0:l.height)===32}onBeforeCreate(n){var e,t;super.onBeforeCreate(n),this.isBuiltinSprite()&&(n.borderRadius=5/this.pixelsPerUnitMultiplier,((t=(e=this.sprite)==null?void 0:e.texture)==null?void 0:t.name)==="Knob"&&(n.borderRadius=999))}onAfterCreated(){var n;this.__didAwake&&(super.onAfterCreated(),!this.isBuiltinSprite()&&this.setTexture((n=this.sprite)==null?void 0:n.texture))}};rm([m(Qy)],El.prototype,"sprite",1),rm([m()],El.prototype,"pixelsPerUnitMultiplier",2);class am extends ch{constructor(){super(...arguments),a(this,"_mainTexture")}get mainTexture(){return this._mainTexture}set mainTexture(e){this._mainTexture!==e&&(this._mainTexture=e,this.onAfterCreated())}onAfterCreated(){this.__didAwake&&(super.onAfterCreated(),this.setTexture(this.mainTexture))}}rm([m(je)],am.prototype,"mainTexture",1);var ZI=Object.defineProperty,JI=Object.getOwnPropertyDescriptor,Xi=(n,e,t,s)=>{for(var o=s>1?void 0:s?JI(e,t):e,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=(s?l(e,t,o):l(o))||o);return s&&o&&ZI(e,t,o),o};const ua=C("debugbutton");class cr{constructor(){a(this,"colorMultiplier"),a(this,"disabledColor"),a(this,"fadeDuration"),a(this,"highlightedColor"),a(this,"normalColor"),a(this,"pressedColor"),a(this,"selectedColor")}}Xi([m()],cr.prototype,"colorMultiplier",2),Xi([m(he)],cr.prototype,"disabledColor",2),Xi([m()],cr.prototype,"fadeDuration",2),Xi([m(he)],cr.prototype,"highlightedColor",2),Xi([m(he)],cr.prototype,"normalColor",2),Xi([m(he)],cr.prototype,"pressedColor",2),Xi([m(he)],cr.prototype,"selectedColor",2);class eL{constructor(){a(this,"disabledTrigger"),a(this,"highlightedTrigger"),a(this,"normalTrigger"),a(this,"pressedTrigger"),a(this,"selectedTrigger")}}class no extends I{constructor(){super(...arguments),a(this,"onClick",new xe),a(this,"_isHovered",0),a(this,"colors"),a(this,"transition"),a(this,"animationTriggers"),a(this,"animator"),a(this,"_interactable",!0),a(this,"_requestedAnimatorTrigger"),a(this,"_isInit",!1),a(this,"_image")}click(){var e;(e=this.onClick)==null||e.invoke()}onPointerEnter(e){var t,s;const o=e.event.pointerType==="mouse"&&e.button===0;o&&(this._isHovered+=1),ua&&console.warn("Button Enter",o,this._isHovered,(t=this.animationTriggers)==null?void 0:t.highlightedTrigger,this.animator),this.interactable&&(this.transition==3&&this.animationTriggers&&this.animator?this.animator.setTrigger(this.animationTriggers.highlightedTrigger):this.transition===1&&this.colors&&((s=this._image)==null||s.setState("hovered")),o&&this.context.input.setCursor("pointer"))}onPointerExit(){var e,t;this._isHovered-=1,this._isHovered<0&&(this._isHovered=0),ua&&console.log("Button Exit",this._isHovered,(e=this.animationTriggers)==null?void 0:e.highlightedTrigger,this.animator),this.interactable&&(this._isHovered>0||(this._isHovered=0,this.transition==3&&this.animationTriggers&&this.animator?this.animator.setTrigger(this.animationTriggers.normalTrigger):this.transition===1&&this.colors&&((t=this._image)==null||t.setState("normal")),this.context.input.unsetCursor("pointer")))}onPointerDown(e){var t,s;ua&&console.log("Button Down",(t=this.animationTriggers)==null?void 0:t.highlightedTrigger,this.animator),this.interactable&&(this.transition==3&&this.animationTriggers&&this.animator?this.animator.setTrigger(this.animationTriggers.pressedTrigger):this.transition===1&&this.colors&&((s=this._image)==null||s.setState("pressed")))}onPointerUp(e){var t,s;ua&&console.warn("Button Up",(t=this.animationTriggers)==null?void 0:t.highlightedTrigger,this.animator,this._isHovered),this.interactable&&(this.transition==3&&this.animationTriggers&&this.animator?this.animator.setTrigger(this._isHovered?this.animationTriggers.highlightedTrigger:this.animationTriggers.normalTrigger):this.transition===1&&this.colors&&((s=this._image)==null||s.setState(this._isHovered?"hovered":"normal")))}onPointerClick(e){if(this.interactable&&!(e.button!==0&&e.event.pointerType===Ud.Mouse)&&(ua&&(console.warn("Button Click",this.onClick),De("CLICKED button "+this.name+" at "+this.context.time.frameCount)),this.onClick&&this.onClick.listenerCount>0&&(this.onClick.invoke(),e.use(),ua))){const t=this.gameObject.worldPosition;t.add(this.gameObject.worldUp.multiplyScalar(1+Math.random()*.5)),$.DrawLabel(t,"CLICK:"+Date.now(),.1,1+Math.random()*.5)}}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}set_interactable(e){this.interactable=e}awake(){super.awake(),ua&&console.log(this),this._isInit=!1,this.init()}start(){var e;(e=this._image)==null||e.setInteractable(this.interactable),this.gameObject.getComponentInParent(Ya)||this.gameObject.addComponent(Au)}onEnable(){super.onEnable()}onDestroy(){this._isHovered&&this.context.input.unsetCursor("pointer")}*setAnimatorTriggerAtEndOfFrame(e){var t;this._requestedAnimatorTrigger=e,yield,yield,this._requestedAnimatorTrigger==e&&((t=this.animator)==null||t.setTrigger(e))}init(){this._isInit||(this._isInit=!0,this._image=P.getComponent(this.gameObject,El),this._image&&(this.stateSetup(this._image),this.interactable?this._image.setState("normal"):this._image.setState("disabled")))}stateSetup(e){var t,s,o,r,l;e.setInteractable(this.interactable);const c=this.getFinalColor(e.color,(t=this.colors)==null?void 0:t.normalColor),h={state:"normal",attributes:{backgroundColor:c,backgroundOpacity:c.alpha}};e.setupState(h);const d=this.getFinalColor(e.color,(s=this.colors)==null?void 0:s.highlightedColor),u={state:"hovered",attributes:{backgroundColor:d,backgroundOpacity:d.alpha}};e.setupState(u);const p=this.getFinalColor(e.color,(o=this.colors)==null?void 0:o.pressedColor),g={state:"pressed",attributes:{backgroundColor:p,backgroundOpacity:p.alpha}};e.setupState(g);const f=this.getFinalColor(e.color,(r=this.colors)==null?void 0:r.selectedColor),y={state:"selected",attributes:{backgroundColor:f,backgroundOpacity:f.alpha}};e.setupState(y);const v=this.getFinalColor(e.color,(l=this.colors)==null?void 0:l.disabledColor),b={state:"disabled",attributes:{backgroundColor:v,backgroundOpacity:v.alpha}};e.setupState(b)}getFinalColor(e,t){return t?e.clone().multiply(t).convertLinearToSRGB():e.clone().convertLinearToSRGB()}}Xi([m(xe)],no.prototype,"onClick",2),Xi([m(cr)],no.prototype,"colors",2),Xi([m()],no.prototype,"transition",2),Xi([m(eL)],no.prototype,"animationTriggers",2),Xi([m(Rt)],no.prototype,"animator",2),Xi([m()],no.prototype,"interactable",1);var tL=Object.defineProperty,lm=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&tL(e,t,o),o};const hr=C("debuginputfield");var Y;const zh=(Y=class extends I{constructor(){super(...arguments),a(this,"textComponent"),a(this,"placeholder"),a(this,"onValueChanged"),a(this,"onEndEdit"),a(this,"inputEventFn"),a(this,"_iosEventFn")}get text(){var n;return((n=this.textComponent)==null?void 0:n.text)??""}set text(n){this.textComponent&&(this.textComponent.text=n,this.placeholder&&(n.length>0?this.placeholder.gameObject.visible=!1:this.placeholder.gameObject.visible=!0))}get isFocused(){return Y.active===this}start(){hr&&console.log(this.name,this)}onEnable(){var n;Y.htmlField||(Y.htmlField=document.createElement("input"),Y.htmlField.style.width="0px",Y.htmlField.style.height="0px",Y.htmlField.style.padding="0px",Y.htmlField.style.border="none",Y.htmlField.style.overflow="hidden",Y.htmlField.style.caretColor="transparent",Y.htmlField.style.outline="none",Y.htmlField.classList.add("ar"),Y.htmlField.onfocus=()=>Y.htmlFieldFocused=!0,Y.htmlField.onblur=()=>Y.htmlFieldFocused=!1,document.body.append(Y.htmlField)),this.inputEventFn||(this.inputEventFn=this.onInput.bind(this)),Y.htmlField.addEventListener("keyup",this.inputEventFn),this.placeholder&&(n=this.textComponent)!=null&&n.text.length&&P.setActive(this.placeholder.gameObject,!1),X.isiOS()&&(this._iosEventFn=this.processInputOniOS.bind(this),window.addEventListener("click",this._iosEventFn))}onDisable(){var n;(n=Y.htmlField)==null||n.removeEventListener("keyup",this.inputEventFn),this.onDeselected(),this._iosEventFn&&window.removeEventListener("click",this._iosEventFn)}clear(){Y.active===this&&Y.htmlField?(Y.htmlField.value="",this.setTextFromInputField()):(this.textComponent&&(this.textComponent.text=""),this.placeholder&&P.setActive(this.placeholder.gameObject,!0))}select(){this.onSelected()}deselect(){this.onDeselected()}onPointerEnter(n){n.event.pointerType==="mouse"&&n.button===0&&this.context.input.setCursor("text")}onPointerExit(n){this.context.input.unsetCursor("text")}onPointerClick(n){hr&&console.log("CLICK",n,Y.active),Y.activeTime=this.context.time.time,Y.active!==this&&this.startCoroutine(this.activeLoop(),Oe.LateUpdate),this.selectInputField()}*activeLoop(){for(this.onSelected();Y.active===this&&!(this.context.input.getPointerClicked(0)&&this.context.time.time-Y.activeTime>.2);)this.setTextFromInputField(),yield;this.onDeselected()}onSelected(){var n,e,t,s;if(Y.active!==this&&(hr&&console.log("Select",this.name,this,Y.htmlField,this.context.isInXR,this.context.arOverlayElement,(n=this.textComponent)==null?void 0:n.text,(e=Y.htmlField)==null?void 0:e.value),(t=Y.active)==null||t.onDeselected(),Y.active=this,this.placeholder&&P.setActive(this.placeholder.gameObject,!1),Y.htmlField)){if(Y.htmlField.value=((s=this.textComponent)==null?void 0:s.text)||"",hr&&console.log("set input field value",Y.htmlField.value),this.context.isInXR){const o=this.context.arOverlayElement;o&&o.append(Y.htmlField)}this.selectInputField()}}onDeselected(){var n;Y.active===this&&(Y.active=null,hr&&console.log("Deselect",this.name,this),Y.htmlField&&(Y.htmlField.blur(),document.body.append(Y.htmlField)),this.placeholder&&(!this.textComponent||this.textComponent.text.length<=0)&&P.setActive(this.placeholder.gameObject,!0),Y.htmlField&&((n=this.onEndEdit)==null||n.invoke(Y.htmlField.value)))}update(){var n;Y.active===this&&((n=this.textComponent)==null||n.markDirty())}onInput(n){var e,t;if(Y.active===this){if(hr&&console.log(n.code,n,(e=Y.htmlField)==null?void 0:e.value,(t=this.textComponent)==null?void 0:t.text),n.code==="Escape"||n.code==="Enter"){this.onDeselected();return}Y.htmlField&&(this.textComponent&&(this.setTextFromInputField(),this.placeholder&&P.setActive(this.placeholder.gameObject,this.textComponent.text.length<=0)),this.selectInputField())}}setTextFromInputField(){var n;if(this.textComponent&&Y.htmlField){const e=this.textComponent.text,t=Y.htmlField.value,s=this.textComponent.text!==Y.htmlField.value;this.textComponent.text=Y.htmlField.value,s&&(hr&&console.log("[InputField] value changed:",t,e),(n=this.onValueChanged)==null||n.invoke(t,e))}}selectInputField(){Y.htmlField&&(hr&&console.log("Focus Inputfield",Y.htmlFieldFocused),Y.htmlField.setSelectionRange(Y.htmlField.value.length,Y.htmlField.value.length),X.isiOS()?Y.htmlField.focus({preventScroll:!0}):setTimeout(()=>{var n;return(n=Y.htmlField)==null?void 0:n.focus()},1))}processInputOniOS(){const n=this.context.physics.raycast();if(!n.length)return;const e=n[0].object,t=Nf(e);(t?.gameObject===this.gameObject||t?.gameObject.parent===this.gameObject)&&this.selectInputField()}},a(Y,"active",null),a(Y,"activeTime",-1),a(Y,"htmlField",null),a(Y,"htmlFieldFocused",!1),Y);lm([m(Nt)],zh.prototype,"textComponent"),lm([m(Nt)],zh.prototype,"placeholder"),lm([m(xe)],zh.prototype,"onValueChanged"),lm([m(xe)],zh.prototype,"onEndEdit");let Yy=zh;var iL=Object.defineProperty,BS=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&iL(e,t,o),o};class Nh extends I{constructor(){super(...arguments),a(this,"id",null),a(this,"keepAspect",!1),a(this,"_object",null)}onEnable(){if(this._object){this.gameObject.add(this._object);return}if(!this.id||!this.context.mainCamera)return;const 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";const t=new uO;t.listenToPointerEvents(this.context.renderer,this.context.mainCamera),this.gameObject.add(t);const s=new pO(e);t.add(s),s.visible=!1;const o=s.material;o.transparent=!0,setTimeout(()=>{s.visible=!0;const r=Ad(this.gameObject).clone();Zl(this.gameObject,0,0,0),this.gameObject.updateMatrixWorld();const l=new Si;l.setFromObject(t),this.setWorldRotation(r.x,r.y,r.z);const c=l.max.x-l.min.x,h=l.max.y-l.min.y;if(this.keepAspect){const u=c/h;c>h?s.scale.set(1/c,1/h/u,1):s.scale.set(1/c*u,1/h,1)}else s.scale.set(1/c,1/h,1);const d=this.gameObject.scale;s.scale.multiply(d)},1)}onDisable(){var e;(e=this._object)==null||e.removeFromParent()}}BS([m()],Nh.prototype,"id"),BS([m()],Nh.prototype,"keepAspect");/* @license
|
|
1393
|
+
C) Set "joinRandomRoom" to true`),!1):($y&&console.log("Join "+this.roomName),this._userWantsToBeInARoom=!0,this.context.connection.joinRoom(this.roomName),!0))}update(){this.context.connection.isConnected&&(this.context.time.time-this._lastPingTime>3&&(this._lastPingTime=this.context.time.time,this.context.connection.sendPing()),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?this._userWantsToBeInARoom&&(console.log("Disconnected from networking backend - attempt reconnecting now"),this.tryJoinRoom()):F()&&console.warn("You are not connected to a room anymore (possibly because the tab was inactive for too long and the server kicked you?)"))}getViewOnlyUrl(){if(this.context.connection.isConnected&&this.context.connection.currentRoomViewId){const e=window.location.search,t=new URLSearchParams(e);return t.has(this.urlParameterName)&&t.delete(this.urlParameterName),t.set(Vy,this.context.connection.currentRoomViewId),window.location.origin+window.location.pathname+"?"+t.toString()}return null}setRandomRoomUrlParameter(){const e=Hl(),t=this.generateRoomName();C(this.urlParameterName)?e.set(this.urlParameterName,t):e.append(this.urlParameterName,t),Ym(t,e)}generateRoomName(){let e="";for(let t=0;t<6;t++)e+=Math.floor(Math.random()*10).toFixed(0);return e}createRoomButton(){if(this._roomButton)return this._roomButton;const e=document.createElement("button");return this._roomButton=e,e.classList.add("create-room-button"),e.setAttribute("priority","90"),e.onclick=()=>{if(this.context.connection.isInRoom)this.urlParameterName&&Gl(this.urlParameterName,null),this.context.connection.leaveRoom(),this._userWantsToBeInARoom=!1;else{if(this.urlParameterName){const t=C(this.urlParameterName);(!t||t===!0)&&(this._lastJoinedRoom?Gl(this.urlParameterName,this._lastJoinedRoom):this.setRandomRoomUrlParameter())}this.tryJoinRoom()}},this._roomButtonIconJoin=Mt("group"),this._roomButtonIconLeave=Mt("group_off"),this.updateRoomButtonState(),this.context.connection.beginListen(ie.JoinedRoom,this.updateRoomButtonState),this.context.connection.beginListen(ie.LeftRoom,this.updateRoomButtonState),e}destroyRoomButton(){this.context.connection.stopListen(ie.JoinedRoom,this.updateRoomButtonState),this.context.connection.stopListen(ie.LeftRoom,this.updateRoomButtonState)}onEnableViewOnlyButton(){this.context.connection.isConnected?this.onCreateViewOnlyButton():(this.context.connection.stopListen(ie.JoinedRoom,this.onCreateViewOnlyButton),this.context.connection.beginListen(ie.JoinedRoom,this.onCreateViewOnlyButton))}onDisableViewOnlyButton(){var e;this.context.connection.stopListen(ie.JoinedRoom,this.onCreateViewOnlyButton),(e=this._viewOnlyButton)==null||e.remove()}}lr([m()],Ls.prototype,"roomName",2),lr([m()],Ls.prototype,"urlParameterName",2),lr([m()],Ls.prototype,"joinRandomRoom",2),lr([m()],Ls.prototype,"requireRoomParameter",2),lr([m()],Ls.prototype,"autoRejoin",2),lr([m()],Ls.prototype,"createJoinButton",2),lr([m()],Ls.prototype,"createViewOnlyButton",2),lr([m()],Ls.prototype,"roomPrefix",1);function VI(){const n=C("testwindowcount")||0;n&&n>0&&$I(n)}function $I(n){if(C("testwindow"))return null;const e=new URL(window.location.href);Qm(e.searchParams,$T,1),Qm(e.searchParams,"testwindow",1);const t=e.toString(),s=[];window.onbeforeunload=()=>{for(const h of s)h.close()};const o=.05,r=128;let l=0,c=0;for(let h=0;h<n;h++){l*r+r*.01>=window.innerWidth&&(c+=1,l=0);const d=l*(r*(1+o))+window.screenLeft,u=c*(r*(1+o))+window.screenTop+90+60*c;l+=1;const p=window.open(t,"test window "+h,`popup=yes width=${r} height=${r} top=${u} left=${d}`);if(!p){console.warn("Failed to open window");continue}s.push(p),p.onload=()=>{p.onbeforeunload=()=>{for(let g=0;g<s.length;g++){const f=s[g];f!==p&&f.close()}s.length=0}}}return s}class Hy extends I{awake(){VI()}}class Gy extends I{constructor(){super(...arguments),a(this,"transformsPerFrame",10),a(this,"interval",0),a(this,"useFlatbuffers",!0),a(this,"builder",null),a(this,"models",null)}awake(){if(this.useFlatbuffers)this.context.connection.beginListenBinary(Lc,e=>{});else{this.models=[];for(let e=0;e<this.transformsPerFrame;e++)this.models.push(new IS(this.context.connection.connectionId+"_simulatedTransform_"+e,this))}}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 $m(1024));const e=this.builder;for(let t=0;t<this.transformsPerFrame;t++){e.clear();const s=xx(this.context.connection.connectionId,this);this.context.connection.sendBinary(s)}}else if(this.models)for(let e=0;e<this.models.length;e++){const t=this.models[e];t.dontSave=!0,t.update(this,null),this.context.connection.send("TestSimulateUserData-"+e,t)}}}}class IS{constructor(e,t){a(this,"guid"),a(this,"fast",!1),a(this,"position"),a(this,"rotation"),a(this,"velocity"),a(this,"dontSave"),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)}isValid(){return this.fast!==void 0||this.position!==void 0||this.rotation!==void 0||this.velocity!==void 0}update(e,t){const s=e.worldPosition;this.position.x=s.x,this.position.y=s.y,this.position.z=s.z;const o=e.worldQuaternion;if(this.rotation.x=o.x,this.rotation.y=o.y,this.rotation.z=o.z,this.rotation.w=o.w,this.fast=!1,t){const 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}}}a(IS,"temp",new S);var HI=Object.defineProperty,em=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&HI(e,t,o),o};const GI=C("debugsignals");class tm{constructor(){a(this,"guid")}}em([m()],tm.prototype,"guid");class jh{constructor(){a(this,"signal"),a(this,"reaction")}}em([m(tm)],jh.prototype,"signal"),em([m(xe)],jh.prototype,"reaction");var js;const LS=(js=class extends I{constructor(){super(...arguments),a(this,"events")}static invoke(n){if(js.receivers[n]){const e=js.receivers[n];if(!e)return;for(const t of e)t.invoke(n)}}awake(){GI&&console.log("SignalReceiver awake",this)}onEnable(){if(this.events)for(const n of this.events)js.receivers[n.signal.guid]||(js.receivers[n.signal.guid]=[]),js.receivers[n.signal.guid].push(this)}onDisable(){if(this.events){for(const n of this.events)if(js.receivers[n.signal.guid]){const e=js.receivers[n.signal.guid].indexOf(this);e>=0&&js.receivers[n.signal.guid].splice(e,1)}}}invoke(n){if(!this.events||!Array.isArray(this.events))return;const e=typeof n=="object"?n.guid:n;for(const t of this.events)if(t.signal.guid===e)try{if(t.reaction){if(!t.reaction.invoke){console.warn("Missing invoke - possibly a serialization error",t,this);continue}}else{console.warn("Missing reaction for signal",t,this);continue}t.reaction.invoke()}catch(s){console.error(s)}}},a(js,"receivers",{}),js);em([m(jh)],LS.prototype,"events");let Dh=LS;var qi=(n=>(n.Activation="ActivationTrack",n.Animation="AnimationTrack",n.Audio="AudioTrack",n.Control="ControlTrack",n.Marker="MarkerTrack",n.Signal="SignalTrack",n))(qi||{}),bn=(n=>(n[n.None=0]="None",n[n.Hold=1]="Hold",n[n.Loop=2]="Loop",n[n.PingPong=3]="PingPong",n[n.Continue=4]="Continue",n))(bn||{}),qy=(n=>(n.Signal="SignalEmitter",n))(qy||{});const _n=C("debugtimeline");class Bh{constructor(){a(this,"director"),a(this,"track")}get muted(){return this.track.muted}set muted(e){var t;e!==this.track.muted&&(this.track.muted=e,(t=this.onMuteChanged)==null||t.call(this))}*forEachClip(e=!1){var t;if((t=this.track)!=null&&t.clips)if(e)for(let s=this.track.clips.length-1;s>=0;s--)yield this.track.clips[s];else for(const s of this.track.clips)yield s}getClipTime(e,t){return t.clipIn+(e-t.start)*t.timeScale}getClipTimeNormalized(e,t){return(e-t.start)/t.duration}evaluateWeight(e,t,s,o=!0){if(t<0||t>=s.length)return 0;const r=s[t];if(o||e>=r.start&&e<=r.end){let l=1;if(r.easeInDuration>0){const c=Math.min((e-r.start)/r.easeInDuration,1);l*=c}if(r.easeOutDuration>0){const c=Math.min((r.end-e)/r.easeOutDuration,1);l*=c}return l}return 0}}class qI{constructor(e){a(this,"clip"),a(this,"rootPositionOffset"),a(this,"rootQuaternionOffset"),a(this,"rootStartPosition"),a(this,"rootEndPosition"),a(this,"rootStartQuaternion"),a(this,"rootEndQuaternion");const t=e.getClip();this.clip=t;const s=e.getRoot(),o=s.name+".position",r=s.name+".quaternion";_n&&console.log(t.name,t.tracks,o);for(const l of t.tracks)if(!(l.times.length<=0)){if(l.name.endsWith(o))this.rootStartPosition=new S().fromArray(l.values,0),this.rootEndPosition=new S().fromArray(l.values,l.values.length-3),this.rootPositionOffset=this.rootEndPosition.clone().sub(this.rootStartPosition),_n&&console.log(this.rootPositionOffset);else if(l.name.endsWith(r)&&(this.rootStartQuaternion=new V().fromArray(l.values,0),this.rootEndQuaternion=new V().fromArray(l.values,l.values.length-4),this.rootQuaternionOffset=this.rootEndQuaternion.clone().multiply(this.rootStartQuaternion),_n)){const c=new Dt().setFromQuaternion(this.rootQuaternionOffset);console.log("ROT",c)}}}get hasOffsets(){return this.rootPositionOffset!==void 0||this.rootQuaternionOffset!==void 0}}class im extends Bh{constructor(){super(...arguments),a(this,"models",[]),a(this,"trackOffset"),a(this,"target"),a(this,"mixer"),a(this,"clips",[]),a(this,"actions",[]),a(this,"weight",1),a(this,"_actionOffsets",[]),a(this,"_didBind",!1),a(this,"_animator",null),a(this,"_useclipOffsets",!0),a(this,"_totalOffsetPosition",new S),a(this,"_totalOffsetRotation",new V),a(this,"_totalOffsetPosition2",new S),a(this,"_totalOffsetRotation2",new V),a(this,"_summedPos",new S),a(this,"_tempPos",new S),a(this,"_summedRot",new V),a(this,"_tempRot",new V),a(this,"_clipRotQuat",new V)}onDisable(){var e;(e=this.mixer)==null||e.stopAllAction()}onDestroy(){this.director.context.animations.unregisterAnimationMixer(this.mixer)}onStateChanged(){this._animator&&px(this._animator.gameObject,this,this.director.isPlaying)}createHooks(e,t){var s,o;if(((s=t.tracks)==null?void 0:s.length)<=0){console.warn("No tracks in AnimationClip",t);return}const r=t.tracks[0].name.split("."),l=r[r.length-2],c=l+".position",h=l+".quaternion";let d=!1,u=!1;for(const p of t.tracks)p.name.endsWith(c)?(d=!0,this.createPositionInterpolant(t,e,p)):p.name.endsWith(h)&&(u=!0,this.createRotationInterpolant(t,e,p));if(!d||!u){const p=(o=this.mixer)==null?void 0:o.getRoot(),g=t.tracks[0],f=g.name.lastIndexOf("."),y=g.name.substring(0,f),v=y.substring(y.lastIndexOf(".")+1),b=p.getObjectByName(v);if(b)if(d){if(!u){const _=t.tracks[0].name.substring(0,f)+".quaternion";_n&&console.warn("Create quaternion track",v,b);const w=b.quaternion,x=new NP(_,[0,t.duration],[w.x,w.y,w.z,w.w,w.x,w.y,w.z,w.w]);t.tracks.push(x),this.createRotationInterpolant(t,e,x)}}else{const _=y+".position";_n&&console.warn("Create position track",v,b);const w=b.position,x=new zP(_,[0,t.duration],[w.x,w.y,w.z,w.x,w.y,w.z]);t.tracks.push(x),this.createPositionInterpolant(t,e,x)}}}bind(){if(!this._didBind){this._didBind=!0,_n&&console.log(this.models),this.mixer?this.target=this.mixer.getRoot():console.warn("No mixer was assigned to animation track");for(const e of this.actions){const t=new qI(e);this._actionOffsets.push(t)}this.target&&(this._animator=P.getComponent(this.target,Rt)??null,this._animator&&px(this._animator.gameObject,this,!0));for(const e of this.models){const t=e.asset,s=t.position,o=t.rotation;s&&s.x!==void 0&&(s.isVector3||(t.position=new S(s.x,s.y,s.z)),o.isQuaternion||(t.rotation=new V(o.x,o.y,o.z,o.w)))}this.ensureTrackOffsets()}}ensureTrackOffsets(){if(this.trackOffset){const e=this.trackOffset.position;e&&(e.isVector3||(this.trackOffset.position=new S(e.x,e.y,e.z)));const t=this.trackOffset.rotation;t&&(t.isQuaternion||(this.trackOffset.rotation=new V(t.x,t.y,t.z,t.w)))}}evaluate(e){var t,s,o,r,l,c,h;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 d=0,u=0,p=!1,g=!1,f=0;for(let y=0;y<this.clips.length;y++){const v=this.models[y],b=this.actions[y],_=v.asset;b.weight=0;const w=e>=v.start&&e<=v.end,x=v.preExtrapolationMode,k=v.postExtrapolationMode,M=y<this.clips.length-1?this.models[y+1]:null;let T=w,L=!1;if(!T&&!p&&v.end<e&&k!==bn.None?(!M||M.start>e)&&(T=!0,p=!0):y==0&&!T&&!g&&v.start>e&&x!==bn.None&&(!M||M.start<e)&&(T=!0,L=!0,g=!0),T){let D=this.weight;D*=this.evaluateWeight(e,y,this.models,T),D*=this.director.weight;let z=w;if(L)switch(x){case bn.Hold:break;case bn.Loop:e+=v.start,z=!0;break;default:e+=v.start,z=!0;break}let j=this.getClipTime(e,v),H=0;const K=_.duration;if(L&&x===bn.Hold&&(j=0),z){if(_.loop)for(H+=Math.floor(j/(K+1e-6));j>K;)j-=K}else if(!w&&p)switch(k){case bn.Hold:j=this.getClipTime(v.end,v);break;case bn.Loop:j%=K;break;case bn.PingPong:const B=Math.floor(j/K)%2!==0;j%=K,B&&(j=K-j);break}v.reversed===!0?b.time=b.getClip().duration-j:b.time=j,b.timeScale=0;const U=Math.max(0,D);if(b.weight=U,f+=U,b.clampWhenFinished=!1,b.isRunning()||b.play(),this._useclipOffsets){const B=d==0?this._totalOffsetPosition:this._totalOffsetPosition2,Q=d==0?this._totalOffsetRotation:this._totalOffsetRotation2;d<1&&(u=1-D),d+=1;const te=this._summedPos.set(0,0,0),ae=this._tempPos.set(0,0,0),le=this._summedRot.identity(),ye=this._tempRot.identity(),He=_.rotation;He&&(this._clipRotQuat.identity(),this._clipRotQuat.slerp(He,D));const vt=this._actionOffsets[y];if(vt.hasOffsets)for(let gr=0;gr<H;gr++)vt.rootPositionOffset?ae.copy(vt.rootPositionOffset):ae.set(0,0,0),ae.applyQuaternion(le),this._clipRotQuat&&ae.applyQuaternion(this._clipRotQuat),vt.rootQuaternionOffset&&(ye.copy(vt.rootQuaternionOffset),le.multiply(ye)),te.add(ae);this._clipRotQuat&&Q.multiply(this._clipRotQuat),Q.multiply(le),_.position&&te.add(_.position),B.add(te)}}}if(this._useclipOffsets&&(this._totalOffsetPosition.lerp(this._totalOffsetPosition2,u),this._totalOffsetRotation.slerp(this._totalOffsetRotation2,u)),this.__mixerError===void 0&&(_n||F())&&(s=(t=this._animator)==null?void 0:t.runtimeAnimatorController)!=null&&s.mixer&&this.mixer!==((r=(o=this._animator)==null?void 0:o.runtimeAnimatorController)==null?void 0:r.mixer)&&(this.__mixerError=!0,console.error("AnimationTrack mixer is not shared with the animator controller - this might result in the timeline to not animate properly. Please report a bug to the Needle Engine team!",this)),(l=this._animator)!=null&&l.runtimeAnimatorController){const y=Math.max(0,1-f);(h=(c=this._animator)==null?void 0:c.runtimeAnimatorController)==null||h.update(y)}else this.mixer.update(e)}createRotationInterpolant(e,t,s){var o;const r=s.createInterpolant.bind(s),l=new V;this.ensureTrackOffsets();const c=(o=this.trackOffset)==null?void 0:o.rotation;s.createInterpolant=()=>{const h=r(),d=h.evaluate.bind(h);return h.evaluate=u=>{var p;const g=d(u);if(l.set(g[0],g[1],g[2],g[3]),l.premultiply(this._totalOffsetRotation),c&&l.premultiply(c),this.director.animationCallbackReceivers)for(const f of this.director.animationCallbackReceivers)(p=f?.onTimelineRotation)==null||p.call(f,this.director,this.target,u,l);return g[0]=l.x,g[1]=l.y,g[2]=l.z,g[3]=l.w,g},h}}createPositionInterpolant(e,t,s){var o,r;const l=s.createInterpolant.bind(s),c=new S;this.ensureTrackOffsets();const h=(o=this.trackOffset)==null?void 0:o.rotation,d=(r=this.trackOffset)==null?void 0:r.position;let u;s.createInterpolant=()=>{const p=l(),g=p.evaluate.bind(p);return p.evaluate=f=>{var y,v,b;const _=g(f);if(c.set(_[0],_[1],_[2]),t.removeStartOffset&&(u===void 0?(u=null,u=(v=(y=this._actionOffsets.find(w=>w.clip===e))==null?void 0:y.rootStartPosition)==null?void 0:v.clone()):u!=null&&u.isVector3&&c.sub(u)),c.applyQuaternion(this._totalOffsetRotation),c.add(this._totalOffsetPosition),h&&c.applyQuaternion(h),d&&(c.x-=d.x,c.y+=d.y,c.z+=d.z),this.director.animationCallbackReceivers)for(const w of this.director.animationCallbackReceivers)(b=w?.onTimelinePosition)==null||b.call(w,this.director,this.target,f,c);return _[0]=c.x,_[1]=c.y,_[2]=c.z,_},p}}}const XI=C("mutetimeline"),jS=class ld extends Bh{constructor(){super(...arguments),a(this,"models",[]),a(this,"listener"),a(this,"audio",[]),a(this,"audioContextTimeOffset",[]),a(this,"lastTime",0),a(this,"audioSource"),a(this,"_audioLoader",null),a(this,"_playableDirectorResumed",!1)}getAudioFilePath(e){const t=this.director.sourceId;return yo(t,e)}onAllowAudioChanged(e){for(let t=0;t<this.models.length;t++){const s=this.models[t];this.audio[t].setVolume(e?s.asset.volume:0)}}addModel(e){const t=new WP(this.listener);this.audio.push(t);const s=e;s._didTriggerPlay=!1,this.models.push(s)}onDisable(){for(const e of this.audio)e.isPlaying&&e.stop();for(const e of this.models)e._didTriggerPlay=!1}onDestroy(){for(const e of this.audio)e.source&&e?.disconnect();this.audio.length=0}onMuteChanged(){if(this.muted)for(let e=0;e<this.audio.length;e++){const t=this.audio[e];t!=null&&t.isPlaying&&t.stop()}}stop(){for(let e=0;e<this.audio.length;e++){const t=this.audio[e];t!=null&&t.isPlaying&&t.stop()}for(const e of this.models)e._didTriggerPlay=!1}onPauseChanged(){for(let e=0;e<this.audio.length;e++){const t=this.audio[e];t!=null&&t.isPlaying&&t.stop()}this._playableDirectorResumed=this.director.isPlaying}evaluate(e){if(XI||this.track.muted||this.director.speed<0)return;const t=this.director.context.application.muted,s=this._playableDirectorResumed;this._playableDirectorResumed=!1;const o=t?.1:0;for(let r=0;r<this.models.length;r++){const l=this.models[r],c=this.audio[r],h=l.asset;if((!c||!c.buffer)&&this.isInTimeRange(l,e-1,e+1)&&this.handleAudioLoading(l,c),ns.userInteractionRegistered!==!1&&!(c===null||!c.buffer))if(c.playbackRate=this.director.context.time.timeScale*this.director.speed,c.loop=h.loop,e>=l.start&&e<=l.end&&e<this.director.duration){if(!c.isPlaying||!this.director.isPlaying)(s||!l._didTriggerPlay&&this.lastTime<e)&&(l.duration*l.timeScale>.3?c.offset=l.clipIn+(e-l.start)*l.timeScale:c.offset=0,_n&&console.log("Timeline Audio ("+this.track.name+") play with offset "+c.offset+" - "+l.asset.clip),c.play(o),l._didTriggerPlay=!0);else{const u=l.clipIn+(e-l.start)*l.timeScale,p=c.context.currentTime-c._startedAt+c.offset;Math.abs(u-p)>.3&&(c.offset=u,c.stop(),c.play(o))}let d=h.volume;if(this.track.volume!==void 0&&(d*=this.track.volume),t&&(d=0),l.easeInDuration>0){const u=Math.min((e-l.start)/l.easeInDuration,1);d*=u}if(l.easeOutDuration>0){const u=Math.min((l.end-e)/l.easeOutDuration,1);d*=u}c.setVolume(d*this.director.weight)}else l._didTriggerPlay=!1,this.director.isPlaying&&c.isPlaying&&c.stop()}this.lastTime=e}loadAudio(e,t=0,s=0){let o=null;const r=e-s,l=e+t;for(const c of this.models)if(this.isInTimeRange(c,r,l)){const h=this.audio[this.models.indexOf(c)],d=this.handleAudioLoading(c,h);d!==null&&(o===null&&(o=[]),o.push(d))}return o!==null?Promise.all(o):null}isInTimeRange(e,t,s){return t<=e.start&&s>=e.end||t>=e.start&&t<=e.end||s>=e.start&&s<=e.end}static dispose(){ld._audioBuffers.clear()}handleAudioLoading(e,t){this._audioLoader||(this._audioLoader=new jm);const s=this.getAudioFilePath(e.asset.clip);if(ld._audioBuffers.get(s)){const r=ld._audioBuffers.get(s);return r.then(l=>{l&&t.setBuffer(l)}),r}_n&&console.warn("LOAD audio track",s,this.director.sourceId);const o=new Promise((r,l)=>{this._audioLoader.load(s,c=>{t.setBuffer(c),r(c)},void 0,c=>{console.error("Error loading audio",c),r(null)})});return ld._audioBuffers.set(s,o),o}};a(jS,"_audioBuffers",new Map);let sm=jS;class Fh extends Bh{constructor(){super(...arguments),a(this,"models",[]),a(this,"didTrigger",[]),a(this,"receivers",[])}evaluate(e){var t;if(this.track.muted)return;const s=this.director.context.time.deltaTime*1.5;for(let o=0;o<this.models.length;o++){const r=this.models[o],l=this.didTrigger[o],c=r.time-e;let h=!1;if(r.retroActive)h=c<=1e-6;else{const d=Math.abs(c);(d===0||d>=1e-5&&d<s)&&(h=!0)}if(h){if(!l)if(_n&&console.log("Trigger signal",e,r.time,r),this.didTrigger[o]=!0,((t=this.receivers)==null?void 0:t.length)<=0)Dh.invoke(r.asset);else for(const d of this.receivers)d&&d.invoke(r.asset)}else r.emitOnce||(this.didTrigger[o]=!1)}}}class nm extends Bh{constructor(){super(...arguments),a(this,"models",[]),a(this,"timelines",[]),a(this,"_previousActiveModel",null)}resolveSourceObjects(e){for(let t=this.models.length-1;t>=0;t--){const s=this.models[t].asset;if(!s.sourceObject||typeof s.sourceObject!="object"){console.log("no source object, removing model",t,s),this.models.splice(t,1);continue}else{const o=P.getComponent(s.sourceObject,Tl);this.timelines.push(o),o&&s.updateDirector&&(o.playOnAwake=!1)}}}evaluate(e){var t;this._previousActiveModel=null;for(let s=0;s<this.models.length;s++){const o=this.models[s],r=o.asset;if(e>=o.start&&e<=o.end){this._previousActiveModel=o;const l=this.getClipTime(e,o);if(r.controlActivation){const c=r.sourceObject;c.visible=!0}if(r.updateDirector){const c=this.timelines[s];c&&(c.isPlaying&&c.pause(),c.time=l,c.evaluate())}}else{const l=(t=this._previousActiveModel)==null?void 0:t.asset;if(r.controlActivation){const c=r.sourceObject;l?.sourceObject!==c&&(c.visible=!1)}}}}}var QI=Object.defineProperty,DS=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&QI(e,t,o),o};const so=C("debugtimeline");var Uh;const Xy=(Uh=class extends I{constructor(){super(...arguments),a(this,"playableAsset"),a(this,"playOnAwake"),a(this,"extrapolationMode",1),a(this,"waitForAudio",!0),a(this,"_visibilityChangeEvt"),a(this,"_clonedPlayableAsset",!1),a(this,"_speed",1),a(this,"_guidsMap"),a(this,"_isPlaying",!1),a(this,"_internalUpdateRoutine"),a(this,"_isPaused",!1),a(this,"_isStopping",!1),a(this,"_time",0),a(this,"_duration",0),a(this,"_weight",1),a(this,"_animationTracks",[]),a(this,"_audioTracks",[]),a(this,"_signalTracks",[]),a(this,"_controlTracks",[]),a(this,"_customTracks",[]),a(this,"_allTracks",[this._animationTracks,this._audioTracks,this._signalTracks,this._controlTracks,this._customTracks]),a(this,"animationCallbackReceivers",[])}static registerCreateTrack(n,e){this.createTrackFunctions[n]=e}get isPlaying(){return this._isPlaying}get isPaused(){return this._isPaused}get time(){return this._time}set time(n){typeof n=="number"&&!Number.isNaN(n)?this._time=n:(so||Xt())&&console.error("INVALID TIMELINE.TIME VALUE",n,this.name)}get duration(){return this._duration}set duration(n){this._duration=n}get weight(){return this._weight}set weight(n){this._weight=n}get speed(){return this._speed}set speed(n){this._speed=n}awake(){var n,e,t,s,o;so&&console.log(this,(n=this.playableAsset)==null?void 0:n.tracks),this.rebuildGraph(),!this.isValid()&&(so||F())&&(so?console.warn("PlayableDirector is not valid","Asset?",this.playableAsset,"Tracks:",(e=this.playableAsset)==null?void 0:e.tracks,"IsArray?",Array.isArray((t=this.playableAsset)==null?void 0:t.tracks),this):(o=(s=this.playableAsset)==null?void 0:s.tracks)!=null&&o.length?console.warn("PlayableDirector is not valid"):console.warn("PlayableDirector has no tracks"))}onEnable(){var n,e,t;for(const s of this._audioTracks)(n=s.onEnable)==null||n.call(s);for(const s of this._customTracks)(e=s.onEnable)==null||e.call(s);for(const s of this._animationTracks)(t=s.onEnable)==null||t.call(s);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(){var n,e,t;this.stop();for(const s of this._audioTracks)(n=s.onDisable)==null||n.call(s);for(const s of this._customTracks)(e=s.onDisable)==null||e.call(s);for(const s of this._animationTracks)(t=s.onDisable)==null||t.call(s);this._visibilityChangeEvt&&window.removeEventListener("visibilitychange",this._visibilityChangeEvt)}onDestroy(){var n;for(const e of this._allTracks)for(const t of e)(n=t.onDestroy)==null||n.call(t)}rebuildGraph(){this.isValid()&&(this.resolveBindings(),this.updateTimelineDuration(),this.setupAndCreateTrackHandlers())}async play(){if(!this.isValid())return;const n=this._isPaused==!0;if(this._isPaused=!1,!this._isPlaying){if(this._isPlaying=!0,n&&this.invokePauseChangedMethodsOnTracks(),this.waitForAudio){const e=[];for(const t of this._audioTracks){const s=t.loadAudio(this._time,1,0);s&&e.push(s)}if(e.length>0&&(await Promise.all(e),!this._isPlaying))return;for(;this._audioTracks.length>0&&this._isPlaying&&!ns.userInteractionRegistered&&this.waitForAudio;)await vs(200)}this.invokeStateChangedMethodsOnTracks(),this._internalUpdateRoutine=this.startCoroutine(this.internalUpdate(),Oe.LateUpdate)}}pause(){this.isValid()&&(this._isPlaying=!1,!this._isPaused&&(this._isPaused=!0,this.internalEvaluate(),this.invokePauseChangedMethodsOnTracks(),this.invokeStateChangedMethodsOnTracks()))}stop(){this._isStopping=!0;for(const t of this._audioTracks)t.stop();const n=this._isPaused==!0,e=this._isPlaying;this._isPlaying&&(this._time=0,this._isPlaying=!1,this._isPaused=!1,this.internalEvaluate(),n&&this.invokePauseChangedMethodsOnTracks()),this._isPlaying=!1,this._isPaused=!1,n&&!e&&this.invokePauseChangedMethodsOnTracks(),e&&this.invokeStateChangedMethodsOnTracks(),this._internalUpdateRoutine&&this.stopCoroutine(this._internalUpdateRoutine),this._internalUpdateRoutine=null,this._isStopping=!1}evaluate(){this.internalEvaluate(!0)}isValid(){return this.playableAsset&&this.playableAsset.tracks&&Array.isArray(this.playableAsset.tracks)}*forEachTrack(){for(const n of this._allTracks)for(const e of n)yield e}get animationTracks(){return this._animationTracks}get audioTracks(){return this._audioTracks}resolveGuids(n){this._guidsMap=n}invokePauseChangedMethodsOnTracks(){var n;for(const e of this.forEachTrack())(n=e.onPauseChanged)==null||n.call(e)}invokeStateChangedMethodsOnTracks(){var n;for(const e of this.forEachTrack())(n=e.onStateChanged)==null||n.call(e,this._isPlaying)}*internalUpdate(){for(;this._isPlaying&&this.activeAndEnabled;)!this._isPaused&&this._isPlaying&&(this._time+=this.context.time.deltaTime*this.speed,this.internalEvaluate()),yield}internalEvaluate(n=!1){if(!this.isValid())return;let e=this._time;switch(this.extrapolationMode){case 0:this._speed>0?e=Math.min(e,this._duration):this._speed<0&&(e=Math.max(e,0)),this._time=e;break;case 1:e%=this._duration,this._time=e;break;case 2:if(e>this._duration){this.stop();return}break}const t=this._time;for(const s of this.playableAsset.tracks)if(!s.muted)switch(s.type){case qi.Activation:if(!n&&!this._isPlaying)continue;for(let o=0;o<s.outputs.length;o++){const r=s.outputs[o];if(typeof r=="object"){let l=!1;if(s.clips)for(const h of s.clips)h.start<=t&&t<=h.end&&(l=!0);const c=r;c.visible!==void 0&&c.visible!==l&&(c.visible=l,so&&console.warn(this.name,"set ActivationTrack-"+o,c.name,l,t))}}break}if(!this._isStopping)for(const s of this._animationTracks)s.evaluate(t);for(const s of this._audioTracks)s.evaluate(t);for(const s of this._signalTracks)s.evaluate(t);for(const s of this._controlTracks)s.evaluate(t);for(const s of this._customTracks)s.evaluate(t)}resolveBindings(){if(this._clonedPlayableAsset||(this._clonedPlayableAsset=!0,this.playableAsset=ql(this.playableAsset)),!this.playableAsset||!this.playableAsset.tracks)return;const n=this.findRoot(this.gameObject);for(const e of this.playableAsset.tracks){for(let t=e.outputs.length-1;t>=0;t--){let s=e.outputs[t];if(typeof s=="string"){this._guidsMap&&this._guidsMap[s]&&(s=this._guidsMap[s]);const o=P.findByGuid(s,n);o===null||typeof o!="object"?(e.outputs.splice(t,1),console.warn("Failed to resolve binding",s,e.name,e.type)):(so&&console.log("Resolved binding",s,"to",o),e.outputs[t]=o)}else if(s===null){if(e.outputs.splice(t,1),Uh.createTrackFunctions[e.type])continue;e.type!==qi.Audio&&e.type!==qi.Control&&e.type!==qi.Marker&&e.type!==qi.Signal&&console.warn("Missing binding",s,e.name,e.type,this.name,this.playableAsset.name)}}if(e.type===qi.Control&&e.clips)for(let t=0;t<e.clips.length;t++){const s=e.clips[t];let o=s.asset.sourceObject;if(typeof o=="string"){this._guidsMap&&this._guidsMap[o]&&(o=this._guidsMap[o]);const r=P.findByGuid(o,n);r===null||typeof r!="object"?console.warn("Failed to resolve sourceObject binding",o,e.name,s):(so&&console.log("Resolved binding",o,"to",r),s.asset.sourceObject=r)}}}}findRoot(n){return n.parent?this.findRoot(n.parent):n}updateTimelineDuration(){if(this._duration=0,!(!this.playableAsset||!this.playableAsset.tracks)){for(const n of this.playableAsset.tracks)if(n.muted!==!0){if(n.clips)for(const e of n.clips)e.end>this._duration&&(this._duration=e.end);if(n.markers)for(const e of n.markers)e.time>this._duration&&(this._duration=e.time+.001)}}}setupAndCreateTrackHandlers(){var n,e,t;if(this._animationTracks.length=0,this._audioTracks.length=0,this._signalTracks.length=0,!this.playableAsset)return;let s=P.findObjectOfType(zn,this.context);for(const o of this.playableAsset.tracks){const r=o.type,l=Uh.createTrackFunctions[r];if(l!=null){const c=l(this,o);if(typeof c.evaluate=="function"){c.director=this,c.track=o,this._customTracks.push(c);continue}}if(o.type===qi.Animation){if(!o.clips||o.clips.length<=0){so&&console.warn("Animation track has no clips",o);continue}for(let c=o.outputs.length-1;c>=0;c--){let h=o.outputs[c];if(h instanceof E){const u=P.getOrAddComponent(h,Rt);u&&(h=u)}const d=(n=h?.gameObject)==null?void 0:n.animations;if(d){const u=new im;u.trackOffset=o.trackOffset,u.director=this,u.track=o;for(let p=0;p<o.clips.length;p++){const g=o.clips[p],f=g.asset;if(!f){console.error(`Timeline ${this.name}: clip #${p} on track "${o.name}" has no animation data`);continue}const y=f.clip;let v=y;if((typeof v=="string"||typeof v=="number")&&(v=d.find(_=>_.name===y)),so&&console.log(f,y,"\u2192",v),!v){console.warn("Could not find animationClip for model",g,o.name,this.name,(e=this.playableAsset)==null?void 0:e.name,d,h);continue}h instanceof Rt&&h.runtimeAnimatorController&&(h.__internalDidAwakeAndStart||h.initializeRuntimeAnimatorController(),h.runtimeAnimatorController.mixer||h.runtimeAnimatorController.bind(h),u.mixer=h.runtimeAnimatorController.mixer),u.mixer||(u.mixer=new Lm(h.gameObject),this.context.animations.registerAnimationMixer(u.mixer)),u.clips.push(v),u.mixer.uncacheAction(v),u.createHooks(g.asset,v);const b=u.mixer.clipAction(v);u.actions.push(b),u.models.push(g)}this._animationTracks.push(u)}}}else if(o.type===qi.Audio){if(!o.clips||o.clips.length<=0)continue;const c=new sm;c.director=this,c.track=o,c.audioSource=o.outputs.find(h=>h instanceof ns),this._audioTracks.push(c),s||(s=(t=this.context.mainCameraComponent)==null?void 0:t.gameObject.addComponent(zn)),c.listener=s.listener;for(let h=0;h<o.clips.length;h++){const d=o.clips[h];c.addModel(d)}}else if(o.type===qi.Marker){const c=new Fh;if(c.director=this,c.track=o,o.markers)for(const h of o.markers)switch(h.type){case qy.Signal:c.models.push(h),c.didTrigger.push(!1);break}if(c!==null&&c.models.length>0){const h=P.getComponent(this.gameObject,Dh);h&&(c.receivers.push(h),this._signalTracks.push(c))}}else if(o.type===qi.Signal){const c=new Fh;if(c.director=this,c.track=o,o.markers)for(const h of o.markers)c.models.push(h),c.didTrigger.push(!1);for(const h of o.outputs)c.receivers.push(h);this._signalTracks.push(c)}else if(o.type===qi.Control){const c=new nm;if(c.director=this,c.track=o,o.clips)for(const h of o.clips)c.models.push(h);c.resolveSourceObjects(this.context),this._controlTracks.push(c)}}}setAudioTracksAllowPlaying(n){for(const e of this._audioTracks)e.onAllowAudioChanged(n)}registerAnimationCallback(n){this.animationCallbackReceivers.push(n)}unregisterAnimationCallback(n){const e=this.animationCallbackReceivers.indexOf(n);e!==-1&&this.animationCallbackReceivers.splice(e,1)}},a(Uh,"createTrackFunctions",{}),Uh);DS([m()],Xy.prototype,"playOnAwake"),DS([m()],Xy.prototype,"extrapolationMode");let Tl=Xy;var YI=Object.defineProperty,om=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&YI(e,t,o),o};class da extends I{constructor(){super(...arguments),a(this,"isGizmo",!1),a(this,"translationSnap",1),a(this,"rotationSnapAngle",15),a(this,"scaleSnap",.25),a(this,"_control"),a(this,"orbit"),a(this,"onControlChangedEvent",e=>{const t=this.orbit;if(t&&(t.enabled=!e.value),e.value){const s=P.getComponentInParent(this.gameObject,sn);s&&s.requestOwnership()}}),a(this,"windowKeyDownListener",e=>{if(this.enabled&&this._control)switch(e.keyCode){case 81:this._control.setSpace(this._control.space==="local"?"world":"local");break;case 16:this.enableSnapping();break;case 87:this._control.setMode("translate");break;case 69:this._control.setMode("rotate");break;case 82:this._control.setMode("scale");break;case 187:case 107:this._control.setSize(this._control.size+.1);break;case 189:case 109:this._control.setSize(Math.max(this._control.size-.1,.1));break;case 88:this._control.showX=!this._control.showX;break;case 89:this._control.showY=!this._control.showY;break;case 90:this._control.showZ=!this._control.showZ;break;case 32:this._control.enabled=!this._control.enabled;break}}),a(this,"windowKeyUpListener",e=>{if(this.enabled)switch(e.keyCode){case 16:this.disableSnapping();break}})}get control(){return this._control}onEnable(){var e;if(!(this.isGizmo&&!yc)&&this.context.mainCamera&&(this._control||(this._control=new dO(this.context.mainCamera,this.context.renderer.domElement),this._control.enabled=!0,this._control.getRaycaster().layers.set(2),this._control.size=1,("_root"in this._control?this._control._root:this._control).traverse(t=>{const s=t;if(s.layers.set(2),s){const o=s.material;o&&(o.opacity=.3)}}),this.orbit=P.getComponentInParent(this.context.mainCamera,_e)??void 0),this._control)){const t=this._control.getHelper();this.context.scene.add(t),this._control.attach(this.gameObject),(e=this._control)==null||e.addEventListener("dragging-changed",this.onControlChangedEvent),window.addEventListener("keydown",this.windowKeyDownListener),window.addEventListener("keyup",this.windowKeyUpListener)}}onDisable(){var e,t,s;(t=(e=this._control)==null?void 0:e.getHelper())==null||t.removeFromParent(),(s=this._control)==null||s.removeEventListener("dragging-changed",this.onControlChangedEvent),window.removeEventListener("keydown",this.windowKeyDownListener),window.removeEventListener("keyup",this.windowKeyUpListener)}enableSnapping(){this._control&&(this._control.setTranslationSnap(this.translationSnap),this._control.setRotationSnap(Cn.degToRad(this.rotationSnapAngle)),this._control.setScaleSnap(this.scaleSnap))}disableSnapping(){this._control&&(this._control.setTranslationSnap(null),this._control.setRotationSnap(null),this._control.setScaleSnap(null))}}om([m()],da.prototype,"isGizmo"),om([m()],da.prototype,"translationSnap"),om([m()],da.prototype,"rotationSnapAngle"),om([m()],da.prototype,"scaleSnap");var KI=Object.defineProperty,ZI=Object.getOwnPropertyDescriptor,rm=(n,e,t,s)=>{for(var o=s>1?void 0:s?ZI(e,t):e,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=(s?l(e,t,o):l(o))||o);return s&&o&&KI(e,t,o),o};class Qy{constructor(){a(this,"texture",null),a(this,"rect")}}rm([m(je)],Qy.prototype,"texture",2);let El=class extends ch{constructor(){super(...arguments),a(this,"_sprite"),a(this,"pixelsPerUnitMultiplier",1)}set image(n){this.sprite||(this.sprite=new Qy),this.sprite.texture=n,this.onAfterCreated()}get image(){return this.sprite?this.sprite.texture:null}get sprite(){return this._sprite}set sprite(n){this._sprite!==n&&(this._sprite=n,this.onAfterCreated())}isBuiltinSprite(){var n,e,t,s,o,r,l;const c=this.sprite;switch((n=c?.texture)==null?void 0:n.name){case"InputFieldBackground":case"UISprite":case"Background":case"Knob":return!0}return!((t=(e=c?.texture)==null?void 0:e.name)!=null&&t.length)&&((o=(s=c?.texture)==null?void 0:s.image)==null?void 0:o.width)===32&&((l=(r=c?.texture)==null?void 0:r.image)==null?void 0:l.height)===32}onBeforeCreate(n){var e,t;super.onBeforeCreate(n),this.isBuiltinSprite()&&(n.borderRadius=5/this.pixelsPerUnitMultiplier,((t=(e=this.sprite)==null?void 0:e.texture)==null?void 0:t.name)==="Knob"&&(n.borderRadius=999))}onAfterCreated(){var n;this.__didAwake&&(super.onAfterCreated(),!this.isBuiltinSprite()&&this.setTexture((n=this.sprite)==null?void 0:n.texture))}};rm([m(Qy)],El.prototype,"sprite",1),rm([m()],El.prototype,"pixelsPerUnitMultiplier",2);class am extends ch{constructor(){super(...arguments),a(this,"_mainTexture")}get mainTexture(){return this._mainTexture}set mainTexture(e){this._mainTexture!==e&&(this._mainTexture=e,this.onAfterCreated())}onAfterCreated(){this.__didAwake&&(super.onAfterCreated(),this.setTexture(this.mainTexture))}}rm([m(je)],am.prototype,"mainTexture",1);var JI=Object.defineProperty,eL=Object.getOwnPropertyDescriptor,Xi=(n,e,t,s)=>{for(var o=s>1?void 0:s?eL(e,t):e,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=(s?l(e,t,o):l(o))||o);return s&&o&&JI(e,t,o),o};const ua=C("debugbutton");class cr{constructor(){a(this,"colorMultiplier"),a(this,"disabledColor"),a(this,"fadeDuration"),a(this,"highlightedColor"),a(this,"normalColor"),a(this,"pressedColor"),a(this,"selectedColor")}}Xi([m()],cr.prototype,"colorMultiplier",2),Xi([m(he)],cr.prototype,"disabledColor",2),Xi([m()],cr.prototype,"fadeDuration",2),Xi([m(he)],cr.prototype,"highlightedColor",2),Xi([m(he)],cr.prototype,"normalColor",2),Xi([m(he)],cr.prototype,"pressedColor",2),Xi([m(he)],cr.prototype,"selectedColor",2);class tL{constructor(){a(this,"disabledTrigger"),a(this,"highlightedTrigger"),a(this,"normalTrigger"),a(this,"pressedTrigger"),a(this,"selectedTrigger")}}class no extends I{constructor(){super(...arguments),a(this,"onClick",new xe),a(this,"_isHovered",0),a(this,"colors"),a(this,"transition"),a(this,"animationTriggers"),a(this,"animator"),a(this,"_interactable",!0),a(this,"_requestedAnimatorTrigger"),a(this,"_isInit",!1),a(this,"_image")}click(){var e;(e=this.onClick)==null||e.invoke()}onPointerEnter(e){var t,s;const o=e.event.pointerType==="mouse"&&e.button===0;o&&(this._isHovered+=1),ua&&console.warn("Button Enter",o,this._isHovered,(t=this.animationTriggers)==null?void 0:t.highlightedTrigger,this.animator),this.interactable&&(this.transition==3&&this.animationTriggers&&this.animator?this.animator.setTrigger(this.animationTriggers.highlightedTrigger):this.transition===1&&this.colors&&((s=this._image)==null||s.setState("hovered")),o&&this.context.input.setCursor("pointer"))}onPointerExit(){var e,t;this._isHovered-=1,this._isHovered<0&&(this._isHovered=0),ua&&console.log("Button Exit",this._isHovered,(e=this.animationTriggers)==null?void 0:e.highlightedTrigger,this.animator),this.interactable&&(this._isHovered>0||(this._isHovered=0,this.transition==3&&this.animationTriggers&&this.animator?this.animator.setTrigger(this.animationTriggers.normalTrigger):this.transition===1&&this.colors&&((t=this._image)==null||t.setState("normal")),this.context.input.unsetCursor("pointer")))}onPointerDown(e){var t,s;ua&&console.log("Button Down",(t=this.animationTriggers)==null?void 0:t.highlightedTrigger,this.animator),this.interactable&&(this.transition==3&&this.animationTriggers&&this.animator?this.animator.setTrigger(this.animationTriggers.pressedTrigger):this.transition===1&&this.colors&&((s=this._image)==null||s.setState("pressed")))}onPointerUp(e){var t,s;ua&&console.warn("Button Up",(t=this.animationTriggers)==null?void 0:t.highlightedTrigger,this.animator,this._isHovered),this.interactable&&(this.transition==3&&this.animationTriggers&&this.animator?this.animator.setTrigger(this._isHovered?this.animationTriggers.highlightedTrigger:this.animationTriggers.normalTrigger):this.transition===1&&this.colors&&((s=this._image)==null||s.setState(this._isHovered?"hovered":"normal")))}onPointerClick(e){if(this.interactable&&!(e.button!==0&&e.event.pointerType===Ud.Mouse)&&(ua&&(console.warn("Button Click",this.onClick),De("CLICKED button "+this.name+" at "+this.context.time.frameCount)),this.onClick&&this.onClick.listenerCount>0&&(this.onClick.invoke(),e.use(),ua))){const t=this.gameObject.worldPosition;t.add(this.gameObject.worldUp.multiplyScalar(1+Math.random()*.5)),$.DrawLabel(t,"CLICK:"+Date.now(),.1,1+Math.random()*.5)}}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}set_interactable(e){this.interactable=e}awake(){super.awake(),ua&&console.log(this),this._isInit=!1,this.init()}start(){var e;(e=this._image)==null||e.setInteractable(this.interactable),this.gameObject.getComponentInParent(Ya)||this.gameObject.addComponent(Au)}onEnable(){super.onEnable()}onDestroy(){this._isHovered&&this.context.input.unsetCursor("pointer")}*setAnimatorTriggerAtEndOfFrame(e){var t;this._requestedAnimatorTrigger=e,yield,yield,this._requestedAnimatorTrigger==e&&((t=this.animator)==null||t.setTrigger(e))}init(){this._isInit||(this._isInit=!0,this._image=P.getComponent(this.gameObject,El),this._image&&(this.stateSetup(this._image),this.interactable?this._image.setState("normal"):this._image.setState("disabled")))}stateSetup(e){var t,s,o,r,l;e.setInteractable(this.interactable);const c=this.getFinalColor(e.color,(t=this.colors)==null?void 0:t.normalColor),h={state:"normal",attributes:{backgroundColor:c,backgroundOpacity:c.alpha}};e.setupState(h);const d=this.getFinalColor(e.color,(s=this.colors)==null?void 0:s.highlightedColor),u={state:"hovered",attributes:{backgroundColor:d,backgroundOpacity:d.alpha}};e.setupState(u);const p=this.getFinalColor(e.color,(o=this.colors)==null?void 0:o.pressedColor),g={state:"pressed",attributes:{backgroundColor:p,backgroundOpacity:p.alpha}};e.setupState(g);const f=this.getFinalColor(e.color,(r=this.colors)==null?void 0:r.selectedColor),y={state:"selected",attributes:{backgroundColor:f,backgroundOpacity:f.alpha}};e.setupState(y);const v=this.getFinalColor(e.color,(l=this.colors)==null?void 0:l.disabledColor),b={state:"disabled",attributes:{backgroundColor:v,backgroundOpacity:v.alpha}};e.setupState(b)}getFinalColor(e,t){return t?e.clone().multiply(t).convertLinearToSRGB():e.clone().convertLinearToSRGB()}}Xi([m(xe)],no.prototype,"onClick",2),Xi([m(cr)],no.prototype,"colors",2),Xi([m()],no.prototype,"transition",2),Xi([m(tL)],no.prototype,"animationTriggers",2),Xi([m(Rt)],no.prototype,"animator",2),Xi([m()],no.prototype,"interactable",1);var iL=Object.defineProperty,lm=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&iL(e,t,o),o};const hr=C("debuginputfield");var Y;const zh=(Y=class extends I{constructor(){super(...arguments),a(this,"textComponent"),a(this,"placeholder"),a(this,"onValueChanged"),a(this,"onEndEdit"),a(this,"inputEventFn"),a(this,"_iosEventFn")}get text(){var n;return((n=this.textComponent)==null?void 0:n.text)??""}set text(n){this.textComponent&&(this.textComponent.text=n,this.placeholder&&(n.length>0?this.placeholder.gameObject.visible=!1:this.placeholder.gameObject.visible=!0))}get isFocused(){return Y.active===this}start(){hr&&console.log(this.name,this)}onEnable(){var n;Y.htmlField||(Y.htmlField=document.createElement("input"),Y.htmlField.style.width="0px",Y.htmlField.style.height="0px",Y.htmlField.style.padding="0px",Y.htmlField.style.border="none",Y.htmlField.style.overflow="hidden",Y.htmlField.style.caretColor="transparent",Y.htmlField.style.outline="none",Y.htmlField.classList.add("ar"),Y.htmlField.onfocus=()=>Y.htmlFieldFocused=!0,Y.htmlField.onblur=()=>Y.htmlFieldFocused=!1,document.body.append(Y.htmlField)),this.inputEventFn||(this.inputEventFn=this.onInput.bind(this)),Y.htmlField.addEventListener("keyup",this.inputEventFn),this.placeholder&&(n=this.textComponent)!=null&&n.text.length&&P.setActive(this.placeholder.gameObject,!1),X.isiOS()&&(this._iosEventFn=this.processInputOniOS.bind(this),window.addEventListener("click",this._iosEventFn))}onDisable(){var n;(n=Y.htmlField)==null||n.removeEventListener("keyup",this.inputEventFn),this.onDeselected(),this._iosEventFn&&window.removeEventListener("click",this._iosEventFn)}clear(){Y.active===this&&Y.htmlField?(Y.htmlField.value="",this.setTextFromInputField()):(this.textComponent&&(this.textComponent.text=""),this.placeholder&&P.setActive(this.placeholder.gameObject,!0))}select(){this.onSelected()}deselect(){this.onDeselected()}onPointerEnter(n){n.event.pointerType==="mouse"&&n.button===0&&this.context.input.setCursor("text")}onPointerExit(n){this.context.input.unsetCursor("text")}onPointerClick(n){hr&&console.log("CLICK",n,Y.active),Y.activeTime=this.context.time.time,Y.active!==this&&this.startCoroutine(this.activeLoop(),Oe.LateUpdate),this.selectInputField()}*activeLoop(){for(this.onSelected();Y.active===this&&!(this.context.input.getPointerClicked(0)&&this.context.time.time-Y.activeTime>.2);)this.setTextFromInputField(),yield;this.onDeselected()}onSelected(){var n,e,t,s;if(Y.active!==this&&(hr&&console.log("Select",this.name,this,Y.htmlField,this.context.isInXR,this.context.arOverlayElement,(n=this.textComponent)==null?void 0:n.text,(e=Y.htmlField)==null?void 0:e.value),(t=Y.active)==null||t.onDeselected(),Y.active=this,this.placeholder&&P.setActive(this.placeholder.gameObject,!1),Y.htmlField)){if(Y.htmlField.value=((s=this.textComponent)==null?void 0:s.text)||"",hr&&console.log("set input field value",Y.htmlField.value),this.context.isInXR){const o=this.context.arOverlayElement;o&&o.append(Y.htmlField)}this.selectInputField()}}onDeselected(){var n;Y.active===this&&(Y.active=null,hr&&console.log("Deselect",this.name,this),Y.htmlField&&(Y.htmlField.blur(),document.body.append(Y.htmlField)),this.placeholder&&(!this.textComponent||this.textComponent.text.length<=0)&&P.setActive(this.placeholder.gameObject,!0),Y.htmlField&&((n=this.onEndEdit)==null||n.invoke(Y.htmlField.value)))}update(){var n;Y.active===this&&((n=this.textComponent)==null||n.markDirty())}onInput(n){var e,t;if(Y.active===this){if(hr&&console.log(n.code,n,(e=Y.htmlField)==null?void 0:e.value,(t=this.textComponent)==null?void 0:t.text),n.code==="Escape"||n.code==="Enter"){this.onDeselected();return}Y.htmlField&&(this.textComponent&&(this.setTextFromInputField(),this.placeholder&&P.setActive(this.placeholder.gameObject,this.textComponent.text.length<=0)),this.selectInputField())}}setTextFromInputField(){var n;if(this.textComponent&&Y.htmlField){const e=this.textComponent.text,t=Y.htmlField.value,s=this.textComponent.text!==Y.htmlField.value;this.textComponent.text=Y.htmlField.value,s&&(hr&&console.log("[InputField] value changed:",t,e),(n=this.onValueChanged)==null||n.invoke(t,e))}}selectInputField(){Y.htmlField&&(hr&&console.log("Focus Inputfield",Y.htmlFieldFocused),Y.htmlField.setSelectionRange(Y.htmlField.value.length,Y.htmlField.value.length),X.isiOS()?Y.htmlField.focus({preventScroll:!0}):setTimeout(()=>{var n;return(n=Y.htmlField)==null?void 0:n.focus()},1))}processInputOniOS(){const n=this.context.physics.raycast();if(!n.length)return;const e=n[0].object,t=Nf(e);(t?.gameObject===this.gameObject||t?.gameObject.parent===this.gameObject)&&this.selectInputField()}},a(Y,"active",null),a(Y,"activeTime",-1),a(Y,"htmlField",null),a(Y,"htmlFieldFocused",!1),Y);lm([m(Nt)],zh.prototype,"textComponent"),lm([m(Nt)],zh.prototype,"placeholder"),lm([m(xe)],zh.prototype,"onValueChanged"),lm([m(xe)],zh.prototype,"onEndEdit");let Yy=zh;var sL=Object.defineProperty,BS=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&sL(e,t,o),o};class Nh extends I{constructor(){super(...arguments),a(this,"id",null),a(this,"keepAspect",!1),a(this,"_object",null)}onEnable(){if(this._object){this.gameObject.add(this._object);return}if(!this.id||!this.context.mainCamera)return;const 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";const t=new uO;t.listenToPointerEvents(this.context.renderer,this.context.mainCamera),this.gameObject.add(t);const s=new pO(e);t.add(s),s.visible=!1;const o=s.material;o.transparent=!0,setTimeout(()=>{s.visible=!0;const r=Ad(this.gameObject).clone();Zl(this.gameObject,0,0,0),this.gameObject.updateMatrixWorld();const l=new Si;l.setFromObject(t),this.setWorldRotation(r.x,r.y,r.z);const c=l.max.x-l.min.x,h=l.max.y-l.min.y;if(this.keepAspect){const u=c/h;c>h?s.scale.set(1/c,1/h/u,1):s.scale.set(1/c*u,1/h,1)}else s.scale.set(1/c,1/h,1);const d=this.gameObject.scale;s.scale.multiply(d)},1)}onDisable(){var e;(e=this._object)==null||e.removeFromParent()}}BS([m()],Nh.prototype,"id"),BS([m()],Nh.prototype,"keepAspect");/* @license
|
|
1391
1394
|
* Copyright 2021 Google LLC. All Rights Reserved.
|
|
1392
1395
|
* Licensed under the Apache License, Version 2.0 (the 'License');
|
|
1393
1396
|
* you may not use this file except in compliance with the License.
|
|
@@ -1400,14 +1403,14 @@ C) Set "joinRandomRoom" to true`),!1):($y&&console.log("Join "+this.roomName),th
|
|
|
1400
1403
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
1401
1404
|
* See the License for the specific language governing permissions and
|
|
1402
1405
|
* limitations under the License.
|
|
1403
|
-
*/const
|
|
1406
|
+
*/const nL={topLight:{intensity:500,position:[.418,16.199,.3]},room:{position:[-.757,13.219,.717],scale:[31.713,28.305,28.591]},boxes:[{position:[-10.906,2.009,1.846],rotation:-.195,scale:[2.328,7.905,4.651]},{position:[-5.607,-.754,-.758],rotation:.994,scale:[1.97,1.534,3.955]},{position:[6.167,.857,7.803],rotation:.561,scale:[3.927,6.285,3.687]},{position:[-2.017,.018,6.124],rotation:.333,scale:[2.002,4.566,2.064]},{position:[2.291,-.756,-2.621],rotation:-.286,scale:[1.546,1.552,1.496]},{position:[-2.193,-.369,-5.547],rotation:.516,scale:[3.875,3.487,2.986]}],lights:[{intensity:50,position:[-16.116,14.37,8.208],scale:[.1,2.428,2.739]},{intensity:50,position:[-16.109,18.021,-8.207],scale:[.1,2.425,2.751]},{intensity:17,position:[14.904,12.198,-1.832],scale:[.15,4.265,6.331]},{intensity:43,position:[-.462,8.89,14.52],scale:[4.38,5.441,.088]},{intensity:20,position:[3.235,11.486,-12.541],scale:[2.5,2,.1]},{intensity:100,position:[0,20,0],scale:[1,.1,1]}]},oL={topLight:{intensity:400,position:[.5,14,.5]},room:{position:[0,13.2,0],scale:[31.5,28.5,31.5]},boxes:[{position:[-10.906,-1,1.846],rotation:-.195,scale:[2.328,7.905,4.651]},{position:[-5.607,-.754,-.758],rotation:.994,scale:[1.97,1.534,3.955]},{position:[6.167,-.16,7.803],rotation:.561,scale:[3.927,6.285,3.687]},{position:[-2.017,.018,6.124],rotation:.333,scale:[2.002,4.566,2.064]},{position:[2.291,-.756,-2.621],rotation:-.286,scale:[1.546,1.552,1.496]},{position:[-2.193,-.369,-5.547],rotation:.516,scale:[3.875,3.487,2.986]}],lights:[{intensity:80,position:[-14,10,8],scale:[.1,2.5,2.5]},{intensity:80,position:[-14,14,-4],scale:[.1,2.5,2.5]},{intensity:23,position:[14,12,0],scale:[.1,5,5]},{intensity:16,position:[0,9,14],scale:[5,5,.1]},{intensity:80,position:[7,8,-14],scale:[2.5,2.5,.1]},{intensity:80,position:[-7,16,-14],scale:[2.5,2.5,.1]},{intensity:1,position:[0,20,0],scale:[.1,.1,.1]}]};class cm extends xi{constructor(e){super(),this.position.y=-3.5;const t=new xa;t.deleteAttribute("uv");const s=new bt({metalness:0,side:wd}),o=new bt({metalness:0}),r=e=="legacy"?nL:oL,l=new Tm(16777215,r.topLight.intensity,28,2);l.position.set(...r.topLight.position),this.add(l);const c=new G(t,s);c.position.set(...r.room.position),c.scale.set(...r.room.scale),this.add(c);for(const h of r.boxes){const d=new G(t,o);d.position.set(...h.position),d.rotation.set(0,h.rotation,0),d.scale.set(...h.scale),this.add(d)}for(const h of r.lights){const d=new G(t,this.createAreaLightMaterial(h.intensity));d.position.set(...h.position),d.scale.set(...h.scale),this.add(d)}}createAreaLightMaterial(e){const t=new Me;return t.color.setScalar(e),t}}var rL=Object.defineProperty,hm=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&rL(e,t,o),o},dm;const Wh=(dm=class extends I{constructor(){super(...arguments),a(this,"target"),a(this,"invertForward",!1),a(this,"keepUpDirection",!0),a(this,"copyTargetRotation",!1)}onBeforeRender(){let n=this.target;if(n||(n=this.context.mainCamera),!n)return;let e=this.copyTargetRotation;(this.context.isInVR||this.context.isInPassThrough)&&(e=!1),Kl(this.gameObject,n,this.keepUpDirection,e),this.invertForward&&this.gameObject.quaternion.multiply(dm.flipYQuat)}createBehaviours(n,e,t){if(e.uuid===this.gameObject.uuid){let s=e;if(this.keepUpDirection){const r=mi.createEmptyParent(e);s=r;const l=this.invertForward?-1:1;r.setMatrix(r.getMatrix().multiply(new se().makeRotationZ(Math.PI/2*l))),e.setMatrix(e.getMatrix().multiply(new se().makeRotationZ(-Math.PI/2*l)))}const o=new Jt("lookat "+this.name,At.sceneStartTrigger(),ve.lookAtCameraAction(s,void 0,this.invertForward?fs.back:fs.forward,this.keepUpDirection?fs.up:fs.zero));n.addBehavior(o)}}},a(dm,"flipYQuat",new V().setFromAxisAngle(new S(0,1,0),Math.PI)),dm);hm([m(E)],Wh.prototype,"target"),hm([m()],Wh.prototype,"invertForward"),hm([m()],Wh.prototype,"keepUpDirection"),hm([m()],Wh.prototype,"copyTargetRotation");let Ky=Wh;var aL=Object.defineProperty,Zy=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&aL(e,t,o),o};class Al extends I{constructor(){super(...arguments),a(this,"url"),a(this,"mode",0),a(this,"clickable",!0)}async open(){if(!this.url){console.warn("OpenURL: URL is not set, can't open.",this);return}this._validateUrl();let e=this.url;switch(!e.startsWith("mailto:")&&e.includes("@")&&(e="mailto:"+e),F()&&De("Open URL: "+e),this.mode){case 0:X.isSafari(),globalThis.open(e,"_blank");break;case 1:X.isSafari()&&X.isiOS()?globalThis.open(e,"_top"):globalThis.open(e,"_self");break;case 2:X.isSafari()?globalThis.open(e,"_top"):globalThis.open(e,"_new");break}}start(){this.gameObject.getComponentInParent(ji)||this.gameObject.addComponent(ji)}onPointerEnter(e){!e.used&&this.clickable&&this.context.input.setCursor("pointer")}onPointerExit(){this.clickable&&this.context.input.unsetCursor("pointer")}onPointerClick(e){var t;this.clickable&&!e.used&&(t=this.url)!=null&&t.length&&this.open()}_validateUrl(){this.url&&this.url.startsWith("www.")&&(F()&&console.warn("URL is not valid, adding https:// to the start of the URL",this.url),this.url="https://"+this.url)}}Zy([m()],Al.prototype,"url"),Zy([m()],Al.prototype,"mode"),Zy([m()],Al.prototype,"clickable");var lL=Object.defineProperty,Il=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&lL(e,t,o),o};class oo extends I{constructor(){super(...arguments),a(this,"side","none"),a(this,"controller",!0),a(this,"hands",!1),a(this,"controlVisibility",!0),a(this,"useGripSpace",!1),a(this,"resetTransformAfterXRSession",!0),a(this,"_startPosition",new S),a(this,"_startRotation",new V),a(this,"_startScale",new S)}get activeAndEnabled(){return!0}onEnterXR(e){this._startPosition.copy(this.gameObject.position),this._startRotation.copy(this.gameObject.quaternion),this._startScale.copy(this.gameObject.scale)}onUpdateXR(e){if(!this.enabled)return;const t=e.xr.getController(this.side);if(t){if(t.hand&&!this.hands){this.controlVisibility&&(this.gameObject.visible=!1);return}else if(!this.controller){this.controlVisibility&&(this.gameObject.visible=!1);return}this.controlVisibility&&(this.gameObject.visible=!0),this.useGripSpace||t.targetRayMode==="transient-pointer"?(this.gameObject.worldPosition=t.gripWorldPosition,this.gameObject.worldQuaternion=t.gripWorldQuaternion,this.gameObject.worldScale=q(t.xr.rigScale,t.xr.rigScale,t.xr.rigScale).multiply(this._startScale)):(this.gameObject.worldPosition=t.rayWorldPosition,this.gameObject.worldQuaternion=t.rayWorldQuaternion,this.gameObject.worldScale=q(t.xr.rigScale,t.xr.rigScale,t.xr.rigScale).multiply(this._startScale))}}onLeaveXR(e){this.resetTransformAfterXRSession&&(this.gameObject.position.copy(this._startPosition),this.gameObject.quaternion.copy(this._startRotation),this.gameObject.scale.copy(this._startScale))}}Il([m()],oo.prototype,"side"),Il([m()],oo.prototype,"controller"),Il([m()],oo.prototype,"hands"),Il([m()],oo.prototype,"controlVisibility"),Il([m()],oo.prototype,"useGripSpace"),Il([m()],oo.prototype,"resetTransformAfterXRSession");function FS(n,e){const t=n.xr.getFrame();if(!t)return console.warn("No XRFrame available"),!1;const s=t.session.enabledFeatures;if(s&&!s.some(r=>r==="camera-access"))return console.error(`No camera feed available - please request the 'camera-access' feature before starting WebXR or add the ARCameraBackground component to your scene.
|
|
1404
1407
|
|
|
1405
1408
|
Example to request camera-access in global scope:
|
|
1406
1409
|
NeedleXRSession.onSessionRequestStart(evt => {
|
|
1407
1410
|
evt.init.optionalFeatures = evt.init.optionalFeatures || [];
|
|
1408
1411
|
evt.init.optionalFeatures.push('camera-access');
|
|
1409
1412
|
});
|
|
1410
|
-
`),F()&&ic("No camera feed available - please request the 'camera-access' feature before starting WebXR or add the ARCameraBackground component to your scene"),!1;const o=t.getViewerPose(n.xr.getReferenceSpace());if(o)for(const r of o.views)if("camera"in r&&r.camera){let l=n.xr.getBinding();if(l||(l=new XRWebGLBinding(t.session,n.getContext())),l){let c=null;if("getCameraImage"in l){
|
|
1413
|
+
`),F()&&ic("No camera feed available - please request the 'camera-access' feature before starting WebXR or add the ARCameraBackground component to your scene"),!1;const o=t.getViewerPose(n.xr.getReferenceSpace());if(o)for(const r of o.views)if("camera"in r&&r.camera){let l=n.xr.getBinding();if(l||(l=new XRWebGLBinding(t.session,n.getContext())),l){let c=null;if("getCameraImage"in l){cL(n,e);const h=n.properties.get(e);if(h)return c=l.getCameraImage(r.camera),h.__webglTexture=c,!0;console.warn("No texture properties found for target texture")}}else console.error(r.camera,n.xr)}else console.error("NO CAMERA IN VIEW");else console.error(n.xr.getReferenceSpace(),t);return!1}const US=new WeakMap;function cL(n,e){const t=US.get(e)||new WeakSet;if(t.has(n))return;t.add(n),US.set(e,t),console.debug("Initialize texture for camera feed");const s=new Me,o=new Ns,r=new xi;r.add(new G(o,s));const l=new we;s.map=e,n.render(r,l)}function hL(n,e,t,s="image/webp",o){return Jy({context:n,width:e,height:t,mimeType:s,camera:o})}function Jy(n){var e,t;n||(n={});const{transparent:s=!1}=n;let{mimeType:o,context:r,width:l,height:c,camera:h}=n;if(!r&&(r=pe.Current,!r))return console.error("Can not save screenshot: No needle-engine context found or provided."),null;if(!h&&(h=r.mainCamera,!h))return console.error("No camera found"),null;const d=r.renderer,u=d.xr.enabled&&d.xr.isPresenting;if(u&&r.currentFrameEvent!=Oe.EarlyUpdate)return console.warn("Screenshot: defer to access XR frame"),new Promise(D=>{jn(z=>{const j=Jy(n);D(j)},Oe.EarlyUpdate,{once:!0})});const p=d.domElement,g=p.width,f=p.height;l||(l=g),c||(c=f);const y=l,v=c;let b=window.devicePixelRatio||1,_=1;r.devicePixelRatio==="auto"||r.devicePixelRatio==="manual"?_=1:_=r.devicePixelRatio/window.devicePixelRatio,b*=_,l/=b,c/=b,l=Math.floor(l),c=Math.floor(c),d.xr.isPresenting&&d.xr.getFrame();const w=d.xr.enabled;d.xr.enabled=!1,d.xr.isPresenting=!1,p.style.width=`${l}px`,p.style.height=`${c}px`;const x=d.getRenderTarget(),k=d.getClearColor(new oe),M=d.getClearAlpha(),T=r.scene.background,L="aspect"in h?h.aspect:null;try{const D=n.render_events!==!1,z=new Array;D&&(Wa(r.scene,Ui,z),z.forEach(B=>{var Q;if(B?.onBeforeRender(),B.isInstancingActive&&B.instances)for(let te=0;te<((Q=B.instances)==null?void 0:Q.length);te++){const ae=B.instances[te];Bn(ae.object,!0)}})),s&&(r.scene.background=null,d.setClearColor(0,0)),n.background&&(r.scene.background=null,d.setClearColor(n.background),n.background instanceof he&&d.setClearAlpha(n.background.a)),s&&d.setClearAlpha(0),d.setSize(l,c,!1),"cam"in h&&(h=h.threeCamera),h instanceof we&&(h.aspect=l/c,h.updateProjectionMatrix());const j="type"in n&&n.type==="texture";let H=null;j&&(H=new $s(l,c,{wrapS:Nv,wrapT:Nv,format:1023}),d.setRenderTarget(H));let K=p;if(u?(H&&console.error('Taking XR screenshots with { type: "texture" } is currently not supported.'),K=$h.compositeWithCameraImage({width:y,height:v,scene:r.scene,camera:h,renderer:d})):r.renderNow(h||null),h instanceof we&&L!=null&&(h.aspect=L,h.updateProjectionMatrix()),D&&z.forEach(B=>B.onAfterRender()),!o&&"download_filename"in n&&n.download_filename)switch((e=n.download_filename.split(".").pop())==null?void 0:e.toLowerCase()){case"png":o="image/png";break;case"jpg":case"jpeg":o="image/jpeg";break;case"webp":o="image/webp";break}if(s&&n.trim===!0){const B=dL(K);B&&(K=B)}if("type"in n){if(n.type==="texture")return H?(n.target&&(n.target.image=H?.texture.image,n.target.needsUpdate=!0),H.texture.offset.set(0,-1),H.texture.needsUpdate=!0,H.texture):(console.error("No target texture found"),null);if(n.type==="blob")return new Promise((B,Q)=>{K.toBlob(te=>{B(te)},o)});if(n.type==="share")return new Promise((B,Q)=>{K.toBlob(te=>{if(te&&"share"in navigator){let ae="file_type"in n&&n.file_type||o;o||(ae="image/png");const le=ae?.split("/")[1]||"png",ye=new File([te],"filename"in n?n.filename||`screenshot.${le}`:`screenshot.${le}`,{type:ae});return navigator.share({title:"title"in n?n.title:void 0,text:"text"in n?n.text:void 0,url:"url"in n?n.url:void 0,files:[ye]}).catch(He=>{console.warn("User cancelled share",He.message)}).finally(()=>{B({blob:te,shared:!0})})}return{blob:te,shared:!1}},o)})}const U=K.toDataURL(o);if("download_filename"in n&&n.download_filename){let B=n.download_filename;if(X.isMobileDevice()&&typeof window<"u"){const Q=B+"_screenshots",te=B.split("."),ae=(t=te.pop())==null?void 0:t.toLowerCase();let le=0;localStorage.getItem(Q)&&(le=parseInt(sessionStorage.getItem(Q)||"0")),le>0&&(B=`${te.join()}-${le}.${ae}`),le+=1,sessionStorage.setItem(Q,le.toString())}zS(U,B)}return U}finally{d.setRenderTarget(x),r.scene.background=T,d.setSize(g,f,!1),d.setClearColor(k,M),L!=null&&h instanceof we&&(h.aspect=L,h.updateProjectionMatrix()),d.xr.enabled=w,d.xr.isPresenting=u,u||r.updateSize(!0)}return null}function dL(n){if(!("document"in globalThis))return null;const e=document.createElement("canvas");e.width=n.width,e.height=n.height;const t=e.getContext("2d");if(!t)return null;t.drawImage(n,0,0);const s=e.width,o=e.height,r=t.getImageData(0,0,s,o).data;let l=o,c=s,h=0,d=0;for(let y=0;y<o;y++)for(let v=0;v<s;v++){const b=(y*s+v)*4;r[b+3]!==0&&(v<c&&(c=v),v>d&&(d=v),y<l&&(l=y),y>h&&(h=y))}const u=d-c+1,p=h-l+1,g=document.createElement("canvas"),f=g.getContext("2d");return f?(g.width=u,g.height=p,f.drawImage(e,c,l,u,p,0,0,u,p),g):null}let Vh=null;function zS(n,e){if(n){if(!n.startsWith("data:image")){console.error("Can not save image: Data url is not an image",n);return}Vh||(Vh=document.createElement("a")),Vh.href=n,Vh.download=e,Vh.click()}}var $h;(n=>{let e=null,t=null,s=null,o=null,r=null;function l(d){const{renderer:u,width:p,height:g}=d,f=u.xr.enabled,y=u.getRenderTarget(),v=u.autoClear,b=p,_=g,w=p/g;(!s||s.width!==b||s.height!==_)&&(s??(s=new $s(b,_,{colorSpace:Mn})),s.width=b,s.height=_,s.samples=4,s.texture.repeat.y=-1,s.texture.offset.y=1),(!r||r.width!==b||r.height!==_)&&(r=document.createElement("canvas"),r.width=b,r.height=_,r.style.position="fixed",r.style.top="0px",r.style.right="0px",r.style.width="300px",r.style.height=`${300/w}px`,r.style.zIndex="1000",r.style.pointerEvents="none",r.style.opacity="1.0",r.style.willChange="contents"),e||(e=h({defines:{DECODE_VIDEO_TEXTURE:!0}})),t||(t=h()),o||(o=new je),u.xr.updateCamera(d.camera),u.xr.enabled=!1,u.autoClear=!1,u.clear(),u.setSize(b,_),u.setRenderTarget(s),FS(d.renderer,o)||console.error("Could not update texture from XR frame");const x=P.findObjectOfType(Hh);return x?x.setTexture(o):(e.setTexture(o),u.render(e,d.camera)),u.clearDepth(),u.setSize(b,_),u.render(d.scene,d.camera),u.setRenderTarget(null),t.setTexture(s.texture),u.render(t,d.camera),r.getContext("2d",{alpha:!1}).drawImage(u.domElement,0,0,r.width,r.height),u.setRenderTarget(y),u.xr.enabled=f,u.autoClear=v,r}n.compositeWithCameraImage=l;const c=`
|
|
1411
1414
|
uniform sampler2D t2D;
|
|
1412
1415
|
varying vec2 vUv;
|
|
1413
1416
|
|
|
@@ -1426,7 +1429,7 @@ void main() {
|
|
|
1426
1429
|
#include <tonemapping_fragment>
|
|
1427
1430
|
#include <colorspace_fragment>
|
|
1428
1431
|
}
|
|
1429
|
-
`;function h(d){const u=d?.material||new Ws({name:"BackgroundMaterial",uniforms:zv.clone(Sd.background.uniforms),vertexShader:Sd.background.vertexShader,fragmentShader:c,defines:d?.defines,side:fo,depthTest:!1,depthWrite:!1,fog:!1});Object.defineProperty(u,"map",{get:function(){return this.threeTexture}});const p=new G(new Ns(2,2),u);return Td(p,!1),p.geometry.deleteAttribute("normal"),p.renderOrder=-1e6,p.setTexture=function(g){u.uniforms.t2D.value=g},p}n.makeFullscreenPlane=h})($h||($h={}));var
|
|
1432
|
+
`;function h(d){const u=d?.material||new Ws({name:"BackgroundMaterial",uniforms:zv.clone(Sd.background.uniforms),vertexShader:Sd.background.vertexShader,fragmentShader:c,defines:d?.defines,side:fo,depthTest:!1,depthWrite:!1,fog:!1});Object.defineProperty(u,"map",{get:function(){return this.threeTexture}});const p=new G(new Ns(2,2),u);return Td(p,!1),p.geometry.deleteAttribute("normal"),p.renderOrder=-1e6,p.setTexture=function(g){u.uniforms.t2D.value=g},p}n.makeFullscreenPlane=h})($h||($h={}));var uL=Object.defineProperty,pL=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&uL(e,t,o),o};const NS=C("debugarcamera");class Hh extends I{constructor(){super(...arguments),a(this,"backgroundTint",new he(1,1,1,1)),a(this,"backgroundPlane"),a(this,"threeTexture"),a(this,"forceTextureInitialization",function(){const e=new Me,t=new Ns,s=new xi;s.add(new G(t,e));const o=new we;return function(r,l){e.map=l,r.render(s,o),NS&&console.warn("Force texture initialization")}}()),a(this,"preRender",()=>{if(!(!this||!this.gameObject)&&this.context.renderer.xr.getFrame()){if(!this.threeTexture&&this.context.renderer&&(this.threeTexture=new je,this.forceTextureInitialization(this.context.renderer,this.threeTexture)),this.backgroundPlane===void 0){const e=this.backgroundTint;this.backgroundPlane=$h.makeFullscreenPlane({material:new Ws({name:"BackgroundMaterial",uniforms:{...zv.clone(Sd.background.uniforms),tint:{value:new fe(e.r,e.g,e.b,e.a)}},vertexShader:Sd.background.vertexShader,fragmentShader:mL,side:Pi,depthTest:!1,depthWrite:!1,fog:!1})})}this.backgroundPlane.parent!==this.scene&&this.scene.add(this.backgroundPlane),this.backgroundPlane.material instanceof Ws&&this.backgroundPlane.material.uniforms.tint.value.set(this.backgroundTint.r,this.backgroundTint.g,this.backgroundTint.b,this.backgroundTint.a),this.updateFromFrame()}})}onBeforeXR(e,t){e==="immersive-ar"&&(t.optionalFeatures=t.optionalFeatures||[],t.optionalFeatures.push("camera-access"),NS&&console.warn("Requesting camera-access"))}onEnterXR(e){e.xr.mode==="immersive-ar"&&(this.backgroundPlane&&(this.context.scene.add(this.backgroundPlane),this.backgroundPlane.visible=!1),this.backgroundPlane&&this.context.scene.add(this.backgroundPlane),this.context.pre_render_callbacks.push(this.preRender))}onLeaveXR(e){this.backgroundPlane&&this.backgroundPlane.removeFromParent();const t=this.context.pre_render_callbacks.indexOf(this.preRender);t>=0&&this.context.pre_render_callbacks.splice(t,1)}get background(){return this.backgroundPlane}onBeforeRender(e){this.updateFromFrame()}updateFromFrame(){var e;this.threeTexture&&((e=this.context.xr)==null?void 0:e.mode)==="immersive-ar"&&(FS(this.context.renderer,this.threeTexture),this.setTexture(this.threeTexture))}setTexture(e){this.backgroundPlane&&(this.threeTexture=e,this.backgroundPlane.setTexture(this.threeTexture),this.backgroundPlane.visible=!0)}}pL([m(he)],Hh.prototype,"backgroundTint");const mL=`
|
|
1430
1433
|
uniform sampler2D t2D;
|
|
1431
1434
|
uniform vec4 tint;
|
|
1432
1435
|
|
|
@@ -1445,17 +1448,17 @@ void main() {
|
|
|
1445
1448
|
#include <tonemapping_fragment>
|
|
1446
1449
|
#include <colorspace_fragment>
|
|
1447
1450
|
}
|
|
1448
|
-
`;var mL=Object.defineProperty,dr=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&mL(e,t,o),o};const WS=C("debugimagetracking"),ev=class Cv{constructor(e,t,s,o,r,l){a(this,"measuredSize"),a(this,"state"),a(this,"_position"),a(this,"_rotation"),a(this,"_trackingComponent"),a(this,"_trackedImage"),a(this,"_bitmap"),a(this,"_pose"),this._trackingComponent=e,this._trackedImage=t,this._bitmap=s,this.measuredSize=o,this.state=r,this._pose=l}get url(){return this._trackedImage.image??""}get widthInMeters(){return this._trackedImage.widthInMeters??void 0}get bitmap(){return this._bitmap}get model(){return this._trackedImage}getPosition(e){return this.ensureTransformData(),e.copy(this._position),e}getQuaternion(e){return this.ensureTransformData(),e.copy(this._rotation),e}applyToObject(e,t=void 0){this.ensureTransformData();const s=e.position.distanceToSquared(this._position)/.05+e.quaternion.angleTo(this._rotation)/.05;t&&(t*=Math.max(1,s)),t===void 0||t>=1?(e.position.copy(this._position),e.quaternion.copy(this._rotation)):(t=Math.max(0,Math.min(1,t)),e.position.lerp(this._position,t),e.quaternion.slerp(this._rotation,t))}ensureTransformData(){if(!this._position){this._position=Cv._positionBuffer.get(),this._rotation=Cv._rotationBuffer.get();const e=this._pose.transform,t=ne.active.convertSpace(e);this._position.copy(t?.position),this._rotation.copy(t?.quaternion)}}};a(ev,"_positionBuffer",new Oi(()=>new S,20)),a(ev,"_rotationBuffer",new Oi(()=>new V,20));let tv=ev;class ro{constructor(){a(this,"image"),a(this,"widthInMeters",.25),a(this,"object"),a(this,"createObjectInstance",!1),a(this,"imageDoesNotMove",!1),a(this,"hideWhenTrackingIsLost",!0)}}dr([m(URL)],ro.prototype,"image"),dr([m()],ro.prototype,"widthInMeters"),dr([m(ce)],ro.prototype,"object"),dr([m()],ro.prototype,"createObjectInstance"),dr([m()],ro.prototype,"imageDoesNotMove"),dr([m()],ro.prototype,"hideWhenTrackingIsLost");class gL{constructor(e,t,s){a(this,"filename"),a(this,"widthInMeters"),a(this,"imageData"),this.filename=e,this.imageData=t,this.widthInMeters=s}get extensionName(){return"image-tracking"}onAfterHierarchy(e,t){const s=X.getiOSVersion(),o=(s?parseInt(s.split(".")[0]):18)>=18?1:100;t.beginBlock('def Preliminary_ReferenceImage "AnchoringReferenceImage"'),t.appendLine("uniform asset image = @image_tracking/"+this.filename+"@"),t.appendLine("uniform double physicalWidth = "+(this.widthInMeters*o).toFixed(8)),t.closeBlock()}onBeforeBuildDocument(e){const t=P.findObjectOfType(Gh);!t||!t.trackedImages||t.trackedImages.length>1&&(F()&&be("USDZ: Only one tracked image is supported."),console.warn("USDZ: Only one tracked image is supported."))}onAfterSerialize(e){e.files["image_tracking/"+this.filename]=this.imageData}onExportObject(e,t,s){var o;const r=P.findObjectOfType(Gh);if(!(!r||!r.trackedImages)){for(const l of r.trackedImages)if(((o=l.object)==null?void 0:o.asset)===e){const c=P.findObjectOfType(gn);if(!c)continue;const{scale:h,target:d}=c.getARScaleAndTarget();let u=e;const p=new se;if(e!==d)for(;u.parent&&u.parent!==d;)u=u.parent,p.premultiply(u.matrix);const g=p.clone().invert();t.setMatrix(g.scale(new S(h,h,h)));break}}}}var pa;const iv=(pa=class extends I{constructor(){super(...arguments),a(this,"trackedImages"),a(this,"smooth",!0),a(this,"trackedImageIndexMap",new Map),a(this,"_supported",!0),a(this,"imageToObjectMap",new Map),a(this,"currentImages",[]),a(this,"webXRIncubationsWarning",`Image tracking is currently not supported on this device. On Chrome for Android, you can enable the <a target="_blank" href="#" onclick="() => console.log('I')">chrome://flags/#webxr-incubations</a> flag.`),a(this,"onImageTrackingUpdate",n=>{const e=ne.active;if(e)for(const t of n){const s=t.model,o=t.state==="tracked";if(!s.object)continue;let r=this.imageToObjectMap.get(s);if(r===void 0)r={object:null,frames:0,lastTrackingTime:Date.now()},this.imageToObjectMap.set(s,r),s.object.loadAssetAsync().then(l=>{if(s.createObjectInstance&&l&&(l=P.instantiate(l)),l){r.object=l;for(const c of l.getComponentsInChildren(Ui))c.setInstancingEnabled(!1);e.rig?(e.rig.gameObject.add(l),t.applyToObject(l),l.activeSelf||P.setActive(l,!0)):console.warn("XRImageTracking: missing XRRig")}});else{if(r.frames++,o&&(r.lastTrackingTime=Date.now()),s.imageDoesNotMove&&r.frames>10||!r.object)continue;e.rig&&(e.rig.gameObject.add(r.object),t.applyToObject(r.object,this.smooth?this.context.time.deltaTimeUnscaled*3:void 0),r.object.activeSelf||P.setActive(r.object,!0))}}})}get supported(){return this._supported}awake(){if(WS&&console.log(this),!!this.trackedImages){for(const n of this.trackedImages)if(n.image&&!pa._imageElements.has(n.image)){const e=n.image;pa._imageElements.set(e,null);const t=document.createElement("img");t.src=e,t.addEventListener("load",async()=>{const s=await createImageBitmap(t);pa._imageElements.set(e,s);const o=await E1(s);if(o){const r=await(await o.convertToBlob({type:"image/png"})).arrayBuffer(),l=P.findObjectOfType(gn);l&&this.trackedImages&&(l.extensions.push(new gL("marker.png",new Uint8Array(r),this.trackedImages[0].widthInMeters)),l.anchoringType="image")}})}}}onBeforeXR(n,e){var t;if(this.trackedImages){e.optionalFeatures=e.optionalFeatures||[],e.optionalFeatures.includes("image-tracking")||e.optionalFeatures.push("image-tracking"),e.trackedImages=[];for(const s of this.trackedImages)if((t=s.image)!=null&&t.length&&s.widthInMeters>0){const o=pa._imageElements.get(s.image);o&&(this.trackedImageIndexMap.set(e.trackedImages.length,s),e.trackedImages.push({image:o,widthInMeters:s.widthInMeters}))}}}onEnterXR(n){var e;if(this.trackedImages){for(const t of this.trackedImages)if((e=t.object)!=null&&e.asset){const s=t.object.asset;s.userData||(s.userData={});const o={visible:s.visible,parent:s.parent,matrix:s.matrix.clone()};s.userData["image-tracking"]=o}}for(const t of this.imageToObjectMap.values())t.frames=0}onLeaveXR(n){var e,t;if(!this.supported&&X.isAndroidDevice()&&be(this.webXRIncubationsWarning),this.trackedImages){for(const s of this.trackedImages)if((e=s.object)!=null&&e.asset){const o=s.object.asset;if(o.userData){const r=o.userData["image-tracking"];r&&(o.visible=r.visible,(t=r.parent)==null||t.add(o),o.matrix.copy(r.matrix),o.matrix.decompose(o.position,o.quaternion,o.scale)),delete o.userData["image-tracking"]}}}}onUpdateXR(n){var e;this.currentImages.length=0;const t=n.xr.frame;if(!t)return;if("getImageTrackingResults"in t){if(((e=n.xr.session.enabledFeatures)==null?void 0:e.includes("image-tracking"))===!1)return;if(t.session&&typeof t.getImageTrackingResults=="function"){const o=t.getImageTrackingResults();if(o.length>0){const r=this.context.renderer.xr.getReferenceSpace();if(r){for(const l of o){const c=l.trackingState,h=l.index,d=this.trackedImageIndexMap.get(h);if(d){const u=t.getPose(l.imageSpace,r),p=new tv(this,d,l.image,l.measuredSize,c,u);this.currentImages.push(p)}else WS&&console.warn("No tracked image for index",h)}if(this.currentImages.length>0)try{this.dispatchEvent(new CustomEvent("image-tracking",{detail:this.currentImages})),this.onImageTrackingUpdate(this.currentImages)}catch(l){console.error(l)}}}}}else{this.didPrintWarning||(this.didPrintWarning=!0,console.log(this.webXRIncubationsWarning)),this._supported=!1,be(this.webXRIncubationsWarning);return}const s=1e3;for(const[o,r]of this.imageToObjectMap){if(!r.object||!o||o.hideWhenTrackingIsLost===!1)continue;let l=!1;for(const c of this.currentImages)if(c.model===o){const h=Date.now()-r.lastTrackingTime;if(o.imageDoesNotMove||c.state==="tracked"||h<=s){l=!0;break}}l||P.setActive(r.object,!1)}}},a(pa,"_imageElements",new Map),pa);dr([m(ro)],iv.prototype,"trackedImages"),dr([m()],iv.prototype,"smooth");let Gh=iv;var fL=Object.defineProperty,Ll=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&fL(e,t,o),o};const ma=C("debugplanetracking");class ao extends I{constructor(){super(...arguments),a(this,"dataTemplate"),a(this,"occluder",!0),a(this,"initiateRoomCaptureIfNoData",!0),a(this,"usePlaneData",!0),a(this,"useMeshData",!0),a(this,"runInVR",!0),a(this,"bounds",new Si),a(this,"center",new S),a(this,"labelOffset",new S),a(this,"_dataId",1),a(this,"_allPlanes",new Map),a(this,"_allMeshes",new Map),a(this,"firstTimeNoPlanesDetected",-100),a(this,"makeOccluder",(e,t,s=!1)=>{if(t){if(t instanceof Array){for(const o of t)this.makeOccluder(e,o,s);return}!s&&!t.name.toLowerCase().includes("occlu")||(t.colorWrite=!1,t.depthTest=!0,t.depthWrite=!0,t.transparent=!1,t.polygonOffset=!0,t.polygonOffsetFactor=1,t.polygonOffsetUnits=.1,e.renderOrder=-1e3)}}),a(this,"_flipForwardMatrix",new se().makeRotationY(Math.PI)),a(this,"_verticesCache",new Map)}get trackedPlanes(){return this._allPlanes.values()}get trackedMeshes(){return this._allMeshes.values()}onBeforeXR(e,t){e==="immersive-vr"&&!this.runInVR||(t.optionalFeatures=t.optionalFeatures||[],this.usePlaneData&&!t.optionalFeatures.includes("plane-detection")&&t.optionalFeatures.push("plane-detection"),this.useMeshData&&!t.optionalFeatures.includes("mesh-detection")&&t.optionalFeatures.push("mesh-detection"))}onEnterXR(e){for(const t of this._allPlanes.keys())this.removeData(t,this._allPlanes);for(const t of this._allMeshes.keys())this.removeData(t,this._allMeshes)}onLeaveXR(e){for(const t of this._allPlanes.keys())this.removeData(t,this._allPlanes);for(const t of this._allMeshes.keys())this.removeData(t,this._allMeshes)}onUpdateXR(e){if(!this.runInVR&&e.xr.isVR)return;const t=e.xr.rig;if(!t){console.warn("No XR rig found, cannot parent tracked planes to it");return}const s=e.xr.frame;if(!this.context.renderer.xr.getReferenceSpace())return;const o=s.detectedPlanes,r=s.detectedMeshes,l=o!==void 0&&o.size>0,c=r!==void 0&&r.size>0;if(this.initiateRoomCaptureIfNoData&&(!l&&!c&&this.firstTimeNoPlanesDetected<-10&&(this.firstTimeNoPlanesDetected=Date.now()),(l||c)&&(this.firstTimeNoPlanesDetected=-1),this.firstTimeNoPlanesDetected>0&&Date.now()-this.firstTimeNoPlanesDetected>2500&&"initiateRoomCapture"in s.session&&(s.session.initiateRoomCapture(),this.firstTimeNoPlanesDetected=-1)),o!==void 0&&this.processFrameData(e.xr,t.gameObject,s,o,this._allPlanes),r!==void 0&&this.processFrameData(e.xr,t.gameObject,s,r,this._allMeshes),ma){const h=this.context.mainCameraComponent.gameObject.worldPosition;for(const d of this._allPlanes.values())!d.mesh||!d.mesh.visible||(this.bounds.makeEmpty(),d.mesh.traverse(u=>{u instanceof G&&this.bounds.expandByObject(u)}),this.bounds.getCenter(this.center),this.labelOffset.copy(h).sub(this.center).normalize().multiplyScalar(.1),$.DrawLabel(this.center.add(this.labelOffset),(d.xrData.semanticLabel||"plane").toUpperCase()+`
|
|
1449
|
-
`+d.xrData.lastChangedTime.toFixed(2),.02))}}removeData(e,t){const s=t.get(e);if(!s)return;t.delete(e),ma&&console.log("Plane no longer tracked, id="+s.id),s.mesh&&(s.mesh.removeFromParent(),s.mesh.traverse(r=>{const l=r.userData.normalsHelper;l?(l.dispose(),l.removeFromParent()):ma&&console.warn("No normals helper found for mesh",s.mesh)}),Ai(s.mesh,!0,!0));const o=new CustomEvent("plane-tracking",{detail:{type:"plane-removed",context:s}});this.dispatchEvent(o)}processFrameData(e,t,s,o,r){const l=this.context.renderer.xr.getReferenceSpace();if(l){for(const c of r.keys())o.has(c)||this.removeData(c,r);for(const c of o){const h="planeSpace"in c?c.planeSpace:"meshSpace"in c?c.meshSpace:void 0;if(!h)continue;const d=s.getPose(h,l);let u;if(r.has(c)){const p=r.get(c);if(u=p.mesh,p.timestamp<c.lastChangedTime){if(p.timestamp=c.lastChangedTime,p.mesh){const f=this.createGeometry(c);if(p.mesh instanceof G)p.mesh.geometry.dispose(),p.mesh.geometry=f,this.makeOccluder(p.mesh,p.mesh.material);else if(p.mesh instanceof mo)for(const y of p.mesh.children)y instanceof G&&(y.geometry.dispose(),y.geometry=f,this.makeOccluder(y,y.material));if(p.collider){const y=p.mesh;p.collider.sharedMesh=y,p.collider.convex=this.checkIfContextShouldBeConvex(y,p.xrData),p.collider.onDisable(),p.collider.onEnable()}ma&&(console.log("Plane updated, id="+p.id,p),p.mesh.traverse(y=>{if(!(y instanceof G))return;const v=y.userData.normalsHelper;v&&v.update()}))}const g=new CustomEvent("plane-tracking",{detail:{type:"plane-updated",context:p}});this.dispatchEvent(g)}}else{if(!this.dataTemplate){const p=new G;ma?p.material=new VP:this.occluder?(p.material=new Me,this.makeOccluder(p,p.material,!0)):p.material=new Me({wireframe:!0,opacity:.5,transparent:!0,color:3355443}),this.dataTemplate=new ce("","",p)}if(!this.dataTemplate.asset)this.dataTemplate.loadAssetAsync();else{const p=P.instantiate(this.dataTemplate.asset);if(p.name="xr-tracked-plane",u=p,mg(p,!1),p instanceof G)Te(p.geometry),p.geometry=this.createGeometry(c),this.makeOccluder(p,p.material,this.occluder&&!this.dataTemplate);else if(p instanceof mo)for(const y of p.children)y instanceof G&&(Te(y.geometry),y.geometry=this.createGeometry(c),this.makeOccluder(y,y.material,this.occluder&&!this.dataTemplate));const g=p.getComponent(Fo);if(g){const y=p;g.sharedMesh=y,g.convex=this.checkIfContextShouldBeConvex(y,c),g.onDisable(),g.onEnable()}p.matrixAutoUpdate=!1,p.matrixWorldNeedsUpdate=!0,t.add(p);const f={id:this._dataId++,xrData:c,timestamp:c.lastChangedTime,mesh:p,collider:g};r.set(c,f),ma&&console.log("New plane detected, id="+f.id,f,{hasCollider:!!g,isGroup:p instanceof mo});try{const y=new CustomEvent("plane-tracking",{detail:{type:"plane-added",context:f}});this.dispatchEvent(y)}catch(y){console.error(y)}}}u&&(d?(u.visible=!0,u.matrix.fromArray(d.transform.matrix),u.matrix.premultiply(this._flipForwardMatrix)):u.visible=!1,ma&&u.traverse(p=>{if(p instanceof G)if(p.userData.normalsHelper)p.userData.normalsHelper.update();else{const g=new mO(p,.05,255);g.layers.disableAll(),g.layers.set(2),this.context.scene.add(g),p.userData.normalsHelper=g}}))}}}checkIfContextShouldBeConvex(e,t){if(!e)return!0;if(e){const s=new Si;s.expandByObject(e);const o=new S;s.getSize(o);let r=!0;return o.x>2&&o.y>2&&o.z>1.5&&(r=!1),r&&"semanticLabel"in t&&t.semanticLabel==="wall"&&(r=!0),r}return!0}createGeometry(e){return"polygon"in e?this.createPlaneGeometry(e.polygon):"vertices"in e&&"indices"in e?this.createMeshGeometry(e.vertices,e.indices):new Vs}createMeshGeometry(e,t){const s=e.toString()+"_"+t.toString();if(this._verticesCache.has(s))return this._verticesCache.get(s);const o=new Vs;o.setIndex(new _t(t,1)),o.setAttribute("position",new _t(e,3));const r=Array();for(let l=0;l<e.length;l+=3)r.push(e[l],e[l+2]);return o.setAttribute("uv",new _t(e,3)),o.computeVertexNormals(),this._verticesCache.set(s,o),o}createPlaneGeometry(e){const t=new Vs,s=[],o=[];e.forEach(g=>{s.push(g.x,g.y,g.z),o.push(g.x,g.z)});const r=new S(s[0],s[1],s[2]),l=new S(s[3],s[4],s[5]),c=new S(s[6],s[7],s[8]),h=new S,d=new S;h.subVectors(l,r),d.subVectors(c,r),h.cross(d),h.normalize();const u=[];for(let g=0;g<s.length/3;g++)u.push(h.x,h.y,h.z);const p=[];for(let g=2;g<e.length;++g)p.push(0,g-1,g);return t.setAttribute("position",new _t(new Float32Array(s),3)),t.setAttribute("uv",new _t(new Float32Array(o),2)),t.setAttribute("normal",new _t(new Float32Array(u),3)),t.setIndex(p),t.computeBoundingBox(),t.computeBoundingSphere(),t}}Ll([m(ce)],ao.prototype,"dataTemplate"),Ll([m()],ao.prototype,"occluder"),Ll([m()],ao.prototype,"initiateRoomCaptureIfNoData"),Ll([m()],ao.prototype,"usePlaneData"),Ll([m()],ao.prototype,"useMeshData"),Ll([m()],ao.prototype,"runInVR");var yL=Object.defineProperty,vL=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&yL(e,t,o),o};const VS=C("debugwebxr");class um extends I{constructor(){super(...arguments),a(this,"priority",0),a(this,"_startScale")}get isActive(){return this.activeAndEnabled&&this.gameObject.visible}setAsActiveXRRig(){var e;(e=ne.active)==null||e.setRigActive(this)}setPriority(e){this.priority=e}awake(){if(VS){const e=new E;e.position.y+=.5,this.gameObject.add(e);const t=e.addNewComponent(ea);t&&(t.isGizmo=!1);const s=new Ci(.5);this.gameObject.add(s)}}isXRRig(){return!0}supportsXR(e){return!0}onEnterXR(e){this._startScale=this.gameObject.scale.clone(),e.xr.addRig(this),VS&&console.log("WebXR: add Rig",this.name,this.priority)}onLeaveXR(e){e.xr.removeRig(this),this._startScale&&this.gameObject&&this.gameObject.scale.copy(this._startScale)}}vL([m()],um.prototype,"priority");class bL extends I{constructor(){super(...arguments),a(this,"toggleKey","KeyP")}update(){this.context.input.isKeyDown(this.toggleKey)&&this.context.domElement.classList.toggle("presentation-mode")}}R.add("AlignmentConstraint",Tc),R.add("Animation",Ft),R.add("Animator",Rt),R.add("AudioListener",zn),R.add("AudioSource",ns),R.add("Avatar_Brain_LookAt",Uc),R.add("Avatar_MouthShapes",zc),R.add("Avatar_MustacheShake",Xf),R.add("AvatarBlink_Simple",zr),R.add("AvatarEyeLook_Rotation",Kf),R.add("AxesHelper",Ja),R.add("BasicIKConstraint",Jf),R.add("BoxHelperComponent",Bo),R.add("Camera",ci),R.add("CharacterController",Nr),R.add("CharacterControllerInput",$n),R.add("Collider",ui),R.add("SphereCollider",el),R.add("BoxCollider",Nu),R.add("MeshCollider",Fo),R.add("CapsuleCollider",Wn),R.add("ContactShadows",Vc),R.add("LogStats",i0),R.add("DeleteBox",Wu),R.add("Deletable",n0),R.add("DeviceFlag",Vu),R.add("DragControls",Hr),R.add("DropListener",Hn),R.add("Duplicatable",h0),R.add("EventListEvent",Ru),R.add("EventTrigger",qu),R.add("GltfExportBox",S0),R.add("GltfExport",P0),R.add("VariantAction",j0),R.add("ChangeTransformOnClick",Xr),R.add("ChangeMaterialOnClick",B0),R.add("SetActiveOnClick",F0),R.add("HideOnStart",pp),R.add("EmphasizeOnClick",ul),R.add("PlayAudioOnClick",Vo),R.add("PlayAnimationOnClick",Jc),R.add("PreliminaryAction",pl),R.add("PreliminaryTrigger",eh),R.add("VisibilityAction",th),R.add("TapGestureTrigger",N0),R.add("USDZExporter",gn),R.add("Fog",xl),R.add("BoxGizmo",ea),R.add("GridHelper",Sl),R.add("GroundProjectedEnv",en),R.add("UsageMarker",$c),R.add("Interactable",s0),R.add("FixedJoint",fy),R.add("HingeJoint",dh),R.add("Light",yi),R.add("LODGroup",ph),R.add("LookAtConstraint",Fr),R.add("NeedleMenu",un),R.add("NestedGltf",kp),R.add("Networking",_y),R.add("OffsetConstraint",ta),R.add("CameraTargetReachedEvent",Fc),R.add("OrbitControls",_e),R.add("ParticleSystemRenderer",ds),R.add("ParticleSystem",yh),R.add("PlayerColor",Nl),R.add("Antialiasing",bh),R.add("BloomEffect",Np),R.add("ChromaticAberration",_h),R.add("ColorAdjustments",or),R.add("DepthOfField",As),R.add("EffectWrapper",xh),R.add("PixelationEffect",Sh),R.add("ScreenSpaceAmbientOcclusion",to),R.add("ScreenSpaceAmbientOcclusionN8",Is),R.add("SharpeningEffect",Ph),R.add("TiltShiftEffect",yn),R.add("ToneMappingEffect",nr),R.add("Vignette",la),R.add("Volume",Ml),R.add("ReflectionProbe",qc),R.add("Renderer",Ui),R.add("MeshRenderer",Qc),R.add("SkinnedMeshRenderer",x0),R.add("Rigidbody",dt),R.add("SceneSwitcher",Ze),R.add("ScreenCapture",ar),R.add("ShadowCatcher",Rh),R.add("RemoteSkybox",qp),R.add("SmoothFollow",Yp),R.add("SpatialTriggerReceiver",vn),R.add("SpatialTrigger",Kp),R.add("SpectatorCamera",Zp),R.add("SpriteRenderer",gi),R.add("SyncedCamera",Wy),R.add("SyncedRoom",Ls),R.add("SyncedTransform",sn),R.add("TestRunner",Hy),R.add("TestSimulateUserData",Gy),R.add("PlayableDirector",Tl),R.add("SignalReceiver",Dh),R.add("AnimationTrackHandler",im),R.add("AudioTrackHandler",sm),R.add("SignalTrackHandler",Fh),R.add("ControlTrackHandler",nm),R.add("TransformGizmo",da),R.add("BaseUIComponent",ps),R.add("UIRootComponent",oh),R.add("Button",no),R.add("Canvas",_l),R.add("CanvasGroup",Ko),R.add("EventSystem",ii),R.add("Graphic",lh),R.add("MaskableGraphic",ch),R.add("Image",El),R.add("RawImage",am),R.add("InputField",Yy),R.add("VerticalLayoutGroup",oy),R.add("HorizontalLayoutGroup",ry),R.add("GridLayoutGroup",ay),R.add("Outline",bl),R.add("ObjectRaycaster",ji),R.add("GraphicRaycaster",Au),R.add("SpatialGrabRaycaster",Dc),R.add("RectTransform",Ts),R.add("SpatialHtml",Nh),R.add("Text",Nt),R.add("EnvironmentScene",cm),R.add("LookAt",Ky),R.add("OpenURL",Al),R.add("VideoPlayer",yt),R.add("Voip",Do),R.add("Avatar",Go),R.add("XRControllerFollow",oo),R.add("XRControllerModel",pn),R.add("XRControllerMovement",Ni),R.add("TeleportTarget",_p),R.add("WebARCameraBackground",Hh),R.add("WebARSessionRoot",$o),R.add("WebXR",wp),R.add("AvatarMarker",hi),R.add("WebXRImageTracking",Gh),R.add("WebXRPlaneTracking",ao),R.add("XRRig",um),R.add("XRFlag",os),R.add("PlayerSync",X0),R.add("PlayerState",Ms),R.add("PresentationMode",bL);const qh=wt,_L=C("debugtypestore");_L&&console.log(R);function wL(n,e){const t=rw(n,e);return t!==void 0?t:null}const xL=new XM,sv=Symbol("deserialize-queue");async function SL(n,e,t,s=null,o){if(!t){console.debug("Can not create component instances: gltf is null");return}let r=s;typeof r=="number"&&(r=new jt(s));const l=e.indexOf("?");e=l===-1?e:e.substring(0,l);const c=new df(t.scene);c.gltfId=e,c.context=n,c.gltf=t,c.nodeToObject=o?.nodeToObjectMap,c.implementationInformation=xL;let h=n[sv];if(h||(h=n[sv]=[]),t.scenes)for(const d of t.scenes)await rv(c,d,h);if(t.children)for(const d of t.children)await rv(c,d,h);n.new_scripts_pre_setup_callbacks.push(()=>{const d=n[sv];if(d){for(const u of d)CL(u,c);d.length=0}if(r){const u={},p=[];ov(t,r,u,p);for(const g of t.scenes)ov(g,r,u,p);for(const g of p)g.resolveGuids(u)}})}const nv=Symbol("original-component-name"),jl=new Map;function ov(n,e,t,s){if(e===null||!n)return;const o=n.guid,r=n.guid;r!=null&&r.length&&(jl.has(r)||(qh&&console.log('Creating InstanceIdProvider with key "'+r+'" for object '+n.name),jl.set(r,new jt(r))));const l=r&&jl.get(r)||e;if(n.guid=l.generateUUID(),o&&o!=="invalid"&&(t[o]=n.guid),n&&n.userData&&n.userData.components)for(const c of n.userData.components){if(c===null)continue;const h=c.guid;h?jl.has(h)||(qh&&console.log('Creating InstanceIdProvider with key "'+h+'" for component '+c[nv]),jl.set(h,new jt(h))):qh&&console.warn("Can not create IdProvider: component "+c[nv]+" has no guid",c.guid);const d=jl.get(h)||e,u=c.guid;c.guid=d.generateUUID(),u&&u!=="invalid"&&(t[u]=c.guid),c.resolveGuids&&s.push(c)}if(n.children)for(const c of n.children)ov(c,e,t,s)}const Xh=[];async function rv(n,e,t,s){var o,r,l,c,h;if(!e)return;const d=e.userData;if(d){const u=d.builtin_components;if(u&&u.length>0)for(const p of u)try{if(p===null)continue;const g=R.get(p.name);if(g!=null){const f=new g;f.sourceId=n.gltfId,Na(f,p,n.implementationInformation),f.context=n.context,"guid"in p&&(f[oc]=p.guid),f[nv]=p.name,Mr(e,f,!1),t.push({instance:f,compData:p,obj:e}),f.isCamera&&n.context&&n.context.mainCamera===null&&f.tag==="MainCamera"&&n.context.setCurrentCamera(f),((l=(r=(o=n.context)==null?void 0:o.physics)==null?void 0:r.engine)==null?void 0:l.isInitialized)===!1&&(f.isCollider||f.isRigidbody)&&((h=(c=n.context)==null?void 0:c.physics.engine)==null||h.initialize())}else qh&&console.debug("unknown component: "+p.name),Xh.includes(p.name)||Xh.push(p.name)}catch(g){console.error(p.name+" - "+g.message,g)}if(Xh.length>0){const p=Xh.join(", ");console.warn("unknown components: "+p),Xh.length=0,Xt()&&De(`<strong>Unknown components in scene</strong>:
|
|
1451
|
+
`;var gL=Object.defineProperty,dr=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&gL(e,t,o),o};const WS=C("debugimagetracking"),ev=class Cv{constructor(e,t,s,o,r,l){a(this,"measuredSize"),a(this,"state"),a(this,"_position"),a(this,"_rotation"),a(this,"_trackingComponent"),a(this,"_trackedImage"),a(this,"_bitmap"),a(this,"_pose"),this._trackingComponent=e,this._trackedImage=t,this._bitmap=s,this.measuredSize=o,this.state=r,this._pose=l}get url(){return this._trackedImage.image??""}get widthInMeters(){return this._trackedImage.widthInMeters??void 0}get bitmap(){return this._bitmap}get model(){return this._trackedImage}getPosition(e){return this.ensureTransformData(),e.copy(this._position),e}getQuaternion(e){return this.ensureTransformData(),e.copy(this._rotation),e}applyToObject(e,t=void 0){this.ensureTransformData();const s=e.position.distanceToSquared(this._position)/.05+e.quaternion.angleTo(this._rotation)/.05;t&&(t*=Math.max(1,s)),t===void 0||t>=1?(e.position.copy(this._position),e.quaternion.copy(this._rotation)):(t=Math.max(0,Math.min(1,t)),e.position.lerp(this._position,t),e.quaternion.slerp(this._rotation,t))}ensureTransformData(){if(!this._position){this._position=Cv._positionBuffer.get(),this._rotation=Cv._rotationBuffer.get();const e=this._pose.transform,t=ne.active.convertSpace(e);this._position.copy(t?.position),this._rotation.copy(t?.quaternion)}}};a(ev,"_positionBuffer",new Oi(()=>new S,20)),a(ev,"_rotationBuffer",new Oi(()=>new V,20));let tv=ev;class ro{constructor(){a(this,"image"),a(this,"widthInMeters",.25),a(this,"object"),a(this,"createObjectInstance",!1),a(this,"imageDoesNotMove",!1),a(this,"hideWhenTrackingIsLost",!0)}}dr([m(URL)],ro.prototype,"image"),dr([m()],ro.prototype,"widthInMeters"),dr([m(ce)],ro.prototype,"object"),dr([m()],ro.prototype,"createObjectInstance"),dr([m()],ro.prototype,"imageDoesNotMove"),dr([m()],ro.prototype,"hideWhenTrackingIsLost");class fL{constructor(e,t,s){a(this,"filename"),a(this,"widthInMeters"),a(this,"imageData"),this.filename=e,this.imageData=t,this.widthInMeters=s}get extensionName(){return"image-tracking"}onAfterHierarchy(e,t){const s=X.getiOSVersion(),o=(s?parseInt(s.split(".")[0]):18)>=18?1:100;t.beginBlock('def Preliminary_ReferenceImage "AnchoringReferenceImage"'),t.appendLine("uniform asset image = @image_tracking/"+this.filename+"@"),t.appendLine("uniform double physicalWidth = "+(this.widthInMeters*o).toFixed(8)),t.closeBlock()}onBeforeBuildDocument(e){const t=P.findObjectOfType(Gh);!t||!t.trackedImages||t.trackedImages.length>1&&(F()&&be("USDZ: Only one tracked image is supported."),console.warn("USDZ: Only one tracked image is supported."))}onAfterSerialize(e){e.files["image_tracking/"+this.filename]=this.imageData}onExportObject(e,t,s){var o;const r=P.findObjectOfType(Gh);if(!(!r||!r.trackedImages)){for(const l of r.trackedImages)if(((o=l.object)==null?void 0:o.asset)===e){const c=P.findObjectOfType(gn);if(!c)continue;const{scale:h,target:d}=c.getARScaleAndTarget();let u=e;const p=new se;if(e!==d)for(;u.parent&&u.parent!==d;)u=u.parent,p.premultiply(u.matrix);const g=p.clone().invert();t.setMatrix(g.scale(new S(h,h,h)));break}}}}var pa;const iv=(pa=class extends I{constructor(){super(...arguments),a(this,"trackedImages"),a(this,"smooth",!0),a(this,"trackedImageIndexMap",new Map),a(this,"_supported",!0),a(this,"imageToObjectMap",new Map),a(this,"currentImages",[]),a(this,"webXRIncubationsWarning",`Image tracking is currently not supported on this device. On Chrome for Android, you can enable the <a target="_blank" href="#" onclick="() => console.log('I')">chrome://flags/#webxr-incubations</a> flag.`),a(this,"onImageTrackingUpdate",n=>{const e=ne.active;if(e)for(const t of n){const s=t.model,o=t.state==="tracked";if(!s.object)continue;let r=this.imageToObjectMap.get(s);if(r===void 0)r={object:null,frames:0,lastTrackingTime:Date.now()},this.imageToObjectMap.set(s,r),s.object.loadAssetAsync().then(l=>{if(s.createObjectInstance&&l&&(l=P.instantiate(l)),l){r.object=l;for(const c of l.getComponentsInChildren(Ui))c.setInstancingEnabled(!1);e.rig?(e.rig.gameObject.add(l),t.applyToObject(l),l.activeSelf||P.setActive(l,!0)):console.warn("XRImageTracking: missing XRRig")}});else{if(r.frames++,o&&(r.lastTrackingTime=Date.now()),s.imageDoesNotMove&&r.frames>10||!r.object)continue;e.rig&&(e.rig.gameObject.add(r.object),t.applyToObject(r.object,this.smooth?this.context.time.deltaTimeUnscaled*3:void 0),r.object.activeSelf||P.setActive(r.object,!0))}}})}get supported(){return this._supported}awake(){if(WS&&console.log(this),!!this.trackedImages){for(const n of this.trackedImages)if(n.image&&!pa._imageElements.has(n.image)){const e=n.image;pa._imageElements.set(e,null);const t=document.createElement("img");t.src=e,t.addEventListener("load",async()=>{const s=await createImageBitmap(t);pa._imageElements.set(e,s);const o=await E1(s);if(o){const r=await(await o.convertToBlob({type:"image/png"})).arrayBuffer(),l=P.findObjectOfType(gn);l&&this.trackedImages&&(l.extensions.push(new fL("marker.png",new Uint8Array(r),this.trackedImages[0].widthInMeters)),l.anchoringType="image")}})}}}onBeforeXR(n,e){var t;if(this.trackedImages){e.optionalFeatures=e.optionalFeatures||[],e.optionalFeatures.includes("image-tracking")||e.optionalFeatures.push("image-tracking"),e.trackedImages=[];for(const s of this.trackedImages)if((t=s.image)!=null&&t.length&&s.widthInMeters>0){const o=pa._imageElements.get(s.image);o&&(this.trackedImageIndexMap.set(e.trackedImages.length,s),e.trackedImages.push({image:o,widthInMeters:s.widthInMeters}))}}}onEnterXR(n){var e;if(this.trackedImages){for(const t of this.trackedImages)if((e=t.object)!=null&&e.asset){const s=t.object.asset;s.userData||(s.userData={});const o={visible:s.visible,parent:s.parent,matrix:s.matrix.clone()};s.userData["image-tracking"]=o}}for(const t of this.imageToObjectMap.values())t.frames=0}onLeaveXR(n){var e,t;if(!this.supported&&X.isAndroidDevice()&&be(this.webXRIncubationsWarning),this.trackedImages){for(const s of this.trackedImages)if((e=s.object)!=null&&e.asset){const o=s.object.asset;if(o.userData){const r=o.userData["image-tracking"];r&&(o.visible=r.visible,(t=r.parent)==null||t.add(o),o.matrix.copy(r.matrix),o.matrix.decompose(o.position,o.quaternion,o.scale)),delete o.userData["image-tracking"]}}}}onUpdateXR(n){var e;this.currentImages.length=0;const t=n.xr.frame;if(!t)return;if("getImageTrackingResults"in t){if(((e=n.xr.session.enabledFeatures)==null?void 0:e.includes("image-tracking"))===!1)return;if(t.session&&typeof t.getImageTrackingResults=="function"){const o=t.getImageTrackingResults();if(o.length>0){const r=this.context.renderer.xr.getReferenceSpace();if(r){for(const l of o){const c=l.trackingState,h=l.index,d=this.trackedImageIndexMap.get(h);if(d){const u=t.getPose(l.imageSpace,r),p=new tv(this,d,l.image,l.measuredSize,c,u);this.currentImages.push(p)}else WS&&console.warn("No tracked image for index",h)}if(this.currentImages.length>0)try{this.dispatchEvent(new CustomEvent("image-tracking",{detail:this.currentImages})),this.onImageTrackingUpdate(this.currentImages)}catch(l){console.error(l)}}}}}else{this.didPrintWarning||(this.didPrintWarning=!0,console.log(this.webXRIncubationsWarning)),this._supported=!1,be(this.webXRIncubationsWarning);return}const s=1e3;for(const[o,r]of this.imageToObjectMap){if(!r.object||!o||o.hideWhenTrackingIsLost===!1)continue;let l=!1;for(const c of this.currentImages)if(c.model===o){const h=Date.now()-r.lastTrackingTime;if(o.imageDoesNotMove||c.state==="tracked"||h<=s){l=!0;break}}l||P.setActive(r.object,!1)}}},a(pa,"_imageElements",new Map),pa);dr([m(ro)],iv.prototype,"trackedImages"),dr([m()],iv.prototype,"smooth");let Gh=iv;var yL=Object.defineProperty,Ll=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&yL(e,t,o),o};const ma=C("debugplanetracking");class ao extends I{constructor(){super(...arguments),a(this,"dataTemplate"),a(this,"occluder",!0),a(this,"initiateRoomCaptureIfNoData",!0),a(this,"usePlaneData",!0),a(this,"useMeshData",!0),a(this,"runInVR",!0),a(this,"bounds",new Si),a(this,"center",new S),a(this,"labelOffset",new S),a(this,"_dataId",1),a(this,"_allPlanes",new Map),a(this,"_allMeshes",new Map),a(this,"firstTimeNoPlanesDetected",-100),a(this,"makeOccluder",(e,t,s=!1)=>{if(t){if(t instanceof Array){for(const o of t)this.makeOccluder(e,o,s);return}!s&&!t.name.toLowerCase().includes("occlu")||(t.colorWrite=!1,t.depthTest=!0,t.depthWrite=!0,t.transparent=!1,t.polygonOffset=!0,t.polygonOffsetFactor=1,t.polygonOffsetUnits=.1,e.renderOrder=-1e3)}}),a(this,"_flipForwardMatrix",new se().makeRotationY(Math.PI)),a(this,"_verticesCache",new Map)}get trackedPlanes(){return this._allPlanes.values()}get trackedMeshes(){return this._allMeshes.values()}onBeforeXR(e,t){e==="immersive-vr"&&!this.runInVR||(t.optionalFeatures=t.optionalFeatures||[],this.usePlaneData&&!t.optionalFeatures.includes("plane-detection")&&t.optionalFeatures.push("plane-detection"),this.useMeshData&&!t.optionalFeatures.includes("mesh-detection")&&t.optionalFeatures.push("mesh-detection"))}onEnterXR(e){for(const t of this._allPlanes.keys())this.removeData(t,this._allPlanes);for(const t of this._allMeshes.keys())this.removeData(t,this._allMeshes)}onLeaveXR(e){for(const t of this._allPlanes.keys())this.removeData(t,this._allPlanes);for(const t of this._allMeshes.keys())this.removeData(t,this._allMeshes)}onUpdateXR(e){if(!this.runInVR&&e.xr.isVR)return;const t=e.xr.rig;if(!t){console.warn("No XR rig found, cannot parent tracked planes to it");return}const s=e.xr.frame;if(!this.context.renderer.xr.getReferenceSpace())return;const o=s.detectedPlanes,r=s.detectedMeshes,l=o!==void 0&&o.size>0,c=r!==void 0&&r.size>0;if(this.initiateRoomCaptureIfNoData&&(!l&&!c&&this.firstTimeNoPlanesDetected<-10&&(this.firstTimeNoPlanesDetected=Date.now()),(l||c)&&(this.firstTimeNoPlanesDetected=-1),this.firstTimeNoPlanesDetected>0&&Date.now()-this.firstTimeNoPlanesDetected>2500&&"initiateRoomCapture"in s.session&&(s.session.initiateRoomCapture(),this.firstTimeNoPlanesDetected=-1)),o!==void 0&&this.processFrameData(e.xr,t.gameObject,s,o,this._allPlanes),r!==void 0&&this.processFrameData(e.xr,t.gameObject,s,r,this._allMeshes),ma){const h=this.context.mainCameraComponent.gameObject.worldPosition;for(const d of this._allPlanes.values())!d.mesh||!d.mesh.visible||(this.bounds.makeEmpty(),d.mesh.traverse(u=>{u instanceof G&&this.bounds.expandByObject(u)}),this.bounds.getCenter(this.center),this.labelOffset.copy(h).sub(this.center).normalize().multiplyScalar(.1),$.DrawLabel(this.center.add(this.labelOffset),(d.xrData.semanticLabel||"plane").toUpperCase()+`
|
|
1452
|
+
`+d.xrData.lastChangedTime.toFixed(2),.02))}}removeData(e,t){const s=t.get(e);if(!s)return;t.delete(e),ma&&console.log("Plane no longer tracked, id="+s.id),s.mesh&&(s.mesh.removeFromParent(),s.mesh.traverse(r=>{const l=r.userData.normalsHelper;l?(l.dispose(),l.removeFromParent()):ma&&console.warn("No normals helper found for mesh",s.mesh)}),Ai(s.mesh,!0,!0));const o=new CustomEvent("plane-tracking",{detail:{type:"plane-removed",context:s}});this.dispatchEvent(o)}processFrameData(e,t,s,o,r){const l=this.context.renderer.xr.getReferenceSpace();if(l){for(const c of r.keys())o.has(c)||this.removeData(c,r);for(const c of o){const h="planeSpace"in c?c.planeSpace:"meshSpace"in c?c.meshSpace:void 0;if(!h)continue;const d=s.getPose(h,l);let u;if(r.has(c)){const p=r.get(c);if(u=p.mesh,p.timestamp<c.lastChangedTime){if(p.timestamp=c.lastChangedTime,p.mesh){const f=this.createGeometry(c);if(p.mesh instanceof G)p.mesh.geometry.dispose(),p.mesh.geometry=f,this.makeOccluder(p.mesh,p.mesh.material);else if(p.mesh instanceof mo)for(const y of p.mesh.children)y instanceof G&&(y.geometry.dispose(),y.geometry=f,this.makeOccluder(y,y.material));if(p.collider){const y=p.mesh;p.collider.sharedMesh=y,p.collider.convex=this.checkIfContextShouldBeConvex(y,p.xrData),p.collider.onDisable(),p.collider.onEnable()}ma&&(console.log("Plane updated, id="+p.id,p),p.mesh.traverse(y=>{if(!(y instanceof G))return;const v=y.userData.normalsHelper;v&&v.update()}))}const g=new CustomEvent("plane-tracking",{detail:{type:"plane-updated",context:p}});this.dispatchEvent(g)}}else{if(!this.dataTemplate){const p=new G;ma?p.material=new VP:this.occluder?(p.material=new Me,this.makeOccluder(p,p.material,!0)):p.material=new Me({wireframe:!0,opacity:.5,transparent:!0,color:3355443}),this.dataTemplate=new ce("","",p)}if(!this.dataTemplate.asset)this.dataTemplate.loadAssetAsync();else{const p=P.instantiate(this.dataTemplate.asset);if(p.name="xr-tracked-plane",u=p,mg(p,!1),p instanceof G)Te(p.geometry),p.geometry=this.createGeometry(c),this.makeOccluder(p,p.material,this.occluder&&!this.dataTemplate);else if(p instanceof mo)for(const y of p.children)y instanceof G&&(Te(y.geometry),y.geometry=this.createGeometry(c),this.makeOccluder(y,y.material,this.occluder&&!this.dataTemplate));const g=p.getComponent(Fo);if(g){const y=p;g.sharedMesh=y,g.convex=this.checkIfContextShouldBeConvex(y,c),g.onDisable(),g.onEnable()}p.matrixAutoUpdate=!1,p.matrixWorldNeedsUpdate=!0,t.add(p);const f={id:this._dataId++,xrData:c,timestamp:c.lastChangedTime,mesh:p,collider:g};r.set(c,f),ma&&console.log("New plane detected, id="+f.id,f,{hasCollider:!!g,isGroup:p instanceof mo});try{const y=new CustomEvent("plane-tracking",{detail:{type:"plane-added",context:f}});this.dispatchEvent(y)}catch(y){console.error(y)}}}u&&(d?(u.visible=!0,u.matrix.fromArray(d.transform.matrix),u.matrix.premultiply(this._flipForwardMatrix)):u.visible=!1,ma&&u.traverse(p=>{if(p instanceof G)if(p.userData.normalsHelper)p.userData.normalsHelper.update();else{const g=new mO(p,.05,255);g.layers.disableAll(),g.layers.set(2),this.context.scene.add(g),p.userData.normalsHelper=g}}))}}}checkIfContextShouldBeConvex(e,t){if(!e)return!0;if(e){const s=new Si;s.expandByObject(e);const o=new S;s.getSize(o);let r=!0;return o.x>2&&o.y>2&&o.z>1.5&&(r=!1),r&&"semanticLabel"in t&&t.semanticLabel==="wall"&&(r=!0),r}return!0}createGeometry(e){return"polygon"in e?this.createPlaneGeometry(e.polygon):"vertices"in e&&"indices"in e?this.createMeshGeometry(e.vertices,e.indices):new Vs}createMeshGeometry(e,t){const s=e.toString()+"_"+t.toString();if(this._verticesCache.has(s))return this._verticesCache.get(s);const o=new Vs;o.setIndex(new _t(t,1)),o.setAttribute("position",new _t(e,3));const r=Array();for(let l=0;l<e.length;l+=3)r.push(e[l],e[l+2]);return o.setAttribute("uv",new _t(e,3)),o.computeVertexNormals(),this._verticesCache.set(s,o),o}createPlaneGeometry(e){const t=new Vs,s=[],o=[];e.forEach(g=>{s.push(g.x,g.y,g.z),o.push(g.x,g.z)});const r=new S(s[0],s[1],s[2]),l=new S(s[3],s[4],s[5]),c=new S(s[6],s[7],s[8]),h=new S,d=new S;h.subVectors(l,r),d.subVectors(c,r),h.cross(d),h.normalize();const u=[];for(let g=0;g<s.length/3;g++)u.push(h.x,h.y,h.z);const p=[];for(let g=2;g<e.length;++g)p.push(0,g-1,g);return t.setAttribute("position",new _t(new Float32Array(s),3)),t.setAttribute("uv",new _t(new Float32Array(o),2)),t.setAttribute("normal",new _t(new Float32Array(u),3)),t.setIndex(p),t.computeBoundingBox(),t.computeBoundingSphere(),t}}Ll([m(ce)],ao.prototype,"dataTemplate"),Ll([m()],ao.prototype,"occluder"),Ll([m()],ao.prototype,"initiateRoomCaptureIfNoData"),Ll([m()],ao.prototype,"usePlaneData"),Ll([m()],ao.prototype,"useMeshData"),Ll([m()],ao.prototype,"runInVR");var vL=Object.defineProperty,bL=(n,e,t,s)=>{for(var o=void 0,r=n.length-1,l;r>=0;r--)(l=n[r])&&(o=l(e,t,o)||o);return o&&vL(e,t,o),o};const VS=C("debugwebxr");class um extends I{constructor(){super(...arguments),a(this,"priority",0),a(this,"_startScale")}get isActive(){return this.activeAndEnabled&&this.gameObject.visible}setAsActiveXRRig(){var e;(e=ne.active)==null||e.setRigActive(this)}setPriority(e){this.priority=e}awake(){if(VS){const e=new E;e.position.y+=.5,this.gameObject.add(e);const t=e.addNewComponent(ea);t&&(t.isGizmo=!1);const s=new Ci(.5);this.gameObject.add(s)}}isXRRig(){return!0}supportsXR(e){return!0}onEnterXR(e){this._startScale=this.gameObject.scale.clone(),e.xr.addRig(this),VS&&console.log("WebXR: add Rig",this.name,this.priority)}onLeaveXR(e){e.xr.removeRig(this),this._startScale&&this.gameObject&&this.gameObject.scale.copy(this._startScale)}}bL([m()],um.prototype,"priority");class _L extends I{constructor(){super(...arguments),a(this,"toggleKey","KeyP")}update(){this.context.input.isKeyDown(this.toggleKey)&&this.context.domElement.classList.toggle("presentation-mode")}}R.add("AlignmentConstraint",Tc),R.add("Animation",Ft),R.add("Animator",Rt),R.add("AudioListener",zn),R.add("AudioSource",ns),R.add("Avatar_Brain_LookAt",Uc),R.add("Avatar_MouthShapes",zc),R.add("Avatar_MustacheShake",Xf),R.add("AvatarBlink_Simple",zr),R.add("AvatarEyeLook_Rotation",Kf),R.add("AxesHelper",Ja),R.add("BasicIKConstraint",Jf),R.add("BoxHelperComponent",Bo),R.add("Camera",ci),R.add("CharacterController",Nr),R.add("CharacterControllerInput",$n),R.add("Collider",ui),R.add("SphereCollider",el),R.add("BoxCollider",Nu),R.add("MeshCollider",Fo),R.add("CapsuleCollider",Wn),R.add("ContactShadows",Vc),R.add("LogStats",i0),R.add("DeleteBox",Wu),R.add("Deletable",n0),R.add("DeviceFlag",Vu),R.add("DragControls",Hr),R.add("DropListener",Hn),R.add("Duplicatable",h0),R.add("EventListEvent",Ru),R.add("EventTrigger",qu),R.add("GltfExportBox",S0),R.add("GltfExport",P0),R.add("VariantAction",j0),R.add("ChangeTransformOnClick",Xr),R.add("ChangeMaterialOnClick",B0),R.add("SetActiveOnClick",F0),R.add("HideOnStart",pp),R.add("EmphasizeOnClick",ul),R.add("PlayAudioOnClick",Vo),R.add("PlayAnimationOnClick",Jc),R.add("PreliminaryAction",pl),R.add("PreliminaryTrigger",eh),R.add("VisibilityAction",th),R.add("TapGestureTrigger",N0),R.add("USDZExporter",gn),R.add("Fog",xl),R.add("BoxGizmo",ea),R.add("GridHelper",Sl),R.add("GroundProjectedEnv",en),R.add("UsageMarker",$c),R.add("Interactable",s0),R.add("FixedJoint",fy),R.add("HingeJoint",dh),R.add("Light",yi),R.add("LODGroup",ph),R.add("LookAtConstraint",Fr),R.add("NeedleMenu",un),R.add("NestedGltf",kp),R.add("Networking",_y),R.add("OffsetConstraint",ta),R.add("CameraTargetReachedEvent",Fc),R.add("OrbitControls",_e),R.add("ParticleSystemRenderer",ds),R.add("ParticleSystem",yh),R.add("PlayerColor",Nl),R.add("Antialiasing",bh),R.add("BloomEffect",Np),R.add("ChromaticAberration",_h),R.add("ColorAdjustments",or),R.add("DepthOfField",As),R.add("EffectWrapper",xh),R.add("PixelationEffect",Sh),R.add("ScreenSpaceAmbientOcclusion",to),R.add("ScreenSpaceAmbientOcclusionN8",Is),R.add("SharpeningEffect",Ph),R.add("TiltShiftEffect",yn),R.add("ToneMappingEffect",nr),R.add("Vignette",la),R.add("Volume",Ml),R.add("ReflectionProbe",qc),R.add("Renderer",Ui),R.add("MeshRenderer",Qc),R.add("SkinnedMeshRenderer",x0),R.add("Rigidbody",dt),R.add("SceneSwitcher",Ze),R.add("ScreenCapture",ar),R.add("ShadowCatcher",Rh),R.add("RemoteSkybox",qp),R.add("SmoothFollow",Yp),R.add("SpatialTriggerReceiver",vn),R.add("SpatialTrigger",Kp),R.add("SpectatorCamera",Zp),R.add("SpriteRenderer",gi),R.add("SyncedCamera",Wy),R.add("SyncedRoom",Ls),R.add("SyncedTransform",sn),R.add("TestRunner",Hy),R.add("TestSimulateUserData",Gy),R.add("PlayableDirector",Tl),R.add("SignalReceiver",Dh),R.add("AnimationTrackHandler",im),R.add("AudioTrackHandler",sm),R.add("SignalTrackHandler",Fh),R.add("ControlTrackHandler",nm),R.add("TransformGizmo",da),R.add("BaseUIComponent",ps),R.add("UIRootComponent",oh),R.add("Button",no),R.add("Canvas",_l),R.add("CanvasGroup",Ko),R.add("EventSystem",ii),R.add("Graphic",lh),R.add("MaskableGraphic",ch),R.add("Image",El),R.add("RawImage",am),R.add("InputField",Yy),R.add("VerticalLayoutGroup",oy),R.add("HorizontalLayoutGroup",ry),R.add("GridLayoutGroup",ay),R.add("Outline",bl),R.add("ObjectRaycaster",ji),R.add("GraphicRaycaster",Au),R.add("SpatialGrabRaycaster",Dc),R.add("RectTransform",Ts),R.add("SpatialHtml",Nh),R.add("Text",Nt),R.add("EnvironmentScene",cm),R.add("LookAt",Ky),R.add("OpenURL",Al),R.add("VideoPlayer",yt),R.add("Voip",Do),R.add("Avatar",Go),R.add("XRControllerFollow",oo),R.add("XRControllerModel",pn),R.add("XRControllerMovement",Ni),R.add("TeleportTarget",_p),R.add("WebARCameraBackground",Hh),R.add("WebARSessionRoot",$o),R.add("WebXR",wp),R.add("AvatarMarker",hi),R.add("WebXRImageTracking",Gh),R.add("WebXRPlaneTracking",ao),R.add("XRRig",um),R.add("XRFlag",os),R.add("PlayerSync",X0),R.add("PlayerState",Ms),R.add("PresentationMode",_L);const qh=wt,wL=C("debugtypestore");wL&&console.log(R);function xL(n,e){const t=rw(n,e);return t!==void 0?t:null}const SL=new XM,sv=Symbol("deserialize-queue");async function CL(n,e,t,s=null,o){if(!t){console.debug("Can not create component instances: gltf is null");return}let r=s;typeof r=="number"&&(r=new jt(s));const l=e.indexOf("?");e=l===-1?e:e.substring(0,l);const c=new df(t.scene);c.gltfId=e,c.context=n,c.gltf=t,c.nodeToObject=o?.nodeToObjectMap,c.implementationInformation=SL;let h=n[sv];if(h||(h=n[sv]=[]),t.scenes)for(const d of t.scenes)await rv(c,d,h);if(t.children)for(const d of t.children)await rv(c,d,h);n.new_scripts_pre_setup_callbacks.push(()=>{const d=n[sv];if(d){for(const u of d)PL(u,c);d.length=0}if(r){const u={},p=[];ov(t,r,u,p);for(const g of t.scenes)ov(g,r,u,p);for(const g of p)g.resolveGuids(u)}})}const nv=Symbol("original-component-name"),jl=new Map;function ov(n,e,t,s){if(e===null||!n)return;const o=n.guid,r=n.guid;r!=null&&r.length&&(jl.has(r)||(qh&&console.log('Creating InstanceIdProvider with key "'+r+'" for object '+n.name),jl.set(r,new jt(r))));const l=r&&jl.get(r)||e;if(n.guid=l.generateUUID(),o&&o!=="invalid"&&(t[o]=n.guid),n&&n.userData&&n.userData.components)for(const c of n.userData.components){if(c===null)continue;const h=c.guid;h?jl.has(h)||(qh&&console.log('Creating InstanceIdProvider with key "'+h+'" for component '+c[nv]),jl.set(h,new jt(h))):qh&&console.warn("Can not create IdProvider: component "+c[nv]+" has no guid",c.guid);const d=jl.get(h)||e,u=c.guid;c.guid=d.generateUUID(),u&&u!=="invalid"&&(t[u]=c.guid),c.resolveGuids&&s.push(c)}if(n.children)for(const c of n.children)ov(c,e,t,s)}const Xh=[];async function rv(n,e,t,s){var o,r,l,c,h;if(!e)return;const d=e.userData;if(d){const u=d.builtin_components;if(u&&u.length>0)for(const p of u)try{if(p===null)continue;const g=R.get(p.name);if(g!=null){const f=new g;f.sourceId=n.gltfId,Na(f,p,n.implementationInformation),f.context=n.context,"guid"in p&&(f[oc]=p.guid),f[nv]=p.name,Mr(e,f,!1),t.push({instance:f,compData:p,obj:e}),f.isCamera&&n.context&&n.context.mainCamera===null&&f.tag==="MainCamera"&&n.context.setCurrentCamera(f),((l=(r=(o=n.context)==null?void 0:o.physics)==null?void 0:r.engine)==null?void 0:l.isInitialized)===!1&&(f.isCollider||f.isRigidbody)&&((h=(c=n.context)==null?void 0:c.physics.engine)==null||h.initialize())}else qh&&console.debug("unknown component: "+p.name),Xh.includes(p.name)||Xh.push(p.name)}catch(g){console.error(p.name+" - "+g.message,g)}if(Xh.length>0){const p=Xh.join(", ");console.warn("unknown components: "+p),Xh.length=0,Xt()&&De(`<strong>Unknown components in scene</strong>:
|
|
1450
1453
|
|
|
1451
1454
|
${p}
|
|
1452
1455
|
|
|
1453
1456
|
This could mean you forgot to add a npmdef to your ExportInfo
|
|
1454
|
-
<a href="https://engine.needle.tools/docs/project_structure.html#creating-and-installing-a-npmdef" target="_blank">documentation</a>`,ki.Warn)}}if(e.children)for(const u of e.children)await rv(n,u,t)}function
|
|
1455
|
-
Use import { NeedleEngineModelLoader } from "@needle-tools/engine" namespace to register your loader.`,n);const s=new Rn;return await Ku(s,e,n),s}case"model/fbx":case"model/vnd.autodesk.fbx":return new qv;case"model/obj":return new Vm;case"model/vnd.usdz+zip":case"model/vnd.usd+zip":case"model/vnd.usda+zip":return console.warn(t.toUpperCase()+" files are not supported."),null;case"model/gltf+json":case"model/gltf-binary":case"model/vrm":{const s=new Rn;return await Ku(s,e,n),s}}}function
|
|
1456
|
-
`,u),l(void 0)})}catch(h){console.error(h),c(h)}})}async function av(n,e,t,s,o){
|
|
1457
|
-
`,d),c(void 0)})}catch(d){console.error(d),h(d)}})}function XS(n,e){const t=y0(n);return n instanceof Rn&&jf(n,e),{componentsExtension:t}}async function Qh(n,e,t,s,o,r){var l;if(HS&&console.warn("Loaded",t,s),s==null)return console.error(`Loaded model is null '${t}' - please make sure the loader is registered correctly`),{scene:new E,animations:[],scenes:[]};if(typeof s!="object")return console.error(`Loaded model is not an object '${t}' - please make sure the loader is registered correctly`),{scene:new E,animations:[],scenes:[]};if(s instanceof E)s={scene:s,animations:s.animations,scenes:[s]};else if(s instanceof Vs){const c=new bt({color:new oe(14540253)}),h=new G(s,c);s={scene:h,animations:[],scenes:[h]}}else Array.isArray(s.scenes)===!1&&console.error(`[Needle Engine] The loaded model object does not have a scenes property '${t}' - please make sure the loader is registered correctly and three.js is not imported multiple times.`);if(t.includes("?")&&(t=t.split("?")[0]),"scenes"in s)for(const c of s.scenes)c&&!((l=c.animations)!=null&&l.length)&&(c.animations=[...s.animations]);return
|
|
1458
|
-
Please refer to the documentation on <a href="https://fwd.needle.tools/needle-engine/docs/local-server">https://docs.needle.tools</a> or ask for help in our <a href="https://discord.needle.tools">discord community</a>`;De(e),console.warn(e)}}function
|
|
1457
|
+
<a href="https://engine.needle.tools/docs/project_structure.html#creating-and-installing-a-npmdef" target="_blank">documentation</a>`,ki.Warn)}}if(e.children)for(const u of e.children)await rv(n,u,t)}function PL(n,e){const{instance:t,compData:s,obj:o}=n;e.object=o,e.target=t,su(t,s,e),qh&&console.debug("add "+s.name,s,t)}class $S{createBuiltinComponents(e,t,s,o,r){return CL(e,t,s,o,r)}writeBuiltinComponentData(e,t){return xL(e,t)}parseSync(e,t,s,o){return qS(e,t,s,o)}loadSync(e,t,s,o,r){return av(e,t,s,o,r)}}wg($S);const HS=C("printGltf")||C("printgltf"),OL=C("debugfileformat");async function GS(n,e){const t=await Xx(n,{useExtension:!0})||"unknown";OL&&console.debug(`Determined file type: '${t}' for url '${n}'`,{registeredModelLoaderCallbacks:il});for(const s of il){const{callback:o}=s,r=o({context:e,url:n,mimetype:t});if(r instanceof Promise&&await r,r)return console.debug(`Using custom loader (${s.name||"unnamed"}) for ${t} at '${n}'`),r}switch(t){case"unsupported":return null;default:case"unknown":{console.warn(`Unknown file type (${t}). Needle Engine will fallback to the GLTFLoader - To support more model formats please create a Needle loader plugin.
|
|
1458
|
+
Use import { NeedleEngineModelLoader } from "@needle-tools/engine" namespace to register your loader.`,n);const s=new Rn;return await Ku(s,e,n),s}case"model/fbx":case"model/vnd.autodesk.fbx":return new qv;case"model/obj":return new Vm;case"model/vnd.usdz+zip":case"model/vnd.usd+zip":case"model/vnd.usda+zip":return console.warn(t.toUpperCase()+" files are not supported."),null;case"model/gltf+json":case"model/gltf-binary":case"model/vrm":{const s=new Rn;return await Ku(s,e,n),s}}}function kL(n,e){return av(e?.context||J.Current,n,n,e?.seed||null,e?.onprogress)}async function qS(n,e,t,s){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),t=""),HS&&console.log("Parse glTF",t);const o=await GS(t,n);if(!o)return;const{componentsExtension:r}=XS(o,n);if(o instanceof Vm){typeof e!="string"&&(e=new TextDecoder().decode(e));const l=o.parse(e);return await Qh(o,n,t,l,s,r)}if(!(o instanceof Rn)){if(o.parse===void 0){console.error("Loader does not support parse");return}const l=o.parse(e,t);return await Qh(o,n,t,l,s,r)}return new Promise((l,c)=>{try{let h=t.split("?")[0].trimEnd();const d=h.split("/");d.length>0&&d[d.length-1]!==""&&d.pop(),h=d.join("/"),h.endsWith("/")||(h+="/"),o.resourcePath=h,o.parse(e,"",async u=>{const p=await Qh(o,n,t,u,s,r);l(p)},u=>{console.error('Loading asset at "'+t+`" failed
|
|
1459
|
+
`,u),l(void 0)})}catch(h){console.error(h),c(h)}})}async function av(n,e,t,s,o){RL(e);const r=await GS(e,n);if(!r)return;const{componentsExtension:l}=XS(r,n);if(!(r instanceof Rn)){const c=await r.loadAsync(e,o);return await Qh(r,n,e,c,s,l)}return new Promise((c,h)=>{try{r.load(e,async d=>{const u=await Qh(r,n,t,d,s,l);c(u)},d=>{o?.call(r,d)},d=>{console.error('Loading asset at "'+e+`" failed
|
|
1460
|
+
`,d),c(void 0)})}catch(d){console.error(d),h(d)}})}function XS(n,e){const t=y0(n);return n instanceof Rn&&jf(n,e),{componentsExtension:t}}async function Qh(n,e,t,s,o,r){var l;if(HS&&console.warn("Loaded",t,s),s==null)return console.error(`Loaded model is null '${t}' - please make sure the loader is registered correctly`),{scene:new E,animations:[],scenes:[]};if(typeof s!="object")return console.error(`Loaded model is not an object '${t}' - please make sure the loader is registered correctly`),{scene:new E,animations:[],scenes:[]};if(s instanceof E)s={scene:s,animations:s.animations,scenes:[s]};else if(s instanceof Vs){const c=new bt({color:new oe(14540253)}),h=new G(s,c);s={scene:h,animations:[],scenes:[h]}}else Array.isArray(s.scenes)===!1&&console.error(`[Needle Engine] The loaded model object does not have a scenes property '${t}' - please make sure the loader is registered correctly and three.js is not imported multiple times.`);if(t.includes("?")&&(t=t.split("?")[0]),"scenes"in s)for(const c of s.scenes)c&&!((l=c.animations)!=null&&l.length)&&(c.animations=[...s.animations]);return TL(n,s),Rx(s)&&(a1(t,s,e),await xs().createBuiltinComponents(e,t,s,o,r||void 0)),await ML(s.scene,e,e.mainCamera),s}async function ML(n,e,t){t||(t=e.mainCamera);try{t?await e.renderer.compileAsync(n,t,e.scene).catch(s=>{console.warn(s.message)}):IM(n,e)}catch(s){console.warn(s?.message||s)}}function RL(n){if(new URL(n,window.location.href).href.startsWith("file://")){const e=`Hi - it looks like you are trying to load a local file which will not work. You need to use a webserver to serve your files.
|
|
1461
|
+
Please refer to the documentation on <a href="https://fwd.needle.tools/needle-engine/docs/local-server">https://docs.needle.tools</a> or ask for help in our <a href="https://discord.needle.tools">discord community</a>`;De(e),console.warn(e)}}function TL(n,e){if(n instanceof qv||n instanceof Vm){let t=e;t instanceof E||(t=e.scene),t.traverse(s=>{const o=s;o!=null&&o.isMesh&&gg(o,o.material)})}}const Yh=C("debugoverlay"),QS="ar",EL="quit-ar";class AL{constructor(){a(this,"arContainer",null),a(this,"currentSession",null),a(this,"_createdAROnlyElements",[]),a(this,"_reparentedObjects",[]),a(this,"contentElement",null),a(this,"originalDomOverlayParent",null),a(this,"requestEndAR",()=>{this.onRequestedEndAR()})}get ARContainer(){return this.arContainer}onBegin(e,t,s){var o;if(this.currentSession=s,this.arContainer=t,X.isMozillaXR()){const r=e.domElement.children;for(let l=0;l<r?.length;l++){const c=r[l];if(!c||c===this.arContainer)return;this._reparentedObjects.push({el:c,previousParent:c.parentElement}),(o=this.arContainer)==null||o.appendChild(c)}t?(this.originalDomOverlayParent=t.parentNode,this.originalDomOverlayParent&&(console.log("Reparent DOM Overlay to body",t,t.style.display),t.style.display="",t.style.visibility="",document.body.appendChild(t))):console.warn("WebXRViewer: No DOM Overlay found")}this.ensureQuitARButton(this.arContainer)}onEnd(e){var t;for(const s of this._createdAROnlyElements)s.remove&&s.remove();for(const s of this._reparentedObjects){const o=s.el;(t=s.previousParent)==null||t.appendChild(o)}this._reparentedObjects.length=0,X.isMozillaXR()&&setTimeout(()=>{var s;const o=e.renderer.domElement;o&&((s=e.domElement.shadowRoot)==null||s.prepend(o));const r=document.querySelectorAll("*");for(var l=0;l<r.length;l++){const c=r[l];c&&c._displayChanged!==void 0&&c._displayWas!==void 0&&(c.style.display=c._displayWas)}},10)}createOverlayContainer(e){if(this.contentElement)return this.contentElement;Yh&&console.log("Setup overlay container");const t=e.shadowRoot.querySelector(".content");this.contentElement=t;const s=e.shadowRoot.querySelector(".overlay-content");return s&&t.appendChild(s),Yh&&!X.isMobileDevice()&&this.ensureQuitARButton(t),t}onRequestedEndAR(){this.currentSession&&(this.currentSession.end(),this.currentSession=null)}ensureQuitARButton(e){const t=document.createElement("slot");t.setAttribute("name","quit-ar"),this.appendElement(t,e),this._createdAROnlyElements.push(t),t.style.pointerEvents="auto";const s=document.querySelector(`.${EL}`);if(s){s.addEventListener("click",this.requestEndAR),Yh&&s.addEventListener("click",()=>console.log("Clicked quit-ar button"));return}t.addEventListener("click",this.requestEndAR),Yh&&t.addEventListener("click",()=>console.log("Clicked fallback close button"));const o=document.createElement("div");o.style.cssText=`
|
|
1459
1462
|
position: fixed;
|
|
1460
1463
|
top: 0;
|
|
1461
1464
|
right: 0;
|
|
@@ -1473,7 +1476,7 @@ Please refer to the documentation on <a href="https://fwd.needle.tools/needle-en
|
|
|
1473
1476
|
align-items: center;
|
|
1474
1477
|
`,o.appendChild(r);var l=document.createElementNS("http://www.w3.org/2000/svg","path");l.setAttribute("d","M 12,12 L 28,28 M 28,12 12,28"),l.setAttribute("stroke","#000000"),l.setAttribute("stroke-width","2px"),l.style.cssText=`
|
|
1475
1478
|
/**filter: drop-shadow(0 0px 1.2px rgba(0,0,0,.7));**/
|
|
1476
|
-
`,r.appendChild(l),Yh&&console.log("Created fallback close button",r,e)}appendElement(e,t){return t.shadowRoot?t.shadowRoot.appendChild(e):t.appendChild(e)}}const ga=C("debugloading"),Kh=C("debugloadingrendering"),YS=C("debuglicense");class
|
|
1479
|
+
`,r.appendChild(l),Yh&&console.log("Created fallback close button",r,e)}appendElement(e,t){return t.shadowRoot?t.shadowRoot.appendChild(e):t.appendChild(e)}}const ga=C("debugloading"),Kh=C("debugloadingrendering"),YS=C("debuglicense");class IL{constructor(){a(this,"className"),a(this,"additionalClasses")}}let Zh=0,KS;function lv(n){ga&&console.log(n.progress.loaded.toFixed(0)+"/"+n.progress.total.toFixed(0),n);const e=n.count,t=n.progress.total;t===0||t===void 0?(KS!==n.name&&(Zh=0),KS=n.name,Zh+=(1-Zh)*.001,ga&&be("Loading "+n.name+" did not report total size")):Zh=n.progress.loaded/t;const s=n.index/e+Zh/e;return W.clamp01(s)}const ZS=class Pv{constructor(e,t){a(this,"loadingProgress",0),a(this,"_element"),a(this,"_progress",0),a(this,"_allowCustomLoadingElement",!0),a(this,"_loadingElement"),a(this,"_loadingTextContainer",null),a(this,"_loadingBar",null),a(this,"_messageContainer",null),a(this,"_loadingElementOptions"),a(this,"_progressLoop"),this._element=e,this._loadingElementOptions=t}async onLoadingBegin(e){const t=this._element.shadowRoot||this._element;if(ga&&console.warn("Begin Loading"),!this._loadingElement){for(let s=0;s<t.children.length;s++){const o=t.children[s];if(o.classList.contains(Pv.LoadingContainerClassName)){if(!this._allowCustomLoadingElement){ga&&console.warn("Remove custom loading container"),t.removeChild(o);continue}this._loadingElement=this.createLoadingElement(o)}}this._loadingElement||(this._loadingElement=this.createLoadingElement())}this._progress=0,this.loadingProgress=0,this._loadingElement.style.display="flex",t.appendChild(this._loadingElement),this.smoothProgressLoop(),this.setMessage(e??"")}onLoadingUpdate(e,t){var s;if(!((s=this._loadingElement)!=null&&s.parentNode))return;let o=0;typeof e=="number"?o=e:("index"in e&&(o=lv(e)),!t&&"name"in e&&this.setMessage("loading "+e.name)),this.loadingProgress=o,t&&this.setMessage(t),this.updateDisplay()}onLoadingFinished(){ga&&console.warn("Finished Loading"),Kh||(this.loadingProgress=1,this.onDoneLoading())}setMessage(e){this._messageContainer&&(this._messageContainer.innerText=e)}smoothProgressLoop(){if(this._progressLoop)return;let e=1/12;Kh&&(e=1/500,typeof Kh=="number"&&(e*=Kh)),this._progressLoop=setInterval(()=>{this.loadingProgress>=.95&&!Kh&&(e=.9),this._progress=W.lerp(this._progress,this.loadingProgress,e*this.loadingProgress),this.updateDisplay()},e)}onDoneLoading(){this._loadingElement&&(ga&&console.log("Hiding loading element"),this._loadingElement.style.display="none",this._loadingElement.remove()),this._progressLoop&&clearInterval(this._progressLoop),this._progressLoop=null}updateDisplay(){const e=this._progress,t=(e*100).toFixed(0)+"%";this._loadingBar&&(this._loadingBar.style.width=e*100+"%"),this._loadingTextContainer&&(this._loadingTextContainer.textContent=t)}createLoadingElement(e){var t,s;ga&&!e&&console.log("Creating loading element"),this._loadingElement=e||document.createElement("div");let o=this._element.getAttribute("loading-style");(!o||o==="auto")&&(window.matchMedia("(prefers-color-scheme: dark)").matches?o="dark":o="light");const r=Zs();if(!e){this._loadingElement.style.position="absolute",this._loadingElement.style.width="100%",this._loadingElement.style.height="100%",this._loadingElement.style.left="0",this._loadingElement.style.top="0";const y=this._element.getAttribute("loading-background");y?this._loadingElement.style.background=y:this._loadingElement.style.backgroundColor="transparent",this._loadingElement.style.display="flex",this._loadingElement.style.alignItems="center",this._loadingElement.style.justifyContent="center",this._loadingElement.style.zIndex=Number.MAX_SAFE_INTEGER.toString(),this._loadingElement.style.flexDirection="column",this._loadingElement.style.pointerEvents="none",this._loadingElement.style.color="white",this._loadingElement.style.fontFamily='system-ui, Roboto, Helvetica, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol"',this._loadingElement.style.fontSize="1rem",o==="light"?this._loadingElement.style.color="rgba(0,0,0,.6)":this._loadingElement.style.color="rgba(255,255,255,.3)"}const l=((t=this._loadingElementOptions)==null?void 0:t.className)??Pv.LoadingContainerClassName;if(this._loadingElement.classList.add(l),(s=this._loadingElementOptions)!=null&&s.additionalClasses)for(const y of this._loadingElementOptions.additionalClasses)this._loadingElement.classList.add(y);const c=document.createElement("div");this._loadingElement.appendChild(c);const h=document.createElement("img"),d=120;if(h.style.width=`${d}px`,h.style.height=`${d}px`,h.style.paddingTop="20px",h.style.paddingBottom="10px",h.style.margin="0px",h.style.userSelect="none",h.style.objectFit="contain",h.style.transition="transform 1.5s ease-out, opacity .3s ease-in-out",h.style.transform="translateY(30px)",h.style.opacity="0.05",setTimeout(()=>{h.style.opacity="1",h.style.transform="translateY(0px)"},1),h.src=nb,r&&this._element){const y=this._element.getAttribute("loading-logo-src");y&&(h.src=y)}c.appendChild(h);const u=document.createElement("div");u.style.cssText=`
|
|
1477
1480
|
display: flex;
|
|
1478
1481
|
flex-direction: column;
|
|
1479
1482
|
align-items: center;
|
|
@@ -1482,7 +1485,7 @@ Please refer to the documentation on <a href="https://fwd.needle.tools/needle-en
|
|
|
1482
1485
|
opacity: 0;
|
|
1483
1486
|
transition: opacity 1s ease-in-out 4s;
|
|
1484
1487
|
`,setTimeout(()=>{u.style.opacity="1"},1),this._loadingElement.appendChild(u);const p=document.createElement("div"),g=100;p.style.display="flex",p.style.width=g+"%",p.style.height="3px",p.style.position="absolute",p.style.left="0",p.style.bottom="0px",p.style.opacity="0",p.style.transition="opacity 1s ease-in-out 2s",setTimeout(()=>{p.style.opacity="1"},1),o==="light"?p.style.backgroundColor="rgba(0,0,0,.2)":p.style.backgroundColor="rgba(255,255,255,.2)",this._loadingElement.appendChild(p),this._loadingBar=document.createElement("div"),p.appendChild(this._loadingBar);const f=function(y){return W.lerp(0,g,y)+"%"};if(this._loadingBar.style.background="#66A22F",this._loadingBar.style.backgroundAttachment="fixed",this._loadingBar.style.width="0%",this._loadingBar.style.height="100%",r&&this._element){const y=this._element.getAttribute("primary-color"),v=this._element.getAttribute("secondary-color");y&&v?this._loadingBar.style.background=`linear-gradient(90deg, ${y} ${f(0)}, ${v} ${f(1)})`:y?this._loadingBar.style.background=y:v&&(this._loadingBar.style.background=v)}return this.handleRuntimeLicense(this._loadingElement),this._loadingElement}async handleRuntimeLicense(e){let t=Js();if(t)return;YS&&console.log("Loading UI has commercial license?",t);const s=document.createElement("div");s.style.paddingTop=".6em",s.style.fontSize=".8em",s.style.textTransform="uppercase",s.innerText=`NEEDLE ENGINE NON COMMERCIAL VERSION
|
|
1485
|
-
CLICK HERE TO GET A LICENSE`,s.style.cursor="pointer",s.style.userSelect="none",s.style.textAlign="center",s.style.pointerEvents="all",s.addEventListener("click",()=>window.open("https://needle.tools/pricing","_self")),s.style.opacity="0",e.appendChild(s),!F()&&jr&&(YS&&console.log("Waiting for runtime license check"),await jr,t=Js()),!t&&(s.style.transition="opacity .5s ease-in-out",s.style.opacity="1")}};a(ZS,"LoadingContainerClassName","loading");let JS=ZS;wg($S);const Ie=C("debugwebcomponent"),eC="needle-engine",tC="vr",iC="desktop",
|
|
1488
|
+
CLICK HERE TO GET A LICENSE`,s.style.cursor="pointer",s.style.userSelect="none",s.style.textAlign="center",s.style.pointerEvents="all",s.addEventListener("click",()=>window.open("https://needle.tools/pricing","_self")),s.style.opacity="0",e.appendChild(s),!F()&&jr&&(YS&&console.log("Waiting for runtime license check"),await jr,t=Js()),!t&&(s.style.transition="opacity .5s ease-in-out",s.style.opacity="1")}};a(ZS,"LoadingContainerClassName","loading");let JS=ZS;wg($S);const Ie=C("debugwebcomponent"),eC="needle-engine",tC="vr",iC="desktop",LL=[QS,tC,iC],Jh="ar-session-active",ed="desktop-session-active",jL=["public-key","version","hash","src","camera-controls","loadstart","progress","loadfinished","dracoDecoderPath","dracoDecoderType","ktx2DecoderPath","tone-mapping","tone-mapping-exposure","background-blurriness","background-color"];class cv extends HTMLElement{constructor(){super(),a(this,"_context"),a(this,"_overlay_ar"),a(this,"_loadingProgress01",0),a(this,"_loadingView"),a(this,"_previousSrc",null),a(this,"_didFullyLoad",!1),a(this,"_loadId",0),a(this,"_abortController",null),a(this,"_lastSourceFiles",null),a(this,"_createContextPromise",null),a(this,"onXRSessionStarted",()=>{var t;const s=this.context.xrSessionMode;s==="immersive-ar"?this.onEnterAR(this.context.xrSession):s==="immersive-vr"&&this.onEnterVR(this.context.xrSession),(t=this.context.xrSession)==null||t.addEventListener("end",()=>{this.dispatchEvent(new CustomEvent("xr-session-ended",{detail:{session:this.context.xrSession,context:this._context,sessionMode:s}})),s==="immersive-ar"?this.onExitAR(this.context.xrSession):s==="immersive-vr"&&this.onExitVR(this.context.xrSession)})}),a(this,"onReady",()=>{var t;return(t=this._loadingView)==null?void 0:t.onLoadingFinished()}),a(this,"onError",()=>{var t;return(t=this._loadingView)==null?void 0:t.setMessage("Loading failed!")}),a(this,"_previouslyRegisteredMap",new Map),this._overlay_ar=new AL,this.addEventListener("ready",this.onReady),Qw(),this.attachShadow({mode:"open"});const e=document.createElement("template");e.innerHTML=`<style>
|
|
1486
1489
|
@import url('https://fonts.googleapis.com/css2?family=Roboto+Flex:opsz,wght@8..144,100..1000&display=swap');
|
|
1487
1490
|
|
|
1488
1491
|
:host {
|
|
@@ -1559,14 +1562,14 @@ CLICK HERE TO GET A LICENSE`,s.style.cursor="pointer",s.style.userSelect="none",
|
|
|
1559
1562
|
<div class="content">
|
|
1560
1563
|
<slot class="overlay-content"></slot>
|
|
1561
1564
|
</div>
|
|
1562
|
-
`,this.shadowRoot&&this.shadowRoot.appendChild(e.content.cloneNode(!0)),this._context=new J({domElement:this}),this.addEventListener("error",this.onError)}static get observedAttributes(){return
|
|
1565
|
+
`,this.shadowRoot&&this.shadowRoot.appendChild(e.content.cloneNode(!0)),this._context=new J({domElement:this}),this.addEventListener("error",this.onError)}static get observedAttributes(){return jL}get loadingProgress01(){return this._loadingProgress01}get loadingFinished(){return this.loadingProgress01>.999}get cameraControls(){const e=this.getAttribute("camera-controls");return e==null?null:!(e===null||e==="False"||e==="false"||e==="0"||e==="none")}getContext(){return new Promise((e,t)=>{if(this._context&&this.loadingFinished)e(this._context);else{const s=()=>{this.removeEventListener("loadfinished",s),this._context&&this.loadingFinished&&e(this._context)};this.addEventListener("loadfinished",s)}})}get context(){return this._context}async connectedCallback(){if(Ie&&console.log("<needle-engine> connected"),this.setPublicKey(),this.setVersion(),this.addEventListener("xr-session-started",this.onXRSessionStarted),this.onSetupDesktop(),!this.getAttribute("src")){const t=globalThis["needle:codegen_files"];Ie&&console.log('src is null, trying to load from globalThis["needle:codegen_files"]',t),t&&(Ie&&console.log('globalThis["needle:codegen_files"]',t),this.setAttribute("src",t))}Ie&&console.log("src",this.getAttribute("src"));const e=this._loadId;setTimeout(()=>{this.isConnected!==!1&&e===this._loadId&&this.onLoad()},1)}disconnectedCallback(){var e;this.removeEventListener("xr-session-started",this.onXRSessionStarted),this._didFullyLoad=!1;const t=this.getAttribute("keep-alive"),s=t==null||t?.length>0&&t!=="true"&&t!=="1";Ie&&console.warn('<needle-engine> disconnected, keep-alive: "'+t+'"',typeof t,"Dispose=",s),s?(Ie&&console.warn("<needle-engine> dispose"),(e=this._context)==null||e.dispose(),this._context=null,this._lastSourceFiles=null,this._loadId+=1):Ie&&console.warn("<needle-engine> is not disposed because keep-alive is set")}attributeChangedCallback(e,t,s){switch(Ie&&console.log("attributeChangedCallback",e,t,s),e){case"src":Ie&&console.warn(`<needle-engine src>
|
|
1563
1566
|
changed from "`,t,'" to "',s,'"'),this.onLoad();break;case"hash":this._context&&(this._context.hash=s);break;case"loadstart":case"progress":case"loadfinished":typeof s=="string"&&s.length>0&&(Ie&&console.log(e+" attribute changed",s),this.registerEventFromAttribute(e,s));break;case"dracoDecoderPath":Ie&&console.log("dracoDecoderPath",s),nx(s);break;case"dracoDecoderType":s==="wasm"||s==="js"?(Ie&&console.log("dracoDecoderType",s),ox(s)):console.error("Invalid dracoDecoderType",s,"expected js or wasm");break;case"ktx2DecoderPath":Ie&&console.log("ktx2DecoderPath",s),rx(s);break;case"tone-mapping":{this.applyAttributes();break}case"tone-mapping-exposure":{this.applyAttributes();break}case"background-blurriness":{const o=parseFloat(s);o!=null&&this._context&&(this._context.scene.backgroundBlurriness=o);break}case"background-color":{this.applyAttributes();break}case"public-key":{s!=Ea&&this.setPublicKey();break}case"version":{s!=ws&&this.setVersion();break}}}get toneMapping(){return this.getAttribute("tonemapping")||this.getAttribute("tone-mapping")}async onLoad(){var e,t;if(!this.isConnected)return;if(this._context||(Ie&&console.warn("Create new context"),this._context=new J({domElement:this})),!this._context){console.error("Needle Engine: Context not initialized");return}const s=this.getSourceFiles();if(!this.checkIfSourceHasChanged(s,this._lastSourceFiles))return;this._abortController&&(Ie&&console.warn("Abort previous loading process"),this._abortController.abort(),this._abortController=null),this._lastSourceFiles=s;const o=++this._loadId;if((s==null||s.length<=0)&&(Ie&&console.warn("Clear scene",s),this._context.clear(),o!==this._loadId))return;const r=this.getAttribute("alias");this.classList.add("loading");const l=Js();this.ensureLoadStartIsRegistered();let c=this.dispatchEvent(new CustomEvent("loadstart",{detail:{context:this._context,alias:r},cancelable:!0}));if(l){const b=this.getAttribute("hide-loading-overlay");b!=null&&b!=="0"&&(c=!1)}c===!1&&!l&&(F()||(c=!0),console.warn("Needle Engine: You need a commercial license to override the default loading view. Visit https://needle.tools/pricing"),F()&&be('You need a <a target="_blank" href="https://needle.tools/pricing">commercial license</a> to override the default loading view. This will not work in production.')),!this._loadingView&&c&&(this._loadingView=new JS(this)),c&&(this._didFullyLoad!==!0?(e=this._loadingView)==null||e.onLoadingBegin("begin load"):setTimeout(()=>{this._loadingView&&this._loadingProgress01<.3&&this._loadId===o&&this._loadingView.onLoadingBegin("begin load")},300)),Ie&&console.warn(`--------------
|
|
1564
1567
|
Needle Engine: Begin loading `+o+`
|
|
1565
|
-
`,s),this.onBeforeBeginLoading();const h=[],d={context:this._context,name:"",progress:{},index:0,count:s.length,totalProgress01:this._loadingProgress01},u=new CustomEvent("progress",{detail:d}),p=new Array,g=new AbortController;this._abortController=g;const f={files:s,abortSignal:g.signal,onLoadingProgress:b=>{var _;if(Ie&&console.debug("Loading progress: ",b),g.signal.aborted)return;const w=b.index;!p[w]&&b.name&&(p[w]=
|
|
1568
|
+
`,s),this.onBeforeBeginLoading();const h=[],d={context:this._context,name:"",progress:{},index:0,count:s.length,totalProgress01:this._loadingProgress01},u=new CustomEvent("progress",{detail:d}),p=new Array,g=new AbortController;this._abortController=g;const f={files:s,abortSignal:g.signal,onLoadingProgress:b=>{var _;if(Ie&&console.debug("Loading progress: ",b),g.signal.aborted)return;const w=b.index;!p[w]&&b.name&&(p[w]=DL(b.name)),b.name=p[w],c&&((_=this._loadingView)==null||_.onLoadingUpdate(b)),d.name=b.name,d.progress=b.progress,this._loadingProgress01=lv(b),d.totalProgress01=this._loadingProgress01,this.dispatchEvent(u)},onLoadingFinished:(b,_,w)=>{Ie&&console.debug(`Finished loading "${_}" (aborted? ${g.signal.aborted})`),!g.signal.aborted&&w&&h.push({src:_,file:w})}},y=this.getAttribute("hash");y!=null&&(this._context.hash=y),this._context.alias=r,this._createContextPromise=this._context.create(f);const v=await this._createContextPromise;if(this.applyAttributes(),Ie&&console.warn(`--------------
|
|
1566
1569
|
Needle Engine: finished loading `+o+`
|
|
1567
1570
|
`,s,`Aborted? ${g.signal.aborted}`),g.signal.aborted){console.log("Loading finished but aborted...");return}if(this._loadId!==o){console.log("Load id changed during loading process");return}this._loadingProgress01=1,c&&v&&((t=this._loadingView)==null||t.onLoadingUpdate(1,"creating scene")),this._didFullyLoad=!0,this.classList.remove("loading"),this.classList.add("loading-finished"),this.dispatchEvent(new CustomEvent("loadfinished",{detail:{context:this._context,src:r,loadedFiles:h}}))}applyAttributes(){var e,t;if((e=this._context)!=null&&e.renderer){const r=Gw(this.toneMapping);r!==void 0&&(this._context.renderer.toneMapping=r);const l=this.getAttribute("tone-mapping-exposure");if(l!=null){const c=parseFloat(l);isNaN(c)||(this._context.renderer.toneMappingExposure=c)}}const s=this.getAttribute("background-blurriness");if(s!=null){const r=parseFloat(s);r!==void 0&&this._context&&(this._context.scene.backgroundBlurriness=r)}const o=this.getAttribute("background-color");if((t=this._context)!=null&&t.renderer&&typeof o=="string"&&o.length>0){const r=he.fromColorRepresentation(o);Ie&&console.debug("<needle-engine> background-color changed, str:",o,"\u2192",r),this._context.renderer.setClearColor(r,r.alpha),this.context.scene.background=null}}internalSetLoadingMessage(e){var t;(t=this._loadingView)==null||t.setMessage(e)}getSourceFiles(){const e=this.getAttribute("src");if(!e)return[];let t;Array.isArray(e)?t=e:e.startsWith("[")&&e.endsWith("]")?t=JSON.parse(e):e.includes(",")?t=e.split(","):t=[e];for(let s=t.length-1;s>=0;s--){const o=t[s];(o==="null"||o==="undefined"||o?.length<=0)&&t.splice(s,1)}return t}checkIfSourceHasChanged(e,t){if(e?.length!==t?.length||e==null&&t!==null||e!==null&&t==null)return!0;if(e!==null&&t!==null){for(let s=0;s<e?.length;s++)if(e[s]!==t[s])return!0}return!1}ensureLoadStartIsRegistered(){const e=this.getAttribute("loadstart");e&&this.registerEventFromAttribute("loadstart",e)}registerEventFromAttribute(e,t){const s=this._previouslyRegisteredMap.get(e);if(s&&(this._previouslyRegisteredMap.delete(e),this.removeEventListener(e,s)),typeof t=="string"&&t.length>0)try{const o=(0,eval)(t);typeof o=="function"&&(this._previouslyRegisteredMap.set(e,o),this.addEventListener(e,r=>o?.call(globalThis,this._context,r)))}catch(o){console.error("Error registering event "+e+'="'+t+`" failed with the following error:
|
|
1568
|
-
`,o)}}setPublicKey(){Ea&&Ea.length>0&&this.setAttribute("public-key",Ea)}setVersion(){ws.length>0&&this.setAttribute("version",ws)}getAROverlayContainer(){return this._overlay_ar.createOverlayContainer(this)}getVROverlayContainer(){for(let e=0;e<this.children.length;e++){const t=this.children[e];if(t.classList.contains("vr"))return t}return null}onEnterAR(e){var t;this.onSetupAR();const s=this.getAROverlayContainer();this._overlay_ar.onBegin(this._context,s,e),this.dispatchEvent(new CustomEvent("enter-ar",{detail:{session:e,context:this._context,htmlContainer:(t=this._overlay_ar)==null?void 0:t.ARContainer}}))}onExitAR(e){var t;this._overlay_ar.onEnd(this._context),this.onSetupDesktop(),this.dispatchEvent(new CustomEvent("exit-ar",{detail:{session:e,context:this._context,htmlContainer:(t=this._overlay_ar)==null?void 0:t.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}}))}onSetupAR(){this.classList.add(Jh),this.classList.remove(ed);const e=this.getAROverlayContainer();Ie&&console.warn("onSetupAR:",e),e&&(e.classList.add(Jh),e.classList.remove(ed)),this.foreachHtmlElement(t=>this.setupElementsForMode(t,QS))}onSetupVR(){this.classList.remove(Jh),this.classList.remove(ed),this.foreachHtmlElement(e=>this.setupElementsForMode(e,tC))}onSetupDesktop(){this.classList.remove(Jh),this.classList.add(ed);const e=this.getAROverlayContainer();e&&(e.classList.remove(Jh),e.classList.add(ed)),this.foreachHtmlElement(t=>this.setupElementsForMode(t,iC))}setupElementsForMode(e,t,s=null){var o,r;if(!(e===((r=(o=this._context)==null?void 0:o.renderer)==null?void 0:r.domElement)||e.id==="VRButton"||e.id==="ARButton"))if(e.classList.contains(t))e.style.visibility="visible",e.style.display==="none"&&(e.style.display="block");else for(const l of IL)e.classList.contains(l)&&(e.style.visibility="hidden",e.style.display="none")}foreachHtmlElement(e){for(let t=0;t<this.children.length;t++){const s=this.children[t];s.style&&e(s)}}onBeforeBeginLoading(){const e=this.getAttribute("dracoDecoderPath");e&&(Ie&&console.log("using custom draco decoder path",e),nx(e));const t=this.getAttribute("dracoDecoderType");t&&(Ie&&console.log("using custom draco decoder type",t),ox(t));const s=this.getAttribute("ktx2DecoderPath");s&&(Ie&&console.log("using custom ktx2 decoder path",s),rx(s))}}typeof window<"u"&&!window.customElements.get(eC)&&window.customElements.define(eC,cv);function jL(n){if(n.startsWith("blob:"))return"blob";const e=n.split("/");let t=e[e.length-1];const s=t.indexOf("?");s>0&&(t=t.substring(0,s));const o=t.indexOf("=");o>0&&(t=t.substring(o));const r=t.split(".").pop(),l=r?["glb","gltf","usdz","usd","fbx","obj","mtl"].indexOf(r.toLowerCase()):-1;if(r&&l>=0&&(t=t.substring(0,t.length-r.length-1)),t=decodeURIComponent(t),t.length>3){let c="",h=!1;const d=["(",")","[","]","{","}",":",";",",",".","!","?"];for(let u=0;u<t.length;u++){let p=t[u];(p==="_"||p==="-")&&(p=" "),!(p===" "&&c.length<=0||d.includes(p)||(c.length===0&&(p=p.toUpperCase()),h&&p===" "))&&(h&&(p=p.toUpperCase()),h=!1,c+=p,p===" "&&(h=!0))}return F()&&t!==c&&console.debug('Generated display name: "'+t+'" \u2192 "'+c+'"'),c.trim()}return F()&&console.debug("Loading: use default name",t),t}const DL=Object.freeze(Object.defineProperty({__proto__:null,NeedleEngineWebComponent:cv},Symbol.toStringTag,{value:"Module"}));function BL(){Ln.registerWaitForInteraction(()=>{const n=$P.getContext();n.addEventListener("statechange",()=>{setTimeout(()=>{const e=n.state;(e==="suspended"||e==="interrupted")&&n.resume().then(()=>{console.log("AudioContext resumed successfully")}).catch(t=>{console.log("Failed to resume AudioContext: "+t)})},500)})})}setTimeout(BL,1e3);const at=C("debugphysics"),hv=C("debugcolliderplacement"),dv=C("debugcollisions"),FL=C("showcolliders"),uv=C("debugraycasts"),_i=Symbol("needle component"),ti=Symbol("physics body"),sC=Symbol("rigidbody");globalThis.NEEDLE_USE_RAPIER=globalThis.NEEDLE_USE_RAPIER!==void 0?globalThis.NEEDLE_USE_RAPIER:!0,at&&console.log("Use Rapier",!0,globalThis.NEEDLE_USE_RAPIER),pe.registerCallback(me.ContextCreationStart,n=>{at&&console.log("Register rapier physics backend"),n.context.physics.engine=new nC(n.context)});const td=class Pm{constructor(e){a(this,"debugRenderColliders",!1),a(this,"debugRenderRaycasts",!1),a(this,"context"),a(this,"_initializePromise"),a(this,"_isInitialized",!1),a(this,"rapierRay"),a(this,"raycastVectorsBuffer",new Oi(()=>new S,10)),a(this,"rapierSphere",null),a(this,"rapierColliderArray",[]),a(this,"rapierIdentityRotation",{x:0,y:0,z:0,w:1}),a(this,"rapierForwardVector",{x:0,y:0,z:1}),a(this,"enabled",!1),a(this,"_tempPosition",new S),a(this,"_tempQuaternion",new V),a(this,"_tempScale",new S),a(this,"_tempMatrix",new se),a(this,"_isUpdatingPhysicsWorld",!1),a(this,"_world"),a(this,"_hasCreatedWorld",!1),a(this,"eventQueue"),a(this,"collisionHandler"),a(this,"objects",[]),a(this,"bodies",[]),a(this,"_meshCache",new Map),a(this,"_gravity",{x:0,y:-9.81,z:0}),a(this,"lines"),a(this,"_tempCenterPos",new S),a(this,"_tempCenterVec",new S),a(this,"_tempCenterQuaternion",new V),this.context=e}removeBody(e){var t,s,o;if(!e)return;this.validate();const r=e[ti];if(e[ti]=null,r&&this.world){const l=this.objects.findIndex(c=>c===e);if(l>=0){const c=this.bodies[l];if(this.bodies.splice(l,1),this.objects.splice(l,1),c instanceof A.RAPIER_PHYSICS.MODULE.Collider){const h=c;(t=this.world)==null||t.removeCollider(h,!0);const d=h.parent();d&&d.numColliders()<=0&&(d[_i]||(s=this.world)==null||s.removeRigidBody(d))}else c instanceof A.RAPIER_PHYSICS.MODULE.RigidBody&&(c.numColliders()<=0?(o=this.world)==null||o.removeRigidBody(c):F()&&(c.did_log_removing||setTimeout(()=>{c.numColliders()>0&&(c.did_log_removing=!0,console.warn("RapierPhysics: removing rigidbody with colliders from the physics world is not possible right now, please remove the colliders first"))},1)))}}}updateBody(e,t,s){if(this.validate(),!!this.enabled&&!(e.destroyed||!e.gameObject)&&!(!t&&!s))if(e.isCollider===!0)console.warn("TODO: implement updating collider position");else{const o=e,r=o[ti];r&&this.syncPhysicsBody(o.gameObject,r,t,s)}}updateProperties(e){if(this.validate(),e.isCollider){const t=e,s=t[ti];s&&(this.internalUpdateColliderProperties(t,s),t.sharedMaterial&&this.updatePhysicsMaterial(t))}else{const t=e,s=this.internal_getRigidbody(t);s&&this.internalUpdateRigidbodyProperties(t,s)}}addForce(e,t,s){this.validate();const o=this.internal_getRigidbody(e);o?o.addForce(t,s):console.warn("Rigidbody doesn't exist: can not apply force (does your object with the Rigidbody have a collider?)")}addImpulse(e,t,s){this.validate();const o=this.internal_getRigidbody(e);o?o.applyImpulse(t,s):console.warn("Rigidbody doesn't exist: can not apply impulse (does your object with the Rigidbody have a collider?)")}getLinearVelocity(e){this.validate();const t=this.internal_getRigidbody(e);return t?t.linvel():null}getAngularVelocity(e){this.validate();const t=this.internal_getRigidbody(e);return t?t.angvel():null}resetForces(e,t){this.validate();const s=this.internal_getRigidbody(e);s?.resetForces(t)}resetTorques(e,t){this.validate();const s=this.internal_getRigidbody(e);s?.resetTorques(t)}applyImpulse(e,t,s){this.validate();const o=this.internal_getRigidbody(e);o?o.applyImpulse(t,s):console.warn("Rigidbody doesn't exist: can not apply impulse (does your object with the Rigidbody have a collider?)")}wakeup(e){this.validate();const t=this.internal_getRigidbody(e);t?t.wakeUp():console.warn("Rigidbody doesn't exist: can not wake up (does your object with the Rigidbody have a collider?)")}isSleeping(e){this.validate();const t=this.internal_getRigidbody(e);return t?.isSleeping()}setAngularVelocity(e,t,s){this.validate();const o=this.internal_getRigidbody(e);o?o.setAngvel(t,s):console.warn("Rigidbody doesn't exist: can not set angular velocity (does your object with the Rigidbody have a collider?)")}setLinearVelocity(e,t,s){this.validate();const o=this.internal_getRigidbody(e);o?o.setLinvel(t,s):console.warn("Rigidbody doesn't exist: can not set linear velocity (does your object with the Rigidbody have a collider?)")}get isInitialized(){return this._isInitialized}async initialize(){return this._initializePromise||(this._initializePromise=this.internalInitialization()),this._initializePromise}async internalInitialization(){return C("__nophysics")?(console.warn("Physics are disabled"),!1):(at&&console.log("Initialize rapier physics engine"),this._hasCreatedWorld?(console.error("Invalid call to create physics world: world is already created"),!0):(this._hasCreatedWorld=!0,A.RAPIER_PHYSICS.MAYBEMODULE==null&&(at&&console.trace("Loading rapier physics engine"),await(await A.RAPIER_PHYSICS.load()).init()),at&&console.log("Physics engine initialized, creating world..."),this._world=new A.RAPIER_PHYSICS.MODULE.World(this._gravity),this.rapierRay=new A.RAPIER_PHYSICS.MODULE.Ray({x:0,y:0,z:0},{x:0,y:0,z:1}),this.enabled=!0,this._isInitialized=!0,at&&console.log("Physics world created"),!0))}validate(){this._isInitialized||at&&(this._lastWarnTime=this._lastWarnTime??0,Date.now()-this._lastWarnTime>1e3&&(this._lastWarnTime=Date.now(),console.warn("Physics engine is not initialized")))}raycast(e,t,s){var o;if(!this._isInitialized)return console.log("Physics engine is not initialized"),null;let r=s?.maxDistance,l=s?.solid;r===void 0&&(r=1/0),l===void 0&&(l=!0);const c=this.getPhysicsRay(this.rapierRay,e,t);if(!c)return null;(this.debugRenderRaycasts||uv)&&$.DrawRay(c.origin,c.dir,255,1);const h=(o=this.world)==null?void 0:o.castRay(c,r,l,s?.queryFilterFlags,s?.filterGroups,void 0,void 0,d=>{const u=d[_i];return s!=null&&s.filterPredicate?s.filterPredicate(u):s?.useIgnoreRaycastLayer!==!1?!(u!=null&&u.gameObject.layers.isEnabled(2)):!0});if(h){const d=c.pointAt(h.timeOfImpact),u=this.raycastVectorsBuffer.get();return u.set(d.x,d.y,d.z),{point:u,collider:h.collider[_i]}}return null}raycastAndGetNormal(e,t,s){var o;if(!this._isInitialized)return null;let r=s?.maxDistance,l=s?.solid;r===void 0&&(r=1/0),l===void 0&&(l=!0);const c=this.getPhysicsRay(this.rapierRay,e,t);if(!c)return null;(this.debugRenderRaycasts||uv)&&$.DrawRay(c.origin,c.dir,255,1);const h=(o=this.world)==null?void 0:o.castRayAndGetNormal(c,r,l,s?.queryFilterFlags,s?.filterGroups,void 0,void 0,d=>{const u=d[_i];return s!=null&&s.filterPredicate?s.filterPredicate(u):s?.useIgnoreRaycastLayer!==!1?!(u!=null&&u.gameObject.layers.isEnabled(2)):!0});if(h){const d=c.pointAt(h.timeOfImpact),u=h.normal,p=this.raycastVectorsBuffer.get(),g=this.raycastVectorsBuffer.get();return p.set(d.x,d.y,d.z),g.set(u.x,u.y,u.z),{point:p,normal:g,collider:h.collider[_i]}}return null}getPhysicsRay(e,t,s){var o,r,l;const c=(o=this.context)==null?void 0:o.mainCamera;if(t===void 0){const u=(r=this.context)==null?void 0:r.input.getPointerPosition(0);if(u)t=u;else return null}if(t.z===void 0){if(!c)return console.error("Can not perform raycast from 2d point - no main camera found"),null;const u=this.raycastVectorsBuffer.get();u.x=t.x,u.y=t.y,u.z=0,(u.x>1||u.y>1||u.y<-1||u.x<-1)&&(at&&console.warn("Converting screenspace to raycast space",u),(l=this.context)==null||l.input.convertScreenspaceToRaycastSpace(u)),u.unproject(c),t=u}const h=t;e.origin.x=h.x,e.origin.y=h.y,e.origin.z=h.z;const d=this.raycastVectorsBuffer.get();if(s)d.set(s.x,s.y,s.z);else{if(!c)return console.error("Can not perform raycast - no camera found"),null;d.set(e.origin.x,e.origin.y,e.origin.z);const u=ee(c);d.sub(u)}return d.normalize(),e.dir.x=d.x,e.dir.y=d.y,e.dir.z=d.z,e}sphereOverlap(e,t){return this.rapierColliderArray.length=0,this._isInitialized?this.world?(this.rapierSphere??(this.rapierSphere=new A.RAPIER_PHYSICS.MODULE.Ball(t)),this.rapierSphere.radius=t,(this.debugRenderRaycasts||uv)&&$.DrawWireSphere(e,t,3359999,1),this.world.intersectionsWithShape(e,this.rapierIdentityRotation,this.rapierSphere,s=>{const o=s[_i],r=new Ix(o.gameObject,o);return this.rapierColliderArray.push(r),!0},void 0,void 0,void 0,void 0,s=>s.isSensor()?!1:s[_i].gameObject.layers.isEnabled(2)==!1),this.rapierColliderArray):this.rapierColliderArray:this.rapierColliderArray}get world(){return this._world}get isUpdating(){return this._isUpdatingPhysicsWorld}get gravity(){var e;return((e=this.world)==null?void 0:e.gravity)??this._gravity}set gravity(e){this.world?this.world.gravity=e:this._gravity=e}clearCaches(){var e,t,s,o;this._meshCache.clear(),(e=this.eventQueue)!=null&&e.raw&&((t=this.eventQueue)==null||t.free()),(s=this.world)!=null&&s.bodies&&((o=this.world)==null||o.free())}async addBoxCollider(e,t){if(this._isInitialized||await this.initialize(),!e.activeAndEnabled)return;if(!this.enabled){at&&console.warn("Physics are disabled");return}const s=e.gameObject,o=Ge(s,this._tempPosition).multiply(t);o.multiplyScalar(.5),o.x<0&&(o.x=Math.abs(o.x)),o.y<0&&(o.y=Math.abs(o.y)),o.z<0&&(o.z=Math.abs(o.z));const r=1e-7;o.x<r&&(o.x=r),o.y<r&&(o.y=r),o.z<r&&(o.z=r);const l=A.RAPIER_PHYSICS.MODULE.ColliderDesc.cuboid(o.x,o.y,o.z);this.createCollider(e,l)}async addSphereCollider(e){if(this._isInitialized||await this.initialize(),!e.activeAndEnabled)return;if(!this.enabled){at&&console.warn("Physics are disabled");return}const t=A.RAPIER_PHYSICS.MODULE.ColliderDesc.ball(.5);this.createCollider(e,t),this.updateProperties(e)}async addCapsuleCollider(e,t,s){if(this._isInitialized||await this.initialize(),!e.activeAndEnabled)return;if(!this.enabled){at&&console.warn("Physics are disabled");return}const o=e.gameObject,r=Ge(o,this._tempPosition);r.x=Math.abs(r.x),r.y=Math.abs(r.y);const l=s*r.x;t=Math.max(t,l*2);const c=W.clamp(t*.5*r.y-s*r.x,0,Number.MAX_SAFE_INTEGER),h=A.RAPIER_PHYSICS.MODULE.ColliderDesc.capsule(c,l);this.createCollider(e,h)}async addMeshCollider(e,t,s,o){var r,l,c;let h=t.geometry;if(!h){at&&console.warn("Missing mesh geometry",t.name);return}(l=(r=h.index)==null?void 0:r.array)!=null&&l.length||(console.warn(`Your MeshCollider is missing vertices or indices in the assined mesh "${t.name}". Consider providing an indexed geometry.`),h=gO(h));let d=null;const u=h.getAttribute("position");if(u instanceof Iv){const y=u.count;d=new Float32Array(y*3);for(let v=0;v<y;v++){const b=u.getX(v),_=u.getY(v),w=u.getZ(v);d[v*3]=b,d[v*3+1]=_,d[v*3+2]=w}}else d=u.array;if(await this.initialize(),!this.enabled){at&&console.warn("Physics are disabled");return}if(!e.activeAndEnabled)return;const p=(c=h.index)==null?void 0:c.array,g=e.gameObject.worldScale.clone();if(o&&g.multiply(o),Math.abs(g.x-1)>1e-4||Math.abs(g.y-1)>1e-4||Math.abs(g.z-1)>1e-4){const y=`${h.uuid}_${g.x}_${g.y}_${g.z}_${s}`;if(this._meshCache.has(y))at&&console.warn("Use cached mesh collider"),d=this._meshCache.get(y);else{(at||F())&&console.debug(`[Performance] Your MeshCollider "${e.name}" is scaled: consider applying the scale to the collider mesh instead (${g.x}, ${g.y}, ${g.z})`);const v=new Float32Array(d.length);for(let b=0;b<d.length;b+=3)v[b]=d[b]*g.x,v[b+1]=d[b+1]*g.y,v[b+2]=d[b+2]*g.z;d=v,this._meshCache.set(y,v)}}const f=s?A.RAPIER_PHYSICS.MODULE.ColliderDesc.convexHull(d):A.RAPIER_PHYSICS.MODULE.ColliderDesc.trimesh(d,p);f&&this.createCollider(e,f)}updatePhysicsMaterial(e){if(!e)return;const t=e.sharedMaterial,s=e[ti];if(s&&t){if(t.bounciness!==void 0&&s.setRestitution(t.bounciness),t.bounceCombine!==void 0)switch(t.bounceCombine){case xt.Average:s.setRestitutionCombineRule(A.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Average);break;case xt.Maximum:s.setRestitutionCombineRule(A.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Max);break;case xt.Minimum:s.setRestitutionCombineRule(A.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Min);break;case xt.Multiply:s.setRestitutionCombineRule(A.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Multiply);break}if(t.dynamicFriction!==void 0&&s.setFriction(t.dynamicFriction),t.frictionCombine!==void 0)switch(t.frictionCombine){case xt.Average:s.setFrictionCombineRule(A.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Average);break;case xt.Maximum:s.setFrictionCombineRule(A.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Max);break;case xt.Minimum:s.setFrictionCombineRule(A.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Min);break;case xt.Multiply:s.setFrictionCombineRule(A.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Multiply);break}}}getBody(e){return e?e[ti]:null}getComponent(e){return e?e[_i]:null}createCollider(e,t){var s;if(!this.world)throw new Error("Physics world not initialized");const o=this._tempMatrix;let r;e.attachedRigidbody?r=this.getRigidbody(e,this._tempMatrix):(at&&console.log("Create collider without rigidbody",e.name),o.makeRotationFromQuaternion(Se(e.gameObject)),o.setPosition(ee(e.gameObject))),o.decompose(this._tempPosition,this._tempQuaternion,this._tempScale),this.tryApplyCenter(e,this._tempPosition),t.setTranslation(this._tempPosition.x,this._tempPosition.y,this._tempPosition.z),t.setRotation(this._tempQuaternion),t.setSensor(e.isTrigger);const l=e.sharedMaterial;if(l){if(l.bounciness!==void 0&&t.setRestitution(l.bounciness),l.bounceCombine!==void 0)switch(l.bounceCombine){case xt.Average:t.setRestitutionCombineRule(A.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Average);break;case xt.Maximum:t.setRestitutionCombineRule(A.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Max);break;case xt.Minimum:t.setRestitutionCombineRule(A.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Min);break;case xt.Multiply:t.setRestitutionCombineRule(A.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Multiply);break}if(l.dynamicFriction!==void 0&&t.setFriction(l.dynamicFriction),l.frictionCombine!==void 0)switch(l.frictionCombine){case xt.Average:t.setFrictionCombineRule(A.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Average);break;case xt.Maximum:t.setFrictionCombineRule(A.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Max);break;case xt.Minimum:t.setFrictionCombineRule(A.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Min);break;case xt.Multiply:t.setFrictionCombineRule(A.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Multiply);break}}((s=e.attachedRigidbody)==null?void 0:s.autoMass)===!1&&(t.setDensity(1e-6),t.setMass(1e-6));try{const c=this.world.createCollider(t,r);return c[_i]=e,e[ti]=c,c.setActiveEvents(A.RAPIER_PHYSICS.MODULE.ActiveEvents.COLLISION_EVENTS),c.setActiveCollisionTypes(A.RAPIER_PHYSICS.MODULE.ActiveCollisionTypes.ALL),this.objects.push(e),this.bodies.push(c),this.updateColliderCollisionGroups(e),c}catch(c){return console.error('Error creating collider "'+e.name+`"
|
|
1569
|
-
Error:`,c),null}}updateColliderCollisionGroups(e){const t=e[ti],s=e.membership;let o=0;if(s==null)o=65535;else for(let c=0;c<s.length;c++){const h=s[c];h>31?console.error(`Rapier only supports 32 layers, layer ${h} is not supported`):o|=1<<Math.floor(h)}const r=e.filter;let l=0;if(r==null)l=65535;else for(let c=0;c<r.length;c++){const h=r[c];h>31?console.error(`Rapier only supports 32 layers, layer ${h} is not supported`):l|=1<<Math.floor(h)}t.setCollisionGroups(o<<16|l)}getRigidbody(e,t){if(!this.world)throw new Error("Physics world not initialized");let s=null;if(e.attachedRigidbody){const o=e.attachedRigidbody;if(s=o[ti],!s){const r=o.isKinematic&&!hv;at&&console.log("Create rigidbody",r);const l=r?A.RAPIER_PHYSICS.MODULE.RigidBodyDesc.kinematicPositionBased():A.RAPIER_PHYSICS.MODULE.RigidBodyDesc.dynamic(),c=ee(e.attachedRigidbody.gameObject);l.setTranslation(c.x,c.y,c.z),l.setRotation(Se(e.attachedRigidbody.gameObject)),l.centerOfMass=new A.RAPIER_PHYSICS.MODULE.Vector3(o.centerOfMass.x,o.centerOfMass.y,o.centerOfMass.z),s=this.world.createRigidBody(l),this.bodies.push(s),this.objects.push(o)}s[_i]=o,o[ti]=s,this.internalUpdateRigidbodyProperties(o,s),this.getRigidbodyRelativeMatrix(e.gameObject,o.gameObject,t),e[sC]=s}else{const o=A.RAPIER_PHYSICS.MODULE.RigidBodyDesc.kinematicPositionBased(),r=ee(e.gameObject);o.setTranslation(r.x,r.y,r.z),o.setRotation(Se(e.gameObject)),s=this.world.createRigidBody(o),t.identity(),s[_i]=null}return s}internal_getRigidbody(e){return e.isCollider===!0?e[sC]:e[ti]}internalUpdateColliderProperties(e,t){const s=t.shape;let o=!1;switch(s.type){case A.RAPIER_PHYSICS.MODULE.ShapeType.Ball:{const g=s,f=e,y=e.gameObject,v=Ge(y,this._tempPosition),b=Math.abs(f.radius*v.x);o=g.radius!==b,g.radius=b,o&&t.setShape(g);break}case A.RAPIER_PHYSICS.MODULE.ShapeType.Cuboid:const r=s,l=e,c=e.gameObject,h=Ge(c,this._tempPosition),d=Math.abs(l.size.x*.5*h.x),u=Math.abs(l.size.y*.5*h.y),p=Math.abs(l.size.z*.5*h.z);o=r.halfExtents.x!==d||r.halfExtents.y!==u||r.halfExtents.z!==p,r.halfExtents.x=d,r.halfExtents.y=u,r.halfExtents.z=p,o&&t.setShape(r);break}if(o){const r=e.attachedRigidbody;if(r!=null&&r.autoMass){const l=this.getBody(r);l?.recomputeMassPropertiesFromColliders()}}this.updateColliderCollisionGroups(e),e.isTrigger!==t.isSensor()&&t.setSensor(e.isTrigger)}internalUpdateRigidbodyProperties(e,t){if(t.enableCcd(e.collisionDetectionMode!==ku.Discrete),t.setLinearDamping(e.drag),t.setAngularDamping(e.angularDrag),t.setGravityScale(e.useGravity?e.gravityScale:0,!0),e.dominanceGroup<=127&&e.dominanceGroup>=-127?t.setDominanceGroup(Math.floor(e.dominanceGroup)):t.setDominanceGroup(0),e.autoMass){t.setAdditionalMass(0,!1);for(let s=0;s<t.numColliders();s++)t.collider(s).setDensity(1);t.recomputeMassPropertiesFromColliders()}else{t.setAdditionalMass(e.mass,!1);for(let s=0;s<t.numColliders();s++)t.collider(s).setDensity(1e-7);t.recomputeMassPropertiesFromColliders()}t.setEnabledRotations(!e.lockRotationX,!e.lockRotationY,!e.lockRotationZ,!1),t.setEnabledTranslations(!e.lockPositionX,!e.lockPositionY,!e.lockPositionZ,!1),e.isKinematic?t.setBodyType(A.RAPIER_PHYSICS.MODULE.RigidBodyType.KinematicPositionBased,!1):t.setBodyType(A.RAPIER_PHYSICS.MODULE.RigidBodyType.Dynamic,!1)}step(e){if(this.world&&this.enabled){if(this._isUpdatingPhysicsWorld=!0,this.eventQueue||(this.eventQueue=new A.RAPIER_PHYSICS.MODULE.EventQueue(!1)),e===void 0||e<=0){this._isUpdatingPhysicsWorld=!1;return}else e!==void 0&&(this.world.timestep=W.lerp(this.world.timestep,e,.8));try{this.world.step(this.eventQueue)}catch(t){console.warn("Error running physics step",t)}this._isUpdatingPhysicsWorld=!1}}postStep(){this.world&&this.enabled&&(this._isUpdatingPhysicsWorld=!0,this.syncObjects(),this._isUpdatingPhysicsWorld=!1,this.eventQueue&&!this.collisionHandler&&(this.collisionHandler=new UL(this.world,this.eventQueue)),this.collisionHandler&&(this.collisionHandler.handleCollisionEvents(),this.collisionHandler.update()),this.updateDebugRendering(this.world))}updateDebugRendering(e){var t,s,o,r;if(at||hv||FL||this.debugRenderColliders===!0){if(!this.lines){const c=new Av({color:7855479,fog:!1}),h=new Vs;this.lines=new Ev(h,c),this.lines.layers.disableAll(),this.lines.layers.enable(2)}this.lines.parent!==((t=this.context)==null?void 0:t.scene)&&((s=this.context)==null||s.scene.add(this.lines));const l=e.debugRender();this.lines.geometry.setAttribute("position",new _t(l.vertices,3)),this.lines.geometry.setAttribute("color",new _t(l.colors,4)),(this.context.time.frame%30===0||((o=this.lines.geometry.boundingSphere)==null?void 0:o.radius)===0)&&this.lines.geometry.computeBoundingSphere()}else this.lines&&((r=this.context)==null||r.scene.remove(this.lines))}syncObjects(){if(!hv)for(let e=0;e<this.bodies.length;e++){const t=this.objects[e],s=this.bodies[e],o=t;if(o?.isCollider===!0&&!o.attachedRigidbody){const h=s.parent();h?this.syncPhysicsBody(t.gameObject,h,!0,!0):this.syncPhysicsBody(t.gameObject,s,!0,!0);continue}const r=s.translation(),l=s.rotation();if(Number.isNaN(r.x)||Number.isNaN(l.x)){!o.__COLLIDER_NAN&&F()&&(console.warn("Collider has NaN values",o.name,o.gameObject,s),o.__COLLIDER_NAN=!0);continue}const c=t.center;if(c&&c.isVector3){this._tempQuaternion.set(l.x,l.y,l.z,l.w);const h=this._tempPosition.copy(c).applyQuaternion(this._tempQuaternion),d=Ge(t.gameObject);h.multiply(d),r.x-=h.x,r.y-=h.y,r.z-=h.z}br(t.gameObject,r.x,r.y,r.z),dg(t.gameObject,l.x,l.y,l.z,l.w)}}syncPhysicsBody(e,t,s,o){if(t instanceof A.RAPIER_PHYSICS.MODULE.RigidBody){const r=ee(e,this._tempPosition),l=Se(e,this._tempQuaternion);switch(t.bodyType()){case A.RAPIER_PHYSICS.MODULE.RigidBodyType.Fixed:case A.RAPIER_PHYSICS.MODULE.RigidBodyType.KinematicPositionBased:case A.RAPIER_PHYSICS.MODULE.RigidBodyType.KinematicVelocityBased:s&&t.setNextKinematicTranslation(r),o&&t.setNextKinematicRotation(l);break;default:s&&t.setTranslation(r,!1),o&&t.setRotation(l,!1);break}}else if(t instanceof A.RAPIER_PHYSICS.MODULE.Collider){e.matrixWorldNeedsUpdate&&e.updateWorldMatrix(!0,!1),e.matrixWorld.decompose(this._tempPosition,this._tempQuaternion,this._tempScale);const r=this._tempPosition,l=this._tempQuaternion,c=t[_i];if(this.tryApplyCenter(c,r),s){const h=t.translation();(h.x!==r.x||h.y!==r.y||h.z!==r.z)&&t.setTranslation(r)}if(o){const h=t.rotation();(h.x!==l.x||h.y!==l.y||h.z!==l.z||h.w!==l.w)&&t.setRotation(l)}}}tryApplyCenter(e,t){const s=e.center;s&&e.gameObject&&(s.x!==0||s.y!==0||s.z!==0)&&(this._tempCenterPos.x=s.x,this._tempCenterPos.y=s.y,this._tempCenterPos.z=s.z,Ge(e.gameObject,this._tempCenterVec),this._tempCenterPos.multiply(this._tempCenterVec),e.attachedRigidbody?this._tempCenterPos.applyQuaternion(e.gameObject.quaternion):(Se(e.gameObject,this._tempCenterQuaternion),this._tempCenterPos.applyQuaternion(this._tempCenterQuaternion)),t.x+=this._tempCenterPos.x,t.y+=this._tempCenterPos.y,t.z+=this._tempCenterPos.z)}getRigidbodyRelativeMatrix(e,t,s,o){if(o===void 0&&(o=Pm._matricesBuffer,o.length=0),e===t){const r=Ge(e,this._tempPosition);s.makeScale(r.x,r.y,r.z);for(let l=o.length-1;l>=0;l--)s.multiply(o[l]);return s}return o.push(e.matrix),e.parent&&this.getRigidbodyRelativeMatrix(e.parent,t,s,o),s}addFixedJoint(e,t){if(!this.world){console.error("Physics world not initialized");return}const s=e[ti],o=t[ti];this.calculateJointRelativeMatrices(e.gameObject,t.gameObject,this._tempMatrix),this._tempMatrix.decompose(this._tempPosition,this._tempQuaternion,this._tempScale);const r=A.RAPIER_PHYSICS.MODULE.JointData.fixed(Pm.centerConnectionPos,Pm.centerConnectionRot,this._tempPosition,this._tempQuaternion),l=this.world.createImpulseJoint(r,s,o,!0);at&&console.log("ADD FIXED JOINT",l)}addHingeJoint(e,t,s,o){if(!this.world){console.error("Physics world not initialized");return}const r=e[ti],l=t[ti];this.calculateJointRelativeMatrices(e.gameObject,t.gameObject,this._tempMatrix),this._tempMatrix.decompose(this._tempPosition,this._tempQuaternion,this._tempScale);const c=A.RAPIER_PHYSICS.MODULE.JointData.revolute(s,this._tempPosition,o),h=this.world.createImpulseJoint(c,r,l,!0);at&&console.log("ADD HINGE JOINT",h)}calculateJointRelativeMatrices(e,t,s){e.updateWorldMatrix(!0,!1),t.updateWorldMatrix(!0,!1);const o=e.matrixWorld,r=t.matrixWorld;o.elements[0]=1,o.elements[5]=1,o.elements[10]=1,r.elements[0]=1,r.elements[5]=1,r.elements[10]=1,s.copy(r).premultiply(o.invert()).invert()}};a(td,"_didLoadPhysicsEngine",!1),a(td,"_matricesBuffer",[]),a(td,"centerConnectionPos",{x:0,y:0,z:0}),a(td,"centerConnectionRot",{x:0,y:0,z:0,w:1});let nC=td;class UL{constructor(e,t){a(this,"world"),a(this,"eventQueue"),a(this,"activeCollisions",[]),a(this,"activeCollisionsStay",[]),a(this,"activeTriggers",[]),this.world=e,this.eventQueue=t}handleCollisionEvents(){this.eventQueue&&this.world&&this.eventQueue.drainCollisionEvents((e,t,s)=>{const o=this.world.getCollider(e),r=this.world.getCollider(t);if(!o||!r)return;const l=o[_i],c=r[_i];dv&&console.log("EVT",l.name,c.name,s,o,r),l&&c&&(s?(this.onCollisionStarted(l,o,c,r),this.onCollisionStarted(c,r,l,o)):(this.onCollisionEnded(l,c),this.onCollisionEnded(c,l)))})}update(){this.onHandleCollisionStay()}onCollisionStarted(e,t,s,o){let r=null;if(e.isTrigger||s.isTrigger)Ar(e.gameObject,l=>{l.onTriggerEnter&&!l.destroyed&&l.onTriggerEnter(s),this.activeTriggers.push({collider:e,component:l,otherCollider:s})});else{const l=e.gameObject;this.world.contactPair(t,o,(c,h)=>{Ar(l,d=>{var u;if(d.destroyed)return;const p=d.onCollisionEnter||d.onCollisionStay||d.onCollisionExit;if(p||dv){if(!r){const g=[],f=c.normal();s instanceof Fo&&s.convex&&(f.x=-f.x,f.y=-f.y,f.z=-f.z);for(let y=0;y<c.numSolverContacts();y++){const v=c.solverContactPoint(y),b=c.contactImpulse(y);if(v){const _=c.contactDist(y),w=c.solverContactFriction(y),x=c.solverContactTangentVelocity(y),k=new Ex(v,_,f,b,w,x);g.push(k),dv&&$.DrawDirection(v,f,16711680,3,!0)}}r=new Ax(l,s,g)}if(p){const g={collider:e,component:d,collision:r};this.activeCollisions.push(g),d.onCollisionStay&&this.activeCollisionsStay.push(g),(u=d.onCollisionEnter)==null||u.call(d,r)}}})})}}onHandleCollisionStay(){for(const e of this.activeCollisionsStay){const t=e.component;if(!t.destroyed&&t.activeAndEnabled&&t.onCollisionStay){if(e.collision.collider.destroyed)continue;const s=e.collision;t.onCollisionStay(s)}}for(const e of this.activeTriggers){const t=e.component;if(!t.destroyed&&t.activeAndEnabled&&t.onTriggerStay){const s=e.otherCollider;if(s.destroyed)continue;t.onTriggerStay(s)}}}onCollisionEnded(e,t){if(!(e.destroyed||t.destroyed)){for(let s=0;s<this.activeCollisions.length;s++){const o=this.activeCollisions[s],r=o.collider;if(r.destroyed||o.collision.collider.destroyed){this.activeCollisions.splice(s,1),s--;continue}if(r===e&&o.collision.collider===t){const l=o.component;if(this.activeCollisions.splice(s,1),s--,l.activeAndEnabled&&l.onCollisionExit){const c=o.collision;l.onCollisionExit(c)}}}for(let s=0;s<this.activeCollisionsStay.length;s++){const o=this.activeCollisionsStay[s],r=o.collider;if(r.destroyed||o.collision.collider.destroyed){this.activeCollisionsStay.splice(s,1),s--;continue}if(r===e&&o.collision.collider===t){const l=o.component;if(this.activeCollisionsStay.splice(s,1),s--,l.activeAndEnabled&&l.onCollisionExit){const c=o.collision;l.onCollisionExit(c)}}}for(let s=0;s<this.activeTriggers.length;s++){const o=this.activeTriggers[s],r=o.collider;if(r.destroyed||o.otherCollider.destroyed){this.activeTriggers.splice(s,1),s--;continue}if(r===e&&o.otherCollider===t){const l=o.component;if(this.activeTriggers.splice(s,1),s--,l.activeAndEnabled&&l.onTriggerExit){const c=o.otherCollider;l.onTriggerExit(c)}}}}}}class zL{static async createComparisonScene(e){const{files:t}=e,s=await Promise.all(t.map(y=>new ce(y).loadAssetAsync())),o=new xi;let r=0;for(const y of s)if(y instanceof E){y.position.y=r,o.add(y);const v=si([y]);r+=v.getSize(new S).y,r+=.1}const l=new we(20);o.add(l);const c=e.environment||"https://dl.polyhaven.org/file/ph-assets/HDRIs/exr/1k/studio_small_09_1k.exr";{let y=null;if(c.endsWith(".hdr")){const v=(await import("./three-examples-DaDLBuy6.min.js").then(b=>b.RGBELoader$1)).RGBELoader;y=new v}else if(c.endsWith(".exr")){const v=(await import("./three-examples-DaDLBuy6.min.js").then(b=>b.EXRLoader$1)).EXRLoader;y=new v}if(y){const v=await y.loadAsync(c).catch(b=>(console.error(b),null));v&&(v.mapping=kn,v.needsUpdate=!0,o.background=v,o.environment=v,o.backgroundBlurriness=.75)}else console.warn("Unsupported environment map format",c)}const h=si(o.children),d=h.getCenter(new S),u=h.getSize(new S),p=Math.max(u.x,u.y,u.z)/(2*Math.tan(Math.PI*l.fov/360));l.position.set(d.x,d.y,p),l.lookAt(d);const g=new $v(l,e.domElement||document.body);g.target=d,g.update();const f=(e.domElement||document.body).getBoundingClientRect();return l.aspect=f.width/f.height,l.updateProjectionMatrix(),{scene:o,camera:l}}}let pv=0;function oC(n){n?pv++:pv--}function NL(){return pv>0}const WL={binary:!0,animations:!0};async function VL(n){if(!n.context)throw new Error("No context provided to exportAsGLTF");n.scene||(n.scene=n.context.scene);const e={...WL,...n},{context:t}=e,s=new Hv;s.register(c=>new l1(c)),s.register(c=>new fE(c)),s.register(c=>new Kx(c)),v0(s,e.context);const o={binary:e.binary,animations:HL(t,e.scene,[])},r=new $L;console.debug("Exporting GLTF",o),r.onBeforeExport(e),oC(!0);const l=await s.parseAsync(e.scene,o).catch(c=>(console.error(c),null));if(oC(!1),r.onAfterExport(e),!l)throw new Error("Failed to export GLTF");if(e.downloadAs!=null){let c=null;if(l instanceof ArrayBuffer?c=new Blob([l],{type:"application/octet-stream"}):console.error("Can not download GLTF as a blob",l),c){const h=URL.createObjectURL(c),d=document.createElement("a");d.href=h;let u=e.downloadAs;!u.endsWith(".glb")&&!u.endsWith(".gltf")&&(u+=e.binary?".glb":".gltf"),d.download=u,d.click()}}return l}const rC=Symbol("needle:weight");class $L{constructor(){a(this,"_undo",[])}onBeforeExport(e){e.context.animations.mixers.forEach(t=>{const s=Ga.tryGetActionsFromMixer(t);if(s)for(let o=0;o<s.length;o++){const r=s[o];r[rC]=r.weight,r.weight=0,this._undo.push(()=>{r.weight=r[rC]})}t.update(0)}),e.context.scene.traverse(t=>{if(!p0(t)){const s=t.parent;s&&(t.removeFromParent(),this._undo.push(()=>s.add(t)))}})}onAfterExport(e){this._undo.forEach(t=>t()),this._undo.length=0}}function HL(n,e,t){n.animations.mixers.forEach(o=>{const r=Ga.tryGetActionsFromMixer(o);if(r)for(let l=0;l<r.length;l++){const c=r[l].getClip();t.push(c)}}),Array.isArray(e)||(e=[e]);for(const o of e)Ga.tryGetAnimationClipsFromObjectHierarchy(o,t);const s=new Set(t);return Array.from(s)}const aC="needle-button",mv=F();var fa,ya,va,wi,Ds,Dl,pm,lC,cC,mm;class gv extends HTMLElement{constructor(){super(),Us(this,pm),Us(this,fa),Us(this,ya),Us(this,va),Us(this,wi),Us(this,Ds),Us(this,Dl),Us(this,mm,e=>{mv&&console.log("Needle Button clicked"),!e.defaultPrevented&&ge(this,wi)&&ge(this,wi).click()}),this.removeEventListener("click",ge(this,mm)),this.addEventListener("click",ge(this,mm))}attributeChangedCallback(e,t,s){dd(this,pm,lC).call(this)}}fa=new WeakMap,ya=new WeakMap,va=new WeakMap,wi=new WeakMap,Ds=new WeakMap,Dl=new WeakMap,pm=new WeakSet,lC=function(){var n,e;if((n=ge(this,wi))==null||n.remove(),this.getAttribute("ar")!=null)ge(this,Ds)??zs(this,Ds,new ml),zs(this,wi,ge(this,Ds).createARButton());else if(this.getAttribute("vr")!=null)ge(this,Ds)??zs(this,Ds,new ml),zs(this,wi,ge(this,Ds).createVRButton());else if(this.getAttribute("quicklook")!=null)ge(this,Ds)??zs(this,Ds,new ml),zs(this,wi,ge(this,Ds).createQuicklookButton());else{mv?console.warn("No button type specified for <needle-button>. Use either ar, vr or quicklook attribute."):console.debug("No button type specified for <needle-button>. Use either ar, vr or quicklook attribute.");return}ge(this,fa)??zs(this,fa,this.attachShadow({mode:"open"})),ge(this,ya)??zs(this,ya,document.createElement("slot")),ge(this,va)??zs(this,va,document.createElement("style")),ge(this,va).innerHTML=`
|
|
1571
|
+
`,o)}}setPublicKey(){Ea&&Ea.length>0&&this.setAttribute("public-key",Ea)}setVersion(){ws.length>0&&this.setAttribute("version",ws)}getAROverlayContainer(){return this._overlay_ar.createOverlayContainer(this)}getVROverlayContainer(){for(let e=0;e<this.children.length;e++){const t=this.children[e];if(t.classList.contains("vr"))return t}return null}onEnterAR(e){var t;this.onSetupAR();const s=this.getAROverlayContainer();this._overlay_ar.onBegin(this._context,s,e),this.dispatchEvent(new CustomEvent("enter-ar",{detail:{session:e,context:this._context,htmlContainer:(t=this._overlay_ar)==null?void 0:t.ARContainer}}))}onExitAR(e){var t;this._overlay_ar.onEnd(this._context),this.onSetupDesktop(),this.dispatchEvent(new CustomEvent("exit-ar",{detail:{session:e,context:this._context,htmlContainer:(t=this._overlay_ar)==null?void 0:t.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}}))}onSetupAR(){this.classList.add(Jh),this.classList.remove(ed);const e=this.getAROverlayContainer();Ie&&console.warn("onSetupAR:",e),e&&(e.classList.add(Jh),e.classList.remove(ed)),this.foreachHtmlElement(t=>this.setupElementsForMode(t,QS))}onSetupVR(){this.classList.remove(Jh),this.classList.remove(ed),this.foreachHtmlElement(e=>this.setupElementsForMode(e,tC))}onSetupDesktop(){this.classList.remove(Jh),this.classList.add(ed);const e=this.getAROverlayContainer();e&&(e.classList.remove(Jh),e.classList.add(ed)),this.foreachHtmlElement(t=>this.setupElementsForMode(t,iC))}setupElementsForMode(e,t,s=null){var o,r;if(!(e===((r=(o=this._context)==null?void 0:o.renderer)==null?void 0:r.domElement)||e.id==="VRButton"||e.id==="ARButton"))if(e.classList.contains(t))e.style.visibility="visible",e.style.display==="none"&&(e.style.display="block");else for(const l of LL)e.classList.contains(l)&&(e.style.visibility="hidden",e.style.display="none")}foreachHtmlElement(e){for(let t=0;t<this.children.length;t++){const s=this.children[t];s.style&&e(s)}}onBeforeBeginLoading(){const e=this.getAttribute("dracoDecoderPath");e&&(Ie&&console.log("using custom draco decoder path",e),nx(e));const t=this.getAttribute("dracoDecoderType");t&&(Ie&&console.log("using custom draco decoder type",t),ox(t));const s=this.getAttribute("ktx2DecoderPath");s&&(Ie&&console.log("using custom ktx2 decoder path",s),rx(s))}}typeof window<"u"&&!window.customElements.get(eC)&&window.customElements.define(eC,cv);function DL(n){if(n.startsWith("blob:"))return"blob";const e=n.split("/");let t=e[e.length-1];const s=t.indexOf("?");s>0&&(t=t.substring(0,s));const o=t.indexOf("=");o>0&&(t=t.substring(o));const r=t.split(".").pop(),l=r?["glb","gltf","usdz","usd","fbx","obj","mtl"].indexOf(r.toLowerCase()):-1;if(r&&l>=0&&(t=t.substring(0,t.length-r.length-1)),t=decodeURIComponent(t),t.length>3){let c="",h=!1;const d=["(",")","[","]","{","}",":",";",",",".","!","?"];for(let u=0;u<t.length;u++){let p=t[u];(p==="_"||p==="-")&&(p=" "),!(p===" "&&c.length<=0||d.includes(p)||(c.length===0&&(p=p.toUpperCase()),h&&p===" "))&&(h&&(p=p.toUpperCase()),h=!1,c+=p,p===" "&&(h=!0))}return F()&&t!==c&&console.debug('Generated display name: "'+t+'" \u2192 "'+c+'"'),c.trim()}return F()&&console.debug("Loading: use default name",t),t}const BL=Object.freeze(Object.defineProperty({__proto__:null,NeedleEngineWebComponent:cv},Symbol.toStringTag,{value:"Module"}));function FL(){Ln.registerWaitForInteraction(()=>{const n=$P.getContext();n.addEventListener("statechange",()=>{setTimeout(()=>{const e=n.state;(e==="suspended"||e==="interrupted")&&n.resume().then(()=>{console.log("AudioContext resumed successfully")}).catch(t=>{console.log("Failed to resume AudioContext: "+t)})},500)})})}setTimeout(FL,1e3);const at=C("debugphysics"),hv=C("debugcolliderplacement"),dv=C("debugcollisions"),UL=C("showcolliders"),uv=C("debugraycasts"),_i=Symbol("needle component"),ti=Symbol("physics body"),sC=Symbol("rigidbody");globalThis.NEEDLE_USE_RAPIER=globalThis.NEEDLE_USE_RAPIER!==void 0?globalThis.NEEDLE_USE_RAPIER:!0,at&&console.log("Use Rapier",!0,globalThis.NEEDLE_USE_RAPIER),pe.registerCallback(me.ContextCreationStart,n=>{at&&console.log("Register rapier physics backend"),n.context.physics.engine=new nC(n.context)});const td=class Pm{constructor(e){a(this,"debugRenderColliders",!1),a(this,"debugRenderRaycasts",!1),a(this,"context"),a(this,"_initializePromise"),a(this,"_isInitialized",!1),a(this,"rapierRay"),a(this,"raycastVectorsBuffer",new Oi(()=>new S,10)),a(this,"rapierSphere",null),a(this,"rapierColliderArray",[]),a(this,"rapierIdentityRotation",{x:0,y:0,z:0,w:1}),a(this,"rapierForwardVector",{x:0,y:0,z:1}),a(this,"enabled",!1),a(this,"_tempPosition",new S),a(this,"_tempQuaternion",new V),a(this,"_tempScale",new S),a(this,"_tempMatrix",new se),a(this,"_isUpdatingPhysicsWorld",!1),a(this,"_world"),a(this,"_hasCreatedWorld",!1),a(this,"eventQueue"),a(this,"collisionHandler"),a(this,"objects",[]),a(this,"bodies",[]),a(this,"_meshCache",new Map),a(this,"_gravity",{x:0,y:-9.81,z:0}),a(this,"lines"),a(this,"_tempCenterPos",new S),a(this,"_tempCenterVec",new S),a(this,"_tempCenterQuaternion",new V),this.context=e}removeBody(e){var t,s,o;if(!e)return;this.validate();const r=e[ti];if(e[ti]=null,r&&this.world){const l=this.objects.findIndex(c=>c===e);if(l>=0){const c=this.bodies[l];if(this.bodies.splice(l,1),this.objects.splice(l,1),c instanceof A.RAPIER_PHYSICS.MODULE.Collider){const h=c;(t=this.world)==null||t.removeCollider(h,!0);const d=h.parent();d&&d.numColliders()<=0&&(d[_i]||(s=this.world)==null||s.removeRigidBody(d))}else c instanceof A.RAPIER_PHYSICS.MODULE.RigidBody&&(c.numColliders()<=0?(o=this.world)==null||o.removeRigidBody(c):F()&&(c.did_log_removing||setTimeout(()=>{c.numColliders()>0&&(c.did_log_removing=!0,console.warn("RapierPhysics: removing rigidbody with colliders from the physics world is not possible right now, please remove the colliders first"))},1)))}}}updateBody(e,t,s){if(this.validate(),!!this.enabled&&!(e.destroyed||!e.gameObject)&&!(!t&&!s))if(e.isCollider===!0)console.warn("TODO: implement updating collider position");else{const o=e,r=o[ti];r&&this.syncPhysicsBody(o.gameObject,r,t,s)}}updateProperties(e){if(this.validate(),e.isCollider){const t=e,s=t[ti];s&&(this.internalUpdateColliderProperties(t,s),t.sharedMaterial&&this.updatePhysicsMaterial(t))}else{const t=e,s=this.internal_getRigidbody(t);s&&this.internalUpdateRigidbodyProperties(t,s)}}addForce(e,t,s){this.validate();const o=this.internal_getRigidbody(e);o?o.addForce(t,s):console.warn("Rigidbody doesn't exist: can not apply force (does your object with the Rigidbody have a collider?)")}addImpulse(e,t,s){this.validate();const o=this.internal_getRigidbody(e);o?o.applyImpulse(t,s):console.warn("Rigidbody doesn't exist: can not apply impulse (does your object with the Rigidbody have a collider?)")}getLinearVelocity(e){this.validate();const t=this.internal_getRigidbody(e);return t?t.linvel():null}getAngularVelocity(e){this.validate();const t=this.internal_getRigidbody(e);return t?t.angvel():null}resetForces(e,t){this.validate();const s=this.internal_getRigidbody(e);s?.resetForces(t)}resetTorques(e,t){this.validate();const s=this.internal_getRigidbody(e);s?.resetTorques(t)}applyImpulse(e,t,s){this.validate();const o=this.internal_getRigidbody(e);o?o.applyImpulse(t,s):console.warn("Rigidbody doesn't exist: can not apply impulse (does your object with the Rigidbody have a collider?)")}wakeup(e){this.validate();const t=this.internal_getRigidbody(e);t?t.wakeUp():console.warn("Rigidbody doesn't exist: can not wake up (does your object with the Rigidbody have a collider?)")}isSleeping(e){this.validate();const t=this.internal_getRigidbody(e);return t?.isSleeping()}setAngularVelocity(e,t,s){this.validate();const o=this.internal_getRigidbody(e);o?o.setAngvel(t,s):console.warn("Rigidbody doesn't exist: can not set angular velocity (does your object with the Rigidbody have a collider?)")}setLinearVelocity(e,t,s){this.validate();const o=this.internal_getRigidbody(e);o?o.setLinvel(t,s):console.warn("Rigidbody doesn't exist: can not set linear velocity (does your object with the Rigidbody have a collider?)")}get isInitialized(){return this._isInitialized}async initialize(){return this._initializePromise||(this._initializePromise=this.internalInitialization()),this._initializePromise}async internalInitialization(){return C("__nophysics")?(console.warn("Physics are disabled"),!1):(at&&console.log("Initialize rapier physics engine"),this._hasCreatedWorld?(console.error("Invalid call to create physics world: world is already created"),!0):(this._hasCreatedWorld=!0,A.RAPIER_PHYSICS.MAYBEMODULE==null&&(at&&console.trace("Loading rapier physics engine"),await(await A.RAPIER_PHYSICS.load()).init()),at&&console.log("Physics engine initialized, creating world..."),this._world=new A.RAPIER_PHYSICS.MODULE.World(this._gravity),this.rapierRay=new A.RAPIER_PHYSICS.MODULE.Ray({x:0,y:0,z:0},{x:0,y:0,z:1}),this.enabled=!0,this._isInitialized=!0,at&&console.log("Physics world created"),!0))}validate(){this._isInitialized||at&&(this._lastWarnTime=this._lastWarnTime??0,Date.now()-this._lastWarnTime>1e3&&(this._lastWarnTime=Date.now(),console.warn("Physics engine is not initialized")))}raycast(e,t,s){var o;if(!this._isInitialized)return console.log("Physics engine is not initialized"),null;let r=s?.maxDistance,l=s?.solid;r===void 0&&(r=1/0),l===void 0&&(l=!0);const c=this.getPhysicsRay(this.rapierRay,e,t);if(!c)return null;(this.debugRenderRaycasts||uv)&&$.DrawRay(c.origin,c.dir,255,1);const h=(o=this.world)==null?void 0:o.castRay(c,r,l,s?.queryFilterFlags,s?.filterGroups,void 0,void 0,d=>{const u=d[_i];return s!=null&&s.filterPredicate?s.filterPredicate(u):s?.useIgnoreRaycastLayer!==!1?!(u!=null&&u.gameObject.layers.isEnabled(2)):!0});if(h){const d=c.pointAt(h.timeOfImpact),u=this.raycastVectorsBuffer.get();return u.set(d.x,d.y,d.z),{point:u,collider:h.collider[_i]}}return null}raycastAndGetNormal(e,t,s){var o;if(!this._isInitialized)return null;let r=s?.maxDistance,l=s?.solid;r===void 0&&(r=1/0),l===void 0&&(l=!0);const c=this.getPhysicsRay(this.rapierRay,e,t);if(!c)return null;(this.debugRenderRaycasts||uv)&&$.DrawRay(c.origin,c.dir,255,1);const h=(o=this.world)==null?void 0:o.castRayAndGetNormal(c,r,l,s?.queryFilterFlags,s?.filterGroups,void 0,void 0,d=>{const u=d[_i];return s!=null&&s.filterPredicate?s.filterPredicate(u):s?.useIgnoreRaycastLayer!==!1?!(u!=null&&u.gameObject.layers.isEnabled(2)):!0});if(h){const d=c.pointAt(h.timeOfImpact),u=h.normal,p=this.raycastVectorsBuffer.get(),g=this.raycastVectorsBuffer.get();return p.set(d.x,d.y,d.z),g.set(u.x,u.y,u.z),{point:p,normal:g,collider:h.collider[_i]}}return null}getPhysicsRay(e,t,s){var o,r,l;const c=(o=this.context)==null?void 0:o.mainCamera;if(t===void 0){const u=(r=this.context)==null?void 0:r.input.getPointerPosition(0);if(u)t=u;else return null}if(t.z===void 0){if(!c)return console.error("Can not perform raycast from 2d point - no main camera found"),null;const u=this.raycastVectorsBuffer.get();u.x=t.x,u.y=t.y,u.z=0,(u.x>1||u.y>1||u.y<-1||u.x<-1)&&(at&&console.warn("Converting screenspace to raycast space",u),(l=this.context)==null||l.input.convertScreenspaceToRaycastSpace(u)),u.unproject(c),t=u}const h=t;e.origin.x=h.x,e.origin.y=h.y,e.origin.z=h.z;const d=this.raycastVectorsBuffer.get();if(s)d.set(s.x,s.y,s.z);else{if(!c)return console.error("Can not perform raycast - no camera found"),null;d.set(e.origin.x,e.origin.y,e.origin.z);const u=ee(c);d.sub(u)}return d.normalize(),e.dir.x=d.x,e.dir.y=d.y,e.dir.z=d.z,e}sphereOverlap(e,t){return this.rapierColliderArray.length=0,this._isInitialized?this.world?(this.rapierSphere??(this.rapierSphere=new A.RAPIER_PHYSICS.MODULE.Ball(t)),this.rapierSphere.radius=t,(this.debugRenderRaycasts||uv)&&$.DrawWireSphere(e,t,3359999,1),this.world.intersectionsWithShape(e,this.rapierIdentityRotation,this.rapierSphere,s=>{const o=s[_i],r=new Ix(o.gameObject,o);return this.rapierColliderArray.push(r),!0},void 0,void 0,void 0,void 0,s=>s.isSensor()?!1:s[_i].gameObject.layers.isEnabled(2)==!1),this.rapierColliderArray):this.rapierColliderArray:this.rapierColliderArray}get world(){return this._world}get isUpdating(){return this._isUpdatingPhysicsWorld}get gravity(){var e;return((e=this.world)==null?void 0:e.gravity)??this._gravity}set gravity(e){this.world?this.world.gravity=e:this._gravity=e}clearCaches(){var e,t,s,o;this._meshCache.clear(),(e=this.eventQueue)!=null&&e.raw&&((t=this.eventQueue)==null||t.free()),(s=this.world)!=null&&s.bodies&&((o=this.world)==null||o.free())}async addBoxCollider(e,t){if(this._isInitialized||await this.initialize(),!e.activeAndEnabled)return;if(!this.enabled){at&&console.warn("Physics are disabled");return}const s=e.gameObject,o=Ge(s,this._tempPosition).multiply(t);o.multiplyScalar(.5),o.x<0&&(o.x=Math.abs(o.x)),o.y<0&&(o.y=Math.abs(o.y)),o.z<0&&(o.z=Math.abs(o.z));const r=1e-7;o.x<r&&(o.x=r),o.y<r&&(o.y=r),o.z<r&&(o.z=r);const l=A.RAPIER_PHYSICS.MODULE.ColliderDesc.cuboid(o.x,o.y,o.z);this.createCollider(e,l)}async addSphereCollider(e){if(this._isInitialized||await this.initialize(),!e.activeAndEnabled)return;if(!this.enabled){at&&console.warn("Physics are disabled");return}const t=A.RAPIER_PHYSICS.MODULE.ColliderDesc.ball(.5);this.createCollider(e,t),this.updateProperties(e)}async addCapsuleCollider(e,t,s){if(this._isInitialized||await this.initialize(),!e.activeAndEnabled)return;if(!this.enabled){at&&console.warn("Physics are disabled");return}const o=e.gameObject,r=Ge(o,this._tempPosition);r.x=Math.abs(r.x),r.y=Math.abs(r.y);const l=s*r.x;t=Math.max(t,l*2);const c=W.clamp(t*.5*r.y-s*r.x,0,Number.MAX_SAFE_INTEGER),h=A.RAPIER_PHYSICS.MODULE.ColliderDesc.capsule(c,l);this.createCollider(e,h)}async addMeshCollider(e,t,s,o){var r,l,c;let h=t.geometry;if(!h){at&&console.warn("Missing mesh geometry",t.name);return}(l=(r=h.index)==null?void 0:r.array)!=null&&l.length||(console.warn(`Your MeshCollider is missing vertices or indices in the assined mesh "${t.name}". Consider providing an indexed geometry.`),h=gO(h));let d=null;const u=h.getAttribute("position");if(u instanceof Iv){const y=u.count;d=new Float32Array(y*3);for(let v=0;v<y;v++){const b=u.getX(v),_=u.getY(v),w=u.getZ(v);d[v*3]=b,d[v*3+1]=_,d[v*3+2]=w}}else d=u.array;if(await this.initialize(),!this.enabled){at&&console.warn("Physics are disabled");return}if(!e.activeAndEnabled)return;const p=(c=h.index)==null?void 0:c.array,g=e.gameObject.worldScale.clone();if(o&&g.multiply(o),Math.abs(g.x-1)>1e-4||Math.abs(g.y-1)>1e-4||Math.abs(g.z-1)>1e-4){const y=`${h.uuid}_${g.x}_${g.y}_${g.z}_${s}`;if(this._meshCache.has(y))at&&console.warn("Use cached mesh collider"),d=this._meshCache.get(y);else{(at||F())&&console.debug(`[Performance] Your MeshCollider "${e.name}" is scaled: consider applying the scale to the collider mesh instead (${g.x}, ${g.y}, ${g.z})`);const v=new Float32Array(d.length);for(let b=0;b<d.length;b+=3)v[b]=d[b]*g.x,v[b+1]=d[b+1]*g.y,v[b+2]=d[b+2]*g.z;d=v,this._meshCache.set(y,v)}}const f=s?A.RAPIER_PHYSICS.MODULE.ColliderDesc.convexHull(d):A.RAPIER_PHYSICS.MODULE.ColliderDesc.trimesh(d,p);f&&this.createCollider(e,f)}updatePhysicsMaterial(e){if(!e)return;const t=e.sharedMaterial,s=e[ti];if(s&&t){if(t.bounciness!==void 0&&s.setRestitution(t.bounciness),t.bounceCombine!==void 0)switch(t.bounceCombine){case xt.Average:s.setRestitutionCombineRule(A.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Average);break;case xt.Maximum:s.setRestitutionCombineRule(A.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Max);break;case xt.Minimum:s.setRestitutionCombineRule(A.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Min);break;case xt.Multiply:s.setRestitutionCombineRule(A.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Multiply);break}if(t.dynamicFriction!==void 0&&s.setFriction(t.dynamicFriction),t.frictionCombine!==void 0)switch(t.frictionCombine){case xt.Average:s.setFrictionCombineRule(A.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Average);break;case xt.Maximum:s.setFrictionCombineRule(A.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Max);break;case xt.Minimum:s.setFrictionCombineRule(A.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Min);break;case xt.Multiply:s.setFrictionCombineRule(A.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Multiply);break}}}getBody(e){return e?e[ti]:null}getComponent(e){return e?e[_i]:null}createCollider(e,t){var s;if(!this.world)throw new Error("Physics world not initialized");const o=this._tempMatrix;let r;e.attachedRigidbody?r=this.getRigidbody(e,this._tempMatrix):(at&&console.log("Create collider without rigidbody",e.name),o.makeRotationFromQuaternion(Se(e.gameObject)),o.setPosition(ee(e.gameObject))),o.decompose(this._tempPosition,this._tempQuaternion,this._tempScale),this.tryApplyCenter(e,this._tempPosition),t.setTranslation(this._tempPosition.x,this._tempPosition.y,this._tempPosition.z),t.setRotation(this._tempQuaternion),t.setSensor(e.isTrigger);const l=e.sharedMaterial;if(l){if(l.bounciness!==void 0&&t.setRestitution(l.bounciness),l.bounceCombine!==void 0)switch(l.bounceCombine){case xt.Average:t.setRestitutionCombineRule(A.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Average);break;case xt.Maximum:t.setRestitutionCombineRule(A.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Max);break;case xt.Minimum:t.setRestitutionCombineRule(A.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Min);break;case xt.Multiply:t.setRestitutionCombineRule(A.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Multiply);break}if(l.dynamicFriction!==void 0&&t.setFriction(l.dynamicFriction),l.frictionCombine!==void 0)switch(l.frictionCombine){case xt.Average:t.setFrictionCombineRule(A.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Average);break;case xt.Maximum:t.setFrictionCombineRule(A.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Max);break;case xt.Minimum:t.setFrictionCombineRule(A.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Min);break;case xt.Multiply:t.setFrictionCombineRule(A.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Multiply);break}}((s=e.attachedRigidbody)==null?void 0:s.autoMass)===!1&&(t.setDensity(1e-6),t.setMass(1e-6));try{const c=this.world.createCollider(t,r);return c[_i]=e,e[ti]=c,c.setActiveEvents(A.RAPIER_PHYSICS.MODULE.ActiveEvents.COLLISION_EVENTS),c.setActiveCollisionTypes(A.RAPIER_PHYSICS.MODULE.ActiveCollisionTypes.ALL),this.objects.push(e),this.bodies.push(c),this.updateColliderCollisionGroups(e),c}catch(c){return console.error('Error creating collider "'+e.name+`"
|
|
1572
|
+
Error:`,c),null}}updateColliderCollisionGroups(e){const t=e[ti],s=e.membership;let o=0;if(s==null)o=65535;else for(let c=0;c<s.length;c++){const h=s[c];h>31?console.error(`Rapier only supports 32 layers, layer ${h} is not supported`):o|=1<<Math.floor(h)}const r=e.filter;let l=0;if(r==null)l=65535;else for(let c=0;c<r.length;c++){const h=r[c];h>31?console.error(`Rapier only supports 32 layers, layer ${h} is not supported`):l|=1<<Math.floor(h)}t.setCollisionGroups(o<<16|l)}getRigidbody(e,t){if(!this.world)throw new Error("Physics world not initialized");let s=null;if(e.attachedRigidbody){const o=e.attachedRigidbody;if(s=o[ti],!s){const r=o.isKinematic&&!hv;at&&console.log("Create rigidbody",r);const l=r?A.RAPIER_PHYSICS.MODULE.RigidBodyDesc.kinematicPositionBased():A.RAPIER_PHYSICS.MODULE.RigidBodyDesc.dynamic(),c=ee(e.attachedRigidbody.gameObject);l.setTranslation(c.x,c.y,c.z),l.setRotation(Se(e.attachedRigidbody.gameObject)),l.centerOfMass=new A.RAPIER_PHYSICS.MODULE.Vector3(o.centerOfMass.x,o.centerOfMass.y,o.centerOfMass.z),s=this.world.createRigidBody(l),this.bodies.push(s),this.objects.push(o)}s[_i]=o,o[ti]=s,this.internalUpdateRigidbodyProperties(o,s),this.getRigidbodyRelativeMatrix(e.gameObject,o.gameObject,t),e[sC]=s}else{const o=A.RAPIER_PHYSICS.MODULE.RigidBodyDesc.kinematicPositionBased(),r=ee(e.gameObject);o.setTranslation(r.x,r.y,r.z),o.setRotation(Se(e.gameObject)),s=this.world.createRigidBody(o),t.identity(),s[_i]=null}return s}internal_getRigidbody(e){return e.isCollider===!0?e[sC]:e[ti]}internalUpdateColliderProperties(e,t){const s=t.shape;let o=!1;switch(s.type){case A.RAPIER_PHYSICS.MODULE.ShapeType.Ball:{const g=s,f=e,y=e.gameObject,v=Ge(y,this._tempPosition),b=Math.abs(f.radius*v.x);o=g.radius!==b,g.radius=b,o&&t.setShape(g);break}case A.RAPIER_PHYSICS.MODULE.ShapeType.Cuboid:const r=s,l=e,c=e.gameObject,h=Ge(c,this._tempPosition),d=Math.abs(l.size.x*.5*h.x),u=Math.abs(l.size.y*.5*h.y),p=Math.abs(l.size.z*.5*h.z);o=r.halfExtents.x!==d||r.halfExtents.y!==u||r.halfExtents.z!==p,r.halfExtents.x=d,r.halfExtents.y=u,r.halfExtents.z=p,o&&t.setShape(r);break}if(o){const r=e.attachedRigidbody;if(r!=null&&r.autoMass){const l=this.getBody(r);l?.recomputeMassPropertiesFromColliders()}}this.updateColliderCollisionGroups(e),e.isTrigger!==t.isSensor()&&t.setSensor(e.isTrigger)}internalUpdateRigidbodyProperties(e,t){if(t.enableCcd(e.collisionDetectionMode!==ku.Discrete),t.setLinearDamping(e.drag),t.setAngularDamping(e.angularDrag),t.setGravityScale(e.useGravity?e.gravityScale:0,!0),e.dominanceGroup<=127&&e.dominanceGroup>=-127?t.setDominanceGroup(Math.floor(e.dominanceGroup)):t.setDominanceGroup(0),e.autoMass){t.setAdditionalMass(0,!1);for(let s=0;s<t.numColliders();s++)t.collider(s).setDensity(1);t.recomputeMassPropertiesFromColliders()}else{t.setAdditionalMass(e.mass,!1);for(let s=0;s<t.numColliders();s++)t.collider(s).setDensity(1e-7);t.recomputeMassPropertiesFromColliders()}t.setEnabledRotations(!e.lockRotationX,!e.lockRotationY,!e.lockRotationZ,!1),t.setEnabledTranslations(!e.lockPositionX,!e.lockPositionY,!e.lockPositionZ,!1),e.isKinematic?t.setBodyType(A.RAPIER_PHYSICS.MODULE.RigidBodyType.KinematicPositionBased,!1):t.setBodyType(A.RAPIER_PHYSICS.MODULE.RigidBodyType.Dynamic,!1)}step(e){if(this.world&&this.enabled){if(this._isUpdatingPhysicsWorld=!0,this.eventQueue||(this.eventQueue=new A.RAPIER_PHYSICS.MODULE.EventQueue(!1)),e===void 0||e<=0){this._isUpdatingPhysicsWorld=!1;return}else e!==void 0&&(this.world.timestep=W.lerp(this.world.timestep,e,.8));try{this.world.step(this.eventQueue)}catch(t){console.warn("Error running physics step",t)}this._isUpdatingPhysicsWorld=!1}}postStep(){this.world&&this.enabled&&(this._isUpdatingPhysicsWorld=!0,this.syncObjects(),this._isUpdatingPhysicsWorld=!1,this.eventQueue&&!this.collisionHandler&&(this.collisionHandler=new zL(this.world,this.eventQueue)),this.collisionHandler&&(this.collisionHandler.handleCollisionEvents(),this.collisionHandler.update()),this.updateDebugRendering(this.world))}updateDebugRendering(e){var t,s,o,r;if(at||hv||UL||this.debugRenderColliders===!0){if(!this.lines){const c=new Av({color:7855479,fog:!1}),h=new Vs;this.lines=new Ev(h,c),this.lines.layers.disableAll(),this.lines.layers.enable(2)}this.lines.parent!==((t=this.context)==null?void 0:t.scene)&&((s=this.context)==null||s.scene.add(this.lines));const l=e.debugRender();this.lines.geometry.setAttribute("position",new _t(l.vertices,3)),this.lines.geometry.setAttribute("color",new _t(l.colors,4)),(this.context.time.frame%30===0||((o=this.lines.geometry.boundingSphere)==null?void 0:o.radius)===0)&&this.lines.geometry.computeBoundingSphere()}else this.lines&&((r=this.context)==null||r.scene.remove(this.lines))}syncObjects(){if(!hv)for(let e=0;e<this.bodies.length;e++){const t=this.objects[e],s=this.bodies[e],o=t;if(o?.isCollider===!0&&!o.attachedRigidbody){const h=s.parent();h?this.syncPhysicsBody(t.gameObject,h,!0,!0):this.syncPhysicsBody(t.gameObject,s,!0,!0);continue}const r=s.translation(),l=s.rotation();if(Number.isNaN(r.x)||Number.isNaN(l.x)){!o.__COLLIDER_NAN&&F()&&(console.warn("Collider has NaN values",o.name,o.gameObject,s),o.__COLLIDER_NAN=!0);continue}const c=t.center;if(c&&c.isVector3){this._tempQuaternion.set(l.x,l.y,l.z,l.w);const h=this._tempPosition.copy(c).applyQuaternion(this._tempQuaternion),d=Ge(t.gameObject);h.multiply(d),r.x-=h.x,r.y-=h.y,r.z-=h.z}br(t.gameObject,r.x,r.y,r.z),dg(t.gameObject,l.x,l.y,l.z,l.w)}}syncPhysicsBody(e,t,s,o){if(t instanceof A.RAPIER_PHYSICS.MODULE.RigidBody){const r=ee(e,this._tempPosition),l=Se(e,this._tempQuaternion);switch(t.bodyType()){case A.RAPIER_PHYSICS.MODULE.RigidBodyType.Fixed:case A.RAPIER_PHYSICS.MODULE.RigidBodyType.KinematicPositionBased:case A.RAPIER_PHYSICS.MODULE.RigidBodyType.KinematicVelocityBased:s&&t.setNextKinematicTranslation(r),o&&t.setNextKinematicRotation(l);break;default:s&&t.setTranslation(r,!1),o&&t.setRotation(l,!1);break}}else if(t instanceof A.RAPIER_PHYSICS.MODULE.Collider){e.matrixWorldNeedsUpdate&&e.updateWorldMatrix(!0,!1),e.matrixWorld.decompose(this._tempPosition,this._tempQuaternion,this._tempScale);const r=this._tempPosition,l=this._tempQuaternion,c=t[_i];if(this.tryApplyCenter(c,r),s){const h=t.translation();(h.x!==r.x||h.y!==r.y||h.z!==r.z)&&t.setTranslation(r)}if(o){const h=t.rotation();(h.x!==l.x||h.y!==l.y||h.z!==l.z||h.w!==l.w)&&t.setRotation(l)}}}tryApplyCenter(e,t){const s=e.center;s&&e.gameObject&&(s.x!==0||s.y!==0||s.z!==0)&&(this._tempCenterPos.x=s.x,this._tempCenterPos.y=s.y,this._tempCenterPos.z=s.z,Ge(e.gameObject,this._tempCenterVec),this._tempCenterPos.multiply(this._tempCenterVec),e.attachedRigidbody?this._tempCenterPos.applyQuaternion(e.gameObject.quaternion):(Se(e.gameObject,this._tempCenterQuaternion),this._tempCenterPos.applyQuaternion(this._tempCenterQuaternion)),t.x+=this._tempCenterPos.x,t.y+=this._tempCenterPos.y,t.z+=this._tempCenterPos.z)}getRigidbodyRelativeMatrix(e,t,s,o){if(o===void 0&&(o=Pm._matricesBuffer,o.length=0),e===t){const r=Ge(e,this._tempPosition);s.makeScale(r.x,r.y,r.z);for(let l=o.length-1;l>=0;l--)s.multiply(o[l]);return s}return o.push(e.matrix),e.parent&&this.getRigidbodyRelativeMatrix(e.parent,t,s,o),s}addFixedJoint(e,t){if(!this.world){console.error("Physics world not initialized");return}const s=e[ti],o=t[ti];this.calculateJointRelativeMatrices(e.gameObject,t.gameObject,this._tempMatrix),this._tempMatrix.decompose(this._tempPosition,this._tempQuaternion,this._tempScale);const r=A.RAPIER_PHYSICS.MODULE.JointData.fixed(Pm.centerConnectionPos,Pm.centerConnectionRot,this._tempPosition,this._tempQuaternion),l=this.world.createImpulseJoint(r,s,o,!0);at&&console.log("ADD FIXED JOINT",l)}addHingeJoint(e,t,s,o){if(!this.world){console.error("Physics world not initialized");return}const r=e[ti],l=t[ti];this.calculateJointRelativeMatrices(e.gameObject,t.gameObject,this._tempMatrix),this._tempMatrix.decompose(this._tempPosition,this._tempQuaternion,this._tempScale);const c=A.RAPIER_PHYSICS.MODULE.JointData.revolute(s,this._tempPosition,o),h=this.world.createImpulseJoint(c,r,l,!0);at&&console.log("ADD HINGE JOINT",h)}calculateJointRelativeMatrices(e,t,s){e.updateWorldMatrix(!0,!1),t.updateWorldMatrix(!0,!1);const o=e.matrixWorld,r=t.matrixWorld;o.elements[0]=1,o.elements[5]=1,o.elements[10]=1,r.elements[0]=1,r.elements[5]=1,r.elements[10]=1,s.copy(r).premultiply(o.invert()).invert()}};a(td,"_didLoadPhysicsEngine",!1),a(td,"_matricesBuffer",[]),a(td,"centerConnectionPos",{x:0,y:0,z:0}),a(td,"centerConnectionRot",{x:0,y:0,z:0,w:1});let nC=td;class zL{constructor(e,t){a(this,"world"),a(this,"eventQueue"),a(this,"activeCollisions",[]),a(this,"activeCollisionsStay",[]),a(this,"activeTriggers",[]),this.world=e,this.eventQueue=t}handleCollisionEvents(){this.eventQueue&&this.world&&this.eventQueue.drainCollisionEvents((e,t,s)=>{const o=this.world.getCollider(e),r=this.world.getCollider(t);if(!o||!r)return;const l=o[_i],c=r[_i];dv&&console.log("EVT",l.name,c.name,s,o,r),l&&c&&(s?(this.onCollisionStarted(l,o,c,r),this.onCollisionStarted(c,r,l,o)):(this.onCollisionEnded(l,c),this.onCollisionEnded(c,l)))})}update(){this.onHandleCollisionStay()}onCollisionStarted(e,t,s,o){let r=null;if(e.isTrigger||s.isTrigger)Ar(e.gameObject,l=>{l.onTriggerEnter&&!l.destroyed&&l.onTriggerEnter(s),this.activeTriggers.push({collider:e,component:l,otherCollider:s})});else{const l=e.gameObject;this.world.contactPair(t,o,(c,h)=>{Ar(l,d=>{var u;if(d.destroyed)return;const p=d.onCollisionEnter||d.onCollisionStay||d.onCollisionExit;if(p||dv){if(!r){const g=[],f=c.normal();s instanceof Fo&&s.convex&&(f.x=-f.x,f.y=-f.y,f.z=-f.z);for(let y=0;y<c.numSolverContacts();y++){const v=c.solverContactPoint(y),b=c.contactImpulse(y);if(v){const _=c.contactDist(y),w=c.solverContactFriction(y),x=c.solverContactTangentVelocity(y),k=new Ex(v,_,f,b,w,x);g.push(k),dv&&$.DrawDirection(v,f,16711680,3,!0)}}r=new Ax(l,s,g)}if(p){const g={collider:e,component:d,collision:r};this.activeCollisions.push(g),d.onCollisionStay&&this.activeCollisionsStay.push(g),(u=d.onCollisionEnter)==null||u.call(d,r)}}})})}}onHandleCollisionStay(){for(const e of this.activeCollisionsStay){const t=e.component;if(!t.destroyed&&t.activeAndEnabled&&t.onCollisionStay){if(e.collision.collider.destroyed)continue;const s=e.collision;t.onCollisionStay(s)}}for(const e of this.activeTriggers){const t=e.component;if(!t.destroyed&&t.activeAndEnabled&&t.onTriggerStay){const s=e.otherCollider;if(s.destroyed)continue;t.onTriggerStay(s)}}}onCollisionEnded(e,t){if(!(e.destroyed||t.destroyed)){for(let s=0;s<this.activeCollisions.length;s++){const o=this.activeCollisions[s],r=o.collider;if(r.destroyed||o.collision.collider.destroyed){this.activeCollisions.splice(s,1),s--;continue}if(r===e&&o.collision.collider===t){const l=o.component;if(this.activeCollisions.splice(s,1),s--,l.activeAndEnabled&&l.onCollisionExit){const c=o.collision;l.onCollisionExit(c)}}}for(let s=0;s<this.activeCollisionsStay.length;s++){const o=this.activeCollisionsStay[s],r=o.collider;if(r.destroyed||o.collision.collider.destroyed){this.activeCollisionsStay.splice(s,1),s--;continue}if(r===e&&o.collision.collider===t){const l=o.component;if(this.activeCollisionsStay.splice(s,1),s--,l.activeAndEnabled&&l.onCollisionExit){const c=o.collision;l.onCollisionExit(c)}}}for(let s=0;s<this.activeTriggers.length;s++){const o=this.activeTriggers[s],r=o.collider;if(r.destroyed||o.otherCollider.destroyed){this.activeTriggers.splice(s,1),s--;continue}if(r===e&&o.otherCollider===t){const l=o.component;if(this.activeTriggers.splice(s,1),s--,l.activeAndEnabled&&l.onTriggerExit){const c=o.otherCollider;l.onTriggerExit(c)}}}}}}class NL{static async createComparisonScene(e){const{files:t}=e,s=await Promise.all(t.map(y=>new ce(y).loadAssetAsync())),o=new xi;let r=0;for(const y of s)if(y instanceof E){y.position.y=r,o.add(y);const v=si([y]);r+=v.getSize(new S).y,r+=.1}const l=new we(20);o.add(l);const c=e.environment||"https://dl.polyhaven.org/file/ph-assets/HDRIs/exr/1k/studio_small_09_1k.exr";{let y=null;if(c.endsWith(".hdr")){const v=(await import("./three-examples-DaDLBuy6.min.js").then(b=>b.RGBELoader$1)).RGBELoader;y=new v}else if(c.endsWith(".exr")){const v=(await import("./three-examples-DaDLBuy6.min.js").then(b=>b.EXRLoader$1)).EXRLoader;y=new v}if(y){const v=await y.loadAsync(c).catch(b=>(console.error(b),null));v&&(v.mapping=kn,v.needsUpdate=!0,o.background=v,o.environment=v,o.backgroundBlurriness=.75)}else console.warn("Unsupported environment map format",c)}const h=si(o.children),d=h.getCenter(new S),u=h.getSize(new S),p=Math.max(u.x,u.y,u.z)/(2*Math.tan(Math.PI*l.fov/360));l.position.set(d.x,d.y,p),l.lookAt(d);const g=new $v(l,e.domElement||document.body);g.target=d,g.update();const f=(e.domElement||document.body).getBoundingClientRect();return l.aspect=f.width/f.height,l.updateProjectionMatrix(),{scene:o,camera:l}}}let pv=0;function oC(n){n?pv++:pv--}function WL(){return pv>0}const VL={binary:!0,animations:!0};async function $L(n){if(!n.context)throw new Error("No context provided to exportAsGLTF");n.scene||(n.scene=n.context.scene);const e={...VL,...n},{context:t}=e,s=new Hv;s.register(c=>new l1(c)),s.register(c=>new fE(c)),s.register(c=>new Kx(c)),v0(s,e.context);const o={binary:e.binary,animations:GL(t,e.scene,[])},r=new HL;console.debug("Exporting GLTF",o),r.onBeforeExport(e),oC(!0);const l=await s.parseAsync(e.scene,o).catch(c=>(console.error(c),null));if(oC(!1),r.onAfterExport(e),!l)throw new Error("Failed to export GLTF");if(e.downloadAs!=null){let c=null;if(l instanceof ArrayBuffer?c=new Blob([l],{type:"application/octet-stream"}):console.error("Can not download GLTF as a blob",l),c){const h=URL.createObjectURL(c),d=document.createElement("a");d.href=h;let u=e.downloadAs;!u.endsWith(".glb")&&!u.endsWith(".gltf")&&(u+=e.binary?".glb":".gltf"),d.download=u,d.click()}}return l}const rC=Symbol("needle:weight");class HL{constructor(){a(this,"_undo",[])}onBeforeExport(e){e.context.animations.mixers.forEach(t=>{const s=Ga.tryGetActionsFromMixer(t);if(s)for(let o=0;o<s.length;o++){const r=s[o];r[rC]=r.weight,r.weight=0,this._undo.push(()=>{r.weight=r[rC]})}t.update(0)}),e.context.scene.traverse(t=>{if(!p0(t)){const s=t.parent;s&&(t.removeFromParent(),this._undo.push(()=>s.add(t)))}})}onAfterExport(e){this._undo.forEach(t=>t()),this._undo.length=0}}function GL(n,e,t){n.animations.mixers.forEach(o=>{const r=Ga.tryGetActionsFromMixer(o);if(r)for(let l=0;l<r.length;l++){const c=r[l].getClip();t.push(c)}}),Array.isArray(e)||(e=[e]);for(const o of e)Ga.tryGetAnimationClipsFromObjectHierarchy(o,t);const s=new Set(t);return Array.from(s)}const aC="needle-button",mv=F();var fa,ya,va,wi,Ds,Dl,pm,lC,cC,mm;class gv extends HTMLElement{constructor(){super(),Us(this,pm),Us(this,fa),Us(this,ya),Us(this,va),Us(this,wi),Us(this,Ds),Us(this,Dl),Us(this,mm,e=>{mv&&console.log("Needle Button clicked"),!e.defaultPrevented&&ge(this,wi)&&ge(this,wi).click()}),this.removeEventListener("click",ge(this,mm)),this.addEventListener("click",ge(this,mm))}attributeChangedCallback(e,t,s){dd(this,pm,lC).call(this)}}fa=new WeakMap,ya=new WeakMap,va=new WeakMap,wi=new WeakMap,Ds=new WeakMap,Dl=new WeakMap,pm=new WeakSet,lC=function(){var n,e;if((n=ge(this,wi))==null||n.remove(),this.getAttribute("ar")!=null)ge(this,Ds)??zs(this,Ds,new ml),zs(this,wi,ge(this,Ds).createARButton());else if(this.getAttribute("vr")!=null)ge(this,Ds)??zs(this,Ds,new ml),zs(this,wi,ge(this,Ds).createVRButton());else if(this.getAttribute("quicklook")!=null)ge(this,Ds)??zs(this,Ds,new ml),zs(this,wi,ge(this,Ds).createQuicklookButton());else{mv?console.warn("No button type specified for <needle-button>. Use either ar, vr or quicklook attribute."):console.debug("No button type specified for <needle-button>. Use either ar, vr or quicklook attribute.");return}ge(this,fa)??zs(this,fa,this.attachShadow({mode:"open"})),ge(this,ya)??zs(this,ya,document.createElement("slot")),ge(this,va)??zs(this,va,document.createElement("style")),ge(this,va).innerHTML=`
|
|
1570
1573
|
button {
|
|
1571
1574
|
all: initial;
|
|
1572
1575
|
cursor: inherit;
|
|
@@ -1600,4 +1603,4 @@ Error:`,c),null}}updateColliderCollisionGroups(e){const t=e[ti],s=e.membership;l
|
|
|
1600
1603
|
justify-content: center;
|
|
1601
1604
|
gap: .5rem;
|
|
1602
1605
|
}
|
|
1603
|
-
`),ge(this,ya).innerHTML=ge(this,wi).innerHTML,ge(this,ya).style.cssText="display: flex; align-items: center; justify-content: center;",ge(this,wi).innerHTML=ge(this,ya).outerHTML,ge(this,fa).innerHTML=ge(this,wi).outerHTML,ge(this,fa).prepend(ge(this,va)),fu(kf,{element:ge(this,fa)}),(e=ge(this,Dl))==null||e.disconnect(),ge(this,Dl)??zs(this,Dl,new MutationObserver(()=>dd(this,pm,cC).call(this))),ge(this,Dl).observe(ge(this,wi),{attributes:!0}),mv&&console.log("Needle Button updated")},cC=function(){ge(this,wi)&&(ge(this,wi).style.display==="none"?this.style.display="none":this.style.display==="none"&&(this.style.display=""))},mm=new WeakMap,a(gv,"observedAttributes",["ar","vr","quicklook"]),typeof window<"u"&&!window.customElements.get(aC)&&window.customElements.define(aC,gv);const id=C("debugavatar");class fv{constructor(e,t,s,o){a(this,"root"),a(this,"head"),a(this,"leftHand"),a(this,"rigthHand");var r;this.root=e,this.head=t,this.leftHand=s,this.rigthHand=o,(r=this.root)==null||r.traverse(l=>l.layers.set(2))}get isValid(){return this.head!==null&&this.head!==void 0}}class hC{constructor(){a(this,"avatarRegistryUrl",null)}async getOrCreateNewAvatarInstance(e,t){if(!t)return console.error("Can not create avatar: failed to provide id or root object"),null;let s=null;if(typeof t=="string"){if(s=await this.loadAvatar(e,t),!s){const r=new Fs;s=P.instantiate(Ma(t,e.scene),r)}}else s=t;if(!s)return null;const o=this.findAvatar(s);return o.isValid?(id&&console.log("[Custom Avatar] valid config",t,id?o:""),o):(console.warn("[Custom Avatar] config isn't valid",t,id?o:""),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(id&&console.log("[Custom Avatar] "+t+", loading..."),t.endsWith(".glb")||(t+=".glb"),this.avatarRegistryUrl===null){const o=await fetch("./"+t);let r=null;if(o.ok){const c=await o.blob();c&&(r=await c.arrayBuffer())}if(!r)return null;const l=await xs().parseSync(e,r,null,0);return l?.scene??null}const s=new Rn;return jf(s,e),new Promise((o,r)=>{const l=this.avatarRegistryUrl+"/"+t;s.load(l,async c=>{await xs().createBuiltinComponents(e,l,c,null,void 0),o(c.scene)},c=>{id&&console.log("[Custom Avatar] "+c.loaded/c.total*100+"% loaded of "+c.total/1024+"kB")},c=>{console.error("[Custom Avatar] Error when loading: "+c),o(null)})})}cacheModel(e,t){}findAvatar(e){const t=e;let s=t;s.children.length==1&&(s=e.children[0]);let o=this.findAvatarPart(s,["head"]);const r=this.findAvatarPart(s,["left","hand"]),l=this.findAvatarPart(s,["right","hand"]);if(!o){o=t;const c=new S;new Si().setFromObject(o).getSize(c);const h=Math.max(c.x,c.y,c.z);console.warn("[Custom Avatar] Normalizing head scale, it's too big: "+h+" meters! Should be < 0.3m"),h>.3&&o.scale.multiplyScalar(1/h*.3)}return new fv(t,o,r,l)}findAvatarPart(e,t){const s=e.name.toLowerCase();let o=!0;for(const r of t){if(!o)break;s.indexOf(r)===-1&&(o=!1)}if(o)return e;if(e.children)for(const r of e.children){const l=this.findAvatarPart(r,t);if(l)return l}return null}handleCustomAvatarErrors(e){if(!e.ok)throw Error(e.statusText);return e}}class dC{get extensionName(){return"DocumentExtension"}onAfterBuildDocument(e){}}class uC{}const GL=Object.freeze(Object.defineProperty({__proto__:null,ActionBuilder:ve,ActionCollection:V1,ActionModel:ks,AlignmentConstraint:Tc,Animation:Ft,AnimationCurve:mh,AnimationExtension:dp,AnimationTrackHandler:im,Animator:Rt,AnimatorController:gs,Antialiasing:bh,AudioExtension:_a,AudioListener:zn,AudioSource:ns,AudioTrackHandler:sm,Avatar:Go,AvatarBlink_Simple:zr,AvatarEyeLook_Rotation:Kf,AvatarLoader:hC,AvatarMarker:hi,AvatarModel:fv,Avatar_Brain_LookAt:Uc,Avatar_MouthShapes:zc,Avatar_MustacheShake:Xf,Avatar_POI:Nn,AxesHelper:Ja,BaseUIComponent:ps,BasicIKConstraint:Jf,BehaviorExtension:Z0,BehaviorModel:Jt,BloomEffect:Np,BoxCollider:Nu,BoxGizmo:ea,BoxHelperComponent:Bo,Button:no,CallInfo:Un,Camera:ci,CameraTargetReachedEvent:Fc,Canvas:_l,CanvasGroup:Ko,CapsuleCollider:Wn,ChangeMaterialOnClick:B0,ChangeTransformOnClick:Xr,CharacterController:Nr,CharacterControllerInput:$n,ChromaticAberration:_h,Collider:ui,ColorAdjustments:or,ColorBySpeedModule:Pl,ColorOverLifetimeModule:Ip,ContactShadows:Vc,ControlTrackHandler:nm,CustomBranding:Jr,Deletable:n0,DeleteBox:Wu,DepthOfField:As,DeviceFlag:Vu,DocumentExtension:dC,DragControls:Hr,DropListener:Hn,Duplicatable:h0,EffectWrapper:xh,EmissionModule:eo,EmphasizeOnClick:ul,EnvironmentScene:cm,EventList:xe,EventListEvent:Ru,EventSystem:ii,EventTrigger:qu,FieldWithDefault:y1,FixedJoint:fy,Fog:xl,GltfExport:P0,GltfExportBox:S0,Gradient:ia,Graphic:lh,GraphicRaycaster:Au,GridHelper:Sl,GridLayoutGroup:ay,GroundProjectedEnv:en,GroupActionModel:Wo,HideOnStart:pp,HingeJoint:dh,HorizontalLayoutGroup:ry,Image:El,InheritVelocityModule:Sy,InputField:Yy,InstanceHandle:w0,InstancingHandler:Ju,Interactable:s0,Keyframe:vi,LODGroup:ph,LODModel:Cl,Light:yi,LimitVelocityOverLifetimeModule:gt,LogStats:i0,LookAt:Ky,LookAtConstraint:Fr,MainModule:Wt,MaskableGraphic:ch,MeshCollider:Fo,MeshRenderer:Qc,MinMaxCurve:Z,MinMaxGradient:sa,NeedleMenu:un,NestedGltf:kp,Networking:_y,NoiseModule:Ce,ObjectRaycaster:ji,OffsetConstraint:ta,OpenURL:Al,OrbitControls:_e,Outline:bl,Padding:Zr,ParticleBurst:Ap,ParticleSubEmitter:Cy,ParticleSystem:yh,ParticleSystemRenderer:ds,PhysicsExtension:J0,PixelationEffect:Sh,PlayAnimationOnClick:Jc,PlayAudioOnClick:Vo,PlayableDirector:Tl,PlayerColor:Nl,PointerEventData:cd,PostProcessingHandler:zy,PreliminaryAction:pl,PreliminaryTrigger:eh,RawImage:am,Rect:Z1,RectTransform:Ts,ReflectionProbe:qc,RegisteredAnimationInfo:mr,RemoteSkybox:qp,Renderer:Ui,RendererLightmap:ep,Rigidbody:dt,RotationBySpeedModule:hs,RotationOverLifetimeModule:Es,SceneSwitcher:Ze,ScreenCapture:ar,ScreenSpaceAmbientOcclusion:to,ScreenSpaceAmbientOcclusionN8:Is,SetActiveOnClick:F0,ShadowCatcher:Rh,ShapeModule:xy,SharpeningEffect:Ph,SignalAsset:tm,SignalReceiver:Dh,SignalReceiverEvent:jh,SignalTrackHandler:Fh,Size:K1,SizeBySpeedModule:bi,SizeOverLifetimeModule:na,SkinnedMeshRenderer:x0,SmoothFollow:Yp,SpatialGrabRaycaster:Dc,SpatialHtml:Nh,SpatialTrigger:Kp,SpatialTriggerReceiver:vn,SpectatorCamera:Zp,SphereCollider:el,Sprite:Qn,SpriteData:fl,SpriteRenderer:gi,SpriteSheet:gl,SubEmitterSystem:Bp,SyncedCamera:Wy,SyncedRoom:Ls,SyncedTransform:sn,TapGestureTrigger:N0,TeleportTarget:_p,TestRunner:Hy,TestSimulateUserData:Gy,Text:Nt,TextBuilder:ny,TextExtension:Pp,TextureSheetAnimationModule:Vt,TiltShiftEffect:yn,ToneMappingEffect:nr,TrailModule:We,TransformData:ut,TransformGizmo:da,TriggerBuilder:At,TriggerModel:dl,UIRaycastUtils:zf,UIRootComponent:oh,USDZExporter:gn,USDZText:Kr,USDZUIExtension:hy,UsageMarker:$c,VariantAction:j0,VelocityOverLifetimeModule:qe,VerticalLayoutGroup:oy,VideoPlayer:yt,Vignette:la,VisibilityAction:th,Voip:Do,Volume:Ml,VolumeParameter:N,VolumeProfile:Fp,WebARCameraBackground:Hh,WebARSessionRoot:$o,WebXR:wp,WebXRImageTracking:Gh,WebXRImageTrackingModel:ro,WebXRPlaneTracking:ao,WebXRTrackedImage:tv,XRControllerFollow:oo,XRControllerModel:pn,XRControllerMovement:Ni,XRFlag:os,XRRig:um,XRState:Di,__Ignore:uC},Symbol.toStringTag,{value:"Module"})),gm=C("debugmissingcamera");pe.registerCallback(me.MissingCamera,n=>{var e,t,s,o;gm&&console.warn("Creating missing camera");const r=n.context.scene,l=new we;l.name="Default Fallback Camera",r.add(l);const c=new ci;if(c.sourceId=((t=(e=n.files)==null?void 0:e[0])==null?void 0:t.src)??"unknown",c.fieldOfView=35,n.context.domElement.getAttribute("transparent")!=null)c.clearFlags=Io.Uninitialized;else if((s=n.context.domElement.getAttribute("skybox-image"))!=null&&s.length||(o=n.context.domElement.getAttribute("background-image"))!=null&&o.length||n.context.lightmaps.tryGetSkybox(c.sourceId))c.clearFlags=Io.Skybox,c.backgroundBlurriness=.2;else{if(c.clearFlags=Io.SolidColor,!n.context.domElement.getAttribute("background-color")){let u="#efefef";typeof window!==void 0&&window.matchMedia("(prefers-color-scheme: dark)").matches&&(u="#1f1f1f"),r.background=new oe(u)}if(!r.environment){const u=new HP(n.context.renderer),p=new cm("neutral");r.environment=u.fromScene(p,.025).texture}}const h=Mr(l,c,!0);l.position.x=0,l.position.y=1,l.position.z=2;const d=n.context.domElement;return d?.cameraControls!=!1&&pC(n.context,h),h}),pe.registerCallback(me.ContextCreated,n=>{if(!n.context.mainCamera){gm&&console.log("Will not auto-fit because a default camera exists");return}const e=n.context.domElement;if(e?.cameraControls==!0){const t=Cb(n.context.mainCamera);if(t?.isCameraController==!0){gm&&console.log("Will not auto-fit because a camera controller exists");return}pC(n.context)}});function pC(n,e){e=e??n.mainCameraComponent;const t=e?.gameObject;if(gm&&console.log("Creating default camera controls",e?.name),t){const s=vc(t,_e);s.sourceId=e?.sourceId??"unknown";const o=n.domElement.getAttribute("auto-rotate");if(s.autoRotate=o!=null&&o!="0"&&o?.toLowerCase()!="false",s.autoRotateSpeed=.5,s.autoFit=!0,s.autoRotate&&o){const r=parseFloat(o);isNaN(r)||(s.autoRotateSpeed=r)}}else console.warn("Missing camera object, can not add orbit controls")}pe.registerCallback(me.ContextCreated,n=>{const e=n.context.domElement.getAttribute("autoplay");if(e!==void 0&&(e===""||e==="true"||e==="1")&&n.files)for(const t of n.files)P.foreachComponent(t.file.scene,s=>{if(s.enabled!==!1){if(s instanceof Ft&&s.playAutomatically||s instanceof Rt||s instanceof Tl&&s.playOnAwake===!0)return!0;if(s instanceof Ft)return s.playAutomatically=!0,!0;if(s instanceof Tl)return s.playOnAwake=!0,!0}},!0)!==!0&&Ga.assignAnimationsFromFile(t.file,{createAnimationComponent:(s,o)=>Ei(s,Ft)})});class qL extends PO{constructor(){super(new Worker(new URL("/generateMeshBVH.worker-BaNp_Xtp.js",import.meta.url),{type:"module"})),this.name="GenerateMeshBVHWorker"}runTask(e,t,s={}){return new Promise((o,r)=>{if(t.getAttribute("position").isInterleavedBufferAttribute||t.index&&t.index.isInterleavedBufferAttribute)throw new Error("GenerateMeshBVHWorker: InterleavedBufferAttribute are not supported for the geometry attributes.");e.onerror=d=>{r(new Error(`[GenerateMeshBVHWorker] ${d.message||"Unknown error. Please check the server console. If you're using vite try adding 'three-mesh-bvh' to 'optimizeDeps.exclude' in your vite.config.js"}`))},e.onmessage=d=>{const{data:u}=d;if(u.error)r(new Error(u.error)),e.onmessage=null;else if(u.serialized){const{serialized:p,position:g}=u,f=OO.deserialize(p,t,{setIndex:!1}),y=Object.assign({setBoundingBox:!0},s);if(t.attributes.position.array=g,p.index)if(t.index)t.index.array=p.index;else{const v=new _t(p.index,1,!1);t.setIndex(v)}y.setBoundingBox&&(t.boundingBox=f.getBoundingBox(new Si)),s.onProgress&&s.onProgress(u.progress),o(f),e.onmessage=null}else s.onProgress&&s.onProgress(u.progress)};const l=t.index?t.index.array:null,c=t.attributes.position.array,h=[c];l&&h.push(l),e.postMessage({index:l,position:c,options:{...s,onProgress:null,includedProgressCallback:!!s.onProgress,groups:[...t.groups]}},h.map(d=>d.buffer).filter(d=>typeof SharedArrayBuffer>"u"||!(d instanceof SharedArrayBuffer)))})}}const XL=Object.freeze(Object.defineProperty({__proto__:null,GenerateMeshBVHWorker:qL},Symbol.toStringTag,{value:"Module"}));export{zT as $physicsKey,ve as ActionBuilder,V1 as ActionCollection,ks as ActionModel,kw as Addressables,Tc as AlignmentConstraint,qa as AmbientMode,Ft as Animation,mh as AnimationCurve,dp as AnimationExtension,im as AnimationTrackHandler,Ga as AnimationUtils,Rt as Animator,Mo as AnimatorConditionMode,gs as AnimatorController,Bf as AnimatorControllerParameterType,Ec as AnimatorStateInfo,bh as Antialiasing,Ln as Application,j_ as AssetDatabase,ce as AssetReference,_a as AudioExtension,zn as AudioListener,ns as AudioSource,sm as AudioTrackHandler,Go as Avatar,zr as AvatarBlink_Simple,Kf as AvatarEyeLook_Rotation,hC as AvatarLoader,hi as AvatarMarker,fv as AvatarModel,Uc as Avatar_Brain_LookAt,zc as Avatar_MouthShapes,Xf as Avatar_MustacheShake,Nn as Avatar_POI,Xa as Axes,Ja as AxesHelper,_g as BUILD_TIME,ps as BaseUIComponent,Jf as BasicIKConstraint,Z0 as BehaviorExtension,Jt as BehaviorModel,Ir as BlobStorage,Np as BloomEffect,Nu as BoxCollider,ea as BoxGizmo,Bo as BoxHelperComponent,no as Button,Po as ButtonsFactory,jx as CallDirection,Un as CallInfo,ci as Camera,Fc as CameraTargetReachedEvent,_l as Canvas,Ko as CanvasGroup,Wn as CapsuleCollider,B0 as ChangeMaterialOnClick,Xr as ChangeTransformOnClick,Nr as CharacterController,$n as CharacterControllerInput,_h as ChromaticAberration,Oi as CircularBuffer,Io as ClearFlags,bn as ClipExtrapolation,ui as Collider,Ax as Collision,ku as CollisionDetectionMode,or as ColorAdjustments,Pl as ColorBySpeedModule,Ip as ColorOverLifetimeModule,$R as Component,I as Component$1,uc as ComponentLifecycleEvents,GL as Components,y_ as ConnectionEvents,Ex as ContactPoint,Vc as ContactShadows,J as Context,IR as ContextArgs,me as ContextEvent,pe as ContextRegistry,nm as ControlTrackHandler,Jr as CustomBranding,o1 as CustomShader,mu as DefaultReflectionMode,n0 as Deletable,Wu as DeleteBox,As as DepthOfField,Vu as DeviceFlag,X as DeviceUtilities,dC as DocumentExtension,Hr as DragControls,r0 as DragMode,Hn as DropListener,h0 as Duplicatable,xh as EffectWrapper,eo as EmissionModule,ul as EmphasizeOnClick,JS as EngineLoadingView,cm as EnvironmentScene,xe as EventList,Ru as EventListEvent,ii as EventSystem,qu as EventTrigger,y1 as FieldWithDefault,_f as FileReference,Aw as FileReferenceSerializer,cE as FileSpawnModel,Gx as File_Event,fy as FixedJoint,xl as Fog,Oe as FrameEvent,jd as GENERATOR,P as GameObject,$ as Gizmos,P0 as GltfExport,S0 as GltfExportBox,ia as Gradient,lh as Graphic,Au as GraphicRaycaster,Jl as Graphics,Sl as GridHelper,ay as GridLayoutGroup,en as GroundProjectedEnv,Wo as GroupActionModel,Du as HideFlags,pp as HideOnStart,dh as HingeJoint,ry as HorizontalLayoutGroup,DM as HostData,El as Image,bf as ImageReference,Tw as ImageReferenceSerializer,Sy as InheritVelocityModule,n_ as Input,oi as InputEventQueue,Be as InputEvents,Yy as InputField,w0 as InstanceHandle,Ju as InstancingHandler,ms as InstancingUtil,X_ as InstantiateEvent,jt as InstantiateIdProvider,Fs as InstantiateOptions,s0 as Interactable,$h as InternalScreenshotUtils,aM as JoinedRoomResponse,Yk as KeyEventArgs,vi as Keyframe,ph as LODGroup,Cl as LODModel,lM as LeftRoomResponse,yi as Light,Nw as LightData,gt as LimitVelocityOverLifetimeModule,AL as LoadingElementOptions,i0 as LogStats,ki as LogType,Ky as LookAt,Fr as LookAtConstraint,A as MODULES,Wt as MainModule,qy as MarkerType,ch as MaskableGraphic,W as Mathf,Fo as MeshCollider,Qc as MeshRenderer,Z as MinMaxCurve,sa as MinMaxGradient,rc as NEKeyboardEvent,An as NEPointerEvent,gv as NeedleButtonElement,l0 as NeedleEngineModelLoader,cv as NeedleEngineWebComponent,un as NeedleMenu,Bd as NeedlePatchesKey,Pg as NeedleXRController,ne as NeedleXRSession,__ as NeedleXRSync,O_ as NeedleXRUtils,kp as NestedGltf,b_ as NetworkConnection,nn as NetworkedStreamEvents,hd as NetworkedStreams,_y as Networking,Y_ as NewInstanceModel,Ce as NoiseModule,ji as ObjectRaycaster,wo as ObjectUtils,ta as OffsetConstraint,Md as OneEuroFilter,og as OneEuroFilterXYZ,Al as OpenURL,_e as OrbitControls,bl as Outline,v_ as OwnershipEvent,Ag as OwnershipModel,Ea as PUBLIC_KEY,Zr as Padding,Ap as ParticleBurst,Cy as ParticleSubEmitter,yh as ParticleSystem,sr as ParticleSystemBaseBehaviour,ds as ParticleSystemRenderer,Ep as ParticleSystemShapeType,Bu as PeerHandle,g_ as PeerNetworking,Gg as Physics,J0 as PhysicsExtension,xt as PhysicsMaterialCombine,Sh as PixelationEffect,Jc as PlayAnimationOnClick,Vo as PlayAudioOnClick,Tl as PlayableDirector,Nl as PlayerColor,Ms as PlayerState,Q1 as PlayerStateEvent,X0 as PlayerSync,Dw as PlayerView,Bw as PlayerViewManager,cd as PointerEventData,Ud as PointerType,rt as PostProcessingEffect,ft as PostProcessingEffectOrder,zy as PostProcessingHandler,pl as PreliminaryAction,eh as PreliminaryTrigger,zo as PreviewHelper,Cr as PrimitiveType,de as Progress,Jm as PromiseAllWithErrors,Zm as PromiseErrorResult,he as RGBAColor,nC as RapierPhysics,am as RawImage,Qs as RaycastOptions,Z1 as Rect,Ts as RectTransform,qc as ReflectionProbe,mr as RegisteredAnimationInfo,qp as RemoteSkybox,Ac as RenderTexture,Cx as RenderTextureSerializer,Ui as Renderer,zw as RendererData,ep as RendererLightmap,dt as Rigidbody,Qe as RigidbodyConstraints,ie as RoomEvents,hs as RotationBySpeedModule,Es as RotationOverLifetimeModule,Qu as SceneLightSettings,Ze as SceneSwitcher,ar as ScreenCapture,to as ScreenSpaceAmbientOcclusion,Is as ScreenSpaceAmbientOcclusionN8,Ss as SendQueue,df as SerializationContext,F0 as SetActiveOnClick,Rh as ShadowCatcher,xy as ShapeModule,Ph as SharpeningEffect,tm as SignalAsset,Dh as SignalReceiver,jh as SignalReceiverEvent,Fh as SignalTrackHandler,K1 as Size,bi as SizeBySpeedModule,na as SizeOverLifetimeModule,x0 as SkinnedMeshRenderer,Yp as SmoothFollow,Dc as SpatialGrabRaycaster,Nh as SpatialHtml,Kp as SpatialTrigger,vn as SpatialTriggerReceiver,Zp as SpectatorCamera,el as SphereCollider,Hg as SphereIntersection,Ix as SphereOverlapResult,Qn as Sprite,fl as SpriteData,gi as SpriteRenderer,gl as SpriteSheet,YR as StateMachineBehaviour,Gf as StreamEndedEvent,Lx as StreamReceivedEvent,Bp as SubEmitterSystem,Wy as SyncedCamera,Ls as SyncedRoom,sn as SyncedTransform,N0 as TapGestureTrigger,_p as TeleportTarget,Hy as TestRunner,zL as TestSceneUtils,Gy as TestSimulateUserData,Nt as Text,ny as TextBuilder,Pp as TextExtension,Vt as TextureSheetAnimationModule,yn as TiltShiftEffect,Vw as Time,nr as ToneMappingEffect,Bh as TrackHandler,qi as TrackType,We as TrailModule,ut as TransformData,da as TransformGizmo,At as TriggerBuilder,dl as TriggerModel,R as TypeStore,zf as UIRaycastUtils,oh as UIRootComponent,O0 as USDDocument,mi as USDObject,C1 as USDWriter,gn as USDZExporter,P1 as USDZExporter$1,Kr as USDZText,hy as USDZUIExtension,Px as UriSerializer,$c as UsageMarker,cM as UserJoinedOrLeftRoomModel,ws as VERSION,j0 as VariantAction,qe as VelocityOverLifetimeModule,oy as VerticalLayoutGroup,yt as VideoPlayer,Co as ViewDevice,la as Vignette,th as VisibilityAction,Do as Voip,Ml as Volume,N as VolumeParameter,Fp as VolumeProfile,dR as WaitForFrames,Iw as WaitForPromise,wf as WaitForSeconds,lo as Watch,Hh as WebARCameraBackground,$o as WebARSessionRoot,wp as WebXR,ml as WebXRButtonFactory,Gh as WebXRImageTracking,ro as WebXRImageTrackingModel,ao as WebXRPlaneTracking,tv as WebXRTrackedImage,oo as XRControllerFollow,pn as XRControllerModel,Ni as XRControllerMovement,os as XRFlag,um as XRRig,Di as XRState,rn as XRStateFlag,uC as __Ignore,z_ as __internalNotifyObjectDestroyed,En as activeInHierarchyFieldName,pb as addAttributeChangeCallback,Ei as addComponent,EE as addCustomExtensionPlugin,Mr as addNewComponent,Dd as addPatch,ou as apply,VR as applyHMRChanges,uw as applyPrototypeExtensions,Q_ as beginListenDestroy,Z_ as beginListenInstantiate,Rg as binaryIdentifierCasts,AR as build_scene_functions,xr as builtinComponentKeyName,lv as calculateProgress01,hk as clearMessages,vT as colorSerializer,iw as compareAssociation,Tu as componentSerializer,Fb as copyTexture,mx as createMotion,ri as debugNet,ac as debugOwner,T1 as decompressGpuTexture,ql as deepClone,vs as delay,Xl as delayForFrames,su as deserializeObject,Ai as destroy,fw as destroyComponentInstance,qx as determineMimeTypeFromExtension,Te as disposeObjectResources,on as disposeStream,oc as editorGuidKeyName,wr as enableSpatialConsole,_T as euler,CT as eventListSerializer,VL as exportAsGLTF,gf as findByGuid,xc as findObjectOfType,bw as findObjectsOfType,Xg as findResourceUsers,zb as fitObjectIntoVolume,Ar as foreachComponent,hu as foreachComponentEnumerator,Pk as forward,gb as generateQRCode,K_ as generateSeed,si as getBoundingBox,Cb as getCameraController,Rr as getComponent,_c as getComponentInChildren,wc as getComponentInParent,bc as getComponents,Wa as getComponentsInChildren,nu as getComponentsInParent,b1 as getFormattedDate,Mt as getIconElement,Of as getIconTexture,xs as getLoader,vc as getOrAddComponent,C as getParam,Mk as getParentHierarchyPath,VO as getPath,sM as getPeerOptions,p_ as getPeerjsInstance,kM as getResourceUserCount,kb as getTempColor,bs as getTempQuaternion,q as getTempVector,Hl as getUrlParams,Ub as getVisibleInCustomShadowRendering,Eb as getWorldDirection,ug as getWorldEuler,ee as getWorldPosition,Se as getWorldQuaternion,Ad as getWorldRotation,Ge as getWorldScale,Js as hasCommercialLicense,kc as hasIndieLicense,Mu as hasPointerEventComponent,Zs as hasProLicense,Hb as hideDebugConsole,E1 as imageToCanvas,Ha as instantiate,a1 as invokeLoadedImportPluginHooks,s_ as invokeXRSessionEnd,i_ as invokeXRSessionStart,_w as isActiveInHierarchy,Va as isActiveSelf,QO as isAndroidDevice,jb as isAnimationAction,Tx as isComponent,UO as isDebugMode,HO as isDesktop,Er as isDestroyed,F as isDevEnvironment,PM as isDisposed,NL as isExporting,Rx as isGLTFModel,sb as isHostedOnGlitch,Df as isHotReloadEnabled,NR as isHotReloading,qO as isIPad,qw as isIconElement,Xt as isLocalNetwork,KO as isMacOS,GO as isMobileDevice,YO as isMozillaXR,ek as isQuest,B_ as isResourceTrackingEnabled,JO as isSafari,au as isUsingInstancing,ZO as isiOS,XO as isiPad,OL as loadAsset,av as loadSync,Id as logHierarchy,yk as lookAtInverse,Kl as lookAtObject,vk as lookAtScreenPoint,NO as makeId,hb as makeIdFromRandomWords,as as makeNameSafe,ww as markAsInstancedRendered,tk as microphonePermissionsGranted,FO as nameof,rb as nameofFactory,Sx as objectSerializer,Qk as offXRSessionEnd,Xk as offXRSessionStart,hT as onAfterRender,cT as onBeforeRender,aT as onClear,lT as onDestroy,vx as onInitialized,bx as onStart,_x as onUpdate,Cg as onXRSessionEnd,Fd as onXRSessionStart,qS as parseSync,Nb as placeOnSurface,gg as postprocessFBXMaterials,uT as prefix,ab as pushState,WO as randomNumber,Tg as registerBinaryType,bu as registerComponent,y0 as registerComponentExtension,us as registerCustomEffectType,v0 as registerExportExtensions,Ku as registerExtensions,lx as registerHotReloadType,wg as registerLoader,ew as registerPrefabProvider,pw as registerPrototypeExtensions,NM as registerType,ub as relativePathPrefix,mb as removeAttributeChangeCallback,mf as removeComponent,AE as removeCustomImportExtensionType,Gk as removePatch,yo as resolveUrl,db as sanitizeString,zS as saveImage,cL as screenshot,Jy as screenshot2,nf as sendDestroyed,m as serializable,rw as serializeObject,Dr as serializeable,Sc as setActive,bb as setAllowBalloonMessages,rk as setAllowOverlayMessages,Td as setAutoFitEnabled,rg as setCameraController,Sw as setDestroyed,Dk as setDevEnvironment,qg as setDisposable,$a as setDontDestroy,Qm as setOrAddParamsToUrl,zO as setParam,Gl as setParamWithoutReload,nM as setPeerOptions,CM as setResourceTrackingEnabled,Ym as setState,mg as setVisibleInCustomShadowRendering,pg as setWorldEuler,lt as setWorldPosition,br as setWorldPositionXYZ,Yi as setWorldQuaternion,dg as setWorldQuaternionXYZW,Lb as setWorldRotation,Zl as setWorldRotationXYZ,Ta as setWorldScale,ic as showBalloonError,De as showBalloonMessage,be as showBalloonWarning,bg as showDebugConsole,fk as slerp,fc as syncDestroy,q0 as syncField,of as syncInstantiate,Rk as textureToCanvas,d_ as tryCastBinary,Qx as tryDetermineMimetypeFromBinary,Xx as tryDetermineMimetypeFromURL,Ma as tryFindObject,u_ as tryGetGuid,cx as unregisterHotReloadType,Km as unwatchWrite,Pb as useForAutoFit,Tt as validate,Od as watchWrite};
|
|
1606
|
+
`),ge(this,ya).innerHTML=ge(this,wi).innerHTML,ge(this,ya).style.cssText="display: flex; align-items: center; justify-content: center;",ge(this,wi).innerHTML=ge(this,ya).outerHTML,ge(this,fa).innerHTML=ge(this,wi).outerHTML,ge(this,fa).prepend(ge(this,va)),fu(kf,{element:ge(this,fa)}),(e=ge(this,Dl))==null||e.disconnect(),ge(this,Dl)??zs(this,Dl,new MutationObserver(()=>dd(this,pm,cC).call(this))),ge(this,Dl).observe(ge(this,wi),{attributes:!0}),mv&&console.log("Needle Button updated")},cC=function(){ge(this,wi)&&(ge(this,wi).style.display==="none"?this.style.display="none":this.style.display==="none"&&(this.style.display=""))},mm=new WeakMap,a(gv,"observedAttributes",["ar","vr","quicklook"]),typeof window<"u"&&!window.customElements.get(aC)&&window.customElements.define(aC,gv);const id=C("debugavatar");class fv{constructor(e,t,s,o){a(this,"root"),a(this,"head"),a(this,"leftHand"),a(this,"rigthHand");var r;this.root=e,this.head=t,this.leftHand=s,this.rigthHand=o,(r=this.root)==null||r.traverse(l=>l.layers.set(2))}get isValid(){return this.head!==null&&this.head!==void 0}}class hC{constructor(){a(this,"avatarRegistryUrl",null)}async getOrCreateNewAvatarInstance(e,t){if(!t)return console.error("Can not create avatar: failed to provide id or root object"),null;let s=null;if(typeof t=="string"){if(s=await this.loadAvatar(e,t),!s){const r=new Fs;s=P.instantiate(Ma(t,e.scene),r)}}else s=t;if(!s)return null;const o=this.findAvatar(s);return o.isValid?(id&&console.log("[Custom Avatar] valid config",t,id?o:""),o):(console.warn("[Custom Avatar] config isn't valid",t,id?o:""),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(id&&console.log("[Custom Avatar] "+t+", loading..."),t.endsWith(".glb")||(t+=".glb"),this.avatarRegistryUrl===null){const o=await fetch("./"+t);let r=null;if(o.ok){const c=await o.blob();c&&(r=await c.arrayBuffer())}if(!r)return null;const l=await xs().parseSync(e,r,null,0);return l?.scene??null}const s=new Rn;return jf(s,e),new Promise((o,r)=>{const l=this.avatarRegistryUrl+"/"+t;s.load(l,async c=>{await xs().createBuiltinComponents(e,l,c,null,void 0),o(c.scene)},c=>{id&&console.log("[Custom Avatar] "+c.loaded/c.total*100+"% loaded of "+c.total/1024+"kB")},c=>{console.error("[Custom Avatar] Error when loading: "+c),o(null)})})}cacheModel(e,t){}findAvatar(e){const t=e;let s=t;s.children.length==1&&(s=e.children[0]);let o=this.findAvatarPart(s,["head"]);const r=this.findAvatarPart(s,["left","hand"]),l=this.findAvatarPart(s,["right","hand"]);if(!o){o=t;const c=new S;new Si().setFromObject(o).getSize(c);const h=Math.max(c.x,c.y,c.z);console.warn("[Custom Avatar] Normalizing head scale, it's too big: "+h+" meters! Should be < 0.3m"),h>.3&&o.scale.multiplyScalar(1/h*.3)}return new fv(t,o,r,l)}findAvatarPart(e,t){const s=e.name.toLowerCase();let o=!0;for(const r of t){if(!o)break;s.indexOf(r)===-1&&(o=!1)}if(o)return e;if(e.children)for(const r of e.children){const l=this.findAvatarPart(r,t);if(l)return l}return null}handleCustomAvatarErrors(e){if(!e.ok)throw Error(e.statusText);return e}}class dC{get extensionName(){return"DocumentExtension"}onAfterBuildDocument(e){}}class uC{}const qL=Object.freeze(Object.defineProperty({__proto__:null,ActionBuilder:ve,ActionCollection:V1,ActionModel:ks,AlignmentConstraint:Tc,Animation:Ft,AnimationCurve:mh,AnimationExtension:dp,AnimationTrackHandler:im,Animator:Rt,AnimatorController:gs,Antialiasing:bh,AudioExtension:_a,AudioListener:zn,AudioSource:ns,AudioTrackHandler:sm,Avatar:Go,AvatarBlink_Simple:zr,AvatarEyeLook_Rotation:Kf,AvatarLoader:hC,AvatarMarker:hi,AvatarModel:fv,Avatar_Brain_LookAt:Uc,Avatar_MouthShapes:zc,Avatar_MustacheShake:Xf,Avatar_POI:Nn,AxesHelper:Ja,BaseUIComponent:ps,BasicIKConstraint:Jf,BehaviorExtension:Z0,BehaviorModel:Jt,BloomEffect:Np,BoxCollider:Nu,BoxGizmo:ea,BoxHelperComponent:Bo,Button:no,CallInfo:Un,Camera:ci,CameraTargetReachedEvent:Fc,Canvas:_l,CanvasGroup:Ko,CapsuleCollider:Wn,ChangeMaterialOnClick:B0,ChangeTransformOnClick:Xr,CharacterController:Nr,CharacterControllerInput:$n,ChromaticAberration:_h,Collider:ui,ColorAdjustments:or,ColorBySpeedModule:Pl,ColorOverLifetimeModule:Ip,ContactShadows:Vc,ControlTrackHandler:nm,CustomBranding:Jr,Deletable:n0,DeleteBox:Wu,DepthOfField:As,DeviceFlag:Vu,DocumentExtension:dC,DragControls:Hr,DropListener:Hn,Duplicatable:h0,EffectWrapper:xh,EmissionModule:eo,EmphasizeOnClick:ul,EnvironmentScene:cm,EventList:xe,EventListEvent:Ru,EventSystem:ii,EventTrigger:qu,FieldWithDefault:y1,FixedJoint:fy,Fog:xl,GltfExport:P0,GltfExportBox:S0,Gradient:ia,Graphic:lh,GraphicRaycaster:Au,GridHelper:Sl,GridLayoutGroup:ay,GroundProjectedEnv:en,GroupActionModel:Wo,HideOnStart:pp,HingeJoint:dh,HorizontalLayoutGroup:ry,Image:El,InheritVelocityModule:Sy,InputField:Yy,InstanceHandle:w0,InstancingHandler:Ju,Interactable:s0,Keyframe:vi,LODGroup:ph,LODModel:Cl,Light:yi,LimitVelocityOverLifetimeModule:gt,LogStats:i0,LookAt:Ky,LookAtConstraint:Fr,MainModule:Wt,MaskableGraphic:ch,MeshCollider:Fo,MeshRenderer:Qc,MinMaxCurve:Z,MinMaxGradient:sa,NeedleMenu:un,NestedGltf:kp,Networking:_y,NoiseModule:Ce,ObjectRaycaster:ji,OffsetConstraint:ta,OpenURL:Al,OrbitControls:_e,Outline:bl,Padding:Zr,ParticleBurst:Ap,ParticleSubEmitter:Cy,ParticleSystem:yh,ParticleSystemRenderer:ds,PhysicsExtension:J0,PixelationEffect:Sh,PlayAnimationOnClick:Jc,PlayAudioOnClick:Vo,PlayableDirector:Tl,PlayerColor:Nl,PointerEventData:cd,PostProcessingHandler:zy,PreliminaryAction:pl,PreliminaryTrigger:eh,RawImage:am,Rect:Z1,RectTransform:Ts,ReflectionProbe:qc,RegisteredAnimationInfo:mr,RemoteSkybox:qp,Renderer:Ui,RendererLightmap:ep,Rigidbody:dt,RotationBySpeedModule:hs,RotationOverLifetimeModule:Es,SceneSwitcher:Ze,ScreenCapture:ar,ScreenSpaceAmbientOcclusion:to,ScreenSpaceAmbientOcclusionN8:Is,SetActiveOnClick:F0,ShadowCatcher:Rh,ShapeModule:xy,SharpeningEffect:Ph,SignalAsset:tm,SignalReceiver:Dh,SignalReceiverEvent:jh,SignalTrackHandler:Fh,Size:K1,SizeBySpeedModule:bi,SizeOverLifetimeModule:na,SkinnedMeshRenderer:x0,SmoothFollow:Yp,SpatialGrabRaycaster:Dc,SpatialHtml:Nh,SpatialTrigger:Kp,SpatialTriggerReceiver:vn,SpectatorCamera:Zp,SphereCollider:el,Sprite:Qn,SpriteData:fl,SpriteRenderer:gi,SpriteSheet:gl,SubEmitterSystem:Bp,SyncedCamera:Wy,SyncedRoom:Ls,SyncedTransform:sn,TapGestureTrigger:N0,TeleportTarget:_p,TestRunner:Hy,TestSimulateUserData:Gy,Text:Nt,TextBuilder:ny,TextExtension:Pp,TextureSheetAnimationModule:Vt,TiltShiftEffect:yn,ToneMappingEffect:nr,TrailModule:We,TransformData:ut,TransformGizmo:da,TriggerBuilder:At,TriggerModel:dl,UIRaycastUtils:zf,UIRootComponent:oh,USDZExporter:gn,USDZText:Kr,USDZUIExtension:hy,UsageMarker:$c,VariantAction:j0,VelocityOverLifetimeModule:qe,VerticalLayoutGroup:oy,VideoPlayer:yt,Vignette:la,VisibilityAction:th,Voip:Do,Volume:Ml,VolumeParameter:N,VolumeProfile:Fp,WebARCameraBackground:Hh,WebARSessionRoot:$o,WebXR:wp,WebXRImageTracking:Gh,WebXRImageTrackingModel:ro,WebXRPlaneTracking:ao,WebXRTrackedImage:tv,XRControllerFollow:oo,XRControllerModel:pn,XRControllerMovement:Ni,XRFlag:os,XRRig:um,XRState:Di,__Ignore:uC},Symbol.toStringTag,{value:"Module"})),gm=C("debugmissingcamera");pe.registerCallback(me.MissingCamera,n=>{var e,t,s;gm&&console.warn("Creating missing camera");const o=n.context.scene,r=new we;r.name="Default Fallback Camera",o.add(r);const l=new ci;if(l.sourceId=((t=(e=n.files)==null?void 0:e[0])==null?void 0:t.src)??"unknown",l.fieldOfView=35,n.context.domElement.getAttribute("transparent")!=null)l.clearFlags=Io.Uninitialized;else if((s=n.context.domElement.getAttribute("background-image"))!=null&&s.length||n.context.lightmaps.tryGetSkybox(l.sourceId))l.clearFlags=Io.Skybox,n.context.domElement.getAttribute("background-blurriness")===null&&(n.context.scene.backgroundBlurriness=.2);else{if(l.clearFlags=Io.SolidColor,!n.context.domElement.getAttribute("background-color")){let d="#efefef";typeof window!==void 0&&window.matchMedia("(prefers-color-scheme: dark)").matches&&(d="#1f1f1f"),o.background=new oe(d)}if(!o.environment){const d=new HP(n.context.renderer),u=new cm("neutral");o.environment=d.fromScene(u,.025).texture}}const c=Mr(r,l,!0);r.position.x=0,r.position.y=1,r.position.z=2;const h=n.context.domElement;return h?.cameraControls!=!1&&pC(n.context,c),c}),pe.registerCallback(me.ContextCreated,n=>{if(!n.context.mainCamera){gm&&console.log("Will not auto-fit because a default camera exists");return}const e=n.context.domElement;if(e?.cameraControls==!0){const t=Cb(n.context.mainCamera);if(t?.isCameraController==!0){gm&&console.log("Will not auto-fit because a camera controller exists");return}pC(n.context)}});function pC(n,e){e=e??n.mainCameraComponent;const t=e?.gameObject;if(gm&&console.log("Creating default camera controls",e?.name),t){const s=vc(t,_e);s.sourceId=e?.sourceId??"unknown";const o=n.domElement.getAttribute("auto-rotate");if(s.autoRotate=o!=null&&o!="0"&&o?.toLowerCase()!="false",s.autoRotateSpeed=.5,s.autoFit=!0,s.autoRotate&&o){const r=parseFloat(o);isNaN(r)||(s.autoRotateSpeed=r)}}else console.warn("Missing camera object, can not add orbit controls")}pe.registerCallback(me.ContextCreated,n=>{const e=n.context.domElement.getAttribute("autoplay");if(e!==void 0&&(e===""||e==="true"||e==="1")&&n.files)for(const t of n.files)P.foreachComponent(t.file.scene,s=>{if(s.enabled!==!1){if(s instanceof Ft&&s.playAutomatically||s instanceof Rt||s instanceof Tl&&s.playOnAwake===!0)return!0;if(s instanceof Ft)return s.playAutomatically=!0,!0;if(s instanceof Tl)return s.playOnAwake=!0,!0}},!0)!==!0&&Ga.assignAnimationsFromFile(t.file,{createAnimationComponent:(s,o)=>Ei(s,Ft)})});class XL extends PO{constructor(){super(new Worker(new URL("/generateMeshBVH.worker-BaNp_Xtp.js",import.meta.url),{type:"module"})),this.name="GenerateMeshBVHWorker"}runTask(e,t,s={}){return new Promise((o,r)=>{if(t.getAttribute("position").isInterleavedBufferAttribute||t.index&&t.index.isInterleavedBufferAttribute)throw new Error("GenerateMeshBVHWorker: InterleavedBufferAttribute are not supported for the geometry attributes.");e.onerror=d=>{r(new Error(`[GenerateMeshBVHWorker] ${d.message||"Unknown error. Please check the server console. If you're using vite try adding 'three-mesh-bvh' to 'optimizeDeps.exclude' in your vite.config.js"}`))},e.onmessage=d=>{const{data:u}=d;if(u.error)r(new Error(u.error)),e.onmessage=null;else if(u.serialized){const{serialized:p,position:g}=u,f=OO.deserialize(p,t,{setIndex:!1}),y=Object.assign({setBoundingBox:!0},s);if(t.attributes.position.array=g,p.index)if(t.index)t.index.array=p.index;else{const v=new _t(p.index,1,!1);t.setIndex(v)}y.setBoundingBox&&(t.boundingBox=f.getBoundingBox(new Si)),s.onProgress&&s.onProgress(u.progress),o(f),e.onmessage=null}else s.onProgress&&s.onProgress(u.progress)};const l=t.index?t.index.array:null,c=t.attributes.position.array,h=[c];l&&h.push(l),e.postMessage({index:l,position:c,options:{...s,onProgress:null,includedProgressCallback:!!s.onProgress,groups:[...t.groups]}},h.map(d=>d.buffer).filter(d=>typeof SharedArrayBuffer>"u"||!(d instanceof SharedArrayBuffer)))})}}const QL=Object.freeze(Object.defineProperty({__proto__:null,GenerateMeshBVHWorker:XL},Symbol.toStringTag,{value:"Module"}));export{zT as $physicsKey,ve as ActionBuilder,V1 as ActionCollection,ks as ActionModel,kw as Addressables,Tc as AlignmentConstraint,qa as AmbientMode,Ft as Animation,mh as AnimationCurve,dp as AnimationExtension,im as AnimationTrackHandler,Ga as AnimationUtils,Rt as Animator,Mo as AnimatorConditionMode,gs as AnimatorController,Bf as AnimatorControllerParameterType,Ec as AnimatorStateInfo,bh as Antialiasing,Ln as Application,j_ as AssetDatabase,ce as AssetReference,_a as AudioExtension,zn as AudioListener,ns as AudioSource,sm as AudioTrackHandler,Go as Avatar,zr as AvatarBlink_Simple,Kf as AvatarEyeLook_Rotation,hC as AvatarLoader,hi as AvatarMarker,fv as AvatarModel,Uc as Avatar_Brain_LookAt,zc as Avatar_MouthShapes,Xf as Avatar_MustacheShake,Nn as Avatar_POI,Xa as Axes,Ja as AxesHelper,_g as BUILD_TIME,ps as BaseUIComponent,Jf as BasicIKConstraint,Z0 as BehaviorExtension,Jt as BehaviorModel,Ir as BlobStorage,Np as BloomEffect,Nu as BoxCollider,ea as BoxGizmo,Bo as BoxHelperComponent,no as Button,Po as ButtonsFactory,jx as CallDirection,Un as CallInfo,ci as Camera,Fc as CameraTargetReachedEvent,_l as Canvas,Ko as CanvasGroup,Wn as CapsuleCollider,B0 as ChangeMaterialOnClick,Xr as ChangeTransformOnClick,Nr as CharacterController,$n as CharacterControllerInput,_h as ChromaticAberration,Oi as CircularBuffer,Io as ClearFlags,bn as ClipExtrapolation,ui as Collider,Ax as Collision,ku as CollisionDetectionMode,or as ColorAdjustments,Pl as ColorBySpeedModule,Ip as ColorOverLifetimeModule,$R as Component,I as Component$1,uc as ComponentLifecycleEvents,qL as Components,y_ as ConnectionEvents,Ex as ContactPoint,Vc as ContactShadows,J as Context,IR as ContextArgs,me as ContextEvent,pe as ContextRegistry,nm as ControlTrackHandler,Jr as CustomBranding,o1 as CustomShader,mu as DefaultReflectionMode,n0 as Deletable,Wu as DeleteBox,As as DepthOfField,Vu as DeviceFlag,X as DeviceUtilities,dC as DocumentExtension,Hr as DragControls,r0 as DragMode,Hn as DropListener,h0 as Duplicatable,xh as EffectWrapper,eo as EmissionModule,ul as EmphasizeOnClick,JS as EngineLoadingView,cm as EnvironmentScene,xe as EventList,Ru as EventListEvent,ii as EventSystem,qu as EventTrigger,y1 as FieldWithDefault,_f as FileReference,Aw as FileReferenceSerializer,cE as FileSpawnModel,Gx as File_Event,fy as FixedJoint,xl as Fog,Oe as FrameEvent,jd as GENERATOR,P as GameObject,$ as Gizmos,P0 as GltfExport,S0 as GltfExportBox,ia as Gradient,lh as Graphic,Au as GraphicRaycaster,Jl as Graphics,Sl as GridHelper,ay as GridLayoutGroup,en as GroundProjectedEnv,Wo as GroupActionModel,Du as HideFlags,pp as HideOnStart,dh as HingeJoint,ry as HorizontalLayoutGroup,DM as HostData,El as Image,bf as ImageReference,Tw as ImageReferenceSerializer,Sy as InheritVelocityModule,n_ as Input,oi as InputEventQueue,Be as InputEvents,Yy as InputField,w0 as InstanceHandle,Ju as InstancingHandler,ms as InstancingUtil,X_ as InstantiateEvent,jt as InstantiateIdProvider,Fs as InstantiateOptions,s0 as Interactable,$h as InternalScreenshotUtils,aM as JoinedRoomResponse,Yk as KeyEventArgs,vi as Keyframe,ph as LODGroup,Cl as LODModel,lM as LeftRoomResponse,yi as Light,Nw as LightData,gt as LimitVelocityOverLifetimeModule,IL as LoadingElementOptions,i0 as LogStats,ki as LogType,Ky as LookAt,Fr as LookAtConstraint,A as MODULES,Wt as MainModule,qy as MarkerType,ch as MaskableGraphic,W as Mathf,Fo as MeshCollider,Qc as MeshRenderer,Z as MinMaxCurve,sa as MinMaxGradient,rc as NEKeyboardEvent,An as NEPointerEvent,gv as NeedleButtonElement,l0 as NeedleEngineModelLoader,cv as NeedleEngineWebComponent,un as NeedleMenu,Bd as NeedlePatchesKey,Pg as NeedleXRController,ne as NeedleXRSession,__ as NeedleXRSync,O_ as NeedleXRUtils,kp as NestedGltf,b_ as NetworkConnection,nn as NetworkedStreamEvents,hd as NetworkedStreams,_y as Networking,Y_ as NewInstanceModel,Ce as NoiseModule,ji as ObjectRaycaster,wo as ObjectUtils,ta as OffsetConstraint,Md as OneEuroFilter,og as OneEuroFilterXYZ,Al as OpenURL,_e as OrbitControls,bl as Outline,v_ as OwnershipEvent,Ag as OwnershipModel,Ea as PUBLIC_KEY,Zr as Padding,Ap as ParticleBurst,Cy as ParticleSubEmitter,yh as ParticleSystem,sr as ParticleSystemBaseBehaviour,ds as ParticleSystemRenderer,Ep as ParticleSystemShapeType,Bu as PeerHandle,g_ as PeerNetworking,Gg as Physics,J0 as PhysicsExtension,xt as PhysicsMaterialCombine,Sh as PixelationEffect,Jc as PlayAnimationOnClick,Vo as PlayAudioOnClick,Tl as PlayableDirector,Nl as PlayerColor,Ms as PlayerState,Q1 as PlayerStateEvent,X0 as PlayerSync,Dw as PlayerView,Bw as PlayerViewManager,cd as PointerEventData,Ud as PointerType,rt as PostProcessingEffect,ft as PostProcessingEffectOrder,zy as PostProcessingHandler,pl as PreliminaryAction,eh as PreliminaryTrigger,zo as PreviewHelper,Cr as PrimitiveType,de as Progress,Jm as PromiseAllWithErrors,Zm as PromiseErrorResult,he as RGBAColor,nC as RapierPhysics,am as RawImage,Qs as RaycastOptions,Z1 as Rect,Ts as RectTransform,qc as ReflectionProbe,mr as RegisteredAnimationInfo,qp as RemoteSkybox,Ac as RenderTexture,Cx as RenderTextureSerializer,Ui as Renderer,zw as RendererData,ep as RendererLightmap,dt as Rigidbody,Qe as RigidbodyConstraints,ie as RoomEvents,hs as RotationBySpeedModule,Es as RotationOverLifetimeModule,Qu as SceneLightSettings,Ze as SceneSwitcher,ar as ScreenCapture,to as ScreenSpaceAmbientOcclusion,Is as ScreenSpaceAmbientOcclusionN8,Ss as SendQueue,df as SerializationContext,F0 as SetActiveOnClick,Rh as ShadowCatcher,xy as ShapeModule,Ph as SharpeningEffect,tm as SignalAsset,Dh as SignalReceiver,jh as SignalReceiverEvent,Fh as SignalTrackHandler,K1 as Size,bi as SizeBySpeedModule,na as SizeOverLifetimeModule,x0 as SkinnedMeshRenderer,Yp as SmoothFollow,Dc as SpatialGrabRaycaster,Nh as SpatialHtml,Kp as SpatialTrigger,vn as SpatialTriggerReceiver,Zp as SpectatorCamera,el as SphereCollider,Hg as SphereIntersection,Ix as SphereOverlapResult,Qn as Sprite,fl as SpriteData,gi as SpriteRenderer,gl as SpriteSheet,YR as StateMachineBehaviour,Gf as StreamEndedEvent,Lx as StreamReceivedEvent,Bp as SubEmitterSystem,Wy as SyncedCamera,Ls as SyncedRoom,sn as SyncedTransform,N0 as TapGestureTrigger,_p as TeleportTarget,Hy as TestRunner,NL as TestSceneUtils,Gy as TestSimulateUserData,Nt as Text,ny as TextBuilder,Pp as TextExtension,Vt as TextureSheetAnimationModule,yn as TiltShiftEffect,Vw as Time,nr as ToneMappingEffect,Bh as TrackHandler,qi as TrackType,We as TrailModule,ut as TransformData,da as TransformGizmo,At as TriggerBuilder,dl as TriggerModel,R as TypeStore,zf as UIRaycastUtils,oh as UIRootComponent,O0 as USDDocument,mi as USDObject,C1 as USDWriter,gn as USDZExporter,P1 as USDZExporter$1,Kr as USDZText,hy as USDZUIExtension,Px as UriSerializer,$c as UsageMarker,cM as UserJoinedOrLeftRoomModel,ws as VERSION,j0 as VariantAction,qe as VelocityOverLifetimeModule,oy as VerticalLayoutGroup,yt as VideoPlayer,Co as ViewDevice,la as Vignette,th as VisibilityAction,Do as Voip,Ml as Volume,N as VolumeParameter,Fp as VolumeProfile,dR as WaitForFrames,Iw as WaitForPromise,wf as WaitForSeconds,lo as Watch,Hh as WebARCameraBackground,$o as WebARSessionRoot,wp as WebXR,ml as WebXRButtonFactory,Gh as WebXRImageTracking,ro as WebXRImageTrackingModel,ao as WebXRPlaneTracking,tv as WebXRTrackedImage,oo as XRControllerFollow,pn as XRControllerModel,Ni as XRControllerMovement,os as XRFlag,um as XRRig,Di as XRState,rn as XRStateFlag,uC as __Ignore,z_ as __internalNotifyObjectDestroyed,En as activeInHierarchyFieldName,pb as addAttributeChangeCallback,Ei as addComponent,EE as addCustomExtensionPlugin,Mr as addNewComponent,Dd as addPatch,ou as apply,VR as applyHMRChanges,uw as applyPrototypeExtensions,Q_ as beginListenDestroy,Z_ as beginListenInstantiate,Rg as binaryIdentifierCasts,AR as build_scene_functions,xr as builtinComponentKeyName,lv as calculateProgress01,hk as clearMessages,vT as colorSerializer,iw as compareAssociation,Tu as componentSerializer,Fb as copyTexture,mx as createMotion,ri as debugNet,ac as debugOwner,T1 as decompressGpuTexture,ql as deepClone,vs as delay,Xl as delayForFrames,su as deserializeObject,Ai as destroy,fw as destroyComponentInstance,qx as determineMimeTypeFromExtension,Te as disposeObjectResources,on as disposeStream,oc as editorGuidKeyName,wr as enableSpatialConsole,_T as euler,CT as eventListSerializer,$L as exportAsGLTF,gf as findByGuid,xc as findObjectOfType,bw as findObjectsOfType,Xg as findResourceUsers,zb as fitObjectIntoVolume,Ar as foreachComponent,hu as foreachComponentEnumerator,Pk as forward,gb as generateQRCode,K_ as generateSeed,si as getBoundingBox,Cb as getCameraController,Rr as getComponent,_c as getComponentInChildren,wc as getComponentInParent,bc as getComponents,Wa as getComponentsInChildren,nu as getComponentsInParent,b1 as getFormattedDate,Mt as getIconElement,Of as getIconTexture,xs as getLoader,vc as getOrAddComponent,C as getParam,Mk as getParentHierarchyPath,VO as getPath,sM as getPeerOptions,p_ as getPeerjsInstance,kM as getResourceUserCount,kb as getTempColor,bs as getTempQuaternion,q as getTempVector,Hl as getUrlParams,Ub as getVisibleInCustomShadowRendering,Eb as getWorldDirection,ug as getWorldEuler,ee as getWorldPosition,Se as getWorldQuaternion,Ad as getWorldRotation,Ge as getWorldScale,Js as hasCommercialLicense,kc as hasIndieLicense,Mu as hasPointerEventComponent,Zs as hasProLicense,Hb as hideDebugConsole,E1 as imageToCanvas,Ha as instantiate,a1 as invokeLoadedImportPluginHooks,s_ as invokeXRSessionEnd,i_ as invokeXRSessionStart,_w as isActiveInHierarchy,Va as isActiveSelf,QO as isAndroidDevice,jb as isAnimationAction,Tx as isComponent,UO as isDebugMode,HO as isDesktop,Er as isDestroyed,F as isDevEnvironment,PM as isDisposed,WL as isExporting,Rx as isGLTFModel,sb as isHostedOnGlitch,Df as isHotReloadEnabled,NR as isHotReloading,qO as isIPad,qw as isIconElement,Xt as isLocalNetwork,KO as isMacOS,GO as isMobileDevice,YO as isMozillaXR,ek as isQuest,B_ as isResourceTrackingEnabled,JO as isSafari,au as isUsingInstancing,ZO as isiOS,XO as isiPad,kL as loadAsset,av as loadSync,Id as logHierarchy,yk as lookAtInverse,Kl as lookAtObject,vk as lookAtScreenPoint,NO as makeId,hb as makeIdFromRandomWords,as as makeNameSafe,ww as markAsInstancedRendered,tk as microphonePermissionsGranted,FO as nameof,rb as nameofFactory,Sx as objectSerializer,Qk as offXRSessionEnd,Xk as offXRSessionStart,hT as onAfterRender,cT as onBeforeRender,aT as onClear,lT as onDestroy,vx as onInitialized,bx as onStart,_x as onUpdate,Cg as onXRSessionEnd,Fd as onXRSessionStart,qS as parseSync,Nb as placeOnSurface,gg as postprocessFBXMaterials,uT as prefix,ab as pushState,WO as randomNumber,Tg as registerBinaryType,bu as registerComponent,y0 as registerComponentExtension,us as registerCustomEffectType,v0 as registerExportExtensions,Ku as registerExtensions,lx as registerHotReloadType,wg as registerLoader,ew as registerPrefabProvider,pw as registerPrototypeExtensions,NM as registerType,ub as relativePathPrefix,mb as removeAttributeChangeCallback,mf as removeComponent,AE as removeCustomImportExtensionType,Gk as removePatch,yo as resolveUrl,db as sanitizeString,zS as saveImage,hL as screenshot,Jy as screenshot2,nf as sendDestroyed,m as serializable,rw as serializeObject,Dr as serializeable,Sc as setActive,bb as setAllowBalloonMessages,rk as setAllowOverlayMessages,Td as setAutoFitEnabled,rg as setCameraController,Sw as setDestroyed,Dk as setDevEnvironment,qg as setDisposable,$a as setDontDestroy,Qm as setOrAddParamsToUrl,zO as setParam,Gl as setParamWithoutReload,nM as setPeerOptions,CM as setResourceTrackingEnabled,Ym as setState,mg as setVisibleInCustomShadowRendering,pg as setWorldEuler,lt as setWorldPosition,br as setWorldPositionXYZ,Yi as setWorldQuaternion,dg as setWorldQuaternionXYZW,Lb as setWorldRotation,Zl as setWorldRotationXYZ,Ta as setWorldScale,ic as showBalloonError,De as showBalloonMessage,be as showBalloonWarning,bg as showDebugConsole,fk as slerp,fc as syncDestroy,q0 as syncField,of as syncInstantiate,Rk as textureToCanvas,d_ as tryCastBinary,Qx as tryDetermineMimetypeFromBinary,Xx as tryDetermineMimetypeFromURL,Ma as tryFindObject,u_ as tryGetGuid,cx as unregisterHotReloadType,Km as unwatchWrite,Pb as useForAutoFit,Tt as validate,Od as watchWrite};
|