@needle-tools/engine 5.0.1 → 5.0.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +7 -0
- package/SKILL.md +1 -1
- package/dist/{needle-engine.bundle-CoiOmZ11.min.js → needle-engine.bundle-B3ywqx5o.min.js} +2 -2
- package/dist/{needle-engine.bundle-CVtRrwCi.js → needle-engine.bundle-BoTyA-Le.js} +768 -753
- package/dist/{needle-engine.bundle-B5tG2TR8.umd.cjs → needle-engine.bundle-CzOPcOui.umd.cjs} +4 -4
- package/dist/needle-engine.d.ts +7 -0
- 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-components/Light.d.ts +8 -0
- package/lib/engine-components/Light.js +20 -0
- package/lib/engine-components/Light.js.map +1 -1
- package/package.json +2 -2
- package/src/engine-components/Light.ts +24 -0
package/dist/{needle-engine.bundle-B5tG2TR8.umd.cjs → needle-engine.bundle-CzOPcOui.umd.cjs}
RENAMED
|
@@ -140,7 +140,7 @@ void main(){
|
|
|
140
140
|
#__vconsole .vc-mask {
|
|
141
141
|
overflow: hidden;
|
|
142
142
|
}
|
|
143
|
-
`,Lo?.prepend(i),s===!0&&_v()<=0&&Bv(),console.log("🌵 Debug console has loaded")}},e.onerror=()=>{console.warn("🌵 Debug console failed to load."+(window.crossOriginIsolated?"This page is using cross-origin isolation, so external scripts can't be loaded.":"")),vl=!1,Zt=null},e.src="https://cdn.jsdelivr.net/npm/vconsole@3.15.1/dist/vconsole.min.js",document.body.appendChild(e)}function aC(){if(!globalThis.VConsole)return;const s=new VConsole.VConsolePlugin("needle-console","🌵 Inspect glTF"),e=()=>document.querySelector("#__vc_plug_"+s._id+" iframe");return s.on("renderTab",function(t){const i=globalThis["needle:codegen_files"];if(!i||i.length===0)return;let n=globalThis["needle:codegen_files"][0];const o=n.indexOf("?");o>-1&&(n=n.substring(0,o));const a=location.protocol+"//"+location.host+location.pathname+"/"+n,l=encodeURIComponent(a);s.fullUrl="https://viewer.needle.tools?inspect&file="+l;var h='<iframe src="" style="width: 100%; height: 99%; border: none;"></iframe>';t(h)}),s.on("show",function(){const t=e();t&&t.src!==s.fullUrl&&(t.src=s.fullUrl)}),s.on("hide",function(){const t=e();t&&(t.src="")}),s.on("addTopBar",function(t){var i=new Array;i.push({name:"Open in new window ↗",onClick:function(n){window.open(s.fullUrl,"_blank"),Zt?.hide()}}),i.push({name:"Reload",onClick:function(n){const o=e();o&&(o.src=s.fullUrl)}}),i.push({name:"Fullscreen",onClick:function(n){const o=e();o.requestFullscreen?o.requestFullscreen():o.webkitRequestFullscreen instanceof Function&&o.webkitRequestFullscreen()}}),t(i)}),s}const Up="padding: 10px; font-family: monospace;",h_="margin-bottom: 10px;",Io="margin-bottom: 10px; margin-top: 15px;",lC="width: 100%; border-collapse: collapse; border: 1px solid rgba(0,0,0,0.1); table-layout: fixed;",Fv="border: 1px solid rgba(0,0,0,0.1); padding: 5px;",cC=Fv,hC=Fv+" word-break: break-all;";function En(s,e=!1){e&&s.sort((i,n)=>(n.value?1:0)-(i.value?1:0));let t=`<table style='${lC}'>`;t+="<tbody>";for(const i of s){const n=typeof i.value=="boolean"?i.value?"✅":"❌":i.value;t+=`<tr><td style='${cC}'>${i.label}</td><td style='${hC}'>${n}</td></tr>`}return t+="</tbody></table>",t}function Uv(){try{if(document.createElement("canvas").getContext("webgl2"))return"✅"}catch{}return"❌"}function dC(){if(!globalThis.VConsole)return;const s=new VConsole.VConsolePlugin("device-utilities","📱 Device Info");return s.on("renderTab",function(e){let t=`<div style='${Up}'>`;const i=wC();t+=`<h3 style='${h_}'>Device: ${i}</h3>`,t+=En([{label:"💻 Desktop",value:exports.DeviceUtilities.isDesktop()},{label:"📱 Mobile Device",value:exports.DeviceUtilities.isMobileDevice()},{label:"🍎 iOS",value:exports.DeviceUtilities.isiOS()},{label:"📱 iPad",value:exports.DeviceUtilities.isiPad()},{label:"🤖 Android",value:exports.DeviceUtilities.isAndroidDevice()},{label:"🦊 Mozilla XR",value:exports.DeviceUtilities.isMozillaXR()},{label:"🌵 Needle App Clip",value:exports.DeviceUtilities.isNeedleAppClip()},{label:"🍏 macOS",value:exports.DeviceUtilities.isMacOS()},{label:"👓 VisionOS",value:exports.DeviceUtilities.isVisionOS()},{label:"🧭 Safari",value:exports.DeviceUtilities.isSafari()},{label:"🕶️ Meta Quest",value:exports.DeviceUtilities.isQuest()},{label:"🔗 QuickLook AR Support",value:exports.DeviceUtilities.supportsQuickLookAR()}],!0);const n=[],o=exports.DeviceUtilities.getiOSVersion();o&&n.push({label:"🍎 iOS Version",value:o});const r=exports.DeviceUtilities.getChromeVersion();r&&n.push({label:"🌐 Chrome Version",value:r});const a=exports.DeviceUtilities.getSafariVersion();a&&n.push({label:"🧭 Safari Version",value:a}),n.length>0&&(t+=En(n,!1)),t+="</div>",t+=`<div style='${Up} margin-top: 20px;'>`,t+=`<h3 style='${h_}'>User Agent Info</h3>`;const l=[{label:"User Agent",value:navigator.userAgent},{label:"Platform",value:navigator.platform},{label:"App Version",value:navigator.appVersion},{label:"User Agent Data",value:navigator.userAgentData?`Platform: ${navigator.userAgentData.platform}, Mobile: ${navigator.userAgentData.mobile}`:"Not supported"},{label:"WebXR",value:"xr"in navigator?"✅":"❌"},{label:"WebGPU",value:"gpu"in navigator?"✅":"❌"},{label:"WebGL 2",value:Uv()}];t+=En(l,!1),t+="</div>",e(t)}),s}function uC(){if(!globalThis.VConsole)return;const s=new VConsole.VConsolePlugin("graphics-info","🎨 Graphics Info");return s.on("renderTab",async function(e){let t=`<div style='${Up}'>`;const i=fC();i.length>0&&(t+=`<h3 style='${Io}'>General GPU Info</h3>`,t+=En(i,!1));const n=mC();n.length>0&&(t+=`<h3 style='${Io}'>WebGL</h3>`,t+=En(n,!1));const o=gC();o.length>0&&(t+=`<h3 style='${Io}'>WebGL 2 Features</h3>`,t+=En(o,!1));const r=yC();r.length>0&&(t+=`<h3 style='${Io}'>WebGL Limits</h3>`,t+=En(r,!1));const a=_C();a.length>0&&(t+=`<h3 style='${Io}'>Texture Formats</h3>`,t+=En(a,!1));const l=await bC();if(l.length>0&&(t+=`<h3 style='${Io}'>WebGPU</h3>`,t+=En(l,!1)),exports.DeviceUtilities.isSafari()){const h=vC();h.length>0&&(t+=`<h3 style='${Io}'>Safari GPU Info</h3>`,t+=En(h,!1))}t+="</div>",e(t)}),s}function fC(){const s=[],e=window.devicePixelRatio;s.push({label:"Device Pixel Ratio",value:e.toString()}),s.push({label:"Width (px)",value:(window.innerWidth*e).toString()}),s.push({label:"Height (px)",value:(window.innerHeight*e).toString()});const i=exports.DeviceUtilities.isMobileDevice()?150:96,n=screen.width/i,o=screen.height/i,r=n*2.54,a=o*2.54;s.push({label:"Estimated Width (cm)",value:r.toFixed(1)}),s.push({label:"Estimated Height (cm)",value:a.toFixed(1)});const l=zv();if(l){s.push({label:"GPU",value:l.renderer}),s.push({label:"Driver",value:l.vendor}),s.push({label:"ANGLE",value:l.angle||"Not detected"});const h=pC(l.renderer);h&&(h.manufacturer&&s.push({label:"Manufacturer",value:h.manufacturer}),h.cardVersion&&s.push({label:"Card Version",value:h.cardVersion}),h.brand&&s.push({label:"Brand",value:h.brand}),s.push({label:"Integrated",value:h.integrated?"Yes":"No"}),h.layer&&s.push({label:"WebGL Layer",value:h.layer}))}return s}function pC(s){if(!s)return null;const e=(h,d)=>{const u=d.match(h);return u&&u[0]},t=e(/(ANGLE)/g,s)||void 0,i=e(/((NVIDIA|AMD|Intel)[^\d]*[^\s]+)/,s)||s,n=i.split(" ");n.shift();const o=e(/(NVIDIA|AMD|Intel)/g,i)||void 0,r=n.length>0?n.pop():void 0,a=n.length>0?n.join(" "):void 0;return{manufacturer:o,cardVersion:r,brand:a,integrated:o==="Intel",layer:t,card:i}}function mC(){const s=[],e=zv();return e&&(s.push({label:"📊 WebGL Version",value:e.version}),s.push({label:"🎮 WebGL 2 Available",value:Uv()})),s}function gC(){const s=[];try{const t=document.createElement("canvas").getContext("webgl2");if(!t)return s;s.push({label:"Float Color Buffer",value:t.getExtension("EXT_color_buffer_float")?"✅":"❌"}),s.push({label:"Anisotropic Filtering",value:t.getExtension("EXT_texture_filter_anisotropic")?"✅":"❌"}),s.push({label:"Float Texture Linear",value:t.getExtension("OES_texture_float_linear")?"✅":"❌"}),s.push({label:"S3TC Compression",value:t.getExtension("WEBGL_compressed_texture_s3tc")?"✅":"❌"}),s.push({label:"ETC Compression",value:t.getExtension("WEBGL_compressed_texture_etc")?"✅":"❌"}),s.push({label:"PVRTC Compression",value:t.getExtension("WEBGL_compressed_texture_pvrtc")?"✅":"❌"}),s.push({label:"ASTC Compression",value:t.getExtension("WEBGL_compressed_texture_astc")?"✅":"❌"})}catch{}return s}function yC(){const s=[];try{const e=document.createElement("canvas"),t=e.getContext("webgl2")||e.getContext("webgl");if(!t)return s;const i=t instanceof WebGL2RenderingContext;s.push({label:"📏 Max Texture Size",value:t.getParameter(t.MAX_TEXTURE_SIZE).toString()}),s.push({label:"🎨 Max Renderbuffer Size",value:t.getParameter(t.MAX_RENDERBUFFER_SIZE).toString()}),s.push({label:"🔗 Max Vertex Attribs",value:t.getParameter(t.MAX_VERTEX_ATTRIBS).toString()}),s.push({label:"🎯 Max Texture Units",value:t.getParameter(t.MAX_TEXTURE_IMAGE_UNITS).toString()}),i&&(s.push({label:"⚡ Max Samples",value:t.getParameter(t.MAX_SAMPLES).toString()}),s.push({label:"🔄 Max Uniform Buffer Bindings",value:t.getParameter(t.MAX_UNIFORM_BUFFER_BINDINGS).toString()}),s.push({label:"📐 Max 3D Texture Size",value:t.getParameter(t.MAX_3D_TEXTURE_SIZE).toString()}))}catch{}return s}function _C(){const s=[];try{document.createElement("canvas").getContext("webgl")&&(s.push({label:"WebGL 1 RGBA",value:"✅"}),s.push({label:"WebGL 1 RGB",value:"✅"}));const n=document.createElement("canvas").getContext("webgl2");n&&(s.push({label:"WebGL 2 RGBA32F",value:n.getExtension("EXT_color_buffer_float")?"✅":"❌"}),s.push({label:"WebGL 2 RGB32F",value:n.getExtension("EXT_color_buffer_float")?"✅":"❌"}),s.push({label:"WebGL 2 R11F_G11F_B10F",value:"✅"}),s.push({label:"WebGL 2 RGB565",value:"✅"}),s.push({label:"WebGL 2 RGB5_A1",value:"✅"}),s.push({label:"WebGL 2 RGBA4444",value:"✅"}))}catch{}return s}async function bC(){const s=[];if(!("gpu"in navigator))return s.push({label:"🚀 WebGPU Support",value:"❌ Not supported"}),s;s.push({label:"🚀 WebGPU Support",value:"✅ Supported"});try{const e=await navigator.gpu.requestAdapter();if(!e)return s.push({label:"🎯 Adapter",value:"No adapter available"}),s;s.push({label:"🎯 Adapter",value:e.name||"Unknown Adapter"});const t=await e.requestDevice();s.push({label:"🔧 Device",value:t.label||"WebGPU Device"}),s.push({label:"📏 Max Texture 2D",value:t.limits.maxTextureDimension2D.toString()}),s.push({label:"📐 Max Texture 3D",value:t.limits.maxTextureDimension3D.toString()}),s.push({label:"📊 Max Texture Array Layers",value:t.limits.maxTextureArrayLayers.toString()}),s.push({label:"💾 Max Buffer Size",value:`${(t.limits.maxBufferSize/1024/1024).toFixed(1)}MB`}),s.push({label:"🔗 Max Bind Groups",value:t.limits.maxBindGroups.toString()})}catch(e){s.push({label:"❌ Error",value:e.message})}return s}function zv(){try{const s=document.createElement("canvas"),e=s.getContext("webgl2")||s.getContext("webgl");if(!e)return null;const t=e.getExtension("WEBGL_debug_renderer_info"),i=t?e.getParameter(t.UNMASKED_RENDERER_WEBGL):e.getParameter(e.RENDERER),n=t?e.getParameter(t.UNMASKED_VENDOR_WEBGL):e.getParameter(e.VENDOR),o=e.getParameter(e.VERSION);let r;if(i&&i.includes("ANGLE")){const a=i.match(/ANGLE \(([^)]+)\)/);a&&(r=a[1])}return{renderer:i,vendor:n,version:o,angle:r}}catch{return null}}function vC(){const s=[];try{const t=document.createElement("canvas").getContext("webgl");if(t){const i=t.getExtension("WEBGL_debug_renderer_info");if(i){const n=t.getParameter(i.UNMASKED_RENDERER_WEBGL);n&&n.includes("Apple")&&s.push({label:"🍎 Apple GPU",value:n})}}}catch{}try{const t=document.createElement("canvas").getContext("webgl");t&&(t.getSupportedExtensions()||[]).includes("WEBGL_compressed_texture_pvrtc")&&s.push({label:"🗜️ PVRTC Support",value:"✅"})}catch{}return s}function wC(){return exports.DeviceUtilities.isQuest()?"Meta Quest":exports.DeviceUtilities.isVisionOS()?"Vision Pro":exports.DeviceUtilities.isiOS()?exports.DeviceUtilities.isiPad()?"iPad":"iPhone/iPod":exports.DeviceUtilities.isAndroidDevice()?"Android Device":exports.DeviceUtilities.isMozillaXR()?"Mozilla XR Browser":exports.DeviceUtilities.isNeedleAppClip()?"Needle App Clip":exports.DeviceUtilities.isMacOS()?"Mac":exports.DeviceUtilities.isDesktop()?"Desktop PC":"Unknown Device"}function xC(){const s=document.querySelector("#__vconsole .vc-switch");return s||null}function SC(){const s=document.querySelector("#__vconsole");return s||null}const jh=x("debugtypes");class CC{_types=new Map;_reverseTypes=new Map;_lazyLoaders=new Map;constructor(){jh&&console.warn("TypeStore: Created",this)}add(e,t){jh&&console.warn("ADD TYPE",e);const i=this._types.get(e);i?jh&&i!==t&&console.warn("Type name exists multiple times in your project and may lead to runtime errors:",e):(this._types.set(e,t),this._reverseTypes.set(t,e))}addLazy(e,t){this._types.has(e)||this._lazyLoaders.set(e,t)}get(e){return this._types.get(e)||null}async getAsync(e){const t=this._types.get(e);if(t)return t;const i=this._lazyLoaders.get(e);if(i){jh&&console.warn("LAZY LOAD TYPE",e);const n=await i();return this.add(e,n),this._lazyLoaders.delete(e),n}return null}getKey(e){return this._reverseTypes.get(e)||null}}const PC=Symbol("BuiltInType"),P=new CC,qm=function(s){P.get(s.name)||P.add(s.name,s)};class OC{context;mixers=[];constructor(e){this.context=e}onDestroy(){this.mixers.forEach(e=>e.stopAllAction()),this.mixers.length=0}registerAnimationMixer(e){if(!e){console.warn("AnimationsRegistry.registerAnimationMixer called with null or undefined mixer");return}this.mixers.includes(e)||this.mixers.push(e)}unregisterAnimationMixer(e){if(!e){console.warn("AnimationsRegistry.unregisterAnimationMixer called with null or undefined mixer");return}const t=this.mixers.indexOf(e);t!==-1&&this.mixers.splice(t,1)}}class Hn{static testIfRootCanAnimate(e,t){const i=e.getRoot();return i&&(i.userData.static||i.matrixAutoUpdate===!1||i.matrixWorldAutoUpdate===!1)?((t===!0||t===void 0&&A())&&console.warn(`AnimationUtils: The root object (${i.name||i.type}) of this AnimationAction has matrixAutoUpdate or matrixWorldAutoUpdate set to false. This may prevent the animation from working correctly. If the object is marked as static, try to change it to dynamic.`,{static:i.userData.static,name:i.userData.name,tag:i.userData.tag,matrixAutoUpdate:i.matrixAutoUpdate,matrixWorldAutoUpdate:i.matrixWorldAutoUpdate}),!1):!0}static tryGetActionsFromMixer(e){const t=e._actions;return t||null}static tryGetAnimationClipsFromObjectHierarchy(e,t){if(t||(t=new Array),e)e.animations&&t.push(...e.animations);else return t;if(e.children)for(const i of e.children)this.tryGetAnimationClipsFromObjectHierarchy(i,t);return t}static autoplayAnimations(e){if(!e||!e.animations)return console.debug("No animations found in file"),null;const t="scene"in e?e.scene:e,i=new Array;for(let o=0;o<e.animations.length;o++){const r=e.animations[o];if(!r.tracks||r.tracks.length<=0){console.warn("Animation has no tracks");continue}for(const a in r.tracks){const l=r.tracks[a],h=c.PropertyBinding.parseTrackName(l.name);let d=c.PropertyBinding.findNode(t,h.nodeName);if(!d){const p=l.__objectName??l.name.substring(0,l.name.indexOf("."));if(d=t.getObjectByProperty("uuid",p),!d)continue}let u=n(d)||n(t);if(!u){const p=P.get("Animation");if(u=t.addComponent(p),!u){console.error("Failed creating Animation component: No 'Animation' component found in TypeStore");break}}i.push(u),u.addClip&&u.addClip(r)}}return i;function n(o){if(!o)return null;const r=o.userData?.components;if(r&&r.length>0)for(let a=0;a<r.length;a++){const l=r[a];if(l.isAnimationComponent===!0)return l}return n(o.parent)}}static emptyClip(){return new c.AnimationClip("empty",0,[])}static createScaleClip(e){const t=e?.duration??.3;let i={x:1,y:1,z:1};e?.scale!==void 0&&(typeof e.scale=="number"?i={x:e.scale,y:e.scale,z:e.scale}:i=e.scale);const n=e?.type??"linear",o=e?.scaleFactor??1.2,r=new Array,a=new Array;switch(n){case"linear":r.push(0,t),a.push(i.x,i.y,i.z,i.x*o,i.y*o,i.z*o);break;case"spring":r.push(0,t*.3,t*.5,t*.7,t*.9,t),a.push(i.x,i.y,i.z,i.x*o,i.y*o,i.z*o,i.x*.9,i.y*.9,i.z*.9,i.x*1.05,i.y*1.05,i.z*1.05,i.x*.98,i.y*.98,i.z*.98,i.x,i.y,i.z);break}const l=new c.KeyframeTrack(".scale",r,a);return new c.AnimationClip("scale",r[r.length-1],[l])}}const Be=function(s){return f(s)},f=function(s){if(s===void 0&&(s=null),!Array.isArray(s))s=d_(s);else for(let e=0;e<s.length;e++){const t=s[e];s[e]=d_(t)}return function(e,t){if(!e){const n=typeof t=="string"?t:t.name;console.warn(`@serializable without a target at '${n}'.`);return}typeof t!="string"&&(t=t.name),Object.getOwnPropertyDescriptor(e,"$serializedTypes")||(e.$serializedTypes={});const i=e.$serializedTypes=e.$serializedTypes||{};i[t]=s}};function d_(s){switch(s?.prototype?.constructor?.name){case"Number":case"String":case"Boolean":return null}return s}const u_=x("debugcomponentevents");class gu{static eventListeners=new Map;static addComponentLifecylceEventListener(e,t){this.eventListeners.has(e)&&this.eventListeners.set(e,[]);let i=this.eventListeners.get(e);i||(i=[]),i.push(t),this.eventListeners.set(e,i),u_&&console.log("Added event listener for "+e,this.eventListeners)}static removeComponentLifecylceEventListener(e,t){const i=this.eventListeners.get(e);if(!i)return;const n=i.indexOf(t);n<0||i.splice(n,1)}static dispatchComponentLifecycleEvent(e,t){const i=this.eventListeners.get(e);if(u_&&console.log("Dispatching event "+e,i),!!i)for(const n of i)n(t)}}const Nv=x("debugdefines");go('if(!globalThis["NEEDLE_ENGINE_VERSION"]) globalThis["NEEDLE_ENGINE_VERSION"] = "0.0.0";');go('if(!globalThis["NEEDLE_ENGINE_GENERATOR"]) globalThis["NEEDLE_ENGINE_GENERATOR"] = "unknown";');go('if(!globalThis["NEEDLE_PROJECT_BUILD_TIME"]) globalThis["NEEDLE_PROJECT_BUILD_TIME"] = "unknown";');go('if(!globalThis["NEEDLE_PUBLIC_KEY"]) globalThis["NEEDLE_PUBLIC_KEY"] = "unknown";');go('globalThis["__NEEDLE_ENGINE_VERSION__"] = "5.0.1";');go('globalThis["__NEEDLE_ENGINE_GENERATOR__"] = "undefined";');go('globalThis["__NEEDLE_PROJECT_BUILD_TIME__"] = "Tue Mar 31 2026 16:36:16 GMT+0000 (Coordinated Universal Time)";');go('globalThis["__NEEDLE_PUBLIC_KEY__"] = "'+NEEDLE_PUBLIC_KEY+'";');const ii="5.0.1",Ea="undefined",_c="Tue Mar 31 2026 16:36:16 GMT+0000 (Coordinated Universal Time)";Nv&&console.log(`Engine version: ${ii} (generator: ${Ea})
|
|
143
|
+
`,Lo?.prepend(i),s===!0&&_v()<=0&&Bv(),console.log("🌵 Debug console has loaded")}},e.onerror=()=>{console.warn("🌵 Debug console failed to load."+(window.crossOriginIsolated?"This page is using cross-origin isolation, so external scripts can't be loaded.":"")),vl=!1,Zt=null},e.src="https://cdn.jsdelivr.net/npm/vconsole@3.15.1/dist/vconsole.min.js",document.body.appendChild(e)}function aC(){if(!globalThis.VConsole)return;const s=new VConsole.VConsolePlugin("needle-console","🌵 Inspect glTF"),e=()=>document.querySelector("#__vc_plug_"+s._id+" iframe");return s.on("renderTab",function(t){const i=globalThis["needle:codegen_files"];if(!i||i.length===0)return;let n=globalThis["needle:codegen_files"][0];const o=n.indexOf("?");o>-1&&(n=n.substring(0,o));const a=location.protocol+"//"+location.host+location.pathname+"/"+n,l=encodeURIComponent(a);s.fullUrl="https://viewer.needle.tools?inspect&file="+l;var h='<iframe src="" style="width: 100%; height: 99%; border: none;"></iframe>';t(h)}),s.on("show",function(){const t=e();t&&t.src!==s.fullUrl&&(t.src=s.fullUrl)}),s.on("hide",function(){const t=e();t&&(t.src="")}),s.on("addTopBar",function(t){var i=new Array;i.push({name:"Open in new window ↗",onClick:function(n){window.open(s.fullUrl,"_blank"),Zt?.hide()}}),i.push({name:"Reload",onClick:function(n){const o=e();o&&(o.src=s.fullUrl)}}),i.push({name:"Fullscreen",onClick:function(n){const o=e();o.requestFullscreen?o.requestFullscreen():o.webkitRequestFullscreen instanceof Function&&o.webkitRequestFullscreen()}}),t(i)}),s}const Up="padding: 10px; font-family: monospace;",h_="margin-bottom: 10px;",Io="margin-bottom: 10px; margin-top: 15px;",lC="width: 100%; border-collapse: collapse; border: 1px solid rgba(0,0,0,0.1); table-layout: fixed;",Fv="border: 1px solid rgba(0,0,0,0.1); padding: 5px;",cC=Fv,hC=Fv+" word-break: break-all;";function En(s,e=!1){e&&s.sort((i,n)=>(n.value?1:0)-(i.value?1:0));let t=`<table style='${lC}'>`;t+="<tbody>";for(const i of s){const n=typeof i.value=="boolean"?i.value?"✅":"❌":i.value;t+=`<tr><td style='${cC}'>${i.label}</td><td style='${hC}'>${n}</td></tr>`}return t+="</tbody></table>",t}function Uv(){try{if(document.createElement("canvas").getContext("webgl2"))return"✅"}catch{}return"❌"}function dC(){if(!globalThis.VConsole)return;const s=new VConsole.VConsolePlugin("device-utilities","📱 Device Info");return s.on("renderTab",function(e){let t=`<div style='${Up}'>`;const i=wC();t+=`<h3 style='${h_}'>Device: ${i}</h3>`,t+=En([{label:"💻 Desktop",value:exports.DeviceUtilities.isDesktop()},{label:"📱 Mobile Device",value:exports.DeviceUtilities.isMobileDevice()},{label:"🍎 iOS",value:exports.DeviceUtilities.isiOS()},{label:"📱 iPad",value:exports.DeviceUtilities.isiPad()},{label:"🤖 Android",value:exports.DeviceUtilities.isAndroidDevice()},{label:"🦊 Mozilla XR",value:exports.DeviceUtilities.isMozillaXR()},{label:"🌵 Needle App Clip",value:exports.DeviceUtilities.isNeedleAppClip()},{label:"🍏 macOS",value:exports.DeviceUtilities.isMacOS()},{label:"👓 VisionOS",value:exports.DeviceUtilities.isVisionOS()},{label:"🧭 Safari",value:exports.DeviceUtilities.isSafari()},{label:"🕶️ Meta Quest",value:exports.DeviceUtilities.isQuest()},{label:"🔗 QuickLook AR Support",value:exports.DeviceUtilities.supportsQuickLookAR()}],!0);const n=[],o=exports.DeviceUtilities.getiOSVersion();o&&n.push({label:"🍎 iOS Version",value:o});const r=exports.DeviceUtilities.getChromeVersion();r&&n.push({label:"🌐 Chrome Version",value:r});const a=exports.DeviceUtilities.getSafariVersion();a&&n.push({label:"🧭 Safari Version",value:a}),n.length>0&&(t+=En(n,!1)),t+="</div>",t+=`<div style='${Up} margin-top: 20px;'>`,t+=`<h3 style='${h_}'>User Agent Info</h3>`;const l=[{label:"User Agent",value:navigator.userAgent},{label:"Platform",value:navigator.platform},{label:"App Version",value:navigator.appVersion},{label:"User Agent Data",value:navigator.userAgentData?`Platform: ${navigator.userAgentData.platform}, Mobile: ${navigator.userAgentData.mobile}`:"Not supported"},{label:"WebXR",value:"xr"in navigator?"✅":"❌"},{label:"WebGPU",value:"gpu"in navigator?"✅":"❌"},{label:"WebGL 2",value:Uv()}];t+=En(l,!1),t+="</div>",e(t)}),s}function uC(){if(!globalThis.VConsole)return;const s=new VConsole.VConsolePlugin("graphics-info","🎨 Graphics Info");return s.on("renderTab",async function(e){let t=`<div style='${Up}'>`;const i=fC();i.length>0&&(t+=`<h3 style='${Io}'>General GPU Info</h3>`,t+=En(i,!1));const n=mC();n.length>0&&(t+=`<h3 style='${Io}'>WebGL</h3>`,t+=En(n,!1));const o=gC();o.length>0&&(t+=`<h3 style='${Io}'>WebGL 2 Features</h3>`,t+=En(o,!1));const r=yC();r.length>0&&(t+=`<h3 style='${Io}'>WebGL Limits</h3>`,t+=En(r,!1));const a=_C();a.length>0&&(t+=`<h3 style='${Io}'>Texture Formats</h3>`,t+=En(a,!1));const l=await bC();if(l.length>0&&(t+=`<h3 style='${Io}'>WebGPU</h3>`,t+=En(l,!1)),exports.DeviceUtilities.isSafari()){const h=vC();h.length>0&&(t+=`<h3 style='${Io}'>Safari GPU Info</h3>`,t+=En(h,!1))}t+="</div>",e(t)}),s}function fC(){const s=[],e=window.devicePixelRatio;s.push({label:"Device Pixel Ratio",value:e.toString()}),s.push({label:"Width (px)",value:(window.innerWidth*e).toString()}),s.push({label:"Height (px)",value:(window.innerHeight*e).toString()});const i=exports.DeviceUtilities.isMobileDevice()?150:96,n=screen.width/i,o=screen.height/i,r=n*2.54,a=o*2.54;s.push({label:"Estimated Width (cm)",value:r.toFixed(1)}),s.push({label:"Estimated Height (cm)",value:a.toFixed(1)});const l=zv();if(l){s.push({label:"GPU",value:l.renderer}),s.push({label:"Driver",value:l.vendor}),s.push({label:"ANGLE",value:l.angle||"Not detected"});const h=pC(l.renderer);h&&(h.manufacturer&&s.push({label:"Manufacturer",value:h.manufacturer}),h.cardVersion&&s.push({label:"Card Version",value:h.cardVersion}),h.brand&&s.push({label:"Brand",value:h.brand}),s.push({label:"Integrated",value:h.integrated?"Yes":"No"}),h.layer&&s.push({label:"WebGL Layer",value:h.layer}))}return s}function pC(s){if(!s)return null;const e=(h,d)=>{const u=d.match(h);return u&&u[0]},t=e(/(ANGLE)/g,s)||void 0,i=e(/((NVIDIA|AMD|Intel)[^\d]*[^\s]+)/,s)||s,n=i.split(" ");n.shift();const o=e(/(NVIDIA|AMD|Intel)/g,i)||void 0,r=n.length>0?n.pop():void 0,a=n.length>0?n.join(" "):void 0;return{manufacturer:o,cardVersion:r,brand:a,integrated:o==="Intel",layer:t,card:i}}function mC(){const s=[],e=zv();return e&&(s.push({label:"📊 WebGL Version",value:e.version}),s.push({label:"🎮 WebGL 2 Available",value:Uv()})),s}function gC(){const s=[];try{const t=document.createElement("canvas").getContext("webgl2");if(!t)return s;s.push({label:"Float Color Buffer",value:t.getExtension("EXT_color_buffer_float")?"✅":"❌"}),s.push({label:"Anisotropic Filtering",value:t.getExtension("EXT_texture_filter_anisotropic")?"✅":"❌"}),s.push({label:"Float Texture Linear",value:t.getExtension("OES_texture_float_linear")?"✅":"❌"}),s.push({label:"S3TC Compression",value:t.getExtension("WEBGL_compressed_texture_s3tc")?"✅":"❌"}),s.push({label:"ETC Compression",value:t.getExtension("WEBGL_compressed_texture_etc")?"✅":"❌"}),s.push({label:"PVRTC Compression",value:t.getExtension("WEBGL_compressed_texture_pvrtc")?"✅":"❌"}),s.push({label:"ASTC Compression",value:t.getExtension("WEBGL_compressed_texture_astc")?"✅":"❌"})}catch{}return s}function yC(){const s=[];try{const e=document.createElement("canvas"),t=e.getContext("webgl2")||e.getContext("webgl");if(!t)return s;const i=t instanceof WebGL2RenderingContext;s.push({label:"📏 Max Texture Size",value:t.getParameter(t.MAX_TEXTURE_SIZE).toString()}),s.push({label:"🎨 Max Renderbuffer Size",value:t.getParameter(t.MAX_RENDERBUFFER_SIZE).toString()}),s.push({label:"🔗 Max Vertex Attribs",value:t.getParameter(t.MAX_VERTEX_ATTRIBS).toString()}),s.push({label:"🎯 Max Texture Units",value:t.getParameter(t.MAX_TEXTURE_IMAGE_UNITS).toString()}),i&&(s.push({label:"⚡ Max Samples",value:t.getParameter(t.MAX_SAMPLES).toString()}),s.push({label:"🔄 Max Uniform Buffer Bindings",value:t.getParameter(t.MAX_UNIFORM_BUFFER_BINDINGS).toString()}),s.push({label:"📐 Max 3D Texture Size",value:t.getParameter(t.MAX_3D_TEXTURE_SIZE).toString()}))}catch{}return s}function _C(){const s=[];try{document.createElement("canvas").getContext("webgl")&&(s.push({label:"WebGL 1 RGBA",value:"✅"}),s.push({label:"WebGL 1 RGB",value:"✅"}));const n=document.createElement("canvas").getContext("webgl2");n&&(s.push({label:"WebGL 2 RGBA32F",value:n.getExtension("EXT_color_buffer_float")?"✅":"❌"}),s.push({label:"WebGL 2 RGB32F",value:n.getExtension("EXT_color_buffer_float")?"✅":"❌"}),s.push({label:"WebGL 2 R11F_G11F_B10F",value:"✅"}),s.push({label:"WebGL 2 RGB565",value:"✅"}),s.push({label:"WebGL 2 RGB5_A1",value:"✅"}),s.push({label:"WebGL 2 RGBA4444",value:"✅"}))}catch{}return s}async function bC(){const s=[];if(!("gpu"in navigator))return s.push({label:"🚀 WebGPU Support",value:"❌ Not supported"}),s;s.push({label:"🚀 WebGPU Support",value:"✅ Supported"});try{const e=await navigator.gpu.requestAdapter();if(!e)return s.push({label:"🎯 Adapter",value:"No adapter available"}),s;s.push({label:"🎯 Adapter",value:e.name||"Unknown Adapter"});const t=await e.requestDevice();s.push({label:"🔧 Device",value:t.label||"WebGPU Device"}),s.push({label:"📏 Max Texture 2D",value:t.limits.maxTextureDimension2D.toString()}),s.push({label:"📐 Max Texture 3D",value:t.limits.maxTextureDimension3D.toString()}),s.push({label:"📊 Max Texture Array Layers",value:t.limits.maxTextureArrayLayers.toString()}),s.push({label:"💾 Max Buffer Size",value:`${(t.limits.maxBufferSize/1024/1024).toFixed(1)}MB`}),s.push({label:"🔗 Max Bind Groups",value:t.limits.maxBindGroups.toString()})}catch(e){s.push({label:"❌ Error",value:e.message})}return s}function zv(){try{const s=document.createElement("canvas"),e=s.getContext("webgl2")||s.getContext("webgl");if(!e)return null;const t=e.getExtension("WEBGL_debug_renderer_info"),i=t?e.getParameter(t.UNMASKED_RENDERER_WEBGL):e.getParameter(e.RENDERER),n=t?e.getParameter(t.UNMASKED_VENDOR_WEBGL):e.getParameter(e.VENDOR),o=e.getParameter(e.VERSION);let r;if(i&&i.includes("ANGLE")){const a=i.match(/ANGLE \(([^)]+)\)/);a&&(r=a[1])}return{renderer:i,vendor:n,version:o,angle:r}}catch{return null}}function vC(){const s=[];try{const t=document.createElement("canvas").getContext("webgl");if(t){const i=t.getExtension("WEBGL_debug_renderer_info");if(i){const n=t.getParameter(i.UNMASKED_RENDERER_WEBGL);n&&n.includes("Apple")&&s.push({label:"🍎 Apple GPU",value:n})}}}catch{}try{const t=document.createElement("canvas").getContext("webgl");t&&(t.getSupportedExtensions()||[]).includes("WEBGL_compressed_texture_pvrtc")&&s.push({label:"🗜️ PVRTC Support",value:"✅"})}catch{}return s}function wC(){return exports.DeviceUtilities.isQuest()?"Meta Quest":exports.DeviceUtilities.isVisionOS()?"Vision Pro":exports.DeviceUtilities.isiOS()?exports.DeviceUtilities.isiPad()?"iPad":"iPhone/iPod":exports.DeviceUtilities.isAndroidDevice()?"Android Device":exports.DeviceUtilities.isMozillaXR()?"Mozilla XR Browser":exports.DeviceUtilities.isNeedleAppClip()?"Needle App Clip":exports.DeviceUtilities.isMacOS()?"Mac":exports.DeviceUtilities.isDesktop()?"Desktop PC":"Unknown Device"}function xC(){const s=document.querySelector("#__vconsole .vc-switch");return s||null}function SC(){const s=document.querySelector("#__vconsole");return s||null}const jh=x("debugtypes");class CC{_types=new Map;_reverseTypes=new Map;_lazyLoaders=new Map;constructor(){jh&&console.warn("TypeStore: Created",this)}add(e,t){jh&&console.warn("ADD TYPE",e);const i=this._types.get(e);i?jh&&i!==t&&console.warn("Type name exists multiple times in your project and may lead to runtime errors:",e):(this._types.set(e,t),this._reverseTypes.set(t,e))}addLazy(e,t){this._types.has(e)||this._lazyLoaders.set(e,t)}get(e){return this._types.get(e)||null}async getAsync(e){const t=this._types.get(e);if(t)return t;const i=this._lazyLoaders.get(e);if(i){jh&&console.warn("LAZY LOAD TYPE",e);const n=await i();return this.add(e,n),this._lazyLoaders.delete(e),n}return null}getKey(e){return this._reverseTypes.get(e)||null}}const PC=Symbol("BuiltInType"),P=new CC,qm=function(s){P.get(s.name)||P.add(s.name,s)};class OC{context;mixers=[];constructor(e){this.context=e}onDestroy(){this.mixers.forEach(e=>e.stopAllAction()),this.mixers.length=0}registerAnimationMixer(e){if(!e){console.warn("AnimationsRegistry.registerAnimationMixer called with null or undefined mixer");return}this.mixers.includes(e)||this.mixers.push(e)}unregisterAnimationMixer(e){if(!e){console.warn("AnimationsRegistry.unregisterAnimationMixer called with null or undefined mixer");return}const t=this.mixers.indexOf(e);t!==-1&&this.mixers.splice(t,1)}}class Hn{static testIfRootCanAnimate(e,t){const i=e.getRoot();return i&&(i.userData.static||i.matrixAutoUpdate===!1||i.matrixWorldAutoUpdate===!1)?((t===!0||t===void 0&&A())&&console.warn(`AnimationUtils: The root object (${i.name||i.type}) of this AnimationAction has matrixAutoUpdate or matrixWorldAutoUpdate set to false. This may prevent the animation from working correctly. If the object is marked as static, try to change it to dynamic.`,{static:i.userData.static,name:i.userData.name,tag:i.userData.tag,matrixAutoUpdate:i.matrixAutoUpdate,matrixWorldAutoUpdate:i.matrixWorldAutoUpdate}),!1):!0}static tryGetActionsFromMixer(e){const t=e._actions;return t||null}static tryGetAnimationClipsFromObjectHierarchy(e,t){if(t||(t=new Array),e)e.animations&&t.push(...e.animations);else return t;if(e.children)for(const i of e.children)this.tryGetAnimationClipsFromObjectHierarchy(i,t);return t}static autoplayAnimations(e){if(!e||!e.animations)return console.debug("No animations found in file"),null;const t="scene"in e?e.scene:e,i=new Array;for(let o=0;o<e.animations.length;o++){const r=e.animations[o];if(!r.tracks||r.tracks.length<=0){console.warn("Animation has no tracks");continue}for(const a in r.tracks){const l=r.tracks[a],h=c.PropertyBinding.parseTrackName(l.name);let d=c.PropertyBinding.findNode(t,h.nodeName);if(!d){const p=l.__objectName??l.name.substring(0,l.name.indexOf("."));if(d=t.getObjectByProperty("uuid",p),!d)continue}let u=n(d)||n(t);if(!u){const p=P.get("Animation");if(u=t.addComponent(p),!u){console.error("Failed creating Animation component: No 'Animation' component found in TypeStore");break}}i.push(u),u.addClip&&u.addClip(r)}}return i;function n(o){if(!o)return null;const r=o.userData?.components;if(r&&r.length>0)for(let a=0;a<r.length;a++){const l=r[a];if(l.isAnimationComponent===!0)return l}return n(o.parent)}}static emptyClip(){return new c.AnimationClip("empty",0,[])}static createScaleClip(e){const t=e?.duration??.3;let i={x:1,y:1,z:1};e?.scale!==void 0&&(typeof e.scale=="number"?i={x:e.scale,y:e.scale,z:e.scale}:i=e.scale);const n=e?.type??"linear",o=e?.scaleFactor??1.2,r=new Array,a=new Array;switch(n){case"linear":r.push(0,t),a.push(i.x,i.y,i.z,i.x*o,i.y*o,i.z*o);break;case"spring":r.push(0,t*.3,t*.5,t*.7,t*.9,t),a.push(i.x,i.y,i.z,i.x*o,i.y*o,i.z*o,i.x*.9,i.y*.9,i.z*.9,i.x*1.05,i.y*1.05,i.z*1.05,i.x*.98,i.y*.98,i.z*.98,i.x,i.y,i.z);break}const l=new c.KeyframeTrack(".scale",r,a);return new c.AnimationClip("scale",r[r.length-1],[l])}}const Be=function(s){return f(s)},f=function(s){if(s===void 0&&(s=null),!Array.isArray(s))s=d_(s);else for(let e=0;e<s.length;e++){const t=s[e];s[e]=d_(t)}return function(e,t){if(!e){const n=typeof t=="string"?t:t.name;console.warn(`@serializable without a target at '${n}'.`);return}typeof t!="string"&&(t=t.name),Object.getOwnPropertyDescriptor(e,"$serializedTypes")||(e.$serializedTypes={});const i=e.$serializedTypes=e.$serializedTypes||{};i[t]=s}};function d_(s){switch(s?.prototype?.constructor?.name){case"Number":case"String":case"Boolean":return null}return s}const u_=x("debugcomponentevents");class gu{static eventListeners=new Map;static addComponentLifecylceEventListener(e,t){this.eventListeners.has(e)&&this.eventListeners.set(e,[]);let i=this.eventListeners.get(e);i||(i=[]),i.push(t),this.eventListeners.set(e,i),u_&&console.log("Added event listener for "+e,this.eventListeners)}static removeComponentLifecylceEventListener(e,t){const i=this.eventListeners.get(e);if(!i)return;const n=i.indexOf(t);n<0||i.splice(n,1)}static dispatchComponentLifecycleEvent(e,t){const i=this.eventListeners.get(e);if(u_&&console.log("Dispatching event "+e,i),!!i)for(const n of i)n(t)}}const Nv=x("debugdefines");go('if(!globalThis["NEEDLE_ENGINE_VERSION"]) globalThis["NEEDLE_ENGINE_VERSION"] = "0.0.0";');go('if(!globalThis["NEEDLE_ENGINE_GENERATOR"]) globalThis["NEEDLE_ENGINE_GENERATOR"] = "unknown";');go('if(!globalThis["NEEDLE_PROJECT_BUILD_TIME"]) globalThis["NEEDLE_PROJECT_BUILD_TIME"] = "unknown";');go('if(!globalThis["NEEDLE_PUBLIC_KEY"]) globalThis["NEEDLE_PUBLIC_KEY"] = "unknown";');go('globalThis["__NEEDLE_ENGINE_VERSION__"] = "5.0.2";');go('globalThis["__NEEDLE_ENGINE_GENERATOR__"] = "undefined";');go('globalThis["__NEEDLE_PROJECT_BUILD_TIME__"] = "Fri Apr 03 2026 09:10:54 GMT+0000 (Coordinated Universal Time)";');go('globalThis["__NEEDLE_PUBLIC_KEY__"] = "'+NEEDLE_PUBLIC_KEY+'";');const ii="5.0.2",Ea="undefined",_c="Fri Apr 03 2026 09:10:54 GMT+0000 (Coordinated Universal Time)";Nv&&console.log(`Engine version: ${ii} (generator: ${Ea})
|
|
144
144
|
Project built at ${_c}`);const no=NEEDLE_PUBLIC_KEY,jn="needle_isActiveInHierarchy",Ho="builtin_components",ec="needle_editor_guid";function go(s){try{(0,eval)(s)}catch(e){Nv&&console.error(e)}}const Xm={experimentalSmartHierarchyUpdate:!1},pi=Symbol("shadowDomOwner"),MC=x("debugpatch");function yu(s,e,t,i){const n=MC===e;if(!t&&!i)return;const o=e+"___needle";EC(s,e,t,i);const r=Object.getOwnPropertyDescriptor(s,e),a=s[e];n&&console.log("Patch",s.constructor.name,e,r,a),r?(n&&console.log("Apply patch with existing descriptor",s.constructor.name,e,r),typeof r.value=="function"&&(s[e]=p_(r.value,s,e))):(n&&console.log("Create patch with new property",s.constructor.name,e,r),Object.defineProperty(s,e,{set:function(l){if(typeof l=="function")this[o]=p_(l,s,e);else{const h=this[o];Vv(s,e,this,h,l),this[o]=l,$v(s,e,this,h,l)}},get:function(){const l=this[o];return typeof l=="function"&&l[o]?l[o]:l}}))}function kC(s,e,t){const i=Qm(s,e);if(i)for(let n=i.length-1;n>=0;n--){const o=i[n];o.prefix===t&&(o.prefix=null),o.postfix===t&&(o.postfix=null),!o.prefix&&!o.postfix&&i.splice(n,1)}}const f_=Symbol("Needle:Patches:WrappedFunction");function p_(s,e,t){if(s[f_])return s;const i=function(...n){Vv(e,t,this,...n);const o=s.apply(this,n);return $v(e,t,this,o,...n),o};return i[f_]=!0,i}const _d="Needle:Patches";function zp(){return globalThis[_d]||(globalThis[_d]=new WeakMap),globalThis[_d]}function Qm(s,e){const t=zp().get(s);return t?t.get(e):null}function EC(s,e,t,i){let n=zp().get(s);n||(n=new Map,zp().set(s,n));let o=n.get(e);o||(o=[],n.set(e,o)),o.push({prefix:t,postfix:i})}function Vv(s,e,t,...i){if(!t)return;const n=Qm(s,e);if(n)for(const o of n)o.prefix?.call(t,...i)}function $v(s,e,t,i,...n){if(!t)return;const o=Qm(s,e);if(o)for(const r of o)r.postfix?.call(t,i,...n)}function RC(s,e){if(typeof window!==void 0&&window.SPECTOR){console.log(window.SPECTOR);const t=new URLSearchParams(window.location.search);if(t.has("spector")){let i=function(){if(n>s.time.frame)return window.requestAnimationFrame(()=>i());const r=o.captureCanvas(e);r&&r instanceof Promise?r.then(()=>o.displayUI()):o.displayUI()};const n=Number.parseInt(t.get("spector")||"0")||0;console.log("Scheduled Spector capture at frame #"+n);const o=new window.SPECTOR.Spector;o.spyCanvases=!0,i();return}else A()&&console.debug("Spector available: Add '?spector=<frame>' to the URL to enable it and capture a frame.")}}function Wv(s){const e=s;return!!(e.parser&&e.parser.json)}var _u=(s=>(s[s.None=0]="None",s[s.DontExport=1]="DontExport",s))(_u||{});const Gv=Symbol("component-name");function Ym(s){return s&&s.isComponent}const TC=Symbol("object"),Af=new _i(()=>new c.Vector3,20);class Hv{_point;_normal;_tangentVelocity;distance;impulse;friction;get point(){return Af.get().set(this._point.x,this._point.y,this._point.z)}get normal(){return Af.get().set(this._normal.x,this._normal.y,this._normal.z)}get tangentVelocity(){return Af.get().set(this._tangentVelocity.x,this._tangentVelocity.y,this._tangentVelocity.z)}constructor(e,t,i,n,o,r){this._point=e,this.distance=t,this._normal=i,this.impulse=n,this.friction=o,this._tangentVelocity=r}}class qv{contacts;constructor(e,t,i){this.me=e,this._collider=t,this._gameObject=t.gameObject,this.contacts=i}me;_collider;get collider(){return this._collider}_gameObject;get gameObject(){return this._gameObject}get rigidBody(){return this.collider?.attachedRigidbody}}class Xv{object;collider;constructor(e,t){this.object=e,this.collider=t}}class Gd{constructor(e){this.context=e,this.root.style.cssText=`
|
|
145
145
|
position: absolute;
|
|
146
146
|
width: 1px; height: 1px;
|
|
@@ -876,7 +876,7 @@ Pinch: ${this.getGesture("pinch")?.value.toFixed(3)}`),n+=`
|
|
|
876
876
|
Layout: `;for(const o of Object.keys(this._layout.components||{})){const r=this.getStick(o),a=this._layout.components[o]?.gamepadIndices,l=a?Object.entries(a).map(h=>h[0][0].toUpperCase()+h[0].slice(1)+"="+h[1]).join(","):"";n+=`
|
|
877
877
|
${o}: ${this._layout.components[o]?.type} [${l}] (${r.x.toPrecision(2)},${r.y.toPrecision(2)})`}}B.DrawLabel(t,n,.006)}onUpdateFrame(e){if(this._handJointPoses.clear(),this._hand_wristDotUp=void 0,!this.xr.referenceSpace||!this.inputSource.gamepad?.connected){this._isTracking=!1;return}const t=e.getPose(this.inputSource.targetRaySpace,this.xr.referenceSpace);this._isTracking=t!=null;let i=null,n=null,o=null,r=null;if(t){const d=t.transform;this._rayMatrix.fromArray(d.matrix).premultiply(wa),this._rayMatrix.decompose(this._rayPosition,this._rayQuaternion,F(1,1,1)),o=F(d.position),r=ei(d.orientation),this._rayPositionRaw.copy(o),this._rayRotationRaw.copy(r)}if(this.inputSource.gripSpace){const d=e.getPose(this.inputSource.gripSpace,this.xr.referenceSpace);if(d){const u=d.transform;if(i=F(u.position),n=ei(u.orientation),this._gripMatrix.fromArray(u.matrix).premultiply(wa),this._gripMatrix.decompose(this._gripPosition,this._gripQuaternion,F(1,1,1)),"linearVelocity"in d&&d.linearVelocity){const p=d.linearVelocity;this._linearVelocity.set(p.x,p.y,p.z)}}}this.xr.context.mainCamera?.parent&&(this._object.parent!==this.xr.context.mainCamera?.parent&&this.xr.context.mainCamera.parent.add(this._object),this._gripSpaceObject!==void 0&&this._gripSpaceObject?.parent!==this.xr.context.mainCamera?.parent&&this.xr.context.mainCamera.parent.add(this._gripSpaceObject),this._raySpaceObject!==void 0&&this._raySpaceObject?.parent!==this.xr.context.mainCamera?.parent&&this.xr.context.mainCamera.parent.add(this._raySpaceObject));const a=this.hand;if(a){let d=!1;const u=a.get("wrist"),p=u&&this.getHandJointPose(u,e);if(p){d=!0;const _=p.transform.position,g=p.transform.orientation;this._object.position.set(_.x,_.y,_.z),this._object.quaternion.set(g.x,g.y,g.z,g.w).multiply(Li)}d||(this._object.position.copy(this._rayPosition),this._object.quaternion.copy(this._rayQuaternion).multiply(Li));const m=a.get("middle-finger-metacarpal"),y=m&&this.getHandJointPose(m,e);y&&(this._gripMatrix.fromArray(y.transform.matrix).premultiply(wa),this._gripMatrix.decompose(this._gripPosition,this._gripQuaternion,F(1,1,1)),i=F().copy(y.transform.position),n=ei().copy(y.transform.orientation),n.multiply(eP),i.add(F(tP).applyQuaternion(n)))}else this.inputSource.gripSpace&&this.targetRayMode==="transient-pointer"&&i&&n?(this._object.position.copy(i),this._object.quaternion.copy(n).multiply(Li)):o&&r&&(this._object.position.copy(o),this._object.quaternion.copy(r).multiply(Li));Jn&&(o&&r&&(this._raySpaceObject?.position.copy(o),this._raySpaceObject?.quaternion.copy(r).multiply(Li)),i&&n&&(this._gripSpaceObject?.position.copy(i),this._gripSpaceObject?.quaternion.copy(n).multiply(Li)));const l=this.xr.context.mainCamera?.parent,h=l?pe(l):void 0;i&&n&&(this._gripWorldPosition.copy(i),l&&this._gripWorldPosition.applyMatrix4(l.matrixWorld),this._gripWorldQuaternion.copy(n),this._gripWorldQuaternion.multiply(Li),h&&this._gripWorldQuaternion.premultiply(h)),this.updateRayWorldPosition(),this.updateRayWorldQuaternion()}onDisconnected(){this._connected=!1,Jn&&console.warn("Controller disconnected",this.index);for(const e of this._object.children)this.xr.context.scene.attach(e);this._object?.removeFromParent(),this._debugAxesHelper?.removeFromParent(),this._debugGripAxesHelper?.removeFromParent(),this._debugRayAxesHelper?.removeFromParent(),this._gripSpaceObject?.removeFromParent(),this._raySpaceObject?.removeFromParent(),this.unsubscribeEvents(),this._hitTestSource&&(this._hitTestSource.cancel(),this._hitTestSource=void 0)}getButton(e){if(!this._layout)return;switch(e){case"primary-button":if(this.isLeft)e="x-button";else if(this.isRight)e="a-button";else return;break;case"primary":return this.hand?this.getGesture("pinch"):this.toNeedleGamepadButton(0,e);case"xr-standard-trigger":if(this.inputSource.gamepad)return this.toNeedleGamepadButton(0,e);break;case"xr-standard-squeeze":if(this.inputSource.gamepad)return this.toNeedleGamepadButton(1,e);break;case"xr-standard-thumbstick":if(this.inputSource.gamepad)return this.toNeedleGamepadButton(3,e);break}if(this._buttonMap.has(e))return this.toNeedleGamepadButton(this._buttonMap.get(e),e);const t=this._layout?.components[e];if(t?.gamepadIndices)switch(t.type){case"button":case"squeeze":if(this.inputSource.gamepad){const i=t.gamepadIndices.button;return this._buttonMap.set(e,i),this.toNeedleGamepadButton(i,e)}break;default:console.warn("Unsupported component type",t.type);break}this._buttonMap.set(e,void 0)}getGesture(e){const t=this.states[e];if(!t)return null;this.states[e]=t;const i=this._needleGamepadButtons[e]||new U_(void 0,e);return i.pressed=t.pressed,i.value=t.value,i.isDown=t.isDown,i.isUp=t.isUp,this._needleGamepadButtons[e]=i,i}getPointerId(e){if((e==="primary"||e==="pinch")&&(e=0),typeof e!="number"){const t=this._buttonMap.get(e);if(t===void 0)return;e=t}return this.index*10+e}_needleGamepadButtons={};toNeedleGamepadButton(e,t){if(!this.inputSource.gamepad?.buttons)return;const i=this.inputSource.gamepad?.buttons[e],n=this.states[e],o=this._needleGamepadButtons[e]||new U_(e,t);return i&&(o.pressed=i.pressed,o.value=i.value,o.touched=i.touched),n&&(o.isDown=n.isDown,o.isUp=n.isUp),this._needleGamepadButtons[e]=o,o}getStick(e){if(!this._layout)return{x:0,y:0,z:0};if(this.isHand)return{x:0,y:0,z:0};e==="primary"&&this._layout.components["xr-standard-thumbstick"]&&(e="xr-standard-thumbstick");const t=this._layout?.components[e];if(t?.gamepadIndices)switch(t.type){case"thumbstick":case"touchpad":if(this.inputSource.gamepad){const i=t.gamepadIndices.xAxis,n=t.gamepadIndices.yAxis;let o=this.inputSource.gamepad.axes[i]||0,r=this.inputSource.gamepad.axes[n]||0;o*=-1,r*=-1;const a=t.gamepadIndices.button,l=this.inputSource.gamepad?.buttons[a]?.value||0;return{x:o,y:r,z:l}}}return{x:0,y:0,z:0}}_buttonMap=new Map;_motioncontroller;_layout;getMotionController;initialize(){if(this._hasSelectEvent=this.profiles.includes("generic-hand-select")||this.profiles.some(e=>e.startsWith("generic-trigger")),this._isMetaQuestTouchController=this.profiles.includes("meta-quest-touch-plus")||this.profiles.includes("oculus-touch-v3"),this._isMxInk=this.profiles.includes("logitech-mx-ink"),!this._layout){if(this.inputSource.targetRayMode==="transient-pointer")return;const e=le.fetchProfile(this.inputSource,Z1,J1);this.getMotionController=e.then(t=>{if(!this.connected)return null;this._motioncontroller=new le.MotionController(this.inputSource,t.profile,t.assetPath||"");const n=t.profile.layouts[this.inputSource.handedness];if(this._layout=n,this._layout){if(!this._layout.gamepad?.length){this._layout.gamepad=[];for(const o in this._layout.components){const r=this._layout.components[o];this._layout.gamepad[r.gamepadIndices.button]=o}}this.profiles.length>=1&&this.profiles[0]==="htc-vive-focus-plus"&&this.inputSource.gamepad&&this.inputSource.gamepad.axes.length===4&&!this._layout.components["xr-standard-thumbstick"]&&(this._layout.components["xr-standard-thumbstick"]={type:"thumbstick",gamepadIndices:{xAxis:2,yAxis:3}})}return this._motioncontroller}).catch(t=>(this.inputSource&&console.warn("Couldn't initialize motion controller profile for ",this.inputSource,t),null))}}emitPointerDownEvent=!0;emitPointerUpEvent=!0;emitPointerMoveEvent=!0;pointerMoveDistanceThreshold=.03;pointerMoveAngleThreshold=.05;subscribeEvents(){this.xr.session.addEventListener("selectstart",this.onSelectStart),this.xr.session.addEventListener("selectend",this.onSelectEnd),this.xr.session.addEventListener("squeezestart",this.onSequeezeStart),this.xr.session.addEventListener("squeezeend",this.onSequeezeEnd)}unsubscribeEvents(){this.xr.session.removeEventListener("selectstart",this.onSelectStart),this.xr.session.removeEventListener("selectend",this.onSelectEnd),this.xr.session.removeEventListener("squeezestart",this.onSequeezeStart),this.xr.session.removeEventListener("squeezeend",this.onSequeezeEnd)}_selectButtonIndex=void 0;_squeezeButtonIndex=void 0;onSelectStart=e=>{if(!this.emitPointerDownEvent||this.inputSource!==e.inputSource)return;this.onUpdateFrame(e.frame),this._hasSelectEvent=!0;const t=this._layout?.selectComponentId,i=this._layout?.components[t]?.gamepadIndices?.button;i!==void 0&&(this._selectButtonIndex=i),!Gh&&(Jn&&B.DrawDirection(this.rayWorldPosition,F(0,.01,1).applyQuaternion(this.rayWorldQuaternion),16711680,10),this.emitPointerEvent(Pe.PointerDown,this._selectButtonIndex||0,"xr-standard-trigger",!0,e))};onSelectEnd=e=>{this.emitPointerUpEvent&&(Gh||this.inputSource===e.inputSource&&this.emitPointerEvent(Pe.PointerUp,this._selectButtonIndex||0,"xr-standard-trigger",!0,e))};onSequeezeStart=e=>{this.emitPointerDownEvent&&this.inputSource===e.inputSource&&(this._squeezeButtonIndex=this._layout?.components["xr-standard-squeeze"]?.gamepadIndices?.button,this._squeezeButtonIndex!==void 0&&(Jn&&B.DrawDirection(this.rayWorldPosition,F(0,.01,1).applyQuaternion(this.rayWorldQuaternion),255,10),this.emitPointerEvent(Pe.PointerDown,this._squeezeButtonIndex||0,"xr-standard-squeeze",!0,e)))};onSequeezeEnd=e=>{this.emitPointerUpEvent&&this.inputSource===e.inputSource&&this._squeezeButtonIndex!==void 0&&this.emitPointerEvent(Pe.PointerUp,this._squeezeButtonIndex||0,"xr-standard-squeeze",!0,e)};states={};updateInputEvents(){if(this.gamepad?.buttons){for(let e=0;e<this.gamepad.buttons.length;e++){const t=this.gamepad.buttons[e],i=this.states[e]||new F_;let n=null;this._isMxInk&&(e===4||e===5)?(t.value>0&&!i.pressed?(n="pointerdown",i.isDown=!0,i.isUp=!1):t.value===0&&i.pressed?(n="pointerup",i.isDown=!1,i.isUp=!0):i.pressed&&(n="pointermove",i.isDown=!1,i.isUp=!1),i.pressed=t.value>0,i.value=t.value):(t.pressed&&!i.pressed?(n="pointerdown",i.isDown=!0,i.isUp=!1):!t.pressed&&i.pressed?(n="pointerup",i.isDown=!1,i.isUp=!0):(i.isDown=!1,i.isUp=!1),i.pressed=t.pressed,i.value=t.value),this.states[e]=i;const o=e!==this._selectButtonIndex&&e!==this._squeezeButtonIndex;if(n!=null&&o){let r=this._layout?.gamepad[e];this._isMxInk&&e===4&&(r="stylus-touch"),this._isMxInk&&e===5&&(r="stylus-tip"),(Jn||Gh)&&console.log("Emitting pointer event",n,e,r,t.value,this.gamepad,this._layout),this.emitPointerEvent(n,e,r??"none",!1,null,t.value)}}if(this._isMetaQuestTouchController){const e=this.gamepad.buttons.length-1,t=this.states[e];if(t&&t.isDown){const i=this.context.menu;i.spatialMenuIsVisible?i.setSpatialMenuVisible(!1):this.context.menu.setSpatialMenuVisible(!0)}}}if(this.hand){const e=this.handObject;if(e){const t=e.joints["index-finger-tip"],i=e.joints["thumb-tip"];if(t&&i){const n=t.position.distanceTo(i.position);this._pinchPosition.lerpVectors(t.position,i.position,.5);const o=this.xr.context.mainCamera?.parent;if(o&&this._pinchPosition.applyMatrix4(o.matrixWorld),n!==0){const l=this.states.pinch||new F_,h=(.02+.01)*1.5;l.value=1-(n-.02)/h;const d=n<.02-.01,u=n>.02+.01;d&&!l.pressed?(Gh&&console.log("pinch start",n),l.isDown=!0,l.isUp=!1,l.pressed=!0):u&&l.pressed?(l.isDown=!1,l.isUp=!0,l.pressed=!1):(l.isDown=!1,l.isUp=!1),this.states.pinch=l}}}}}_didMoveLastFrame=!1;_lastPointerMovePosition=new c.Vector3;_lastPointerMoveQuaternion=new c.Quaternion;onUpdateMove(){if(!this.emitPointerMoveEvent)return;let e=!1;if(this._lastPointerMovePosition.distanceTo(this.gripWorldPosition)>this.pointerMoveDistanceThreshold*this.xr.rigScale&&(e=!0),e||this._lastPointerMoveQuaternion.angleTo(this.gripWorldQuaternion)>this.pointerMoveAngleThreshold&&(e=!0),e){this._didMoveLastFrame=!0,this._lastPointerMovePosition.copy(this.gripWorldPosition),this._lastPointerMoveQuaternion.copy(this.gripWorldQuaternion),Jn&&B.DrawLabel(this.rayWorldPosition.add(this.object.worldForward.multiplyScalar(.1)),"move",.01);let i=this.xr.context.input.getFirstPressedButtonForPointer(this.index);i===void 0&&(i=0);const n=this.gamepad?.buttons[i]?.value;this.emitPointerEvent("pointermove",i,"none",!1,null,n)}else this._didMoveLastFrame=!1}pointerInit;emitPointerEvent(e,t,i,n,o=null,r){if(!this.emitEvents){Jn&&e!==Pe.PointerMove&&console.warn("Pointer events are disabled for this controller",this.index,e,t);return}if(this.xr.mode==="immersive-vr"||this.xr.isPassThrough){this.pointerInit.origin=this,this.pointerInit.pointerId=this.getPointerId(t),this.pointerInit.pointerType=this.hand?"hand":"controller",this.pointerInit.button=t,this.pointerInit.buttonName=i,this.pointerInit.isPrimary=n,this.pointerInit.mode=this.inputSource.targetRayMode,this.pointerInit.ray=this.ray,this.pointerInit.device=this.object,this.pointerInit.pressure=r,this.pointerInit.clientX=this._rayPosition.x/this.xr.rigScale,this.pointerInit.clientY=this._rayPosition.y/this.xr.rigScale,this.pointerInit.clientZ=this._rayPosition.z/this.xr.rigScale;const a=U.Current;U.Current=this.xr.context,Jn&&e!=="pointermove"&&console.warn("Pointer event",e,t,i,{...this.pointerInit}),this.xr.context.input.createInputEvent(new ss(e,o,this.pointerInit)),U.Current=a}}}class F_{isDown=!1;isUp=!1;pressed=!1;value=0}class U_{index;name;touched=!1;pressed=!1;value=0;isDown=!1;isUp=!1;constructor(e,t){this.index=e,this.name=t}}const nc=x("debugwebxr");class Vf{controllerStates=[];userId;context;userStateEvtName;constructor(e,t){this.userId=e,this.context=t,this.userStateEvtName="xr-sync-user-state-"+e,this.context.connection.beginListen(this.userStateEvtName,this.onReceivedControllerState)}dispose(){this.context.connection.stopListen(this.userStateEvtName,this.onReceivedControllerState)}onReceivedControllerState=e=>{nc&&console.log(`XRSync: Received change for ${this.userId}: ${e.type} ${e.handedness}; tracked=${e.isTracking}`);let t=!1;for(let i=0;i<this.controllerStates.length;i++)if(this.controllerStates[i].index===e.index){this.controllerStates[i]=e,t=!0;break}t||this.controllerStates.push(e)};update(e){if(this.context.connection.isConnected!=!1){for(let t=this.controllerStates.length-1;t>=0;t--){const i=this.controllerStates[t];let n=!1;for(let o=0;o<e.controllers.length;o++)e.controllers[o].index===i.index&&(n=!0);n||(nc&&console.log(`XRSync: ${i.type} ${i.handedness} removed`,i.index),this.controllerStates.splice(t,1),this.sendControllerRemoved(i))}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(i=>i.index===e.index);if(t){let i=!1;i||=t.isTracking!=e.isTracking,i&&(t.isTracking=e.isTracking,this.context.connection.send(this.userStateEvtName,t))}else{const i={guid:this.userId+"-"+e.index,isTracking:e.isTracking,handedness:e.side,index:e.index,type:e.hand?"hand":"controller"};this.controllerStates.push(i),this.context.connection.send(this.userStateEvtName,i),nc&&console.log(`XRSync: ${i.type} ${i.handedness} added`,i.index)}}}class F0{hasState(e){return e?this._states.has(e):!1}isTracking(e,t){if(!e)return;const i=this._states.get(e);return i?i.controllerStates.find(o=>o.handedness===t)?.isTracking||!1:void 0}getDeviceType(e,t){if(!e)return;const i=this._states.get(e);return i?i.controllerStates.find(o=>o.handedness===t)?.type||"unknown":void 0}context;constructor(e){this.context=e,this.context.connection.beginListen(K.JoinedRoom,this.onJoinedRoom),this.context.connection.beginListen(K.LeftRoom,this.onLeftRoom),this.context.connection.beginListen(K.UserJoinedRoom,this.onOtherUserJoinedRoom),this.context.connection.beginListen(K.UserLeftRoom,this.onOtherUserLeftRoom)}destroy(){this.context.connection.stopListen(K.JoinedRoom,this.onJoinedRoom),this.context.connection.stopListen(K.LeftRoom,this.onLeftRoom),this.context.connection.stopListen(K.UserJoinedRoom,this.onOtherUserJoinedRoom),this.context.connection.stopListen(K.UserLeftRoom,this.onOtherUserLeftRoom)}onJoinedRoom=()=>{if(this.context.connection.connectionId){this._states.has(this.context.connection.connectionId)||(nc&&console.log("XRSync: Local user joined room",this.context.connection.connectionId),this._states.set(this.context.connection.connectionId,new Vf(this.context.connection.connectionId,this.context)));for(const e of this.context.connection.usersInRoom())this._states.has(e)||this._states.set(e,new Vf(e,this.context))}};onLeftRoom=()=>{this.context.connection.connectionId&&(this._states.has(this.context.connection.connectionId)||(this._states.get(this.context.connection.connectionId)?.dispose(),this._states.delete(this.context.connection.connectionId)))};onOtherUserJoinedRoom=e=>{const t=e.userId;this._states.has(t)||(nc&&console.log("XRSync: Remote user joined room",t),this._states.set(t,new Vf(t,this.context)))};onOtherUserLeftRoom=e=>{const t=e.userId;this._states.has(t)||(this._states.get(t)?.dispose(),this._states.delete(t))};_states=new Map;onUpdate(e){this.context.connection.isConnected&&this.context.connection.connectionId&&this._states.get(this.context.connection.connectionId)?.update(e)}onExitXR(e){this.context.connection.isConnected&&this.context.connection.connectionId&&this._states.get(this.context.connection.connectionId)?.onExitXR(e)}}class z_{_fadeToColorQuad;_fadeToColorMaterial;constructor(){this._fadeToColorMaterial=new c.MeshBasicMaterial({color:0,transparent:!0,depthTest:!1,fog:!1,side:c.DoubleSide}),this._fadeToColorQuad=new c.Mesh(new c.PlaneGeometry(10,10),this._fadeToColorMaterial)}dispose(){this._fadeToColorQuad.geometry.dispose(),this._fadeToColorMaterial.dispose()}update(e,t){const i=this._fadeToColorQuad,n=this._fadeToColorMaterial;i.parent!==e&&n.opacity>0?e.add(i):n.opacity===0&&i.removeFromParent(),i.layers.set(2),i.material=this._fadeToColorMaterial,i.position.z=-1,i.renderOrder=1/0;const o=this._requestedFadeValue;n.opacity=I.lerp(n.opacity,o,t/.03),Math.abs(n.opacity-o)<=.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}_requestedFadeValue=0;_transitionPromise=null;_transitionResolve=null}class La{static _active=null;static get active(){return this._active}static _requestInFlight=!1;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 i=await navigator.xr.requestSession(e,t).catch(n=>{console.error("Failed to start temporary XR session:",n)});return i?(i.addEventListener("end",()=>{this._active=null}),this._requestInFlight?(this._requestInFlight=!1,this._active=new La(e,t,i),this._active):(i.end(),null)):(this._requestInFlight=!1,null)}return null}static async handoff(){return this._active?this._active.handoff():null}static async stop(){this._requestInFlight=!1,this._active&&(await this._active.end(),await _s(100)),this._active=null}_session;_mode;_init;get isAR(){return this._mode==="immersive-ar"}get isVR(){return this._mode==="immersive-vr"}_renderer;_camera;_scene;constructor(e,t,i){this._mode=e,this._init=t,this._session=i,this._session.addEventListener("end",this.onEnd),this._renderer=new c.WebGLRenderer({alpha:!0,antialias:!0}),this._renderer.outputColorSpace="srgb",this._renderer.setPixelRatio(Math.min(2,window.devicePixelRatio)),this._renderer.setSize(window.innerWidth,window.innerHeight,!0),exports.DeviceUtilities.isNeedleAppClip()&&window.requestAnimationFrame(()=>{const n=Math.min(2,window.devicePixelRatio),o=Math.floor(window.innerWidth*n),r=Math.floor(window.innerHeight*n);this._renderer.domElement.width=o,this._renderer.domElement.height=r}),this._renderer.setAnimationLoop(this.onFrame),this._renderer.xr.setSession(i),this._renderer.xr.enabled=!0,this._camera=new c.PerspectiveCamera,this._scene=new c.Scene,this._scene.fog=new c.Fog(4473924,10,250),this._scene.add(this._camera),this.setupScene()}end(){return this._session?this._session.end():Promise.resolve()}async handoff(){if(!this._session)throw 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}onEnd=()=>{this._session?.removeEventListener("end",this.onEnd),this._renderer.setAnimationLoop(null),this._renderer.dispose(),this._scene.clear()};_lastTime=0;_frames=0;onFrame=(e,t)=>{const i=e-this._lastTime;this.update(e,i),this._camera.parent!==this._scene&&this._scene.add(this._camera),this._renderer.render(this._scene,this._camera),this._lastTime=e,this._frames++};_roomFlyObjects=[];_logoObject=null;get _logoDistance(){return this.isAR?.3:5}get _logoScale(){return this.isAR?.04:1}update(e,t){const i=e*4e-4;for(let r=0;r<this._roomFlyObjects.length;r++){const a=this._roomFlyObjects[r];a.position.y+=Math.sin(i+r*.5)*.005,a.rotateY(.002)}const n=this._logoObject,o=this._renderer.xr.getCamera();if(n){const r=new c.Vector3;o.getWorldDirection(r);const a=o.position.clone().addScaledVector(r,this._logoDistance),l=this.isAR?.005:1e-5;n.position.lerp(a,this._frames<=2?1:t*l),n.lookAt(this._camera.position)}}async onBeforeHandoff(){await _s(1e3),this._scene.clear()}setupScene(){this._scene.background=new c.Color(0);let e=Da;if($n()){const d=document.querySelector("needle-engine");if(d){const u=d.getAttribute("logo-src");u?.length&&(e=u,A()&&console.debug("[XR] Using custom loading logo from license:",e))}}const t=this._logoObject=new c.Mesh(new c.PlaneGeometry(1,1,1,1),new c.MeshBasicMaterial({transparent:!0,side:2}));t.scale.multiplyScalar(this._logoScale*window.devicePixelRatio),t.renderOrder=1e3,t.material.opacity=0,this._scene.add(t);const i=document.createElement("canvas"),n=i.getContext("2d"),o=new Image,r=d=>{if(!n)return;t.material.opacity=1;const u=1024;i.width=u,i.height=u,n.imageSmoothingQuality="high";const p=u*.19,m=o.width/o.height;{const w=i.height-p*1.5,R=w*m,O=(i.width-R)/2;n.drawImage(o,O,0,R,w)}const y=u*.12,_="Loading...";n.shadowBlur=0,n.fillStyle=this.isAR?"white":"rgba(255,255,255,0.4)",n.font=`${y}px Arial`,n.shadowBlur=u*.02,n.shadowColor="rgba(0,0,0,0.5)",n.shadowOffsetX=0,n.shadowOffsetY=0;const g=n.measureText(_);n.fillText(_,i.width/2-g.width/2,i.height-p/4),n.font=`${y}px Arial`,n.fillText(_,i.width/2-g.width/2,i.height-p/4);const v=new c.TextureLoader().load(i.toDataURL());v.generateMipmaps=!0,v.colorSpace="srgb",v.anisotropy=4;const b=i.width/i.height;t.scale.x=this._logoScale*b*window.devicePixelRatio,t.scale.y=this._logoScale*window.devicePixelRatio,t.material.map=v,t.material.needsUpdate=!0};o.onload=()=>r(),o.onerror=d=>{console.error("Failed to load temporary XR logo:",e,d),o.src=Da},o.crossOrigin="anonymous",o.src=e;const a=new c.DirectionalLight(16777215,1);a.position.set(0,20,0),a.castShadow=!1,this._scene.add(a);const l=new c.DirectionalLight(16777215,1);l.position.set(0,-1,0),l.castShadow=!1,this._scene.add(l);const h=new c.PointLight(16777215,1,100,1);if(h.position.set(0,2,0),h.castShadow=!1,h.distance=200,this._scene.add(h),this.isAR===!1)for(let u=0;u<100;u++){const p=new c.MeshStandardMaterial({color:2236962,metalness:1,roughness:.8}),m=Va.Sphere,y=_o.createPrimitive(m,{material:p});y.position.x=I.random(-50,50),y.position.y=I.random(-2,50),y.position.z=I.random(-50,50),y.rotation.x=I.random(0,Math.PI*2),y.rotation.y=I.random(0,Math.PI*2),y.rotation.z=I.random(0,Math.PI*2),y.scale.multiplyScalar(.5+Math.random()*10);const _=y.position.distanceTo(this._camera.position)-y.scale.x;_<10&&(y.position.z+=5,y.position.multiplyScalar(1+1/_)),this._roomFlyObjects.push(y),this._scene.add(y)}}}var xc;(s=>{const e=[];function t(){e?.length||A()&&console.warn("No USDZ exporters found – cannot export USDZ for QuickLook.");for(const o of e)o.exportAndOpen();return!0}s.exportAndOpen=t;function i(o){e.push(o)}s.registerExporter=i;function n(o){if(!e)return;const r=e.indexOf(o);r>=0&&e.splice(r,1)}s.unregisterExporter=n})(xc||(xc={}));const Ue=x("debugwebxr"),N_=x("stats");let $f=0;function iP(s){let e=null;const t=s;return t.getAROverlayContainer?e=t.getAROverlayContainer():e=s,e}nP();async function nP(){let s="immersive-vr";try{if(exports.DeviceUtilities.isNeedleAppClip()?s="immersive-ar":await navigator.xr?.isSessionSupported("immersive-vr")||(s="immersive-ar"),!await navigator.xr?.isSessionSupported("immersive-ar")&&s==="immersive-ar")return}catch(e){console.debug("[NeedleXRSession:granted] Error while checking XR support:",e);return}if(x("debugasap")){let e=globalThis["needle:XRSession"];if(e instanceof Promise){delete globalThis["needle:XRSession"],ce.addContextCreatedCallback(async t=>{if(!e)return;_a(!0);const i=await e;if(i){const n=q.getDefaultSessionInit(s);q.setSession(s,i,n,t.context)}else console.error("[NeedleXRSession:granted] 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}navigator.xr?.addEventListener("sessiongranted",async()=>{const e=sessionStorage.getItem("needle_xr_session_mode"),t=sessionStorage.getItem("needle_xr_session_init")??null,i=t?JSON.parse(t):null;let n=null;if(U0()&&(await La.start(e||s,i||q.getDefaultSessionInit(s)).catch(o=>console.warn("[NeedleXRSession:granted] TemporaryXRContext start failed:",o)),await rP(),n=await La.handoff()),n)q.setSession(n.mode,n.session,n.init,U.Current);else if(e&&t){console.log("[NeedleXRSession:granted] Restore last session");const o=JSON.parse(t);q.start(e,o).catch(r=>console.warn(r))}else q.start(s).catch(o=>console.warn("[NeedleXRSession:granted] failed:",o))},{once:!0})}}function sP(s,e){sessionStorage.setItem("needle_xr_session_mode",s),sessionStorage.setItem("needle_xr_session_init",JSON.stringify(e))}function oP(){sessionStorage.removeItem("needle_xr_session_mode"),sessionStorage.removeItem("needle_xr_session_init")}const fg=new Set;ce.registerCallback(ae.ContextCreationStart,async s=>{fg.add(s.context)});ce.registerCallback(ae.ContextCreated,async s=>{fg.delete(s.context);const e=s.context?.domElement.getAttribute("autostart")||null;aP(e)});function U0(){return fg.size>0}function rP(){return new Promise(s=>{const e=Date.now(),t=setInterval(()=>{(!U0()||Date.now()-e>6e4)&&(clearInterval(t),s())},100)})}exports.DeviceUtilities.isDesktop()&&A()&&window.addEventListener("keydown",s=>{(s.key==="x"||s.key==="Escape")&&q.active&&q.stop()});function aP(s){s&&s?.toLowerCase()==="ar"&&fn.registerWaitForInteraction(()=>{q.start("ar")})}const Hh=Symbol("initial-fov"),Wf=Symbol("initial-near");class q{static _sync=null;static getXRSync(e){return this._sync||(this._sync=new F0(e)),this._sync}static get currentSessionRequest(){return this._currentSessionRequestMode}static _currentSessionRequestMode=null;static get active(){return this._activeSession}static get activeMode(){return this._activeSession?.mode??null}static get xrSystem(){return"xr"in navigator?navigator.xr:void 0}static isXRSupported(){return Promise.all([this.isVRSupported(),this.isARSupported()]).then(e=>e.some(t=>t)).catch(()=>!1)}static isVRSupported(){return this.isSessionSupported("immersive-vr")}static isARSupported(){return this.isSessionSupported("immersive-ar")}static isSessionSupported(e){return this.xrSystem?.isSessionSupported(e).catch(t=>(Ue&&console.error(t),!1))??Promise.resolve(!1)}static _currentSessionRequest;static _activeSession;static onSessionRequestStart(e){this._sessionRequestStartListeners.push(e)}static offSessionRequestStart(e){const t=this._sessionRequestStartListeners.indexOf(e);t>=0&&this._sessionRequestStartListeners.splice(t,1)}static _sessionRequestStartListeners=[];static onSessionRequestEnd(e){this._sessionRequestEndListeners.push(e)}static offSessionRequestEnd(e){const t=this._sessionRequestEndListeners.indexOf(e);t>=0&&this._sessionRequestEndListeners.splice(t,1)}static _sessionRequestEndListeners=[];static onXRSessionStart(e){this._xrStartListeners.push(e)}static offXRSessionStart(e){const t=this._xrStartListeners.indexOf(e);t>=0&&this._xrStartListeners.splice(t,1)}static _xrStartListeners=[];static onXRSessionEnd(e){this._xrEndListeners.push(e)}static offXRSessionEnd(e){const t=this._xrEndListeners.indexOf(e);t>=0&&this._xrEndListeners.splice(t,1)}static _xrEndListeners=[];static onControllerAdded(e){this._controllerAddedListeners.push(e)}static offControllerAdded(e){const t=this._controllerAddedListeners.indexOf(e);t>=0&&this._controllerAddedListeners.splice(t,1)}static _controllerAddedListeners=[];static onControllerRemoved(e){this._controllerRemovedListeners.push(e)}static offControllerRemoved(e){const t=this._controllerRemovedListeners.indexOf(e);t>=0&&this._controllerRemovedListeners.splice(t,1)}static _controllerRemovedListeners=[];static offerSession(e,t,i){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(n=>q.setSession(e,n,t,i)).catch(n=>{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 exports.DeviceUtilities.isVisionOS()||t.push("hand-tracking"),{optionalFeatures:t};case"immersive-vr":const i=["local-floor","bounded-floor","high-fixed-foveation-level","layers"];return exports.DeviceUtilities.isVisionOS()||i.push("hand-tracking"),{optionalFeatures:i};default:return console.warn("No default session init for mode",e),{}}}static async start(e,t,i){if(t||(t={}),exports.DeviceUtilities.isiOS()){const a=await this.isARSupported().catch(()=>!1);if(exports.DeviceUtilities.isVisionOS()&&!a&&(e==="ar"||e==="immersive-ar")&&(e="quicklook"),e==="quicklook")return ni.sendEvent(U.Current,"xr",{action:"quicklook_export",source:"NeedleXRSession.start"}),xc.exportAndOpen(),null;if(!a&&(e==="immersive-ar"||e==="ar")){this.invokeSessionRequestStart("immersive-ar",t);const l=new URL("https://appclip.apple.com/id?p=tools.needle.launch-app.Clip");l.searchParams.set("url",location.href);const h=l.toString();ni.sendEvent(U.Current,"xr",{action:"app_clip_launch",source:"NeedleXRSession.start",url:h});const d=window.top||window;try{console.debug("iOS device detected - opening Needle App Clip for AR experience",{mode:e,init:t,url:l}),d.location.href=h}catch(u){console.warn("Error navigating to AppClip "+h+`
|
|
878
878
|
`,u),window!==window.top?window.open(h,"_blank"):window.location.href=h}return setTimeout(()=>{this.invokeSessionRequestEnd("immersive-ar",t||{},null)},3e3),null}}if(e==="quicklook")return console.warn("QuickLook mode is only supported on iOS devices"),null;if(e=="ar"&&(e="immersive-ar"),A()&&x("debugxrpreroom"))return console.warn("Debug: Starting temporary XR session"),await La.start(e,t||q.getDefaultSessionInit(e)),null;if(this._currentSessionRequest)return console.warn("A XRSession is already being requested"),(Ue||A())&&fe("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(i||(i=U.Current),i||(i=ce.All[0]),!i)throw new Error("No Needle Engine Context found");switch(e){case"immersive-ar":{if(await this.xrSystem?.isSessionSupported("immersive-ar")!==!0)return console.error(e+" is not supported by this browser."),null;const l=this.getDefaultSessionInit(e),h=iP(i.domElement);h&&!exports.DeviceUtilities.isQuest()&&(l.domOverlay={root:h},l.optionalFeatures.push("dom-overlay")),t={...l,...t}}break;case"immersive-vr":{if(await this.xrSystem?.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.requiredFeatures??=[],await La.stop();const n=e=="immersive-ar"?i.scripts_immersive_ar:i.scripts_immersive_vr;Ue?console.log(`%cRequesting ${e} session`,"font-weight:bold;",t,n):console.log(`%cRequesting ${e} session`,"font-weight:bold;");for(const a of n)a.onBeforeXR&&a.activeAndEnabled&&!a.destroyed&&a.onBeforeXR(e,t);this.invokeSessionRequestStart(e,t),Ue&&Se("Requesting "+e+" session ("+Date.now()+")"),ni.sendEvent(U.Current,"xr",{action:"session_request",mode:e,features:(t.requiredFeatures??[]).concat(t.optionalFeatures??[]).join(","),source:"NeedleXRSession.start"}),this._currentSessionRequest=navigator?.xr?.requestSession(e,t),this._currentSessionRequestMode=e;const o=await this._currentSessionRequest?.catch(a=>{console.error(a,"Code: "+a?.code),a?.code===9&&fe("Couldn't start XR session. Make sure you allow the required permissions."),console.log("If the specified XR configuration is not supported (e.g. entering AR doesnt work) - make sure you access the website on a secure connection (HTTPS) and your device has the required permissions (e.g. camera access)"),location.protocol==="http:"&&fe("XR requires a secure connection (HTTPS)")});return this._currentSessionRequest=void 0,this._currentSessionRequestMode=null,this.invokeSessionRequestEnd(e,t,o),o?this.setSession(e,o,t,i):(console.warn("XR Session request was rejected"),null)}static invokeSessionRequestStart(e,t){for(const i of this._sessionRequestStartListeners)i({mode:e,init:t})}static invokeSessionRequestEnd(e,t,i){for(const n of this._sessionRequestEndListeners)n({mode:e,init:t,newSession:i||null})}static setSession(e,t,i,n){if(this._activeSession)return console.error("A XRSession is already running"),this._activeSession;const o=e=="immersive-ar"?n.scripts_immersive_ar:n.scripts_immersive_vr;return this._activeSession=new q(e,t,n,{scripts:o,controller_added:this._controllerAddedListeners,controller_removed:this._controllerRemovedListeners,init:i}),t.addEventListener("end",this.onEnd),Ue?console.log(`%cStarted ${e} session`,"font-weight:bold;",o):console.log(`%cStarted ${e} session`,"font-weight:bold;"),this._activeSession}static $_stop_request=Symbol();static stop(){const e=this._activeSession;e&&(e[this.$_stop_request]===void 0?(Ue&&console.log("[NeedleXRSession] Stopping XR Session... (new)"),e[this.$_stop_request]=setTimeout(()=>{e.end()})):Ue&&console.warn("[NeedleXRSession] XR Session stop already requested"))}static onEnd=()=>{Ue&&console.log("XR Session ended"),this._activeSession=null};context;get sync(){return q._sync}get running(){return!this._ended&&this.session!=null}session;mode;get interactionMode(){return this.session.interactionMode}get visibilityState(){return this.session.visibilityState}get isVisibleBlurred(){return this.session.visibilityState==="visible-blurred"}get isSystemKeyboardSupported(){return this.session.isSystemKeyboardSupported}get environmentBlendMode(){return this.session.environmentBlendMode}get frame(){return this.context.xrFrame}controllers=[];get leftController(){return this.controllers.find(e=>e.side==="left")}get rightController(){return this.controllers.find(e=>e.side==="right")}getController(e){return typeof e=="number"?this.controllers[e]||null:this.controllers.find(t=>t.side===e)||null}get isPassThrough(){return!!(this.environmentBlendMode!=="opaque"&&this.interactionMode==="world-space"||this.mode==="immersive-ar"&&this.environmentBlendMode!=="opaque"&&this.controllers.some(e=>e.inputSource.targetRayMode==="tracked-pointer")||A()&&exports.DeviceUtilities.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?.gameObject&&dr(e.gameObject)||e?.isActive===!1?(this.updateActiveXRRig(),this._rigs[0]??null):e}_rigScale=1;_lastRigScaleUpdate=-1;get rigScale(){return this._rigs[0]?(this._lastRigScaleUpdate!==this.context.time.frame&&(this._lastRigScaleUpdate=this.context.time.frame,this._rigScale=this._rigs[0].gameObject.worldScale.x),this._rigScale):1}addRig(e){this._rigs.indexOf(e)>=0||(e.priority===void 0&&(e.priority=0),this._rigs.push(e),this.updateActiveXRRig())}removeRig(e){const t=this._rigs.indexOf(e);t!==-1&&(this._rigs.splice(t,1),this.updateActiveXRRig())}setRigActive(e){const t=this._rigs.indexOf(e),i=this._rigs[0];this._rigs.splice(t,1),this._rigs.unshift(e),e.priority=i?.priority??0,this.updateActiveXRRig()}getUserOffsetInRig(){const e=this.context.mainCamera?.position;if(!e||!this.rig)return F(0,0,0);const t=F(e);return t.x*=-1,t.z*=-1,t.applyQuaternion(ei(this.rig.gameObject.quaternion)),t}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 i=1;i<this._rigs.length;i++){const n=this._rigs[i];if(n.isActive){if(dr(n.gameObject)){this._rigs.splice(i,1),i--;continue}(!t||t.isActive===!1||n.priority!==void 0&&n.priority>t.priority)&&(t=n)}}if(e!==t){const i=this._rigs.indexOf(t);i>=0&&this._rigs.splice(i,1),this._rigs.unshift(t)}Ue&&(e===t?console.log("Updated Active XR Rig:",t,"prev:",e):console.log("Updated Active XRRig:",t," (the same as before)"))}_rigs=[];_viewerHitTestSource=null;getHitTest(e){if(e)return this.getControllerHitTest(e);if(!this._viewerHitTestSource)return null;const t=this._viewerHitTestSource,i=this.frame.getHitTestResults(t);if(i.length>0){const n=i[0];return this.convertHitTestResult(n)}return null}getControllerHitTest(e){const t=e.getHitTestSource();if(!t)return null;const i=this.frame.getHitTestResultsForTransientInput(t);for(const n of i)if(n.inputSource===e.inputSource)for(const o of n.results)return this.convertHitTestResult(o);return null}convertHitTestResult(e){const t=this.context.renderer.xr.getReferenceSpace(),i=t&&e.getPose(t);if(i){const n=F(i.transform.position),o=ei(i.transform.orientation),r=this.context.mainCamera;if(r?.parent!==this._cameraRenderParent&&n.applyMatrix4(wa),r?.parent){n.applyMatrix4(r.parent.matrixWorld),o.multiply(Li);const a=pe(r.parent);a.premultiply(Li),o.premultiply(a)}return{hit:e,position:n,quaternion:o}}return null}convertSpace(e){const t=F(e.position);t.applyMatrix4(wa);const i=ei(e.orientation);return i.premultiply(Li),{position:t,quaternion:i}}_defaultRig;_xr_scripts;_xr_update_scripts=[];_inactive_scripts=[];_controllerAdded;_controllerRemoved;_originalCameraWorldPosition;_originalCameraWorldRotation;_originalCameraWorldScale;_originalCameraParent;_mainCamera=null;constructor(e,t,i,n){sP(e,n.init),this.session=t,this.mode=e,this.context=i,(Ue||x("console"))&&_a(!0),this._xr_scripts=[...n.scripts],this._xr_update_scripts=this._xr_scripts.filter(o=>typeof o.onUpdateXR=="function"),this._controllerAdded=n.controller_added,this._controllerRemoved=n.controller_removed,xs(this.onBefore,ge.LateUpdate),this.context.pre_render_callbacks.push(this.onBeforeRender),this.context.post_render_callbacks.push(this.onAfterRender),(n.init.optionalFeatures?.includes("hit-test")||n.init.requiredFeatures?.includes("hit-test"))&&t.requestReferenceSpace("viewer").then(o=>t.requestHitTestSource?.call(t,{space:o})?.then(r=>this._viewerHitTestSource=r).catch(r=>console.error(r))).catch(o=>console.error(o)),this.context.mainCamera&&(this._originalCameraWorldPosition=Y(this.context.mainCamera,new c.Vector3),this._originalCameraWorldRotation=pe(this.context.mainCamera,new c.Quaternion),this._originalCameraWorldScale=je(this.context.mainCamera,new c.Vector3),this._originalCameraParent=this.context.mainCamera.parent,this.context.mainCamera instanceof c.PerspectiveCamera&&(this.context.mainCamera[Hh]=this.context.mainCamera.fov)),this._defaultRig=new K1,this.context.scene.add(this._defaultRig.gameObject),this.addRig(this._defaultRig);for(let o=0;o<t.inputSources.length;o++){const r=t.inputSources[o];if(!r.handedness){console.warn("Input source in xr session has no handedness - ignoring",o);continue}this.onInputSourceAdded(r)}this.session.addEventListener("end",this.onEnd),this.session.addEventListener("inputsourceschange",o=>{for(const r of o.removed)this.disconnectInputSource(r);for(const r of o.added)this.onInputSourceAdded(r)}),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):Ue&&console.warn("controllerAutoUpdate is not available in three.js - cannot disable it"),exports.DeviceUtilities.isNeedleAppClip()&&window.requestAnimationFrame(()=>{const o=this.context.renderer.domElement,r=window.devicePixelRatio||1,a=o.width,l=o.height,h=Math.floor(window.innerWidth*r),d=Math.floor(window.innerHeight*r);(Math.abs(a-h)>2||Math.abs(l-d)>2)&&(o.width=h,o.height=d,console.debug("Applied DPR scaling for Needle AppClip XR session",r,o.width,o.height))})}onRendererSessionSet=()=>{this.running&&(this.context.renderer.xr.enabled=!0,this.context.renderer.xr.updateCamera(this.context.mainCamera),this.context.mainCameraComponent?.applyClearFlags())};onInputSourceAdded=e=>{if(e.targetRayMode==="screen")return;let t=0;for(let n=0;n<this.session.inputSources.length;n++)if(this.session.inputSources[n]===e){t=n;break}if(this.controllers.find(n=>n.inputSource===e)){console.debug("Controller already exists for input source",t);return}else if(this._newControllers.find(n=>n.inputSource===e)){console.debug("Controller already registered for input source",t);return}const i=new ug(this,e,t);this._newControllers.push(i)};disconnectInputSource(e){const t=(o,r)=>{if(o.inputSource===e){Ue&&console.log("Disconnecting controller",o.index);const a=r.indexOf(o);a>=0&&r.splice(a,1),this.invokeControllerEvent(o,this._controllerRemoved,"removed");const l={xr:this,controller:o,change:"removed"};for(const h of this._xr_scripts)h.onXRControllerRemoved&&h.onXRControllerRemoved(l);o.onDisconnected()}},i=[...this.controllers];for(let o=i.length-1;o>=0;o--){const r=i[o];t(r,this.controllers)}const n=[...this._newControllers];for(let o=n.length-1;o>=0;o--){const r=n[o];t(r,this._newControllers)}}end(){this._ended||this.session.end().catch(e=>console.warn(e))}_ended=!1;_newControllers=[];onEnd=e=>{if(this._ended)return;this._ended=!0,console.debug("XR Session ended"),ni.sendEvent(U.Current,"xr",{action:"session_end",mode:this.mode,source:"NeedleXRSession.onEnd"}),oP(),this.onAfterRender(),this.revertCustomForward(),this._didStart=!1,this._previousCameraParent=null,this.requestedCameraNearPlane=null,yo(this.onBefore,ge.LateUpdate);const t=this.context.pre_render_callbacks.indexOf(this.onBeforeRender);t>=0&&this.context.pre_render_callbacks.splice(t,1);const i=this.context.post_render_callbacks.indexOf(this.onAfterRender);i>=0&&this.context.post_render_callbacks.splice(i,1),this.context.xr=null,this.context.renderer.xr.enabled=!1,this.context.pre_update_oneshot_callbacks.push(()=>{this.context.mainCameraComponent?.applyClearFlags(),this.context.mainCameraComponent?.applyClippingPlane()}),D0({session:this});for(const o of q._xrEndListeners)o({xr:this});const n=[...this.controllers];for(let o=0;o<n.length;o++)this.disconnectInputSource(n[o].inputSource);this.controllers.length=0,this._newControllers.length=0;for(const o of this._xr_scripts)o?.onLeaveXR?.({xr:this});this.sync?.onExitXR(this),this.context.mainCamera&&(this._originalCameraParent?.add(this.context.mainCamera),this._originalCameraWorldPosition&&at(this.context.mainCamera,this._originalCameraWorldPosition),this._originalCameraWorldRotation&&dn(this.context.mainCamera,this._originalCameraWorldRotation),this._originalCameraWorldScale&&ka(this.context.mainCamera,this._originalCameraWorldScale),this.context.mainCamera instanceof c.PerspectiveCamera&&(this.context.mainCamera[Hh]&&(this.context.mainCamera.fov=this.context.mainCamera[Hh],this.context.mainCamera[Hh]=0),this.context.mainCamera[Wf]&&(this.context.mainCamera.near=this.context.mainCamera[Wf],this.context.mainCamera[Wf]=0))),this.context.requestSizeUpdate(),this._defaultRig.gameObject.removeFromParent(),_a(!1)};_didStart=!1;onBefore=e=>{const t=e.xrFrame;if(!t)return;this.context.xr=this,this.context.mainCameraComponent&&this.context.mainCameraComponent!==this._mainCamera&&(this._mainCamera=this.context.mainCameraComponent),this.rig?.isActive==!1&&(Ue&&console.warn("Latest rig is not active - trying to activate a different rig",this.rig),this.updateActiveXRRig()),this.rig&&this._mainCamera?.gameObject&&this._mainCamera?.gameObject?.parent!==this.rig.gameObject&&this.rig.gameObject.add(this._mainCamera?.gameObject),this.internalUpdateState(),this.applyCustomForward();const i={xr:this};if(this._didStart){if(this.context.new_scripts_xr.length>0){const n=[...this.context.new_scripts_xr];for(let o=0;o<n.length;o++){const r=this.context.new_scripts_xr[o];if(!r||r.destroyed||r.supportsXR?.(this.mode)==!1){this.context.new_scripts_xr.splice(o,1);continue}if(!r.activeAndEnabled){this.context.new_scripts_xr.splice(o,1),this.markInactive(r);continue}if(this.addScript(r)){this.invokeCallback_EnterXR(r);for(const a of this.controllers)this.invokeCallback_ControllerAdded(r,a)}}}}else{if(this._didStart=!0,this.mode==="immersive-vr"){const o=ri(this.context.scene.children);if(o){const r=o.getSize(F());if(r.length()>0){const a=this._defaultRig.gameObject;a.position.set(o.min.x+r.x*.5,o.min.y,o.max.z+r.z*.5+1.5);const l=o.getCenter(F());l.y=a.position.y,a.lookAt(l)}}}A0({session:this}),_r();for(const o of q._xrStartListeners)o(i);const n=[...this._xr_scripts];Ue&&console.log("NeedleXRSession start, handle scripts:",n);for(const o of n){if(o.destroyed){this._script_to_remove.push(o);continue}if(!o.activeAndEnabled){this.markInactive(o);continue}this.invokeCallback_EnterXR(o);for(const r of this.controllers)this.invokeCallback_ControllerAdded(o,r)}}this.syncCameraCullingMask();for(const n of this.controllers)n.onUpdate(t);if(this._newControllers.length>0){const n=[...this._newControllers];this._newControllers.length=0;for(const o of n){if(!o.connected){console.warn("New controller is not connected",o);continue}this.controllers.push(o);for(const r of this._xr_scripts){if(r.destroyed){this._script_to_remove.push(r);continue}r.activeAndEnabled!==!1&&this.invokeCallback_ControllerAdded(r,o)}}this.controllers.sort((o,r)=>o.index-r.index)}Ue&&this.context.time.frame%30===0&&this.controllers.length<=0&&this.session.inputSources.length>0&&(_a(!0),console.error("XRControllers are not added but inputSources are present"));for(const n of this._xr_update_scripts){if(n.destroyed===!0){this._script_to_remove.push(n);continue}if(n.activeAndEnabled===!1){this.markInactive(n);continue}n.onUpdateXR&&n.onUpdateXR(i)}if(this.handleInactiveScripts(),this._script_to_remove.length>0){const n=[...new Set(this._script_to_remove)];this._script_to_remove.length=0;for(const o of n)!o.destroyed&&this.running&&o.onLeaveXR?.(i),this.removeScript(o)}this.sync?.onUpdate(this),this.onRenderDebug()};onRenderDebug(){if(Ue)for(const e of this.controllers)e.onRenderDebug();if((Ue||N_)&&this.rig&&($f++,$f>=20)){const e=this.rig.gameObject.worldPosition,t=this.rig.gameObject.worldForward;e.add(t.multiplyScalar(1.5));const i=this.rig.gameObject.worldUp;e.add(i.multiplyScalar(2.5));let n="";if(n+=`${this.context.time.smoothedFps.toFixed(0)} FPS`,n+=`, calls: ${this.context.renderer.info.render.calls}, tris: ${this.context.renderer.info.render.triangles.toLocaleString()}`,Ue||N_)for(const o of this.controllers)n+=`
|
|
879
|
-
${o.hand?"hand":"ctrl"} ${o.inputSource.handedness}[${o.index}] con:${o.connected} tr:${o.isTracking} hts:${o.hasHitTestSource?"yes":"no"}`;$f=0,B.DrawLabel(e,n,void 0,1/60*20)}}onBeforeRender=()=>{this.context.mainCamera&&(this.updateFade(this.context.mainCamera),this.requestedCameraNearPlane!==null&&this.context.mainCamera instanceof c.PerspectiveCamera&&(this.context.mainCamera.near=this.requestedCameraNearPlane,this.requestedCameraNearPlane=null))};onAfterRender=()=>{if(this.onUpdateFade_PostRender(),exports.DeviceUtilities.isDesktop()||!this._renderOnceOnDevice){const e=this.context.renderer;if(e.xr.isPresenting&&this.context.mainCamera){this._renderOnceOnDevice=!0;const t=e.xr.enabled,i=e.getRenderTarget(),n=this.context.scene.background;e.xr.enabled=!1,e.setRenderTarget(null),this.isPassThrough&&(this.context.scene.background=null),this.context.composer?this.context.composer.render(this.context.time.deltaTime):e.render(this.context.scene,this.context.mainCamera),e.xr.enabled=t,e.setRenderTarget(i),this.context.scene.background=n}}};addScript(e){return this._xr_scripts.includes(e)?!1:(Ue&&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 i of this.controllers)this.invokeCallback_ControllerAdded(t,i)}}}_script_to_remove=[];removeScript(e,t=!0){Ue&&console.log("Remove XRScript",e);const i=this._xr_scripts.indexOf(e);i>=0&&this._xr_scripts.splice(i,1);const n=this._xr_update_scripts.indexOf(e);if(n>=0&&this._xr_update_scripts.splice(n,1),t){const o=this._inactive_scripts.indexOf(e);o>=0&&this._inactive_scripts.splice(o,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(){const e=this.context.xrCamera,t=this.context.mainCameraComponent?.cullingMask;if(e&&t!==void 0){for(const i of e.cameras)i.layers.mask=t;e.layers.mask=t}else if(e){for(const i of e.cameras)i.layers.enableAll();e.layers.enableAll()}}invokeControllerEvent(e,t,i){for(let n=t.length-1;n>=0;n--){const o=t[n];if(o)try{o({xr:this,controller:e,change:i})}catch(r){console.error(r)}}}_camera;_cameraRenderParent=new c.Object3D().rotateY(Math.PI);_previousCameraParent;_customforward=!0;originalCameraNearPlane;requestedCameraNearPlane=null;applyCustomForward(){if(this.context.mainCamera&&this._customforward){this._camera=this.context.mainCamera,this._camera.parent!==this._cameraRenderParent&&(this._previousCameraParent=this._camera.parent,this._previousCameraParent?.add(this._cameraRenderParent)),this._cameraRenderParent.name="XR Camera Render Parent",this._cameraRenderParent.add(this._camera);{let e=.02;const t=.001;if(this.rig){const i=je(this.rig.gameObject);e*=i.x}this._camera instanceof c.PerspectiveCamera&&Math.abs(this._camera.near-e)>t&&(this.isAR?this.originalCameraNearPlane=this._camera.near:this._camera.near=e,Ue&&console.debug(`Setting camera near plane to ${e} (was ${this.originalCameraNearPlane}) to account for XR rendering scale`))}}}revertCustomForward(){this._camera&&this._previousCameraParent&&this._previousCameraParent.add(this._camera),this._previousCameraParent=null,this._camera instanceof c.PerspectiveCamera&&this.originalCameraNearPlane!=null&&(this._camera.near=this.originalCameraNearPlane,this.originalCameraNearPlane=void 0)}_viewerPose;_transformOrientation=new c.Quaternion;_transformPosition=new c.Vector3;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)}}_transition;get transition(){return this._transition||(this._transition=new z_),this._transition}fadeTransition(){return this._transition||(this._transition=new z_),this._transition.fadeTransition()}updateFade(e){this._transition&&e instanceof c.PerspectiveCamera&&this._transition.update(e,this.context.time.deltaTime)}onUpdateFade_PostRender(){this._transition?.remove()}}const Gf=x("debugwebxr");class z0{static tryFindAvatarObjects(e,t,i){if(i.head&&i.leftHand&&i.rightHand)return;const n=e.name.toLocaleLowerCase();!i.head&&n.includes("head")&&(Gf&&console.log("FOUND AVATAR HEAD",e.name),i.head=new Z("",t,e)),n.includes("hand")&&(!i.leftHand&&n.includes("left")&&(Gf&&console.log("FOUND AVATAR LEFT HAND",e.name),i.leftHand=new Z("",t,e)),!i.rightHand&&n.includes("right")&&(Gf&&console.log("FOUND AVATAR RIGHT HAND",e.name),i.rightHand=new Z("",t,e)));for(let o=0;o<e.children.length;o++){if(i.head&&i.leftHand&&i.rightHand)return;const r=e.children[o];this.tryFindAvatarObjects(r,t,i)}}}class te extends c.Color{alpha=1;get isRGBAColor(){return!0}set a(e){this.alpha=e}get a(){return this.alpha}constructor(e,t,i,n){super(),typeof e=="number"&&typeof t=="number"&&typeof i=="number"?(this.set(e,t,i),this.alpha=typeof n=="number"?n:1):e!==void 0&&(this.set(e),this.alpha=1)}clone(){const e=super.clone();return e.alpha=this.alpha,e}copy(e){return this.r=e.r,this.g=e.g,this.b=e.b,"alpha"in e&&typeof e.alpha=="number"?this.alpha=e.alpha:typeof e.a=="number"&&(this.alpha=e.a),this}lerp(e,t){const i=e;return i.alpha!=null&&(this.alpha=I.lerp(this.alpha,i.alpha,t)),super.lerp(e,t)}lerpColors(e,t,i){const n=e,o=t;return n.alpha!=null&&o.alpha!=null&&(this.alpha=I.lerp(n.alpha,o.alpha,i)),super.lerpColors(e,t,i)}multiply(e){const t=e;return t.alpha!=null&&(this.alpha=this.alpha*t.alpha),super.multiply(e)}fromArray(e,t=0){return this.alpha=e[t+3],super.fromArray(e,t)}static fromColorRepresentation(e){if(typeof e=="string"){if(e.trim()==="transparent")return new te(0,0,0,0);if(e.startsWith("#")&&e.length===9){const t=parseInt(e.slice(1,9),16),i=t>>24&255,n=t>>16&255,o=t>>8&255,r=t>>0&255;return new te(i/255,n/255,o/255,r/255)}else if(e.startsWith("#")){const t=parseInt(e.slice(1),16),i=t>>16&255,n=t>>8&255,o=t>>0&255;return new te(i/255,n/255,o/255,1)}else if(e.startsWith("rgba")){const t=e.slice(5,-1).split(",").map(Number);return new te(t[0]/255,t[1]/255,t[2]/255,t[3])}else if(e.startsWith("rgb")){const t=e.slice(4,-1).split(",").map(Number);return new te(t[0]/255,t[1]/255,t[2]/255,1)}}else if(Array.isArray(e)){if(e.length===4)return new te(e[0],e[1],e[2],e[3]);if(e.length===3)return new te(e[0],e[1],e[2],1);console.error("Invalid color array length. Expected 3 or 4, got "+e.length)}return new te(e)}}const Mt=new c.Vector3,V_=new c.Vector3,$_=new c.Quaternion,lP=x("debuggizmos"),nn=8947848,Hf=32;class B{constructor(){}static enabled=!0;static isGizmo(e){return e[Jp]!==void 0}static setVisible(e){for(const t of Ei.timedObjectsBuffer)t.visible=e}static DrawLabel(e,t,i=.05,n=0,o,r,a){if(!B.enabled)return null;o||(o=nn);const l=q.active?.rigScale??1,h=Ei.getTextLabel(n,t,i*l,o,r);return a instanceof c.Object3D&&a.add(h),h.position.x=e.x,h.position.y=e.y,h.position.z=e.z,h}static DrawRay(e,t,i=nn,n=0,o=!0){if(!B.enabled)return;const r=Ei.getLine(n),a=r.geometry.getAttribute("position");a.setXYZ(0,e.x,e.y,e.z),Mt.set(t.x,t.y,t.z).multiplyScalar(999999999),a.setXYZ(1,e.x+Mt.x,e.y+Mt.y,e.z+Mt.z),a.needsUpdate=!0,r.material.depthTest=o,r.material.depthWrite=!1,r.material.fog=!1,rn(r.material,i)}static DrawDirection(e,t,i=nn,n=0,o=!0,r=1){if(!B.enabled)return;const a=Ei.getLine(n),l=a.geometry.getAttribute("position");l.setXYZ(0,e.x,e.y,e.z),t.w!==void 0?(Mt.set(0,0,-r),$_.set(t.x,t.y,t.z,t.w),Mt.applyQuaternion($_)):(Mt.set(t.x,t.y,t.z),Mt.multiplyScalar(r)),l.setXYZ(1,e.x+Mt.x,e.y+Mt.y,e.z+Mt.z),l.needsUpdate=!0,a.material.depthTest=o,a.material.depthWrite=!1,rn(a.material,i)}static DrawLine(e,t,i=nn,n=0,o=!0){if(!B.enabled)return;const r=Ei.getLine(n),a=r.geometry.getAttribute("position");a.setXYZ(0,e.x,e.y,e.z),a.setXYZ(1,t.x,t.y,t.z),a.needsUpdate=!0,r.material.depthTest=o,r.material.depthWrite=!1,r.material.fog=!1,rn(r.material,i)}static DrawCircle(e,t,i,n=nn,o=0,r=!0){if(!B.enabled)return;const a=Ei.getCircle(o);a.position.set(e.x,e.y,e.z),a.scale.set(i,i,i),a.quaternion.setFromUnitVectors(this._up,Mt.set(t.x,t.y,t.z).normalize()),a.material.depthTest=r,a.material.depthWrite=!1,a.material.fog=!1,rn(a.material,n)}static DrawWireSphere(e,t,i=nn,n=0,o=!0){if(!B.enabled)return;const r=Ei.getSphere(t,n,!0);hr(r,e.x,e.y,e.z),r.material.depthTest=o,r.material.depthWrite=!1,r.material.fog=!1,rn(r.material,i)}static DrawSphere(e,t,i=nn,n=0,o=!0){if(!B.enabled)return;const r=Ei.getSphere(t,n,!1);hr(r,e.x,e.y,e.z),r.material.depthTest=o,r.material.depthWrite=!1,rn(r.material,i)}static DrawWireBox(e,t,i=nn,n=0,o=!0,r=void 0){if(!B.enabled)return;const a=Ei.getBox(n);a.position.set(e.x,e.y,e.z),a.scale.set(t.x,t.y,t.z),r?a.quaternion.copy(r):a.quaternion.identity(),a.material.depthTest=o,a.material.wireframe=!0,a.material.depthWrite=!1,a.material.fog=!1,rn(a.material,i)}static DrawWireBox3(e,t=nn,i=0,n=!0){if(!B.enabled)return;const o=Ei.getBox(i);o.position.copy(e.getCenter(Mt)),o.scale.copy(e.getSize(Mt)),o.material.depthTest=n,o.material.wireframe=!0,o.material.depthWrite=!1,o.material.fog=!1,rn(o.material,t)}static _up=new c.Vector3(0,1,0);static DrawArrow(e,t,i=nn,n=0,o=!0,r=!1){if(!B.enabled)return;const a=Ei.getArrowHead(n);a.position.set(t.x,t.y,t.z),a.quaternion.setFromUnitVectors(this._up.set(0,1,0),Mt.set(t.x,t.y,t.z).sub(V_.set(e.x,e.y,e.z)).normalize());const h=Mt.set(t.x,t.y,t.z).sub(V_.set(e.x,e.y,e.z)).length()*.1;a.scale.set(h,h,h),a.material.depthTest=o,a.material.wireframe=r,rn(a.material,i),this.DrawLine(e,t,i,n,o)}static DrawWireMesh(e){const t=Ei.getMesh(e.duration??0);"mesh"in e?(t.geometry=e.mesh.geometry,t.matrixWorld.copy(e.mesh.matrixWorld)):(t.geometry=e.geometry,t.matrixWorld.copy(e.matrix)),t.matrixAutoUpdate=!1,t.matrixWorldAutoUpdate=!1,t.material.depthTest=e.depthTest??!0,t.material.wireframe=!0,rn(t.material,e.color??nn)}}const cP=new c.BoxGeometry(1,1,1);function pg(s=null){const e=new c.Color(s??14540253),t=new c.EdgesGeometry(cP);return new c.LineSegments(t,new c.LineBasicMaterial({color:e}))}function rn(s,e){if(Array.isArray(s)){for(const i of s)rn(i,e);return}const t=e instanceof te?e.a:1;s.color.set(e),s.opacity=t,s.transparent=t<1}const Jp=Symbol("GizmoCache");class Ei{static familyName="needle-gizmos";static ensureFont(){let e=ie.__webpack_exports__default.FontLibrary.getFontFamily(this.familyName);e||(e=ie.__webpack_exports__default.FontLibrary.addFontFamily(this.familyName),e.addVariant("normal","normal","https://cdn.needle.tools/static/fonts/msdf/arial/arial-msdf.json","https://cdn.needle.tools/static/fonts/msdf/arial/arial.png")?.addEventListener("ready",()=>{ie.__webpack_exports__default.update()}))}static getTextLabel(e,t,i,n,o){this.ensureFont();let r=this.textLabelCache.pop(),a=1;o&&typeof o=="string"&&o?.length>=8&&o.startsWith("#")?(a=parseInt(o.substring(7),16)/255,o=o.substring(0,7),lP&&console.log(o,a)):typeof o=="object"&&o.a!==void 0&&(a=o.a);const l={boxSizing:"border-box",fontFamily:this.familyName,width:"auto",fontSize:i,color:n,lineHeight:1,backgroundColor:o??void 0,backgroundOpacity:a,textContent:t,borderRadius:.5*i,padding:.8*i,whiteSpace:"pre",offset:.05*i};if(r)r.set(l);else{r=new ie.__webpack_exports__Text(l);const h=this,d=r;d.setText=function(u){this.set({textContent:u}),h.tmuiNeedsUpdate=!0}}return this.tmuiNeedsUpdate=!0,this.registerTimedObject(U.Current,r,e,this.textLabelCache),r}static getBox(e){let t=this.boxesCache.pop();if(!t){const i=new c.BoxGeometry(1,1,1);t=new c.Mesh(i)}return this.registerTimedObject(U.Current,t,e,this.boxesCache),t}static getLine(e){let t=this.linesCache.pop();if(!t){t=new c.Line;let i=t.geometry.getAttribute("position");i||(i=new c.BufferAttribute(new Float32Array(6),3),t.geometry.setAttribute("position",i))}return t.frustumCulled=!1,this.registerTimedObject(U.Current,t,e,this.linesCache),t}static getCircle(e){let t=this.circlesCache.pop();if(!t){t=new c.Line;let i=t.geometry.getAttribute("position");if(!i){i=new c.BufferAttribute(new Float32Array(Hf*3),3),t.geometry.setAttribute("position",i);const n=F(0,1,0),o=F(0,0,1),r=F(o);r.cross(n).normalize();const a=F(r),l=Math.PI*2/(Hf-1);for(let h=0;h<Hf+1;h++){const d=l*h;n.copy(a).multiplyScalar(Math.cos(d)*1),r.copy(o).multiplyScalar(Math.sin(d)*1);const u=n.add(r);i.setXYZ(h,u.x,u.y,u.z)}}}return t.frustumCulled=!1,this.registerTimedObject(U.Current,t,e,this.circlesCache),t}static getSphere(e,t,i){let n=this.spheresCache.pop();return n||(n=new c.Mesh(new c.SphereGeometry(1,8,8))),n.scale.set(e,e,e),n.material.wireframe=i,this.registerTimedObject(U.Current,n,t,this.spheresCache),n}static getArrowHead(e){let t=this.arrowHeadsCache.pop();return t||(t=new c.Mesh(new c.CylinderGeometry(0,.5,1,8))),this.registerTimedObject(U.Current,t,e,this.arrowHeadsCache),t}static getMesh(e){let t=this.mesh.pop();return t||(t=new c.Mesh,t.material=new c.MeshBasicMaterial),this.registerTimedObject(U.Current,t,e,this.mesh),t}static linesCache=[];static circlesCache=[];static spheresCache=[];static boxesCache=[];static arrowHeadsCache=[];static mesh=[];static textLabelCache=[];static registerTimedObject(e,t,i,n){if(!e){console.error("No Needle Engine context available. Did you call a Gizmos function in global scope?");return}const o=this.contextBeforeRenderCallbacks.get(e),r=this.contextPostRenderCallbacks.get(e);if(o){if(e.pre_render_callbacks[e.pre_render_callbacks.length-1]!==o){const a=e.pre_render_callbacks.indexOf(o);a>=0&&e.pre_render_callbacks.splice(a,1),e.pre_render_callbacks.push(o)}}else{const a=()=>{this.onBeforeRender(e,this.timedObjectsBuffer)};this.contextBeforeRenderCallbacks.set(e,a),e.pre_render_callbacks.push(a)}if(r){if(e.post_render_callbacks[e.post_render_callbacks.length-1]!==r){const a=e.post_render_callbacks.indexOf(r);a>=0&&e.post_render_callbacks.splice(a,1),e.post_render_callbacks.push(r)}}else{const a=()=>{this.onPostRender(e,this.timedObjectsBuffer,this.timesBuffer)};this.contextPostRenderCallbacks.set(e,a),e.post_render_callbacks.push(a)}t.traverse(a=>{a.layers.disableAll(),a.layers.enable(2)}),t.renderOrder=999999,t[Jp]=n,t.castShadow=!1,t.receiveShadow=!1,t.isGizmo=!0,this.timedObjectsBuffer.push(t),this.timesBuffer.push(U.Current.time.realtimeSinceStartup+i),e.scene.add(t)}static timedObjectsBuffer=new Array;static timesBuffer=new Array;static contextPostRenderCallbacks=new Map;static contextBeforeRenderCallbacks=new Map;static tmuiNeedsUpdate=!1;static onBeforeRender(e,t){this.tmuiNeedsUpdate&&(this.tmuiNeedsUpdate=!1,ie.__webpack_exports__default.update());for(let i=0;i<t.length;i++){const n=t[i];if(e.mainCamera&&n instanceof ie.__webpack_exports__default.MeshUIBaseElement){if(dr(n))continue;const o=e.isInVR,r=!1,a=!o;Nc(n,e.mainCamera,r,a)}}}static onPostRender(e,t,i){const n=e.time.realtimeSinceStartup;for(let o=t.length-1;o>=0;o--){const r=t[o];n>=i[o]-1e-6&&(t.splice(o,1),i.splice(o,1),r.removeFromParent(),dr(r)!=!0&&r[Jp].push(r))}}}const Vt=x("debugphysics"),hP=x("debugworker"),W_=new c.Layers;class bo{static AllLayers=4294967295;ray;cam;screenPoint;raycaster;results;targets;recursive=!0;minDistance;maxDistance;lineThreshold;layerMask;ignore;testObject;useAcceleratedRaycast;allowSlowRaycastFallback=!0;screenPointFromOffset(e,t){this.screenPoint===void 0&&(this.screenPoint=new c.Vector2),this.screenPoint.x=e/window.innerWidth*2-1,this.screenPoint.y=-(t/window.innerHeight)*2+1}setLayer(e){W_.set(e),this.layerMask=W_}setMask(e){this.layerMask||(this.layerMask=new c.Layers);const t=this.layerMask;t?t.mask=e:this.layerMask=e}}class mg{distance;point;object;constructor(e,t,i){this.object=e,this.distance=t,this.point=i}}class Ia{static _raycasting=0;static get raycasting(){return this._raycasting>0}raycastPhysicsFast(e,t=void 0,i=1/0,n=!0){return this.context.physics.engine?.raycast(e,t,{maxDistance:i,solid:n})??null}raycastPhysicsFastAndGetNormal(e,t=void 0,i=1/0,n=!0){return this.context.physics.engine?.raycastAndGetNormal(e,t,{maxDistance:i,solid:n})??null}sphereOverlapPhysics(e,t){return this.context.physics.engine?.sphereOverlap(e,t)??null}context;engine;constructor(e){this.context=e}raycaster=new c.Raycaster;defaultRaycastOptions=new bo;targetBuffer=new Array(1);defaultThresholds={Mesh:{},Line:{threshold:-1},LOD:{},Points:{threshold:0},Sprite:{}};sphereResults=new Array;sphereMask=new c.Layers;sphere=new c.Sphere;sphereOverlap(e,t,i=!0,n=!1,o=null){if(this.sphereResults.length=0,!this.context.scene)return this.sphereResults;const r=this.sphereMask;r.enableAll(),r.disable(2);for(const a of this.context.scene.children)this.intersectSphere(a,e,t,r,this.sphereResults,i,n,o);return this.sphereResults.sort((a,l)=>a.distance-l.distance)}raycastFromRay(e,t=null){const i=t??this.defaultRaycastOptions;i.ray=e;const n=this.raycast(i);return i===this.defaultRaycastOptions&&(i.ray=void 0),n}raycast(e=null){Vt&&performance.mark("raycast.start"),e||(e=this.defaultRaycastOptions);const t=e.screenPoint??this.context.input.mousePositionRC,i=e.raycaster??this.raycaster;if(i.near=e.minDistance??0,i.far=e.maxDistance??1/0,i.params=this.defaultThresholds,e.lineThreshold===void 0&&(e.lineThreshold=-1),i.params.Line={threshold:e.lineThreshold},e.ray)i.ray.copy(e.ray);else{const a=e.cam??this.context.mainCamera;if(!a)return Vt&&console.error("Can not perform raycast - no main camera found"),this.defaultRaycastOptions.results&&(this.defaultRaycastOptions.results.length=0),this.defaultRaycastOptions.results??[];const l=this.context.xrCamera;this.context.isInXR&&l instanceof c.ArrayCamera&&l.cameras.length>0?i.setFromCamera(t,l.cameras[0]):i.setFromCamera(t,a)}let n=e.targets;n||(n=this.targetBuffer,n.length=1,n[0]=this.context.scene);let o=e.results;this.defaultRaycastOptions.results&&(this.defaultRaycastOptions.results.length=0),o||(this.defaultRaycastOptions.results||(this.defaultRaycastOptions.results=new Array),o=this.defaultRaycastOptions.results),e.layerMask!==void 0?e.layerMask instanceof c.Layers?i.layers.mask=e.layerMask.mask:i.layers.mask=e.layerMask:(i.layers.enableAll(),i.layers.disable(2)),Vt&&console.time("raycast"),o.length=0,Ia._raycasting++,this.intersect(this.raycaster,n,o,e),o.sort((a,l)=>a.distance-l.distance);const r=e.ignore;return r!==void 0&&r.length>0&&(o=o.filter(a=>!r.includes(a.object))),Ia._raycasting--,Vt&&(console.timeEnd("raycast"),console.warn("#"+this.context.time.frame+", hits:",o?.length?[...o]:"nothing"),performance.mark("raycast.end"),performance.measure("raycast","raycast.start","raycast.end")),o}intersect(e,t,i,n){for(const o of t){if(!o||o.visible===!1||B.isGizmo(o)||n.lineThreshold!==void 0&&n.lineThreshold<0&&o instanceof c.Line)continue;let r=!0;const a=o,l=a.geometry;if(o.raycastAllowed===!1&&(r=!1),r&&n.testObject){const h=n.testObject?.(o);if(h===!1)continue;h==="continue in children"&&(r=!1)}else r&&(l&&G_(l)||(r=!1));if(r){const h=i.length,d=o.raycastPreference||"lod";let u=d!=="bounds";if(n.precise===!1&&(u=!1),l&&(u||=l.getAttribute("position")?.array?.length<64),a instanceof X.GroundedSkybox&&(u=!1),d==="lod"){const p=re.getRaycastMesh(o);p&&(a.geometry=p)}if(!u&&uP(a,e,i)||(n.useAcceleratedRaycast!==!1?Zd.runMeshBVHRaycast(e,a,i,this.context,n):e.intersectObject(a,!1,i)),a.geometry=l,Vt&&i.length!=h){const p=i[i.length-1];B.DrawWireSphere(p.point,.1,7798784,1,!1),B.DrawWireMesh({mesh:o,depthTest:!1,duration:.2,color:7798784})}}n.recursive!==!1&&this.intersect(e,o.children,i,n)}return i}tempBoundingBox=new c.Box3;intersectSphere(e,t,i,n,o,r,a,l){let h=e&&e.isMesh&&e.layers.test(n)&&!B.isGizmo(e);h&&=e.visible,h&&=!(e instanceof c.Line),h&&=!(e instanceof X.GroundedSkybox);const d=e,u=d.geometry;if(h&&l){const p=l(e);if(p===!1)return;p==="continue in children"&&(h=!1)}if(u&&G_(u)||(h=!1),h){if(a){const p=this.sphere;p.center.copy(t),p.radius=i;const m=o.length;if(Zd.runMeshBVHRaycast(this.sphere,d,o,this.context,{}),m!=o.length&&!r)return}else if(u.boundingBox||u.computeBoundingBox(),u.boundingBox){d.matrixWorldNeedsUpdate&&d.updateWorldMatrix(!1,!1);const p=this.tempBoundingBox.copy(u.boundingBox).applyMatrix4(d.matrixWorld),m=this.sphere;if(m.center.copy(t),m.radius=i,m.intersectsBox(p)){const y=Y(e),_=y.distanceTo(m.center),g=new mg(e,_,y);if(o.push(g),!r)return}}}if(e.children)for(const p of e.children){const m=o.length;if(this.intersectSphere(p,t,i,n,o,r,a,l),m!=o.length&&!r)return}}}function G_(s){return!(s.index&&s.index.array.length<3)}const jo=new c.Sphere,qh=new c.Plane,dP=new c.Matrix3;function uP(s,e,t){const i=s._computeIntersections;if(!i)return!1;let n=s["_computeIntersections:Needle"];return n||(n=s["_computeIntersections:Needle"]=function(o,r,a){const l=this,h=l.geometry.boundingSphere;if(h){if(l instanceof X.GroundedSkybox){qh.setFromNormalAndCoplanarPoint(F(0,1,0),F(0,-l.position.y,0)),qh.applyMatrix4(l.matrixWorld,dP);const u=o.ray.intersectPlane(qh,F());if(u){jo.copy(h),jo.applyMatrix4(l.matrixWorld);const m=F(u).sub(o.ray.origin).length(),y=jo.radius*.5;m<y&&r.push({distance:m,point:u,object:l,normal:qh.normal.clone()})}return}jo.copy(h),jo.applyMatrix4(l.matrixWorld);const d=o.ray.intersectSphere(jo,F());if(d){const u=F(d).sub(o.ray.origin),p=u.length();if(p>jo.radius){const m=u.clone().normalize();r.push({distance:p,point:d,object:l,normal:m})}}}}),s._computeIntersections=n,e.intersectObject(s,!1,t),s._computeIntersections=i,!0}var Zd;(s=>{let e=0;function t(b,w,R,O,M){if(!w.geometry||!w.geometry.hasAttribute("position"))return!1;const D=w.geometry;if(w?.isSkinnedMesh){const L=w,j=L.bvhNeedsUpdate;if(!L.staticGenerator)l(),r&&(L.staticGenerator=new r(w),L.staticGenerator.applyWorldTransforms=!1,L.staticGeometry=L.staticGenerator.generate(),D.boundsTree=a?.call(L.staticGeometry),L.staticGeometryLastUpdate=performance.now()+Math.random()*200,L.bvhNeedsUpdate=!0);else if(D.boundsTree&&(L.autoUpdateMeshBvhInterval!==void 0&&L.autoUpdateMeshBvhInterval>=0||j===!0)){const V=performance.now(),W=V-L.staticGeometryLastUpdate,k=L.autoUpdateMeshBvhInterval??100;(j||W>k)&&(Vt&&console.warn(`Physics: updating skinned mesh bvh for ${w.name} after ${W.toFixed(2)}ms`),L.bvhNeedsUpdate=!1,L.staticGeometryLastUpdate=V,L.staticGenerator?.generate(L.staticGeometry),D.boundsTree.refit())}}else if(!D.boundsTree){d||v();let L=!0;if((O.xr||D[y]===!1||D.getAttribute("position")?.isInterleavedBufferAttribute||D.index&&D.index?.isInterleavedBufferAttribute||e>10)&&(L=!1),L&&p){if(D[m]===void 0){let j=null;if(g.length>0){const V=g.shift();V&&!V.running&&(j=V)}if(!j&&_.length<3)try{hP&&console.warn("[GenerateMeshBVHWorker] Creating worker with import.meta.url:",typeof document>"u"?require("url").pathToFileURL(__filename).href:ya&&ya.tagName.toUpperCase()==="SCRIPT"&&ya.src||new URL("needle-engine.bundle-B5tG2TR8.umd.cjs",document.baseURI).href),j=new p,_.push(j)}catch(V){V instanceof DOMException&&V.name==="SecurityError"?(console.warn("Failed to create MeshBVH worker, falling back to main thread generation. This can happen when running from file://, if the browser does not support workers or if the browser is blocking workers for other reasons."),console.debug(V),e+=10):(console.error("Failed to create MeshBVH worker. Please see below for more details:"),console.log(V)),e++}if(j!=null&&!j.running){const V=w.name;Vt&&console.log("<<<< worker start",V,j),D[m]="queued",performance.mark("bvh.create.start");const W=D.clone();try{j.generate(W).then(k=>{D[m]="done",D.boundsTree=k}).catch(k=>{D[m]="failed - "+k?.message,D[y]=!1,Vt&&console.error("Failed to generate mesh bvh on worker",k)}).finally(()=>{Vt&&console.log(">>>>> worker done",V,{hasBoundsTre:D.boundsTree!=null}),g.push(j),W.dispose(),performance.mark("bvh.create.end"),performance.measure("bvh.create (worker)","bvh.create.start","bvh.create.end")})}catch(k){console.error("Failed to generate mesh bvh on worker",k)}}else Vt&&console.warn("No worker available")}}else(!u||!L)&&(l(),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(b instanceof c.Raycaster){const L=b,j=w.raycast;if(D.boundsTree)l(),n&&(w.acceleratedRaycast||(w.acceleratedRaycast=n.bind(w),Vt&&console.debug(`Physics: bind acceleratedRaycast fn to "${w.name}"`)),w.raycast=w.acceleratedRaycast);else if(Vt&&console.warn("No bounds tree found for mesh",w.name,{workerTask:D[m],hasAcceleratedRaycast:n!=null}),M.allowSlowRaycastFallback===!1&&(D.getAttribute("position")?.array?.length??0)>2e3)return Vt&&console.warn("Skipping raycast because no bounds tree is available and allowSlowRaycastFallback is false"),!1;const V=L.firstHitOnly;return L.firstHitOnly=!1,L.intersectObject(w,!1,R),L.firstHitOnly=V,w.raycast=j,!0}else if(b instanceof c.Sphere){const L=D.boundsTree;if(L){const j=b;if(h.copy(w.matrixWorld).invert(),j.applyMatrix4(h),L.intersectsSphere(j)){const W=Y(w),k=W.distanceTo(j.center),N=new mg(w,k,W);R.push(N)}}return!0}return!1}s.runMeshBVHRaycast=t;let i=!1,n=null,o=null,r=null,a=null;function l(){i||(i=!0,Promise.resolve().then(()=>require("./vendor-CntUvmJu.umd.cjs")).then(b=>b.index$1).then(b=>{n=b.acceleratedRaycast,o=b.MeshBVH,r=b.StaticGeometryGenerator,a=b.computeBoundsTree}).catch(b=>{(Vt||A())&&console.error("Failed to load BVH library...",b.message)}))}const h=new c.Matrix4;let d=!1,u=!1,p=null;const m=Symbol("Needle:MeshBVH-Worker"),y=Symbol("Needle:MeshBVH-CanUseWorker"),_=[],g=[];function v(){d=!0,u=!0,Promise.resolve().then(()=>kA).then(b=>{p=b.GenerateMeshBVHWorker}).catch(b=>{Vt||A()?console.warn("Failed to setup mesh bvh worker"):console.debug("Failed to setup mesh bvh worker",b)}).finally(()=>{u=!1})}})(Zd||(Zd={}));const H_=Symbol("gltf-loader-internal-usage-tracker"),fP=x("debugusers");class xa{get name(){return"NEEDLE_internal_usage_tracker"}static isLoading(e){return xa._loadingProcesses>0}static _loadingProcesses=0;parser;_getDependency;_loadingId;_loadedObjects=new Set;constructor(e){this.parser=e,this._getDependency=this.parser.getDependency,this._loadingId=Date.now().toString()}beforeRoot(){xa._loadingProcesses++;const e=this,t=this._getDependency;return this.parser.getDependency=function(i,n){const o=t.call(this,i,n);return o.then(r=>(r&&(e._loadedObjects.add(r),r[H_]=e._loadingId),r)),o},null}afterRoot(e){xa._loadingProcesses--,this.parser.getDependency=this._getDependency;for(const t of this._loadedObjects)delete t[H_],t instanceof c.Object3D&&(t.parent||t instanceof c.Mesh&&setTimeout(()=>{fP&&console.warn("> GLTF LOADER: Mesh not used in scene!",t),t.material=null,t.geometry=null},1e3));return null}}class N0{constructor(){window.addEventListener("unhandledrejection",e=>{if(e.defaultPrevented)return;const t=e?.reason?.path;if(t){const i=t[0];i&&i.tagName==="IMG"&&(console.warn(`Could not load image:
|
|
879
|
+
${o.hand?"hand":"ctrl"} ${o.inputSource.handedness}[${o.index}] con:${o.connected} tr:${o.isTracking} hts:${o.hasHitTestSource?"yes":"no"}`;$f=0,B.DrawLabel(e,n,void 0,1/60*20)}}onBeforeRender=()=>{this.context.mainCamera&&(this.updateFade(this.context.mainCamera),this.requestedCameraNearPlane!==null&&this.context.mainCamera instanceof c.PerspectiveCamera&&(this.context.mainCamera.near=this.requestedCameraNearPlane,this.requestedCameraNearPlane=null))};onAfterRender=()=>{if(this.onUpdateFade_PostRender(),exports.DeviceUtilities.isDesktop()||!this._renderOnceOnDevice){const e=this.context.renderer;if(e.xr.isPresenting&&this.context.mainCamera){this._renderOnceOnDevice=!0;const t=e.xr.enabled,i=e.getRenderTarget(),n=this.context.scene.background;e.xr.enabled=!1,e.setRenderTarget(null),this.isPassThrough&&(this.context.scene.background=null),this.context.composer?this.context.composer.render(this.context.time.deltaTime):e.render(this.context.scene,this.context.mainCamera),e.xr.enabled=t,e.setRenderTarget(i),this.context.scene.background=n}}};addScript(e){return this._xr_scripts.includes(e)?!1:(Ue&&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 i of this.controllers)this.invokeCallback_ControllerAdded(t,i)}}}_script_to_remove=[];removeScript(e,t=!0){Ue&&console.log("Remove XRScript",e);const i=this._xr_scripts.indexOf(e);i>=0&&this._xr_scripts.splice(i,1);const n=this._xr_update_scripts.indexOf(e);if(n>=0&&this._xr_update_scripts.splice(n,1),t){const o=this._inactive_scripts.indexOf(e);o>=0&&this._inactive_scripts.splice(o,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(){const e=this.context.xrCamera,t=this.context.mainCameraComponent?.cullingMask;if(e&&t!==void 0){for(const i of e.cameras)i.layers.mask=t;e.layers.mask=t}else if(e){for(const i of e.cameras)i.layers.enableAll();e.layers.enableAll()}}invokeControllerEvent(e,t,i){for(let n=t.length-1;n>=0;n--){const o=t[n];if(o)try{o({xr:this,controller:e,change:i})}catch(r){console.error(r)}}}_camera;_cameraRenderParent=new c.Object3D().rotateY(Math.PI);_previousCameraParent;_customforward=!0;originalCameraNearPlane;requestedCameraNearPlane=null;applyCustomForward(){if(this.context.mainCamera&&this._customforward){this._camera=this.context.mainCamera,this._camera.parent!==this._cameraRenderParent&&(this._previousCameraParent=this._camera.parent,this._previousCameraParent?.add(this._cameraRenderParent)),this._cameraRenderParent.name="XR Camera Render Parent",this._cameraRenderParent.add(this._camera);{let e=.02;const t=.001;if(this.rig){const i=je(this.rig.gameObject);e*=i.x}this._camera instanceof c.PerspectiveCamera&&Math.abs(this._camera.near-e)>t&&(this.isAR?this.originalCameraNearPlane=this._camera.near:this._camera.near=e,Ue&&console.debug(`Setting camera near plane to ${e} (was ${this.originalCameraNearPlane}) to account for XR rendering scale`))}}}revertCustomForward(){this._camera&&this._previousCameraParent&&this._previousCameraParent.add(this._camera),this._previousCameraParent=null,this._camera instanceof c.PerspectiveCamera&&this.originalCameraNearPlane!=null&&(this._camera.near=this.originalCameraNearPlane,this.originalCameraNearPlane=void 0)}_viewerPose;_transformOrientation=new c.Quaternion;_transformPosition=new c.Vector3;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)}}_transition;get transition(){return this._transition||(this._transition=new z_),this._transition}fadeTransition(){return this._transition||(this._transition=new z_),this._transition.fadeTransition()}updateFade(e){this._transition&&e instanceof c.PerspectiveCamera&&this._transition.update(e,this.context.time.deltaTime)}onUpdateFade_PostRender(){this._transition?.remove()}}const Gf=x("debugwebxr");class z0{static tryFindAvatarObjects(e,t,i){if(i.head&&i.leftHand&&i.rightHand)return;const n=e.name.toLocaleLowerCase();!i.head&&n.includes("head")&&(Gf&&console.log("FOUND AVATAR HEAD",e.name),i.head=new Z("",t,e)),n.includes("hand")&&(!i.leftHand&&n.includes("left")&&(Gf&&console.log("FOUND AVATAR LEFT HAND",e.name),i.leftHand=new Z("",t,e)),!i.rightHand&&n.includes("right")&&(Gf&&console.log("FOUND AVATAR RIGHT HAND",e.name),i.rightHand=new Z("",t,e)));for(let o=0;o<e.children.length;o++){if(i.head&&i.leftHand&&i.rightHand)return;const r=e.children[o];this.tryFindAvatarObjects(r,t,i)}}}class te extends c.Color{alpha=1;get isRGBAColor(){return!0}set a(e){this.alpha=e}get a(){return this.alpha}constructor(e,t,i,n){super(),typeof e=="number"&&typeof t=="number"&&typeof i=="number"?(this.set(e,t,i),this.alpha=typeof n=="number"?n:1):e!==void 0&&(this.set(e),this.alpha=1)}clone(){const e=super.clone();return e.alpha=this.alpha,e}copy(e){return this.r=e.r,this.g=e.g,this.b=e.b,"alpha"in e&&typeof e.alpha=="number"?this.alpha=e.alpha:typeof e.a=="number"&&(this.alpha=e.a),this}lerp(e,t){const i=e;return i.alpha!=null&&(this.alpha=I.lerp(this.alpha,i.alpha,t)),super.lerp(e,t)}lerpColors(e,t,i){const n=e,o=t;return n.alpha!=null&&o.alpha!=null&&(this.alpha=I.lerp(n.alpha,o.alpha,i)),super.lerpColors(e,t,i)}multiply(e){const t=e;return t.alpha!=null&&(this.alpha=this.alpha*t.alpha),super.multiply(e)}fromArray(e,t=0){return this.alpha=e[t+3],super.fromArray(e,t)}static fromColorRepresentation(e){if(typeof e=="string"){if(e.trim()==="transparent")return new te(0,0,0,0);if(e.startsWith("#")&&e.length===9){const t=parseInt(e.slice(1,9),16),i=t>>24&255,n=t>>16&255,o=t>>8&255,r=t>>0&255;return new te(i/255,n/255,o/255,r/255)}else if(e.startsWith("#")){const t=parseInt(e.slice(1),16),i=t>>16&255,n=t>>8&255,o=t>>0&255;return new te(i/255,n/255,o/255,1)}else if(e.startsWith("rgba")){const t=e.slice(5,-1).split(",").map(Number);return new te(t[0]/255,t[1]/255,t[2]/255,t[3])}else if(e.startsWith("rgb")){const t=e.slice(4,-1).split(",").map(Number);return new te(t[0]/255,t[1]/255,t[2]/255,1)}}else if(Array.isArray(e)){if(e.length===4)return new te(e[0],e[1],e[2],e[3]);if(e.length===3)return new te(e[0],e[1],e[2],1);console.error("Invalid color array length. Expected 3 or 4, got "+e.length)}return new te(e)}}const Mt=new c.Vector3,V_=new c.Vector3,$_=new c.Quaternion,lP=x("debuggizmos"),nn=8947848,Hf=32;class B{constructor(){}static enabled=!0;static isGizmo(e){return e[Jp]!==void 0}static setVisible(e){for(const t of Ei.timedObjectsBuffer)t.visible=e}static DrawLabel(e,t,i=.05,n=0,o,r,a){if(!B.enabled)return null;o||(o=nn);const l=q.active?.rigScale??1,h=Ei.getTextLabel(n,t,i*l,o,r);return a instanceof c.Object3D&&a.add(h),h.position.x=e.x,h.position.y=e.y,h.position.z=e.z,h}static DrawRay(e,t,i=nn,n=0,o=!0){if(!B.enabled)return;const r=Ei.getLine(n),a=r.geometry.getAttribute("position");a.setXYZ(0,e.x,e.y,e.z),Mt.set(t.x,t.y,t.z).multiplyScalar(999999999),a.setXYZ(1,e.x+Mt.x,e.y+Mt.y,e.z+Mt.z),a.needsUpdate=!0,r.material.depthTest=o,r.material.depthWrite=!1,r.material.fog=!1,rn(r.material,i)}static DrawDirection(e,t,i=nn,n=0,o=!0,r=1){if(!B.enabled)return;const a=Ei.getLine(n),l=a.geometry.getAttribute("position");l.setXYZ(0,e.x,e.y,e.z),t.w!==void 0?(Mt.set(0,0,-r),$_.set(t.x,t.y,t.z,t.w),Mt.applyQuaternion($_)):(Mt.set(t.x,t.y,t.z),Mt.multiplyScalar(r)),l.setXYZ(1,e.x+Mt.x,e.y+Mt.y,e.z+Mt.z),l.needsUpdate=!0,a.material.depthTest=o,a.material.depthWrite=!1,rn(a.material,i)}static DrawLine(e,t,i=nn,n=0,o=!0){if(!B.enabled)return;const r=Ei.getLine(n),a=r.geometry.getAttribute("position");a.setXYZ(0,e.x,e.y,e.z),a.setXYZ(1,t.x,t.y,t.z),a.needsUpdate=!0,r.material.depthTest=o,r.material.depthWrite=!1,r.material.fog=!1,rn(r.material,i)}static DrawCircle(e,t,i,n=nn,o=0,r=!0){if(!B.enabled)return;const a=Ei.getCircle(o);a.position.set(e.x,e.y,e.z),a.scale.set(i,i,i),a.quaternion.setFromUnitVectors(this._up,Mt.set(t.x,t.y,t.z).normalize()),a.material.depthTest=r,a.material.depthWrite=!1,a.material.fog=!1,rn(a.material,n)}static DrawWireSphere(e,t,i=nn,n=0,o=!0){if(!B.enabled)return;const r=Ei.getSphere(t,n,!0);hr(r,e.x,e.y,e.z),r.material.depthTest=o,r.material.depthWrite=!1,r.material.fog=!1,rn(r.material,i)}static DrawSphere(e,t,i=nn,n=0,o=!0){if(!B.enabled)return;const r=Ei.getSphere(t,n,!1);hr(r,e.x,e.y,e.z),r.material.depthTest=o,r.material.depthWrite=!1,rn(r.material,i)}static DrawWireBox(e,t,i=nn,n=0,o=!0,r=void 0){if(!B.enabled)return;const a=Ei.getBox(n);a.position.set(e.x,e.y,e.z),a.scale.set(t.x,t.y,t.z),r?a.quaternion.copy(r):a.quaternion.identity(),a.material.depthTest=o,a.material.wireframe=!0,a.material.depthWrite=!1,a.material.fog=!1,rn(a.material,i)}static DrawWireBox3(e,t=nn,i=0,n=!0){if(!B.enabled)return;const o=Ei.getBox(i);o.position.copy(e.getCenter(Mt)),o.scale.copy(e.getSize(Mt)),o.material.depthTest=n,o.material.wireframe=!0,o.material.depthWrite=!1,o.material.fog=!1,rn(o.material,t)}static _up=new c.Vector3(0,1,0);static DrawArrow(e,t,i=nn,n=0,o=!0,r=!1){if(!B.enabled)return;const a=Ei.getArrowHead(n);a.position.set(t.x,t.y,t.z),a.quaternion.setFromUnitVectors(this._up.set(0,1,0),Mt.set(t.x,t.y,t.z).sub(V_.set(e.x,e.y,e.z)).normalize());const h=Mt.set(t.x,t.y,t.z).sub(V_.set(e.x,e.y,e.z)).length()*.1;a.scale.set(h,h,h),a.material.depthTest=o,a.material.wireframe=r,rn(a.material,i),this.DrawLine(e,t,i,n,o)}static DrawWireMesh(e){const t=Ei.getMesh(e.duration??0);"mesh"in e?(t.geometry=e.mesh.geometry,t.matrixWorld.copy(e.mesh.matrixWorld)):(t.geometry=e.geometry,t.matrixWorld.copy(e.matrix)),t.matrixAutoUpdate=!1,t.matrixWorldAutoUpdate=!1,t.material.depthTest=e.depthTest??!0,t.material.wireframe=!0,rn(t.material,e.color??nn)}}const cP=new c.BoxGeometry(1,1,1);function pg(s=null){const e=new c.Color(s??14540253),t=new c.EdgesGeometry(cP);return new c.LineSegments(t,new c.LineBasicMaterial({color:e}))}function rn(s,e){if(Array.isArray(s)){for(const i of s)rn(i,e);return}const t=e instanceof te?e.a:1;s.color.set(e),s.opacity=t,s.transparent=t<1}const Jp=Symbol("GizmoCache");class Ei{static familyName="needle-gizmos";static ensureFont(){let e=ie.__webpack_exports__default.FontLibrary.getFontFamily(this.familyName);e||(e=ie.__webpack_exports__default.FontLibrary.addFontFamily(this.familyName),e.addVariant("normal","normal","https://cdn.needle.tools/static/fonts/msdf/arial/arial-msdf.json","https://cdn.needle.tools/static/fonts/msdf/arial/arial.png")?.addEventListener("ready",()=>{ie.__webpack_exports__default.update()}))}static getTextLabel(e,t,i,n,o){this.ensureFont();let r=this.textLabelCache.pop(),a=1;o&&typeof o=="string"&&o?.length>=8&&o.startsWith("#")?(a=parseInt(o.substring(7),16)/255,o=o.substring(0,7),lP&&console.log(o,a)):typeof o=="object"&&o.a!==void 0&&(a=o.a);const l={boxSizing:"border-box",fontFamily:this.familyName,width:"auto",fontSize:i,color:n,lineHeight:1,backgroundColor:o??void 0,backgroundOpacity:a,textContent:t,borderRadius:.5*i,padding:.8*i,whiteSpace:"pre",offset:.05*i};if(r)r.set(l);else{r=new ie.__webpack_exports__Text(l);const h=this,d=r;d.setText=function(u){this.set({textContent:u}),h.tmuiNeedsUpdate=!0}}return this.tmuiNeedsUpdate=!0,this.registerTimedObject(U.Current,r,e,this.textLabelCache),r}static getBox(e){let t=this.boxesCache.pop();if(!t){const i=new c.BoxGeometry(1,1,1);t=new c.Mesh(i)}return this.registerTimedObject(U.Current,t,e,this.boxesCache),t}static getLine(e){let t=this.linesCache.pop();if(!t){t=new c.Line;let i=t.geometry.getAttribute("position");i||(i=new c.BufferAttribute(new Float32Array(6),3),t.geometry.setAttribute("position",i))}return t.frustumCulled=!1,this.registerTimedObject(U.Current,t,e,this.linesCache),t}static getCircle(e){let t=this.circlesCache.pop();if(!t){t=new c.Line;let i=t.geometry.getAttribute("position");if(!i){i=new c.BufferAttribute(new Float32Array(Hf*3),3),t.geometry.setAttribute("position",i);const n=F(0,1,0),o=F(0,0,1),r=F(o);r.cross(n).normalize();const a=F(r),l=Math.PI*2/(Hf-1);for(let h=0;h<Hf+1;h++){const d=l*h;n.copy(a).multiplyScalar(Math.cos(d)*1),r.copy(o).multiplyScalar(Math.sin(d)*1);const u=n.add(r);i.setXYZ(h,u.x,u.y,u.z)}}}return t.frustumCulled=!1,this.registerTimedObject(U.Current,t,e,this.circlesCache),t}static getSphere(e,t,i){let n=this.spheresCache.pop();return n||(n=new c.Mesh(new c.SphereGeometry(1,8,8))),n.scale.set(e,e,e),n.material.wireframe=i,this.registerTimedObject(U.Current,n,t,this.spheresCache),n}static getArrowHead(e){let t=this.arrowHeadsCache.pop();return t||(t=new c.Mesh(new c.CylinderGeometry(0,.5,1,8))),this.registerTimedObject(U.Current,t,e,this.arrowHeadsCache),t}static getMesh(e){let t=this.mesh.pop();return t||(t=new c.Mesh,t.material=new c.MeshBasicMaterial),this.registerTimedObject(U.Current,t,e,this.mesh),t}static linesCache=[];static circlesCache=[];static spheresCache=[];static boxesCache=[];static arrowHeadsCache=[];static mesh=[];static textLabelCache=[];static registerTimedObject(e,t,i,n){if(!e){console.error("No Needle Engine context available. Did you call a Gizmos function in global scope?");return}const o=this.contextBeforeRenderCallbacks.get(e),r=this.contextPostRenderCallbacks.get(e);if(o){if(e.pre_render_callbacks[e.pre_render_callbacks.length-1]!==o){const a=e.pre_render_callbacks.indexOf(o);a>=0&&e.pre_render_callbacks.splice(a,1),e.pre_render_callbacks.push(o)}}else{const a=()=>{this.onBeforeRender(e,this.timedObjectsBuffer)};this.contextBeforeRenderCallbacks.set(e,a),e.pre_render_callbacks.push(a)}if(r){if(e.post_render_callbacks[e.post_render_callbacks.length-1]!==r){const a=e.post_render_callbacks.indexOf(r);a>=0&&e.post_render_callbacks.splice(a,1),e.post_render_callbacks.push(r)}}else{const a=()=>{this.onPostRender(e,this.timedObjectsBuffer,this.timesBuffer)};this.contextPostRenderCallbacks.set(e,a),e.post_render_callbacks.push(a)}t.traverse(a=>{a.layers.disableAll(),a.layers.enable(2)}),t.renderOrder=999999,t[Jp]=n,t.castShadow=!1,t.receiveShadow=!1,t.isGizmo=!0,this.timedObjectsBuffer.push(t),this.timesBuffer.push(U.Current.time.realtimeSinceStartup+i),e.scene.add(t)}static timedObjectsBuffer=new Array;static timesBuffer=new Array;static contextPostRenderCallbacks=new Map;static contextBeforeRenderCallbacks=new Map;static tmuiNeedsUpdate=!1;static onBeforeRender(e,t){this.tmuiNeedsUpdate&&(this.tmuiNeedsUpdate=!1,ie.__webpack_exports__default.update());for(let i=0;i<t.length;i++){const n=t[i];if(e.mainCamera&&n instanceof ie.__webpack_exports__default.MeshUIBaseElement){if(dr(n))continue;const o=e.isInVR,r=!1,a=!o;Nc(n,e.mainCamera,r,a)}}}static onPostRender(e,t,i){const n=e.time.realtimeSinceStartup;for(let o=t.length-1;o>=0;o--){const r=t[o];n>=i[o]-1e-6&&(t.splice(o,1),i.splice(o,1),r.removeFromParent(),dr(r)!=!0&&r[Jp].push(r))}}}const Vt=x("debugphysics"),hP=x("debugworker"),W_=new c.Layers;class bo{static AllLayers=4294967295;ray;cam;screenPoint;raycaster;results;targets;recursive=!0;minDistance;maxDistance;lineThreshold;layerMask;ignore;testObject;useAcceleratedRaycast;allowSlowRaycastFallback=!0;screenPointFromOffset(e,t){this.screenPoint===void 0&&(this.screenPoint=new c.Vector2),this.screenPoint.x=e/window.innerWidth*2-1,this.screenPoint.y=-(t/window.innerHeight)*2+1}setLayer(e){W_.set(e),this.layerMask=W_}setMask(e){this.layerMask||(this.layerMask=new c.Layers);const t=this.layerMask;t?t.mask=e:this.layerMask=e}}class mg{distance;point;object;constructor(e,t,i){this.object=e,this.distance=t,this.point=i}}class Ia{static _raycasting=0;static get raycasting(){return this._raycasting>0}raycastPhysicsFast(e,t=void 0,i=1/0,n=!0){return this.context.physics.engine?.raycast(e,t,{maxDistance:i,solid:n})??null}raycastPhysicsFastAndGetNormal(e,t=void 0,i=1/0,n=!0){return this.context.physics.engine?.raycastAndGetNormal(e,t,{maxDistance:i,solid:n})??null}sphereOverlapPhysics(e,t){return this.context.physics.engine?.sphereOverlap(e,t)??null}context;engine;constructor(e){this.context=e}raycaster=new c.Raycaster;defaultRaycastOptions=new bo;targetBuffer=new Array(1);defaultThresholds={Mesh:{},Line:{threshold:-1},LOD:{},Points:{threshold:0},Sprite:{}};sphereResults=new Array;sphereMask=new c.Layers;sphere=new c.Sphere;sphereOverlap(e,t,i=!0,n=!1,o=null){if(this.sphereResults.length=0,!this.context.scene)return this.sphereResults;const r=this.sphereMask;r.enableAll(),r.disable(2);for(const a of this.context.scene.children)this.intersectSphere(a,e,t,r,this.sphereResults,i,n,o);return this.sphereResults.sort((a,l)=>a.distance-l.distance)}raycastFromRay(e,t=null){const i=t??this.defaultRaycastOptions;i.ray=e;const n=this.raycast(i);return i===this.defaultRaycastOptions&&(i.ray=void 0),n}raycast(e=null){Vt&&performance.mark("raycast.start"),e||(e=this.defaultRaycastOptions);const t=e.screenPoint??this.context.input.mousePositionRC,i=e.raycaster??this.raycaster;if(i.near=e.minDistance??0,i.far=e.maxDistance??1/0,i.params=this.defaultThresholds,e.lineThreshold===void 0&&(e.lineThreshold=-1),i.params.Line={threshold:e.lineThreshold},e.ray)i.ray.copy(e.ray);else{const a=e.cam??this.context.mainCamera;if(!a)return Vt&&console.error("Can not perform raycast - no main camera found"),this.defaultRaycastOptions.results&&(this.defaultRaycastOptions.results.length=0),this.defaultRaycastOptions.results??[];const l=this.context.xrCamera;this.context.isInXR&&l instanceof c.ArrayCamera&&l.cameras.length>0?i.setFromCamera(t,l.cameras[0]):i.setFromCamera(t,a)}let n=e.targets;n||(n=this.targetBuffer,n.length=1,n[0]=this.context.scene);let o=e.results;this.defaultRaycastOptions.results&&(this.defaultRaycastOptions.results.length=0),o||(this.defaultRaycastOptions.results||(this.defaultRaycastOptions.results=new Array),o=this.defaultRaycastOptions.results),e.layerMask!==void 0?e.layerMask instanceof c.Layers?i.layers.mask=e.layerMask.mask:i.layers.mask=e.layerMask:(i.layers.enableAll(),i.layers.disable(2)),Vt&&console.time("raycast"),o.length=0,Ia._raycasting++,this.intersect(this.raycaster,n,o,e),o.sort((a,l)=>a.distance-l.distance);const r=e.ignore;return r!==void 0&&r.length>0&&(o=o.filter(a=>!r.includes(a.object))),Ia._raycasting--,Vt&&(console.timeEnd("raycast"),console.warn("#"+this.context.time.frame+", hits:",o?.length?[...o]:"nothing"),performance.mark("raycast.end"),performance.measure("raycast","raycast.start","raycast.end")),o}intersect(e,t,i,n){for(const o of t){if(!o||o.visible===!1||B.isGizmo(o)||n.lineThreshold!==void 0&&n.lineThreshold<0&&o instanceof c.Line)continue;let r=!0;const a=o,l=a.geometry;if(o.raycastAllowed===!1&&(r=!1),r&&n.testObject){const h=n.testObject?.(o);if(h===!1)continue;h==="continue in children"&&(r=!1)}else r&&(l&&G_(l)||(r=!1));if(r){const h=i.length,d=o.raycastPreference||"lod";let u=d!=="bounds";if(n.precise===!1&&(u=!1),l&&(u||=l.getAttribute("position")?.array?.length<64),a instanceof X.GroundedSkybox&&(u=!1),d==="lod"){const p=re.getRaycastMesh(o);p&&(a.geometry=p)}if(!u&&uP(a,e,i)||(n.useAcceleratedRaycast!==!1?Zd.runMeshBVHRaycast(e,a,i,this.context,n):e.intersectObject(a,!1,i)),a.geometry=l,Vt&&i.length!=h){const p=i[i.length-1];B.DrawWireSphere(p.point,.1,7798784,1,!1),B.DrawWireMesh({mesh:o,depthTest:!1,duration:.2,color:7798784})}}n.recursive!==!1&&this.intersect(e,o.children,i,n)}return i}tempBoundingBox=new c.Box3;intersectSphere(e,t,i,n,o,r,a,l){let h=e&&e.isMesh&&e.layers.test(n)&&!B.isGizmo(e);h&&=e.visible,h&&=!(e instanceof c.Line),h&&=!(e instanceof X.GroundedSkybox);const d=e,u=d.geometry;if(h&&l){const p=l(e);if(p===!1)return;p==="continue in children"&&(h=!1)}if(u&&G_(u)||(h=!1),h){if(a){const p=this.sphere;p.center.copy(t),p.radius=i;const m=o.length;if(Zd.runMeshBVHRaycast(this.sphere,d,o,this.context,{}),m!=o.length&&!r)return}else if(u.boundingBox||u.computeBoundingBox(),u.boundingBox){d.matrixWorldNeedsUpdate&&d.updateWorldMatrix(!1,!1);const p=this.tempBoundingBox.copy(u.boundingBox).applyMatrix4(d.matrixWorld),m=this.sphere;if(m.center.copy(t),m.radius=i,m.intersectsBox(p)){const y=Y(e),_=y.distanceTo(m.center),g=new mg(e,_,y);if(o.push(g),!r)return}}}if(e.children)for(const p of e.children){const m=o.length;if(this.intersectSphere(p,t,i,n,o,r,a,l),m!=o.length&&!r)return}}}function G_(s){return!(s.index&&s.index.array.length<3)}const jo=new c.Sphere,qh=new c.Plane,dP=new c.Matrix3;function uP(s,e,t){const i=s._computeIntersections;if(!i)return!1;let n=s["_computeIntersections:Needle"];return n||(n=s["_computeIntersections:Needle"]=function(o,r,a){const l=this,h=l.geometry.boundingSphere;if(h){if(l instanceof X.GroundedSkybox){qh.setFromNormalAndCoplanarPoint(F(0,1,0),F(0,-l.position.y,0)),qh.applyMatrix4(l.matrixWorld,dP);const u=o.ray.intersectPlane(qh,F());if(u){jo.copy(h),jo.applyMatrix4(l.matrixWorld);const m=F(u).sub(o.ray.origin).length(),y=jo.radius*.5;m<y&&r.push({distance:m,point:u,object:l,normal:qh.normal.clone()})}return}jo.copy(h),jo.applyMatrix4(l.matrixWorld);const d=o.ray.intersectSphere(jo,F());if(d){const u=F(d).sub(o.ray.origin),p=u.length();if(p>jo.radius){const m=u.clone().normalize();r.push({distance:p,point:d,object:l,normal:m})}}}}),s._computeIntersections=n,e.intersectObject(s,!1,t),s._computeIntersections=i,!0}var Zd;(s=>{let e=0;function t(b,w,R,O,M){if(!w.geometry||!w.geometry.hasAttribute("position"))return!1;const D=w.geometry;if(w?.isSkinnedMesh){const L=w,j=L.bvhNeedsUpdate;if(!L.staticGenerator)l(),r&&(L.staticGenerator=new r(w),L.staticGenerator.applyWorldTransforms=!1,L.staticGeometry=L.staticGenerator.generate(),D.boundsTree=a?.call(L.staticGeometry),L.staticGeometryLastUpdate=performance.now()+Math.random()*200,L.bvhNeedsUpdate=!0);else if(D.boundsTree&&(L.autoUpdateMeshBvhInterval!==void 0&&L.autoUpdateMeshBvhInterval>=0||j===!0)){const V=performance.now(),W=V-L.staticGeometryLastUpdate,k=L.autoUpdateMeshBvhInterval??100;(j||W>k)&&(Vt&&console.warn(`Physics: updating skinned mesh bvh for ${w.name} after ${W.toFixed(2)}ms`),L.bvhNeedsUpdate=!1,L.staticGeometryLastUpdate=V,L.staticGenerator?.generate(L.staticGeometry),D.boundsTree.refit())}}else if(!D.boundsTree){d||v();let L=!0;if((O.xr||D[y]===!1||D.getAttribute("position")?.isInterleavedBufferAttribute||D.index&&D.index?.isInterleavedBufferAttribute||e>10)&&(L=!1),L&&p){if(D[m]===void 0){let j=null;if(g.length>0){const V=g.shift();V&&!V.running&&(j=V)}if(!j&&_.length<3)try{hP&&console.warn("[GenerateMeshBVHWorker] Creating worker with import.meta.url:",typeof document>"u"?require("url").pathToFileURL(__filename).href:ya&&ya.tagName.toUpperCase()==="SCRIPT"&&ya.src||new URL("needle-engine.bundle-CzOPcOui.umd.cjs",document.baseURI).href),j=new p,_.push(j)}catch(V){V instanceof DOMException&&V.name==="SecurityError"?(console.warn("Failed to create MeshBVH worker, falling back to main thread generation. This can happen when running from file://, if the browser does not support workers or if the browser is blocking workers for other reasons."),console.debug(V),e+=10):(console.error("Failed to create MeshBVH worker. Please see below for more details:"),console.log(V)),e++}if(j!=null&&!j.running){const V=w.name;Vt&&console.log("<<<< worker start",V,j),D[m]="queued",performance.mark("bvh.create.start");const W=D.clone();try{j.generate(W).then(k=>{D[m]="done",D.boundsTree=k}).catch(k=>{D[m]="failed - "+k?.message,D[y]=!1,Vt&&console.error("Failed to generate mesh bvh on worker",k)}).finally(()=>{Vt&&console.log(">>>>> worker done",V,{hasBoundsTre:D.boundsTree!=null}),g.push(j),W.dispose(),performance.mark("bvh.create.end"),performance.measure("bvh.create (worker)","bvh.create.start","bvh.create.end")})}catch(k){console.error("Failed to generate mesh bvh on worker",k)}}else Vt&&console.warn("No worker available")}}else(!u||!L)&&(l(),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(b instanceof c.Raycaster){const L=b,j=w.raycast;if(D.boundsTree)l(),n&&(w.acceleratedRaycast||(w.acceleratedRaycast=n.bind(w),Vt&&console.debug(`Physics: bind acceleratedRaycast fn to "${w.name}"`)),w.raycast=w.acceleratedRaycast);else if(Vt&&console.warn("No bounds tree found for mesh",w.name,{workerTask:D[m],hasAcceleratedRaycast:n!=null}),M.allowSlowRaycastFallback===!1&&(D.getAttribute("position")?.array?.length??0)>2e3)return Vt&&console.warn("Skipping raycast because no bounds tree is available and allowSlowRaycastFallback is false"),!1;const V=L.firstHitOnly;return L.firstHitOnly=!1,L.intersectObject(w,!1,R),L.firstHitOnly=V,w.raycast=j,!0}else if(b instanceof c.Sphere){const L=D.boundsTree;if(L){const j=b;if(h.copy(w.matrixWorld).invert(),j.applyMatrix4(h),L.intersectsSphere(j)){const W=Y(w),k=W.distanceTo(j.center),N=new mg(w,k,W);R.push(N)}}return!0}return!1}s.runMeshBVHRaycast=t;let i=!1,n=null,o=null,r=null,a=null;function l(){i||(i=!0,Promise.resolve().then(()=>require("./vendor-CntUvmJu.umd.cjs")).then(b=>b.index$1).then(b=>{n=b.acceleratedRaycast,o=b.MeshBVH,r=b.StaticGeometryGenerator,a=b.computeBoundsTree}).catch(b=>{(Vt||A())&&console.error("Failed to load BVH library...",b.message)}))}const h=new c.Matrix4;let d=!1,u=!1,p=null;const m=Symbol("Needle:MeshBVH-Worker"),y=Symbol("Needle:MeshBVH-CanUseWorker"),_=[],g=[];function v(){d=!0,u=!0,Promise.resolve().then(()=>kA).then(b=>{p=b.GenerateMeshBVHWorker}).catch(b=>{Vt||A()?console.warn("Failed to setup mesh bvh worker"):console.debug("Failed to setup mesh bvh worker",b)}).finally(()=>{u=!1})}})(Zd||(Zd={}));const H_=Symbol("gltf-loader-internal-usage-tracker"),fP=x("debugusers");class xa{get name(){return"NEEDLE_internal_usage_tracker"}static isLoading(e){return xa._loadingProcesses>0}static _loadingProcesses=0;parser;_getDependency;_loadingId;_loadedObjects=new Set;constructor(e){this.parser=e,this._getDependency=this.parser.getDependency,this._loadingId=Date.now().toString()}beforeRoot(){xa._loadingProcesses++;const e=this,t=this._getDependency;return this.parser.getDependency=function(i,n){const o=t.call(this,i,n);return o.then(r=>(r&&(e._loadedObjects.add(r),r[H_]=e._loadingId),r)),o},null}afterRoot(e){xa._loadingProcesses--,this.parser.getDependency=this._getDependency;for(const t of this._loadedObjects)delete t[H_],t instanceof c.Object3D&&(t.parent||t instanceof c.Mesh&&setTimeout(()=>{fP&&console.warn("> GLTF LOADER: Mesh not used in scene!",t),t.material=null,t.geometry=null},1e3));return null}}class N0{constructor(){window.addEventListener("unhandledrejection",e=>{if(e.defaultPrevented)return;const t=e?.reason?.path;if(t){const i=t[0];i&&i.tagName==="IMG"&&(console.warn(`Could not load image:
|
|
880
880
|
`+i.src),e.preventDefault())}})}}const Pu=x("trackresources");function V0(){return Pu==="dispose"}let br=!0;Pu===0&&(br=!1);function pP(s){br=s}function $0(){return br}const W0=Symbol("disposable");function G0(s,e){s&&(s[W0]=e,nr&&console.warn("Set disposable",e,s))}const H0=Symbol("disposed");function mP(s){return s[H0]===!0}function we(s){if(s){if(s[W0]===!1){nr&&console.warn("Object is marked as not disposable",s);return}if(typeof s=="object"&&(s[H0]=!0),s instanceof c.Scene)we(s.environment),we(s.background),we(s.customDepthMaterial),we(s.customDistanceMaterial);else if(s instanceof c.SkinnedMesh)we(s.geometry),we(s.material),we(s.skeleton),we(s.bindMatrix),we(s.bindMatrixInverse),we(s.customDepthMaterial),we(s.customDistanceMaterial),s.visible=!1;else if(s instanceof c.Mesh)we(s.geometry),we(s.material),we(s.customDepthMaterial),we(s.customDistanceMaterial),s.visible=!1;else if(s instanceof c.Object3D)s.visible=!1;else if(s instanceof c.BufferGeometry){qr(s);for(const e of Object.keys(s.attributes)){const t=s.attributes[e];we(t)}}else if(s instanceof c.BufferAttribute||s instanceof c.InterleavedBufferAttribute)nr&&console.warn("BufferAttribute dispose not supported",s.count);else if(s instanceof Array)for(const e of s)e instanceof c.Material&&we(e);else if(s instanceof c.Material){qr(s);for(const t of Object.keys(s)){const i=s[t];i instanceof c.Texture&&we(i)}const e=s.uniforms;if(e)for(const t of Object.keys(e)){const i=e[t];i instanceof c.Texture?we(i):i instanceof c.Uniform$1&&we(i.value)}}else s instanceof c.Texture?(qr(s),qr(s.source),s.source?.data instanceof ImageBitmap&&qr(s.source.data)):s instanceof c.Skeleton?(qr(s.boneTexture),s.boneTexture=null):s instanceof c.Bone||!(s instanceof c.Object3D)&&nr&&console.warn("Unknown object type",s)}}function qr(s){s&&((nr||V0()||Pu)&&console.warn("🧨 FREE",s),s instanceof ImageBitmap||"dispose"in s&&typeof s.dispose=="function"&&s.dispose())}function gP(s){}const yP=new Set;function gg(s,e,t=null,i){if(i||(i=yP,i.clear()),!s)return i;const n=s[Sc];if(n)for(const o of n)i.has(o)||t?.call(null,o)!==!1&&(i.add(o),e&&gg(o,!0,t,i));return i}function _P(s){return s[zl]}const nr=x("debugresourceusers")||x("debugmemory"),Sc=Symbol("needle-resource-users"),zl=Symbol("needle-resource-users-count");function Bt(s,e){yu(s,e,function(t,i){br&&!Ia.raycasting&&(Jd(Sc,this,t,!1),Jd(Sc,this,i,!0))})}br&&(Bt(c.Mesh.prototype,"material"),Bt(c.Mesh.prototype,"geometry"),Bt(c.Material.prototype,"map"),Bt(c.Material.prototype,"bumpMap"),Bt(c.Material.prototype,"alphaMap"),Bt(c.Material.prototype,"normalMap"),Bt(c.Material.prototype,"displacementMap"),Bt(c.Material.prototype,"roughnessMap"),Bt(c.Material.prototype,"metalnessMap"),Bt(c.Material.prototype,"emissiveMap"),Bt(c.Material.prototype,"specularMap"),Bt(c.Material.prototype,"envMap"),Bt(c.Material.prototype,"lightMap"),Bt(c.Material.prototype,"aoMap"),Bt(c.Material.prototype,"gradientMap"));function bP(s){if(br===!1)return;const e=s[Sc];if(e)for(const t of e)Jd(Sc,t,s,!1)}br&&yu(c.Material.prototype,"dispose",function(){bP(this)});let em=0;function Jd(s,e,t,i){if(em>0)return;if(Array.isArray(t)){for(const o of t)Jd(s,e,o,i);return}if(!t)return;let n=t[s];if(n||(n=new Set),i){if(e&&!n.has(e)){n.add(e);let o=t[zl]||0;o+=1,t[zl]=o,nr&&console.warn(`🟢 Added user of "${t.type}"`,e,t,o,"users:",n)}}else if(e&&n.has(e)){n.delete(e);let o=t[zl]||0;o>0&&(o-=1,t[zl]=o),nr&&console.warn(`🔴 Removed user of "${t.type}"`,e,t,o,"users:",n),o<=0&&(xa.isLoading(t)||(Pu&&console.warn(`🔴 Removed all user of "${t.type}"`,t),V0()&&we(t)))}t[s]=n}try{yu(c.WebGLRenderer.prototype,"render",function(){em++},function(){em--})}catch(s){console.warn("Could not wrap WebGLRenderer.render",s)}const Cc=Symbol("NEEDLE_NEED_UPDATE_INSTANCE"),q0=Symbol("isUsingInstancing"),X0=Symbol("instancingRenderer"),Nl=Symbol("instancingAutoUpdateBounds");class Ni{static isUsingInstancing(e){return e[q0]===!0}static getRenderer(e){return e[X0]||null}setAutoUpdateBounds(e,t){const i=Ni.getRenderer(e);i&&(i[Nl]=t)}static markDirty(e,t=!0){if(e&&(this.isUsingInstancing(e)&&(e[Cc]=!0,e.matrixWorldNeedsUpdate=!0),t))for(const i of e.children)Ni.markDirty(i,!0)}}const Q0=new Map;function Y0(s,e){if(!s)return;if(!e){console.warn("No prototype found",s,s.prototype,s.constructor);return}const t=Q0.get(e);t&&t.apply(s)}function yg(s){const e=vP(s.prototype);Q0.set(s,e)}function vP(s){return new wP(s)}class wP{$symbol;extensions;descriptors;constructor(e){this.$symbol=Symbol("prototype-extension"),this.extensions=Object.keys(e),this.descriptors=new Array;for(let t=0;t<this.extensions.length;t++){const i=this.extensions[t],n=Object.getOwnPropertyDescriptor(e,i);n&&this.descriptors.push(n)}}apply(e){if(!e[this.$symbol]){e[this.$symbol]=!0;for(let t=0;t<this.extensions.length;t++){const i=this.extensions[t],n=this.descriptors[t];n&&Object.defineProperty(e,i,n)}}}}function Ou(s){s&&s.isObject3D===!0&&Y0(s,c.Object3D)}let q_=!1;function xP(){if(q_)return;if(q_=!0,Xm.experimentalSmartHierarchyUpdate){const i=c.Object3D.prototype.add;c.Object3D.prototype.add=function(...r){return Xf(),i.apply(this,r)};const n=c.Object3D.prototype.attach;c.Object3D.prototype.attach=function(...r){return Xf(),n.apply(this,r)};const o=c.Object3D.prototype.remove;c.Object3D.prototype.remove=function(...r){return Xf(),o.apply(this,r)}}c.Object3D.prototype.SetActive=function(i){this.visible=i},c.Object3D.prototype.setActive=function(i){this.visible=i},c.Object3D.prototype.destroy=function(){bi(this)},c.Object3D.prototype.addComponent=function(i,n){return hn(this,i,n)},c.Object3D.prototype.addNewComponent=function(i,n){return hn(this,i,n)},c.Object3D.prototype.removeComponent=function(i){return vg(this,i)},c.Object3D.prototype.getOrAddComponent=function(i,n){return Xc(this,i,n)},c.Object3D.prototype.getComponent=function(i){return vr(this,i)},c.Object3D.prototype.getComponents=function(i,n){return Qc(this,i,n)},c.Object3D.prototype.getComponentInChildren=function(i,n=!1){return Yc(this,i,n)},c.Object3D.prototype.getComponentsInChildren=function(i,n){return Wa(this,i,n)},c.Object3D.prototype.getComponentInParent=function(i,n=!1){return Pc(this,i,n)},c.Object3D.prototype.getComponentsInParent=function(i,n){return Eu(this,i,n)},Object.getOwnPropertyDescriptor(c.Object3D.prototype,"activeSelf")||Object.defineProperty(c.Object3D.prototype,"activeSelf",{get:function(){return $a(this)},set:function(i){sc(this,i)}}),Object.getOwnPropertyDescriptor(c.Object3D.prototype,"raycastAllowed")||Object.defineProperty(c.Object3D.prototype,"raycastAllowed",{get:function(){return this.userData&&this.userData.raycastAllowed!==!1},set:function(i){const n=this;n.userData||(n.userData={}),n.userData.raycastAllowed=i}}),Object.getOwnPropertyDescriptor(c.Object3D.prototype,"worldPosition")||Object.defineProperty(c.Object3D.prototype,"worldPosition",{get:function(){return this instanceof X.TransformControlsGizmo?Y(this.object):Y(this)},set:function(i){at(this,i)}}),Object.getOwnPropertyDescriptor(c.Object3D.prototype,"worldQuaternion")||Object.defineProperty(c.Object3D.prototype,"worldQuaternion",{get:function(){return this instanceof X.TransformControlsGizmo?pe(this.object):pe(this)},set:function(i){dn(this,i)}}),Object.getOwnPropertyDescriptor(c.Object3D.prototype,"worldRotation")||Object.defineProperty(c.Object3D.prototype,"worldRotation",{get:function(){return mu(this)},set:function(i){Ev(this,i)}}),Object.getOwnPropertyDescriptor(c.Object3D.prototype,"worldScale")||Object.defineProperty(c.Object3D.prototype,"worldScale",{get:function(){return je(this)},set:function(i){ka(this,i)}});const s=new c.Matrix4,e=new c.Vector3(0,0,0),t=new c.Vector3(0,1,0);Object.getOwnPropertyDescriptor(c.Object3D.prototype,"worldForward")||Object.defineProperty(c.Object3D.prototype,"worldForward",{get:function(){return F().set(0,0,1).applyQuaternion(pe(this))},set:function(i){const n=ei().setFromRotationMatrix(s.lookAt(e.set(0,0,0),i,t.set(0,1,0)));this.worldQuaternion=n}}),Object.getOwnPropertyDescriptor(c.Object3D.prototype,"worldRight")||Object.defineProperty(c.Object3D.prototype,"worldRight",{get:function(){return F().set(1,0,0).applyQuaternion(pe(this))}}),Object.getOwnPropertyDescriptor(c.Object3D.prototype,"worldUp")||Object.defineProperty(c.Object3D.prototype,"worldUp",{get:function(){return F().set(0,1,0).applyQuaternion(pe(this))}}),Object.getOwnPropertyDescriptor(c.Object3D.prototype,"contains")||Object.defineProperty(c.Object3D.prototype,"contains",{value:function(i){if(!i)return!1;if(this===i)return!0;for(const n of this.children)if(n.contains(i))return!0;return!1}}),yg(c.Object3D)}const wd=x("debuggetcomponent"),sr=x("debuginstantiate");class gn{idProvider;parent;keepWorldPosition;position;rotation;scale;visible;context;components;clone(){const e=new gn;return e.idProvider=this.idProvider,e.parent=this.parent,e.keepWorldPosition=this.keepWorldPosition,e.position=Array.isArray(this.position)?[...this.position]:this.position?.clone(),e.rotation=Array.isArray(this.rotation)?[...this.rotation]:this.rotation?.clone(),e.scale=Array.isArray(this.scale)?[...this.scale]:this.scale?.clone(),e.visible=this.visible,e.context=this.context,e.components=this.components,e}cloneAssign(e){this.idProvider=e.idProvider,this.parent=e.parent,this.keepWorldPosition=e.keepWorldPosition,this.position=Array.isArray(e.position)?[...e.position]:e.position?.clone(),this.rotation=Array.isArray(e.rotation)?[...e.rotation]:e.rotation?.clone(),this.scale=Array.isArray(e.scale)?[...e.scale]:e.scale?.clone(),this.visible=e.visible,this.context=e.context,this.components=e.components}}function $a(s){return s.visible}function sc(s,e){return typeof e=="number"&&(e=e>.5),s.visible=e,s.visible}function K0(s){return s[jn]||Mu(s)}function Z0(s,e){s[q0]=e}function Mu(s){return Ni.isUsingInstancing(s)}function _g(s,e){return Ma(s,e,!0,!0)}const J0=Symbol("isDestroyed");function dr(s){return s[J0]}function ew(s,e){s[J0]=e}const tm=Symbol("isDontDestroy");function na(s,e=!0){s[tm]=e}const xd=[],Sd=[];function bi(s,e=!0,t=!1){xd.length=0,Sd.length=0,im(s,e,!0);for(const i of xd)i.gameObject=null,i.context=null;for(const i of Sd)ew(i,!0),t&&we(i);Sd.length=0,xd.length=0}function im(s,e=!0,t=!0){if(s==null)return;const i=s;if(i.isComponent){if(i[tm])return;xd.push(i);const r=i.gameObject;i.__internalDisable(),i.__internalDestroy(),i.gameObject=r;return}if(s[tm])return;const n=s;wd&&console.log(n),Sd.push(n);const o=n.userData?.components;if(o!=null&&Array.isArray(o)){let r=o.length;for(let a=0;a<o.length;a++){const l=o[a];im(l,e,!1),o.length<r&&(r=o.length,a--)}}if(e&&n.children)for(const r of n.children)im(r,e,!1);t&&n.removeFromParent()}function ur(s,e,t=!0){return tw(s,e,t)}function*ku(s,e,t=!1,i=999,n=0){if(s?.userData.components&&!(n>i)){for(const o of s.userData.components)e&&o?.isComponent===!0&&o instanceof e?yield o:yield o;if(t===!0)for(const o of s.children)yield*ku(o,e,!0,i,n+1)}}function tw(s,e,t,i=0){if(s){if(s.isObject3D,i>1e3){console.warn("Failed to iterate components: too many levels");return}if(s.userData?.components)for(let n=0;n<s.userData.components.length;n++){const o=s.userData.components[n];if(o?.isComponent===!0){const r=e(o);if(r!==void 0)return r}}if(t&&s.children){const n=i+1;for(let o=0;o<s.children.length;o++){const r=s.children[o];if(!r)continue;const a=tw(r,e,t,n);if(a!==void 0)return a}}}}function ho(s,e){if("isAssetReference"in s)return s.instantiate(e??void 0);let t=null;e!=null&&(e.x!==void 0?(t=new gn,t.position=e):t=e);let i=U.Current;t?.context&&(i=t.context),wd&&i.alias&&console.log("context",i.alias),t&&!t.idProvider&&(t.idProvider=new xt(Date.now()));const n=[],o={},r={},a=iw(i,s,t,n,o,r);a&&(PP(a,o),CP(r,o)),wd&&($d(s,!0),$d(a,!0));const l={};if(t?.components!==!1){for(const h in n){const d=n[h],u=d.guid;t&&t.idProvider&&(d.guid=t.idProvider.generateUUID(),l[u]=d.guid,wd&&console.log(d.name,d.guid)),Cu(d,i),d.__internalNewInstanceCreated&&d.__internalNewInstanceCreated()}for(const h in n){const d=n[h];d.resolveGuids&&d.resolveGuids(l),d.enabled!==!1&&(d.enabled=!0)}eu(i)}return a}function iw(s,e,t,i,n,o){if(!e||e[pi])return null;const r=e.userData;e.userData={};const a=e.children;e.children=[];const l=e.clone(!1);if(Ou(l),e.userData=r,e.children=a,n[e.uuid]={original:e,clone:l},sr&&console.log("ADD",e,l),e.type==="SkinnedMesh"&&(o[e.uuid]={original:e,clone:l}),t?.visible!==void 0&&(l.visible=t.visible),t?.idProvider){l.uuid=t.idProvider.generateUUID();const d=l;d&&(d.guid=l.uuid)}e.animations&&e.animations.length>0&&(l.animations=[...e.animations]);const h=e.parent;if(h&&h.add(l),t?.position)if(Array.isArray(t.position)){const d=new c.Vector3;d.fromArray(t.position),l.worldPosition=d}else l.worldPosition=t.position;else l.position.copy(e.position);if(t?.rotation){if(t.rotation instanceof c.Quaternion)l.worldQuaternion=t.rotation;else if(t.rotation instanceof c.Euler)l.worldQuaternion=ei().setFromEuler(t.rotation);else if(Array.isArray(t.rotation)){const d=new c.Euler;d.fromArray(t.rotation),l.worldQuaternion=ei().setFromEuler(d)}}else l.quaternion.copy(e.quaternion);if(t?.scale)if(Array.isArray(t.scale)){const d=new c.Vector3;d.fromArray(t.scale),t.scale=d}else l.scale.copy(t.scale);else l.scale.copy(e.scale);if(t?.parent&&t.parent!=="scene"){let d=null;if(typeof t.parent=="string"?d=Ma(t.parent,s.scene,!0):d=t.parent,d){const u=t.keepWorldPosition===!0?d.attach:d.add;u?u.call(d,l):console.error("Invalid parent object",d,"received when instantiating:",e)}else console.warn("could not find parent:",t.parent)}for(const[d,u]of Object.entries(e.userData))d!=="components"&&(l.userData[d]=u);if(e.userData?.components){const d=e.userData.components,u=[];l.userData.components=u;for(let p=0;p<d.length;p++){const m=d[p],y=new m.constructor;SP(m,y),m[ec]!==void 0&&(y[ec]=m[ec]),u.push(y),y.gameObject=l,i.push(y),n[m.guid]={original:m,clone:y},gu.dispatchComponentLifecycleEvent("component-added",y)}}t&&(t.position=void 0,t.rotation=void 0,t.scale=void 0,t.parent=void 0,t.visible=void 0);for(const d in e.children){const u=e.children[d],p=iw(s,u,t,i,n,o);p&&(n[p.uuid]={original:u,clone:p},l.add(p))}return l}function SP(s,e,t){Ra(e,s,void 0,{})}function CP(s,e){for(const t in s){const i=s[t],n=i.original,o=n.skeleton,r=i.clone;if(!o){console.warn("Skinned mesh has no skeleton?",i);continue}const a=o.bones,l=r.skeleton.clone();r.skeleton=l,r.bindMatrix.clone().copy(n.bindMatrix),r.bindMatrixInverse.copy(n.bindMatrixInverse);const h=[];l.bones=h;for(let d=0;d<a.length;d++){const u=a[d],m=e[u.uuid].clone;h.push(m)}}for(const t in s){const i=s[t].clone;i.skeleton.update(),i.bind(i.skeleton,i.bindMatrix),i.updateMatrixWorld(!0)}}function PP(s,e){for(const t in e){const n=e[t].clone;if(n?.isObject3D&&n?.userData?.components)for(let o=0;o<n.userData.components.length;o++){const r=n.userData.components[o],a=Object.entries(r);for(const[l,h]of a)if(Array.isArray(h)){const d=[];r[l]=d;for(let u=0;u<h.length;u++){const p=h[u];if(typeof p!="object"){d.push(p);continue}const m=X_(r,l,p,e);m!==void 0?(sr&&console.log("Found new instance for",l,p,"->",m),d.push(m)):(sr&&console.warn("Could not find new instance for",l,p),d.push(p))}}else if(typeof h=="object"){const d=X_(r,l,h,e);d!==void 0?r[l]=d:sr&&console.warn("Could not find new instance for",l,h)}}}}function X_(s,e,t,i){if(t!=null)if(t.isComponent===!0){const n=t.gameObject;if(n){const o=n.uuid,r=i[o]?.clone;if(!r){sr&&console.log("reference did not change",e,s,t);return}const a=n.userData.components.indexOf(t);if(a>=0&&r.isObject3D)return sr&&console.log(e,o),r.userData.components[a];console.warn("could not find component",e,t)}}else if(t.isObject3D===!0){if(e==="gameObject")return;const n=t;if(n){const o=n.uuid,r=i[o]?.clone;if(r)return sr&&console.log(e,"old",t,"new",r),r}}else{if(t.isVector4||t.isVector3||t.isVector2||t.isQuaternion||t.isEuler)return t.clone();if(t.isColor===!0)return t.clone();if(t.isEventList===!0)return t.__internalOnInstantiate(i)}}function oc(s,e){try{e||s()}catch(t){return console.error(t),!1}return!0}const nm=x("debugnewscripts"),OP=x("debughierarchy"),Ce=[];function MP(){return Ce.length>0}function eu(s){if(nm&&console.log("Register new components",s.new_scripts.length,[...s.new_scripts],s.alias?"element: "+s.alias:s.hash,s),s.new_scripts_pre_setup_callbacks.length>0){for(const e of s.new_scripts_pre_setup_callbacks)e&&e();s.new_scripts_pre_setup_callbacks.length=0}if(!(s.new_scripts.length<=0)){Ce.length=0,s.new_scripts.length>0&&Ce.push(...s.new_scripts),s.new_scripts.length=0;for(let e=0;e<Ce.length;e++)try{const t=Ce[e];if(t.isComponent!==!0){(A()||nm)&&console.error(`Registered script is not a Needle Engine component.
|
|
881
881
|
The script will be ignored. Please make sure your component extends "Behaviour" imported from "@needle-tools/engine"
|
|
882
882
|
`,t),Ce.splice(e,1),e--;continue}if(t.destroyed)continue;if(!t.gameObject){console.warn(`Component can not be initialized: no GameObject assigned.
|
|
@@ -1307,7 +1307,7 @@ dateFormat X
|
|
|
1307
1307
|
axisFormat %s
|
|
1308
1308
|
`;const p=Array.from(o),m=new Set;for(const v of p)if(v.affectedObjects&&typeof v.affectedObjects!="string"){if(Array.isArray(v.affectedObjects))for(const b of v.affectedObjects)m.add(b);else m.add(v.affectedObjects);r&&(u+=`section ${v.animationName} (${v.id})
|
|
1309
1309
|
`,u+=`${v.id} : ${v.start}, ${v.duration}s
|
|
1310
|
-
`)}r&&o.size&&console.log(u);const y=new Set;for(const v of m){v.getPath||console.error("USDZExporter: Animation target object has no getPath method. This is likely a bug",v);let b=v.getPath();b.startsWith("<")&&(b=b.substring(1)),b.endsWith(">")&&(b=b.substring(0,b.length-1)),y.add({path:b,obj:v})}const _=Array.from(y).sort((v,b)=>v.path.length-b.path.length),g=new Array;for(let v=0;v<_.length;v++)for(let b=v+1;b<_.length;b++)if(_[b].path.startsWith(_[v].path)){const w=_[b],R=_[v];g.push({child:w.obj.displayName+" ("+w.path+")",parent:R.obj.displayName+" ("+R.path+")"})}g.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:g,playAnimationActions:o})}for(const u of new Set([...t,...i]))if(Array.isArray(u))for(const p of u)n.add(p.uuid);else n.add(u.uuid);rd&&console.log("All Behavior trigger sources and action targets",t,i,n),this.targetUuids=new Set(n)}onAfterHierarchy(e,t){if(this.behaviours?.length){t.beginBlock('def Scope "Behaviors"');for(const i of this.behaviours)i.writeTo(this,e.document,t);t.closeBlock()}}async onAfterSerialize(e){rd&&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:i}of this.audioClipsCopy){if(e.files[i])return;const r=await(await(await fetch(t)).blob()).arrayBuffer(),a=new Uint8Array(r);e.files[i]=a}this.behaviourComponentsCopy.length=0,this.audioClipsCopy.length=0}}class dy{get extensionName(){return"Physics"}onExportObject(e,t,i){const n=S.getComponents(e,$e).filter(l=>l.enabled),o=S.getComponents(e,Xi).filter(l=>l.enabled&&!l.isTrigger);let r=n.length>0?n[0]:null;const a=o.length>0?o[0]:null;a&&!r&&(r=new $e,r.isKinematic=!0),r&&t.addEventListener("serialize",(l,h)=>{if(r){if(l.appendLine(),l.beginBlock('def RealityKitComponent "RigidBody"',"{",!0),r.useGravity||l.appendLine("bool gravityEnabled = 0"),l.appendLine('uniform token info:id = "RealityKit.RigidBody"'),r.isKinematic&&l.appendLine('token motionType = "Kinematic"'),l.beginBlock('def RealityKitStruct "massFrame"',"{",!0),l.appendLine(`float m_mass = ${r.mass}`),l.beginBlock('def RealityKitStruct "m_pose"',"{",!0),l.appendLine(`float3 position = (${r.centerOfMass.x}, ${r.centerOfMass.y}, ${r.centerOfMass.z})`),l.closeBlock("}"),l.closeBlock("}"),o.length>0){const d=o[0];l.beginBlock('def RealityKitStruct "material"',"{",!0);const u=d.sharedMaterial;u&&u.dynamicFriction!==void 0&&l.appendLine(`double dynamicFriction = ${d.sharedMaterial?.dynamicFriction}`),u&&u.bounciness!==void 0&&l.appendLine(`double restitution = ${d.sharedMaterial?.bounciness}`),u&&u.staticFriction!==void 0&&l.appendLine(`double staticFriction = ${d.sharedMaterial?.staticFriction}`),l.closeBlock("}")}l.closeBlock("}")}}),a&&(t.addEventListener("serialize",(l,h)=>{l.beginBlock('def RealityKitComponent "Collider"',"{",!0),l.appendLine("uint group = 1"),l.appendLine('uniform token info:id = "RealityKit.Collider"'),l.appendLine("uint mask = 4294967295");const u=a.isTrigger?"Trigger":"Default";if(l.appendLine(`token type = "${u}"`),l.beginBlock('def RealityKitStruct "Shape"',"{",!0),a instanceof Xa){const p=a;l.appendLine('token shapeType = "Sphere"'),l.appendLine(`float radius = ${p.radius}`)}else if(a instanceof Vu){const p=a;l.appendLine('token shapeType = "Box"'),l.appendLine(`float3 extent = (${p.size.x}, ${p.size.y}, ${p.size.z})`)}else if(a instanceof bs){const p=a;l.appendLine('token shapeType = "Capsule"'),l.appendLine(`float radius = ${p.radius}`),l.appendLine(`float height = ${p.height}`)}else if(a instanceof wo&&a.sharedMesh?.geometry){const p=a.sharedMesh.geometry;p.boundingBox||p.computeBoundingBox();const m=a.sharedMesh.geometry.boundingBox;m&&(l.appendLine('token shapeType = "Box"'),l.appendLine(`float3 extent = (${m.max.x-m.min.x}, ${m.max.y-m.min.y}, ${m.max.z-m.min.z})`),console.log("[USDZ] Only Box, Sphere, and Capsule colliders are supported in visionOS/iOS. MeshCollider will be exported as Box",a))}else console.warn("[USDZ] Only Box, Sphere, and Capsule colliders are supported in visionOS/iOS. Ignoring collider:",a);l.beginBlock('def RealityKitStruct "pose"',"{",!0),l.closeBlock("}"),l.closeBlock("}"),l.closeBlock("}")}),o.length>1&&console.log("WARNING: Multiple colliders detected. visionOS / iOS can only support objects with a single collider, only exporting the first collider: ",a))}}const Zk=x("debugshadowcomponents");ie.__webpack_exports__Block.prototype.interactable={get(){return this.interactive},set(s){this.interactable=s}};class Wi extends E{isRoot(){return this.Root?.gameObject===this.gameObject}get canvas(){const e=this.Root;return e?.isCanvas?e:null}get Canvas(){return this.canvas}markDirty(){Gt.markUIDirty(this.context)}get shadowComponent(){return this._shadowComponent}set shadowComponent(e){this._shadowComponent=e}_shadowComponent=null;_controlsChildLayout=!0;get controlsChildLayout(){return this._controlsChildLayout}set controlsChildLayout(e){this._controlsChildLayout=e,this.shadowComponent&&(this.shadowComponent.autoLayout=e)}_root=void 0;get Root(){return this._root===void 0&&(this._root=S.getComponentInParent(this.gameObject,uh)),this._root}_parentComponent=void 0;__internalNewInstanceCreated(e){return super.__internalNewInstanceCreated(e),this.shadowComponent=null,this._root=void 0,this._parentComponent=void 0,this}onEnable(){super.onEnable()}addShadowComponent(e,t){if(!e)return;this.removeShadowComponent();const i=this.isRoot()?this.gameObject:this.gameObject.parent;if(this._parentComponent=S.getComponentInParent(i,Wi),!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[pi]=this,this.setShadowComponentOwner(e);let n=!1;if(this.Root?.gameObject===this.gameObject)this.gameObject.add(e);else{const o=this._parentComponent.shadowComponent;o&&(o?.add(e),n=!0)}this.shadowComponent=e,t&&t.shadowComponent&&this.shadowComponent&&t.shadowComponent.add(this.shadowComponent),Hc&&e.add(new c.AxesHelper(.5)),this.onAfterAddedToScene(),n&&ie.__webpack_exports__update(),Zk&&console.warn("Added shadow component",this.shadowComponent)}setShadowComponentOwner(e){if(e&&(e[pi]===void 0||e[pi]===this)&&(e[pi]=this,e.children))for(const t of e.children)this.setShadowComponentOwner(t)}traverseOwnedShadowComponents(e,t,i){if(e&&e[pi]===t){i(e);for(const n of e.children)this.traverseOwnedShadowComponents(n,t,i)}}removeShadowComponent(){this.shadowComponent&&this.shadowComponent.removeFromParent()}onAfterAddedToScene(){}setInteractable(e){this.shadowComponent&&(this.shadowComponent.interactable=e)}}class uh extends Wi{awake(){super.awake()}}var Jk=Object.defineProperty,eE=Object.getOwnPropertyDescriptor,fh=(s,e,t,i)=>{for(var n=i>1?void 0:i?eE(e,t):e,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&Jk(e,t,n),n};const dp=x("debugui"),up=x("debuguilayout");class hx{width;height}class dx{x;y;width;height}const on=new c.Vector3,Ol=new c.Matrix4,ad=new c.Quaternion,el=class ux extends Wi{get parent(){return this._parentRectTransform}get translation(){return this.gameObject.position}get rotation(){return this.gameObject.quaternion}get scale(){return this.gameObject.scale}_anchoredPosition;get anchoredPosition(){return this._anchoredPosition||(this._anchoredPosition=new c.Vector2),this._anchoredPosition}set anchoredPosition(e){this._anchoredPosition=e}sizeDelta=new c.Vector2(100,100);pivot=new c.Vector2(.5,.5);anchorMin=new c.Vector2(0,0);anchorMax=new c.Vector2(1,1);minWidth;minHeight;get width(){let e=this.sizeDelta.x;if(this.anchorMin.x!==this.anchorMax.x&&this._parentRectTransform){const t=this._parentRectTransform.width,i=this.anchorMax.x-this.anchorMin.x;e=t*i,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,i=this.anchorMax.y-this.anchorMin.y;e=t*i,e+=this.sizeDelta.y}return this.minHeight!==void 0&&e<this.minHeight?this.minHeight:e}lastMatrix;rectBlock;_transformNeedsUpdate=!1;_initialPosition;_parentRectTransform;_lastUpdateFrame=-1;awake(){super.awake(),this._lastUpdateFrame=-1,this._parentRectTransform=void 0,this.rectBlock=new c.Object3D,this.rectBlock.name=this.name,this.lastMatrix=new c.Matrix4,this._lastAnchoring=null,this._initialPosition=this.gameObject.position.clone(),this._initialPosition.z=0,this._anchoredPosition||(this._anchoredPosition=new c.Vector2),sa(this,"_anchoredPosition",()=>{this.markDirty()}),sa(this,"sizeDelta",()=>{this.markDirty()}),sa(this,"pivot",()=>{this.markDirty()}),sa(this,"anchorMin",()=>{this.markDirty()}),sa(this,"anchorMax",()=>{this.markDirty()})}onEnable(){super.onEnable(),this.rectBlock||(this.rectBlock=new c.Object3D),this.lastMatrix||(this.lastMatrix=new c.Matrix4),this._lastAnchoring||(this._lastAnchoring=new c.Vector2),this._initialPosition||(this._initialPosition=new c.Vector3),this._anchoredPosition||(this._anchoredPosition=new c.Vector2),this.addShadowComponent(this.rectBlock),this._transformNeedsUpdate=!0,this.canvas?.registerTransform(this)}onDisable(){super.onDisable(),this.removeShadowComponent(),this.canvas?.unregisterTransform(this)}onParentRectTransformChanged(e){this._transformNeedsUpdate||this.onApplyTransform(up?`${e.name} changed`:void 0)}get isDirty(){return this._transformNeedsUpdate||(this._transformNeedsUpdate=!this.lastMatrix.equals(this.gameObject.matrix)),this._transformNeedsUpdate}markDirty(){this._transformNeedsUpdate||(up&&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){if(this.context.time.frameCount===this._lastUpdateFrame)return;this._lastUpdateFrame=this.context.time.frameCount;const t=this.shadowComponent;if(!t)return;this.gameObject.parent?this._parentRectTransform=S.getComponentInParent(this.gameObject.parent,ux):this._parentRectTransform=void 0,this._transformNeedsUpdate=!1,up&&console.warn("RectTransform → ApplyTransform",this.name+" because "+e),this.isRoot()?this.Root.screenspace||(t.rotation.y=Math.PI):(t.matrix.identity(),t.matrixAutoUpdate=!1,on.set(0,0,0),this.applyPivot(on),t.matrix.setPosition(on.x,on.y,0),(this.gameObject.quaternion.x||this.gameObject.quaternion.y||this.gameObject.quaternion.z)&&(ad.copy(this.gameObject.quaternion),ad.x*=-1,ad.z*=-1,Ol.makeRotationFromQuaternion(ad),t.matrix.premultiply(Ol)),on.set(0,0,0),this.applyAnchoring(on),this.canvas?.screenspace?on.z+=.1:on.z+=.01,Ol.identity(),Ol.setPosition(on.x,on.y,on.z),t.matrix.premultiply(Ol),t.matrix.scale(this.gameObject.scale)),this.lastMatrix.copy(this.gameObject.matrix);const i=!0;for(const n of ku(this.gameObject,Wi,i,1)){if(n===this||!n.activeAndEnabled)continue;const o=n;o.onParentRectTransformChanged&&o.onParentRectTransformChanged(this)}}_lastAnchoring;applyAnchoring(e){this._lastAnchoring||(this._lastAnchoring=new c.Vector2);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 i=this._parentRectTransform;if(i){let n=0;const o=1-this.anchorMax.y-this.anchorMin.y;n-=i.height*.5*o,e.y+=n;let r=0;const a=1-this.anchorMax.x-this.anchorMin.x;r-=i.width*.5*a,e.x+=r}}applyPivot(e){if(this.pivot&&!this.isRoot()){const t=this.pivot.x-.5;e.x-=t*this.sizeDelta.x*this.gameObject.scale.x;const i=this.pivot.y-.5;e.y-=i*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}_createdBlocks=[];_createdTextBlocks=[];createNewBlock(e){e={...this.getBasicOptions(),...e},dp&&console.log(this.name,e);const t=new ie.__webpack_exports__Block(e);return this._createdBlocks.push(t),t}createNewText(e){dp&&console.log(e),e={...this.getBasicOptions(),...e},dp&&console.log(this.name,e);const t=new ie.__webpack_exports__Text(e);return this._createdTextBlocks.push(t),t}};fh([f(c.Vector2)],el.prototype,"anchoredPosition",1);fh([f(c.Vector2)],el.prototype,"sizeDelta",2);fh([f(c.Vector2)],el.prototype,"pivot",2);fh([f(c.Vector2)],el.prototype,"anchorMin",2);fh([f(c.Vector2)],el.prototype,"anchorMax",2);let mn=el;var tE=Object.defineProperty,fx=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&tE(e,t,n),n};class tl extends E{effectColor;effectDistance}fx([f(te)],tl.prototype,"effectColor");fx([f(c.Vector2)],tl.prototype,"effectDistance");var iE=Object.defineProperty,nE=Object.getOwnPropertyDescriptor,px=(s,e,t,i)=>{for(var n=i>1?void 0:i?nE(e,t):e,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&iE(e,t,n),n};const Fo={backgroundColor:new c.Color(1,1,1),backgroundOpacity:1,borderColor:new c.Color(1,1,1),borderOpacity:1},uy=class Hl extends Wi{get isGraphic(){return!0}get color(){return this._color||(this._color=new te(1,1,1,1)),this._color}set color(e){(!this._color||this._color.r!==e.r||this._color.g!==e.g||this._color.b!==e.b||this._color.alpha!==e.alpha)&&(this._color||(this._color=new te(1,1,1,1)),this._color.copy(e),this.onColorChanged())}_alphaFactor=1;setAlphaFactor(e){this._alphaFactor=e,this.onColorChanged()}get alphaFactor(){return this._alphaFactor}sRGBColor=new c.Color(1,0,1);onColorChanged(){if(this.uiObject){this.sRGBColor.copy(this._color),this.sRGBColor.convertLinearToSRGB(),Fo.backgroundColor=this.sRGBColor,Fo.backgroundOpacity=this._color.alpha;const e=this.uiObject._simpleState__activeStates?.[0];if(e){const t=this.uiObject._simpleState__states?.[e];t&&("backgroundColor"in t&&(Fo.backgroundColor=t.backgroundColor),"backgroundOpacity"in t&&(Fo.backgroundOpacity=t.backgroundOpacity))}Fo.backgroundOpacity*=this._alphaFactor,this.applyEffects(Fo,this._alphaFactor),this.uiObject.set(Fo),this.markDirty()}}get m_Color(){return this._color}raycastTarget=!0;uiObject=null;_color=null;_rect=null;_stateManager=null;get rectTransform(){if(this._rect||(this._rect=S.getComponent(this.gameObject,mn)),!this._rect)throw new Error("Not Supported: Make sure to add a RectTransform component before adding a UI Graphic component.");return this._rect}onParentRectTransformChanged(){this.uiObject?.set({width:this.rectTransform.width,height:this.rectTransform.height}),this.markDirty()}__internalNewInstanceCreated(e){return super.__internalNewInstanceCreated(e),this._rect=null,this.uiObject=null,this._stateManager=null,this._color&&(this._color=this._color.clone()),this}setState(e){this.makePanel(),this.uiObject&&(this.uiObject.setState(e),this?.markDirty())}setupState(e){this.makePanel(),this.uiObject&&(this._stateManager||(this._stateManager=new ie.SimpleStateBehavior(this.uiObject)),this.uiObject.setupState(e.state,e.attributes))}setOptions(e){this.makePanel(),this.uiObject&&this.uiObject.set(e)}awake(){super.awake(),this.makePanel(),sa(this,"_color",()=>mO(this,this.onColorChanged))}onEnable(){super.onEnable(),this.uiObject&&(this.rectTransform.shadowComponent?.add(this.uiObject),this.addShadowComponent(this.uiObject,this.rectTransform))}onDisable(){super.onDisable(),this.uiObject&&this.removeShadowComponent()}_currentlyCreatingPanel=!1;makePanel(){if(this.uiObject||this._currentlyCreatingPanel)return;this._currentlyCreatingPanel=!0;const t={backgroundColor:this.color,backgroundOpacity:this.color.alpha,offset:.015};this.onBeforeCreate(t),this.applyEffects(t),this.onCreate(t),this.controlsChildLayout=!1,this._currentlyCreatingPanel=!1,this.onAfterCreated(),this.onColorChanged()}onBeforeCreate(e){}onCreate(e){this.uiObject=this.rectTransform.createNewBlock(e),this.uiObject.name=this.name}onAfterCreated(){}applyEffects(e,t=1){const i=this.gameObject?.getComponent(tl);i&&(i.effectDistance&&(e.borderWidth=Math.max(Math.abs(i.effectDistance.x),Math.abs(i.effectDistance.y))),i.effectColor&&(e.borderColor=i.effectColor,e.borderOpacity=i.effectColor.alpha*t))}static textureCache=new Map;async setTexture(e){if(this.setOptions({backgroundOpacity:0}),e){if(Hl.textureCache.has(e))e=Hl.textureCache.get(e);else if(!e.isRenderTargetTexture){const t=e.clone();t.colorSpace=c.LinearSRGBColorSpace,Hl.textureCache.set(e,t),e=t}this.setOptions({backgroundImage:e,borderRadius:0,backgroundOpacity:this.color.alpha,backgroundSize:"stretch"}),re.NEEDLE_progressive.assignTextureLOD(e,0).then(t=>{t instanceof c.Texture&&(e&&Hl.textureCache.set(e,t),this.setOptions({backgroundImage:t}),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)}};px([f(te)],uy.prototype,"color",1);px([f()],uy.prototype,"raycastTarget",2);let ph=uy;class mh extends ph{_flippedObject=!1;onAfterCreated(){this.uiObject&&!this._flippedObject&&(this._flippedObject=!0,this.uiObject.scale.y*=-1)}}var sE=Object.defineProperty,oE=Object.getOwnPropertyDescriptor,ks=(s,e,t,i)=>{for(var n=i>1?void 0:i?oE(e,t):e,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&sE(e,t,n),n};const Uo=x("debugtext");var Ze=(s=>(s[s.UpperLeft=0]="UpperLeft",s[s.UpperCenter=1]="UpperCenter",s[s.UpperRight=2]="UpperRight",s[s.MiddleLeft=3]="MiddleLeft",s[s.MiddleCenter=4]="MiddleCenter",s[s.MiddleRight=5]="MiddleRight",s[s.LowerLeft=6]="LowerLeft",s[s.LowerCenter=7]="LowerCenter",s[s.LowerRight=8]="LowerRight",s))(Ze||{}),mx=(s=>(s[s.Normal=0]="Normal",s[s.Bold=1]="Bold",s[s.Italic=2]="Italic",s[s.BoldAndItalic=3]="BoldAndItalic",s))(mx||{});class Dt extends ph{alignment=0;verticalOverflow=0;horizontalOverflow=0;lineSpacing=1;supportRichText=!1;font;fontStyle=0;setAlphaFactor(e){super.setAlphaFactor(e),this.uiObject?.set({fontOpacity:this.color.alpha*this.alphaFactor}),this.markDirty()}get text(){return this._text}set text(e){e!==this._text&&(this._text=e,this.feedText(this.text,this.supportRichText),this.markDirty(),this.context.accessibility.updateElement(this,{label:this.text}))}set_text(e){this.text=e}get fontSize(){return this._fontSize}set fontSize(e){this._fontSize=e,this.uiObject?.set({fontSize:e})}sRGBTextColor=new c.Color(1,0,1);onColorChanged(){this.sRGBTextColor.copy(this.color),this.sRGBTextColor.convertLinearToSRGB(),this.uiObject?.set({color:this.sRGBTextColor,fontOpacity:this.color.alpha})}onParentRectTransformChanged(){super.onParentRectTransformChanged(),this.uiObject&&this.updateOverflow()}onBeforeCanvasRender(e){this.updateOverflow()}updateOverflow(){const e=this.uiObject?._overflow;e&&(e._needsUpdate=!0)}onCreate(e){Uo&&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,Uo&&(e.backgroundColor=16750848,e.backgroundOpacity=.5);const t=this.rectTransform;e={...e,...this.getTextOpts()},this.getAlignment(e),Uo&&(e.backgroundColor=Math.random()*16777215,e.backgroundOpacity=.1),this.uiObject=t.createNewText(e),this.feedText(this.text,this.supportRichText)}onAfterAddedToScene(){super.onAfterAddedToScene(),this.handleTextRenderOnTop()}_text="";_fontSize=12;_textMeshUi=null;getTextOpts(){const e=this.fontSize,t={color:this.color,fontOpacity:this.color.alpha,fontSize:e,fontKerning:"normal"};return this.setFont(t,this.fontStyle),t}onEnable(){super.onEnable(),this.context.accessibility.updateElement(this,{role:"text",label:this.text,hidden:!1}),this._didHandleTextRenderOnTop=!1,this.uiObject&&this.uiObject.addAfterUpdate(()=>{this.setShadowComponentOwner(this.uiObject),this.markDirty()}),setTimeout(()=>this.markDirty(),10),this.canvas?.registerEventReceiver(this)}onDisable(){super.onDisable(),this.canvas?.unregisterEventReceiver(this),this.context.accessibility.updateElement(this,{hidden:!0})}onDestroy(){super.onDestroy(),this.context.accessibility.removeElement(this)}getAlignment(e){switch(e.flexDirection="column",this.alignment){case 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){if(Uo&&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 i=this.getNextTag(e);if(i){if(i.startIndex>0){for(let r=this.uiObject.children.length-1;r>=0;r--){const a=this.uiObject.children[r];a.isUI&&(this.uiObject.remove(a),a.clear())}const o=new ie.__webpack_exports__Inline({textContent:e.substring(0,i.startIndex),color:"inherit"});this.uiObject.add(o)}}else{this.uiObject.textContent="",this.setOptions({textContent:e});return}const n=[];for(;i;){const o=this.getNextTag(e,i.endIndex),r={fontFamily:this.uiObject?.get("fontFamily"),color:"inherit",textContent:""};if(o){r.textContent=this.getText(e,i,o),this.handleTag(i,r,n);const a=new ie.__webpack_exports__Inline(r);this.uiObject?.add(a)}else{r.textContent=e.substring(i.endIndex),this.handleTag(i,r,n);const a=new ie.__webpack_exports__Inline(r);this.uiObject?.add(a)}i=o}}}_didHandleTextRenderOnTop=!1;handleTextRenderOnTop(){this._didHandleTextRenderOnTop||(this._didHandleTextRenderOnTop=!0,this.startCoroutine(this.renderOnTopCoroutine()))}*renderOnTopCoroutine(){if(!this.canvas)return;const e=[],t=this.canvas,i={renderOnTop:t.renderOnTop,depthWrite:t.depthWrite,doubleSided:t.doubleSided};for(;;){let n=!1;if(this._textMeshUi)for(let o=0;o<this._textMeshUi.length;o++){if(e[o]===!0)continue;n=!0;const r=this._textMeshUi[o];r.textContent&&(nu(r,i),e[o]=!0)}if(!n)break;yield}}handleTag(e,t,i){if(!e.isEndTag){if(e.type.includes("color")){const n=new fp(e,{color:t.color});if(i.push(n),e.type.length>6){const o=parseInt("0x"+e.type.substring(7));t.color=o}else t.color=new c.Color(1,1,1)}else if(e.type=="b"){this.setFont(t,1);const n=new fp(e,{fontWeight:700});i.push(n)}else if(e.type=="i"){this.setFont(t,2);const n=new fp(e,{fontStyle:"italic"});i.push(n)}}}getText(e,t,i){return e.substring(t.endIndex,i.startIndex)}getNextTag(e,t=0){const i=e.indexOf("<",t),n=e.indexOf(">",i);if(i>=0&&n>=0){const o=e.substring(i+1,n);return{type:o,startIndex:i,endIndex:n+1,isEndTag:o.startsWith("/")}}return null}setFont(e,t){if(!this.font)return;const i=this.font,n=this.getFamilyNameWithCorrectSuffix(i,t);Uo&&console.log("Selected font family:"+n);let o=ie.__webpack_exports__FontLibrary.getFontFamily(n);switch(o||(o=ie.__webpack_exports__FontLibrary.addFontFamily(n)),e.fontFamily=o,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 r=o.getVariant(e.fontWeight,e.fontStyle);if(!r){let a=n;a?.endsWith("-msdf.json")||(a+="-msdf.json");let l=n;l?.endsWith(".png")||(l+=".png"),r=o.addVariant(e.fontWeight,e.fontStyle,a,l),r?.addEventListener("ready",()=>{this.markDirty()})}}getFamilyNameWithCorrectSuffix(e,t){(e.startsWith("https:")||e.startsWith("http:"))&&(e=new URL(e).pathname);const i=e.lastIndexOf("-");if(i<0)return e;const n=e.substring(i+1)?.toLowerCase();if(rE.includes(n))return Uo&&console.warn("Unsupported font style: "+n),e;const o=e.lastIndexOf("/");let r=e;o>=0&&(r=r.substring(o+1));const a=r[0]===r[0].toUpperCase(),l=e.substring(0,i>o?i:e.length);switch(Uo&&console.log("Select font: ",e,mx[t],r,a,l),t){case 0:return a?l+"-Regular":l+"-regular";case 1:return a?l+"-Bold":l+"-bold";case 2:return a?l+"-Italic":l+"-italic";case 3:return a?l+"-BoldItalic":l+"-bolditalic";default:return e}}}ks([f()],Dt.prototype,"alignment",2);ks([f()],Dt.prototype,"verticalOverflow",2);ks([f()],Dt.prototype,"horizontalOverflow",2);ks([f()],Dt.prototype,"lineSpacing",2);ks([f()],Dt.prototype,"supportRichText",2);ks([f(URL)],Dt.prototype,"font",2);ks([f()],Dt.prototype,"fontStyle",2);ks([f()],Dt.prototype,"text",1);ks([f()],Dt.prototype,"fontSize",1);class fp{tag;previousValues;constructor(e,t){this.tag=e,this.previousValues=t}}const rE=["medium","mediumitalic","black","blackitalic","thin","thinitalic","extrabold","light","lightitalic","semibold"];class ma{static global_id=0;static getId(){return this.global_id++}id;content="";font=[];pointSize=144;width;height;depth;wrapMode;horizontalAlignment;verticalAlignment;material;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}constructor(e){this.id=e}writeTo(e,t){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?.push("sans-serif"));const i=this.font.map(n=>`"${n}"`).join(", ");t.appendLine(`string[] font = [ ${i} ]`),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/${qu(this.material)}>`),t.closeBlock()}}class fy{static singleLine(e,t,i){const n=new ma("text_"+ma.getId());return n.content=e,t&&(n.pointSize=t),i&&(n.depth=i),n}static multiLine(e,t,i,n,o,r){const a=new ma("text_"+ma.getId());return a.content=e,a.width=t,a.height=i,a.horizontalAlignment=n,a.verticalAlignment=o,r!==void 0&&(a.wrapMode=r),a}}const aE=new c.Matrix4().makeRotationY(Math.PI),lE=new c.Matrix4().makeScale(-1,1,-1);class tf{get extensionName(){return"text"}exportText(e,t,i){const n=S.getComponent(e,Dt);if(!n)return;const o=S.getComponent(e,mn);let r=100,a=100;o&&(r=o.width,a=o.height);const l=aE.clone();o&&l.premultiply(lE),t.setMatrix(l);const h=n.color.clone();t.material=new c.MeshStandardMaterial({color:h,emissive:h}),t.addEventListener("serialize",(d,u)=>{let p=n.text;p=p.replace(/\r/g,""),p=p.replace(/\n/g,"\\n");const m=fy.multiLine(p,r,a,"center","bottom","flowing");this.setTextAlignment(m,n.alignment),this.setOverflow(m,n),t.material&&(m.material=t.material),m.pointSize=this.convertToTextSize(n.fontSize),m.depth=.001,m.writeTo(void 0,d)})}convertToTextSize(e){return 1/.0502*144*e}setOverflow(e,t){t.horizontalOverflow?e.wrapMode="singleLine":e.wrapMode="flowing"}setTextAlignment(e,t){switch(t){case Ze.LowerLeft:case Ze.MiddleLeft:case Ze.UpperLeft:e.horizontalAlignment="left";break;case Ze.LowerCenter:case Ze.MiddleCenter:case Ze.UpperCenter:e.horizontalAlignment="center";break;case Ze.LowerRight:case Ze.MiddleRight:case Ze.UpperRight:e.horizontalAlignment="right";break}switch(t){case Ze.LowerLeft:case Ze.LowerCenter:case Ze.LowerRight:e.verticalAlignment="bottom";break;case Ze.MiddleLeft:case Ze.MiddleCenter:case Ze.MiddleRight:e.verticalAlignment="middle";break;case Ze.UpperLeft:case Ze.UpperCenter:case Ze.UpperRight:e.verticalAlignment="top";break}}}var cE=Object.defineProperty,Qe=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&cE(e,t,n),n};const zb=x("debuguilayout");class Er{left=0;right=0;top=0;bottom=0;get vertical(){return this.top+this.bottom}get horizontal(){return this.left+this.right}}Qe([f()],Er.prototype,"left");Qe([f()],Er.prototype,"right");Qe([f()],Er.prototype,"top");Qe([f()],Er.prototype,"bottom");class Ci extends E{_rectTransform=null;get rectTransform(){return this._rectTransform}onParentRectTransformChanged(e){this._needsUpdate=!0}_needsUpdate=!1;get isDirty(){return this._needsUpdate}get isLayoutGroup(){return!0}updateLayout(){this._rectTransform&&(zb&&console.warn("Layout Update",this.context.time.frame,this.name),this._needsUpdate=!1,this.onCalculateLayout(this._rectTransform))}childAlignment=0;reverseArrangement=!1;spacing=0;padding;minWidth=0;minHeight=0;flexibleHeight=0;flexibleWidth=0;preferredHeight=0;preferredWidth=0;start(){this._needsUpdate=!0}onEnable(){zb&&console.log(this.name,this),this._rectTransform=this.gameObject.getComponent(mn);const e=this.gameObject.getComponentInParent(Fa);e&&e.registerLayoutGroup(this),this._needsUpdate=!0}onDisable(){const e=this.gameObject.getComponentInParent(Fa);e&&e.unregisterLayoutGroup(this)}set m_Spacing(e){e!==this.spacing&&(this._needsUpdate=!0,this.spacing=e)}get m_Spacing(){return this.spacing}}Qe([f()],Ci.prototype,"childAlignment");Qe([f()],Ci.prototype,"reverseArrangement");Qe([f()],Ci.prototype,"spacing");Qe([f(Er)],Ci.prototype,"padding");Qe([f()],Ci.prototype,"minWidth");Qe([f()],Ci.prototype,"minHeight");Qe([f()],Ci.prototype,"flexibleHeight");Qe([f()],Ci.prototype,"flexibleWidth");Qe([f()],Ci.prototype,"preferredHeight");Qe([f()],Ci.prototype,"preferredWidth");class Co extends Ci{childControlHeight=!0;childControlWidth=!0;childForceExpandHeight=!1;childForceExpandWidth=!1;childScaleHeight=!1;childScaleWidth=!1;onCalculateLayout(e){const t=this.primaryAxis,i=e.width;let n=i;const o=e.height;let r=o;n-=this.padding.horizontal,r-=this.padding.vertical,t==="x"?this.padding.horizontal:this.padding.vertical;const a=t==="x",l=a?"y":"x",h=a?this.childControlWidth:this.childControlHeight,d=a?this.childControlHeight:this.childControlWidth,u=a?this.childForceExpandWidth:this.childForceExpandHeight,p=a?this.childForceExpandHeight:this.childForceExpandWidth,m=a?r:n,y=a?i:o,_=.5*(a?this.childAlignment%3:Math.floor(this.childAlignment/3));let g=0;a?g+=this.padding.left:g+=this.padding.top;let v=0,b=0;for(let D=0;D<this.gameObject.children.length;D++){const L=this.gameObject.children[D],j=S.getComponent(L,mn);j?.activeAndEnabled&&(b+=1,a?v+=j.width:v+=j.height)}let w=0;const R=this.spacing*(b-1);if(u||h){let D=0;a?D=n-=R:D=r-=R,b>0&&(w=D/b)}let O=0;O+=this.padding.left,O-=this.padding.right,_!==0&&(g=y-v,g*=_,g-=R*_,a?(g-=this.padding.right*_,g+=this.padding.left*(1-_),g<this.padding.left&&(g=this.padding.left)):(g-=this.padding.bottom*_,g+=this.padding.top*(1-_),g<this.padding.top&&(g=this.padding.top)));let M=1;for(let D=0;D<this.gameObject.children.length;D++){const L=this.gameObject.children[D],j=S.getComponent(L,mn);if(j?.activeAndEnabled){j.pivot?.set(.5,.5),j.anchorMin.set(0,1),j.anchorMax.set(0,1);const V=i*.5+O*.5;j.anchoredPosition.x!==V&&(j.anchoredPosition.x=V);const W=o*-.5;j.anchoredPosition.y!==W&&(j.anchoredPosition.y=W),p&&d&&j.sizeDelta[l]!==m&&(j.sizeDelta[l]=m),u&&h&&j.sizeDelta[t]!==w&&(j.sizeDelta[t]=w);const k=a?j.width:j.height,N=k*.5;if(g+=N,u){const ee=w*M-w*.5;ee>g&&(g=ee-w*.5+k+this.padding.left,g-=N)}let $=g;t==="y"&&($=-$),j.anchoredPosition[t]!==$&&(j.anchoredPosition[t]=$),g+=N,g+=this.spacing,M+=1}}}}Qe([f()],Co.prototype,"childControlHeight");Qe([f()],Co.prototype,"childControlWidth");Qe([f()],Co.prototype,"childForceExpandHeight");Qe([f()],Co.prototype,"childForceExpandWidth");Qe([f()],Co.prototype,"childScaleHeight");Qe([f()],Co.prototype,"childScaleWidth");class py extends Co{get primaryAxis(){return"y"}}class my extends Co{get primaryAxis(){return"x"}}class gy extends Ci{onCalculateLayout(){}}var hE=Object.defineProperty,dE=Object.getOwnPropertyDescriptor,Kn=(s,e,t,i)=>{for(var n=i>1?void 0:i?dE(e,t):e,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&hE(e,t,n),n},gx=(s=>(s[s.ScreenSpaceOverlay=0]="ScreenSpaceOverlay",s[s.ScreenSpaceCamera=1]="ScreenSpaceCamera",s[s.WorldSpace=2]="WorldSpace",s[s.Undefined=-1]="Undefined",s))(gx||{});const pp=x("debuguilayout"),Gi=class yx extends uh{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)}_renderOnTop;set depthWrite(e){this._depthWrite!==e&&(this._depthWrite=e,this.onRenderSettingsChanged())}get depthWrite(){return this._depthWrite}_depthWrite=!1;set doubleSided(e){this._doubleSided!==e&&(this._doubleSided=e,this.onRenderSettingsChanged())}get doubleSided(){return this._doubleSided}_doubleSided=!0;set castShadows(e){this._castShadows!==e&&(this._castShadows=e,this.onRenderSettingsChanged())}get castShadows(){return this._castShadows}_castShadows=!1;set receiveShadows(e){this._receiveShadows!==e&&(this._receiveShadows=e,this.onRenderSettingsChanged())}get receiveShadows(){return this._receiveShadows}_receiveShadows=!1;get renderMode(){return this._renderMode}set renderMode(e){this._renderMode!==e&&(this._renderMode=e,this.onRenderSettingsChanged())}_renderMode=-1;_rootCanvas;set rootCanvas(e){this._rootCanvas instanceof yx||(this._rootCanvas=e)}get rootCanvas(){return this._rootCanvas}_scaleFactor=1;get scaleFactor(){return this._scaleFactor}set scaleFactor(e){this._scaleFactor=e}worldCamera;planeDistance=-1;awake(){this.shadowComponent=this.gameObject,this.previousParent=this.gameObject.parent,pp&&console.log("Canvas.Awake()",this.previousParent?.name+"/"+this.gameObject.name),super.awake()}start(){this.applyRenderSettings()}onEnable(){super.onEnable(),this._updateRenderSettingsRoutine=void 0,this._lastMatrixWorld=new c.Matrix4,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)}_boundRenderSettingsChanged=this.onRenderSettingsChanged.bind(this);previousParent=null;_lastMatrixWorld=null;_rectTransforms=[];registerTransform(e){this._rectTransforms.push(e)}unregisterTransform(e){const t=this._rectTransforms.indexOf(e);t!==-1&&this._rectTransforms.splice(t,1)}_layoutGroups=new Map;registerLayoutGroup(e){const t=e.gameObject;this._layoutGroups.set(t,e)}unregisterLayoutGroup(e){const t=e.gameObject;this._layoutGroups.delete(t)}_receivers=[];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 zc(1).then(()=>{this.gameObject.visible=!0}))}onLeaveXR(e){this.screenspace&&(e.xr.isVR||e.xr.isPassThrough)&&(this.gameObject.visible=!0)}onBeforeRenderRoutine=()=>{if(this.previousParent=this.gameObject.parent,(this.context.xr?.isVR||this.context.xr?.isPassThrough)&&this.screenspace){this.gameObject.visible=!1,this.gameObject.removeFromParent();return}this.renderOnTop||this.screenspace?this.gameObject.removeFromParent():(this.onUpdateRenderMode(),this.handleLayoutUpdates(),this.shadowComponent?.updateMatrixWorld(!0),this.shadowComponent?.updateWorldMatrix(!0,!0),this.invokeBeforeRenderEvents(),Gt.ensureUpdateMeshUI(ie.ThreeMeshUI,this.context))};onAfterRenderRoutine=()=>{if((this.context.xr?.isVR||this.context.xr?.isPassThrough)&&this.screenspace){this.previousParent?.add(this.gameObject);return}if((this.screenspace||this.renderOnTop)&&this.previousParent&&this.context.mainCamera){this.screenspace?this.context.mainCamera?.add(this.gameObject):this.previousParent.add(this.gameObject);const e=this.context.renderer.autoClear,t=this.context.renderer.autoClearColor;this.context.renderer.autoClear=!1,this.context.renderer.autoClearColor=!1,this.context.renderer.clearDepth(),this.onUpdateRenderMode(!0),this.handleLayoutUpdates(),this.shadowComponent?.updateMatrixWorld(!0),this.invokeBeforeRenderEvents(),Gt.ensureUpdateMeshUI(ie.ThreeMeshUI,this.context,!0),this.context.renderer.render(this.gameObject,this.context.mainCamera),this.context.renderer.autoClear=e,this.context.renderer.autoClearColor=t,this.previousParent.add(this.gameObject)}this._lastMatrixWorld?.copy(this.gameObject.matrixWorld)};invokeBeforeRenderEvents(){for(const e of this._receivers)e.onBeforeCanvasRender?.(this)}handleLayoutUpdates(){this._lastMatrixWorld===null&&(this._lastMatrixWorld=new c.Matrix4);const e=!this._lastMatrixWorld.equals(this.gameObject.matrixWorld);pp&&e&&console.log("Canvas Layout changed",this.context.time.frameCount,this.name);for(const t of this._rectTransforms){e&&t.markDirty();let i=this._layoutGroups.get(t.gameObject);t.isDirty&&!i&&(i=t.gameObject.getComponentInParent(Ci)),(t.isDirty||i?.isDirty)&&(pp&&console.log("CANVAS UPDATE ### "+t.name+" ##################################### "+this.context.time.frame),i?.updateLayout(),t.updateTransform())}}applyRenderSettings(){this.onRenderSettingsChanged()}_updateRenderSettingsRoutine;onRenderSettingsChanged(){this._updateRenderSettingsRoutine||(this._updateRenderSettingsRoutine=this.startCoroutine(this._updateRenderSettingsDelayed(),ge.OnBeforeRender))}*_updateRenderSettingsDelayed(){if(yield,this._updateRenderSettingsRoutine=void 0,this.shadowComponent){this.onUpdateRenderMode(),nu(this.shadowComponent,this);for(const e of S.getComponentsInChildren(this.gameObject,Wi))nu(e.shadowComponent,this)}}_activeRenderMode=-1;_lastWidth=-1;_lastHeight=-1;onUpdateRenderMode(e=!1){if(!e&&this._renderMode===this._activeRenderMode&&this._lastWidth===this.context.domWidth&&this._lastHeight===this.context.domHeight)return;this._activeRenderMode=this._renderMode;let t=this.context.mainCameraComponent,i=10;switch(t&&t.nearClipPlane>0&&t.farClipPlane>0&&(i=I.lerp(t.nearClipPlane,t.farClipPlane,.01)),this._renderMode===1&&(this.worldCamera&&(t=this.worldCamera),this.planeDistance>0&&(i=this.planeDistance)),this._renderMode){case 0:case 1:if(this._lastWidth=this.context.domWidth,this._lastHeight=this.context.domHeight,!t)return;const n=i+.01;this.gameObject.position.x=0,this.gameObject.position.y=0,this.gameObject.position.z=-n,this.gameObject.quaternion.identity();const o=this.gameObject.getComponent(mn);let r=!1;o.sizeDelta.x!==this.context.domWidth&&(r=!0),o.sizeDelta.y!==this.context.domHeight&&(r=!0);const a=t.fieldOfView*Math.PI/180,l=2*Math.tan(a/2)*Math.abs(n);this.gameObject.scale.x=l/this.context.domHeight,this.gameObject.scale.y=l/this.context.domHeight,this.gameObject.scale.z=.01,r&&(o.sizeDelta.x=this.context.domWidth,o.sizeDelta.y=this.context.domHeight,o?.markDirty());break;case 2:this._lastWidth=-1,this._lastHeight=-1;break}}};Kn([f()],Gi.prototype,"renderOnTop",1);Kn([f()],Gi.prototype,"depthWrite",1);Kn([f()],Gi.prototype,"doubleSided",1);Kn([f()],Gi.prototype,"castShadows",1);Kn([f()],Gi.prototype,"receiveShadows",1);Kn([f()],Gi.prototype,"renderMode",1);Kn([f(Gi)],Gi.prototype,"rootCanvas",1);Kn([f()],Gi.prototype,"scaleFactor",1);Kn([f(si)],Gi.prototype,"worldCamera",2);Kn([f()],Gi.prototype,"planeDistance",2);let Fa=Gi;var uE=Object.defineProperty,fE=Object.getOwnPropertyDescriptor,yy=(s,e,t,i)=>{for(var n=i>1?void 0:i?fE(e,t):e,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&uE(e,t,n),n};class po extends E{get alpha(){return this._alpha}set alpha(e){e!==this._alpha&&(this._alpha=e,this.markDirty())}get isCanvasGroup(){return!0}_alpha=1;interactable=!0;blocksRaycasts=!0;_isDirty=!1;markDirty(){this._isDirty||(this._isDirty=!0,this.startCoroutine(this.applyChangesDelayed(),ge.OnBeforeRender))}*applyChangesDelayed(){this._isDirty=!1,this.applyChangesNow()}_buffer=[];applyChangesNow(){this._buffer.length=0;for(const e of S.getComponentsInChildren(this.gameObject,Wi,this._buffer)){const t=e;t.setAlphaFactor&&t.setAlphaFactor(this._alpha)}}}yy([f()],po.prototype,"alpha",1);yy([f()],po.prototype,"interactable",2);yy([f()],po.prototype,"blocksRaycasts",2);class _y{get extensionName(){return"tmui"}onExportObject(e,t,i){const n=S.getComponent(e,Fa);if(n&&n.enabled&&n.renderMode===gx.WorldSpace){const o=new tf,r=S.getComponent(e,mn),a=S.getComponent(e,po),l=new Array;if(r){if(!S.isActiveSelf(e)){const u=S.isActiveSelf(e);S.setActive(e,!0),r.onEnable(),r.updateTransform(),l.push(()=>{r.onDisable(),S.setActive(e,u)})}e.traverse(u=>{if(!S.isActiveInHierarchy(u)){const p=S.isActiveSelf(u);S.setActive(u,!0);const m=S.getComponent(u,Wi);m&&(m.onEnable(),l.push(()=>{m.onDisable()}));const y=S.getComponent(u,mn);y&&(y.onEnable(),y.updateTransform(),y.onApplyTransform(),l.push(()=>{y.onDisable()}));const _=S.getComponent(u,Dt);_&&(_.onEnable(),l.push(()=>{_.onDisable()})),l.push(()=>{S.setActive(u,p)})}}),r.width,r.height;const h=qe.createEmpty(),d=r.shadowComponent;if(t.add(h),d){const u=d.matrix;h.setMatrix(u);const p=new Map,m=new Map;p.set(d,h),m.set(d,a?a.alpha:1),d.traverse(y=>{if(y===d)return;const _=qe.createEmpty();_.setMatrix(y.matrix);const g=y.parent,v=!!g&&typeof g.textContent=="string"&&g.textContent.length>0;let b=m.get(g)||1;const w=S.getComponent(y,po);if(w&&(b*=w.alpha),y instanceof c.Mesh&&v){const O=y[pi];O?o.exportText(O.gameObject,_,i):console.error("Error when exporting UI: shadow component owner not found. This is likely a bug.",y)}if(y instanceof c.Mesh&&!v){const O=y.geometry.clone();O.scale(1,1,-1),this.flipWindingOrder(O),_.geometry=O;const M=new c.Color,D=y.material.opacity;M.copy(y.material.color),_.material=new c.MeshBasicMaterial({color:M,opacity:D*b,map:y.material.map,transparent:!0})}p.set(y,_),m.set(y,b);const R=p.get(g);if(!R){console.error("Error when exporting UI: shadow component parent not found!",y,y.parent);return}R.add(_)})}}for(const h of l)h()}}flipWindingOrder(e){const t=e.index.array;for(let i=0,n=t.length/3;i<n;i++){const o=t[i*3];t[i*3]=t[i*3+2],t[i*3+2]=o}e.index.needsUpdate=!0}}const ql=x("debugusdz");function pE(s,e){const t=[],i=S.getComponentsInChildren(s,lt),n=S.getComponentsInChildren(s,Tt),o=new Array,r=new Array;if(e.injectImplicitBehaviours)for(const a of i){if(!a||!a.runtimeAnimatorController||!a.enabled)continue;const l=a.runtimeAnimatorController.activeState;if(!l||!l.motion||!l.motion.clip||l.motion.clip.tracks?.length<1||o.includes(a))continue;const h=new Dc;h.animator=a,h.stateName=l.name,h.trigger="start",h.name="PlayAnimationOnClick_implicitAtStart_"+h.stateName;const d=new c.Object3D;S.addComponent(d,h),r.push(d),o.push(a),s.add(d)}else for(const a of i){if(!a||!a.runtimeAnimatorController||!a.enabled)continue;ql&&console.log(a);const l=[];for(const h of a.runtimeAnimatorController.enumerateActions()){ql&&console.log(h);const d=h.getClip();l.includes(d)||l.push(d)}t.push({root:a.gameObject,clips:l})}if(e.injectImplicitBehaviours)for(const a of n){if(!a||!a.clip||!a.enabled||!a.playAutomatically||o.includes(a))continue;const l=new Dc;l.animation=a,l.stateName=a.clip.name,l.trigger="start",l.name="PlayAnimationOnClick_implicitAtStart_"+l.stateName;const h=new c.Object3D;S.addComponent(h,l),r.push(h),o.push(a),s.add(h)}else for(const a of n){ql&&console.log(a);const l=[];for(const h of a.animations)l.includes(h)||l.push(h);t.push({root:a.gameObject,clips:l})}ql&&t?.length>0&&console.log("USDZ Animation Clips without behaviours",t);for(const a of t)for(const l of a.clips)e.registerAnimation(a.root,l);return r}function mE(s,e){const t=S.getComponentsInChildren(s,vi),i=S.getComponentsInChildren(s,uo),n=new Array,o=new Array;ql&&console.log({audioSources:t,playAudioOnClicks:i});for(const r of i){if(!r.target)continue;const a=t.indexOf(r.target);a>-1&&t.splice(a,1)}for(const r of t){if(!r||!r.clip||r.volume<=0||n.includes(r))continue;const a=new uo;a.target=r,a.name="PlayAudioOnClick_implicitAtStart_",a.trigger="start";const l=new c.Object3D;S.addComponent(l,a),console.log("implicit PlayAudioOnStart",l,a),o.push(l),n.push(r),s.add(l)}return o}function gE(s){return new St("DisableAtStart",Rt.sceneStartTrigger(),ue.fadeAction(s,0,!1))}function Nb(s,e){const t=s.domElement.shadowRoot.querySelector("link[rel='ar']");if(t)return t;const i=document.createElement("div");i.classList.add("menu"),i.classList.add("quicklook-menu"),i.style.display="none",i.style.visibility="hidden";const n=document.createElement("button");n.id="open-in-ar",e?(n.innerText="View in AR",n.title="View this scene in AR. The scene will be exported to USDZ and opened with Apple's QuickLook."):(n.innerText="View in AR",n.title="Download this scene for AR. Open the downloaded USDZ file to view it in AR using Apple's QuickLook."),i.appendChild(n);const o=document.createElement("a");o.id="needle-usdz-link",o.style.display="none",o.rel="ar",o.href="",o.target="_blank",i.appendChild(o);const r=document.createElement("img");return r.id="button",o.appendChild(r),s.domElement.shadowRoot.appendChild(i),o}var yE=Object.defineProperty,Pt=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&yE(e,t,n),n};const pt=x("debugusdz"),_E=x("debugusdzpruning");class Rr{callToAction;checkoutTitle;checkoutSubtitle;callToActionURL}Pt([f()],Rr.prototype,"callToAction");Pt([f()],Rr.prototype,"checkoutTitle");Pt([f()],Rr.prototype,"checkoutSubtitle");Pt([f()],Rr.prototype,"callToActionURL");const hi=class Wo extends E{static beforeExport=new ne;static afterExport=new ne;static beforeLODExport=new ne;objectToExport=void 0;autoExportAnimations=!0;autoExportAudioSources=!0;exportFileName=void 0;customUsdzFile=void 0;customBranding;anchoringType="plane";maxTextureSize=2048;planeAnchoringAlignment="horizontal";interactive=!0;physics=!0;allowCreateQuicklookButton=!0;quickLookCompatible=!0;extensions=[];link;button;start(){pt&&(console.log("USDZExporter",this),console.log("Debug USDZ Mode. Press 'T' to export"),window.addEventListener("keydown",e=>{e.key==="t"&&this.exportAndOpen()})),this.objectToExport||(this.objectToExport=this.gameObject),!this.objectToExport?.children?.length&&!this.objectToExport?.isMesh&&(this.objectToExport=this.context.scene)}onEnable(){const e=exports.DeviceUtilities.supportsQuickLookAR(),t=exports.DeviceUtilities.isiOS()||exports.DeviceUtilities.isiPad();!this.button&&(pt||e||t)&&(this.allowCreateQuicklookButton&&(this.button=this.createQuicklookButton()),this.lastCallback=this.quicklookCallback.bind(this),this.link=Nb(this.context,e),this.link.addEventListener("message",this.lastCallback)),pt&&Se("USDZ Exporter enabled: "+this.name),document.getElementById("open-in-ar")?.addEventListener("click",this.onClickedOpenInARElement),xc.registerExporter(this)}onDisable(){this.button?.remove(),this.link?.removeEventListener("message",this.lastCallback),pt&&Se("USDZ Exporter disabled: "+this.name),document.getElementById("open-in-ar")?.removeEventListener("click",this.onClickedOpenInARElement),xc.unregisterExporter(this)}onClickedOpenInARElement=e=>{e.preventDefault(),this.exportAndOpen()};async exportAsync(){return this.exportAndOpen()}async exportAndOpen(){let e=this.exportFileName??this.objectToExport?.name??this.name;if(e+="-"+Hw(),Vn()||(e!==""&&(e+="-"),e+="MadeWithNeedle"),this.link||(this.link=Nb(this.context,exports.DeviceUtilities.supportsQuickLookAR())),this.customUsdzFile)return pt&&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;Wo.beforeExport.invoke({exporter:this});const t=await this.export(this.objectToExport).finally(()=>{Wo.afterExport.invoke({exporter:this})});return t?(pt&&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(e){if(!e)return console.warn("No object to export"),null;const t=this._currentExportTasks.get(e);if(t)return t;const i=this.internalExport(e);return i instanceof Promise?(this._currentExportTasks.set(e,i),i.then(n=>(this._currentExportTasks.delete(e),n)).catch(n=>(this._currentExportTasks.delete(e),console.error("Error during USDZ export – please report a bug!",n),null))):i}_currentExportTasks=new Map;_previousTimeScale=1;async internalExport(e){oe.start("export-usdz",{onProgress:O=>{this.dispatchEvent(new CustomEvent("export-progress",{detail:{progress:O}}))}}),oe.report("export-usdz",{message:"Starting export",totalSteps:40,currentStep:0}),oe.report("export-usdz",{message:"Load progressive textures",autoStep:5}),oe.start("export-usdz-textures","export-usdz");const t=S.getComponentsInChildren(e,ci);for(const O of t)O&&O.enabled&&O.updateSprite(!0);const i=S.getComponentsInChildren(e,Ht),n=new Array;let o=0;for(const O of i){for(const M of O.sharedMeshes)if(M){let D=0;const L={exporter:this,type:"mesh",object:O.gameObject,mesh:M};if(Wo.beforeLODExport.invoke(L),L.overrideLevel!==void 0)if(L.overrideLevel===-1){pt&&console.warn("Skipping LOD export for mesh due to overrideLevel -1",O.gameObject,M);continue}else L.overrideLevel>=0&&(D=L.overrideLevel,pt&&console.log("Overriding LOD level for mesh export to level "+D+" "+M.name));const j=re.NEEDLE_progressive.assignMeshLOD(M,D);j instanceof Promise&&n.push(new Promise((V,W)=>{j.then(()=>{o++,oe.report("export-usdz-textures",{message:"Loaded progressive mesh",currentStep:o,totalSteps:n.length}),V()}).catch(k=>W(k))}))}for(const M of O.sharedMaterials)if(M){let D=0;const L={exporter:this,type:"texture",object:O.gameObject,material:M};if(Wo.beforeLODExport.invoke(L),L.overrideLevel!==void 0)if(L.overrideLevel===-1){pt&&console.warn("Skipping LOD assignment due to overrideLevel -1",O.gameObject,M);continue}else L.overrideLevel>=0&&(D=L.overrideLevel,pt&&console.log("Overriding LOD level for texture export to level "+D+" "+M.name));const j=re.NEEDLE_progressive.assignTextureLOD(M,D);j instanceof Promise&&n.push(new Promise((V,W)=>{j.then(()=>{o++,oe.report("export-usdz-textures",{message:"Loaded progressive texture",currentStep:o,totalSteps:n.length}),V()}).catch(k=>W(k))}))}}pt&&Se("Progressive Loading: "+n.length),await Promise.all(n),pt&&Se("Progressive Loading: done"),oe.end("export-usdz-textures");const r=Wt.Global.Mask;Wt.Global.Set(Ln.AR);const a=new Kw,l=new Xu(this.quickLookCompatible);let h;const d=[];this.interactive&&(d.push(new hy),d.push(new Mr),globalThis.NEEDLE_USE_RAPIER&&S.getComponentsInChildren(e,$e).length>0&&(this.physics?(h=new dy,d.push(h)):A()&&console.warn("USDZExporter: Physics export is disabled, but there are active Rigidbody components in the scene. They will not be exported.")),d.push(new tf),d.push(new _y));const u=[l,...d,...this.extensions],p={self:this,exporter:a,extensions:u,object:e};oe.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,oe.report("export-usdz","auto export animations and audio sources");const m=new Array;this.autoExportAnimations&&m.push(...pE(e,l)),u.find(O=>O.extensionName==="Audio")&&this.autoExportAudioSources&&m.push(...mE(e)),a.debug=pt,a.pruneUnusedNodes=!_E;const _=gr.instance.objs.map(O=>O.batchedMesh);a.keepObject=O=>{let M=!0;const D=S.getComponent(O,Ht);return D&&!D.enabled&&(M=!1),M&&_.includes(O)&&(M=!1),M&&S.getComponentInParent(O,oh)&&(M=!1),M&&S.getComponentInParent(O,Xn)&&(M=!1),pt&&!M&&console.log("USDZExporter: Discarding object",O),M},a.beforeWritingDocument=()=>{if(A()&&l&&h){const O=l.animatedRoots;for(const M of O){const D=S.getComponentsInChildren(M,$e).filter(j=>j.enabled),L=S.getComponents(M,Xi).filter(j=>j.enabled&&!j.isTrigger);(D.length>0||L.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.",M)}}};const g=new Array;this.objectToExport&&this.quickLookCompatible&&this.interactive&&this.objectToExport.traverse(O=>{O.visible||g.push(O)});const v=u.find(O=>O.extensionName==="Behaviour");this.interactive&&v&&g.length>0&&v.addBehavior(gE(g));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"),oe.report("export-usdz","Invoking exporter.parse");const w=await a.parse(this.objectToExport,{ar:{anchoring:{type:this.anchoringType},planeAnchoring:{alignment:this.planeAnchoringAlignment}},extensions:u,quickLookCompatible:this.quickLookCompatible,maxTextureSize:this.maxTextureSize,exportInvisible:b}),R=new Blob([w],{type:"model/vnd.usdz+zip"});this.revertWebARSessionRoot(),this.context.time.timeScale=this._previousTimeScale,oe.report("export-usdz","Invoking after-export"),this.dispatchEvent(new CustomEvent("after-export",{detail:p}));for(const O of m)S.destroy(O);return Wt.Global.Set(r),oe.end("export-usdz"),R}openInQuickLook(e,t){const i=e instanceof Blob?URL.createObjectURL(e):e,n=this.buildQuicklookOverlay();pt&&console.log("QuickLook Overlay",n);const o=n.callToAction?encodeURIComponent(n.callToAction):"",r=n.checkoutTitle?encodeURIComponent(n.checkoutTitle):"",a=n.checkoutSubtitle?encodeURIComponent(n.checkoutSubtitle):"";this.link.href=i+`#callToAction=${o}&checkoutTitle=${r}&checkoutSubtitle=${a}&callToActionURL=${n.callToActionURL}`,this.lastCallback||(this.lastCallback=this.quicklookCallback.bind(this),this.link.addEventListener("message",this.lastCallback)),this.link.download=t+".usdz",this.link.click()}download(e,t){Wo.save(e,t)}static save(e,t){const i=document.createElement("a");i.style.display="none",document.body.appendChild(i),typeof e=="string"?i.href=e:i.href=URL.createObjectURL(e),i.download=t,i.click(),i.remove()}lastCallback;quicklookCallback(e){if(e?.data=="_apple_ar_quicklook_button_tapped"){pt&&fe("Quicklook closed via call to action button");var t=new CustomEvent("quicklook-button-tapped",{detail:this});if(this.dispatchEvent(t),!t.defaultPrevented){const i=new URLSearchParams(this.link.href);if(i){const n=i.get("callToActionURL");pt&&Se("Quicklook url: "+n),n&&(Vn()?globalThis.open(n,"_blank"):console.warn("Quicklook closed: custom redirects require a Needle Engine Pro license: https://needle.tools/pricing",n))}}}}buildQuicklookOverlay(){const e={};return this.customBranding&&Object.assign(e,this.customBranding),Vn()||(console.log("Custom Quicklook banner text requires pro license: https://needle.tools/pricing"),e.callToAction="Close",e.checkoutTitle="🌵 Made with Needle",e.checkoutSubtitle="_"),(e.callToAction?.length||e.checkoutTitle?.length||e.checkoutSubtitle?.length)&&(e.callToAction?.length||(e.callToAction="\0"),e.checkoutTitle?.length||(e.checkoutTitle="\0"),e.checkoutSubtitle?.length||(e.checkoutSubtitle="\0")),this.dispatchEvent(new CustomEvent("quicklook-overlay",{detail:e})),e}static invertForwardMatrix=new c.Matrix4().makeRotationY(Math.PI);static invertForwardQuaternion=new c.Quaternion().setFromEuler(new c.Euler(0,Math.PI,0));_rootSessionRootWasAppliedTo=null;_rootPositionBeforeExport=new c.Vector3;_rootRotationBeforeExport=new c.Quaternion;_rootScaleBeforeExport=new c.Vector3;getARScaleAndTarget(){if(!this.objectToExport)return{scale:1,_invertForward:!1,target:this.gameObject,sessionRoot:null};const e=S.findObjectOfType(ef);let t=S.getComponentInParent(this.objectToExport,Ui);t||(t=S.getComponentInChildren(this.objectToExport,Ui));let i=1,n=!1;const o=this.objectToExport;return e?i=e.arScale:t&&(i=t.arScale,n=t.invertForward),{scale:1/i,_invertForward:n,target:o,sessionRoot:t?.gameObject??null}}applyWebARSessionRoot(){if(!this.objectToExport)return;const{scale:e,_invertForward:t,target:i,sessionRoot:n}=this.getARScaleAndTarget(),o=n?.matrixWorld.clone().invert();this._rootSessionRootWasAppliedTo=i,this._rootPositionBeforeExport.copy(i.position),this._rootRotationBeforeExport.copy(i.quaternion),this._rootScaleBeforeExport.copy(i.scale),i.scale.multiplyScalar(e),t&&i.quaternion.multiply(Wo.invertForwardQuaternion),i.updateMatrix(),i.updateMatrixWorld(!0),n&&o&&i.matrix.premultiply(o)}revertWebARSessionRoot(){if(!this.objectToExport||!this._rootSessionRootWasAppliedTo)return;const e=this._rootSessionRootWasAppliedTo;e.position.copy(this._rootPositionBeforeExport),e.quaternion.copy(this._rootRotationBeforeExport),e.scale.copy(this._rootScaleBeforeExport),e.updateMatrix(),e.updateMatrixWorld(!0),this._rootSessionRootWasAppliedTo=null}createQuicklookButton(){const t=lo.getOrCreate().createQuicklookButton();return t.parentNode||this.context.menu.appendChild(t),t}};Pt([f(c.Object3D)],hi.prototype,"objectToExport");Pt([f()],hi.prototype,"autoExportAnimations");Pt([f()],hi.prototype,"autoExportAudioSources");Pt([f()],hi.prototype,"exportFileName");Pt([f(URL)],hi.prototype,"customUsdzFile");Pt([f(Rr)],hi.prototype,"customBranding");Pt([f()],hi.prototype,"anchoringType");Pt([f()],hi.prototype,"maxTextureSize");Pt([f()],hi.prototype,"planeAnchoringAlignment");Pt([f()],hi.prototype,"interactive");Pt([f()],hi.prototype,"physics");Pt([f()],hi.prototype,"allowCreateQuicklookButton");Pt([f()],hi.prototype,"quickLookCompatible");let Wn=hi;Dk({find:()=>Ga(Wn),create:()=>new Wn});var bE=Object.defineProperty,vE=Object.getOwnPropertyDescriptor,by=(s,e,t,i)=>{for(var n=vE(e,t),o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&bE(e,t,n),n};class il extends E{get fog(){return this._fog||(this._fog=new c.Fog(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}_fog;onEnable(){this.scene.fog=this.fog}onDisable(){this.scene.fog===this._fog&&(this.scene.fog=null)}}by([f()],il.prototype,"near");by([f()],il.prototype,"far");by([f(c.Color)],il.prototype,"color");var wE=Object.defineProperty,vy=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&wE(e,t,n),n};class Tr extends E{objectBounds=!1;color;isGizmo=!0;_gizmoObject=null;_boxHelper=null;onEnable(){this.isGizmo&&!Hc||(this._gizmoObject||(this.objectBounds?this._gizmoObject=new c.BoxHelper(this.gameObject,this.color??16776960):(this.objectBounds=!1,this._gizmoObject=pg(this.color??16776960))),this.objectBounds?(this.scene.add(this._gizmoObject),this._boxHelper=this._gizmoObject,this.startCoroutine(this.syncObjectBounds(),ge.OnBeforeRender)):this.gameObject.add(this._gizmoObject))}onDisable(){this._gizmoObject&&this.gameObject.remove(this._gizmoObject)}*syncObjectBounds(){for(;this._boxHelper;)this._boxHelper?.update(),yield}}vy([f()],Tr.prototype,"objectBounds");vy([f(c.Color)],Tr.prototype,"color");vy([f()],Tr.prototype,"isGizmo");var xE=Object.defineProperty,wy=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&xE(e,t,n),n};class nl extends E{isGizmo=!1;color0;color1;gridHelper;size;divisions;offset;onEnable(){if(this.isGizmo&&!Hc)return;const e=this.size,t=this.divisions;this.gridHelper||(this.gridHelper=new c.GridHelper(e,t,this.color0??new c.Color(.4,.4,.4),this.color1??new c.Color(.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)}}wy([f()],nl.prototype,"isGizmo");wy([f(c.Color)],nl.prototype,"color0");wy([f(c.Color)],nl.prototype,"color1");var SE=Object.defineProperty,xy=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&SE(e,t,n),n};class Sy extends E{connectedBody;get rigidBody(){return this._rigidBody}_rigidBody=null;onEnable(){this._rigidBody||(this._rigidBody=this.gameObject.getComponent($e)),this.rigidBody&&this.connectedBody&&this.startCoroutine(this.create())}*create(){yield,this.rigidBody&&this.connectedBody&&this.activeAndEnabled&&this.createJoint(this.rigidBody,this.connectedBody)}}xy([f($e)],Sy.prototype,"connectedBody");class Cy extends Sy{createJoint(e,t){this.context.physics.engine?.addFixedJoint(e,t)}}class gh extends Sy{anchor;axis;createJoint(e,t){this.axis&&this.anchor&&this.context.physics.engine?.addHingeJoint(e,t,this.anchor,this.axis)}}xy([f(c.Vector3)],gh.prototype,"anchor");xy([f(c.Vector3)],gh.prototype,"axis");var CE=Object.defineProperty,PE=Object.getOwnPropertyDescriptor,Pi=(s,e,t,i)=>{for(var n=i>1?void 0:i?PE(e,t):e,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&CE(e,t,n),n};function Jr(s){return s*Math.PI/180}const Vb=300,Gs=x("debuglights");class Ot extends E{type=0;get range(){return this._range}set range(e){this._range=e,this.light&&(this.light.type==="SpotLight"||this.light.type==="PointLight")&&"distance"in this.light&&(this.light.distance=e)}_range=1;get spotAngle(){return this._spotAngle}set spotAngle(e){this._spotAngle=e,this.light&&this.light.type==="SpotLight"&&"angle"in this.light&&(this.light.angle=Jr(e/2))}_spotAngle=30;get innerSpotAngle(){return this._innerSpotAngle}set innerSpotAngle(e){if(this._innerSpotAngle=e,this.light&&this.light.type==="SpotLight"&&"penumbra"in this.light){const t=this.spotAngle,n=1-Jr(e/2)/Jr(t/2);this.light.penumbra=n}}_innerSpotAngle=10;set color(e){this._color=e,this.light!==void 0&&(this.light.color=e)}get color(){return this.light?this.light.color:this._color}_color=new c.Color(16777215);set shadowNearPlane(e){if(e!==this._shadowNearPlane&&(this._shadowNearPlane=e,this.light?.shadow?.camera!==void 0)){const t=this.light.shadow.camera;t.near=e}}get shadowNearPlane(){return this._shadowNearPlane}_shadowNearPlane=.1;set shadowBias(e){e!==this._shadowBias&&(this._shadowBias=e,this.light?.shadow?.bias!==void 0&&(this.light.shadow.bias=e,this.light.shadow.needsUpdate=!0))}get shadowBias(){return this._shadowBias}_shadowBias=0;set shadowNormalBias(e){e!==this._shadowNormalBias&&(this._shadowNormalBias=e,this.light?.shadow?.normalBias!==void 0&&(this.light.shadow.normalBias=e,this.light.shadow.needsUpdate=!0))}get shadowNormalBias(){return this._shadowNormalBias}_shadowNormalBias=0;_overrideShadowBiasSettings=!1;set shadows(e){this._shadows=e,this.light&&(this.light.castShadow=e!==0,this.updateShadowSoftHard())}get shadows(){return this._shadows}_shadows=1;lightmapBakeType=4;set intensity(e){this._intensity=e,this.light&&(this.light.intensity=e),Gs&&console.log("Set light intensity to "+this._intensity,e,this)}get intensity(){return this._intensity}_intensity=-1;get shadowDistance(){const e=this.light;return e?.shadow?e.shadow.camera.far:-1}set shadowDistance(e){this._shadowDistance=e;const t=this.light;if(t?.shadow){const i=t.shadow.camera;i.far=e,i.updateProjectionMatrix()}}_shadowDistance;shadowWidth;shadowHeight;get shadowResolution(){const e=this.light;return e?.shadow?e.shadow.mapSize.x:-1}set shadowResolution(e){if(e===this._shadowResolution)return;this._shadowResolution=e;const t=this.light;t?.shadow&&(t.shadow.mapSize.set(e,e),t.shadow.needsUpdate=!0)}_shadowResolution=void 0;get isBaked(){return this.lightmapBakeType===2}get selfIsLight(){if(this.gameObject.isLight===!0)return!0;switch(this.gameObject.type){case"SpotLight":case"PointLight":case"DirectionalLight":return!0}return!1}light=void 0;getWorldPosition(e){return this.light?this.type===1?this.light.getWorldPosition(e).multiplyScalar(1):this.light.getWorldPosition(e):e}awake(){this.color=new c.Color(this.color??16777215),Gs&&console.log(this.name,this)}onEnable(){Gs&&console.log("ENABLE LIGHT",this.name),this.createLight(),!this.isBaked&&(this.light&&(this.light.visible=!0,this.light.intensity=this._intensity,Gs&&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(),ge.LateUpdate))}onDisable(){Gs&&console.log("DISABLE LIGHT",this.name),this.light&&(this.selfIsLight?this.light.intensity=0:this.light.visible=!1)}createLight(){const e=this.selfIsLight;if(e&&!this.light)this.light=this.gameObject,this.light.name=this.name,this._intensity=this.light.intensity,this.type===1&&this.setDirectionalLight(this.light);else if(!this.light)switch(this.type){case 1:const t=new c.DirectionalLight(this.color,this.intensity*Math.PI);if(t.position.set(0,0,-Vb*.5).applyQuaternion(this.gameObject.quaternion),this.gameObject.add(t.target),hr(t.target,0,0,0),this.light=t,this.gameObject.position.set(0,0,0),this.gameObject.rotation.set(0,0,0),Gs){const r=new c.DirectionalLightHelper(this.light,.2,this.color);this.context.scene.add(r)}break;case 0:const i=new c.SpotLight(this.color,this.intensity*Math.PI,this.range,Jr(this.spotAngle/2),1-Jr(this.innerSpotAngle/2)/Jr(this.spotAngle/2),2);i.position.set(0,0,0),i.rotation.set(0,0,0),this.light=i;const n=i.target;i.add(n),n.position.set(0,0,this.range),n.rotation.set(0,0,0);break;case 2:const o=new c.PointLight(this.color,this.intensity*Math.PI,this.range);this.light=o;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),Gs&&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=Vb*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 i=this.gameObject.scale.x;t.left*=i,t.right*=i}if(this.shadowHeight!==void 0)t.top=this.shadowHeight/2,t.bottom=-this.shadowHeight/2;else{const i=this.gameObject.scale.y;t.top*=i,t.bottom*=i}this.light.shadow.needsUpdate=!0,Gs&&this.context.scene.add(new c.CameraHelper(t))}this.isBaked?this.light.removeFromParent():e||this.gameObject.add(this.light)}}*updateMainLightRoutine(){for(;;){this.type===1&&((!this.context.mainLight||this.intensity>this.context.mainLight.intensity)&&(this.context.mainLight=this),yield);break}}static allowChangingRendererShadowMapType=!0;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)}}Pi([f()],Ot.prototype,"type",2);Pi([f()],Ot.prototype,"range",1);Pi([f()],Ot.prototype,"spotAngle",1);Pi([f()],Ot.prototype,"innerSpotAngle",1);Pi([f(c.Color)],Ot.prototype,"color",1);Pi([f()],Ot.prototype,"shadowNearPlane",1);Pi([f()],Ot.prototype,"shadowBias",1);Pi([f()],Ot.prototype,"shadowNormalBias",1);Pi([f()],Ot.prototype,"shadows",1);Pi([f()],Ot.prototype,"lightmapBakeType",2);Pi([f()],Ot.prototype,"intensity",1);Pi([f()],Ot.prototype,"shadowDistance",1);Pi([f()],Ot.prototype,"shadowResolution",1);new c.Vector3(0,0,0);var OE=Object.defineProperty,nf=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&OE(e,t,n),n};const mp=x("debuglods"),ME=x("nolods");class sl{screenRelativeTransitionHeight;distance;renderers}nf([f()],sl.prototype,"screenRelativeTransitionHeight");nf([f()],sl.prototype,"distance");nf([f(Ht)],sl.prototype,"renderers");class kE{model;get renderers(){return this.model.renderers}constructor(e){this.model=e}}class sf extends E{lodModels=[];_lods=[];_settings=[];_lodsHandler;start(){if(mp&&console.log("LODGROUP",this.name,this.lodModels,this),!ME&&!this._lodsHandler&&this.gameObject&&this.lodModels&&Array.isArray(this.lodModels)){const e=[];for(const i of this.lodModels){const n=new kE(i);this._lods.push(n);for(const o of n.renderers)e.includes(o)||e.push(o)}this._lodsHandler=new Array;for(let i=0;i<e.length;i++){const n=new c.LOD;this._lodsHandler.push(n),this.gameObject.add(n)}const t=new c.Object3D;t.name="Cull "+this.name;for(let i=0;i<e.length;i++){const n=e[i],o=this._lodsHandler[i],r=n.gameObject;mp&&console.log(i,r.name);for(const a of this._lods){const l=a.model.distance;let h=null;if(a.renderers.includes(n)?h=r:h=t,h.type==="Group"){console.warn(`LODGroup ${this.name}: Group or MultiMaterial object's are not supported as LOD object: ${h.name}`);continue}mp&&console.log("LEVEL",h.name,l),o.autoUpdate=!1,this.onAddLodLevel(o,h,a.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 i=t.getCurrentLevel(),n=t.levels[i];t.layers.mask=n.object.layers.mask}}onAddLodLevel(e,t,i){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,i*this._distanceFactor,.01);const n={lod:e,levelIndex:e.levels.length-1,distance:i};this._settings.push(n)}_distanceFactor=1;distanceFactor(e){if(e!==this._distanceFactor){this._distanceFactor=e;for(const t of this._settings){const i=t.lod.levels[t.levelIndex];i.distance=t.distance*e}}}}nf([f(sl)],sf.prototype,"lodModels");var EE=Object.defineProperty,Py=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&EE(e,t,n),n};const ld=x("debugnestedgltf");class ol extends E{filePath;loaded=new ne;loadAssetInParent=!0;_isLoadingOrDoneLoading=!1;listenToProgress(e){this.filePath?.beginListenDownload(e)}preload(){return this.filePath?.preload()||null}async start(){if(this._isLoadingOrDoneLoading)return;ld&&console.log(this,this.guid);const e=this.gameObject.parent;if(e&&this.filePath){this._isLoadingOrDoneLoading=!0;const t=new gn;t.idProvider=new xt(this.hash(this.guid)),t.parent=this.loadAssetInParent!==!1?e:this.gameObject,this.gameObject.updateMatrix();const i=this.gameObject.matrix;ld&&console.log("Load nested:",this.filePath?.url??this.filePath,this.gameObject.position);const n=await this.filePath?.instantiate?.call(this.filePath,t);ld&&console.log("Nested loaded:",this.filePath?.url??this.filePath,n),n&&this.loadAssetInParent!==!1&&(n.matrixAutoUpdate=!1,n.matrix.identity(),n.applyMatrix4(i),n.matrixAutoUpdate=!0,n.layers.disableAll(),n.layers.set(this.layer),this.loaded.invoke({component:this,instance:n,asset:this.filePath})),ld&&console.log("Nested loading done:",this.filePath?.url??this.filePath,n)}}onDestroy(){this.filePath?.unload()}hash(e){let t=0;for(let i=0;i<e.length;i++)t=e.charCodeAt(i)+((t<<5)-t);return t}}Py([f(Z)],ol.prototype,"filePath");Py([f(ne)],ol.prototype,"loaded");Py([f()],ol.prototype,"loadAssetInParent");var RE=Object.defineProperty,Oy=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&RE(e,t,n),n};const TE=x("debugnet"),of=class wm extends E{url=null;urlParameterName=null;localhost=null;awake(){TE&&console.log(this),this.context.connection.registerProvider(this)}getWebsocketUrl(){let e=this.url?wm.GetUrl(this.url,this.localhost):null;if(this.urlParameterName){const o=x(this.urlParameterName);o&&typeof o=="string"&&(e=o)}if(!e)return null;const i=new RegExp("(((https?)|(?<socket_prefix>wss?))://)?(www.)?(?<url>.+)","gm").exec(e);return i?.groups?i?.groups.socket_prefix?e:"wss://"+i?.groups.url:null}static GetUrl(e,t){let i=e;const n=wm.IsLocalNetwork()&&t;if(n&&(i=t),e?.startsWith("/")){const o=n?i:window.location.origin;o?.endsWith("/")&&e.startsWith("/")&&(e=e.substring(1)),i=o+e}return i}static IsLocalNetwork(e=window.location.hostname){return yi(e)}};Oy([f()],of.prototype,"url");Oy([f()],of.prototype,"urlParameterName");Oy([f()],of.prototype,"localhost");let My=of;var AE=Object.defineProperty,rf=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&AE(e,t,n),n};class Ar extends E{referenceSpace;from;affectPosition=!1;affectRotation=!1;alignLookDirection=!1;levelLookDirection=!1;levelPosition=!1;positionOffset=new c.Vector3(0,0,0);rotationOffset=new c.Vector3(0,0,0);offset=new c.Vector3(0,0,0);update(){if(!this.from)return;var e=Y(this.from),t=pe(this.from);this.offset.copy(this.positionOffset);const i=this.offset.length();if(this.referenceSpace&&this.offset.transformDirection(this.referenceSpace.matrixWorld).multiplyScalar(i),e.add(this.offset),this.levelPosition&&this.referenceSpace){const a=new c.Plane(this.gameObject.up,0),l=Y(this.referenceSpace);a.setFromNormalAndCoplanarPoint(this.gameObject.up,l);const h=new c.Vector3(0,0,0);a.projectPoint(e,h),e.copy(h)}this.affectPosition&&at(this.gameObject,e);const n=new c.Euler(this.rotationOffset.x,this.rotationOffset.y,this.rotationOffset.z),o=new c.Quaternion().setFromEuler(n);this.affectRotation&&dn(this.gameObject,t.multiply(o));const r=new c.Vector3;this.from.getWorldDirection(r).multiplyScalar(50),this.levelLookDirection&&(r.y=0),this.alignLookDirection&&this.gameObject.lookAt(r)}}rf([f(S)],Ar.prototype,"referenceSpace");rf([f(S)],Ar.prototype,"from");rf([f(c.Vector3)],Ar.prototype,"positionOffset");rf([f(c.Vector3)],Ar.prototype,"rotationOffset");var DE=Object.defineProperty,Po=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&DE(e,t,n),n};class oi{time=0;value=0;inTangent=1/0;inWeight;outTangent=1/0;outWeight;weightedMode;constructor(e=0,t=0){this.time=e,this.value=t}}Po([f()],oi.prototype,"time");Po([f()],oi.prototype,"value");Po([f()],oi.prototype,"inTangent");Po([f()],oi.prototype,"inWeight");Po([f()],oi.prototype,"outTangent");Po([f()],oi.prototype,"outWeight");Po([f()],oi.prototype,"weightedMode");const _x=class Xl{static linearFromTo(e,t,i){const n=new Xl,o=new oi;o.time=0,o.value=e;const r=new oi;return r.time=i,r.value=t,n.keys.push(o,r),n}static constant(e){const t=new Xl,i=new oi;return i.time=0,i.value=e,t.keys.push(i),t}keys=[];clone(){const e=new Xl;return e.keys=this.keys?.map(t=>{const i=new oi;return i.time=t.time,i.value=t.value,i.inTangent=t.inTangent,i.inWeight=t.inWeight,i.outTangent=t.outTangent,i.outWeight=t.outWeight,i.weightedMode=t.weightedMode,i})||[],e}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 i=this.keys[t];if(i.time<=e)if(t+1<this.keys.length){const o=this.keys[t+1];if(o.time<e)continue;return!isFinite(i.outTangent)||!isFinite(o.inTangent)?i.value:Xl.interpolateValue(e,i,o)}else return i.value}return this.keys[this.keys.length-1].value}static interpolateValue(e,t,i){const n=t.time,o=t.value,r=t.outTangent,a=i.time,l=i.value,h=i.inTangent,d=a-n,u=d*d,p=u*d,m=((r+h)*d-2*(l-o))/p,y=(3*(l-o)-(h+2*r)*d)/u,_=r,g=o,v=e-n,b=v*v,w=b*v;return m*w+y*b+_*v+g}};Po([f(oi)],_x.prototype,"keys");let yh=_x;var LE=Object.defineProperty,C=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&LE(e,t,n),n};const cd=x("debugparticles");var rs=(s=>(s[s.Billboard=0]="Billboard",s[s.Stretch=1]="Stretch",s[s.HorizontalBillboard=2]="HorizontalBillboard",s[s.VerticalBillboard=3]="VerticalBillboard",s[s.Mesh=4]="Mesh",s))(rs||{});class Dr{alphaKeys=[];colorKeys=[];get duration(){return 1}evaluate(e,t){let i,n=0,o=null,r=0;for(let a=0;a<this.alphaKeys.length;a++){const l=this.alphaKeys[a];(l.time<e||!i)&&(i=l,n=a)}for(let a=0;a<this.colorKeys.length;a++){const l=this.colorKeys[a];(l.time<e||!o)&&(o=l,r=a)}if(o)if(r+1<this.colorKeys.length){const l=this.colorKeys[r+1],h=I.remap(e,o.time,l.time,0,1);t.r=I.lerp(o.color.r,l.color.r,h),t.g=I.lerp(o.color.g,l.color.g,h),t.b=I.lerp(o.color.b,l.color.b,h)}else t.r=o.color.r,t.g=o.color.g,t.b=o.color.b;if(i)if(n+1<this.alphaKeys.length){const l=this.alphaKeys[n+1],h=I.remap(e,i.time,l.time,0,1);t.alpha=I.lerp(i.alpha,l.alpha,h)}else t.alpha=i.alpha;return t}}C([f()],Dr.prototype,"alphaKeys");C([f()],Dr.prototype,"colorKeys");var Lc=(s=>(s[s.Local=0]="Local",s[s.World=1]="World",s[s.Custom=2]="Custom",s))(Lc||{}),hu=(s=>(s[s.Sphere=0]="Sphere",s[s.SphereShell=1]="SphereShell",s[s.Hemisphere=2]="Hemisphere",s[s.HemisphereShell=3]="HemisphereShell",s[s.Cone=4]="Cone",s[s.Box=5]="Box",s[s.Mesh=6]="Mesh",s[s.ConeShell=7]="ConeShell",s[s.ConeVolume=8]="ConeVolume",s[s.ConeVolumeShell=9]="ConeVolumeShell",s[s.Circle=10]="Circle",s[s.CircleEdge=11]="CircleEdge",s[s.SingleSidedEdge=12]="SingleSidedEdge",s[s.MeshRenderer=13]="MeshRenderer",s[s.SkinnedMeshRenderer=14]="SkinnedMeshRenderer",s[s.BoxShell=15]="BoxShell",s[s.BoxEdge=16]="BoxEdge",s[s.Donut=17]="Donut",s[s.Rectangle=18]="Rectangle",s[s.Sprite=19]="Sprite",s[s.SpriteRenderer=20]="SpriteRenderer",s))(hu||{});const Es=class Ql{static constant(e){const t=new Ql;return t.setConstant(e),t}static betweenTwoConstants(e,t){const i=new Ql;return i.setMinMaxConstant(e,t),i}static curve(e,t=1){const i=new Ql;return i.setCurve(e,t),i}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}mode="Constant";constant;constantMin;constantMax;curve;curveMin;curveMax;curveMultiplier;clone(){const e=new Ql;return e.mode=this.mode,e.constant=this.constant,e.constantMin=this.constantMin,e.constantMax=this.constantMax,e.curve=this.curve?.clone(),e.curveMin=this.curveMin?.clone(),e.curveMax=this.curveMax?.clone(),e.curveMultiplier=this.curveMultiplier,e}evaluate(e,t){const i=t===void 0?Math.random():t;switch(this.mode){case 0:case"Constant":return this.constant;case 1:case"Curve":return e=I.clamp01(e),this.curve.evaluate(e)*this.curveMultiplier;case 2:case"TwoCurves":const n=e*this.curveMin.duration,o=e*this.curveMax.duration;return I.lerp(this.curveMin.evaluate(n),this.curveMax.evaluate(o),i%1)*this.curveMultiplier;case 3:case"TwoConstants":return I.lerp(this.constantMin,this.constantMax,i%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 i=0;i<e.keys.length;i++){const n=e.keys[i];n.value>t&&(t=n.value)}return t}};C([f()],Es.prototype,"mode");C([f()],Es.prototype,"constant");C([f()],Es.prototype,"constantMin");C([f()],Es.prototype,"constantMax");C([f(yh)],Es.prototype,"curve");C([f(yh)],Es.prototype,"curveMin");C([f(yh)],Es.prototype,"curveMax");C([f()],Es.prototype,"curveMultiplier");let H=Es;const Oo=class _t{static constant(e){const t=new _t;return t.constant(e),t}static betweenTwoColors(e,t){const i=new _t;return i.betweenTwoColors(e,t),i}constant(e){return this.mode=0,this.color=e,this}betweenTwoColors(e,t){return this.mode=2,this.colorMin=e,this.colorMax=t,this}mode=0;color;colorMin;colorMax;gradient;gradientMin;gradientMax;static _temp=new te(0,0,0,1);static _temp2=new te(0,0,0,1);evaluate(e,t){const i=t===void 0?Math.random():t;switch(this.mode){case 0:case"Color":return this.color;case 1:case"Gradient":return this.gradient.evaluate(e,_t._temp),_t._temp;case 2:case"TwoColors":return _t._temp.lerpColors(this.colorMin,this.colorMax,i);case 3:case"TwoGradients":return this.gradientMin.evaluate(e,_t._temp),this.gradientMax.evaluate(e,_t._temp2),_t._temp.lerp(_t._temp2,i);case 4:case"RandomColor":const o=Math.random();return this.gradientMin.evaluate(e,_t._temp),this.gradientMax.evaluate(e,_t._temp2),_t._temp.lerp(_t._temp2,o)}return _t._temp.set(16777215),_t._temp.alpha=1,_t._temp}};C([f()],Oo.prototype,"mode");C([f(te)],Oo.prototype,"color");C([f(te)],Oo.prototype,"colorMin");C([f(te)],Oo.prototype,"colorMax");C([f(Dr)],Oo.prototype,"gradient");C([f(Dr)],Oo.prototype,"gradientMin");C([f(Dr)],Oo.prototype,"gradientMax");let Lr=Oo;var xm=(s=>(s[s.Hierarchy=0]="Hierarchy",s[s.Local=1]="Local",s[s.Shape=2]="Shape",s))(xm||{});class Lt{cullingMode;duration;emitterVelocityMode;flipRotation;gravityModifier;gravityModifierMultiplier;loop;maxParticles;playOnAwake;prewarm;ringBufferLoopRange;ringBufferMode;scalingMode;simulationSpace;simulationSpeed;startColor;startDelay;startDelayMultiplier;startLifetime;startLifetimeMultiplier;startRotation;startRotationMultiplier;startRotation3D;startRotationX;startRotationXMultiplier;startRotationY;startRotationYMultiplier;startRotationZ;startRotationZMultiplier;startSize;startSize3D;startSizeMultiplier;startSizeX;startSizeXMultiplier;startSizeY;startSizeYMultiplier;startSizeZ;startSizeZMultiplier;startSpeed;startSpeedMultiplier;stopAction;useUnscaledTime}C([f(H)],Lt.prototype,"gravityModifier");C([f(Lr)],Lt.prototype,"startColor");C([f(H)],Lt.prototype,"startDelay");C([f(H)],Lt.prototype,"startLifetime");C([f(H)],Lt.prototype,"startRotation");C([f(H)],Lt.prototype,"startRotationX");C([f(H)],Lt.prototype,"startRotationY");C([f(H)],Lt.prototype,"startRotationZ");C([f(H)],Lt.prototype,"startSize");C([f(H)],Lt.prototype,"startSizeX");C([f(H)],Lt.prototype,"startSizeY");C([f(H)],Lt.prototype,"startSizeZ");C([f(H)],Lt.prototype,"startSpeed");class du{cycleCount;maxCount;minCount;probability;repeatInterval;time;count;_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 i=this.time+this.repeatInterval*this._performed;if(e>=i&&(this._performed+=1,Math.random()<this.probability))switch(this.count.mode){case 0:t=this.count.constant;break;case 3:t=I.lerp(this.count.constantMin,this.count.constantMax,Math.random());break;case 1:t=this.count.curve.evaluate(Math.random());break;case 2:const n=Math.random();t=I.lerp(this.count.curveMin.evaluate(n),this.count.curveMax.evaluate(n),Math.random());break}}return t}}class Rs{enabled;get burstCount(){return this.bursts?.length??0}bursts;rateOverTime;rateOverTimeMultiplier;rateOverDistance;rateOverDistanceMultiplier;system;reset(){this.bursts?.forEach(e=>e.reset())}getBurst(){let e=0;if(this.burstCount>0)for(let t=0;t<this.burstCount;t++){const i=this.bursts[t];this.system.main.loop&&i.time>=this.system.time&&i.reset(),e+=Math.round(i.run(this.system.time))}return e}}C([f()],Rs.prototype,"enabled");C([f()],Rs.prototype,"bursts");C([f(H)],Rs.prototype,"rateOverTime");C([f()],Rs.prototype,"rateOverTimeMultiplier");C([f(H)],Rs.prototype,"rateOverDistance");C([f()],Rs.prototype,"rateOverDistanceMultiplier");class af{enabled;color}C([f(Lr)],af.prototype,"color");class Ir{enabled;separateAxes;size;sizeMultiplier;x;xMultiplier;y;yMultiplier;z;zMultiplier;_time=0;_temp=new c.Vector3;evaluate(e,t,i){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,i)*this.xMultiplier,t.y=this.y.evaluate(e,i)*this.yMultiplier,t.z=this.z.evaluate(e,i)*this.zMultiplier;else{const n=this.size.evaluate(e,i)*this.sizeMultiplier;t.x=n}return t}}C([f(H)],Ir.prototype,"size");C([f(H)],Ir.prototype,"x");C([f(H)],Ir.prototype,"y");C([f(H)],Ir.prototype,"z");const Ye=class Yl{get type(){return hu[this.shapeType]}initialize(e){this.onInitialize(e),e.position.x=this._vector.x,e.position.y=this._vector.y,e.position.z=this._vector.z}toJSON(){return this}clone(){return new Yl}shapeType=5;enabled=!0;alignToDirection=!1;angle=0;arc=360;arcSpread;arcSpeedMultiplier;arcMode;boxThickness;position;rotation;_rotation=new c.Euler;scale;radius;radiusThickness;sphericalDirectionAmount;randomDirectionAmount;randomPositionAmount;meshShapeType;meshRenderer;_meshObj;_meshGeometry;setMesh(e){this.meshRenderer=e,e?(this._meshObj=e.sharedMeshes[Math.floor(Math.random()*e.sharedMeshes.length)],this._meshGeometry=this._meshObj.geometry):(this._meshObj=void 0,this._meshGeometry=void 0)}system;_space;_worldSpaceMatrix=new c.Matrix4;_worldSpaceMatrixInverse=new c.Matrix4;constructor(){cd&&console.log(this)}update(e,t){}onUpdate(e,t,i,n){this.system=e,this._space=i,i===1&&(this._worldSpaceMatrix.copy(n.matrixWorld),this._worldSpaceMatrix.elements[0]=1,this._worldSpaceMatrix.elements[5]=1,this._worldSpaceMatrix.elements[10]=1,this._worldSpaceMatrixInverse.copy(this._worldSpaceMatrix).invert())}applyRotation(e){const t=this.rotation.x!==0||this.rotation.y!==0||this.rotation.z!==0;return t&&(this._rotation.x=I.toRadians(this.rotation.x),this._rotation.y=I.toRadians(this.rotation.y),this._rotation.z=I.toRadians(this.rotation.z),this._rotation.order="ZYX",e.applyEuler(this._rotation)),t}_vector=new c.Vector3(0,0,0);_temp=new c.Vector3(0,0,0);_triangle=new c.Triangle;onInitialize(e){this._vector.set(0,0,0),e.mesh=void 0,e.mesh_geometry=void 0;const t=this._temp.copy(this.position),i=this._space===1;i&&t.applyQuaternion(this.system.worldQuaternion);let n=this.radius;if(i&&(n*=this.system.worldScale.x),this.enabled){switch(this.shapeType){case 5:cd&&B.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(t);break;case 4:this.randomConePoint(this.position,this.angle,n,this.radiusThickness,this.arc,this.arcMode,this._vector);break;case 0:this.randomSpherePoint(this.position,n,this.radiusThickness,this.arc,this._vector);break;case 10:this.randomCirclePoint(this.position,n,this.radiusThickness,this.arc,this._vector);break;case 13:const o=this.meshRenderer;o?.destroyed==!1&&this.setMesh(o);const r=e.mesh=this._meshObj,a=e.mesh_geometry=this._meshGeometry;if(r&&a)switch(this.meshShapeType){case 0:{const l=a.getAttribute("position"),h=Math.floor(Math.random()*l.count);this._vector.fromBufferAttribute(l,h),this._vector.applyMatrix4(r.matrixWorld),e.mesh_normal=h}break;case 1:break;case 2:{const l=a.index;if(l){let h=Math.random(),d=Math.random();h+d>1&&(h=1-h,d=1-d);const u=Math.floor(Math.random()*(l.count/3));let p=u*3,m=u*3+1,y=u*3+2;p=l.getX(p),m=l.getX(m),y=l.getX(y);const _=a.getAttribute("position");this._triangle.a.fromBufferAttribute(_,p),this._triangle.b.fromBufferAttribute(_,m),this._triangle.c.fromBufferAttribute(_,y),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),e.mesh_normal=u}}break}break;default:this._vector.set(0,0,0),A()&&!globalThis.__particlesystem_shapetype_unsupported&&(console.warn("ParticleSystem ShapeType is not supported:",hu[this.shapeType]),globalThis.__particlesystem_shapetype_unsupported=!0);break}this.randomizePosition(this._vector,this.randomPositionAmount)}this.applyRotation(this._vector),i&&(this._vector.applyQuaternion(this.system.worldQuaternion),this._vector.add(this.system.worldPos)),cd&&B.DrawSphere(this._vector,.03,16711680,.5,!0)}_dir=new c.Vector3;getDirection(e,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 i=t.x,n=t.y,o=t.z;this._dir.set(i,n,o),this.system?.worldspace?this._dir.sub(this.system.worldPos):this._dir.sub(this.position);break;case 13:const r=e.mesh,a=e.mesh_geometry;if(r&&a)switch(this.meshShapeType){case 0:{const l=a.getAttribute("normal"),h=e.mesh_normal;this._dir.fromBufferAttribute(l,h)}break;case 1:break;case 2:{const l=a.index;if(l){const h=e.mesh_normal,d=l.getX(h*3),u=l.getX(h*3+1),p=l.getX(h*3+2),m=a.getAttribute("position"),y=F(),_=F(),g=F();y.fromBufferAttribute(m,d),_.fromBufferAttribute(m,u),g.fromBufferAttribute(m,p),y.sub(_),g.sub(_),y.cross(g),this._dir.copy(y).multiplyScalar(-1);const v=pe(r);this._dir.applyQuaternion(v)}}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),cd&&(B.DrawSphere(t,.01,8925952,.5,!0),B.DrawDirection(t,this._dir,8925952,.5,!0)),this._dir}static _randomQuat=new c.Quaternion;static _tempVec=new c.Vector3;randomizePosition(e,t){if(t<=0)return;const i=Yl._tempVec;i.set(Math.random()*2-1,Math.random()*2-1,Math.random()*2-1),i.x*=t*this.scale.x,i.y*=t*this.scale.y,i.z*=t*this.scale.z,e.add(i)}randomizeDirection(e,t){if(t===0)return;const i=Yl._randomQuat,n=Yl._tempVec;n.set(Math.random()-.5,Math.random()-.5,Math.random()-.5).normalize(),i.setFromAxisAngle(n,t*Math.random()*Math.PI),e.applyQuaternion(i)}spherizeDirection(e,t){if(t===0)return;const i=Math.random()*Math.PI*2,n=Math.acos(1-Math.random()*2),o=Math.sin(n)*Math.cos(i),r=Math.sin(n)*Math.sin(i),a=Math.cos(n),l=new c.Vector3(o,r,a);e.lerp(l,t)}randomSpherePoint(e,t,i,n,o){const r=Math.random(),a=Math.random(),l=2*Math.PI*r*(n/360),h=Math.acos(2*a-1),d=I.lerp(1,1-Math.pow(1-Math.random(),Math.PI),i)*t,u=e.x+this.scale.x*(-d*Math.sin(h)*Math.cos(l)),p=e.y+this.scale.y*(d*Math.sin(h)*Math.sin(l)),m=e.z+this.scale.z*(d*Math.cos(h));o.x=u,o.y=p,o.z=m}randomCirclePoint(e,t,i,n,o){const r=Math.random(),a=2*Math.PI*r*(n/360),l=I.lerp(1,1-Math.pow(1-Math.random(),Math.PI),i)*t,h=e.x+this.scale.x*l*Math.cos(a),d=e.y+this.scale.y*l*Math.sin(a),u=e.z;o.x=h,o.y=d,o.z=u}_loopTime=0;_loopDirection=1;randomConePoint(e,t,i,n,o,r,a){let l=0,h=0;switch(r){case 0:l=Math.random(),h=Math.random();break;case 2:this._loopTime>1&&(this._loopDirection=-1),this._loopTime<0&&(this._loopDirection=1);case 1:l=.5,h=Math.random(),this._loopTime+=this.system.deltaTime*this._loopDirection;break}let d=2*Math.PI*l*(o/360);switch(r){case 2:case 1:d+=Math.PI+.5,d+=this._loopTime*Math.PI*2,d%=I.toRadians(o);break}const u=Math.acos(2*h-1),p=I.lerp(1,1-Math.pow(1-Math.random(),Math.PI),n)*i,m=e.x+-p*Math.sin(u)*Math.cos(d),y=e.y+p*Math.sin(u)*Math.sin(d),_=e.z;a.x=m*this.scale.x,a.y=y*this.scale.y,a.z=_*this.scale.z}};C([f()],Ye.prototype,"shapeType");C([f()],Ye.prototype,"enabled");C([f()],Ye.prototype,"alignToDirection");C([f()],Ye.prototype,"angle");C([f()],Ye.prototype,"arc");C([f()],Ye.prototype,"arcSpread");C([f()],Ye.prototype,"arcSpeedMultiplier");C([f()],Ye.prototype,"arcMode");C([f(c.Vector3)],Ye.prototype,"boxThickness");C([f(c.Vector3)],Ye.prototype,"position");C([f(c.Vector3)],Ye.prototype,"rotation");C([f(c.Vector3)],Ye.prototype,"scale");C([f()],Ye.prototype,"radius");C([f()],Ye.prototype,"radiusThickness");C([f()],Ye.prototype,"sphericalDirectionAmount");C([f()],Ye.prototype,"randomDirectionAmount");C([f()],Ye.prototype,"randomPositionAmount");C([f()],Ye.prototype,"meshShapeType");C([f(lh)],Ye.prototype,"meshRenderer");let ky=Ye;class me{damping;enabled;frequency;octaveCount;octaveMultiplier;octaveScale;positionAmount;quality;remap;remapEnabled;remapMultiplier;remapX;remapXMultiplier;remapY;remapYMultiplier;remapZ;remapZMultiplier;scrollSpeedMultiplier;separateAxes;strengthMultiplier;strengthX;strengthXMultiplier;strengthY;strengthYMultiplier;strengthZ;strengthZMultiplier;_noise;_time=0;update(e){this._time+=e.time.deltaTime*this.scrollSpeedMultiplier}_temp=new c.Vector3;apply(e,t,i,n,o,r){if(!this.enabled)return;this._noise||(this._noise=le.createNoise4D(()=>0));const a=this._temp.set(t.x,t.y,t.z).multiplyScalar(this.frequency),l=this._noise(a.x,a.y,a.z,this._time),h=this._noise(a.x,a.y,a.z,this._time+1e3*this.frequency),d=this._noise(a.x,a.y,a.z,this._time+2e3*this.frequency);this._temp.set(l,h,d).normalize();const u=o/r;let p=this.positionAmount.evaluate(u);this.separateAxes?(this._temp.x*=p*this.strengthXMultiplier,this._temp.y*=p*this.strengthYMultiplier,this._temp.z*=p*this.strengthZMultiplier):(this.strengthX&&(p*=this.strengthX.evaluate(u)*1.5),this._temp.multiplyScalar(p)),i.x+=this._temp.x,i.y+=this._temp.y,i.z+=this._temp.z}}C([f()],me.prototype,"damping");C([f()],me.prototype,"enabled");C([f()],me.prototype,"frequency");C([f()],me.prototype,"octaveCount");C([f()],me.prototype,"octaveMultiplier");C([f()],me.prototype,"octaveScale");C([f(H)],me.prototype,"positionAmount");C([f()],me.prototype,"quality");C([f(H)],me.prototype,"remap");C([f()],me.prototype,"remapEnabled");C([f()],me.prototype,"remapMultiplier");C([f(H)],me.prototype,"remapX");C([f()],me.prototype,"remapXMultiplier");C([f(H)],me.prototype,"remapY");C([f()],me.prototype,"remapYMultiplier");C([f(H)],me.prototype,"remapZ");C([f()],me.prototype,"remapZMultiplier");C([f()],me.prototype,"scrollSpeedMultiplier");C([f()],me.prototype,"separateAxes");C([f()],me.prototype,"strengthMultiplier");C([f(H)],me.prototype,"strengthX");C([f()],me.prototype,"strengthXMultiplier");C([f(H)],me.prototype,"strengthY");C([f()],me.prototype,"strengthYMultiplier");C([f(H)],me.prototype,"strengthZ");C([f()],me.prototype,"strengthZMultiplier");class Le{enabled;attachRibbonToTransform=!1;colorOverLifetime;colorOverTrail;dieWithParticles=!0;inheritParticleColor=!0;lifetime;lifetimeMultiplier;minVertexDistance=.2;mode=0;ratio=1;ribbonCount=1;shadowBias=0;sizeAffectsLifetime=!1;sizeAffectsWidth=!1;splitSubEmitterRibbons=!1;textureMode=0;widthOverTrail;widthOverTrailMultiplier;worldSpace=!1;getWidth(e,t,i,n){const o=this.widthOverTrail.evaluate(i,n);return e*=o,e}getColor(e,t,i){const n=this.colorOverTrail.evaluate(i),o=this.colorOverLifetime.evaluate(t);e.x*=n.r*o.r,e.y*=n.g*o.g,e.z*=n.b*o.b,"alpha"in n&&"alpha"in o&&(e.w*=n.alpha*o.alpha)}}C([f()],Le.prototype,"enabled");C([f()],Le.prototype,"attachRibbonToTransform");C([f(Lr)],Le.prototype,"colorOverLifetime");C([f(Lr)],Le.prototype,"colorOverTrail");C([f()],Le.prototype,"dieWithParticles");C([f()],Le.prototype,"inheritParticleColor");C([f(H)],Le.prototype,"lifetime");C([f()],Le.prototype,"lifetimeMultiplier");C([f()],Le.prototype,"minVertexDistance");C([f()],Le.prototype,"mode");C([f()],Le.prototype,"ratio");C([f()],Le.prototype,"ribbonCount");C([f()],Le.prototype,"shadowBias");C([f()],Le.prototype,"sizeAffectsLifetime");C([f()],Le.prototype,"sizeAffectsWidth");C([f()],Le.prototype,"splitSubEmitterRibbons");C([f()],Le.prototype,"textureMode");C([f(H)],Le.prototype,"widthOverTrail");C([f()],Le.prototype,"widthOverTrailMultiplier");C([f()],Le.prototype,"worldSpace");class Fe{enabled;space=0;orbitalX;orbitalY;orbitalZ;orbitalXMultiplier;orbitalYMultiplier;orbitalZMultiplier;orbitalOffsetX;orbitalOffsetY;orbitalOffsetZ;speedModifier;speedModifierMultiplier;x;xMultiplier;y;yMultiplier;z;zMultiplier;_system;update(e){this._system=e}_temp=new c.Vector3;_temp2=new c.Vector3;_temp3=new c.Vector3;_hasOrbital=!1;_index=0;_orbitalMatrix=new c.Matrix4;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,i,n,o,r,a){if(!this.enabled)return;const l=r/a,h=this.speedModifier.evaluate(l)*this.speedModifierMultiplier,d=this.x.evaluate(l),u=this.y.evaluate(l),p=this.z.evaluate(l);if(this._temp.set(-d,u,p),this._system&&this._system.main.simulationSpace===1&&this._temp.applyQuaternion(this._system.worldQuaternion),this._hasOrbital&&this._system?.worldPos){const y=this._temp2.set(i.x,i.y,i.z),_=this.orbitalXMultiplier,g=this.orbitalYMultiplier,v=this.orbitalZMultiplier,b=h*Math.PI*2*10,w=Math.cos(b*_),R=Math.sin(b*_),O=Math.cos(b*g),M=Math.sin(b*g),D=Math.cos(b*v),L=Math.sin(b*v),j=y.x*(O*D)+y.y*(O*L)+y.z*-M,V=y.x*(R*M*D-w*L)+y.y*(R*M*L+w*D)+y.z*(R*O),W=y.x*(w*M*D+R*L)+y.y*(w*M*L-R*D)+y.z*(w*O),k=this._temp3.set(y.x-j,y.y-V,y.z-W);k.normalize(),k.multiplyScalar(.2/o*Math.max(this.orbitalXMultiplier,this.orbitalYMultiplier,this.orbitalZMultiplier)),n.x+=k.x,n.y+=k.y,n.z+=k.z}n.x+=this._temp.x,n.y+=this._temp.y,n.z+=this._temp.z,n.x*=h,n.y*=h,n.z*=h}}C([f()],Fe.prototype,"enabled");C([f()],Fe.prototype,"space");C([f(H)],Fe.prototype,"orbitalX");C([f(H)],Fe.prototype,"orbitalY");C([f(H)],Fe.prototype,"orbitalZ");C([f()],Fe.prototype,"orbitalXMultiplier");C([f()],Fe.prototype,"orbitalYMultiplier");C([f()],Fe.prototype,"orbitalZMultiplier");C([f()],Fe.prototype,"orbitalOffsetX");C([f()],Fe.prototype,"orbitalOffsetY");C([f()],Fe.prototype,"orbitalOffsetZ");C([f(H)],Fe.prototype,"speedModifier");C([f()],Fe.prototype,"speedModifierMultiplier");C([f(H)],Fe.prototype,"x");C([f()],Fe.prototype,"xMultiplier");C([f(H)],Fe.prototype,"y");C([f()],Fe.prototype,"yMultiplier");C([f(H)],Fe.prototype,"z");C([f()],Fe.prototype,"zMultiplier");class It{animation;enabled;cycleCount;frameOverTime;frameOverTimeMultiplier;numTilesX;numTilesY;startFrame;startFrameMultiplier;rowMode;rowIndex;spriteCount;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 i=this.frameOverTime.evaluate(e%1);return i*=this.frameOverTimeMultiplier,i*=t,i=i%t,i=Math.floor(i),i}}C([f()],It.prototype,"animation");C([f()],It.prototype,"enabled");C([f()],It.prototype,"cycleCount");C([f(H)],It.prototype,"frameOverTime");C([f()],It.prototype,"frameOverTimeMultiplier");C([f()],It.prototype,"numTilesX");C([f()],It.prototype,"numTilesY");C([f(H)],It.prototype,"startFrame");C([f()],It.prototype,"startFrameMultiplier");C([f()],It.prototype,"rowMode");C([f()],It.prototype,"rowIndex");C([f()],It.prototype,"spriteCount");C([f()],It.prototype,"timeMode");class _n{enabled;separateAxes;x;xMultiplier;y;yMultiplier;z;zMultiplier;evaluate(e,t){return this.enabled?this.separateAxes?0:this.z.evaluate(e,t)*-1:0}}C([f()],_n.prototype,"enabled");C([f()],_n.prototype,"separateAxes");C([f(H)],_n.prototype,"x");C([f()],_n.prototype,"xMultiplier");C([f(H)],_n.prototype,"y");C([f()],_n.prototype,"yMultiplier");C([f(H)],_n.prototype,"z");C([f()],_n.prototype,"zMultiplier");class Qi{enabled;range;separateAxes;x;xMultiplier;y;yMultiplier;z;zMultiplier;evaluate(e,t){if(!this.enabled)return 0;if(!this.separateAxes){const i=I.lerp(this.range.x,this.range.y,t);return this.z.evaluate(i)*-1}return 0}}C([f()],Qi.prototype,"enabled");C([f()],Qi.prototype,"range");C([f()],Qi.prototype,"separateAxes");C([f(H)],Qi.prototype,"x");C([f()],Qi.prototype,"xMultiplier");C([f(H)],Qi.prototype,"y");C([f()],Qi.prototype,"yMultiplier");C([f(H)],Qi.prototype,"z");C([f()],Qi.prototype,"zMultiplier");class nt{enabled;dampen;drag;dragMultiplier;limit;limitMultiplier;separateAxes;limitX;limitXMultiplier;limitY;limitYMultiplier;limitZ;limitZMultiplier;multiplyDragByParticleSize=!1;multiplyDragByParticleVelocity=!1;space;_temp=new c.Vector3;_temp2=new c.Vector3;apply(e,t,i,n,o,r,a){if(this.enabled){const l=this.limit.evaluate(o)*this.limitMultiplier;if(t.length()>l){this._temp.copy(t).normalize().multiplyScalar(l);const d=this.dampen*.5;t.x=I.lerp(t.x,this._temp.x,d),t.y=I.lerp(t.y,this._temp.y,d),t.z=I.lerp(t.z,this._temp.z,d),i.x=I.lerp(i.x,this._temp.x,d),i.y=I.lerp(i.y,this._temp.y,d),i.z=I.lerp(i.z,this._temp.z,d)}}}}C([f()],nt.prototype,"enabled");C([f()],nt.prototype,"dampen");C([f(H)],nt.prototype,"drag");C([f()],nt.prototype,"dragMultiplier");C([f(H)],nt.prototype,"limit");C([f()],nt.prototype,"limitMultiplier");C([f()],nt.prototype,"separateAxes");C([f(H)],nt.prototype,"limitX");C([f()],nt.prototype,"limitXMultiplier");C([f(H)],nt.prototype,"limitY");C([f()],nt.prototype,"limitYMultiplier");C([f(H)],nt.prototype,"limitZ");C([f()],nt.prototype,"limitZMultiplier");C([f()],nt.prototype,"multiplyDragByParticleSize");C([f()],nt.prototype,"multiplyDragByParticleVelocity");C([f()],nt.prototype,"space");const _h=class bx{enabled;curve;curveMultiplier;mode;clone(){const e=new bx;return e.enabled=this.enabled,e.curve=this.curve?.clone(),e.curveMultiplier=this.curveMultiplier,e.mode=this.mode,e}system;get _lastWorldPosition(){return this.system._iv_lastWorldPosition||(this.system._iv_lastWorldPosition=new c.Vector3),this.system._iv_lastWorldPosition}get _velocity(){return this.system._iv_velocity||(this.system._iv_velocity=new c.Vector3),this.system._iv_velocity}_temp=new c.Vector3;_firstUpdate=!0;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}}_frames=0;applyCurrent(e,t,i){if(this.enabled&&this.system&&this.system.worldspace!==!1&&this.mode===1){const n=this.curve.evaluate(t,i);this._temp.copy(this._velocity).multiplyScalar(n),e.x+=this._temp.x,e.y+=this._temp.y,e.z+=this._temp.z}}};C([f()],_h.prototype,"enabled");C([f(H)],_h.prototype,"curve");C([f()],_h.prototype,"curveMultiplier");C([f()],_h.prototype,"mode");let Ey=_h;class di{enabled;range;separateAxes;size;sizeMultiplier;x;xMultiplier;y;yMultiplier;z;zMultiplier;evaluate(e,t,i,n){const o=e.length(),r=I.remap(o,this.range.x,this.range.y,0,1),a=this.size.evaluate(r,i);return n.x*=a,n.y*=a,n.z*=a,n}}C([f()],di.prototype,"enabled");C([f(c.Vector2)],di.prototype,"range");C([f()],di.prototype,"separateAxes");C([f(H)],di.prototype,"size");C([f()],di.prototype,"sizeMultiplier");C([f(H)],di.prototype,"x");C([f()],di.prototype,"xMultiplier");C([f(H)],di.prototype,"y");C([f()],di.prototype,"yMultiplier");C([f(H)],di.prototype,"z");C([f()],di.prototype,"zMultiplier");class rl{enabled;range;color;evaluate(e,t,i){const n=e.length(),o=I.remap(n,this.range.x,this.range.y,0,1),r=this.color.evaluate(o,t);i.x*=r.r,i.y*=r.g,i.z*=r.b,"alpha"in r&&(i.w*=r.alpha)}}C([f()],rl.prototype,"enabled");C([f(c.Vector2)],rl.prototype,"range");C([f(Lr)],rl.prototype,"color");new c.Vector3(1,1,1);new c.Vector3(0,0,1);class Ry{constructor(e,t,i,n){this.system=e,this.particleSystem=t,this.subSystem=i,this.subParticleSystem=n,this.subParticleSystem&&this.subParticleSystem&&(this.subParticleSystem.onlyUsedByOther=!0);const o=1e3;this._circularBuffer=new _i(()=>new le.Matrix4,o)}type="NeedleParticleSubEmitter";emitterType;emitterProbability;q_=new c.Quaternion;v_=new c.Vector3;v2_=new c.Vector3;_emitterMatrix=new le.Matrix4;_circularBuffer;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===Sm.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===Sm.Death){let n=e.life;if(e[ga]!==void 0&&(n=e[ga]),!(e.age+t*1.2>=n))return;const r=this.subSystem.main.maxParticles-this.subSystem.currentParticles;e.emissionState.waitEmiting=r}const i=new le.Matrix4;i.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||i.multiplyMatrices(this._emitterMatrix,i),this.subParticleSystem.emit(t,e.emissionState,i)}}var IE=Object.defineProperty,Ie=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&IE(e,t,n),n};const Js=x("debugparticles"),jE=x("noprogressive"),BE=x("debugprogressive");var Sm=(s=>(s[s.Birth=0]="Birth",s[s.Collision=1]="Collision",s[s.Death=2]="Death",s[s.Trigger=3]="Trigger",s[s.Manual=4]="Manual",s))(Sm||{});class Yi extends E{renderMode;particleMaterial;trailMaterial;particleMesh;maxParticleSize;minParticleSize;velocityScale;cameraVelocityScale;lengthScale;start(){if(this.maxParticleSize!==.5&&this.minParticleSize!==0&&A()){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(){return this.particleMaterial?.transparent??!1}getMaterial(e=!1){let t=e===!0&&this.trailMaterial?this.trailMaterial:this.particleMaterial;if(t){if(t.type==="MeshStandardMaterial"){Js&&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=c.LinearSRGBColorSpace,t.map.premultiplyAlpha=!1);const i=new c.MeshBasicMaterial;i.copy(t),e?this.trailMaterial=i:this.particleMaterial=i}t.map&&(t.map.colorSpace=c.LinearSRGBColorSpace,t.map.premultiplyAlpha=!1),e&&t.side===c.FrontSide&&(t=t.clone(),t.side=c.BackSide,e?this.trailMaterial=t:this.particleMaterial=t)}return t&&!jE&&t._didRequestTextureLOD===void 0&&(t._didRequestTextureLOD=0,BE&&console.log("Load material LOD",t.name),re.NEEDLE_progressive.assignTextureLOD(t,0)),t}getMesh(e){let t=null;if(!t&&(this.particleMesh instanceof c.Mesh&&(t=this.particleMesh.geometry),t===null)){t=new c.PlaneGeometry(1,1);const n=t.attributes.uv;for(let o=0;o<n.count;o++)n.setX(o,1-n.getX(o))}return new c.Mesh(t,this.getMaterial())}}Ie([f()],Yi.prototype,"renderMode");Ie([f(c.Material)],Yi.prototype,"particleMaterial");Ie([f(c.Material)],Yi.prototype,"trailMaterial");Ie([f()],Yi.prototype,"maxParticleSize");Ie([f()],Yi.prototype,"minParticleSize");Ie([f()],Yi.prototype,"velocityScale");Ie([f()],Yi.prototype,"cameraVelocityScale");Ie([f()],Yi.prototype,"lengthScale");class hd{_curve;_factor;constructor(e,t=1){this._curve=e,this._factor=t}type="function";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 Ty{type="value";toJSON(){throw new Error("Method not implemented.")}clone(){throw new Error("Method not implemented.")}startGen(e){}system;constructor(e){this.system=e}}class FE extends Ty{genValue(){return this.system.textureSheetAnimation.getStartIndex()}}class UE extends Ty{_lastPosition=new c.Vector3;_lastDistance=0;update(){const e=Y(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 n=this.system.emission.rateOverDistance.evaluate(this.system.time/this.system.duration,Math.random());let r=this._lastDistance/this.system.deltaTime*n;Number.isFinite(r)||(r=0),e+=r}const t=this.system.emission.getBurst();t>0&&(e+=t/this.system.deltaTime);const i=this.system.maxParticles-this.system.currentParticles;return I.clamp(e,0,i/this.system.deltaTime)}}class zE extends Ty{genValue(){return this.system.isPlaying,0}}class Mo{system;get context(){return this.system.context}constructor(e){this.type=Object.getPrototypeOf(this).constructor.name||"ParticleSystemBaseBehaviour",e&&(this.system=e)}type;initialize(e){}update(e,t){}frameUpdate(e){}toJSON(){throw new Error("Method not implemented.")}clone(){throw new Error("Method not implemented.")}reset(){}}class NE extends Mo{type="NeedleTextureSheet";update(e,t){const i=this.system.textureSheetAnimation;if(i.enabled){const n=e.age/e.life,o=i.evaluate(n);o!==void 0&&(e.uvTile=o)}}}const $b=Symbol("particleRotation");class VE extends Mo{type="NeedleRotation";initialize(e){e[$b]=Math.random()}update(e,t){if(e.rotation===void 0)return;const i=e.age/e.life;if(typeof e.rotation=="number"&&(this.system.rotationOverLifetime.enabled?e.rotation+=this.system.rotationOverLifetime.evaluate(i,e[$b])*t:this.system.renderer.renderMode===rs.Billboard&&(e.rotation=Math.PI),this.system.rotationBySpeed.enabled)){const n=e.velocity.length();e.rotation+=this.system.rotationBySpeed.evaluate(i,n)*t}}}const Wb=Symbol("sizeLerpFactor"),$E=new c.Vector3;class WE extends Mo{type="NeedleSize";_minSize=0;_maxSize=1;initialize(e){e[Wb]=Math.random(),this._minSize=this.system.renderer.minParticleSize,this._maxSize=this.system.renderer.maxParticleSize}update(e,t){const i=e.age/e.life;let n=1;this.system.sizeOverLifetime.enabled&&(n*=this.system.sizeOverLifetime.evaluate(i,void 0,e[Wb]).x);let o=1;this.system.renderer.renderMode!==rs.Mesh&&(o=this.system.worldScale.x/this.system.cameraScale);const r=F(e.startSize).multiplyScalar(n*o);if(e.size.set(r.x,r.y,r.z),this.system.localspace){const a=vx(this.system,$E);e.size.x*=a.x,e.size.y*=a.y,e.size.z*=a.z}}}const ga=Symbol("particleLife"),gp=Symbol("trailLifetime"),Gb=Symbol("trailStartLength"),yp=Symbol("trailWidthRandom");class GE extends Mo{type="NeedleTrail";initialize(e){e instanceof le.TrailParticle&&(e[ga]=e.life,this.system.trails.enabled&&this.system.trails.dieWithParticles===!1&&(e[gp]=this.system.trails.lifetime.evaluate(Math.random(),Math.random()),e.life+=e[gp]),e[Gb]=e.length,e[yp]=Math.random())}update(e){if(this.system.trails?.enabled&&e instanceof le.TrailParticle){const t=e,i=e.age/e[ga],n=e.previous.values(),o=e.previous.length;for(let r=0;r<o;r++){const l=n.next().value,h=1-r/(o-1),d=e.size;if(d.x<=0&&!this.system.trails.sizeAffectsWidth){const u=20*this.system.trails.widthOverTrail.evaluate(.5,t[yp]);d.x=u,d.y=u,d.z=u}l.size=this.system.trails.getWidth(d.x,i,h,t[yp]),l.color.copy(e.color),this.system.trails.getColor(l.color,i,h)}if(e.age>e[ga]){e.velocity.set(0,0,0);const r=(e.age-e[ga])/e[gp];t.length=I.lerp(e[Gb],0,r)}}}}const dd=Symbol("startVelocity"),Hb=Symbol("gravityModifier"),_p=Symbol("gravitySpeed"),ud=Symbol("velocity lerp factor"),Cm=new c.Vector3;class HE extends Mo{type="NeedleVelocity";_gravityDirection=new c.Vector3;initialize(e){const t=this.system.main.simulationSpeed;e.startSpeed=this.system.main.startSpeed.evaluate(Math.random(),Math.random());const i=this.system.shape.getDirection(e,e.position);e.velocity.x=i.x*e.startSpeed,e.velocity.y=i.y*e.startSpeed,e.velocity.z=i.z*e.startSpeed,this.system.inheritVelocity?.enabled&&this.system.inheritVelocity.applyInitial(e.velocity),e[dd]?e[dd].copy(e.velocity):e[dd]=e.velocity.clone();const n=this.system.main.gravityModifier.evaluate(Math.random(),Math.random());e[Hb]=n*t,e[_p]=n*t*.5,e[ud]=Math.random(),this.system.velocityOverLifetime?.init(e),this._gravityDirection.set(0,-1,0),this.system.main.simulationSpace===Lc.Local&&this._gravityDirection.applyQuaternion(this.system.worldQuaternionInverted).normalize()}update(e,t){const i=e[dd],n=e[Hb];if(n!==0){const u=n*e[_p];Cm.copy(this._gravityDirection).multiplyScalar(u),e[_p]+=t*.05,i.add(Cm)}e.velocity.copy(i);const o=e.age/e.life;this.system.inheritVelocity?.enabled&&this.system.inheritVelocity.applyCurrent(e.velocity,o,e[ud]);const r=this.system.noise;r.enabled&&r.apply(0,e.position,e.velocity,t,e.age,e.life);const a=this.system.sizeBySpeed;a?.enabled&&(e.size=a.evaluate(e.velocity,o,e[ud],e.size));const l=this.system.colorBySpeed;l?.enabled&&l.evaluate(e.velocity,e[ud],e.color);const h=this.system.velocityOverLifetime;h.enabled&&h.apply(e,0,e.position,e.velocity,t,e.age,e.life);const d=this.system.limitVelocityOverLifetime;if(d.enabled&&d.apply(e.position,i,e.velocity,e.size,o,t,1),this.system.worldspace){const u=this.system.worldScale;e.velocity.x*=u.x,e.velocity.y*=u.y,e.velocity.z*=u.z}}}const qb=Symbol("colorLerpFactor"),Xb=new te(1,1,1,1),zo=new te(1,1,1,1);class qE extends Mo{type="NeedleColor";initialize(e){}_init(e){const t=this.system.renderer.particleMaterial;zo.copy(this.system.main.startColor.evaluate(Math.random())),t?.color&&(Xb.copy(t.color),zo.multiply(Xb)),zo.convertLinearToSRGB(),e.startColor.set(zo.r,zo.g,zo.b,zo.alpha),e.color.copy(e.startColor),e[qb]=Math.random()}update(e,t){if(e.age===0&&this._init(e),this.system.colorOverLifetime.enabled){const i=e.age/e.life,n=this.system.colorOverLifetime.color.evaluate(i,e[qb]);e.color.set(n.r,n.g,n.b,"alpha"in n?n.alpha:1).multiply(e.startColor)}else e.color.copy(e.startColor)}}class XE{system;emission;get anim(){return this.system.textureSheetAnimation}constructor(e){this.system=e,this.emission=new UE(this.system)}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()}autoDestroy;get looping(){return this.system.main.loop}get duration(){return this.system.duration}get shape(){return this.system.shape}get startLife(){return new hd(this.system.main.startLifetime)}get startSpeed(){return new hd(this.system.main.startSpeed)}get startRotation(){return new hd(this.system.main.startRotation)}get startSize(){return new hd(this.system.main.startSize)}startLength;get startColor(){return new le.ConstantColor(new le.Vector4(1,1,1,1))}get emissionOverTime(){return this.emission}get emissionOverDistance(){return new zE(this.system)}emissionBursts;onlyUsedByOther;behaviors=[];get instancingGeometry(){return this.system.renderer.getMesh(this.system.renderer.renderMode).geometry}get renderMode(){if(this.system.trails.enabled===!0)return le.RenderMode.Trail;switch(this.system.renderer.renderMode){case rs.Billboard:return le.RenderMode.BillBoard;case rs.Stretch:return le.RenderMode.StretchedBillBoard;case rs.HorizontalBillboard:return le.RenderMode.HorizontalBillBoard;case rs.VerticalBillboard:return le.RenderMode.VerticalBillBoard;case rs.Mesh:return le.RenderMode.Mesh}return le.RenderMode.BillBoard}rendererEmitterSettings={startLength:new le.ConstantValue(220),followLocalOrigin:!1};get speedFactor(){let e=this.system.main.simulationSpeed;return this.system.renderer?.renderMode===rs.Stretch&&(e*=this.system.renderer.velocityScale??1),e}flatWhiteTexture;clonedTexture={original:void 0,clone:void 0};get texture(){const e=this.material;if(e&&e.map){const t=e.map;if(this.clonedTexture.original!==t||!this.clonedTexture.clone){const i=t.clone();i.premultiplyAlpha=!1,i.colorSpace=c.LinearSRGBColorSpace,this.clonedTexture.original=t,this.clonedTexture.clone=i}return this.clonedTexture.clone}return this.flatWhiteTexture||(this.flatWhiteTexture=cg(new te(1,1,1,1),1)),this.flatWhiteTexture}get startTileIndex(){return new FE(this.system)}get uTileCount(){return this.anim.enabled?this.anim?.numTilesX:void 0}get vTileCount(){return this.anim.enabled?this.anim?.numTilesY:void 0}get renderOrder(){return 1}get blending(){return this.system.renderer.particleMaterial?.blending??c.NormalBlending}get transparent(){return this.system.renderer.transparent}get worldSpace(){return this.system.main.simulationSpace===Lc.World}}class QE{burstParticleIndex=0;burstParticleCount=0;isBursting=!1;travelDistance=0;previousWorldPos;burstIndex=0;burstWaveIndex=0;time=0;waitEmiting=0}const jt=class Bd extends E{play(e=!1){e&&S.foreachComponent(this.gameObject,t=>{t instanceof Bd&&t!==this&&t.play(!1)},!0),this._isPlaying=!0,this._particleSystem&&(this._particleSystem.emissionState.time=0,this._particleSystem.emitEnded=!1),this.emission?.reset()}pause(e=!0){e&&S.foreachComponent(this.gameObject,t=>{t instanceof Bd&&t!==this&&t.pause(!1)},!0),this._isPlaying=!1}stop(e=!0,t=!1){e&&S.foreachComponent(this.gameObject,i=>{i instanceof Bd&&i!==this&&i.stop(!1,t)},!0),this._isPlaying=!1,this._time=0,t&&this.reset()}reset(){this._time=0,this._particleSystem&&(this._particleSystem.particleNum=0,this._particleSystem.emissionState.time=0,this._particleSystem.emitEnded=!1,this.emission?.reset())}_state;emit(e){if(this._particleSystem){this.onUpdate(),e=Math.min(e,this.maxParticles-this.currentParticles),this._state||(this._state=new QE),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}colorOverLifetime;main;emission;sizeOverLifetime;shape;noise;trails;velocityOverLifetime;limitVelocityOverLifetime;inheritVelocity;colorBySpeed;textureSheetAnimation;rotationOverLifetime;rotationBySpeed;sizeBySpeed;get renderer(){return this._renderer}get isPlaying(){return this._isPlaying}get currentParticles(){return this._particleSystem?.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}_cameraScale=1;get container(){return this._container}get worldspace(){return this.main.simulationSpace===Lc.World}get localspace(){return this.main.simulationSpace===Lc.Local}__worldQuaternion=new c.Quaternion;get worldQuaternion(){return this.__worldQuaternion}_worldQuaternionInverted=new c.Quaternion;get worldQuaternionInverted(){return this._worldQuaternionInverted}_worldScale=new c.Vector3;get worldScale(){return this._worldScale}_worldPositionFrame=-1;_worldPos=new c.Vector3;get worldPos(){return this._worldPositionFrame!==this.context.time.frame&&(this._worldPositionFrame=this.context.time.frame,Y(this.gameObject,this._worldPos)),this._worldPos}get matrixWorld(){return this._container.matrixWorld}get isSubsystem(){return this._isUsedAsSubsystem}addBehaviour(e){return this._particleSystem?(e instanceof Mo&&(e.system=this),Js&&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,i=t.indexOf(e);return i!==-1&&((A()||Js)&&console.debug("Remove custom ParticleSystem Behaviour",i,e),t.splice(i,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}_renderer;_batchSystem;_particleSystem;_interface;_container;_time=0;_isPlaying=!0;_isUsedAsSubsystem=!1;_didPreWarm=!1;set bursts(e){for(let t=0;t<e.length;t++){const i=e[t];if(!(i instanceof du)){const n=new du;Ra(n,i),e[t]=n}}this._bursts=e}_bursts;set subEmitterSystems(e){for(let t=0;t<e.length;t++){const i=e[t];if(!(i instanceof uu)){const n=new uu;Ra(n,i),e[t]=n}}Js&&e.length>0&&console.log("SubEmitters: ",e,this),this._subEmitterSystems=e}_subEmitterSystems;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(Yi),!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 c.Object3D,this._container.matrixAutoUpdate=!1,this.context.scene.add(this._container),this._batchSystem=new le.BatchedParticleRenderer,this._batchSystem.name=this.gameObject.name,this._container.add(this._batchSystem),this._interface=new XE(this),this._particleSystem=new le.ParticleSystem(this._interface),this._particleSystem.addBehavior(new WE(this)),this._particleSystem.addBehavior(new qE(this)),this._particleSystem.addBehavior(new NE(this)),this._particleSystem.addBehavior(new VE(this)),this._particleSystem.addBehavior(new HE(this)),this._particleSystem.addBehavior(new GE(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),Js&&(console.log(this),this.gameObject.add(new c.AxesHelper(1)))}start(){this.addSubParticleSystems(),this.updateLayers(),this.renderer.particleMesh instanceof c.Mesh&&this._interface.renderMode==le.RenderMode.Mesh&&re.NEEDLE_progressive.assignMeshLOD(this.renderer.particleMesh,0).then(e=>{e&&this.particleSystem&&this._interface.renderMode==le.RenderMode.Mesh&&(this.particleSystem.instancingGeometry=e)})}onDestroy(){this._container?.removeFromParent(),this._batchSystem?.removeFromParent(),this._particleSystem?.emitter.removeFromParent(),this._particleSystem?.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(){this.main&&(this._didPreWarm===!1&&this.main?.prewarm===!0&&(this._didPreWarm=!0,this.preWarm()),this.onUpdate(),this.onSimulate(this.deltaTime))}preWarm(){if(!this.emission?.enabled||this.emission.rateOverTime.getMax()<=0)return;const t=1/60,i=this.main.duration,n=this.main.startLifetime.getMax(),r=Math.min(Math.max(i,n)/Math.max(.01,this.main.simulationSpeed),1e3),a=Math.ceil(r/t),l=Date.now();Js&&console.log(`Particles ${this.name} - Prewarm for ${a} frames (${r} sec). Duration: ${i}, Lifetime: ${n}`);for(let h=0;h<a&&!(this.currentParticles>=this.maxParticles);h++){const d=Date.now()-l;if(d>2e3){console.warn(`Particles ${this.name} - Prewarm took too long. Aborting: ${d}`);break}this.onUpdate(),this.onSimulate(t)}}_lastBatchesCount=-1;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 i=this.layer;t.layers.mask=1<<i}}onUpdate(){if(this._bursts&&(this.emission.bursts=this._bursts,delete this._bursts),!this._isPlaying)return;const e=this.context.mainCamera;if(e){const n=je(e);this._cameraScale=n.x}const t=!this.worldspace,i=this.gameObject;if(pe(i,this.__worldQuaternion),this._worldQuaternionInverted.copy(this.__worldQuaternion).invert(),je(this.gameObject,this._worldScale),t&&this._container&&this.gameObject?.parent){const n=vx(this,Cm);this._container.matrix.makeScale(n.x,n.y,n.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),this.inheritVelocity?.update(this.context),this.velocityOverLifetime.update(this)}addSubParticleSystems(){if(this._subEmitterSystems&&this._particleSystem)for(const e of this._subEmitterSystems){e.particleSystem&&(e.particleSystem.__internalAwake?e.particleSystem.__internalAwake():A()&&console.warn("SubParticleSystem serialization issue(?)",e.particleSystem,e));const t=e.particleSystem?._particleSystem;if(t){e.particleSystem._isUsedAsSubsystem=!0;const i=new Ry(this,this._particleSystem,e.particleSystem,t);i.emitterType=e.type,i.emitterProbability=e.emitProbability,this._particleSystem.addBehavior(i)}else Js&&console.warn("Could not add SubParticleSystem",e,this)}}};Ie([f(af)],jt.prototype,"colorOverLifetime");Ie([f(Lt)],jt.prototype,"main");Ie([f(Rs)],jt.prototype,"emission");Ie([f(Ir)],jt.prototype,"sizeOverLifetime");Ie([f(ky)],jt.prototype,"shape");Ie([f(me)],jt.prototype,"noise");Ie([f(Le)],jt.prototype,"trails");Ie([f(Fe)],jt.prototype,"velocityOverLifetime");Ie([f(nt)],jt.prototype,"limitVelocityOverLifetime");Ie([f(Ey)],jt.prototype,"inheritVelocity");Ie([f(rl)],jt.prototype,"colorBySpeed");Ie([f(It)],jt.prototype,"textureSheetAnimation");Ie([f(_n)],jt.prototype,"rotationOverLifetime");Ie([f(Qi)],jt.prototype,"rotationBySpeed");Ie([f(di)],jt.prototype,"sizeBySpeed");let Ic=jt;class uu{particleSystem;emitProbability=1;properties;type;_deserialize(e,t){const i=this.particleSystem;if(i instanceof Ic)return;let n="";i&&typeof i.guid=="string"&&(n=i.guid,this.particleSystem=S.findByGuid(n,t)),Js&&!(this.particleSystem instanceof Ic)&&console.warn("Could not find particle system for sub emitter",n,t,this)}}function vx(s,e){if(e.set(1,1,1),s.gameObject.parent&&s.localspace)switch(s.main.scalingMode){case xm.Local:e=je(s.gameObject.parent,e),e.x=1/e.x,e.y=1/e.y,e.z=1/e.z;break;default:if(!s.unsupported_scaling_mode){s.unsupported_scaling_mode=!0;const t="ParticleSystem scale mode "+xm[s.main.scalingMode]+" is not supported";A()&&fe(t),console.warn(t,s.name,s)}e=je(s.gameObject,e);break}return e}var YE=Object.defineProperty,Ay=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&YE(e,t,n),n};class al extends E{strength=1;radius=2;targets=[];update(){const e=this.gameObject.worldPosition,t=-this.strength*this.context.time.deltaTime;this.targets?.forEach(i=>{if(!i)return;const n=i.gameObject.worldPosition.sub(e),o=n.length();if(o>this.radius)return;let r=t;o>1?r/=o*o:r/=Math.max(.05,o),i.applyImpulse(n.multiplyScalar(r))})}}Ay([f()],al.prototype,"strength");Ay([f()],al.prototype,"radius");Ay([f($e)],al.prototype,"targets");class Ua extends E{_didAssignPlayerColor=!1;onEnable(){this.context.connection.beginListen(K.JoinedRoom,this.tryAssignColor),this._didAssignPlayerColor||this.startCoroutine(this.waitForConnection())}onDisable(){this.context.connection.stopListen(K.JoinedRoom,this.tryAssignColor)}*waitForConnection(){for(;!this.destroyed&&this.activeAndEnabled&&(yield sg(.2),!this.tryAssignColor()););}tryAssignColor=()=>{const e=S.getComponentInParent(this.gameObject,zi);if(e&&e.owner)return this._didAssignPlayerColor=!0,this.assignUserColor(e.owner),!0;const t=S.getComponentInParent(this.gameObject,Oe);return t?.connectionId?(this._didAssignPlayerColor=!0,this.assignUserColor(t.connectionId),!0):!1};assignUserColor(e){const t=Ua.hashCode(e),i=Ua.colorFromHashCode(t);if(this.gameObject.type==="Mesh"){const n=this.gameObject;this.assignColor(i,e,n)}else if(this.gameObject.children)for(const n of this.gameObject.children){const o=n;o.material&&o.material.color&&this.assignColor(i,e,o)}}assignColor(e,t,i){let n=i.material;n&&(n._playerMaterial!==t&&(n=n.clone(),n._playerMaterial=t,i.material=n),n.color=e)}static hashCode(e){var t=0,i,n;if(e.length===0)return t;for(i=0;i<e.length;i++)n=e.charCodeAt(i),t=(t<<5)-t+n,t|=0;return t}static colorFromHashCode(e){const t=(e&16711680)>>16,i=(e&65280)>>8,n=e&255;return new c.Color(t/255,i/255,n/255)}}const Kl=x("debugpost");let Pm=null;function KE(s){Pm=s}function wx(s){let e=s.gameObject;for(;e;){for(const t of ku(e))if(t.isPostProcessingManager===!0)return t;e=e.parent}return null}function ZE(s){let e=wx(s);if(!e)if(Pm){Kl&&console.warn("Adding postprocessing manager to the scene.");const t=s.scene;e=hn(t,Pm)}else A()&&console.warn("No post processing manager found");return e}const et={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 Ge=null;function JE(s){if(Kl==="verbose"&&console.debug("Before ordering effects",[...s]),!Ge){Ge=new Map,Ge.set(T.POSTPROCESSING.MODULE.NormalPass,et.NormalPass),Ge.set(T.POSTPROCESSING.MODULE.DepthDownsamplingPass,et.DepthDownsamplingPass),Ge.set(T.POSTPROCESSING.MODULE.SMAAEffect,et.SMAA),Ge.set(T.POSTPROCESSING.MODULE.SSAOEffect,et.SSAO);const e=T.POSTPROCESSING_AO.MAYBEMODULE;e&&(Ge.set(e.N8AOPostPass,et.SSAO),Ge.set(e.N8AOPass,et.SSAO)),Ge.set(T.POSTPROCESSING.MODULE.TiltShiftEffect,et.TiltShift),Ge.set(T.POSTPROCESSING.MODULE.DepthOfFieldEffect,et.DepthOfField),Ge.set(T.POSTPROCESSING.MODULE.ChromaticAberrationEffect,et.ChromaticAberration),Ge.set(T.POSTPROCESSING.MODULE.BloomEffect,et.Bloom),Ge.set(T.POSTPROCESSING.MODULE.SelectiveBloomEffect,et.Bloom),Ge.set(T.POSTPROCESSING.MODULE.VignetteEffect,et.Vignette),Ge.set(T.POSTPROCESSING.MODULE.PixelationEffect,et.Pixelation),Ge.set(T.POSTPROCESSING.MODULE.ToneMappingEffect,et.ToneMapping),Ge.set(T.POSTPROCESSING.MODULE.HueSaturationEffect,et.HueSaturation),Ge.set(T.POSTPROCESSING.MODULE.BrightnessContrastEffect,et.BrightnessContrast)}s.sort((e,t)=>{const i=typeof e.priority=="number"?e.priority:Ge.get(e.effect.constructor)??Number.NEGATIVE_INFINITY,n=typeof t.priority=="number"?t.priority:Ge.get(t.effect.constructor)??Number.NEGATIVE_INFINITY;return i===Number.NEGATIVE_INFINITY?(Kl&&console.warn("Unknown effect found: ",e.constructor.name,e),1):n===Number.NEGATIVE_INFINITY?(Kl&&console.warn("Unknown effect found: ",t.constructor.name,t),-1):i-n}),Kl==="verbose"&&console.debug("After ordering effects",[...s])}var eR=Object.defineProperty,tR=Object.getOwnPropertyDescriptor,xx=(s,e,t,i)=>{for(var n=tR(e,t),o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&eR(e,t,n),n};const iR=x("debugpost");class z{isVolumeParameter=!0;constructor(e){e!==void 0&&this.initialize(e)}_isInitialized=!1;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)}_active=!0;get value(){return this._valueRaw}set value(e){this.isInitialized||this.initialize(e),this.processValue(e,!1)}_value;_valueRaw;set defaultValue(e){this._defaultValue=e}_defaultValue=void 0;__init(){this.processValue(this._valueRaw,!0)}valueProcessor;onValueChanged;processValue(e,t){if(e==null||!t&&this.testIfValueChanged(e)===!1)return;const i=this._value;iR&&typeof i=="number"&&typeof e=="number"&&(i?.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,i,this)}testIfValueChanged(e){return this._valueRaw!==e}}xx([f()],z.prototype,"overrideState");xx([f()],z.prototype,"value");class nR extends Hi{constructor(){super([z])}onSerialize(e,t){}onDeserialize(e,t){const i=t.target,n=t.path;let o;if(i&&n&&(o=i[n]),(typeof o!="object"||typeof o=="object"&&o.isVolumeParameter!==!0)&&(o=new z),typeof e=="object"&&"value"in e){const r=e.value;o.initialize(r),o.overrideState=e.overrideState}else o.value=e;return o}}new nR;var sR=Object.defineProperty,oR=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&sR(e,t,n),n};const bp=x("debugpost");class Xe extends E{get isPostProcessingEffect(){return!0}order=void 0;constructor(e=void 0){if(super(),e)for(const t of Object.keys(e)){const i=e[t],n=this[t];n instanceof z?n.initialize(i):n!==void 0&&(this[t]=i)}}active=!0;_manager=null;onEnable(){super.onEnable(),bp&&console.warn("Enable",this.constructor.name+(this.__internalDidAwakeAndStart?"":" (awake)")),this.__internalDidAwakeAndStart&&(this.active=!0),this.onEffectEnabled()}onDisable(){super.onDisable(),bp&&console.warn("Disable",this.constructor.name),this._manager?.removeEffect(this),this.active=!1}onEffectEnabled(e){e&&e.isPostProcessingManager===!0?this._manager=e:this._manager||(this._manager=ZE(this)),this._manager.addEffect(this),this._manager.dirty=!0}init(){}_result;_postprocessingContext=null;get postprocessingContext(){return this._postprocessingContext}apply(e){return this._postprocessingContext=e,this._result||(this.initParameters(),this._result=this.onCreateEffect?.call(this)),this._result&&this.initParameters(),this._result}unapply(){}dispose(){bp&&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 i=this[t];i instanceof z&&i.__init()}}onEditorModification(e){const t=e.propertyName;if(this[t]instanceof z){const i=e.value;return this[t].value=i,!0}}}oR([f()],Xe.prototype,"active");var rR=Object.defineProperty,aR=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&rR(e,t,n),n};const lR=x("debugpost"),Om={};function Ki(s,e){Om[s]=e}function cR(s){return s.__type in Om?Om[s.__type]:(lR&&s.__type&&console.warn("Unknown postprocessing type",s.__type,s),Xe)}class lf{components=[];__init(e){this.components?.forEach(t=>{t.gameObject===void 0&&e.gameObject.addComponent(t),t.init()})}addEffect(e){this.components.push(e)}removeEffect(e){const t=this.components.indexOf(e);t>=0&&this.components.splice(t,1)}}aR([Be([s=>cR(s),Xe])],lf.prototype,"components");var hR=Object.defineProperty,dR=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&hR(e,t,n),n};const uR=x("debugpost");class bh extends Xe{get typeName(){return"Antialiasing"}preset=new z(2);onCreateEffect(){const e=new T.POSTPROCESSING.MODULE.SMAAEffect({preset:this.preset?.value??T.POSTPROCESSING.MODULE.SMAAPreset.HIGH,edgeDetectionMode:T.POSTPROCESSING.MODULE.EdgeDetectionMode.LUMA});return this.preset.onValueChanged=t=>{uR&&console.log("Antialiasing preset changed to",t),e.applyPreset(t)},e}}dR([f(z)],bh.prototype,"preset");Ki("Antialiasing",bh);var fR=Object.defineProperty,Dy=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&fR(e,t,n),n};const cf=class Sx extends Xe{static useSelectiveBloom=!1;get typeName(){return"Bloom"}threshold=new z(.9);intensity=new z(1);scatter=new z(.7);selectiveBloom;init(){this.threshold.valueProcessor=e=>e,this.intensity.valueProcessor=e=>e,this.scatter.valueProcessor=e=>e}onCreateEffect(){let e;if(this.selectiveBloom==null&&(this.selectiveBloom=Sx.useSelectiveBloom),this.selectiveBloom){const t=e=new T.POSTPROCESSING.MODULE.SelectiveBloomEffect(this.context.scene,this.context.mainCamera,{blendFunction:T.POSTPROCESSING.MODULE.BlendFunction.ADD,mipmapBlur:!0,luminanceThreshold:this.threshold.value,luminanceSmoothing:this.scatter.value,radius:.85,intensity:this.intensity.value});t.inverted=!0}else e=new T.POSTPROCESSING.MODULE.BloomEffect({blendFunction:T.POSTPROCESSING.MODULE.BlendFunction.ADD,mipmapBlur:!0,luminanceThreshold:this.threshold.value,luminanceSmoothing:this.scatter.value,radius:.85,intensity:this.intensity.value});return this.intensity.onValueChanged=t=>{e.intensity=t},this.threshold.onValueChanged=t=>{e.luminanceMaterial.threshold=Math.pow(t,2.2)},this.scatter.onValueChanged=t=>{e.luminancePass.enabled=!0,e.luminanceMaterial.smoothing=t,e.mipmapBlurPass&&(e.mipmapBlurPass.radius=c.MathUtils.lerp(.1,.9,t))},e}};Dy([f(z)],cf.prototype,"threshold");Dy([f(z)],cf.prototype,"intensity");Dy([f(z)],cf.prototype,"scatter");let hf=cf;Ki("Bloom",hf);var pR=Object.defineProperty,mR=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&pR(e,t,n),n};class vh extends Xe{get typeName(){return"ChromaticAberration"}intensity=new z(0);onCreateEffect(){const e=new T.POSTPROCESSING.MODULE.ChromaticAberrationEffect;return e.offset=new c.Vector2(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}}mR([f(z)],vh.prototype,"intensity");Ki("ChromaticAberration",vh);var Zl=(s=>(s[s.None=0]="None",s[s.Neutral=1]="Neutral",s[s.ACES=2]="ACES",s[s.AgX=3]="AgX",s[s.KhronosNeutral=4]="KhronosNeutral",s))(Zl||{});const Qb=new Map;function vp(s){switch(s){case 0:return c.LinearToneMapping;case 1:return c.ReinhardToneMapping;case 2:return c.ACESFilmicToneMapping;case 3:return c.AgXToneMapping;case 4:return c.NeutralToneMapping;default:return Qb.has(s)||(Qb.set(s,!0),console.warn("[Postprocessing] Unknown tone mapping mode",s)),c.NeutralToneMapping}}function gR(s){switch(s){case c.LinearToneMapping:return 0;case c.ACESFilmicToneMapping:return 2;case c.AgXToneMapping:return 3;case c.NeutralToneMapping:return 1;case c.ReinhardToneMapping:return 1;default:return 0}}function Fd(s){switch(s){case c.LinearToneMapping:return T.POSTPROCESSING.MODULE.ToneMappingMode.LINEAR;case c.ACESFilmicToneMapping:return T.POSTPROCESSING.MODULE.ToneMappingMode.ACES_FILMIC;case c.AgXToneMapping:return T.POSTPROCESSING.MODULE.ToneMappingMode.AGX;case c.NeutralToneMapping:return T.POSTPROCESSING.MODULE.ToneMappingMode.NEUTRAL;case c.ReinhardToneMapping:return T.POSTPROCESSING.MODULE.ToneMappingMode.REINHARD;default:return T.POSTPROCESSING.MODULE.ToneMappingMode.LINEAR}}var yR=Object.defineProperty,Cx=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&yR(e,t,n),n};const wp=x("debugpost");class mo extends Xe{get typeName(){return"ToneMapping"}mode=new z(void 0);exposure=new z(1);setMode(e){const t=Zl[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=wx(this);e&&super.onEffectEnabled(e)}_tonemappingEffect=null;onCreateEffect(){if(this.mode.isInitialized==!1){const i=gR(this.context.renderer.toneMapping);wp&&console.log("[PostProcessing] Initializing ToneMapping mode to renderer.toneMapping",this.context.renderer.toneMapping+" → "+i),this.mode.initialize(i)}this._tonemappingEffect?.dispose();const e=vp(this.mode.value),t=this._tonemappingEffect=new T.POSTPROCESSING.MODULE.ToneMappingEffect({mode:Fd(e)});return this.mode.onValueChanged=i=>{if(typeof i=="string")i=T0(i),t.mode=Fd(i);else{const n=vp(i);t.mode=Fd(n)}t.name="ToneMapping ("+Zl[i]+")",wp&&console.log("[PostProcessing] ToneMapping mode changed to",Zl[i],e,t.mode)},wp&&console.log("[PostProcessing] Use ToneMapping",Zl[this.mode.value],e,t.mode,"renderer.tonemapping: "+this.context.renderer.toneMapping),t}onBeforeRender(){if(this._tonemappingEffect&&this.postprocessingContext?.handler.getEffectIsActive(this._tonemappingEffect)&&(this.mode.overrideState&&(this.context.renderer.toneMapping=vp(this.mode.value)),this.exposure.overrideState&&this.exposure.value!==void 0)){const e=Math.max(0,this.exposure.value);this.context.renderer.toneMappingExposure=e}}}Cx([f(z)],mo.prototype,"mode");Cx([f(z)],mo.prototype,"exposure");Ki("Tonemapping",mo);var _R=Object.defineProperty,df=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&_R(e,t,n),n};class ko extends Xe{get typeName(){return"ColorAdjustments"}remap=!0;postExposure=new z(1);contrast=new z(0);hueShift=new z(0);saturation=new z(0);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(){const e=[];let t=this.postprocessingContext?.components.find(o=>o instanceof mo);t||(t=new mo,this.postprocessingContext?.components.push(t)),this.postExposure.onValueChanged=o=>{this.postExposure.overrideState&&t?t.exposure.value=o: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 i=new T.POSTPROCESSING.MODULE.BrightnessContrastEffect;this.contrast.onValueChanged=o=>i.contrast=o;const n=new T.POSTPROCESSING.MODULE.HueSaturationEffect;return this.hueShift.onValueChanged=o=>n.hue=o,this.saturation.onValueChanged=o=>n.saturation=o,e.push(i),e.push(n),e}}df([f(z)],ko.prototype,"postExposure");df([f(z)],ko.prototype,"contrast");df([f(z)],ko.prototype,"hueShift");df([f(z)],ko.prototype,"saturation");Ki("ColorAdjustments",ko);var bR=Object.defineProperty,jr=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&bR(e,t,n),n};const vR=x("debugpost");class bn extends Xe{get typeName(){return"DepthOfField"}mode;focusDistance=new z(1);focalLength=new z(.2);aperture=new z(20);gaussianMaxRadius=new z;resolutionScale=new z(1/window.devicePixelRatio);bokehScale=new z;init(){this.focalLength.valueProcessor=t=>{const i=t/300;return I.lerp(2,.01,i)};const e=20;this.aperture.valueProcessor=t=>{const i=1-t/32;return I.lerp(1,e,i)}}onCreateEffect(){if(this.mode===0){vR&&console.warn("DepthOfField: Mode is set to Off");return}const e=new T.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(){}}jr([f()],bn.prototype,"mode");jr([f(z)],bn.prototype,"focusDistance");jr([f(z)],bn.prototype,"focalLength");jr([f(z)],bn.prototype,"aperture");jr([f(z)],bn.prototype,"gaussianMaxRadius");jr([f(z)],bn.prototype,"resolutionScale");jr([f(z)],bn.prototype,"bokehScale");Ki("DepthOfField",bn);class jc extends Xe{effect;constructor(e){super(),this.effect=e}get typeName(){return this.effect.constructor.name}onCreateEffect(){return this.effect}}var wR=Object.defineProperty,xR=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&wR(e,t,n),n};class wh extends Xe{get typeName(){return"PixelationEffect"}granularity=new z(10);onCreateEffect(){const e=new T.POSTPROCESSING.MODULE.PixelationEffect;return this.granularity.onValueChanged=t=>{e.granularity=t},e}}xR([f(z)],wh.prototype,"granularity");Ki("PixelationEffect",wh);var SR=Object.defineProperty,xh=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&SR(e,t,n),n};class Ts extends Xe{get typeName(){return"ScreenSpaceAmbientOcclusion"}intensity=new z(2);falloff=new z(1);samples=new z(9);color=new z(new c.Color(0,0,0));luminanceInfluence=new z(.7);onBeforeRender(){if(this._ssao&&this.context.mainCamera instanceof c.PerspectiveCamera){const e=this.context.mainCamera.far-this.context.mainCamera.near;this._ssao.ssaoMaterial.worldDistanceFalloff=e*.01,this._ssao.ssaoMaterial.worldDistanceThreshold=this.context.mainCamera.far}}_ssao;onCreateEffect(){const e=this.context.mainCamera,t=new T.POSTPROCESSING.MODULE.NormalPass(this.context.scene,e),i=new T.POSTPROCESSING.MODULE.DepthDownsamplingPass({normalBuffer:t.texture,resolutionScale:.5}),n=this._ssao=new T.POSTPROCESSING.MODULE.SSAOEffect(e,t.texture,{normalDepthBuffer:i.texture,worldDistanceThreshold:1,worldDistanceFalloff:1,worldProximityThreshold:.1,worldProximityFalloff:2,intensity:1,blendFunction:T.POSTPROCESSING.MODULE.BlendFunction.MULTIPLY,luminanceInfluence:.5});this.intensity.onValueChanged=r=>{n.intensity=r},this.falloff.onValueChanged=r=>{n.ssaoMaterial.radius=r*.1},this.samples.onValueChanged=r=>{n.ssaoMaterial.samples=r},this.color.onValueChanged=r=>{n.color||(n.color=new c.Color),n.color.copy(r)},this.luminanceInfluence.onValueChanged=r=>{n.luminanceInfluence=r};const o=new Array;return o.push(t),o.push(i),o.push(n),o}}xh([f(z)],Ts.prototype,"intensity");xh([f(z)],Ts.prototype,"falloff");xh([f(z)],Ts.prototype,"samples");xh([f(z)],Ts.prototype,"color");xh([f(z)],Ts.prototype,"luminanceInfluence");Ki("ScreenSpaceAmbientOcclusion",Ts);var CR=Object.defineProperty,Br=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&CR(e,t,n),n};const PR=x("debugN8AO");var Mm=(s=>(s[s.Performance=0]="Performance",s[s.Low=1]="Low",s[s.Medium=2]="Medium",s[s.High=3]="High",s[s.Ultra=4]="Ultra",s))(Mm||{});class vn extends Xe{get typeName(){return"ScreenSpaceAmbientOcclusionN8"}get pass(){return this._ssao}gammaCorrection=!0;aoRadius=new z(1);falloff=new z(1);intensity=new z(1);color=new z(new c.Color(0,0,0));screenspaceRadius=!1;quality=2;_ssao;onValidate(){this._ssao&&(this._ssao.setQualityMode(Mm[this.quality]),this._ssao.configuration.gammaCorrection=this.gammaCorrection,this._ssao.configuration.screenSpaceRadius=this.screenspaceRadius)}onCreateEffect(){const e=this.context.mainCamera,t=this.context.domWidth,i=this.context.domHeight,n=this._ssao=new T.POSTPROCESSING_AO.MODULE.N8AOPostPass(this.context.scene,e,t,i);n.name="SSAO_N8";const o=Mm[this.quality];if(n.setQualityMode(o),n.configuration.transparencyAware=!1,n.configuration.halfRes=window.devicePixelRatio>1,n.effectCompositerQuad?.material){const a=n.effectCompositerQuad.material;a.fragmentShader=a.fragmentShader.replace(`if (depth == 1.0) {
|
|
1310
|
+
`)}r&&o.size&&console.log(u);const y=new Set;for(const v of m){v.getPath||console.error("USDZExporter: Animation target object has no getPath method. This is likely a bug",v);let b=v.getPath();b.startsWith("<")&&(b=b.substring(1)),b.endsWith(">")&&(b=b.substring(0,b.length-1)),y.add({path:b,obj:v})}const _=Array.from(y).sort((v,b)=>v.path.length-b.path.length),g=new Array;for(let v=0;v<_.length;v++)for(let b=v+1;b<_.length;b++)if(_[b].path.startsWith(_[v].path)){const w=_[b],R=_[v];g.push({child:w.obj.displayName+" ("+w.path+")",parent:R.obj.displayName+" ("+R.path+")"})}g.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:g,playAnimationActions:o})}for(const u of new Set([...t,...i]))if(Array.isArray(u))for(const p of u)n.add(p.uuid);else n.add(u.uuid);rd&&console.log("All Behavior trigger sources and action targets",t,i,n),this.targetUuids=new Set(n)}onAfterHierarchy(e,t){if(this.behaviours?.length){t.beginBlock('def Scope "Behaviors"');for(const i of this.behaviours)i.writeTo(this,e.document,t);t.closeBlock()}}async onAfterSerialize(e){rd&&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:i}of this.audioClipsCopy){if(e.files[i])return;const r=await(await(await fetch(t)).blob()).arrayBuffer(),a=new Uint8Array(r);e.files[i]=a}this.behaviourComponentsCopy.length=0,this.audioClipsCopy.length=0}}class dy{get extensionName(){return"Physics"}onExportObject(e,t,i){const n=S.getComponents(e,$e).filter(l=>l.enabled),o=S.getComponents(e,Xi).filter(l=>l.enabled&&!l.isTrigger);let r=n.length>0?n[0]:null;const a=o.length>0?o[0]:null;a&&!r&&(r=new $e,r.isKinematic=!0),r&&t.addEventListener("serialize",(l,h)=>{if(r){if(l.appendLine(),l.beginBlock('def RealityKitComponent "RigidBody"',"{",!0),r.useGravity||l.appendLine("bool gravityEnabled = 0"),l.appendLine('uniform token info:id = "RealityKit.RigidBody"'),r.isKinematic&&l.appendLine('token motionType = "Kinematic"'),l.beginBlock('def RealityKitStruct "massFrame"',"{",!0),l.appendLine(`float m_mass = ${r.mass}`),l.beginBlock('def RealityKitStruct "m_pose"',"{",!0),l.appendLine(`float3 position = (${r.centerOfMass.x}, ${r.centerOfMass.y}, ${r.centerOfMass.z})`),l.closeBlock("}"),l.closeBlock("}"),o.length>0){const d=o[0];l.beginBlock('def RealityKitStruct "material"',"{",!0);const u=d.sharedMaterial;u&&u.dynamicFriction!==void 0&&l.appendLine(`double dynamicFriction = ${d.sharedMaterial?.dynamicFriction}`),u&&u.bounciness!==void 0&&l.appendLine(`double restitution = ${d.sharedMaterial?.bounciness}`),u&&u.staticFriction!==void 0&&l.appendLine(`double staticFriction = ${d.sharedMaterial?.staticFriction}`),l.closeBlock("}")}l.closeBlock("}")}}),a&&(t.addEventListener("serialize",(l,h)=>{l.beginBlock('def RealityKitComponent "Collider"',"{",!0),l.appendLine("uint group = 1"),l.appendLine('uniform token info:id = "RealityKit.Collider"'),l.appendLine("uint mask = 4294967295");const u=a.isTrigger?"Trigger":"Default";if(l.appendLine(`token type = "${u}"`),l.beginBlock('def RealityKitStruct "Shape"',"{",!0),a instanceof Xa){const p=a;l.appendLine('token shapeType = "Sphere"'),l.appendLine(`float radius = ${p.radius}`)}else if(a instanceof Vu){const p=a;l.appendLine('token shapeType = "Box"'),l.appendLine(`float3 extent = (${p.size.x}, ${p.size.y}, ${p.size.z})`)}else if(a instanceof bs){const p=a;l.appendLine('token shapeType = "Capsule"'),l.appendLine(`float radius = ${p.radius}`),l.appendLine(`float height = ${p.height}`)}else if(a instanceof wo&&a.sharedMesh?.geometry){const p=a.sharedMesh.geometry;p.boundingBox||p.computeBoundingBox();const m=a.sharedMesh.geometry.boundingBox;m&&(l.appendLine('token shapeType = "Box"'),l.appendLine(`float3 extent = (${m.max.x-m.min.x}, ${m.max.y-m.min.y}, ${m.max.z-m.min.z})`),console.log("[USDZ] Only Box, Sphere, and Capsule colliders are supported in visionOS/iOS. MeshCollider will be exported as Box",a))}else console.warn("[USDZ] Only Box, Sphere, and Capsule colliders are supported in visionOS/iOS. Ignoring collider:",a);l.beginBlock('def RealityKitStruct "pose"',"{",!0),l.closeBlock("}"),l.closeBlock("}"),l.closeBlock("}")}),o.length>1&&console.log("WARNING: Multiple colliders detected. visionOS / iOS can only support objects with a single collider, only exporting the first collider: ",a))}}const Zk=x("debugshadowcomponents");ie.__webpack_exports__Block.prototype.interactable={get(){return this.interactive},set(s){this.interactable=s}};class Wi extends E{isRoot(){return this.Root?.gameObject===this.gameObject}get canvas(){const e=this.Root;return e?.isCanvas?e:null}get Canvas(){return this.canvas}markDirty(){Gt.markUIDirty(this.context)}get shadowComponent(){return this._shadowComponent}set shadowComponent(e){this._shadowComponent=e}_shadowComponent=null;_controlsChildLayout=!0;get controlsChildLayout(){return this._controlsChildLayout}set controlsChildLayout(e){this._controlsChildLayout=e,this.shadowComponent&&(this.shadowComponent.autoLayout=e)}_root=void 0;get Root(){return this._root===void 0&&(this._root=S.getComponentInParent(this.gameObject,uh)),this._root}_parentComponent=void 0;__internalNewInstanceCreated(e){return super.__internalNewInstanceCreated(e),this.shadowComponent=null,this._root=void 0,this._parentComponent=void 0,this}onEnable(){super.onEnable()}addShadowComponent(e,t){if(!e)return;this.removeShadowComponent();const i=this.isRoot()?this.gameObject:this.gameObject.parent;if(this._parentComponent=S.getComponentInParent(i,Wi),!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[pi]=this,this.setShadowComponentOwner(e);let n=!1;if(this.Root?.gameObject===this.gameObject)this.gameObject.add(e);else{const o=this._parentComponent.shadowComponent;o&&(o?.add(e),n=!0)}this.shadowComponent=e,t&&t.shadowComponent&&this.shadowComponent&&t.shadowComponent.add(this.shadowComponent),Hc&&e.add(new c.AxesHelper(.5)),this.onAfterAddedToScene(),n&&ie.__webpack_exports__update(),Zk&&console.warn("Added shadow component",this.shadowComponent)}setShadowComponentOwner(e){if(e&&(e[pi]===void 0||e[pi]===this)&&(e[pi]=this,e.children))for(const t of e.children)this.setShadowComponentOwner(t)}traverseOwnedShadowComponents(e,t,i){if(e&&e[pi]===t){i(e);for(const n of e.children)this.traverseOwnedShadowComponents(n,t,i)}}removeShadowComponent(){this.shadowComponent&&this.shadowComponent.removeFromParent()}onAfterAddedToScene(){}setInteractable(e){this.shadowComponent&&(this.shadowComponent.interactable=e)}}class uh extends Wi{awake(){super.awake()}}var Jk=Object.defineProperty,eE=Object.getOwnPropertyDescriptor,fh=(s,e,t,i)=>{for(var n=i>1?void 0:i?eE(e,t):e,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&Jk(e,t,n),n};const dp=x("debugui"),up=x("debuguilayout");class hx{width;height}class dx{x;y;width;height}const on=new c.Vector3,Ol=new c.Matrix4,ad=new c.Quaternion,el=class ux extends Wi{get parent(){return this._parentRectTransform}get translation(){return this.gameObject.position}get rotation(){return this.gameObject.quaternion}get scale(){return this.gameObject.scale}_anchoredPosition;get anchoredPosition(){return this._anchoredPosition||(this._anchoredPosition=new c.Vector2),this._anchoredPosition}set anchoredPosition(e){this._anchoredPosition=e}sizeDelta=new c.Vector2(100,100);pivot=new c.Vector2(.5,.5);anchorMin=new c.Vector2(0,0);anchorMax=new c.Vector2(1,1);minWidth;minHeight;get width(){let e=this.sizeDelta.x;if(this.anchorMin.x!==this.anchorMax.x&&this._parentRectTransform){const t=this._parentRectTransform.width,i=this.anchorMax.x-this.anchorMin.x;e=t*i,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,i=this.anchorMax.y-this.anchorMin.y;e=t*i,e+=this.sizeDelta.y}return this.minHeight!==void 0&&e<this.minHeight?this.minHeight:e}lastMatrix;rectBlock;_transformNeedsUpdate=!1;_initialPosition;_parentRectTransform;_lastUpdateFrame=-1;awake(){super.awake(),this._lastUpdateFrame=-1,this._parentRectTransform=void 0,this.rectBlock=new c.Object3D,this.rectBlock.name=this.name,this.lastMatrix=new c.Matrix4,this._lastAnchoring=null,this._initialPosition=this.gameObject.position.clone(),this._initialPosition.z=0,this._anchoredPosition||(this._anchoredPosition=new c.Vector2),sa(this,"_anchoredPosition",()=>{this.markDirty()}),sa(this,"sizeDelta",()=>{this.markDirty()}),sa(this,"pivot",()=>{this.markDirty()}),sa(this,"anchorMin",()=>{this.markDirty()}),sa(this,"anchorMax",()=>{this.markDirty()})}onEnable(){super.onEnable(),this.rectBlock||(this.rectBlock=new c.Object3D),this.lastMatrix||(this.lastMatrix=new c.Matrix4),this._lastAnchoring||(this._lastAnchoring=new c.Vector2),this._initialPosition||(this._initialPosition=new c.Vector3),this._anchoredPosition||(this._anchoredPosition=new c.Vector2),this.addShadowComponent(this.rectBlock),this._transformNeedsUpdate=!0,this.canvas?.registerTransform(this)}onDisable(){super.onDisable(),this.removeShadowComponent(),this.canvas?.unregisterTransform(this)}onParentRectTransformChanged(e){this._transformNeedsUpdate||this.onApplyTransform(up?`${e.name} changed`:void 0)}get isDirty(){return this._transformNeedsUpdate||(this._transformNeedsUpdate=!this.lastMatrix.equals(this.gameObject.matrix)),this._transformNeedsUpdate}markDirty(){this._transformNeedsUpdate||(up&&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){if(this.context.time.frameCount===this._lastUpdateFrame)return;this._lastUpdateFrame=this.context.time.frameCount;const t=this.shadowComponent;if(!t)return;this.gameObject.parent?this._parentRectTransform=S.getComponentInParent(this.gameObject.parent,ux):this._parentRectTransform=void 0,this._transformNeedsUpdate=!1,up&&console.warn("RectTransform → ApplyTransform",this.name+" because "+e),this.isRoot()?this.Root.screenspace||(t.rotation.y=Math.PI):(t.matrix.identity(),t.matrixAutoUpdate=!1,on.set(0,0,0),this.applyPivot(on),t.matrix.setPosition(on.x,on.y,0),(this.gameObject.quaternion.x||this.gameObject.quaternion.y||this.gameObject.quaternion.z)&&(ad.copy(this.gameObject.quaternion),ad.x*=-1,ad.z*=-1,Ol.makeRotationFromQuaternion(ad),t.matrix.premultiply(Ol)),on.set(0,0,0),this.applyAnchoring(on),this.canvas?.screenspace?on.z+=.1:on.z+=.01,Ol.identity(),Ol.setPosition(on.x,on.y,on.z),t.matrix.premultiply(Ol),t.matrix.scale(this.gameObject.scale)),this.lastMatrix.copy(this.gameObject.matrix);const i=!0;for(const n of ku(this.gameObject,Wi,i,1)){if(n===this||!n.activeAndEnabled)continue;const o=n;o.onParentRectTransformChanged&&o.onParentRectTransformChanged(this)}}_lastAnchoring;applyAnchoring(e){this._lastAnchoring||(this._lastAnchoring=new c.Vector2);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 i=this._parentRectTransform;if(i){let n=0;const o=1-this.anchorMax.y-this.anchorMin.y;n-=i.height*.5*o,e.y+=n;let r=0;const a=1-this.anchorMax.x-this.anchorMin.x;r-=i.width*.5*a,e.x+=r}}applyPivot(e){if(this.pivot&&!this.isRoot()){const t=this.pivot.x-.5;e.x-=t*this.sizeDelta.x*this.gameObject.scale.x;const i=this.pivot.y-.5;e.y-=i*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}_createdBlocks=[];_createdTextBlocks=[];createNewBlock(e){e={...this.getBasicOptions(),...e},dp&&console.log(this.name,e);const t=new ie.__webpack_exports__Block(e);return this._createdBlocks.push(t),t}createNewText(e){dp&&console.log(e),e={...this.getBasicOptions(),...e},dp&&console.log(this.name,e);const t=new ie.__webpack_exports__Text(e);return this._createdTextBlocks.push(t),t}};fh([f(c.Vector2)],el.prototype,"anchoredPosition",1);fh([f(c.Vector2)],el.prototype,"sizeDelta",2);fh([f(c.Vector2)],el.prototype,"pivot",2);fh([f(c.Vector2)],el.prototype,"anchorMin",2);fh([f(c.Vector2)],el.prototype,"anchorMax",2);let mn=el;var tE=Object.defineProperty,fx=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&tE(e,t,n),n};class tl extends E{effectColor;effectDistance}fx([f(te)],tl.prototype,"effectColor");fx([f(c.Vector2)],tl.prototype,"effectDistance");var iE=Object.defineProperty,nE=Object.getOwnPropertyDescriptor,px=(s,e,t,i)=>{for(var n=i>1?void 0:i?nE(e,t):e,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&iE(e,t,n),n};const Fo={backgroundColor:new c.Color(1,1,1),backgroundOpacity:1,borderColor:new c.Color(1,1,1),borderOpacity:1},uy=class Hl extends Wi{get isGraphic(){return!0}get color(){return this._color||(this._color=new te(1,1,1,1)),this._color}set color(e){(!this._color||this._color.r!==e.r||this._color.g!==e.g||this._color.b!==e.b||this._color.alpha!==e.alpha)&&(this._color||(this._color=new te(1,1,1,1)),this._color.copy(e),this.onColorChanged())}_alphaFactor=1;setAlphaFactor(e){this._alphaFactor=e,this.onColorChanged()}get alphaFactor(){return this._alphaFactor}sRGBColor=new c.Color(1,0,1);onColorChanged(){if(this.uiObject){this.sRGBColor.copy(this._color),this.sRGBColor.convertLinearToSRGB(),Fo.backgroundColor=this.sRGBColor,Fo.backgroundOpacity=this._color.alpha;const e=this.uiObject._simpleState__activeStates?.[0];if(e){const t=this.uiObject._simpleState__states?.[e];t&&("backgroundColor"in t&&(Fo.backgroundColor=t.backgroundColor),"backgroundOpacity"in t&&(Fo.backgroundOpacity=t.backgroundOpacity))}Fo.backgroundOpacity*=this._alphaFactor,this.applyEffects(Fo,this._alphaFactor),this.uiObject.set(Fo),this.markDirty()}}get m_Color(){return this._color}raycastTarget=!0;uiObject=null;_color=null;_rect=null;_stateManager=null;get rectTransform(){if(this._rect||(this._rect=S.getComponent(this.gameObject,mn)),!this._rect)throw new Error("Not Supported: Make sure to add a RectTransform component before adding a UI Graphic component.");return this._rect}onParentRectTransformChanged(){this.uiObject?.set({width:this.rectTransform.width,height:this.rectTransform.height}),this.markDirty()}__internalNewInstanceCreated(e){return super.__internalNewInstanceCreated(e),this._rect=null,this.uiObject=null,this._stateManager=null,this._color&&(this._color=this._color.clone()),this}setState(e){this.makePanel(),this.uiObject&&(this.uiObject.setState(e),this?.markDirty())}setupState(e){this.makePanel(),this.uiObject&&(this._stateManager||(this._stateManager=new ie.SimpleStateBehavior(this.uiObject)),this.uiObject.setupState(e.state,e.attributes))}setOptions(e){this.makePanel(),this.uiObject&&this.uiObject.set(e)}awake(){super.awake(),this.makePanel(),sa(this,"_color",()=>mO(this,this.onColorChanged))}onEnable(){super.onEnable(),this.uiObject&&(this.rectTransform.shadowComponent?.add(this.uiObject),this.addShadowComponent(this.uiObject,this.rectTransform))}onDisable(){super.onDisable(),this.uiObject&&this.removeShadowComponent()}_currentlyCreatingPanel=!1;makePanel(){if(this.uiObject||this._currentlyCreatingPanel)return;this._currentlyCreatingPanel=!0;const t={backgroundColor:this.color,backgroundOpacity:this.color.alpha,offset:.015};this.onBeforeCreate(t),this.applyEffects(t),this.onCreate(t),this.controlsChildLayout=!1,this._currentlyCreatingPanel=!1,this.onAfterCreated(),this.onColorChanged()}onBeforeCreate(e){}onCreate(e){this.uiObject=this.rectTransform.createNewBlock(e),this.uiObject.name=this.name}onAfterCreated(){}applyEffects(e,t=1){const i=this.gameObject?.getComponent(tl);i&&(i.effectDistance&&(e.borderWidth=Math.max(Math.abs(i.effectDistance.x),Math.abs(i.effectDistance.y))),i.effectColor&&(e.borderColor=i.effectColor,e.borderOpacity=i.effectColor.alpha*t))}static textureCache=new Map;async setTexture(e){if(this.setOptions({backgroundOpacity:0}),e){if(Hl.textureCache.has(e))e=Hl.textureCache.get(e);else if(!e.isRenderTargetTexture){const t=e.clone();t.colorSpace=c.LinearSRGBColorSpace,Hl.textureCache.set(e,t),e=t}this.setOptions({backgroundImage:e,borderRadius:0,backgroundOpacity:this.color.alpha,backgroundSize:"stretch"}),re.NEEDLE_progressive.assignTextureLOD(e,0).then(t=>{t instanceof c.Texture&&(e&&Hl.textureCache.set(e,t),this.setOptions({backgroundImage:t}),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)}};px([f(te)],uy.prototype,"color",1);px([f()],uy.prototype,"raycastTarget",2);let ph=uy;class mh extends ph{_flippedObject=!1;onAfterCreated(){this.uiObject&&!this._flippedObject&&(this._flippedObject=!0,this.uiObject.scale.y*=-1)}}var sE=Object.defineProperty,oE=Object.getOwnPropertyDescriptor,ks=(s,e,t,i)=>{for(var n=i>1?void 0:i?oE(e,t):e,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&sE(e,t,n),n};const Uo=x("debugtext");var Ze=(s=>(s[s.UpperLeft=0]="UpperLeft",s[s.UpperCenter=1]="UpperCenter",s[s.UpperRight=2]="UpperRight",s[s.MiddleLeft=3]="MiddleLeft",s[s.MiddleCenter=4]="MiddleCenter",s[s.MiddleRight=5]="MiddleRight",s[s.LowerLeft=6]="LowerLeft",s[s.LowerCenter=7]="LowerCenter",s[s.LowerRight=8]="LowerRight",s))(Ze||{}),mx=(s=>(s[s.Normal=0]="Normal",s[s.Bold=1]="Bold",s[s.Italic=2]="Italic",s[s.BoldAndItalic=3]="BoldAndItalic",s))(mx||{});class Dt extends ph{alignment=0;verticalOverflow=0;horizontalOverflow=0;lineSpacing=1;supportRichText=!1;font;fontStyle=0;setAlphaFactor(e){super.setAlphaFactor(e),this.uiObject?.set({fontOpacity:this.color.alpha*this.alphaFactor}),this.markDirty()}get text(){return this._text}set text(e){e!==this._text&&(this._text=e,this.feedText(this.text,this.supportRichText),this.markDirty(),this.context.accessibility.updateElement(this,{label:this.text}))}set_text(e){this.text=e}get fontSize(){return this._fontSize}set fontSize(e){this._fontSize=e,this.uiObject?.set({fontSize:e})}sRGBTextColor=new c.Color(1,0,1);onColorChanged(){this.sRGBTextColor.copy(this.color),this.sRGBTextColor.convertLinearToSRGB(),this.uiObject?.set({color:this.sRGBTextColor,fontOpacity:this.color.alpha})}onParentRectTransformChanged(){super.onParentRectTransformChanged(),this.uiObject&&this.updateOverflow()}onBeforeCanvasRender(e){this.updateOverflow()}updateOverflow(){const e=this.uiObject?._overflow;e&&(e._needsUpdate=!0)}onCreate(e){Uo&&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,Uo&&(e.backgroundColor=16750848,e.backgroundOpacity=.5);const t=this.rectTransform;e={...e,...this.getTextOpts()},this.getAlignment(e),Uo&&(e.backgroundColor=Math.random()*16777215,e.backgroundOpacity=.1),this.uiObject=t.createNewText(e),this.feedText(this.text,this.supportRichText)}onAfterAddedToScene(){super.onAfterAddedToScene(),this.handleTextRenderOnTop()}_text="";_fontSize=12;_textMeshUi=null;getTextOpts(){const e=this.fontSize,t={color:this.color,fontOpacity:this.color.alpha,fontSize:e,fontKerning:"normal"};return this.setFont(t,this.fontStyle),t}onEnable(){super.onEnable(),this.context.accessibility.updateElement(this,{role:"text",label:this.text,hidden:!1}),this._didHandleTextRenderOnTop=!1,this.uiObject&&this.uiObject.addAfterUpdate(()=>{this.setShadowComponentOwner(this.uiObject),this.markDirty()}),setTimeout(()=>this.markDirty(),10),this.canvas?.registerEventReceiver(this)}onDisable(){super.onDisable(),this.canvas?.unregisterEventReceiver(this),this.context.accessibility.updateElement(this,{hidden:!0})}onDestroy(){super.onDestroy(),this.context.accessibility.removeElement(this)}getAlignment(e){switch(e.flexDirection="column",this.alignment){case 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){if(Uo&&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 i=this.getNextTag(e);if(i){if(i.startIndex>0){for(let r=this.uiObject.children.length-1;r>=0;r--){const a=this.uiObject.children[r];a.isUI&&(this.uiObject.remove(a),a.clear())}const o=new ie.__webpack_exports__Inline({textContent:e.substring(0,i.startIndex),color:"inherit"});this.uiObject.add(o)}}else{this.uiObject.textContent="",this.setOptions({textContent:e});return}const n=[];for(;i;){const o=this.getNextTag(e,i.endIndex),r={fontFamily:this.uiObject?.get("fontFamily"),color:"inherit",textContent:""};if(o){r.textContent=this.getText(e,i,o),this.handleTag(i,r,n);const a=new ie.__webpack_exports__Inline(r);this.uiObject?.add(a)}else{r.textContent=e.substring(i.endIndex),this.handleTag(i,r,n);const a=new ie.__webpack_exports__Inline(r);this.uiObject?.add(a)}i=o}}}_didHandleTextRenderOnTop=!1;handleTextRenderOnTop(){this._didHandleTextRenderOnTop||(this._didHandleTextRenderOnTop=!0,this.startCoroutine(this.renderOnTopCoroutine()))}*renderOnTopCoroutine(){if(!this.canvas)return;const e=[],t=this.canvas,i={renderOnTop:t.renderOnTop,depthWrite:t.depthWrite,doubleSided:t.doubleSided};for(;;){let n=!1;if(this._textMeshUi)for(let o=0;o<this._textMeshUi.length;o++){if(e[o]===!0)continue;n=!0;const r=this._textMeshUi[o];r.textContent&&(nu(r,i),e[o]=!0)}if(!n)break;yield}}handleTag(e,t,i){if(!e.isEndTag){if(e.type.includes("color")){const n=new fp(e,{color:t.color});if(i.push(n),e.type.length>6){const o=parseInt("0x"+e.type.substring(7));t.color=o}else t.color=new c.Color(1,1,1)}else if(e.type=="b"){this.setFont(t,1);const n=new fp(e,{fontWeight:700});i.push(n)}else if(e.type=="i"){this.setFont(t,2);const n=new fp(e,{fontStyle:"italic"});i.push(n)}}}getText(e,t,i){return e.substring(t.endIndex,i.startIndex)}getNextTag(e,t=0){const i=e.indexOf("<",t),n=e.indexOf(">",i);if(i>=0&&n>=0){const o=e.substring(i+1,n);return{type:o,startIndex:i,endIndex:n+1,isEndTag:o.startsWith("/")}}return null}setFont(e,t){if(!this.font)return;const i=this.font,n=this.getFamilyNameWithCorrectSuffix(i,t);Uo&&console.log("Selected font family:"+n);let o=ie.__webpack_exports__FontLibrary.getFontFamily(n);switch(o||(o=ie.__webpack_exports__FontLibrary.addFontFamily(n)),e.fontFamily=o,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 r=o.getVariant(e.fontWeight,e.fontStyle);if(!r){let a=n;a?.endsWith("-msdf.json")||(a+="-msdf.json");let l=n;l?.endsWith(".png")||(l+=".png"),r=o.addVariant(e.fontWeight,e.fontStyle,a,l),r?.addEventListener("ready",()=>{this.markDirty()})}}getFamilyNameWithCorrectSuffix(e,t){(e.startsWith("https:")||e.startsWith("http:"))&&(e=new URL(e).pathname);const i=e.lastIndexOf("-");if(i<0)return e;const n=e.substring(i+1)?.toLowerCase();if(rE.includes(n))return Uo&&console.warn("Unsupported font style: "+n),e;const o=e.lastIndexOf("/");let r=e;o>=0&&(r=r.substring(o+1));const a=r[0]===r[0].toUpperCase(),l=e.substring(0,i>o?i:e.length);switch(Uo&&console.log("Select font: ",e,mx[t],r,a,l),t){case 0:return a?l+"-Regular":l+"-regular";case 1:return a?l+"-Bold":l+"-bold";case 2:return a?l+"-Italic":l+"-italic";case 3:return a?l+"-BoldItalic":l+"-bolditalic";default:return e}}}ks([f()],Dt.prototype,"alignment",2);ks([f()],Dt.prototype,"verticalOverflow",2);ks([f()],Dt.prototype,"horizontalOverflow",2);ks([f()],Dt.prototype,"lineSpacing",2);ks([f()],Dt.prototype,"supportRichText",2);ks([f(URL)],Dt.prototype,"font",2);ks([f()],Dt.prototype,"fontStyle",2);ks([f()],Dt.prototype,"text",1);ks([f()],Dt.prototype,"fontSize",1);class fp{tag;previousValues;constructor(e,t){this.tag=e,this.previousValues=t}}const rE=["medium","mediumitalic","black","blackitalic","thin","thinitalic","extrabold","light","lightitalic","semibold"];class ma{static global_id=0;static getId(){return this.global_id++}id;content="";font=[];pointSize=144;width;height;depth;wrapMode;horizontalAlignment;verticalAlignment;material;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}constructor(e){this.id=e}writeTo(e,t){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?.push("sans-serif"));const i=this.font.map(n=>`"${n}"`).join(", ");t.appendLine(`string[] font = [ ${i} ]`),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/${qu(this.material)}>`),t.closeBlock()}}class fy{static singleLine(e,t,i){const n=new ma("text_"+ma.getId());return n.content=e,t&&(n.pointSize=t),i&&(n.depth=i),n}static multiLine(e,t,i,n,o,r){const a=new ma("text_"+ma.getId());return a.content=e,a.width=t,a.height=i,a.horizontalAlignment=n,a.verticalAlignment=o,r!==void 0&&(a.wrapMode=r),a}}const aE=new c.Matrix4().makeRotationY(Math.PI),lE=new c.Matrix4().makeScale(-1,1,-1);class tf{get extensionName(){return"text"}exportText(e,t,i){const n=S.getComponent(e,Dt);if(!n)return;const o=S.getComponent(e,mn);let r=100,a=100;o&&(r=o.width,a=o.height);const l=aE.clone();o&&l.premultiply(lE),t.setMatrix(l);const h=n.color.clone();t.material=new c.MeshStandardMaterial({color:h,emissive:h}),t.addEventListener("serialize",(d,u)=>{let p=n.text;p=p.replace(/\r/g,""),p=p.replace(/\n/g,"\\n");const m=fy.multiLine(p,r,a,"center","bottom","flowing");this.setTextAlignment(m,n.alignment),this.setOverflow(m,n),t.material&&(m.material=t.material),m.pointSize=this.convertToTextSize(n.fontSize),m.depth=.001,m.writeTo(void 0,d)})}convertToTextSize(e){return 1/.0502*144*e}setOverflow(e,t){t.horizontalOverflow?e.wrapMode="singleLine":e.wrapMode="flowing"}setTextAlignment(e,t){switch(t){case Ze.LowerLeft:case Ze.MiddleLeft:case Ze.UpperLeft:e.horizontalAlignment="left";break;case Ze.LowerCenter:case Ze.MiddleCenter:case Ze.UpperCenter:e.horizontalAlignment="center";break;case Ze.LowerRight:case Ze.MiddleRight:case Ze.UpperRight:e.horizontalAlignment="right";break}switch(t){case Ze.LowerLeft:case Ze.LowerCenter:case Ze.LowerRight:e.verticalAlignment="bottom";break;case Ze.MiddleLeft:case Ze.MiddleCenter:case Ze.MiddleRight:e.verticalAlignment="middle";break;case Ze.UpperLeft:case Ze.UpperCenter:case Ze.UpperRight:e.verticalAlignment="top";break}}}var cE=Object.defineProperty,Qe=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&cE(e,t,n),n};const zb=x("debuguilayout");class Er{left=0;right=0;top=0;bottom=0;get vertical(){return this.top+this.bottom}get horizontal(){return this.left+this.right}}Qe([f()],Er.prototype,"left");Qe([f()],Er.prototype,"right");Qe([f()],Er.prototype,"top");Qe([f()],Er.prototype,"bottom");class Ci extends E{_rectTransform=null;get rectTransform(){return this._rectTransform}onParentRectTransformChanged(e){this._needsUpdate=!0}_needsUpdate=!1;get isDirty(){return this._needsUpdate}get isLayoutGroup(){return!0}updateLayout(){this._rectTransform&&(zb&&console.warn("Layout Update",this.context.time.frame,this.name),this._needsUpdate=!1,this.onCalculateLayout(this._rectTransform))}childAlignment=0;reverseArrangement=!1;spacing=0;padding;minWidth=0;minHeight=0;flexibleHeight=0;flexibleWidth=0;preferredHeight=0;preferredWidth=0;start(){this._needsUpdate=!0}onEnable(){zb&&console.log(this.name,this),this._rectTransform=this.gameObject.getComponent(mn);const e=this.gameObject.getComponentInParent(Fa);e&&e.registerLayoutGroup(this),this._needsUpdate=!0}onDisable(){const e=this.gameObject.getComponentInParent(Fa);e&&e.unregisterLayoutGroup(this)}set m_Spacing(e){e!==this.spacing&&(this._needsUpdate=!0,this.spacing=e)}get m_Spacing(){return this.spacing}}Qe([f()],Ci.prototype,"childAlignment");Qe([f()],Ci.prototype,"reverseArrangement");Qe([f()],Ci.prototype,"spacing");Qe([f(Er)],Ci.prototype,"padding");Qe([f()],Ci.prototype,"minWidth");Qe([f()],Ci.prototype,"minHeight");Qe([f()],Ci.prototype,"flexibleHeight");Qe([f()],Ci.prototype,"flexibleWidth");Qe([f()],Ci.prototype,"preferredHeight");Qe([f()],Ci.prototype,"preferredWidth");class Co extends Ci{childControlHeight=!0;childControlWidth=!0;childForceExpandHeight=!1;childForceExpandWidth=!1;childScaleHeight=!1;childScaleWidth=!1;onCalculateLayout(e){const t=this.primaryAxis,i=e.width;let n=i;const o=e.height;let r=o;n-=this.padding.horizontal,r-=this.padding.vertical,t==="x"?this.padding.horizontal:this.padding.vertical;const a=t==="x",l=a?"y":"x",h=a?this.childControlWidth:this.childControlHeight,d=a?this.childControlHeight:this.childControlWidth,u=a?this.childForceExpandWidth:this.childForceExpandHeight,p=a?this.childForceExpandHeight:this.childForceExpandWidth,m=a?r:n,y=a?i:o,_=.5*(a?this.childAlignment%3:Math.floor(this.childAlignment/3));let g=0;a?g+=this.padding.left:g+=this.padding.top;let v=0,b=0;for(let D=0;D<this.gameObject.children.length;D++){const L=this.gameObject.children[D],j=S.getComponent(L,mn);j?.activeAndEnabled&&(b+=1,a?v+=j.width:v+=j.height)}let w=0;const R=this.spacing*(b-1);if(u||h){let D=0;a?D=n-=R:D=r-=R,b>0&&(w=D/b)}let O=0;O+=this.padding.left,O-=this.padding.right,_!==0&&(g=y-v,g*=_,g-=R*_,a?(g-=this.padding.right*_,g+=this.padding.left*(1-_),g<this.padding.left&&(g=this.padding.left)):(g-=this.padding.bottom*_,g+=this.padding.top*(1-_),g<this.padding.top&&(g=this.padding.top)));let M=1;for(let D=0;D<this.gameObject.children.length;D++){const L=this.gameObject.children[D],j=S.getComponent(L,mn);if(j?.activeAndEnabled){j.pivot?.set(.5,.5),j.anchorMin.set(0,1),j.anchorMax.set(0,1);const V=i*.5+O*.5;j.anchoredPosition.x!==V&&(j.anchoredPosition.x=V);const W=o*-.5;j.anchoredPosition.y!==W&&(j.anchoredPosition.y=W),p&&d&&j.sizeDelta[l]!==m&&(j.sizeDelta[l]=m),u&&h&&j.sizeDelta[t]!==w&&(j.sizeDelta[t]=w);const k=a?j.width:j.height,N=k*.5;if(g+=N,u){const ee=w*M-w*.5;ee>g&&(g=ee-w*.5+k+this.padding.left,g-=N)}let $=g;t==="y"&&($=-$),j.anchoredPosition[t]!==$&&(j.anchoredPosition[t]=$),g+=N,g+=this.spacing,M+=1}}}}Qe([f()],Co.prototype,"childControlHeight");Qe([f()],Co.prototype,"childControlWidth");Qe([f()],Co.prototype,"childForceExpandHeight");Qe([f()],Co.prototype,"childForceExpandWidth");Qe([f()],Co.prototype,"childScaleHeight");Qe([f()],Co.prototype,"childScaleWidth");class py extends Co{get primaryAxis(){return"y"}}class my extends Co{get primaryAxis(){return"x"}}class gy extends Ci{onCalculateLayout(){}}var hE=Object.defineProperty,dE=Object.getOwnPropertyDescriptor,Kn=(s,e,t,i)=>{for(var n=i>1?void 0:i?dE(e,t):e,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&hE(e,t,n),n},gx=(s=>(s[s.ScreenSpaceOverlay=0]="ScreenSpaceOverlay",s[s.ScreenSpaceCamera=1]="ScreenSpaceCamera",s[s.WorldSpace=2]="WorldSpace",s[s.Undefined=-1]="Undefined",s))(gx||{});const pp=x("debuguilayout"),Gi=class yx extends uh{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)}_renderOnTop;set depthWrite(e){this._depthWrite!==e&&(this._depthWrite=e,this.onRenderSettingsChanged())}get depthWrite(){return this._depthWrite}_depthWrite=!1;set doubleSided(e){this._doubleSided!==e&&(this._doubleSided=e,this.onRenderSettingsChanged())}get doubleSided(){return this._doubleSided}_doubleSided=!0;set castShadows(e){this._castShadows!==e&&(this._castShadows=e,this.onRenderSettingsChanged())}get castShadows(){return this._castShadows}_castShadows=!1;set receiveShadows(e){this._receiveShadows!==e&&(this._receiveShadows=e,this.onRenderSettingsChanged())}get receiveShadows(){return this._receiveShadows}_receiveShadows=!1;get renderMode(){return this._renderMode}set renderMode(e){this._renderMode!==e&&(this._renderMode=e,this.onRenderSettingsChanged())}_renderMode=-1;_rootCanvas;set rootCanvas(e){this._rootCanvas instanceof yx||(this._rootCanvas=e)}get rootCanvas(){return this._rootCanvas}_scaleFactor=1;get scaleFactor(){return this._scaleFactor}set scaleFactor(e){this._scaleFactor=e}worldCamera;planeDistance=-1;awake(){this.shadowComponent=this.gameObject,this.previousParent=this.gameObject.parent,pp&&console.log("Canvas.Awake()",this.previousParent?.name+"/"+this.gameObject.name),super.awake()}start(){this.applyRenderSettings()}onEnable(){super.onEnable(),this._updateRenderSettingsRoutine=void 0,this._lastMatrixWorld=new c.Matrix4,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)}_boundRenderSettingsChanged=this.onRenderSettingsChanged.bind(this);previousParent=null;_lastMatrixWorld=null;_rectTransforms=[];registerTransform(e){this._rectTransforms.push(e)}unregisterTransform(e){const t=this._rectTransforms.indexOf(e);t!==-1&&this._rectTransforms.splice(t,1)}_layoutGroups=new Map;registerLayoutGroup(e){const t=e.gameObject;this._layoutGroups.set(t,e)}unregisterLayoutGroup(e){const t=e.gameObject;this._layoutGroups.delete(t)}_receivers=[];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 zc(1).then(()=>{this.gameObject.visible=!0}))}onLeaveXR(e){this.screenspace&&(e.xr.isVR||e.xr.isPassThrough)&&(this.gameObject.visible=!0)}onBeforeRenderRoutine=()=>{if(this.previousParent=this.gameObject.parent,(this.context.xr?.isVR||this.context.xr?.isPassThrough)&&this.screenspace){this.gameObject.visible=!1,this.gameObject.removeFromParent();return}this.renderOnTop||this.screenspace?this.gameObject.removeFromParent():(this.onUpdateRenderMode(),this.handleLayoutUpdates(),this.shadowComponent?.updateMatrixWorld(!0),this.shadowComponent?.updateWorldMatrix(!0,!0),this.invokeBeforeRenderEvents(),Gt.ensureUpdateMeshUI(ie.ThreeMeshUI,this.context))};onAfterRenderRoutine=()=>{if((this.context.xr?.isVR||this.context.xr?.isPassThrough)&&this.screenspace){this.previousParent?.add(this.gameObject);return}if((this.screenspace||this.renderOnTop)&&this.previousParent&&this.context.mainCamera){this.screenspace?this.context.mainCamera?.add(this.gameObject):this.previousParent.add(this.gameObject);const e=this.context.renderer.autoClear,t=this.context.renderer.autoClearColor;this.context.renderer.autoClear=!1,this.context.renderer.autoClearColor=!1,this.context.renderer.clearDepth(),this.onUpdateRenderMode(!0),this.handleLayoutUpdates(),this.shadowComponent?.updateMatrixWorld(!0),this.invokeBeforeRenderEvents(),Gt.ensureUpdateMeshUI(ie.ThreeMeshUI,this.context,!0),this.context.renderer.render(this.gameObject,this.context.mainCamera),this.context.renderer.autoClear=e,this.context.renderer.autoClearColor=t,this.previousParent.add(this.gameObject)}this._lastMatrixWorld?.copy(this.gameObject.matrixWorld)};invokeBeforeRenderEvents(){for(const e of this._receivers)e.onBeforeCanvasRender?.(this)}handleLayoutUpdates(){this._lastMatrixWorld===null&&(this._lastMatrixWorld=new c.Matrix4);const e=!this._lastMatrixWorld.equals(this.gameObject.matrixWorld);pp&&e&&console.log("Canvas Layout changed",this.context.time.frameCount,this.name);for(const t of this._rectTransforms){e&&t.markDirty();let i=this._layoutGroups.get(t.gameObject);t.isDirty&&!i&&(i=t.gameObject.getComponentInParent(Ci)),(t.isDirty||i?.isDirty)&&(pp&&console.log("CANVAS UPDATE ### "+t.name+" ##################################### "+this.context.time.frame),i?.updateLayout(),t.updateTransform())}}applyRenderSettings(){this.onRenderSettingsChanged()}_updateRenderSettingsRoutine;onRenderSettingsChanged(){this._updateRenderSettingsRoutine||(this._updateRenderSettingsRoutine=this.startCoroutine(this._updateRenderSettingsDelayed(),ge.OnBeforeRender))}*_updateRenderSettingsDelayed(){if(yield,this._updateRenderSettingsRoutine=void 0,this.shadowComponent){this.onUpdateRenderMode(),nu(this.shadowComponent,this);for(const e of S.getComponentsInChildren(this.gameObject,Wi))nu(e.shadowComponent,this)}}_activeRenderMode=-1;_lastWidth=-1;_lastHeight=-1;onUpdateRenderMode(e=!1){if(!e&&this._renderMode===this._activeRenderMode&&this._lastWidth===this.context.domWidth&&this._lastHeight===this.context.domHeight)return;this._activeRenderMode=this._renderMode;let t=this.context.mainCameraComponent,i=10;switch(t&&t.nearClipPlane>0&&t.farClipPlane>0&&(i=I.lerp(t.nearClipPlane,t.farClipPlane,.01)),this._renderMode===1&&(this.worldCamera&&(t=this.worldCamera),this.planeDistance>0&&(i=this.planeDistance)),this._renderMode){case 0:case 1:if(this._lastWidth=this.context.domWidth,this._lastHeight=this.context.domHeight,!t)return;const n=i+.01;this.gameObject.position.x=0,this.gameObject.position.y=0,this.gameObject.position.z=-n,this.gameObject.quaternion.identity();const o=this.gameObject.getComponent(mn);let r=!1;o.sizeDelta.x!==this.context.domWidth&&(r=!0),o.sizeDelta.y!==this.context.domHeight&&(r=!0);const a=t.fieldOfView*Math.PI/180,l=2*Math.tan(a/2)*Math.abs(n);this.gameObject.scale.x=l/this.context.domHeight,this.gameObject.scale.y=l/this.context.domHeight,this.gameObject.scale.z=.01,r&&(o.sizeDelta.x=this.context.domWidth,o.sizeDelta.y=this.context.domHeight,o?.markDirty());break;case 2:this._lastWidth=-1,this._lastHeight=-1;break}}};Kn([f()],Gi.prototype,"renderOnTop",1);Kn([f()],Gi.prototype,"depthWrite",1);Kn([f()],Gi.prototype,"doubleSided",1);Kn([f()],Gi.prototype,"castShadows",1);Kn([f()],Gi.prototype,"receiveShadows",1);Kn([f()],Gi.prototype,"renderMode",1);Kn([f(Gi)],Gi.prototype,"rootCanvas",1);Kn([f()],Gi.prototype,"scaleFactor",1);Kn([f(si)],Gi.prototype,"worldCamera",2);Kn([f()],Gi.prototype,"planeDistance",2);let Fa=Gi;var uE=Object.defineProperty,fE=Object.getOwnPropertyDescriptor,yy=(s,e,t,i)=>{for(var n=i>1?void 0:i?fE(e,t):e,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&uE(e,t,n),n};class po extends E{get alpha(){return this._alpha}set alpha(e){e!==this._alpha&&(this._alpha=e,this.markDirty())}get isCanvasGroup(){return!0}_alpha=1;interactable=!0;blocksRaycasts=!0;_isDirty=!1;markDirty(){this._isDirty||(this._isDirty=!0,this.startCoroutine(this.applyChangesDelayed(),ge.OnBeforeRender))}*applyChangesDelayed(){this._isDirty=!1,this.applyChangesNow()}_buffer=[];applyChangesNow(){this._buffer.length=0;for(const e of S.getComponentsInChildren(this.gameObject,Wi,this._buffer)){const t=e;t.setAlphaFactor&&t.setAlphaFactor(this._alpha)}}}yy([f()],po.prototype,"alpha",1);yy([f()],po.prototype,"interactable",2);yy([f()],po.prototype,"blocksRaycasts",2);class _y{get extensionName(){return"tmui"}onExportObject(e,t,i){const n=S.getComponent(e,Fa);if(n&&n.enabled&&n.renderMode===gx.WorldSpace){const o=new tf,r=S.getComponent(e,mn),a=S.getComponent(e,po),l=new Array;if(r){if(!S.isActiveSelf(e)){const u=S.isActiveSelf(e);S.setActive(e,!0),r.onEnable(),r.updateTransform(),l.push(()=>{r.onDisable(),S.setActive(e,u)})}e.traverse(u=>{if(!S.isActiveInHierarchy(u)){const p=S.isActiveSelf(u);S.setActive(u,!0);const m=S.getComponent(u,Wi);m&&(m.onEnable(),l.push(()=>{m.onDisable()}));const y=S.getComponent(u,mn);y&&(y.onEnable(),y.updateTransform(),y.onApplyTransform(),l.push(()=>{y.onDisable()}));const _=S.getComponent(u,Dt);_&&(_.onEnable(),l.push(()=>{_.onDisable()})),l.push(()=>{S.setActive(u,p)})}}),r.width,r.height;const h=qe.createEmpty(),d=r.shadowComponent;if(t.add(h),d){const u=d.matrix;h.setMatrix(u);const p=new Map,m=new Map;p.set(d,h),m.set(d,a?a.alpha:1),d.traverse(y=>{if(y===d)return;const _=qe.createEmpty();_.setMatrix(y.matrix);const g=y.parent,v=!!g&&typeof g.textContent=="string"&&g.textContent.length>0;let b=m.get(g)||1;const w=S.getComponent(y,po);if(w&&(b*=w.alpha),y instanceof c.Mesh&&v){const O=y[pi];O?o.exportText(O.gameObject,_,i):console.error("Error when exporting UI: shadow component owner not found. This is likely a bug.",y)}if(y instanceof c.Mesh&&!v){const O=y.geometry.clone();O.scale(1,1,-1),this.flipWindingOrder(O),_.geometry=O;const M=new c.Color,D=y.material.opacity;M.copy(y.material.color),_.material=new c.MeshBasicMaterial({color:M,opacity:D*b,map:y.material.map,transparent:!0})}p.set(y,_),m.set(y,b);const R=p.get(g);if(!R){console.error("Error when exporting UI: shadow component parent not found!",y,y.parent);return}R.add(_)})}}for(const h of l)h()}}flipWindingOrder(e){const t=e.index.array;for(let i=0,n=t.length/3;i<n;i++){const o=t[i*3];t[i*3]=t[i*3+2],t[i*3+2]=o}e.index.needsUpdate=!0}}const ql=x("debugusdz");function pE(s,e){const t=[],i=S.getComponentsInChildren(s,lt),n=S.getComponentsInChildren(s,Tt),o=new Array,r=new Array;if(e.injectImplicitBehaviours)for(const a of i){if(!a||!a.runtimeAnimatorController||!a.enabled)continue;const l=a.runtimeAnimatorController.activeState;if(!l||!l.motion||!l.motion.clip||l.motion.clip.tracks?.length<1||o.includes(a))continue;const h=new Dc;h.animator=a,h.stateName=l.name,h.trigger="start",h.name="PlayAnimationOnClick_implicitAtStart_"+h.stateName;const d=new c.Object3D;S.addComponent(d,h),r.push(d),o.push(a),s.add(d)}else for(const a of i){if(!a||!a.runtimeAnimatorController||!a.enabled)continue;ql&&console.log(a);const l=[];for(const h of a.runtimeAnimatorController.enumerateActions()){ql&&console.log(h);const d=h.getClip();l.includes(d)||l.push(d)}t.push({root:a.gameObject,clips:l})}if(e.injectImplicitBehaviours)for(const a of n){if(!a||!a.clip||!a.enabled||!a.playAutomatically||o.includes(a))continue;const l=new Dc;l.animation=a,l.stateName=a.clip.name,l.trigger="start",l.name="PlayAnimationOnClick_implicitAtStart_"+l.stateName;const h=new c.Object3D;S.addComponent(h,l),r.push(h),o.push(a),s.add(h)}else for(const a of n){ql&&console.log(a);const l=[];for(const h of a.animations)l.includes(h)||l.push(h);t.push({root:a.gameObject,clips:l})}ql&&t?.length>0&&console.log("USDZ Animation Clips without behaviours",t);for(const a of t)for(const l of a.clips)e.registerAnimation(a.root,l);return r}function mE(s,e){const t=S.getComponentsInChildren(s,vi),i=S.getComponentsInChildren(s,uo),n=new Array,o=new Array;ql&&console.log({audioSources:t,playAudioOnClicks:i});for(const r of i){if(!r.target)continue;const a=t.indexOf(r.target);a>-1&&t.splice(a,1)}for(const r of t){if(!r||!r.clip||r.volume<=0||n.includes(r))continue;const a=new uo;a.target=r,a.name="PlayAudioOnClick_implicitAtStart_",a.trigger="start";const l=new c.Object3D;S.addComponent(l,a),console.log("implicit PlayAudioOnStart",l,a),o.push(l),n.push(r),s.add(l)}return o}function gE(s){return new St("DisableAtStart",Rt.sceneStartTrigger(),ue.fadeAction(s,0,!1))}function Nb(s,e){const t=s.domElement.shadowRoot.querySelector("link[rel='ar']");if(t)return t;const i=document.createElement("div");i.classList.add("menu"),i.classList.add("quicklook-menu"),i.style.display="none",i.style.visibility="hidden";const n=document.createElement("button");n.id="open-in-ar",e?(n.innerText="View in AR",n.title="View this scene in AR. The scene will be exported to USDZ and opened with Apple's QuickLook."):(n.innerText="View in AR",n.title="Download this scene for AR. Open the downloaded USDZ file to view it in AR using Apple's QuickLook."),i.appendChild(n);const o=document.createElement("a");o.id="needle-usdz-link",o.style.display="none",o.rel="ar",o.href="",o.target="_blank",i.appendChild(o);const r=document.createElement("img");return r.id="button",o.appendChild(r),s.domElement.shadowRoot.appendChild(i),o}var yE=Object.defineProperty,Pt=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&yE(e,t,n),n};const pt=x("debugusdz"),_E=x("debugusdzpruning");class Rr{callToAction;checkoutTitle;checkoutSubtitle;callToActionURL}Pt([f()],Rr.prototype,"callToAction");Pt([f()],Rr.prototype,"checkoutTitle");Pt([f()],Rr.prototype,"checkoutSubtitle");Pt([f()],Rr.prototype,"callToActionURL");const hi=class Wo extends E{static beforeExport=new ne;static afterExport=new ne;static beforeLODExport=new ne;objectToExport=void 0;autoExportAnimations=!0;autoExportAudioSources=!0;exportFileName=void 0;customUsdzFile=void 0;customBranding;anchoringType="plane";maxTextureSize=2048;planeAnchoringAlignment="horizontal";interactive=!0;physics=!0;allowCreateQuicklookButton=!0;quickLookCompatible=!0;extensions=[];link;button;start(){pt&&(console.log("USDZExporter",this),console.log("Debug USDZ Mode. Press 'T' to export"),window.addEventListener("keydown",e=>{e.key==="t"&&this.exportAndOpen()})),this.objectToExport||(this.objectToExport=this.gameObject),!this.objectToExport?.children?.length&&!this.objectToExport?.isMesh&&(this.objectToExport=this.context.scene)}onEnable(){const e=exports.DeviceUtilities.supportsQuickLookAR(),t=exports.DeviceUtilities.isiOS()||exports.DeviceUtilities.isiPad();!this.button&&(pt||e||t)&&(this.allowCreateQuicklookButton&&(this.button=this.createQuicklookButton()),this.lastCallback=this.quicklookCallback.bind(this),this.link=Nb(this.context,e),this.link.addEventListener("message",this.lastCallback)),pt&&Se("USDZ Exporter enabled: "+this.name),document.getElementById("open-in-ar")?.addEventListener("click",this.onClickedOpenInARElement),xc.registerExporter(this)}onDisable(){this.button?.remove(),this.link?.removeEventListener("message",this.lastCallback),pt&&Se("USDZ Exporter disabled: "+this.name),document.getElementById("open-in-ar")?.removeEventListener("click",this.onClickedOpenInARElement),xc.unregisterExporter(this)}onClickedOpenInARElement=e=>{e.preventDefault(),this.exportAndOpen()};async exportAsync(){return this.exportAndOpen()}async exportAndOpen(){let e=this.exportFileName??this.objectToExport?.name??this.name;if(e+="-"+Hw(),Vn()||(e!==""&&(e+="-"),e+="MadeWithNeedle"),this.link||(this.link=Nb(this.context,exports.DeviceUtilities.supportsQuickLookAR())),this.customUsdzFile)return pt&&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;Wo.beforeExport.invoke({exporter:this});const t=await this.export(this.objectToExport).finally(()=>{Wo.afterExport.invoke({exporter:this})});return t?(pt&&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(e){if(!e)return console.warn("No object to export"),null;const t=this._currentExportTasks.get(e);if(t)return t;const i=this.internalExport(e);return i instanceof Promise?(this._currentExportTasks.set(e,i),i.then(n=>(this._currentExportTasks.delete(e),n)).catch(n=>(this._currentExportTasks.delete(e),console.error("Error during USDZ export – please report a bug!",n),null))):i}_currentExportTasks=new Map;_previousTimeScale=1;async internalExport(e){oe.start("export-usdz",{onProgress:O=>{this.dispatchEvent(new CustomEvent("export-progress",{detail:{progress:O}}))}}),oe.report("export-usdz",{message:"Starting export",totalSteps:40,currentStep:0}),oe.report("export-usdz",{message:"Load progressive textures",autoStep:5}),oe.start("export-usdz-textures","export-usdz");const t=S.getComponentsInChildren(e,ci);for(const O of t)O&&O.enabled&&O.updateSprite(!0);const i=S.getComponentsInChildren(e,Ht),n=new Array;let o=0;for(const O of i){for(const M of O.sharedMeshes)if(M){let D=0;const L={exporter:this,type:"mesh",object:O.gameObject,mesh:M};if(Wo.beforeLODExport.invoke(L),L.overrideLevel!==void 0)if(L.overrideLevel===-1){pt&&console.warn("Skipping LOD export for mesh due to overrideLevel -1",O.gameObject,M);continue}else L.overrideLevel>=0&&(D=L.overrideLevel,pt&&console.log("Overriding LOD level for mesh export to level "+D+" "+M.name));const j=re.NEEDLE_progressive.assignMeshLOD(M,D);j instanceof Promise&&n.push(new Promise((V,W)=>{j.then(()=>{o++,oe.report("export-usdz-textures",{message:"Loaded progressive mesh",currentStep:o,totalSteps:n.length}),V()}).catch(k=>W(k))}))}for(const M of O.sharedMaterials)if(M){let D=0;const L={exporter:this,type:"texture",object:O.gameObject,material:M};if(Wo.beforeLODExport.invoke(L),L.overrideLevel!==void 0)if(L.overrideLevel===-1){pt&&console.warn("Skipping LOD assignment due to overrideLevel -1",O.gameObject,M);continue}else L.overrideLevel>=0&&(D=L.overrideLevel,pt&&console.log("Overriding LOD level for texture export to level "+D+" "+M.name));const j=re.NEEDLE_progressive.assignTextureLOD(M,D);j instanceof Promise&&n.push(new Promise((V,W)=>{j.then(()=>{o++,oe.report("export-usdz-textures",{message:"Loaded progressive texture",currentStep:o,totalSteps:n.length}),V()}).catch(k=>W(k))}))}}pt&&Se("Progressive Loading: "+n.length),await Promise.all(n),pt&&Se("Progressive Loading: done"),oe.end("export-usdz-textures");const r=Wt.Global.Mask;Wt.Global.Set(Ln.AR);const a=new Kw,l=new Xu(this.quickLookCompatible);let h;const d=[];this.interactive&&(d.push(new hy),d.push(new Mr),globalThis.NEEDLE_USE_RAPIER&&S.getComponentsInChildren(e,$e).length>0&&(this.physics?(h=new dy,d.push(h)):A()&&console.warn("USDZExporter: Physics export is disabled, but there are active Rigidbody components in the scene. They will not be exported.")),d.push(new tf),d.push(new _y));const u=[l,...d,...this.extensions],p={self:this,exporter:a,extensions:u,object:e};oe.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,oe.report("export-usdz","auto export animations and audio sources");const m=new Array;this.autoExportAnimations&&m.push(...pE(e,l)),u.find(O=>O.extensionName==="Audio")&&this.autoExportAudioSources&&m.push(...mE(e)),a.debug=pt,a.pruneUnusedNodes=!_E;const _=gr.instance.objs.map(O=>O.batchedMesh);a.keepObject=O=>{let M=!0;const D=S.getComponent(O,Ht);return D&&!D.enabled&&(M=!1),M&&_.includes(O)&&(M=!1),M&&S.getComponentInParent(O,oh)&&(M=!1),M&&S.getComponentInParent(O,Xn)&&(M=!1),pt&&!M&&console.log("USDZExporter: Discarding object",O),M},a.beforeWritingDocument=()=>{if(A()&&l&&h){const O=l.animatedRoots;for(const M of O){const D=S.getComponentsInChildren(M,$e).filter(j=>j.enabled),L=S.getComponents(M,Xi).filter(j=>j.enabled&&!j.isTrigger);(D.length>0||L.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.",M)}}};const g=new Array;this.objectToExport&&this.quickLookCompatible&&this.interactive&&this.objectToExport.traverse(O=>{O.visible||g.push(O)});const v=u.find(O=>O.extensionName==="Behaviour");this.interactive&&v&&g.length>0&&v.addBehavior(gE(g));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"),oe.report("export-usdz","Invoking exporter.parse");const w=await a.parse(this.objectToExport,{ar:{anchoring:{type:this.anchoringType},planeAnchoring:{alignment:this.planeAnchoringAlignment}},extensions:u,quickLookCompatible:this.quickLookCompatible,maxTextureSize:this.maxTextureSize,exportInvisible:b}),R=new Blob([w],{type:"model/vnd.usdz+zip"});this.revertWebARSessionRoot(),this.context.time.timeScale=this._previousTimeScale,oe.report("export-usdz","Invoking after-export"),this.dispatchEvent(new CustomEvent("after-export",{detail:p}));for(const O of m)S.destroy(O);return Wt.Global.Set(r),oe.end("export-usdz"),R}openInQuickLook(e,t){const i=e instanceof Blob?URL.createObjectURL(e):e,n=this.buildQuicklookOverlay();pt&&console.log("QuickLook Overlay",n);const o=n.callToAction?encodeURIComponent(n.callToAction):"",r=n.checkoutTitle?encodeURIComponent(n.checkoutTitle):"",a=n.checkoutSubtitle?encodeURIComponent(n.checkoutSubtitle):"";this.link.href=i+`#callToAction=${o}&checkoutTitle=${r}&checkoutSubtitle=${a}&callToActionURL=${n.callToActionURL}`,this.lastCallback||(this.lastCallback=this.quicklookCallback.bind(this),this.link.addEventListener("message",this.lastCallback)),this.link.download=t+".usdz",this.link.click()}download(e,t){Wo.save(e,t)}static save(e,t){const i=document.createElement("a");i.style.display="none",document.body.appendChild(i),typeof e=="string"?i.href=e:i.href=URL.createObjectURL(e),i.download=t,i.click(),i.remove()}lastCallback;quicklookCallback(e){if(e?.data=="_apple_ar_quicklook_button_tapped"){pt&&fe("Quicklook closed via call to action button");var t=new CustomEvent("quicklook-button-tapped",{detail:this});if(this.dispatchEvent(t),!t.defaultPrevented){const i=new URLSearchParams(this.link.href);if(i){const n=i.get("callToActionURL");pt&&Se("Quicklook url: "+n),n&&(Vn()?globalThis.open(n,"_blank"):console.warn("Quicklook closed: custom redirects require a Needle Engine Pro license: https://needle.tools/pricing",n))}}}}buildQuicklookOverlay(){const e={};return this.customBranding&&Object.assign(e,this.customBranding),Vn()||(console.log("Custom Quicklook banner text requires pro license: https://needle.tools/pricing"),e.callToAction="Close",e.checkoutTitle="🌵 Made with Needle",e.checkoutSubtitle="_"),(e.callToAction?.length||e.checkoutTitle?.length||e.checkoutSubtitle?.length)&&(e.callToAction?.length||(e.callToAction="\0"),e.checkoutTitle?.length||(e.checkoutTitle="\0"),e.checkoutSubtitle?.length||(e.checkoutSubtitle="\0")),this.dispatchEvent(new CustomEvent("quicklook-overlay",{detail:e})),e}static invertForwardMatrix=new c.Matrix4().makeRotationY(Math.PI);static invertForwardQuaternion=new c.Quaternion().setFromEuler(new c.Euler(0,Math.PI,0));_rootSessionRootWasAppliedTo=null;_rootPositionBeforeExport=new c.Vector3;_rootRotationBeforeExport=new c.Quaternion;_rootScaleBeforeExport=new c.Vector3;getARScaleAndTarget(){if(!this.objectToExport)return{scale:1,_invertForward:!1,target:this.gameObject,sessionRoot:null};const e=S.findObjectOfType(ef);let t=S.getComponentInParent(this.objectToExport,Ui);t||(t=S.getComponentInChildren(this.objectToExport,Ui));let i=1,n=!1;const o=this.objectToExport;return e?i=e.arScale:t&&(i=t.arScale,n=t.invertForward),{scale:1/i,_invertForward:n,target:o,sessionRoot:t?.gameObject??null}}applyWebARSessionRoot(){if(!this.objectToExport)return;const{scale:e,_invertForward:t,target:i,sessionRoot:n}=this.getARScaleAndTarget(),o=n?.matrixWorld.clone().invert();this._rootSessionRootWasAppliedTo=i,this._rootPositionBeforeExport.copy(i.position),this._rootRotationBeforeExport.copy(i.quaternion),this._rootScaleBeforeExport.copy(i.scale),i.scale.multiplyScalar(e),t&&i.quaternion.multiply(Wo.invertForwardQuaternion),i.updateMatrix(),i.updateMatrixWorld(!0),n&&o&&i.matrix.premultiply(o)}revertWebARSessionRoot(){if(!this.objectToExport||!this._rootSessionRootWasAppliedTo)return;const e=this._rootSessionRootWasAppliedTo;e.position.copy(this._rootPositionBeforeExport),e.quaternion.copy(this._rootRotationBeforeExport),e.scale.copy(this._rootScaleBeforeExport),e.updateMatrix(),e.updateMatrixWorld(!0),this._rootSessionRootWasAppliedTo=null}createQuicklookButton(){const t=lo.getOrCreate().createQuicklookButton();return t.parentNode||this.context.menu.appendChild(t),t}};Pt([f(c.Object3D)],hi.prototype,"objectToExport");Pt([f()],hi.prototype,"autoExportAnimations");Pt([f()],hi.prototype,"autoExportAudioSources");Pt([f()],hi.prototype,"exportFileName");Pt([f(URL)],hi.prototype,"customUsdzFile");Pt([f(Rr)],hi.prototype,"customBranding");Pt([f()],hi.prototype,"anchoringType");Pt([f()],hi.prototype,"maxTextureSize");Pt([f()],hi.prototype,"planeAnchoringAlignment");Pt([f()],hi.prototype,"interactive");Pt([f()],hi.prototype,"physics");Pt([f()],hi.prototype,"allowCreateQuicklookButton");Pt([f()],hi.prototype,"quickLookCompatible");let Wn=hi;Dk({find:()=>Ga(Wn),create:()=>new Wn});var bE=Object.defineProperty,vE=Object.getOwnPropertyDescriptor,by=(s,e,t,i)=>{for(var n=vE(e,t),o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&bE(e,t,n),n};class il extends E{get fog(){return this._fog||(this._fog=new c.Fog(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}_fog;onEnable(){this.scene.fog=this.fog}onDisable(){this.scene.fog===this._fog&&(this.scene.fog=null)}}by([f()],il.prototype,"near");by([f()],il.prototype,"far");by([f(c.Color)],il.prototype,"color");var wE=Object.defineProperty,vy=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&wE(e,t,n),n};class Tr extends E{objectBounds=!1;color;isGizmo=!0;_gizmoObject=null;_boxHelper=null;onEnable(){this.isGizmo&&!Hc||(this._gizmoObject||(this.objectBounds?this._gizmoObject=new c.BoxHelper(this.gameObject,this.color??16776960):(this.objectBounds=!1,this._gizmoObject=pg(this.color??16776960))),this.objectBounds?(this.scene.add(this._gizmoObject),this._boxHelper=this._gizmoObject,this.startCoroutine(this.syncObjectBounds(),ge.OnBeforeRender)):this.gameObject.add(this._gizmoObject))}onDisable(){this._gizmoObject&&this.gameObject.remove(this._gizmoObject)}*syncObjectBounds(){for(;this._boxHelper;)this._boxHelper?.update(),yield}}vy([f()],Tr.prototype,"objectBounds");vy([f(c.Color)],Tr.prototype,"color");vy([f()],Tr.prototype,"isGizmo");var xE=Object.defineProperty,wy=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&xE(e,t,n),n};class nl extends E{isGizmo=!1;color0;color1;gridHelper;size;divisions;offset;onEnable(){if(this.isGizmo&&!Hc)return;const e=this.size,t=this.divisions;this.gridHelper||(this.gridHelper=new c.GridHelper(e,t,this.color0??new c.Color(.4,.4,.4),this.color1??new c.Color(.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)}}wy([f()],nl.prototype,"isGizmo");wy([f(c.Color)],nl.prototype,"color0");wy([f(c.Color)],nl.prototype,"color1");var SE=Object.defineProperty,xy=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&SE(e,t,n),n};class Sy extends E{connectedBody;get rigidBody(){return this._rigidBody}_rigidBody=null;onEnable(){this._rigidBody||(this._rigidBody=this.gameObject.getComponent($e)),this.rigidBody&&this.connectedBody&&this.startCoroutine(this.create())}*create(){yield,this.rigidBody&&this.connectedBody&&this.activeAndEnabled&&this.createJoint(this.rigidBody,this.connectedBody)}}xy([f($e)],Sy.prototype,"connectedBody");class Cy extends Sy{createJoint(e,t){this.context.physics.engine?.addFixedJoint(e,t)}}class gh extends Sy{anchor;axis;createJoint(e,t){this.axis&&this.anchor&&this.context.physics.engine?.addHingeJoint(e,t,this.anchor,this.axis)}}xy([f(c.Vector3)],gh.prototype,"anchor");xy([f(c.Vector3)],gh.prototype,"axis");var CE=Object.defineProperty,PE=Object.getOwnPropertyDescriptor,Pi=(s,e,t,i)=>{for(var n=i>1?void 0:i?PE(e,t):e,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&CE(e,t,n),n};function Jr(s){return s*Math.PI/180}const Vb=300,Gs=x("debuglights");class Ot extends E{type=0;get range(){return this._range}set range(e){this._range=e,this.light&&(this.light.type==="SpotLight"||this.light.type==="PointLight")&&"distance"in this.light&&(this.light.distance=e)}_range=1;get spotAngle(){return this._spotAngle}set spotAngle(e){this._spotAngle=e,this.light&&this.light.type==="SpotLight"&&"angle"in this.light&&(this.light.angle=Jr(e/2))}_spotAngle=30;get innerSpotAngle(){return this._innerSpotAngle}set innerSpotAngle(e){if(this._innerSpotAngle=e,this.light&&this.light.type==="SpotLight"&&"penumbra"in this.light){const t=this.spotAngle,n=1-Jr(e/2)/Jr(t/2);this.light.penumbra=n}}_innerSpotAngle=10;set color(e){this._color=e,this.light!==void 0&&(this.light.color=e)}get color(){return this.light?this.light.color:this._color}_color=new c.Color(16777215);set shadowNearPlane(e){if(e!==this._shadowNearPlane&&(this._shadowNearPlane=e,this.light?.shadow?.camera!==void 0)){const t=this.light.shadow.camera;t.near=e}}get shadowNearPlane(){return this._shadowNearPlane}_shadowNearPlane=.1;set shadowBias(e){e!==this._shadowBias&&(this._shadowBias=e,this.light?.shadow?.bias!==void 0&&(this.light.shadow.bias=e,this.light.shadow.needsUpdate=!0))}get shadowBias(){return this._shadowBias}_shadowBias=0;set shadowNormalBias(e){e!==this._shadowNormalBias&&(this._shadowNormalBias=e,this.light?.shadow?.normalBias!==void 0&&(this.light.shadow.normalBias=e,this.light.shadow.needsUpdate=!0))}get shadowNormalBias(){return this._shadowNormalBias}_shadowNormalBias=0;_overrideShadowBiasSettings=!1;set shadows(e){this._shadows=e,this.light&&(this.light.castShadow=e!==0,this.updateShadowSoftHard())}get shadows(){return this._shadows}_shadows=1;lightmapBakeType=4;set intensity(e){this._intensity=e,this.light&&(this.light.intensity=e),Gs&&console.log("Set light intensity to "+this._intensity,e,this)}get intensity(){return this._intensity}_intensity=-1;get shadowDistance(){const e=this.light;return e?.shadow?e.shadow.camera.far:-1}set shadowDistance(e){this._shadowDistance=e;const t=this.light;if(t?.shadow){const i=t.shadow.camera;i.far=e,i.updateProjectionMatrix()}}_shadowDistance;shadowWidth;shadowHeight;get shadowResolution(){const e=this.light;return e?.shadow?e.shadow.mapSize.x:-1}set shadowResolution(e){if(e===this._shadowResolution)return;this._shadowResolution=e;const t=this.light;t?.shadow&&(t.shadow.mapSize.set(e,e),t.shadow.needsUpdate=!0)}_shadowResolution=void 0;get isBaked(){return this.lightmapBakeType===2}get selfIsLight(){if(this.gameObject.isLight===!0)return!0;switch(this.gameObject.type){case"SpotLight":case"PointLight":case"DirectionalLight":return!0}return!1}light=void 0;getWorldPosition(e){return this.light?this.type===1?this.light.getWorldPosition(e).multiplyScalar(1):this.light.getWorldPosition(e):e}awake(){this.color=new c.Color(this.color??16777215),Gs&&console.log(this.name,this)}onEnable(){Gs&&console.log("ENABLE LIGHT",this.name),this.createLight(),!this.isBaked&&(this.light&&(this.light.visible=!0,this.light.intensity=this._intensity,Gs&&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(),ge.LateUpdate))}onDisable(){Gs&&console.log("DISABLE LIGHT",this.name),this.light&&(this.selfIsLight?this.light.intensity=0:this.light.visible=!1)}createLight(){const e=this.selfIsLight;if(e&&!this.light)this.light=this.gameObject,this.light.name=this.name,this._intensity=this.light.intensity,this.type===1&&this.setDirectionalLight(this.light);else if(!this.light)switch(this.type){case 1:const t=new c.DirectionalLight(this.color,this.intensity*Math.PI);if(t.position.set(0,0,-Vb*.5).applyQuaternion(this.gameObject.quaternion),this.gameObject.add(t.target),hr(t.target,0,0,0),this.light=t,this.gameObject.position.set(0,0,0),this.gameObject.rotation.set(0,0,0),Gs){const r=new c.DirectionalLightHelper(this.light,.2,this.color);this.context.scene.add(r)}break;case 0:const i=new c.SpotLight(this.color,this.intensity*Math.PI,this.range,Jr(this.spotAngle/2),1-Jr(this.innerSpotAngle/2)/Jr(this.spotAngle/2),2);i.position.set(0,0,0),i.rotation.set(0,0,0),this.light=i;const n=i.target;i.add(n),n.position.set(0,0,this.range),n.rotation.set(0,0,0);break;case 2:const o=new c.PointLight(this.color,this.intensity*Math.PI,this.range);this.light=o;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),Gs&&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=Vb*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 i=this.gameObject.scale.x;t.left*=i,t.right*=i}if(this.shadowHeight!==void 0)t.top=this.shadowHeight/2,t.bottom=-this.shadowHeight/2;else{const i=this.gameObject.scale.y;t.top*=i,t.bottom*=i}this.light.shadow.needsUpdate=!0,Gs&&this.context.scene.add(new c.CameraHelper(t))}this.isBaked?this.light.removeFromParent():e||this.gameObject.add(this.light)}}*updateMainLightRoutine(){for(;;){this.type===1&&((!this.context.mainLight||this.intensity>this.context.mainLight.intensity)&&(this.context.mainLight=this),yield);break}}static allowChangingRendererShadowMapType=!0;updateShadowSoftHard(){this.light&&this.light.shadow&&(this.shadows===2||(this.light.shadow.radius=1,this.light.shadow.blurSamples=1))}onEnterXR(e){this.applyXRScale(e.xr.rigScale)}onUpdateXR(e){this.applyXRScale(e.xr.rigScale)}onLeaveXR(e){this.applyXRScale(1)}applyXRScale(e){this.light&&(this.light.intensity=this._intensity/e,"distance"in this.light&&(this.light.distance=this._range/e))}setDirectionalLight(e){e.add(e.target),e.target.position.set(0,0,-1)}}Pi([f()],Ot.prototype,"type",2);Pi([f()],Ot.prototype,"range",1);Pi([f()],Ot.prototype,"spotAngle",1);Pi([f()],Ot.prototype,"innerSpotAngle",1);Pi([f(c.Color)],Ot.prototype,"color",1);Pi([f()],Ot.prototype,"shadowNearPlane",1);Pi([f()],Ot.prototype,"shadowBias",1);Pi([f()],Ot.prototype,"shadowNormalBias",1);Pi([f()],Ot.prototype,"shadows",1);Pi([f()],Ot.prototype,"lightmapBakeType",2);Pi([f()],Ot.prototype,"intensity",1);Pi([f()],Ot.prototype,"shadowDistance",1);Pi([f()],Ot.prototype,"shadowResolution",1);new c.Vector3(0,0,0);var OE=Object.defineProperty,nf=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&OE(e,t,n),n};const mp=x("debuglods"),ME=x("nolods");class sl{screenRelativeTransitionHeight;distance;renderers}nf([f()],sl.prototype,"screenRelativeTransitionHeight");nf([f()],sl.prototype,"distance");nf([f(Ht)],sl.prototype,"renderers");class kE{model;get renderers(){return this.model.renderers}constructor(e){this.model=e}}class sf extends E{lodModels=[];_lods=[];_settings=[];_lodsHandler;start(){if(mp&&console.log("LODGROUP",this.name,this.lodModels,this),!ME&&!this._lodsHandler&&this.gameObject&&this.lodModels&&Array.isArray(this.lodModels)){const e=[];for(const i of this.lodModels){const n=new kE(i);this._lods.push(n);for(const o of n.renderers)e.includes(o)||e.push(o)}this._lodsHandler=new Array;for(let i=0;i<e.length;i++){const n=new c.LOD;this._lodsHandler.push(n),this.gameObject.add(n)}const t=new c.Object3D;t.name="Cull "+this.name;for(let i=0;i<e.length;i++){const n=e[i],o=this._lodsHandler[i],r=n.gameObject;mp&&console.log(i,r.name);for(const a of this._lods){const l=a.model.distance;let h=null;if(a.renderers.includes(n)?h=r:h=t,h.type==="Group"){console.warn(`LODGroup ${this.name}: Group or MultiMaterial object's are not supported as LOD object: ${h.name}`);continue}mp&&console.log("LEVEL",h.name,l),o.autoUpdate=!1,this.onAddLodLevel(o,h,a.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 i=t.getCurrentLevel(),n=t.levels[i];t.layers.mask=n.object.layers.mask}}onAddLodLevel(e,t,i){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,i*this._distanceFactor,.01);const n={lod:e,levelIndex:e.levels.length-1,distance:i};this._settings.push(n)}_distanceFactor=1;distanceFactor(e){if(e!==this._distanceFactor){this._distanceFactor=e;for(const t of this._settings){const i=t.lod.levels[t.levelIndex];i.distance=t.distance*e}}}}nf([f(sl)],sf.prototype,"lodModels");var EE=Object.defineProperty,Py=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&EE(e,t,n),n};const ld=x("debugnestedgltf");class ol extends E{filePath;loaded=new ne;loadAssetInParent=!0;_isLoadingOrDoneLoading=!1;listenToProgress(e){this.filePath?.beginListenDownload(e)}preload(){return this.filePath?.preload()||null}async start(){if(this._isLoadingOrDoneLoading)return;ld&&console.log(this,this.guid);const e=this.gameObject.parent;if(e&&this.filePath){this._isLoadingOrDoneLoading=!0;const t=new gn;t.idProvider=new xt(this.hash(this.guid)),t.parent=this.loadAssetInParent!==!1?e:this.gameObject,this.gameObject.updateMatrix();const i=this.gameObject.matrix;ld&&console.log("Load nested:",this.filePath?.url??this.filePath,this.gameObject.position);const n=await this.filePath?.instantiate?.call(this.filePath,t);ld&&console.log("Nested loaded:",this.filePath?.url??this.filePath,n),n&&this.loadAssetInParent!==!1&&(n.matrixAutoUpdate=!1,n.matrix.identity(),n.applyMatrix4(i),n.matrixAutoUpdate=!0,n.layers.disableAll(),n.layers.set(this.layer),this.loaded.invoke({component:this,instance:n,asset:this.filePath})),ld&&console.log("Nested loading done:",this.filePath?.url??this.filePath,n)}}onDestroy(){this.filePath?.unload()}hash(e){let t=0;for(let i=0;i<e.length;i++)t=e.charCodeAt(i)+((t<<5)-t);return t}}Py([f(Z)],ol.prototype,"filePath");Py([f(ne)],ol.prototype,"loaded");Py([f()],ol.prototype,"loadAssetInParent");var RE=Object.defineProperty,Oy=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&RE(e,t,n),n};const TE=x("debugnet"),of=class wm extends E{url=null;urlParameterName=null;localhost=null;awake(){TE&&console.log(this),this.context.connection.registerProvider(this)}getWebsocketUrl(){let e=this.url?wm.GetUrl(this.url,this.localhost):null;if(this.urlParameterName){const o=x(this.urlParameterName);o&&typeof o=="string"&&(e=o)}if(!e)return null;const i=new RegExp("(((https?)|(?<socket_prefix>wss?))://)?(www.)?(?<url>.+)","gm").exec(e);return i?.groups?i?.groups.socket_prefix?e:"wss://"+i?.groups.url:null}static GetUrl(e,t){let i=e;const n=wm.IsLocalNetwork()&&t;if(n&&(i=t),e?.startsWith("/")){const o=n?i:window.location.origin;o?.endsWith("/")&&e.startsWith("/")&&(e=e.substring(1)),i=o+e}return i}static IsLocalNetwork(e=window.location.hostname){return yi(e)}};Oy([f()],of.prototype,"url");Oy([f()],of.prototype,"urlParameterName");Oy([f()],of.prototype,"localhost");let My=of;var AE=Object.defineProperty,rf=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&AE(e,t,n),n};class Ar extends E{referenceSpace;from;affectPosition=!1;affectRotation=!1;alignLookDirection=!1;levelLookDirection=!1;levelPosition=!1;positionOffset=new c.Vector3(0,0,0);rotationOffset=new c.Vector3(0,0,0);offset=new c.Vector3(0,0,0);update(){if(!this.from)return;var e=Y(this.from),t=pe(this.from);this.offset.copy(this.positionOffset);const i=this.offset.length();if(this.referenceSpace&&this.offset.transformDirection(this.referenceSpace.matrixWorld).multiplyScalar(i),e.add(this.offset),this.levelPosition&&this.referenceSpace){const a=new c.Plane(this.gameObject.up,0),l=Y(this.referenceSpace);a.setFromNormalAndCoplanarPoint(this.gameObject.up,l);const h=new c.Vector3(0,0,0);a.projectPoint(e,h),e.copy(h)}this.affectPosition&&at(this.gameObject,e);const n=new c.Euler(this.rotationOffset.x,this.rotationOffset.y,this.rotationOffset.z),o=new c.Quaternion().setFromEuler(n);this.affectRotation&&dn(this.gameObject,t.multiply(o));const r=new c.Vector3;this.from.getWorldDirection(r).multiplyScalar(50),this.levelLookDirection&&(r.y=0),this.alignLookDirection&&this.gameObject.lookAt(r)}}rf([f(S)],Ar.prototype,"referenceSpace");rf([f(S)],Ar.prototype,"from");rf([f(c.Vector3)],Ar.prototype,"positionOffset");rf([f(c.Vector3)],Ar.prototype,"rotationOffset");var DE=Object.defineProperty,Po=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&DE(e,t,n),n};class oi{time=0;value=0;inTangent=1/0;inWeight;outTangent=1/0;outWeight;weightedMode;constructor(e=0,t=0){this.time=e,this.value=t}}Po([f()],oi.prototype,"time");Po([f()],oi.prototype,"value");Po([f()],oi.prototype,"inTangent");Po([f()],oi.prototype,"inWeight");Po([f()],oi.prototype,"outTangent");Po([f()],oi.prototype,"outWeight");Po([f()],oi.prototype,"weightedMode");const _x=class Xl{static linearFromTo(e,t,i){const n=new Xl,o=new oi;o.time=0,o.value=e;const r=new oi;return r.time=i,r.value=t,n.keys.push(o,r),n}static constant(e){const t=new Xl,i=new oi;return i.time=0,i.value=e,t.keys.push(i),t}keys=[];clone(){const e=new Xl;return e.keys=this.keys?.map(t=>{const i=new oi;return i.time=t.time,i.value=t.value,i.inTangent=t.inTangent,i.inWeight=t.inWeight,i.outTangent=t.outTangent,i.outWeight=t.outWeight,i.weightedMode=t.weightedMode,i})||[],e}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 i=this.keys[t];if(i.time<=e)if(t+1<this.keys.length){const o=this.keys[t+1];if(o.time<e)continue;return!isFinite(i.outTangent)||!isFinite(o.inTangent)?i.value:Xl.interpolateValue(e,i,o)}else return i.value}return this.keys[this.keys.length-1].value}static interpolateValue(e,t,i){const n=t.time,o=t.value,r=t.outTangent,a=i.time,l=i.value,h=i.inTangent,d=a-n,u=d*d,p=u*d,m=((r+h)*d-2*(l-o))/p,y=(3*(l-o)-(h+2*r)*d)/u,_=r,g=o,v=e-n,b=v*v,w=b*v;return m*w+y*b+_*v+g}};Po([f(oi)],_x.prototype,"keys");let yh=_x;var LE=Object.defineProperty,C=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&LE(e,t,n),n};const cd=x("debugparticles");var rs=(s=>(s[s.Billboard=0]="Billboard",s[s.Stretch=1]="Stretch",s[s.HorizontalBillboard=2]="HorizontalBillboard",s[s.VerticalBillboard=3]="VerticalBillboard",s[s.Mesh=4]="Mesh",s))(rs||{});class Dr{alphaKeys=[];colorKeys=[];get duration(){return 1}evaluate(e,t){let i,n=0,o=null,r=0;for(let a=0;a<this.alphaKeys.length;a++){const l=this.alphaKeys[a];(l.time<e||!i)&&(i=l,n=a)}for(let a=0;a<this.colorKeys.length;a++){const l=this.colorKeys[a];(l.time<e||!o)&&(o=l,r=a)}if(o)if(r+1<this.colorKeys.length){const l=this.colorKeys[r+1],h=I.remap(e,o.time,l.time,0,1);t.r=I.lerp(o.color.r,l.color.r,h),t.g=I.lerp(o.color.g,l.color.g,h),t.b=I.lerp(o.color.b,l.color.b,h)}else t.r=o.color.r,t.g=o.color.g,t.b=o.color.b;if(i)if(n+1<this.alphaKeys.length){const l=this.alphaKeys[n+1],h=I.remap(e,i.time,l.time,0,1);t.alpha=I.lerp(i.alpha,l.alpha,h)}else t.alpha=i.alpha;return t}}C([f()],Dr.prototype,"alphaKeys");C([f()],Dr.prototype,"colorKeys");var Lc=(s=>(s[s.Local=0]="Local",s[s.World=1]="World",s[s.Custom=2]="Custom",s))(Lc||{}),hu=(s=>(s[s.Sphere=0]="Sphere",s[s.SphereShell=1]="SphereShell",s[s.Hemisphere=2]="Hemisphere",s[s.HemisphereShell=3]="HemisphereShell",s[s.Cone=4]="Cone",s[s.Box=5]="Box",s[s.Mesh=6]="Mesh",s[s.ConeShell=7]="ConeShell",s[s.ConeVolume=8]="ConeVolume",s[s.ConeVolumeShell=9]="ConeVolumeShell",s[s.Circle=10]="Circle",s[s.CircleEdge=11]="CircleEdge",s[s.SingleSidedEdge=12]="SingleSidedEdge",s[s.MeshRenderer=13]="MeshRenderer",s[s.SkinnedMeshRenderer=14]="SkinnedMeshRenderer",s[s.BoxShell=15]="BoxShell",s[s.BoxEdge=16]="BoxEdge",s[s.Donut=17]="Donut",s[s.Rectangle=18]="Rectangle",s[s.Sprite=19]="Sprite",s[s.SpriteRenderer=20]="SpriteRenderer",s))(hu||{});const Es=class Ql{static constant(e){const t=new Ql;return t.setConstant(e),t}static betweenTwoConstants(e,t){const i=new Ql;return i.setMinMaxConstant(e,t),i}static curve(e,t=1){const i=new Ql;return i.setCurve(e,t),i}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}mode="Constant";constant;constantMin;constantMax;curve;curveMin;curveMax;curveMultiplier;clone(){const e=new Ql;return e.mode=this.mode,e.constant=this.constant,e.constantMin=this.constantMin,e.constantMax=this.constantMax,e.curve=this.curve?.clone(),e.curveMin=this.curveMin?.clone(),e.curveMax=this.curveMax?.clone(),e.curveMultiplier=this.curveMultiplier,e}evaluate(e,t){const i=t===void 0?Math.random():t;switch(this.mode){case 0:case"Constant":return this.constant;case 1:case"Curve":return e=I.clamp01(e),this.curve.evaluate(e)*this.curveMultiplier;case 2:case"TwoCurves":const n=e*this.curveMin.duration,o=e*this.curveMax.duration;return I.lerp(this.curveMin.evaluate(n),this.curveMax.evaluate(o),i%1)*this.curveMultiplier;case 3:case"TwoConstants":return I.lerp(this.constantMin,this.constantMax,i%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 i=0;i<e.keys.length;i++){const n=e.keys[i];n.value>t&&(t=n.value)}return t}};C([f()],Es.prototype,"mode");C([f()],Es.prototype,"constant");C([f()],Es.prototype,"constantMin");C([f()],Es.prototype,"constantMax");C([f(yh)],Es.prototype,"curve");C([f(yh)],Es.prototype,"curveMin");C([f(yh)],Es.prototype,"curveMax");C([f()],Es.prototype,"curveMultiplier");let H=Es;const Oo=class _t{static constant(e){const t=new _t;return t.constant(e),t}static betweenTwoColors(e,t){const i=new _t;return i.betweenTwoColors(e,t),i}constant(e){return this.mode=0,this.color=e,this}betweenTwoColors(e,t){return this.mode=2,this.colorMin=e,this.colorMax=t,this}mode=0;color;colorMin;colorMax;gradient;gradientMin;gradientMax;static _temp=new te(0,0,0,1);static _temp2=new te(0,0,0,1);evaluate(e,t){const i=t===void 0?Math.random():t;switch(this.mode){case 0:case"Color":return this.color;case 1:case"Gradient":return this.gradient.evaluate(e,_t._temp),_t._temp;case 2:case"TwoColors":return _t._temp.lerpColors(this.colorMin,this.colorMax,i);case 3:case"TwoGradients":return this.gradientMin.evaluate(e,_t._temp),this.gradientMax.evaluate(e,_t._temp2),_t._temp.lerp(_t._temp2,i);case 4:case"RandomColor":const o=Math.random();return this.gradientMin.evaluate(e,_t._temp),this.gradientMax.evaluate(e,_t._temp2),_t._temp.lerp(_t._temp2,o)}return _t._temp.set(16777215),_t._temp.alpha=1,_t._temp}};C([f()],Oo.prototype,"mode");C([f(te)],Oo.prototype,"color");C([f(te)],Oo.prototype,"colorMin");C([f(te)],Oo.prototype,"colorMax");C([f(Dr)],Oo.prototype,"gradient");C([f(Dr)],Oo.prototype,"gradientMin");C([f(Dr)],Oo.prototype,"gradientMax");let Lr=Oo;var xm=(s=>(s[s.Hierarchy=0]="Hierarchy",s[s.Local=1]="Local",s[s.Shape=2]="Shape",s))(xm||{});class Lt{cullingMode;duration;emitterVelocityMode;flipRotation;gravityModifier;gravityModifierMultiplier;loop;maxParticles;playOnAwake;prewarm;ringBufferLoopRange;ringBufferMode;scalingMode;simulationSpace;simulationSpeed;startColor;startDelay;startDelayMultiplier;startLifetime;startLifetimeMultiplier;startRotation;startRotationMultiplier;startRotation3D;startRotationX;startRotationXMultiplier;startRotationY;startRotationYMultiplier;startRotationZ;startRotationZMultiplier;startSize;startSize3D;startSizeMultiplier;startSizeX;startSizeXMultiplier;startSizeY;startSizeYMultiplier;startSizeZ;startSizeZMultiplier;startSpeed;startSpeedMultiplier;stopAction;useUnscaledTime}C([f(H)],Lt.prototype,"gravityModifier");C([f(Lr)],Lt.prototype,"startColor");C([f(H)],Lt.prototype,"startDelay");C([f(H)],Lt.prototype,"startLifetime");C([f(H)],Lt.prototype,"startRotation");C([f(H)],Lt.prototype,"startRotationX");C([f(H)],Lt.prototype,"startRotationY");C([f(H)],Lt.prototype,"startRotationZ");C([f(H)],Lt.prototype,"startSize");C([f(H)],Lt.prototype,"startSizeX");C([f(H)],Lt.prototype,"startSizeY");C([f(H)],Lt.prototype,"startSizeZ");C([f(H)],Lt.prototype,"startSpeed");class du{cycleCount;maxCount;minCount;probability;repeatInterval;time;count;_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 i=this.time+this.repeatInterval*this._performed;if(e>=i&&(this._performed+=1,Math.random()<this.probability))switch(this.count.mode){case 0:t=this.count.constant;break;case 3:t=I.lerp(this.count.constantMin,this.count.constantMax,Math.random());break;case 1:t=this.count.curve.evaluate(Math.random());break;case 2:const n=Math.random();t=I.lerp(this.count.curveMin.evaluate(n),this.count.curveMax.evaluate(n),Math.random());break}}return t}}class Rs{enabled;get burstCount(){return this.bursts?.length??0}bursts;rateOverTime;rateOverTimeMultiplier;rateOverDistance;rateOverDistanceMultiplier;system;reset(){this.bursts?.forEach(e=>e.reset())}getBurst(){let e=0;if(this.burstCount>0)for(let t=0;t<this.burstCount;t++){const i=this.bursts[t];this.system.main.loop&&i.time>=this.system.time&&i.reset(),e+=Math.round(i.run(this.system.time))}return e}}C([f()],Rs.prototype,"enabled");C([f()],Rs.prototype,"bursts");C([f(H)],Rs.prototype,"rateOverTime");C([f()],Rs.prototype,"rateOverTimeMultiplier");C([f(H)],Rs.prototype,"rateOverDistance");C([f()],Rs.prototype,"rateOverDistanceMultiplier");class af{enabled;color}C([f(Lr)],af.prototype,"color");class Ir{enabled;separateAxes;size;sizeMultiplier;x;xMultiplier;y;yMultiplier;z;zMultiplier;_time=0;_temp=new c.Vector3;evaluate(e,t,i){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,i)*this.xMultiplier,t.y=this.y.evaluate(e,i)*this.yMultiplier,t.z=this.z.evaluate(e,i)*this.zMultiplier;else{const n=this.size.evaluate(e,i)*this.sizeMultiplier;t.x=n}return t}}C([f(H)],Ir.prototype,"size");C([f(H)],Ir.prototype,"x");C([f(H)],Ir.prototype,"y");C([f(H)],Ir.prototype,"z");const Ye=class Yl{get type(){return hu[this.shapeType]}initialize(e){this.onInitialize(e),e.position.x=this._vector.x,e.position.y=this._vector.y,e.position.z=this._vector.z}toJSON(){return this}clone(){return new Yl}shapeType=5;enabled=!0;alignToDirection=!1;angle=0;arc=360;arcSpread;arcSpeedMultiplier;arcMode;boxThickness;position;rotation;_rotation=new c.Euler;scale;radius;radiusThickness;sphericalDirectionAmount;randomDirectionAmount;randomPositionAmount;meshShapeType;meshRenderer;_meshObj;_meshGeometry;setMesh(e){this.meshRenderer=e,e?(this._meshObj=e.sharedMeshes[Math.floor(Math.random()*e.sharedMeshes.length)],this._meshGeometry=this._meshObj.geometry):(this._meshObj=void 0,this._meshGeometry=void 0)}system;_space;_worldSpaceMatrix=new c.Matrix4;_worldSpaceMatrixInverse=new c.Matrix4;constructor(){cd&&console.log(this)}update(e,t){}onUpdate(e,t,i,n){this.system=e,this._space=i,i===1&&(this._worldSpaceMatrix.copy(n.matrixWorld),this._worldSpaceMatrix.elements[0]=1,this._worldSpaceMatrix.elements[5]=1,this._worldSpaceMatrix.elements[10]=1,this._worldSpaceMatrixInverse.copy(this._worldSpaceMatrix).invert())}applyRotation(e){const t=this.rotation.x!==0||this.rotation.y!==0||this.rotation.z!==0;return t&&(this._rotation.x=I.toRadians(this.rotation.x),this._rotation.y=I.toRadians(this.rotation.y),this._rotation.z=I.toRadians(this.rotation.z),this._rotation.order="ZYX",e.applyEuler(this._rotation)),t}_vector=new c.Vector3(0,0,0);_temp=new c.Vector3(0,0,0);_triangle=new c.Triangle;onInitialize(e){this._vector.set(0,0,0),e.mesh=void 0,e.mesh_geometry=void 0;const t=this._temp.copy(this.position),i=this._space===1;i&&t.applyQuaternion(this.system.worldQuaternion);let n=this.radius;if(i&&(n*=this.system.worldScale.x),this.enabled){switch(this.shapeType){case 5:cd&&B.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(t);break;case 4:this.randomConePoint(this.position,this.angle,n,this.radiusThickness,this.arc,this.arcMode,this._vector);break;case 0:this.randomSpherePoint(this.position,n,this.radiusThickness,this.arc,this._vector);break;case 10:this.randomCirclePoint(this.position,n,this.radiusThickness,this.arc,this._vector);break;case 13:const o=this.meshRenderer;o?.destroyed==!1&&this.setMesh(o);const r=e.mesh=this._meshObj,a=e.mesh_geometry=this._meshGeometry;if(r&&a)switch(this.meshShapeType){case 0:{const l=a.getAttribute("position"),h=Math.floor(Math.random()*l.count);this._vector.fromBufferAttribute(l,h),this._vector.applyMatrix4(r.matrixWorld),e.mesh_normal=h}break;case 1:break;case 2:{const l=a.index;if(l){let h=Math.random(),d=Math.random();h+d>1&&(h=1-h,d=1-d);const u=Math.floor(Math.random()*(l.count/3));let p=u*3,m=u*3+1,y=u*3+2;p=l.getX(p),m=l.getX(m),y=l.getX(y);const _=a.getAttribute("position");this._triangle.a.fromBufferAttribute(_,p),this._triangle.b.fromBufferAttribute(_,m),this._triangle.c.fromBufferAttribute(_,y),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),e.mesh_normal=u}}break}break;default:this._vector.set(0,0,0),A()&&!globalThis.__particlesystem_shapetype_unsupported&&(console.warn("ParticleSystem ShapeType is not supported:",hu[this.shapeType]),globalThis.__particlesystem_shapetype_unsupported=!0);break}this.randomizePosition(this._vector,this.randomPositionAmount)}this.applyRotation(this._vector),i&&(this._vector.applyQuaternion(this.system.worldQuaternion),this._vector.add(this.system.worldPos)),cd&&B.DrawSphere(this._vector,.03,16711680,.5,!0)}_dir=new c.Vector3;getDirection(e,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 i=t.x,n=t.y,o=t.z;this._dir.set(i,n,o),this.system?.worldspace?this._dir.sub(this.system.worldPos):this._dir.sub(this.position);break;case 13:const r=e.mesh,a=e.mesh_geometry;if(r&&a)switch(this.meshShapeType){case 0:{const l=a.getAttribute("normal"),h=e.mesh_normal;this._dir.fromBufferAttribute(l,h)}break;case 1:break;case 2:{const l=a.index;if(l){const h=e.mesh_normal,d=l.getX(h*3),u=l.getX(h*3+1),p=l.getX(h*3+2),m=a.getAttribute("position"),y=F(),_=F(),g=F();y.fromBufferAttribute(m,d),_.fromBufferAttribute(m,u),g.fromBufferAttribute(m,p),y.sub(_),g.sub(_),y.cross(g),this._dir.copy(y).multiplyScalar(-1);const v=pe(r);this._dir.applyQuaternion(v)}}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),cd&&(B.DrawSphere(t,.01,8925952,.5,!0),B.DrawDirection(t,this._dir,8925952,.5,!0)),this._dir}static _randomQuat=new c.Quaternion;static _tempVec=new c.Vector3;randomizePosition(e,t){if(t<=0)return;const i=Yl._tempVec;i.set(Math.random()*2-1,Math.random()*2-1,Math.random()*2-1),i.x*=t*this.scale.x,i.y*=t*this.scale.y,i.z*=t*this.scale.z,e.add(i)}randomizeDirection(e,t){if(t===0)return;const i=Yl._randomQuat,n=Yl._tempVec;n.set(Math.random()-.5,Math.random()-.5,Math.random()-.5).normalize(),i.setFromAxisAngle(n,t*Math.random()*Math.PI),e.applyQuaternion(i)}spherizeDirection(e,t){if(t===0)return;const i=Math.random()*Math.PI*2,n=Math.acos(1-Math.random()*2),o=Math.sin(n)*Math.cos(i),r=Math.sin(n)*Math.sin(i),a=Math.cos(n),l=new c.Vector3(o,r,a);e.lerp(l,t)}randomSpherePoint(e,t,i,n,o){const r=Math.random(),a=Math.random(),l=2*Math.PI*r*(n/360),h=Math.acos(2*a-1),d=I.lerp(1,1-Math.pow(1-Math.random(),Math.PI),i)*t,u=e.x+this.scale.x*(-d*Math.sin(h)*Math.cos(l)),p=e.y+this.scale.y*(d*Math.sin(h)*Math.sin(l)),m=e.z+this.scale.z*(d*Math.cos(h));o.x=u,o.y=p,o.z=m}randomCirclePoint(e,t,i,n,o){const r=Math.random(),a=2*Math.PI*r*(n/360),l=I.lerp(1,1-Math.pow(1-Math.random(),Math.PI),i)*t,h=e.x+this.scale.x*l*Math.cos(a),d=e.y+this.scale.y*l*Math.sin(a),u=e.z;o.x=h,o.y=d,o.z=u}_loopTime=0;_loopDirection=1;randomConePoint(e,t,i,n,o,r,a){let l=0,h=0;switch(r){case 0:l=Math.random(),h=Math.random();break;case 2:this._loopTime>1&&(this._loopDirection=-1),this._loopTime<0&&(this._loopDirection=1);case 1:l=.5,h=Math.random(),this._loopTime+=this.system.deltaTime*this._loopDirection;break}let d=2*Math.PI*l*(o/360);switch(r){case 2:case 1:d+=Math.PI+.5,d+=this._loopTime*Math.PI*2,d%=I.toRadians(o);break}const u=Math.acos(2*h-1),p=I.lerp(1,1-Math.pow(1-Math.random(),Math.PI),n)*i,m=e.x+-p*Math.sin(u)*Math.cos(d),y=e.y+p*Math.sin(u)*Math.sin(d),_=e.z;a.x=m*this.scale.x,a.y=y*this.scale.y,a.z=_*this.scale.z}};C([f()],Ye.prototype,"shapeType");C([f()],Ye.prototype,"enabled");C([f()],Ye.prototype,"alignToDirection");C([f()],Ye.prototype,"angle");C([f()],Ye.prototype,"arc");C([f()],Ye.prototype,"arcSpread");C([f()],Ye.prototype,"arcSpeedMultiplier");C([f()],Ye.prototype,"arcMode");C([f(c.Vector3)],Ye.prototype,"boxThickness");C([f(c.Vector3)],Ye.prototype,"position");C([f(c.Vector3)],Ye.prototype,"rotation");C([f(c.Vector3)],Ye.prototype,"scale");C([f()],Ye.prototype,"radius");C([f()],Ye.prototype,"radiusThickness");C([f()],Ye.prototype,"sphericalDirectionAmount");C([f()],Ye.prototype,"randomDirectionAmount");C([f()],Ye.prototype,"randomPositionAmount");C([f()],Ye.prototype,"meshShapeType");C([f(lh)],Ye.prototype,"meshRenderer");let ky=Ye;class me{damping;enabled;frequency;octaveCount;octaveMultiplier;octaveScale;positionAmount;quality;remap;remapEnabled;remapMultiplier;remapX;remapXMultiplier;remapY;remapYMultiplier;remapZ;remapZMultiplier;scrollSpeedMultiplier;separateAxes;strengthMultiplier;strengthX;strengthXMultiplier;strengthY;strengthYMultiplier;strengthZ;strengthZMultiplier;_noise;_time=0;update(e){this._time+=e.time.deltaTime*this.scrollSpeedMultiplier}_temp=new c.Vector3;apply(e,t,i,n,o,r){if(!this.enabled)return;this._noise||(this._noise=le.createNoise4D(()=>0));const a=this._temp.set(t.x,t.y,t.z).multiplyScalar(this.frequency),l=this._noise(a.x,a.y,a.z,this._time),h=this._noise(a.x,a.y,a.z,this._time+1e3*this.frequency),d=this._noise(a.x,a.y,a.z,this._time+2e3*this.frequency);this._temp.set(l,h,d).normalize();const u=o/r;let p=this.positionAmount.evaluate(u);this.separateAxes?(this._temp.x*=p*this.strengthXMultiplier,this._temp.y*=p*this.strengthYMultiplier,this._temp.z*=p*this.strengthZMultiplier):(this.strengthX&&(p*=this.strengthX.evaluate(u)*1.5),this._temp.multiplyScalar(p)),i.x+=this._temp.x,i.y+=this._temp.y,i.z+=this._temp.z}}C([f()],me.prototype,"damping");C([f()],me.prototype,"enabled");C([f()],me.prototype,"frequency");C([f()],me.prototype,"octaveCount");C([f()],me.prototype,"octaveMultiplier");C([f()],me.prototype,"octaveScale");C([f(H)],me.prototype,"positionAmount");C([f()],me.prototype,"quality");C([f(H)],me.prototype,"remap");C([f()],me.prototype,"remapEnabled");C([f()],me.prototype,"remapMultiplier");C([f(H)],me.prototype,"remapX");C([f()],me.prototype,"remapXMultiplier");C([f(H)],me.prototype,"remapY");C([f()],me.prototype,"remapYMultiplier");C([f(H)],me.prototype,"remapZ");C([f()],me.prototype,"remapZMultiplier");C([f()],me.prototype,"scrollSpeedMultiplier");C([f()],me.prototype,"separateAxes");C([f()],me.prototype,"strengthMultiplier");C([f(H)],me.prototype,"strengthX");C([f()],me.prototype,"strengthXMultiplier");C([f(H)],me.prototype,"strengthY");C([f()],me.prototype,"strengthYMultiplier");C([f(H)],me.prototype,"strengthZ");C([f()],me.prototype,"strengthZMultiplier");class Le{enabled;attachRibbonToTransform=!1;colorOverLifetime;colorOverTrail;dieWithParticles=!0;inheritParticleColor=!0;lifetime;lifetimeMultiplier;minVertexDistance=.2;mode=0;ratio=1;ribbonCount=1;shadowBias=0;sizeAffectsLifetime=!1;sizeAffectsWidth=!1;splitSubEmitterRibbons=!1;textureMode=0;widthOverTrail;widthOverTrailMultiplier;worldSpace=!1;getWidth(e,t,i,n){const o=this.widthOverTrail.evaluate(i,n);return e*=o,e}getColor(e,t,i){const n=this.colorOverTrail.evaluate(i),o=this.colorOverLifetime.evaluate(t);e.x*=n.r*o.r,e.y*=n.g*o.g,e.z*=n.b*o.b,"alpha"in n&&"alpha"in o&&(e.w*=n.alpha*o.alpha)}}C([f()],Le.prototype,"enabled");C([f()],Le.prototype,"attachRibbonToTransform");C([f(Lr)],Le.prototype,"colorOverLifetime");C([f(Lr)],Le.prototype,"colorOverTrail");C([f()],Le.prototype,"dieWithParticles");C([f()],Le.prototype,"inheritParticleColor");C([f(H)],Le.prototype,"lifetime");C([f()],Le.prototype,"lifetimeMultiplier");C([f()],Le.prototype,"minVertexDistance");C([f()],Le.prototype,"mode");C([f()],Le.prototype,"ratio");C([f()],Le.prototype,"ribbonCount");C([f()],Le.prototype,"shadowBias");C([f()],Le.prototype,"sizeAffectsLifetime");C([f()],Le.prototype,"sizeAffectsWidth");C([f()],Le.prototype,"splitSubEmitterRibbons");C([f()],Le.prototype,"textureMode");C([f(H)],Le.prototype,"widthOverTrail");C([f()],Le.prototype,"widthOverTrailMultiplier");C([f()],Le.prototype,"worldSpace");class Fe{enabled;space=0;orbitalX;orbitalY;orbitalZ;orbitalXMultiplier;orbitalYMultiplier;orbitalZMultiplier;orbitalOffsetX;orbitalOffsetY;orbitalOffsetZ;speedModifier;speedModifierMultiplier;x;xMultiplier;y;yMultiplier;z;zMultiplier;_system;update(e){this._system=e}_temp=new c.Vector3;_temp2=new c.Vector3;_temp3=new c.Vector3;_hasOrbital=!1;_index=0;_orbitalMatrix=new c.Matrix4;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,i,n,o,r,a){if(!this.enabled)return;const l=r/a,h=this.speedModifier.evaluate(l)*this.speedModifierMultiplier,d=this.x.evaluate(l),u=this.y.evaluate(l),p=this.z.evaluate(l);if(this._temp.set(-d,u,p),this._system&&this._system.main.simulationSpace===1&&this._temp.applyQuaternion(this._system.worldQuaternion),this._hasOrbital&&this._system?.worldPos){const y=this._temp2.set(i.x,i.y,i.z),_=this.orbitalXMultiplier,g=this.orbitalYMultiplier,v=this.orbitalZMultiplier,b=h*Math.PI*2*10,w=Math.cos(b*_),R=Math.sin(b*_),O=Math.cos(b*g),M=Math.sin(b*g),D=Math.cos(b*v),L=Math.sin(b*v),j=y.x*(O*D)+y.y*(O*L)+y.z*-M,V=y.x*(R*M*D-w*L)+y.y*(R*M*L+w*D)+y.z*(R*O),W=y.x*(w*M*D+R*L)+y.y*(w*M*L-R*D)+y.z*(w*O),k=this._temp3.set(y.x-j,y.y-V,y.z-W);k.normalize(),k.multiplyScalar(.2/o*Math.max(this.orbitalXMultiplier,this.orbitalYMultiplier,this.orbitalZMultiplier)),n.x+=k.x,n.y+=k.y,n.z+=k.z}n.x+=this._temp.x,n.y+=this._temp.y,n.z+=this._temp.z,n.x*=h,n.y*=h,n.z*=h}}C([f()],Fe.prototype,"enabled");C([f()],Fe.prototype,"space");C([f(H)],Fe.prototype,"orbitalX");C([f(H)],Fe.prototype,"orbitalY");C([f(H)],Fe.prototype,"orbitalZ");C([f()],Fe.prototype,"orbitalXMultiplier");C([f()],Fe.prototype,"orbitalYMultiplier");C([f()],Fe.prototype,"orbitalZMultiplier");C([f()],Fe.prototype,"orbitalOffsetX");C([f()],Fe.prototype,"orbitalOffsetY");C([f()],Fe.prototype,"orbitalOffsetZ");C([f(H)],Fe.prototype,"speedModifier");C([f()],Fe.prototype,"speedModifierMultiplier");C([f(H)],Fe.prototype,"x");C([f()],Fe.prototype,"xMultiplier");C([f(H)],Fe.prototype,"y");C([f()],Fe.prototype,"yMultiplier");C([f(H)],Fe.prototype,"z");C([f()],Fe.prototype,"zMultiplier");class It{animation;enabled;cycleCount;frameOverTime;frameOverTimeMultiplier;numTilesX;numTilesY;startFrame;startFrameMultiplier;rowMode;rowIndex;spriteCount;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 i=this.frameOverTime.evaluate(e%1);return i*=this.frameOverTimeMultiplier,i*=t,i=i%t,i=Math.floor(i),i}}C([f()],It.prototype,"animation");C([f()],It.prototype,"enabled");C([f()],It.prototype,"cycleCount");C([f(H)],It.prototype,"frameOverTime");C([f()],It.prototype,"frameOverTimeMultiplier");C([f()],It.prototype,"numTilesX");C([f()],It.prototype,"numTilesY");C([f(H)],It.prototype,"startFrame");C([f()],It.prototype,"startFrameMultiplier");C([f()],It.prototype,"rowMode");C([f()],It.prototype,"rowIndex");C([f()],It.prototype,"spriteCount");C([f()],It.prototype,"timeMode");class _n{enabled;separateAxes;x;xMultiplier;y;yMultiplier;z;zMultiplier;evaluate(e,t){return this.enabled?this.separateAxes?0:this.z.evaluate(e,t)*-1:0}}C([f()],_n.prototype,"enabled");C([f()],_n.prototype,"separateAxes");C([f(H)],_n.prototype,"x");C([f()],_n.prototype,"xMultiplier");C([f(H)],_n.prototype,"y");C([f()],_n.prototype,"yMultiplier");C([f(H)],_n.prototype,"z");C([f()],_n.prototype,"zMultiplier");class Qi{enabled;range;separateAxes;x;xMultiplier;y;yMultiplier;z;zMultiplier;evaluate(e,t){if(!this.enabled)return 0;if(!this.separateAxes){const i=I.lerp(this.range.x,this.range.y,t);return this.z.evaluate(i)*-1}return 0}}C([f()],Qi.prototype,"enabled");C([f()],Qi.prototype,"range");C([f()],Qi.prototype,"separateAxes");C([f(H)],Qi.prototype,"x");C([f()],Qi.prototype,"xMultiplier");C([f(H)],Qi.prototype,"y");C([f()],Qi.prototype,"yMultiplier");C([f(H)],Qi.prototype,"z");C([f()],Qi.prototype,"zMultiplier");class nt{enabled;dampen;drag;dragMultiplier;limit;limitMultiplier;separateAxes;limitX;limitXMultiplier;limitY;limitYMultiplier;limitZ;limitZMultiplier;multiplyDragByParticleSize=!1;multiplyDragByParticleVelocity=!1;space;_temp=new c.Vector3;_temp2=new c.Vector3;apply(e,t,i,n,o,r,a){if(this.enabled){const l=this.limit.evaluate(o)*this.limitMultiplier;if(t.length()>l){this._temp.copy(t).normalize().multiplyScalar(l);const d=this.dampen*.5;t.x=I.lerp(t.x,this._temp.x,d),t.y=I.lerp(t.y,this._temp.y,d),t.z=I.lerp(t.z,this._temp.z,d),i.x=I.lerp(i.x,this._temp.x,d),i.y=I.lerp(i.y,this._temp.y,d),i.z=I.lerp(i.z,this._temp.z,d)}}}}C([f()],nt.prototype,"enabled");C([f()],nt.prototype,"dampen");C([f(H)],nt.prototype,"drag");C([f()],nt.prototype,"dragMultiplier");C([f(H)],nt.prototype,"limit");C([f()],nt.prototype,"limitMultiplier");C([f()],nt.prototype,"separateAxes");C([f(H)],nt.prototype,"limitX");C([f()],nt.prototype,"limitXMultiplier");C([f(H)],nt.prototype,"limitY");C([f()],nt.prototype,"limitYMultiplier");C([f(H)],nt.prototype,"limitZ");C([f()],nt.prototype,"limitZMultiplier");C([f()],nt.prototype,"multiplyDragByParticleSize");C([f()],nt.prototype,"multiplyDragByParticleVelocity");C([f()],nt.prototype,"space");const _h=class bx{enabled;curve;curveMultiplier;mode;clone(){const e=new bx;return e.enabled=this.enabled,e.curve=this.curve?.clone(),e.curveMultiplier=this.curveMultiplier,e.mode=this.mode,e}system;get _lastWorldPosition(){return this.system._iv_lastWorldPosition||(this.system._iv_lastWorldPosition=new c.Vector3),this.system._iv_lastWorldPosition}get _velocity(){return this.system._iv_velocity||(this.system._iv_velocity=new c.Vector3),this.system._iv_velocity}_temp=new c.Vector3;_firstUpdate=!0;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}}_frames=0;applyCurrent(e,t,i){if(this.enabled&&this.system&&this.system.worldspace!==!1&&this.mode===1){const n=this.curve.evaluate(t,i);this._temp.copy(this._velocity).multiplyScalar(n),e.x+=this._temp.x,e.y+=this._temp.y,e.z+=this._temp.z}}};C([f()],_h.prototype,"enabled");C([f(H)],_h.prototype,"curve");C([f()],_h.prototype,"curveMultiplier");C([f()],_h.prototype,"mode");let Ey=_h;class di{enabled;range;separateAxes;size;sizeMultiplier;x;xMultiplier;y;yMultiplier;z;zMultiplier;evaluate(e,t,i,n){const o=e.length(),r=I.remap(o,this.range.x,this.range.y,0,1),a=this.size.evaluate(r,i);return n.x*=a,n.y*=a,n.z*=a,n}}C([f()],di.prototype,"enabled");C([f(c.Vector2)],di.prototype,"range");C([f()],di.prototype,"separateAxes");C([f(H)],di.prototype,"size");C([f()],di.prototype,"sizeMultiplier");C([f(H)],di.prototype,"x");C([f()],di.prototype,"xMultiplier");C([f(H)],di.prototype,"y");C([f()],di.prototype,"yMultiplier");C([f(H)],di.prototype,"z");C([f()],di.prototype,"zMultiplier");class rl{enabled;range;color;evaluate(e,t,i){const n=e.length(),o=I.remap(n,this.range.x,this.range.y,0,1),r=this.color.evaluate(o,t);i.x*=r.r,i.y*=r.g,i.z*=r.b,"alpha"in r&&(i.w*=r.alpha)}}C([f()],rl.prototype,"enabled");C([f(c.Vector2)],rl.prototype,"range");C([f(Lr)],rl.prototype,"color");new c.Vector3(1,1,1);new c.Vector3(0,0,1);class Ry{constructor(e,t,i,n){this.system=e,this.particleSystem=t,this.subSystem=i,this.subParticleSystem=n,this.subParticleSystem&&this.subParticleSystem&&(this.subParticleSystem.onlyUsedByOther=!0);const o=1e3;this._circularBuffer=new _i(()=>new le.Matrix4,o)}type="NeedleParticleSubEmitter";emitterType;emitterProbability;q_=new c.Quaternion;v_=new c.Vector3;v2_=new c.Vector3;_emitterMatrix=new le.Matrix4;_circularBuffer;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===Sm.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===Sm.Death){let n=e.life;if(e[ga]!==void 0&&(n=e[ga]),!(e.age+t*1.2>=n))return;const r=this.subSystem.main.maxParticles-this.subSystem.currentParticles;e.emissionState.waitEmiting=r}const i=new le.Matrix4;i.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||i.multiplyMatrices(this._emitterMatrix,i),this.subParticleSystem.emit(t,e.emissionState,i)}}var IE=Object.defineProperty,Ie=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&IE(e,t,n),n};const Js=x("debugparticles"),jE=x("noprogressive"),BE=x("debugprogressive");var Sm=(s=>(s[s.Birth=0]="Birth",s[s.Collision=1]="Collision",s[s.Death=2]="Death",s[s.Trigger=3]="Trigger",s[s.Manual=4]="Manual",s))(Sm||{});class Yi extends E{renderMode;particleMaterial;trailMaterial;particleMesh;maxParticleSize;minParticleSize;velocityScale;cameraVelocityScale;lengthScale;start(){if(this.maxParticleSize!==.5&&this.minParticleSize!==0&&A()){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(){return this.particleMaterial?.transparent??!1}getMaterial(e=!1){let t=e===!0&&this.trailMaterial?this.trailMaterial:this.particleMaterial;if(t){if(t.type==="MeshStandardMaterial"){Js&&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=c.LinearSRGBColorSpace,t.map.premultiplyAlpha=!1);const i=new c.MeshBasicMaterial;i.copy(t),e?this.trailMaterial=i:this.particleMaterial=i}t.map&&(t.map.colorSpace=c.LinearSRGBColorSpace,t.map.premultiplyAlpha=!1),e&&t.side===c.FrontSide&&(t=t.clone(),t.side=c.BackSide,e?this.trailMaterial=t:this.particleMaterial=t)}return t&&!jE&&t._didRequestTextureLOD===void 0&&(t._didRequestTextureLOD=0,BE&&console.log("Load material LOD",t.name),re.NEEDLE_progressive.assignTextureLOD(t,0)),t}getMesh(e){let t=null;if(!t&&(this.particleMesh instanceof c.Mesh&&(t=this.particleMesh.geometry),t===null)){t=new c.PlaneGeometry(1,1);const n=t.attributes.uv;for(let o=0;o<n.count;o++)n.setX(o,1-n.getX(o))}return new c.Mesh(t,this.getMaterial())}}Ie([f()],Yi.prototype,"renderMode");Ie([f(c.Material)],Yi.prototype,"particleMaterial");Ie([f(c.Material)],Yi.prototype,"trailMaterial");Ie([f()],Yi.prototype,"maxParticleSize");Ie([f()],Yi.prototype,"minParticleSize");Ie([f()],Yi.prototype,"velocityScale");Ie([f()],Yi.prototype,"cameraVelocityScale");Ie([f()],Yi.prototype,"lengthScale");class hd{_curve;_factor;constructor(e,t=1){this._curve=e,this._factor=t}type="function";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 Ty{type="value";toJSON(){throw new Error("Method not implemented.")}clone(){throw new Error("Method not implemented.")}startGen(e){}system;constructor(e){this.system=e}}class FE extends Ty{genValue(){return this.system.textureSheetAnimation.getStartIndex()}}class UE extends Ty{_lastPosition=new c.Vector3;_lastDistance=0;update(){const e=Y(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 n=this.system.emission.rateOverDistance.evaluate(this.system.time/this.system.duration,Math.random());let r=this._lastDistance/this.system.deltaTime*n;Number.isFinite(r)||(r=0),e+=r}const t=this.system.emission.getBurst();t>0&&(e+=t/this.system.deltaTime);const i=this.system.maxParticles-this.system.currentParticles;return I.clamp(e,0,i/this.system.deltaTime)}}class zE extends Ty{genValue(){return this.system.isPlaying,0}}class Mo{system;get context(){return this.system.context}constructor(e){this.type=Object.getPrototypeOf(this).constructor.name||"ParticleSystemBaseBehaviour",e&&(this.system=e)}type;initialize(e){}update(e,t){}frameUpdate(e){}toJSON(){throw new Error("Method not implemented.")}clone(){throw new Error("Method not implemented.")}reset(){}}class NE extends Mo{type="NeedleTextureSheet";update(e,t){const i=this.system.textureSheetAnimation;if(i.enabled){const n=e.age/e.life,o=i.evaluate(n);o!==void 0&&(e.uvTile=o)}}}const $b=Symbol("particleRotation");class VE extends Mo{type="NeedleRotation";initialize(e){e[$b]=Math.random()}update(e,t){if(e.rotation===void 0)return;const i=e.age/e.life;if(typeof e.rotation=="number"&&(this.system.rotationOverLifetime.enabled?e.rotation+=this.system.rotationOverLifetime.evaluate(i,e[$b])*t:this.system.renderer.renderMode===rs.Billboard&&(e.rotation=Math.PI),this.system.rotationBySpeed.enabled)){const n=e.velocity.length();e.rotation+=this.system.rotationBySpeed.evaluate(i,n)*t}}}const Wb=Symbol("sizeLerpFactor"),$E=new c.Vector3;class WE extends Mo{type="NeedleSize";_minSize=0;_maxSize=1;initialize(e){e[Wb]=Math.random(),this._minSize=this.system.renderer.minParticleSize,this._maxSize=this.system.renderer.maxParticleSize}update(e,t){const i=e.age/e.life;let n=1;this.system.sizeOverLifetime.enabled&&(n*=this.system.sizeOverLifetime.evaluate(i,void 0,e[Wb]).x);let o=1;this.system.renderer.renderMode!==rs.Mesh&&(o=this.system.worldScale.x/this.system.cameraScale);const r=F(e.startSize).multiplyScalar(n*o);if(e.size.set(r.x,r.y,r.z),this.system.localspace){const a=vx(this.system,$E);e.size.x*=a.x,e.size.y*=a.y,e.size.z*=a.z}}}const ga=Symbol("particleLife"),gp=Symbol("trailLifetime"),Gb=Symbol("trailStartLength"),yp=Symbol("trailWidthRandom");class GE extends Mo{type="NeedleTrail";initialize(e){e instanceof le.TrailParticle&&(e[ga]=e.life,this.system.trails.enabled&&this.system.trails.dieWithParticles===!1&&(e[gp]=this.system.trails.lifetime.evaluate(Math.random(),Math.random()),e.life+=e[gp]),e[Gb]=e.length,e[yp]=Math.random())}update(e){if(this.system.trails?.enabled&&e instanceof le.TrailParticle){const t=e,i=e.age/e[ga],n=e.previous.values(),o=e.previous.length;for(let r=0;r<o;r++){const l=n.next().value,h=1-r/(o-1),d=e.size;if(d.x<=0&&!this.system.trails.sizeAffectsWidth){const u=20*this.system.trails.widthOverTrail.evaluate(.5,t[yp]);d.x=u,d.y=u,d.z=u}l.size=this.system.trails.getWidth(d.x,i,h,t[yp]),l.color.copy(e.color),this.system.trails.getColor(l.color,i,h)}if(e.age>e[ga]){e.velocity.set(0,0,0);const r=(e.age-e[ga])/e[gp];t.length=I.lerp(e[Gb],0,r)}}}}const dd=Symbol("startVelocity"),Hb=Symbol("gravityModifier"),_p=Symbol("gravitySpeed"),ud=Symbol("velocity lerp factor"),Cm=new c.Vector3;class HE extends Mo{type="NeedleVelocity";_gravityDirection=new c.Vector3;initialize(e){const t=this.system.main.simulationSpeed;e.startSpeed=this.system.main.startSpeed.evaluate(Math.random(),Math.random());const i=this.system.shape.getDirection(e,e.position);e.velocity.x=i.x*e.startSpeed,e.velocity.y=i.y*e.startSpeed,e.velocity.z=i.z*e.startSpeed,this.system.inheritVelocity?.enabled&&this.system.inheritVelocity.applyInitial(e.velocity),e[dd]?e[dd].copy(e.velocity):e[dd]=e.velocity.clone();const n=this.system.main.gravityModifier.evaluate(Math.random(),Math.random());e[Hb]=n*t,e[_p]=n*t*.5,e[ud]=Math.random(),this.system.velocityOverLifetime?.init(e),this._gravityDirection.set(0,-1,0),this.system.main.simulationSpace===Lc.Local&&this._gravityDirection.applyQuaternion(this.system.worldQuaternionInverted).normalize()}update(e,t){const i=e[dd],n=e[Hb];if(n!==0){const u=n*e[_p];Cm.copy(this._gravityDirection).multiplyScalar(u),e[_p]+=t*.05,i.add(Cm)}e.velocity.copy(i);const o=e.age/e.life;this.system.inheritVelocity?.enabled&&this.system.inheritVelocity.applyCurrent(e.velocity,o,e[ud]);const r=this.system.noise;r.enabled&&r.apply(0,e.position,e.velocity,t,e.age,e.life);const a=this.system.sizeBySpeed;a?.enabled&&(e.size=a.evaluate(e.velocity,o,e[ud],e.size));const l=this.system.colorBySpeed;l?.enabled&&l.evaluate(e.velocity,e[ud],e.color);const h=this.system.velocityOverLifetime;h.enabled&&h.apply(e,0,e.position,e.velocity,t,e.age,e.life);const d=this.system.limitVelocityOverLifetime;if(d.enabled&&d.apply(e.position,i,e.velocity,e.size,o,t,1),this.system.worldspace){const u=this.system.worldScale;e.velocity.x*=u.x,e.velocity.y*=u.y,e.velocity.z*=u.z}}}const qb=Symbol("colorLerpFactor"),Xb=new te(1,1,1,1),zo=new te(1,1,1,1);class qE extends Mo{type="NeedleColor";initialize(e){}_init(e){const t=this.system.renderer.particleMaterial;zo.copy(this.system.main.startColor.evaluate(Math.random())),t?.color&&(Xb.copy(t.color),zo.multiply(Xb)),zo.convertLinearToSRGB(),e.startColor.set(zo.r,zo.g,zo.b,zo.alpha),e.color.copy(e.startColor),e[qb]=Math.random()}update(e,t){if(e.age===0&&this._init(e),this.system.colorOverLifetime.enabled){const i=e.age/e.life,n=this.system.colorOverLifetime.color.evaluate(i,e[qb]);e.color.set(n.r,n.g,n.b,"alpha"in n?n.alpha:1).multiply(e.startColor)}else e.color.copy(e.startColor)}}class XE{system;emission;get anim(){return this.system.textureSheetAnimation}constructor(e){this.system=e,this.emission=new UE(this.system)}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()}autoDestroy;get looping(){return this.system.main.loop}get duration(){return this.system.duration}get shape(){return this.system.shape}get startLife(){return new hd(this.system.main.startLifetime)}get startSpeed(){return new hd(this.system.main.startSpeed)}get startRotation(){return new hd(this.system.main.startRotation)}get startSize(){return new hd(this.system.main.startSize)}startLength;get startColor(){return new le.ConstantColor(new le.Vector4(1,1,1,1))}get emissionOverTime(){return this.emission}get emissionOverDistance(){return new zE(this.system)}emissionBursts;onlyUsedByOther;behaviors=[];get instancingGeometry(){return this.system.renderer.getMesh(this.system.renderer.renderMode).geometry}get renderMode(){if(this.system.trails.enabled===!0)return le.RenderMode.Trail;switch(this.system.renderer.renderMode){case rs.Billboard:return le.RenderMode.BillBoard;case rs.Stretch:return le.RenderMode.StretchedBillBoard;case rs.HorizontalBillboard:return le.RenderMode.HorizontalBillBoard;case rs.VerticalBillboard:return le.RenderMode.VerticalBillBoard;case rs.Mesh:return le.RenderMode.Mesh}return le.RenderMode.BillBoard}rendererEmitterSettings={startLength:new le.ConstantValue(220),followLocalOrigin:!1};get speedFactor(){let e=this.system.main.simulationSpeed;return this.system.renderer?.renderMode===rs.Stretch&&(e*=this.system.renderer.velocityScale??1),e}flatWhiteTexture;clonedTexture={original:void 0,clone:void 0};get texture(){const e=this.material;if(e&&e.map){const t=e.map;if(this.clonedTexture.original!==t||!this.clonedTexture.clone){const i=t.clone();i.premultiplyAlpha=!1,i.colorSpace=c.LinearSRGBColorSpace,this.clonedTexture.original=t,this.clonedTexture.clone=i}return this.clonedTexture.clone}return this.flatWhiteTexture||(this.flatWhiteTexture=cg(new te(1,1,1,1),1)),this.flatWhiteTexture}get startTileIndex(){return new FE(this.system)}get uTileCount(){return this.anim.enabled?this.anim?.numTilesX:void 0}get vTileCount(){return this.anim.enabled?this.anim?.numTilesY:void 0}get renderOrder(){return 1}get blending(){return this.system.renderer.particleMaterial?.blending??c.NormalBlending}get transparent(){return this.system.renderer.transparent}get worldSpace(){return this.system.main.simulationSpace===Lc.World}}class QE{burstParticleIndex=0;burstParticleCount=0;isBursting=!1;travelDistance=0;previousWorldPos;burstIndex=0;burstWaveIndex=0;time=0;waitEmiting=0}const jt=class Bd extends E{play(e=!1){e&&S.foreachComponent(this.gameObject,t=>{t instanceof Bd&&t!==this&&t.play(!1)},!0),this._isPlaying=!0,this._particleSystem&&(this._particleSystem.emissionState.time=0,this._particleSystem.emitEnded=!1),this.emission?.reset()}pause(e=!0){e&&S.foreachComponent(this.gameObject,t=>{t instanceof Bd&&t!==this&&t.pause(!1)},!0),this._isPlaying=!1}stop(e=!0,t=!1){e&&S.foreachComponent(this.gameObject,i=>{i instanceof Bd&&i!==this&&i.stop(!1,t)},!0),this._isPlaying=!1,this._time=0,t&&this.reset()}reset(){this._time=0,this._particleSystem&&(this._particleSystem.particleNum=0,this._particleSystem.emissionState.time=0,this._particleSystem.emitEnded=!1,this.emission?.reset())}_state;emit(e){if(this._particleSystem){this.onUpdate(),e=Math.min(e,this.maxParticles-this.currentParticles),this._state||(this._state=new QE),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}colorOverLifetime;main;emission;sizeOverLifetime;shape;noise;trails;velocityOverLifetime;limitVelocityOverLifetime;inheritVelocity;colorBySpeed;textureSheetAnimation;rotationOverLifetime;rotationBySpeed;sizeBySpeed;get renderer(){return this._renderer}get isPlaying(){return this._isPlaying}get currentParticles(){return this._particleSystem?.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}_cameraScale=1;get container(){return this._container}get worldspace(){return this.main.simulationSpace===Lc.World}get localspace(){return this.main.simulationSpace===Lc.Local}__worldQuaternion=new c.Quaternion;get worldQuaternion(){return this.__worldQuaternion}_worldQuaternionInverted=new c.Quaternion;get worldQuaternionInverted(){return this._worldQuaternionInverted}_worldScale=new c.Vector3;get worldScale(){return this._worldScale}_worldPositionFrame=-1;_worldPos=new c.Vector3;get worldPos(){return this._worldPositionFrame!==this.context.time.frame&&(this._worldPositionFrame=this.context.time.frame,Y(this.gameObject,this._worldPos)),this._worldPos}get matrixWorld(){return this._container.matrixWorld}get isSubsystem(){return this._isUsedAsSubsystem}addBehaviour(e){return this._particleSystem?(e instanceof Mo&&(e.system=this),Js&&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,i=t.indexOf(e);return i!==-1&&((A()||Js)&&console.debug("Remove custom ParticleSystem Behaviour",i,e),t.splice(i,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}_renderer;_batchSystem;_particleSystem;_interface;_container;_time=0;_isPlaying=!0;_isUsedAsSubsystem=!1;_didPreWarm=!1;set bursts(e){for(let t=0;t<e.length;t++){const i=e[t];if(!(i instanceof du)){const n=new du;Ra(n,i),e[t]=n}}this._bursts=e}_bursts;set subEmitterSystems(e){for(let t=0;t<e.length;t++){const i=e[t];if(!(i instanceof uu)){const n=new uu;Ra(n,i),e[t]=n}}Js&&e.length>0&&console.log("SubEmitters: ",e,this),this._subEmitterSystems=e}_subEmitterSystems;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(Yi),!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 c.Object3D,this._container.matrixAutoUpdate=!1,this.context.scene.add(this._container),this._batchSystem=new le.BatchedParticleRenderer,this._batchSystem.name=this.gameObject.name,this._container.add(this._batchSystem),this._interface=new XE(this),this._particleSystem=new le.ParticleSystem(this._interface),this._particleSystem.addBehavior(new WE(this)),this._particleSystem.addBehavior(new qE(this)),this._particleSystem.addBehavior(new NE(this)),this._particleSystem.addBehavior(new VE(this)),this._particleSystem.addBehavior(new HE(this)),this._particleSystem.addBehavior(new GE(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),Js&&(console.log(this),this.gameObject.add(new c.AxesHelper(1)))}start(){this.addSubParticleSystems(),this.updateLayers(),this.renderer.particleMesh instanceof c.Mesh&&this._interface.renderMode==le.RenderMode.Mesh&&re.NEEDLE_progressive.assignMeshLOD(this.renderer.particleMesh,0).then(e=>{e&&this.particleSystem&&this._interface.renderMode==le.RenderMode.Mesh&&(this.particleSystem.instancingGeometry=e)})}onDestroy(){this._container?.removeFromParent(),this._batchSystem?.removeFromParent(),this._particleSystem?.emitter.removeFromParent(),this._particleSystem?.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(){this.main&&(this._didPreWarm===!1&&this.main?.prewarm===!0&&(this._didPreWarm=!0,this.preWarm()),this.onUpdate(),this.onSimulate(this.deltaTime))}preWarm(){if(!this.emission?.enabled||this.emission.rateOverTime.getMax()<=0)return;const t=1/60,i=this.main.duration,n=this.main.startLifetime.getMax(),r=Math.min(Math.max(i,n)/Math.max(.01,this.main.simulationSpeed),1e3),a=Math.ceil(r/t),l=Date.now();Js&&console.log(`Particles ${this.name} - Prewarm for ${a} frames (${r} sec). Duration: ${i}, Lifetime: ${n}`);for(let h=0;h<a&&!(this.currentParticles>=this.maxParticles);h++){const d=Date.now()-l;if(d>2e3){console.warn(`Particles ${this.name} - Prewarm took too long. Aborting: ${d}`);break}this.onUpdate(),this.onSimulate(t)}}_lastBatchesCount=-1;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 i=this.layer;t.layers.mask=1<<i}}onUpdate(){if(this._bursts&&(this.emission.bursts=this._bursts,delete this._bursts),!this._isPlaying)return;const e=this.context.mainCamera;if(e){const n=je(e);this._cameraScale=n.x}const t=!this.worldspace,i=this.gameObject;if(pe(i,this.__worldQuaternion),this._worldQuaternionInverted.copy(this.__worldQuaternion).invert(),je(this.gameObject,this._worldScale),t&&this._container&&this.gameObject?.parent){const n=vx(this,Cm);this._container.matrix.makeScale(n.x,n.y,n.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),this.inheritVelocity?.update(this.context),this.velocityOverLifetime.update(this)}addSubParticleSystems(){if(this._subEmitterSystems&&this._particleSystem)for(const e of this._subEmitterSystems){e.particleSystem&&(e.particleSystem.__internalAwake?e.particleSystem.__internalAwake():A()&&console.warn("SubParticleSystem serialization issue(?)",e.particleSystem,e));const t=e.particleSystem?._particleSystem;if(t){e.particleSystem._isUsedAsSubsystem=!0;const i=new Ry(this,this._particleSystem,e.particleSystem,t);i.emitterType=e.type,i.emitterProbability=e.emitProbability,this._particleSystem.addBehavior(i)}else Js&&console.warn("Could not add SubParticleSystem",e,this)}}};Ie([f(af)],jt.prototype,"colorOverLifetime");Ie([f(Lt)],jt.prototype,"main");Ie([f(Rs)],jt.prototype,"emission");Ie([f(Ir)],jt.prototype,"sizeOverLifetime");Ie([f(ky)],jt.prototype,"shape");Ie([f(me)],jt.prototype,"noise");Ie([f(Le)],jt.prototype,"trails");Ie([f(Fe)],jt.prototype,"velocityOverLifetime");Ie([f(nt)],jt.prototype,"limitVelocityOverLifetime");Ie([f(Ey)],jt.prototype,"inheritVelocity");Ie([f(rl)],jt.prototype,"colorBySpeed");Ie([f(It)],jt.prototype,"textureSheetAnimation");Ie([f(_n)],jt.prototype,"rotationOverLifetime");Ie([f(Qi)],jt.prototype,"rotationBySpeed");Ie([f(di)],jt.prototype,"sizeBySpeed");let Ic=jt;class uu{particleSystem;emitProbability=1;properties;type;_deserialize(e,t){const i=this.particleSystem;if(i instanceof Ic)return;let n="";i&&typeof i.guid=="string"&&(n=i.guid,this.particleSystem=S.findByGuid(n,t)),Js&&!(this.particleSystem instanceof Ic)&&console.warn("Could not find particle system for sub emitter",n,t,this)}}function vx(s,e){if(e.set(1,1,1),s.gameObject.parent&&s.localspace)switch(s.main.scalingMode){case xm.Local:e=je(s.gameObject.parent,e),e.x=1/e.x,e.y=1/e.y,e.z=1/e.z;break;default:if(!s.unsupported_scaling_mode){s.unsupported_scaling_mode=!0;const t="ParticleSystem scale mode "+xm[s.main.scalingMode]+" is not supported";A()&&fe(t),console.warn(t,s.name,s)}e=je(s.gameObject,e);break}return e}var YE=Object.defineProperty,Ay=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&YE(e,t,n),n};class al extends E{strength=1;radius=2;targets=[];update(){const e=this.gameObject.worldPosition,t=-this.strength*this.context.time.deltaTime;this.targets?.forEach(i=>{if(!i)return;const n=i.gameObject.worldPosition.sub(e),o=n.length();if(o>this.radius)return;let r=t;o>1?r/=o*o:r/=Math.max(.05,o),i.applyImpulse(n.multiplyScalar(r))})}}Ay([f()],al.prototype,"strength");Ay([f()],al.prototype,"radius");Ay([f($e)],al.prototype,"targets");class Ua extends E{_didAssignPlayerColor=!1;onEnable(){this.context.connection.beginListen(K.JoinedRoom,this.tryAssignColor),this._didAssignPlayerColor||this.startCoroutine(this.waitForConnection())}onDisable(){this.context.connection.stopListen(K.JoinedRoom,this.tryAssignColor)}*waitForConnection(){for(;!this.destroyed&&this.activeAndEnabled&&(yield sg(.2),!this.tryAssignColor()););}tryAssignColor=()=>{const e=S.getComponentInParent(this.gameObject,zi);if(e&&e.owner)return this._didAssignPlayerColor=!0,this.assignUserColor(e.owner),!0;const t=S.getComponentInParent(this.gameObject,Oe);return t?.connectionId?(this._didAssignPlayerColor=!0,this.assignUserColor(t.connectionId),!0):!1};assignUserColor(e){const t=Ua.hashCode(e),i=Ua.colorFromHashCode(t);if(this.gameObject.type==="Mesh"){const n=this.gameObject;this.assignColor(i,e,n)}else if(this.gameObject.children)for(const n of this.gameObject.children){const o=n;o.material&&o.material.color&&this.assignColor(i,e,o)}}assignColor(e,t,i){let n=i.material;n&&(n._playerMaterial!==t&&(n=n.clone(),n._playerMaterial=t,i.material=n),n.color=e)}static hashCode(e){var t=0,i,n;if(e.length===0)return t;for(i=0;i<e.length;i++)n=e.charCodeAt(i),t=(t<<5)-t+n,t|=0;return t}static colorFromHashCode(e){const t=(e&16711680)>>16,i=(e&65280)>>8,n=e&255;return new c.Color(t/255,i/255,n/255)}}const Kl=x("debugpost");let Pm=null;function KE(s){Pm=s}function wx(s){let e=s.gameObject;for(;e;){for(const t of ku(e))if(t.isPostProcessingManager===!0)return t;e=e.parent}return null}function ZE(s){let e=wx(s);if(!e)if(Pm){Kl&&console.warn("Adding postprocessing manager to the scene.");const t=s.scene;e=hn(t,Pm)}else A()&&console.warn("No post processing manager found");return e}const et={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 Ge=null;function JE(s){if(Kl==="verbose"&&console.debug("Before ordering effects",[...s]),!Ge){Ge=new Map,Ge.set(T.POSTPROCESSING.MODULE.NormalPass,et.NormalPass),Ge.set(T.POSTPROCESSING.MODULE.DepthDownsamplingPass,et.DepthDownsamplingPass),Ge.set(T.POSTPROCESSING.MODULE.SMAAEffect,et.SMAA),Ge.set(T.POSTPROCESSING.MODULE.SSAOEffect,et.SSAO);const e=T.POSTPROCESSING_AO.MAYBEMODULE;e&&(Ge.set(e.N8AOPostPass,et.SSAO),Ge.set(e.N8AOPass,et.SSAO)),Ge.set(T.POSTPROCESSING.MODULE.TiltShiftEffect,et.TiltShift),Ge.set(T.POSTPROCESSING.MODULE.DepthOfFieldEffect,et.DepthOfField),Ge.set(T.POSTPROCESSING.MODULE.ChromaticAberrationEffect,et.ChromaticAberration),Ge.set(T.POSTPROCESSING.MODULE.BloomEffect,et.Bloom),Ge.set(T.POSTPROCESSING.MODULE.SelectiveBloomEffect,et.Bloom),Ge.set(T.POSTPROCESSING.MODULE.VignetteEffect,et.Vignette),Ge.set(T.POSTPROCESSING.MODULE.PixelationEffect,et.Pixelation),Ge.set(T.POSTPROCESSING.MODULE.ToneMappingEffect,et.ToneMapping),Ge.set(T.POSTPROCESSING.MODULE.HueSaturationEffect,et.HueSaturation),Ge.set(T.POSTPROCESSING.MODULE.BrightnessContrastEffect,et.BrightnessContrast)}s.sort((e,t)=>{const i=typeof e.priority=="number"?e.priority:Ge.get(e.effect.constructor)??Number.NEGATIVE_INFINITY,n=typeof t.priority=="number"?t.priority:Ge.get(t.effect.constructor)??Number.NEGATIVE_INFINITY;return i===Number.NEGATIVE_INFINITY?(Kl&&console.warn("Unknown effect found: ",e.constructor.name,e),1):n===Number.NEGATIVE_INFINITY?(Kl&&console.warn("Unknown effect found: ",t.constructor.name,t),-1):i-n}),Kl==="verbose"&&console.debug("After ordering effects",[...s])}var eR=Object.defineProperty,tR=Object.getOwnPropertyDescriptor,xx=(s,e,t,i)=>{for(var n=tR(e,t),o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&eR(e,t,n),n};const iR=x("debugpost");class z{isVolumeParameter=!0;constructor(e){e!==void 0&&this.initialize(e)}_isInitialized=!1;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)}_active=!0;get value(){return this._valueRaw}set value(e){this.isInitialized||this.initialize(e),this.processValue(e,!1)}_value;_valueRaw;set defaultValue(e){this._defaultValue=e}_defaultValue=void 0;__init(){this.processValue(this._valueRaw,!0)}valueProcessor;onValueChanged;processValue(e,t){if(e==null||!t&&this.testIfValueChanged(e)===!1)return;const i=this._value;iR&&typeof i=="number"&&typeof e=="number"&&(i?.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,i,this)}testIfValueChanged(e){return this._valueRaw!==e}}xx([f()],z.prototype,"overrideState");xx([f()],z.prototype,"value");class nR extends Hi{constructor(){super([z])}onSerialize(e,t){}onDeserialize(e,t){const i=t.target,n=t.path;let o;if(i&&n&&(o=i[n]),(typeof o!="object"||typeof o=="object"&&o.isVolumeParameter!==!0)&&(o=new z),typeof e=="object"&&"value"in e){const r=e.value;o.initialize(r),o.overrideState=e.overrideState}else o.value=e;return o}}new nR;var sR=Object.defineProperty,oR=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&sR(e,t,n),n};const bp=x("debugpost");class Xe extends E{get isPostProcessingEffect(){return!0}order=void 0;constructor(e=void 0){if(super(),e)for(const t of Object.keys(e)){const i=e[t],n=this[t];n instanceof z?n.initialize(i):n!==void 0&&(this[t]=i)}}active=!0;_manager=null;onEnable(){super.onEnable(),bp&&console.warn("Enable",this.constructor.name+(this.__internalDidAwakeAndStart?"":" (awake)")),this.__internalDidAwakeAndStart&&(this.active=!0),this.onEffectEnabled()}onDisable(){super.onDisable(),bp&&console.warn("Disable",this.constructor.name),this._manager?.removeEffect(this),this.active=!1}onEffectEnabled(e){e&&e.isPostProcessingManager===!0?this._manager=e:this._manager||(this._manager=ZE(this)),this._manager.addEffect(this),this._manager.dirty=!0}init(){}_result;_postprocessingContext=null;get postprocessingContext(){return this._postprocessingContext}apply(e){return this._postprocessingContext=e,this._result||(this.initParameters(),this._result=this.onCreateEffect?.call(this)),this._result&&this.initParameters(),this._result}unapply(){}dispose(){bp&&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 i=this[t];i instanceof z&&i.__init()}}onEditorModification(e){const t=e.propertyName;if(this[t]instanceof z){const i=e.value;return this[t].value=i,!0}}}oR([f()],Xe.prototype,"active");var rR=Object.defineProperty,aR=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&rR(e,t,n),n};const lR=x("debugpost"),Om={};function Ki(s,e){Om[s]=e}function cR(s){return s.__type in Om?Om[s.__type]:(lR&&s.__type&&console.warn("Unknown postprocessing type",s.__type,s),Xe)}class lf{components=[];__init(e){this.components?.forEach(t=>{t.gameObject===void 0&&e.gameObject.addComponent(t),t.init()})}addEffect(e){this.components.push(e)}removeEffect(e){const t=this.components.indexOf(e);t>=0&&this.components.splice(t,1)}}aR([Be([s=>cR(s),Xe])],lf.prototype,"components");var hR=Object.defineProperty,dR=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&hR(e,t,n),n};const uR=x("debugpost");class bh extends Xe{get typeName(){return"Antialiasing"}preset=new z(2);onCreateEffect(){const e=new T.POSTPROCESSING.MODULE.SMAAEffect({preset:this.preset?.value??T.POSTPROCESSING.MODULE.SMAAPreset.HIGH,edgeDetectionMode:T.POSTPROCESSING.MODULE.EdgeDetectionMode.LUMA});return this.preset.onValueChanged=t=>{uR&&console.log("Antialiasing preset changed to",t),e.applyPreset(t)},e}}dR([f(z)],bh.prototype,"preset");Ki("Antialiasing",bh);var fR=Object.defineProperty,Dy=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&fR(e,t,n),n};const cf=class Sx extends Xe{static useSelectiveBloom=!1;get typeName(){return"Bloom"}threshold=new z(.9);intensity=new z(1);scatter=new z(.7);selectiveBloom;init(){this.threshold.valueProcessor=e=>e,this.intensity.valueProcessor=e=>e,this.scatter.valueProcessor=e=>e}onCreateEffect(){let e;if(this.selectiveBloom==null&&(this.selectiveBloom=Sx.useSelectiveBloom),this.selectiveBloom){const t=e=new T.POSTPROCESSING.MODULE.SelectiveBloomEffect(this.context.scene,this.context.mainCamera,{blendFunction:T.POSTPROCESSING.MODULE.BlendFunction.ADD,mipmapBlur:!0,luminanceThreshold:this.threshold.value,luminanceSmoothing:this.scatter.value,radius:.85,intensity:this.intensity.value});t.inverted=!0}else e=new T.POSTPROCESSING.MODULE.BloomEffect({blendFunction:T.POSTPROCESSING.MODULE.BlendFunction.ADD,mipmapBlur:!0,luminanceThreshold:this.threshold.value,luminanceSmoothing:this.scatter.value,radius:.85,intensity:this.intensity.value});return this.intensity.onValueChanged=t=>{e.intensity=t},this.threshold.onValueChanged=t=>{e.luminanceMaterial.threshold=Math.pow(t,2.2)},this.scatter.onValueChanged=t=>{e.luminancePass.enabled=!0,e.luminanceMaterial.smoothing=t,e.mipmapBlurPass&&(e.mipmapBlurPass.radius=c.MathUtils.lerp(.1,.9,t))},e}};Dy([f(z)],cf.prototype,"threshold");Dy([f(z)],cf.prototype,"intensity");Dy([f(z)],cf.prototype,"scatter");let hf=cf;Ki("Bloom",hf);var pR=Object.defineProperty,mR=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&pR(e,t,n),n};class vh extends Xe{get typeName(){return"ChromaticAberration"}intensity=new z(0);onCreateEffect(){const e=new T.POSTPROCESSING.MODULE.ChromaticAberrationEffect;return e.offset=new c.Vector2(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}}mR([f(z)],vh.prototype,"intensity");Ki("ChromaticAberration",vh);var Zl=(s=>(s[s.None=0]="None",s[s.Neutral=1]="Neutral",s[s.ACES=2]="ACES",s[s.AgX=3]="AgX",s[s.KhronosNeutral=4]="KhronosNeutral",s))(Zl||{});const Qb=new Map;function vp(s){switch(s){case 0:return c.LinearToneMapping;case 1:return c.ReinhardToneMapping;case 2:return c.ACESFilmicToneMapping;case 3:return c.AgXToneMapping;case 4:return c.NeutralToneMapping;default:return Qb.has(s)||(Qb.set(s,!0),console.warn("[Postprocessing] Unknown tone mapping mode",s)),c.NeutralToneMapping}}function gR(s){switch(s){case c.LinearToneMapping:return 0;case c.ACESFilmicToneMapping:return 2;case c.AgXToneMapping:return 3;case c.NeutralToneMapping:return 1;case c.ReinhardToneMapping:return 1;default:return 0}}function Fd(s){switch(s){case c.LinearToneMapping:return T.POSTPROCESSING.MODULE.ToneMappingMode.LINEAR;case c.ACESFilmicToneMapping:return T.POSTPROCESSING.MODULE.ToneMappingMode.ACES_FILMIC;case c.AgXToneMapping:return T.POSTPROCESSING.MODULE.ToneMappingMode.AGX;case c.NeutralToneMapping:return T.POSTPROCESSING.MODULE.ToneMappingMode.NEUTRAL;case c.ReinhardToneMapping:return T.POSTPROCESSING.MODULE.ToneMappingMode.REINHARD;default:return T.POSTPROCESSING.MODULE.ToneMappingMode.LINEAR}}var yR=Object.defineProperty,Cx=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&yR(e,t,n),n};const wp=x("debugpost");class mo extends Xe{get typeName(){return"ToneMapping"}mode=new z(void 0);exposure=new z(1);setMode(e){const t=Zl[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=wx(this);e&&super.onEffectEnabled(e)}_tonemappingEffect=null;onCreateEffect(){if(this.mode.isInitialized==!1){const i=gR(this.context.renderer.toneMapping);wp&&console.log("[PostProcessing] Initializing ToneMapping mode to renderer.toneMapping",this.context.renderer.toneMapping+" → "+i),this.mode.initialize(i)}this._tonemappingEffect?.dispose();const e=vp(this.mode.value),t=this._tonemappingEffect=new T.POSTPROCESSING.MODULE.ToneMappingEffect({mode:Fd(e)});return this.mode.onValueChanged=i=>{if(typeof i=="string")i=T0(i),t.mode=Fd(i);else{const n=vp(i);t.mode=Fd(n)}t.name="ToneMapping ("+Zl[i]+")",wp&&console.log("[PostProcessing] ToneMapping mode changed to",Zl[i],e,t.mode)},wp&&console.log("[PostProcessing] Use ToneMapping",Zl[this.mode.value],e,t.mode,"renderer.tonemapping: "+this.context.renderer.toneMapping),t}onBeforeRender(){if(this._tonemappingEffect&&this.postprocessingContext?.handler.getEffectIsActive(this._tonemappingEffect)&&(this.mode.overrideState&&(this.context.renderer.toneMapping=vp(this.mode.value)),this.exposure.overrideState&&this.exposure.value!==void 0)){const e=Math.max(0,this.exposure.value);this.context.renderer.toneMappingExposure=e}}}Cx([f(z)],mo.prototype,"mode");Cx([f(z)],mo.prototype,"exposure");Ki("Tonemapping",mo);var _R=Object.defineProperty,df=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&_R(e,t,n),n};class ko extends Xe{get typeName(){return"ColorAdjustments"}remap=!0;postExposure=new z(1);contrast=new z(0);hueShift=new z(0);saturation=new z(0);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(){const e=[];let t=this.postprocessingContext?.components.find(o=>o instanceof mo);t||(t=new mo,this.postprocessingContext?.components.push(t)),this.postExposure.onValueChanged=o=>{this.postExposure.overrideState&&t?t.exposure.value=o: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 i=new T.POSTPROCESSING.MODULE.BrightnessContrastEffect;this.contrast.onValueChanged=o=>i.contrast=o;const n=new T.POSTPROCESSING.MODULE.HueSaturationEffect;return this.hueShift.onValueChanged=o=>n.hue=o,this.saturation.onValueChanged=o=>n.saturation=o,e.push(i),e.push(n),e}}df([f(z)],ko.prototype,"postExposure");df([f(z)],ko.prototype,"contrast");df([f(z)],ko.prototype,"hueShift");df([f(z)],ko.prototype,"saturation");Ki("ColorAdjustments",ko);var bR=Object.defineProperty,jr=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&bR(e,t,n),n};const vR=x("debugpost");class bn extends Xe{get typeName(){return"DepthOfField"}mode;focusDistance=new z(1);focalLength=new z(.2);aperture=new z(20);gaussianMaxRadius=new z;resolutionScale=new z(1/window.devicePixelRatio);bokehScale=new z;init(){this.focalLength.valueProcessor=t=>{const i=t/300;return I.lerp(2,.01,i)};const e=20;this.aperture.valueProcessor=t=>{const i=1-t/32;return I.lerp(1,e,i)}}onCreateEffect(){if(this.mode===0){vR&&console.warn("DepthOfField: Mode is set to Off");return}const e=new T.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(){}}jr([f()],bn.prototype,"mode");jr([f(z)],bn.prototype,"focusDistance");jr([f(z)],bn.prototype,"focalLength");jr([f(z)],bn.prototype,"aperture");jr([f(z)],bn.prototype,"gaussianMaxRadius");jr([f(z)],bn.prototype,"resolutionScale");jr([f(z)],bn.prototype,"bokehScale");Ki("DepthOfField",bn);class jc extends Xe{effect;constructor(e){super(),this.effect=e}get typeName(){return this.effect.constructor.name}onCreateEffect(){return this.effect}}var wR=Object.defineProperty,xR=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&wR(e,t,n),n};class wh extends Xe{get typeName(){return"PixelationEffect"}granularity=new z(10);onCreateEffect(){const e=new T.POSTPROCESSING.MODULE.PixelationEffect;return this.granularity.onValueChanged=t=>{e.granularity=t},e}}xR([f(z)],wh.prototype,"granularity");Ki("PixelationEffect",wh);var SR=Object.defineProperty,xh=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&SR(e,t,n),n};class Ts extends Xe{get typeName(){return"ScreenSpaceAmbientOcclusion"}intensity=new z(2);falloff=new z(1);samples=new z(9);color=new z(new c.Color(0,0,0));luminanceInfluence=new z(.7);onBeforeRender(){if(this._ssao&&this.context.mainCamera instanceof c.PerspectiveCamera){const e=this.context.mainCamera.far-this.context.mainCamera.near;this._ssao.ssaoMaterial.worldDistanceFalloff=e*.01,this._ssao.ssaoMaterial.worldDistanceThreshold=this.context.mainCamera.far}}_ssao;onCreateEffect(){const e=this.context.mainCamera,t=new T.POSTPROCESSING.MODULE.NormalPass(this.context.scene,e),i=new T.POSTPROCESSING.MODULE.DepthDownsamplingPass({normalBuffer:t.texture,resolutionScale:.5}),n=this._ssao=new T.POSTPROCESSING.MODULE.SSAOEffect(e,t.texture,{normalDepthBuffer:i.texture,worldDistanceThreshold:1,worldDistanceFalloff:1,worldProximityThreshold:.1,worldProximityFalloff:2,intensity:1,blendFunction:T.POSTPROCESSING.MODULE.BlendFunction.MULTIPLY,luminanceInfluence:.5});this.intensity.onValueChanged=r=>{n.intensity=r},this.falloff.onValueChanged=r=>{n.ssaoMaterial.radius=r*.1},this.samples.onValueChanged=r=>{n.ssaoMaterial.samples=r},this.color.onValueChanged=r=>{n.color||(n.color=new c.Color),n.color.copy(r)},this.luminanceInfluence.onValueChanged=r=>{n.luminanceInfluence=r};const o=new Array;return o.push(t),o.push(i),o.push(n),o}}xh([f(z)],Ts.prototype,"intensity");xh([f(z)],Ts.prototype,"falloff");xh([f(z)],Ts.prototype,"samples");xh([f(z)],Ts.prototype,"color");xh([f(z)],Ts.prototype,"luminanceInfluence");Ki("ScreenSpaceAmbientOcclusion",Ts);var CR=Object.defineProperty,Br=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&CR(e,t,n),n};const PR=x("debugN8AO");var Mm=(s=>(s[s.Performance=0]="Performance",s[s.Low=1]="Low",s[s.Medium=2]="Medium",s[s.High=3]="High",s[s.Ultra=4]="Ultra",s))(Mm||{});class vn extends Xe{get typeName(){return"ScreenSpaceAmbientOcclusionN8"}get pass(){return this._ssao}gammaCorrection=!0;aoRadius=new z(1);falloff=new z(1);intensity=new z(1);color=new z(new c.Color(0,0,0));screenspaceRadius=!1;quality=2;_ssao;onValidate(){this._ssao&&(this._ssao.setQualityMode(Mm[this.quality]),this._ssao.configuration.gammaCorrection=this.gammaCorrection,this._ssao.configuration.screenSpaceRadius=this.screenspaceRadius)}onCreateEffect(){const e=this.context.mainCamera,t=this.context.domWidth,i=this.context.domHeight,n=this._ssao=new T.POSTPROCESSING_AO.MODULE.N8AOPostPass(this.context.scene,e,t,i);n.name="SSAO_N8";const o=Mm[this.quality];if(n.setQualityMode(o),n.configuration.transparencyAware=!1,n.configuration.halfRes=window.devicePixelRatio>1,n.effectCompositerQuad?.material){const a=n.effectCompositerQuad.material;a.fragmentShader=a.fragmentShader.replace(`if (depth == 1.0) {
|
|
1311
1311
|
texel = vec4(0.0, 0.0, 0.0, 1.0);`,`if (depth == 1.0) {
|
|
1312
1312
|
gl_FragColor = sceneTexel;
|
|
1313
1313
|
return;`),a.needsUpdate=!0}const r=new c.WebGLRenderTarget(t,i);return n.configuration.beautyRenderTarget=r,n.configuration.autoRenderBeauty=!1,n.configuration.gammaCorrection=this.gammaCorrection,n.configuration.screenSpaceRadius=this.screenspaceRadius,PR&&(n.enableDebugMode(),console.log(n),setInterval(()=>{console.log("SSAO",n.lastTime)},1e3),setInterval(()=>{console.log("SSAO",n.enabled,{ssao:n,autoRenderBeauty:n.configuration.autoRenderBeauty})},4e3)),this.intensity.onValueChanged=a=>{n.configuration.intensity=a},this.falloff.onValueChanged=a=>{n.configuration.distanceFalloff=a},this.aoRadius.onValueChanged=a=>{n.configuration.aoRadius=a},this.color.onValueChanged=a=>{n.color||(n.color=new c.Color),n.configuration.color.copy(a)},n}}Br([Ct(),f()],vn.prototype,"gammaCorrection");Br([f(z)],vn.prototype,"aoRadius");Br([f(z)],vn.prototype,"falloff");Br([f(z)],vn.prototype,"intensity");Br([f(z)],vn.prototype,"color");Br([Ct(),f()],vn.prototype,"screenspaceRadius");Br([Ct(),f()],vn.prototype,"quality");Ki("ScreenSpaceAmbientOcclusionN8",vn);var OR=Object.defineProperty,MR=Object.getOwnPropertyDescriptor,Px=(s,e,t,i)=>{for(var n=MR(e,t),o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&OR(e,t,n),n};class Sh extends Xe{get typeName(){return"Sharpening"}order=et.Sharpening;_effect;onCreateEffect(){return this._effect??=new(kR()),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}_amount=1;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}_radius=1}Px([f()],Sh.prototype,"amount");Px([f()],Sh.prototype,"radius");function kR(){const s=`
|
|
@@ -1651,4 +1651,4 @@ Needle Engine: Begin loading `+i+`
|
|
|
1651
1651
|
Needle Engine: finished loading `+i+`
|
|
1652
1652
|
`,t,`Aborted? ${u.signal.aborted}`),u.signal.aborted){console.log("Loading finished but aborted...");return}if(this._loadId!==i){console.log("Load id changed during loading process");return}this._loadingProgress01=1,r&&y&&this._loadingView?.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:n,loadedFiles:a}}))}applyAttributes(){const e=this.getOrCreateContext();if(e.renderer){const o=T0(this.toneMapping);o!==void 0&&(e.renderer.toneMapping=o);const r=this.getAttribute("tone-mapping-exposure");if(r!=null){const a=parseFloat(r);isNaN(a)||(e.renderer.toneMappingExposure=a)}}const t=this.getAttribute("background-blurriness");if(t!=null){const o=parseFloat(t);isNaN(o)||(e.scene.backgroundBlurriness=o)}const i=this.getAttribute("environment-intensity");if(i!=null){const o=parseFloat(i);isNaN(o)||(e.scene.environmentIntensity=o)}const n=this.getAttribute("background-color");if(e.renderer)if(typeof n=="string"&&n.length>0){const o=te.fromColorRepresentation(n);be&&console.debug("<needle-engine> background-color changed, str:",n,"→",o),e.renderer.setClearColor(o,o.alpha),e.scene.background=null}else this.getAttribute("background-image")&&this.setAttribute("background-image",this.getAttribute("background-image"))}onXRSessionStarted=()=>{const e=this.getOrCreateContext(),t=e.xrSessionMode;t==="immersive-ar"?this.onEnterAR(e.xrSession):t==="immersive-vr"&&this.onEnterVR(e.xrSession),e.xrSession?.addEventListener("end",()=>{this.dispatchEvent(new CustomEvent("xr-session-ended",{detail:{session:e.xrSession,context:this._context,sessionMode:t}})),t==="immersive-ar"?this.onExitAR(e.xrSession):t==="immersive-vr"&&this.onExitVR(e.xrSession)})};onReady=()=>this._loadingView?.onLoadingFinished();onError=()=>this._loadingView?.setMessage("Loading failed!");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 i=t.length-1;i>=0;i--){const n=t[i];(n==="null"||n==="undefined"||n?.length<=0)&&t.splice(i,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 i=0;i<e?.length;i++)if(e[i]!==t[i])return!0}return!1}_previouslyRegisteredMap=new Map;ensureLoadStartIsRegistered(){const e=this.getAttribute("loadstart");e&&this.registerEventFromAttribute("loadstart",e)}registerEventFromAttribute(e,t){const i=this._previouslyRegisteredMap.get(e);if(i&&(this._previouslyRegisteredMap.delete(e),this.removeEventListener(e,i)),typeof t=="string"&&t.length>0)try{const n=(0,eval)(t);typeof n=="function"&&(this._previouslyRegisteredMap.set(e,n),this.addEventListener(e,o=>n?.call(globalThis,this.getOrCreateContext(),o)))}catch(n){console.error("Error registering event "+e+'="'+t+`" failed with the following error:
|
|
1653
1653
|
`,n)}}setPublicKey(){no&&no.length>0&&this.setAttribute("public-key",no)}setVersion(){ii.length>0&&this.setAttribute("version",ii)}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){const t=this.getOrCreateContext();this.onSetupAR();const i=this.getAROverlayContainer();this._overlay_ar.onBegin(t,i,e),this.dispatchEvent(new CustomEvent("enter-ar",{detail:{session:e,context:t,htmlContainer:this._overlay_ar?.ARContainer}}))}onExitAR(e){const t=this.getOrCreateContext();this._overlay_ar.onEnd(t),this.onSetupDesktop(),this.dispatchEvent(new CustomEvent("exit-ar",{detail:{session:e,context:t,htmlContainer:this._overlay_ar?.ARContainer}}))}onEnterVR(e){const t=this.getOrCreateContext();this.onSetupVR(),this.dispatchEvent(new CustomEvent("enter-vr",{detail:{session:e,context:t}}))}onExitVR(e){const t=this.getOrCreateContext();this.onSetupDesktop(),this.dispatchEvent(new CustomEvent("exit-vr",{detail:{session:e,context:t}}))}onSetupAR(){this.classList.add(Il),this.classList.remove(jl);const e=this.getAROverlayContainer();be&&console.warn("onSetupAR:",e),e&&(e.classList.add(Il),e.classList.remove(jl)),this.foreachHtmlElement(t=>this.setupElementsForMode(t,Gx))}onSetupVR(){this.classList.remove(Il),this.classList.remove(jl),this.foreachHtmlElement(e=>this.setupElementsForMode(e,Hx))}onSetupDesktop(){this.classList.remove(Il),this.classList.add(jl);const e=this.getAROverlayContainer();e&&(e.classList.remove(Il),e.classList.add(jl)),this.foreachHtmlElement(t=>this.setupElementsForMode(t,qx))}setupElementsForMode(e,t,i=null){if(e===this._context?.renderer?.domElement||e.id==="VRButton"||e.id==="ARButton")return;if(e.classList.contains(t))e.style.visibility="visible",e.style.display==="none"&&(e.style.display="block");else for(const o of uA)e.classList.contains(o)&&(e.style.visibility="hidden",e.style.display="none")}foreachHtmlElement(e){for(let t=0;t<this.children.length;t++){const i=this.children[t];i.style&&e(i)}}onBeforeBeginLoading(){const e=this.getAttribute("dracoDecoderPath");e&&(be&&console.log("using custom draco decoder path",e),Bb(e));const t=this.getAttribute("dracoDecoderType");t&&(be&&console.log("using custom draco decoder type",t),Fb(t));const i=this.getAttribute("ktx2DecoderPath");i&&(be&&console.log("using custom ktx2 decoder path",i),Ub(i))}setAttribute(e,t){super.setAttribute(e,typeof t=="string"?t:String(t))}getAttribute(e){return super.getAttribute(e)}addEventListener(e,t,i){return super.addEventListener(e,t,i)}}function pA(s){if(s.startsWith("blob:"))return"blob";const e=s.split("/");let t=e[e.length-1];const i=t.indexOf("?");i>0&&(t=t.substring(0,i));const n=t.indexOf("=");n>0&&(t=t.substring(n));const o=t.split(".").pop(),a=o?["glb","gltf","usdz","usd","fbx","obj","mtl"].indexOf(o.toLowerCase()):-1;if(o&&a>=0&&(t=t.substring(0,t.length-o.length-1)),t=decodeURIComponent(t),t.length>3){let l="",h=!1;const d=["(",")","[","]","{","}",":",";",",",".","!","?"];for(let u=0;u<t.length;u++){let p=t[u];(p==="_"||p==="-")&&(p=" "),!(p===" "&&l.length<=0||d.includes(p)||(l.length===0&&(p=p.toUpperCase()),h&&p===" "))&&(h&&(p=p.toUpperCase()),h=!1,l+=p,p===" "&&(h=!0))}return A()&&t!==l&&console.debug('Generated display name: "'+t+'" → "'+l+'"'),l.trim()}return t}function mA(s){bu(e=>{const t=s.getAttribute("loading-blur");if(t!==null&&t!=="0"&&e.domElement===s){const i=e.lodsManager.manager?.awaitLoading({frames:5,signal:AbortSignal.timeout(1e4),maxPromisesPerObject:1}).catch(r=>{});let n="20px";t.endsWith("px")&&(n=t);const o=170;if(e.scene.background===null){const r=s,a=e.renderer.domElement,l=a.style.filter,h=a.style.overflow;a.style.filter+=`blur(${n})`,r.style.overflow="hidden",i?.then(()=>{const d=a.animate([{filter:"blur(0px)"}],{duration:o,easing:"ease-in"});d.onfinish=()=>{a.style.filter=l,r.style.overflow=h}})}else{const r=document.createElement("div");e.domElement.prepend(r),r.style.cssText="position: absolute; top: 0; left: 0; width: 100%; height: 100%; z-index: 10; pointer-events: none",r.style.backdropFilter=`blur(${n})`,i?.then(()=>{const a=r.animate([{backdropFilter:"blur(0px)",opacity:0}],{duration:o,easing:"ease-in"});a.onfinish=()=>{r.remove()}})}}},{once:!0})}const gA=Object.freeze(Object.defineProperty({__proto__:null,NeedleEngineWebComponent:qy},Symbol.toStringTag,{value:"Module"}));function yA(){typeof window>"u"||(window.customElements.get("needle-engine")||window.customElements.define("needle-engine",qy),window.customElements.get("needle-button")||window.customElements.define("needle-button",Wx),window.customElements.get("needle-logo-element")||window.customElements.define("needle-logo-element",Su),window.customElements.get("needle-menu")||window.customElements.define("needle-menu",wc))}let av=!1;function _A(){av||(av=!0,yA(),ak(),R0(),mM(),aA(),xP(),lA(),qT(),tA(),setTimeout(XT,1e3),IO(),AO(),XO(),FO())}const Ee=x("debugphysics"),Rp=x("debugcolliderplacement"),Tp=x("debugcollisions"),bA=x("showcolliders"),md=x("debugraycasts"),Kt=Symbol("needle component"),gt=Symbol("physics body"),lv=Symbol("rigidbody");globalThis.NEEDLE_USE_RAPIER=globalThis.NEEDLE_USE_RAPIER!==void 0?globalThis.NEEDLE_USE_RAPIER:!0;Ee&&console.log("Use Rapier",!0,globalThis.NEEDLE_USE_RAPIER);ce.registerCallback(ae.ContextCreationStart,s=>{Ee&&console.log("Register rapier physics backend"),s.context.physics.engine=new Oa(s.context)});class Oa{debugRenderColliders=!1;debugRenderRaycasts=!1;removeBody(e){if(Ee&&console.log("REMOVE BODY",e?.name,e[gt]),!e)return;this.validate();const t=e[gt];if(e[gt]=null,t&&this.world){const i=this.objects.findIndex(n=>n===e);if(i>=0){const n=this.bodies[i];if(this.bodies.splice(i,1),this.objects.splice(i,1),n instanceof T.RAPIER_PHYSICS.MODULE.Collider){const o=n;this.world?.removeCollider(o,!0);const r=o.parent();r&&r.numColliders()<=0&&(r[Kt]||this.world?.removeRigidBody(r))}else n instanceof T.RAPIER_PHYSICS.MODULE.RigidBody&&(n.numColliders()<=0?this.world?.removeRigidBody(n):A()&&(n.did_log_removing||setTimeout(()=>{n.numColliders()>0&&(n.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)))}}}setColliderEnabled(e,t){const i=e[gt];return i?(i.setEnabled(t),Ee&&console.log("SET COLLIDER ENABLED",e.name,t),!0):!1}updateBody(e,t,i){if(this.validate(),!!this.enabled&&!(e.destroyed||!e.gameObject)&&!(!t&&!i))if(e.isCollider===!0)console.warn("TODO: implement updating collider position");else{const n=e,o=n[gt];o&&this.syncPhysicsBody(n.gameObject,o,t,i)}}updateProperties(e){if(this.validate(),e.isCollider){const t=e,i=t[gt];i&&(this.internalUpdateColliderProperties(t,i),t.sharedMaterial&&this.updatePhysicsMaterial(t))}else{const t=e,i=this.internal_getRigidbody(t);i&&this.internalUpdateRigidbodyProperties(t,i)}}addForce(e,t,i){this.validate();const n=this.internal_getRigidbody(e);n?n.addForce(t,i):this._isInitialized&&console.warn("Physics Body doesn't exist: can not apply force (does your object with the Rigidbody have a collider?)")}addImpulse(e,t,i){this.validate();const n=this.internal_getRigidbody(e);n?n.applyImpulse(t,i):this._isInitialized&&console.warn("Physics Body 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(),this.internal_getRigidbody(e)?.resetForces(t)}resetTorques(e,t){this.validate(),this.internal_getRigidbody(e)?.resetTorques(t)}applyImpulse(e,t,i){this.validate();const n=this.internal_getRigidbody(e);n?n.applyImpulse(t,i):this._isInitialized&&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():this._isInitialized&&console.warn("Rigidbody doesn't exist: can not wake up (does your object with the Rigidbody have a collider?)")}isSleeping(e){return this.validate(),this.internal_getRigidbody(e)?.isSleeping()}setAngularVelocity(e,t,i){this.validate();const n=this.internal_getRigidbody(e);n?n.setAngvel(t,i):this._isInitialized&&console.warn("Rigidbody doesn't exist: can not set angular velocity (does your object with the Rigidbody have a collider?)")}setLinearVelocity(e,t,i){this.validate();const n=this.internal_getRigidbody(e);n?n.setLinvel(t,i):this._isInitialized&&console.warn("Rigidbody doesn't exist: can not set linear velocity (does your object with the Rigidbody have a collider?)")}context;_initializePromise;_isInitialized=!1;constructor(e){this.context=e}get isInitialized(){return this._isInitialized}async initialize(){return this._initializePromise||(this._initializePromise=this.internalInitialization()),this._initializePromise}async internalInitialization(){return x("__nophysics")?(console.warn("Physics are disabled"),!1):(Ee&&console.log("Initialize rapier physics engine"),this._hasCreatedWorld?(console.error("Invalid call to create physics world: world is already created"),!0):(this._hasCreatedWorld=!0,T.RAPIER_PHYSICS.MAYBEMODULE==null&&(Ee&&console.trace("Loading rapier physics engine"),await(await T.RAPIER_PHYSICS.load()).init()),Ee&&console.log("Physics engine initialized, creating world..."),this._world=new T.RAPIER_PHYSICS.MODULE.World(this._gravity),this.rapierRay=new T.RAPIER_PHYSICS.MODULE.Ray({x:0,y:0,z:0},{x:0,y:0,z:1}),this.enabled=!0,this._isInitialized=!0,Ee&&console.log("Physics world created"),!0))}validate(){this._isInitialized||Ee&&(this._lastWarnTime=this._lastWarnTime??0,Date.now()-this._lastWarnTime>1e3&&(this._lastWarnTime=Date.now(),console.warn("Physics engine is not initialized")))}rapierRay;raycastVectorsBuffer=new _i(()=>new c.Vector3,10);raycast(e,t,i){if(!this._isInitialized)return console.log("Physics engine is not initialized"),null;let n=i?.maxDistance,o=i?.solid;n===void 0&&(n=1/0),o===void 0&&(o=!0);const r=this.getPhysicsRay(this.rapierRay,e,t);if(!r)return null;(this.debugRenderRaycasts||md)&&B.DrawRay(r.origin,r.dir,255,1);const a=this.world?.castRay(r,n,o,i?.queryFilterFlags,i?.filterGroups,void 0,void 0,l=>{const h=l[Kt];return i?.filterPredicate?i.filterPredicate(h):i?.useIgnoreRaycastLayer!==!1?!h?.gameObject.layers.isEnabled(2):!0});if(a){const l=r.pointAt(a.timeOfImpact),h=this.raycastVectorsBuffer.get();return h.set(l.x,l.y,l.z),{point:h,collider:a.collider[Kt]}}return null}raycastAndGetNormal(e,t,i){if(!this._isInitialized)return null;let n=i?.maxDistance,o=i?.solid;n===void 0&&(n=1/0),o===void 0&&(o=!0);const r=this.getPhysicsRay(this.rapierRay,e,t);if(!r)return null;(this.debugRenderRaycasts||md)&&B.DrawRay(r.origin,r.dir,255,1);const a=this.world?.castRayAndGetNormal(r,n,o,i?.queryFilterFlags,i?.filterGroups,void 0,void 0,l=>{const h=l[Kt];return i?.filterPredicate?i.filterPredicate(h):i?.useIgnoreRaycastLayer!==!1?!h?.gameObject.layers.isEnabled(2):!0});if(a){const l=r.pointAt(a.timeOfImpact),h=a.normal,d=this.raycastVectorsBuffer.get(),u=this.raycastVectorsBuffer.get();return d.set(l.x,l.y,l.z),u.set(h.x,h.y,h.z),{point:d,normal:u,collider:a.collider[Kt]}}return null}getPhysicsRay(e,t,i){const n=this.context?.mainCamera;if(t===void 0){const a=this.context?.input.getPointerPosition(0);if(a)t=a;else return null}if(t.z===void 0){if(!n)return console.error("Can not perform raycast from 2d point - no main camera found"),null;const a=this.raycastVectorsBuffer.get();a.x=t.x,a.y=t.y,a.z=0,(a.x>1||a.y>1||a.y<-1||a.x<-1)&&(Ee&&console.warn("Converting screenspace to raycast space",a),this.context?.input.convertScreenspaceToRaycastSpace(a)),a.unproject(n),t=a}const o=t;e.origin.x=o.x,e.origin.y=o.y,e.origin.z=o.z;const r=this.raycastVectorsBuffer.get();if(i)r.set(i.x,i.y,i.z);else{if(!n)return console.error("Can not perform raycast - no camera found"),null;r.set(e.origin.x,e.origin.y,e.origin.z);const a=Y(n);r.sub(a)}return r.normalize(),e.dir.x=r.x,e.dir.y=r.y,e.dir.z=r.z,e}rapierSphere=null;rapierBox=null;rapierColliderArray=[];rapierIdentityRotation={x:0,y:0,z:0,w:1};rapierForwardVector={x:0,y:0,z:1};sphereOverlap(e,t){return this.rapierSphere??=new T.RAPIER_PHYSICS.MODULE.Ball(t),this.rapierSphere.radius=t,(this.debugRenderRaycasts||md)&&B.DrawWireSphere(e,t,3359999,1),this.shapeOverlap(e,this.rapierIdentityRotation,this.rapierSphere)}boxOverlap(e,t,i=null){return i===null&&(i=this.rapierIdentityRotation),this.rapierBox??=new T.RAPIER_PHYSICS.MODULE.Cuboid(1,1,1),this.rapierBox.halfExtents.x=t.x*.5,this.rapierBox.halfExtents.y=t.y*.5,this.rapierBox.halfExtents.z=t.z*.5,(this.debugRenderRaycasts||md)&&B.DrawWireBox(e,t,3359999,1,!0,i),this.shapeOverlap(e,i,this.rapierBox)}shapeOverlap(e,t,i){return this.rapierColliderArray.length=0,this._isInitialized?this.world?(this.world.intersectionsWithShape(e,t,i,n=>{const o=n[Kt],r=new Xv(o.gameObject,o);return this.rapierColliderArray.push(r),!0},void 0,void 0,void 0,void 0,n=>n.isSensor()?!1:n[Kt].gameObject.layers.isEnabled(2)==!1),this.rapierColliderArray):this.rapierColliderArray:this.rapierColliderArray}enabled=!1;get world(){return this._world}_tempPosition=new c.Vector3;_tempQuaternion=new c.Quaternion;_tempScale=new c.Vector3;_tempMatrix=new c.Matrix4;static _didLoadPhysicsEngine=!1;_isUpdatingPhysicsWorld=!1;get isUpdating(){return this._isUpdatingPhysicsWorld}_world;_hasCreatedWorld=!1;eventQueue;collisionHandler;objects=[];bodies=[];_meshCache=new Map;_gravity={x:0,y:-9.81,z:0};get gravity(){return this.world?.gravity??this._gravity}set gravity(e){this.world?this.world.gravity=e:this._gravity=e}clearCaches(){this._meshCache.clear(),this.eventQueue?.raw&&this.eventQueue?.free(),this.world?.bodies&&this.world?.free()}async addBoxCollider(e,t){if(this._isInitialized||await this.initialize(),!e.activeAndEnabled)return;if(!this.enabled){Ee&&console.warn("Physics are disabled");return}const i=e.gameObject,n=je(i,this._tempPosition).multiply(t);n.multiplyScalar(.5),n.x<0&&(n.x=Math.abs(n.x)),n.y<0&&(n.y=Math.abs(n.y)),n.z<0&&(n.z=Math.abs(n.z));const o=1e-7;n.x<o&&(n.x=o),n.y<o&&(n.y=o),n.z<o&&(n.z=o);const r=T.RAPIER_PHYSICS.MODULE.ColliderDesc.cuboid(n.x,n.y,n.z);this.createCollider(e,r)}async addSphereCollider(e){if(this._isInitialized||await this.initialize(),!e.activeAndEnabled)return;if(!this.enabled){Ee&&console.warn("Physics are disabled");return}const t=T.RAPIER_PHYSICS.MODULE.ColliderDesc.ball(.5);this.createCollider(e,t),this.updateProperties(e)}async addCapsuleCollider(e,t,i){if(this._isInitialized||await this.initialize(),!e.activeAndEnabled)return;if(!this.enabled){Ee&&console.warn("Physics are disabled");return}const o=e.gameObject.worldScale;o.x=Math.abs(o.x),o.y=Math.abs(o.y);const r=i*o.x;t=Math.max(t,r);const a=I.clamp(t*.5*o.y-i*o.x,0,Number.MAX_SAFE_INTEGER),l=T.RAPIER_PHYSICS.MODULE.ColliderDesc.capsule(a,r);this.createCollider(e,l)}async addMeshCollider(e,t,i,n){let o=t.geometry;if(!o){Ee&&console.warn("Missing mesh geometry",t.name);return}o.index?.array?.length||(console.warn(`Your MeshCollider is missing vertices or indices in the assined mesh "${t.name}". Consider providing an indexed geometry.`),o=X.mergeVertices(o));let r=null;const a=o.getAttribute("position");if(a instanceof c.InterleavedBufferAttribute){const u=a.count;r=new Float32Array(u*3);for(let p=0;p<u;p++){const m=a.getX(p),y=a.getY(p),_=a.getZ(p);r[p*3]=m,r[p*3+1]=y,r[p*3+2]=_}}else r=a.array;if(await this.initialize(),!this.enabled){Ee&&console.warn("Physics are disabled");return}if(!e.activeAndEnabled)return;const l=o.index?.array,h=e.gameObject.worldScale.clone();if(n&&h.multiply(n),Math.abs(h.x-1)>1e-4||Math.abs(h.y-1)>1e-4||Math.abs(h.z-1)>1e-4){const u=`${o.uuid}_${h.x}_${h.y}_${h.z}_${i}`;if(this._meshCache.has(u))Ee&&console.warn("Use cached mesh collider"),r=this._meshCache.get(u);else{(Ee||A())&&console.debug(`[Performance] Your MeshCollider "${e.name}" is scaled: consider applying the scale to the collider mesh instead (${h.x}, ${h.y}, ${h.z})`);const p=new Float32Array(r.length);for(let m=0;m<r.length;m+=3)p[m]=r[m]*h.x,p[m+1]=r[m+1]*h.y,p[m+2]=r[m+2]*h.z;r=p,this._meshCache.set(u,p)}}const d=i?T.RAPIER_PHYSICS.MODULE.ColliderDesc.convexHull(r):T.RAPIER_PHYSICS.MODULE.ColliderDesc.trimesh(r,l);d&&this.createCollider(e,d)}updatePhysicsMaterial(e){if(!e)return;const t=e.sharedMaterial,i=e[gt];if(i&&t){if(t.bounciness!==void 0&&i.setRestitution(t.bounciness),t.bounceCombine!==void 0)switch(t.bounceCombine){case st.Average:i.setRestitutionCombineRule(T.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Average);break;case st.Maximum:i.setRestitutionCombineRule(T.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Max);break;case st.Minimum:i.setRestitutionCombineRule(T.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Min);break;case st.Multiply:i.setRestitutionCombineRule(T.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Multiply);break}if(t.dynamicFriction!==void 0&&i.setFriction(t.dynamicFriction),t.frictionCombine!==void 0)switch(t.frictionCombine){case st.Average:i.setFrictionCombineRule(T.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Average);break;case st.Maximum:i.setFrictionCombineRule(T.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Max);break;case st.Minimum:i.setFrictionCombineRule(T.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Min);break;case st.Multiply:i.setFrictionCombineRule(T.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Multiply);break}}}getBody(e){return e?e[gt]:null}getComponent(e){return e?e[Kt]:null}createCollider(e,t){if(!this.world)throw new Error("Physics world not initialized");const i=this._tempMatrix;let n;e.attachedRigidbody?n=this.getRigidbody(e,this._tempMatrix):(Ee&&console.log("Create collider without rigidbody",e.name),i.makeRotationFromQuaternion(pe(e.gameObject)),i.setPosition(Y(e.gameObject))),i.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 o=e.sharedMaterial;if(o){if(o.bounciness!==void 0&&t.setRestitution(o.bounciness),o.bounceCombine!==void 0)switch(o.bounceCombine){case st.Average:t.setRestitutionCombineRule(T.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Average);break;case st.Maximum:t.setRestitutionCombineRule(T.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Max);break;case st.Minimum:t.setRestitutionCombineRule(T.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Min);break;case st.Multiply:t.setRestitutionCombineRule(T.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Multiply);break}if(o.dynamicFriction!==void 0&&t.setFriction(o.dynamicFriction),o.frictionCombine!==void 0)switch(o.frictionCombine){case st.Average:t.setFrictionCombineRule(T.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Average);break;case st.Maximum:t.setFrictionCombineRule(T.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Max);break;case st.Minimum:t.setFrictionCombineRule(T.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Min);break;case st.Multiply:t.setFrictionCombineRule(T.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Multiply);break}}e.attachedRigidbody?.autoMass===!1&&(t.setDensity(1e-6),t.setMass(1e-6));try{const r=this.world.createCollider(t,n);return r[Kt]=e,e[gt]=r,r.setActiveEvents(T.RAPIER_PHYSICS.MODULE.ActiveEvents.COLLISION_EVENTS),r.setActiveCollisionTypes(T.RAPIER_PHYSICS.MODULE.ActiveCollisionTypes.ALL),this.objects.push(e),this.bodies.push(r),this.updateColliderCollisionGroups(e),Ee&&console.log("Created collider",e.name,r),r}catch(r){return console.error('Error creating collider "'+e.name+`"
|
|
1654
|
-
Error:`,r),null}}updateColliderCollisionGroups(e){const t=e[gt],i=e.membership;let n=0;if(i==null)n=65535;else for(let a=0;a<i.length;a++){const l=i[a];l>31?console.error(`Rapier only supports 32 layers, layer ${l} is not supported`):n|=1<<Math.floor(l)}const o=e.filter;let r=0;if(o==null)r=65535;else for(let a=0;a<o.length;a++){const l=o[a];l>31?console.error(`Rapier only supports 32 layers, layer ${l} is not supported`):r|=1<<Math.floor(l)}t.setCollisionGroups(n<<16|r)}getRigidbody(e,t){if(!this.world)throw new Error("Physics world not initialized");let i=null;if(e.attachedRigidbody){const n=e.attachedRigidbody;if(i=n[gt],!i){const o=n.isKinematic&&!Rp;Ee&&console.log("Create rigidbody",o);const r=o?T.RAPIER_PHYSICS.MODULE.RigidBodyDesc.kinematicPositionBased():T.RAPIER_PHYSICS.MODULE.RigidBodyDesc.dynamic(),a=Y(e.attachedRigidbody.gameObject);r.setTranslation(a.x,a.y,a.z),r.setRotation(pe(e.attachedRigidbody.gameObject)),r.centerOfMass=new T.RAPIER_PHYSICS.MODULE.Vector3(n.centerOfMass.x,n.centerOfMass.y,n.centerOfMass.z),i=this.world.createRigidBody(r),this.bodies.push(i),this.objects.push(n)}i[Kt]=n,n[gt]=i,this.internalUpdateRigidbodyProperties(n,i),this.getRigidbodyRelativeMatrix(e.gameObject,n.gameObject,t),e[lv]=i}else{const n=T.RAPIER_PHYSICS.MODULE.RigidBodyDesc.kinematicPositionBased(),o=Y(e.gameObject);n.setTranslation(o.x,o.y,o.z),n.setRotation(pe(e.gameObject)),i=this.world.createRigidBody(n),t.identity(),i[Kt]=null}return i}internal_getRigidbody(e){return e.isCollider===!0?e[lv]:e[gt]}internalUpdateColliderProperties(e,t){const i=t.shape;let n=!1;switch(i.type){case T.RAPIER_PHYSICS.MODULE.ShapeType.Ball:{const p=i,m=e,y=e.gameObject,_=je(y,this._tempPosition),g=Math.abs(m.radius*_.x);n=p.radius!==g,p.radius=g,n&&t.setShape(p);break}case T.RAPIER_PHYSICS.MODULE.ShapeType.Cuboid:const o=i,r=e,a=e.gameObject,l=je(a,this._tempPosition),h=Math.abs(r.size.x*.5*l.x),d=Math.abs(r.size.y*.5*l.y),u=Math.abs(r.size.z*.5*l.z);n=o.halfExtents.x!==h||o.halfExtents.y!==d||o.halfExtents.z!==u,o.halfExtents.x=h,o.halfExtents.y=d,o.halfExtents.z=u,n&&t.setShape(o);break}if(n){const o=e.attachedRigidbody;o?.autoMass&&this.getBody(o)?.recomputeMassPropertiesFromColliders()}this.updateColliderCollisionGroups(e),e.isTrigger!==t.isSensor()&&t.setSensor(e.isTrigger)}internalUpdateRigidbodyProperties(e,t){if(t.enableCcd(e.collisionDetectionMode!==Au.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 i=0;i<t.numColliders();i++)t.collider(i).setDensity(1);t.recomputeMassPropertiesFromColliders()}else{t.setAdditionalMass(e.mass,!1);for(let i=0;i<t.numColliders();i++)t.collider(i).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(T.RAPIER_PHYSICS.MODULE.RigidBodyType.KinematicPositionBased,!1):t.setBodyType(T.RAPIER_PHYSICS.MODULE.RigidBodyType.Dynamic,!1)}lines;disabledLines;step(e){if(this.world&&this.enabled){if(this._isUpdatingPhysicsWorld=!0,this.eventQueue||(this.eventQueue=new T.RAPIER_PHYSICS.MODULE.EventQueue(!1)),e===void 0||e<=0){this._isUpdatingPhysicsWorld=!1;return}else if(e!==void 0){const t=I.lerp(this.world.timestep,e,.8);this.world.timestep=t}try{this.world.step(this.eventQueue)}catch(t){console.warn("Error running physics step",{timestep:this.world.timestep},t)}this._isUpdatingPhysicsWorld=!1}}postStep(){this.world&&this.enabled&&(this._isUpdatingPhysicsWorld=!0,this.syncObjects(),this._isUpdatingPhysicsWorld=!1,this.eventQueue&&!this.collisionHandler&&(this.collisionHandler=new vA(this.world,this.eventQueue)),this.collisionHandler&&(this.collisionHandler.handleCollisionEvents(),this.collisionHandler.update()),this.updateDebugRendering(this.world))}updateDebugRendering(e){if(Ee||Rp||bA||this.debugRenderColliders===!0){if(!this.lines){const n=new c.LineBasicMaterial({color:7855479,fog:!1}),o=new c.BufferGeometry;this.lines=new c.LineSegments(o,n),this.lines.layers.disableAll(),this.lines.layers.enable(2)}if(!this.disabledLines){const n=new c.LineBasicMaterial({color:14514039,fog:!1}),o=new c.BufferGeometry;this.disabledLines=new c.LineSegments(o,n),this.disabledLines.layers.disableAll(),this.disabledLines.layers.enable(2)}this.lines.parent!==this.context?.scene&&this.context?.scene.add(this.lines),this.disabledLines.parent!==this.context?.scene&&this.context?.scene.add(this.disabledLines);const t=e.debugRender(void 0,n=>n.isEnabled());this.lines.geometry.setAttribute("position",new c.BufferAttribute(t.vertices,3)),this.lines.geometry.setAttribute("color",new c.BufferAttribute(t.colors,4));const i=e.debugRender(void 0,n=>!n.isEnabled());this.disabledLines.geometry.setAttribute("position",new c.BufferAttribute(i.vertices,3)),this.disabledLines.geometry.setAttribute("color",new c.BufferAttribute(i.colors,4)),this.disabledLines.visible=i.vertices.length>0,(this.context.time.frame%30===0||this.lines.geometry.boundingSphere?.radius===0)&&(this.lines.geometry.computeBoundingSphere(),this.disabledLines.geometry.computeBoundingSphere())}else this.lines&&this.context?.scene.remove(this.lines),this.disabledLines&&this.context?.scene.remove(this.disabledLines)}syncObjects(){if(!Rp)for(let e=0;e<this.bodies.length;e++){const t=this.objects[e],i=this.bodies[e],n=t;if(n?.isCollider===!0&&!n.attachedRigidbody){const l=i.parent();l?this.syncPhysicsBody(t.gameObject,l,!0,!0):this.syncPhysicsBody(t.gameObject,i,!0,!0);continue}const o=i.translation(),r=i.rotation();if(Number.isNaN(o.x)||Number.isNaN(r.x)){!n.__COLLIDER_NAN&&A()&&(console.warn("Collider has NaN values",n.name,n.gameObject,i),n.__COLLIDER_NAN=!0);continue}const a=t.center;if(a&&a.isVector3){this._tempQuaternion.set(r.x,r.y,r.z,r.w);const l=this._tempPosition.copy(a).applyQuaternion(this._tempQuaternion),h=je(t.gameObject);l.multiply(h),o.x-=l.x,o.y-=l.y,o.z-=l.z}hr(t.gameObject,o.x,o.y,o.z),Nm(t.gameObject,r.x,r.y,r.z,r.w)}}syncPhysicsBody(e,t,i,n){if(t instanceof T.RAPIER_PHYSICS.MODULE.RigidBody){const o=Y(e,this._tempPosition),r=pe(e,this._tempQuaternion);switch(t.bodyType()){case T.RAPIER_PHYSICS.MODULE.RigidBodyType.Fixed:case T.RAPIER_PHYSICS.MODULE.RigidBodyType.KinematicPositionBased:case T.RAPIER_PHYSICS.MODULE.RigidBodyType.KinematicVelocityBased:i&&t.setNextKinematicTranslation(o),n&&t.setNextKinematicRotation(r);break;default:i&&t.setTranslation(o,!1),n&&t.setRotation(r,!1);break}}else if(t instanceof T.RAPIER_PHYSICS.MODULE.Collider){e.matrixWorldNeedsUpdate&&e.updateWorldMatrix(!0,!1),e.matrixWorld.decompose(this._tempPosition,this._tempQuaternion,this._tempScale);const o=this._tempPosition,r=this._tempQuaternion,a=t[Kt];if(this.tryApplyCenter(a,o),i){const l=t.translation();(l.x!==o.x||l.y!==o.y||l.z!==o.z)&&t.setTranslation(o)}if(n){const l=t.rotation();(l.x!==r.x||l.y!==r.y||l.z!==r.z||l.w!==r.w)&&t.setRotation(r)}}}_tempCenterPos=new c.Vector3;_tempCenterVec=new c.Vector3;_tempCenterQuaternion=new c.Quaternion;tryApplyCenter(e,t){const i=e.center;i&&e.gameObject&&(i.x!==0||i.y!==0||i.z!==0)&&(this._tempCenterPos.x=i.x,this._tempCenterPos.y=i.y,this._tempCenterPos.z=i.z,je(e.gameObject,this._tempCenterVec),this._tempCenterPos.multiply(this._tempCenterVec),e.attachedRigidbody?this._tempCenterPos.applyQuaternion(e.gameObject.quaternion):(pe(e.gameObject,this._tempCenterQuaternion),this._tempCenterPos.applyQuaternion(this._tempCenterQuaternion)),t.x+=this._tempCenterPos.x,t.y+=this._tempCenterPos.y,t.z+=this._tempCenterPos.z)}static _matricesBuffer=[];getRigidbodyRelativeMatrix(e,t,i,n){if(n===void 0&&(n=Oa._matricesBuffer,n.length=0),e===t){const o=je(e,this._tempPosition);i.makeScale(o.x,o.y,o.z);for(let r=n.length-1;r>=0;r--)i.multiply(n[r]);return i}return n.push(e.matrix),e.parent&&this.getRigidbodyRelativeMatrix(e.parent,t,i,n),i}static centerConnectionPos={x:0,y:0,z:0};static centerConnectionRot={x:0,y:0,z:0,w:1};addFixedJoint(e,t){if(!this.world){console.error("Physics world not initialized");return}const i=e[gt],n=t[gt];this.calculateJointRelativeMatrices(e.gameObject,t.gameObject,this._tempMatrix),this._tempMatrix.decompose(this._tempPosition,this._tempQuaternion,this._tempScale);const o=T.RAPIER_PHYSICS.MODULE.JointData.fixed(Oa.centerConnectionPos,Oa.centerConnectionRot,this._tempPosition,this._tempQuaternion),r=this.world.createImpulseJoint(o,i,n,!0);Ee&&console.log("ADD FIXED JOINT",r)}addHingeJoint(e,t,i,n){if(!this.world){console.error("Physics world not initialized");return}const o=e[gt],r=t[gt];this.calculateJointRelativeMatrices(e.gameObject,t.gameObject,this._tempMatrix),this._tempMatrix.decompose(this._tempPosition,this._tempQuaternion,this._tempScale);const a=T.RAPIER_PHYSICS.MODULE.JointData.revolute(i,this._tempPosition,n),l=this.world.createImpulseJoint(a,o,r,!0);Ee&&console.log("ADD HINGE JOINT",l)}calculateJointRelativeMatrices(e,t,i){e.updateWorldMatrix(!0,!1),t.updateWorldMatrix(!0,!1);const n=e.matrixWorld,o=t.matrixWorld;n.elements[0]=1,n.elements[5]=1,n.elements[10]=1,o.elements[0]=1,o.elements[5]=1,o.elements[10]=1,i.copy(o).premultiply(n.invert()).invert()}}class vA{world;eventQueue;constructor(e,t){this.world=e,this.eventQueue=t}activeCollisions=[];activeCollisionsStay=[];activeTriggers=[];handleCollisionEvents(){this.eventQueue&&this.world&&this.eventQueue.drainCollisionEvents((e,t,i)=>{const n=this.world.getCollider(e),o=this.world.getCollider(t);if(!n||!o)return;const r=n[Kt],a=o[Kt];Tp&&console.log("EVT",r.name,a.name,i,n,o),r&&a&&(i?(this.onCollisionStarted(r,n,a,o),this.onCollisionStarted(a,o,r,n)):(this.onCollisionEnded(r,a),this.onCollisionEnded(a,r)))})}update(){this.onHandleCollisionStay()}onCollisionStarted(e,t,i,n){let o=null;if(e.isTrigger||i.isTrigger)ur(e.gameObject,r=>{r.onTriggerEnter&&!r.destroyed&&r.onTriggerEnter(i),this.activeTriggers.push({collider:e,component:r,otherCollider:i})});else{const r=e.gameObject;this.world.contactPair(t,n,(a,l)=>{ur(r,h=>{if(h.destroyed)return;const d=h.onCollisionEnter||h.onCollisionStay||h.onCollisionExit;if(d||Tp){if(!o){const u=[],p=a.normal();i instanceof wo&&i.convex&&(p.x=-p.x,p.y=-p.y,p.z=-p.z);for(let m=0;m<a.numSolverContacts();m++){const y=a.solverContactPoint(m),_=a.contactImpulse(m);if(y){const g=a.contactDist(m),v=a.solverContactFriction(m),b=a.solverContactTangentVelocity(m),w=new Hv(y,g,p,_,v,b);u.push(w),Tp&&B.DrawDirection(y,p,16711680,3,!0)}}o=new qv(r,i,u)}if(d){const u={collider:e,component:h,collision:o};this.activeCollisions.push(u),h.onCollisionStay&&this.activeCollisionsStay.push(u),h.onCollisionEnter?.call(h,o)}}})})}}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 i=e.collision;t.onCollisionStay(i)}}for(const e of this.activeTriggers){const t=e.component;if(!t.destroyed&&t.activeAndEnabled&&t.onTriggerStay){const i=e.otherCollider;if(i.destroyed)continue;t.onTriggerStay(i)}}}onCollisionEnded(e,t){if(!(e.destroyed||t.destroyed)){for(let i=0;i<this.activeCollisions.length;i++){const n=this.activeCollisions[i],o=n.collider;if(o.destroyed||n.collision.collider.destroyed){this.activeCollisions.splice(i,1),i--;continue}if(o===e&&n.collision.collider===t){const r=n.component;if(this.activeCollisions.splice(i,1),i--,r.activeAndEnabled&&r.onCollisionExit){const a=n.collision;r.onCollisionExit(a)}}}for(let i=0;i<this.activeCollisionsStay.length;i++){const n=this.activeCollisionsStay[i],o=n.collider;if(o.destroyed||n.collision.collider.destroyed){this.activeCollisionsStay.splice(i,1),i--;continue}if(o===e&&n.collision.collider===t){const r=n.component;if(this.activeCollisionsStay.splice(i,1),i--,r.activeAndEnabled&&r.onCollisionExit){const a=n.collision;r.onCollisionExit(a)}}}for(let i=0;i<this.activeTriggers.length;i++){const n=this.activeTriggers[i],o=n.collider;if(o.destroyed||n.otherCollider.destroyed){this.activeTriggers.splice(i,1),i--;continue}if(o===e&&n.otherCollider===t){const r=n.component;if(this.activeTriggers.splice(i,1),i--,r.activeAndEnabled&&r.onTriggerExit){const a=n.otherCollider;r.onTriggerExit(a)}}}}}}let Am=0;function cv(s){s?Am++:Am--}function wA(){return Am>0}const xA={binary:!0,animations:!0};async function SA(s){if(!s.context)throw new Error("No context provided to exportAsGLTF");s.scene||(s.scene=s.context.scene);const e={...xA,...s},{context:t}=e,i=new X.GLTFExporter;i.register(a=>new Vw(a)),i.register(a=>new ok(a)),i.register(a=>new Ww(a)),$g(i,e.context);const n={binary:e.binary,animations:PA(t,e.scene,[])},o=new CA;console.debug("Exporting GLTF",n),o.onBeforeExport(e),cv(!0);const r=await i.parseAsync(e.scene,n).catch(a=>(console.error(a),null));if(cv(!1),o.onAfterExport(e),!r)throw new Error("Failed to export GLTF");if(e.downloadAs!=null){let a=null;if(r instanceof ArrayBuffer?a=new Blob([r],{type:"application/octet-stream"}):console.error("Can not download GLTF as a blob",r),a){const l=URL.createObjectURL(a),h=document.createElement("a");h.href=l;let d=e.downloadAs;!d.endsWith(".glb")&&!d.endsWith(".gltf")&&(d+=e.binary?".glb":".gltf"),h.download=d,h.click()}}return r}const hv=Symbol("needle:weight");class CA{_undo=[];onBeforeExport(e){e.context.animations.mixers.forEach(t=>{const i=Hn.tryGetActionsFromMixer(t);if(i)for(let n=0;n<i.length;n++){const o=i[n];o[hv]=o.weight,o.weight=0,this._undo.push(()=>{o.weight=o[hv]})}t.update(0)}),e.context.scene.traverse(t=>{if(!mm(t)){const i=t.parent;i&&(t.removeFromParent(),this._undo.push(()=>i.add(t)))}})}onAfterExport(e){this._undo.forEach(t=>t()),this._undo.length=0}}function PA(s,e,t){s.animations.mixers.forEach(n=>{const o=Hn.tryGetActionsFromMixer(n);if(o)for(let r=0;r<o.length;r++){const l=o[r].getClip();t.push(l)}}),Array.isArray(e)||(e=[e]);for(const n of e)Hn.tryGetAnimationClipsFromObjectHierarchy(n,t);const i=new Set(t);return Array.from(i)}const Bl=x("debugavatar");class Xy{root;head;leftHand;rigthHand;get isValid(){return this.head!==null&&this.head!==void 0}constructor(e,t,i,n){this.root=e,this.head=t,this.leftHand=i,this.rigthHand=n,this.root?.traverse(o=>o.layers.set(2))}}class Xx{avatarRegistryUrl=null;async getOrCreateNewAvatarInstance(e,t){if(!t)return console.error("Can not create avatar: failed to provide id or root object"),null;let i=null;if(typeof t=="string"){if(i=await this.loadAvatar(e,t),!i){const o=new gn;i=S.instantiate(Ma(t,e.scene),o)}}else i=t;if(!i)return null;const n=this.findAvatar(i);return n.isValid?(Bl&&console.log("[Custom Avatar] valid config",t,Bl?n:""),n):(console.warn("[Custom Avatar] config isn't valid",t,Bl?n:""),null)}async loadAvatar(e,t){if(console.assert(t!=null&&typeof t=="string","Avatar id must not be null"),t.length<=0||!t)return null;if(Bl&&console.log("[Custom Avatar] "+t+", loading..."),t.endsWith(".glb")||(t+=".glb"),this.avatarRegistryUrl===null){const n=await fetch("./"+t);let o=null;if(n.ok){const a=await n.blob();a&&(o=await a.arrayBuffer())}return o?(await un().parseSync(e,o,null,0))?.scene??null:null}const i=new X.GLTFLoader;return cy(i,e),new Promise((n,o)=>{const r=this.avatarRegistryUrl+"/"+t;i.load(r,async a=>{await un().createBuiltinComponents(e,r,a,null,void 0),n(a.scene)},a=>{Bl&&console.log("[Custom Avatar] "+a.loaded/a.total*100+"% loaded of "+a.total/1024+"kB")},a=>{console.error("[Custom Avatar] Error when loading: "+a),n(null)})})}cacheModel(e,t){}findAvatar(e){const t=e;let i=t;i.children.length==1&&(i=e.children[0]);let n=this.findAvatarPart(i,["head"]);const o=this.findAvatarPart(i,["left","hand"]),r=this.findAvatarPart(i,["right","hand"]);if(!n){n=t;const l=new c.Vector3;new c.Box3().setFromObject(n).getSize(l);const h=Math.max(l.x,l.y,l.z);console.warn("[Custom Avatar] Normalizing head scale, it's too big: "+h+" meters! Should be < 0.3m"),h>.3&&n.scale.multiplyScalar(1/h*.3)}return new Xy(t,n,o,r)}findAvatarPart(e,t){const i=e.name.toLowerCase();let n=!0;for(const o of t){if(!n)break;i.indexOf(o)===-1&&(n=!1)}if(n)return e;if(e.children)for(const o of e.children){const r=this.findAvatarPart(o,t);if(r)return r}return null}handleCustomAvatarErrors(e){if(!e.ok)throw Error(e.statusText);return e}}class Qx{get extensionName(){return"DocumentExtension"}onAfterBuildDocument(e){}}class Yx{}const OA=Object.freeze(Object.defineProperty({__proto__:null,ActionBuilder:ue,ActionCollection:ox,ActionModel:Jt,AlignmentConstraint:ih,Animation:Tt,AnimationCurve:yh,AnimationExtension:Xu,AnimationTrackHandler:Rc,Animator:lt,AnimatorController:Vi,Antialiasing:bh,Attractor:al,AudioExtension:Mr,AudioListener:ds,AudioSource:vi,AudioTrackHandler:us,Avatar:fo,AvatarBlink_Simple:Sr,AvatarEyeLook_Rotation:Lg,AvatarLoader:Xx,AvatarMarker:Oe,AvatarModel:Xy,Avatar_Brain_LookAt:Ac,Avatar_MouthShapes:sh,Avatar_MustacheShake:Ag,Avatar_POI:lr,AxesHelper:qa,BaseUIComponent:Wi,BasicIKConstraint:jg,BehaviorExtension:hy,BehaviorModel:St,BloomEffect:hf,BoxCollider:Vu,BoxGizmo:Tr,BoxHelperComponent:bt,Button:Ds,CallInfo:ls,Camera:si,CameraTargetReachedEvent:Ec,Canvas:Fa,CanvasGroup:po,CapsuleCollider:bs,ChangeMaterialOnClick:iy,ChangeTransformOnClick:kr,CharacterController:Cr,CharacterControllerInput:Cs,ChromaticAberration:vh,ClickThrough:wf,ColorAdjustments:ko,ColorBySpeedModule:rl,ColorOverLifetimeModule:af,ContactShadows:oh,ControlTrackHandler:Bu,CursorFollow:Vr,CustomBranding:Rr,Deletable:zg,DeleteBox:ro,DepthOfField:bn,DeviceFlag:$u,DocumentExtension:Qx,DragControls:Ko,DropListener:Os,Duplicatable:qg,EffectWrapper:jc,EmissionModule:Rs,EmphasizeOnClick:Ka,EnvironmentScene:Fu,EventList:ne,EventListEvent:Tu,EventSystem:Gt,EventTrigger:Hu,FieldWithDefault:zw,FixedJoint:Cy,Fog:il,GltfExport:Zg,GltfExportBox:Yg,Gradient:Dr,Graphic:ph,GraphicRaycaster:Du,GridHelper:nl,GridLayoutGroup:gy,GroundProjectedEnv:Xn,GroupActionModel:Zo,HideOnStart:Ii,HingeJoint:gh,HorizontalLayoutGroup:my,get HoverAnimation(){return exports.HoverAnimation},Image:dl,InheritVelocityModule:Ey,InputField:zy,InstanceHandle:cr,InstancingHandler:gr,Interactable:Ug,Keyframe:oi,LODGroup:sf,LODModel:sl,Light:Ot,LimitVelocityOverLifetimeModule:nt,LogStats:Fg,LookAt:Ny,LookAtConstraint:xr,MainModule:Lt,MarkerTrackHandler:ju,MaskableGraphic:mh,MeshCollider:wo,MeshRenderer:lh,MinMaxCurve:H,MinMaxGradient:Lr,NeedleMenu:Yn,NestedGltf:ol,Networking:My,NoiseModule:me,ObjectRaycaster:$i,OffsetConstraint:Ar,OpenURL:ul,OrbitControls:he,Outline:tl,Padding:Er,ParticleBurst:du,ParticleSubEmitter:Ry,ParticleSystem:Ic,ParticleSystemRenderer:Yi,PhysicsExtension:dy,PixelationEffect:wh,PlayAnimationOnClick:Dc,PlayAudioOnClick:uo,PlayableDirector:ja,PlayerColor:Ua,PointerEventData:Zc,PostProcessingHandler:za,PreliminaryAction:Za,PreliminaryTrigger:hh,RawImage:_f,Rect:dx,RectTransform:mn,ReflectionProbe:os,RegisteredAnimationInfo:so,RemoteSkybox:Uu,Renderer:Ht,RendererLightmap:Wg,Rigidbody:$e,RotationBySpeedModule:Qi,RotationOverLifetimeModule:_n,SceneSwitcher:We,ScreenCapture:Eo,ScreenSpaceAmbientOcclusion:Ts,ScreenSpaceAmbientOcclusionN8:vn,ScrollFollow:Ls,SeeThrough:As,SetActiveOnClick:ny,ShadowCatcher:Ph,ShapeModule:ky,SharpeningEffect:Sh,SignalAsset:Iu,SignalReceiver:eh,SignalReceiverEvent:Jc,SignalTrackHandler:Tc,Size:hx,SizeBySpeedModule:di,SizeOverLifetimeModule:Ir,SkinnedMeshRenderer:Gg,SmoothFollow:ff,SpatialGrabRaycaster:fr,SpatialHtml:Eh,SpatialTrigger:pf,SpatialTriggerReceiver:Gn,SpectatorCamera:mf,SphereCollider:Xa,SplineContainer:zr,SplineData:qn,SplineWalker:Zi,Sprite:Ms,SpriteData:Pa,SpriteRenderer:ci,SpriteSheet:Ba,SubEmitterSystem:uu,SyncedCamera:jy,SyncedRoom:wn,SyncedTransform:pn,TapGestureTrigger:oy,TeleportTarget:Ju,TestRunner:By,TestSimulateUserData:Fy,Text:Dt,TextBuilder:fy,TextExtension:tf,TextureSheetAnimationModule:It,TiltShiftEffect:Zn,ToneMappingEffect:mo,TrailModule:Le,TransformData:Ae,TransformGizmo:Nr,TriggerBuilder:Rt,TriggerModel:ao,UIRaycastUtils:xg,UIRootComponent:uh,USDZExporter:Wn,USDZText:ma,USDZUIExtension:_y,UsageMarker:rh,VariantAction:ty,VelocityOverLifetimeModule:Fe,VerticalLayoutGroup:py,VideoPlayer:tt,get ViewBox(){return exports.ViewBox},Vignette:Fr,VisibilityAction:dh,Voip:vo,Volume:Ur,VolumeParameter:z,VolumeProfile:lf,WebARCameraBackground:Th,WebARSessionRoot:Ui,WebXR:ef,WebXRImageTracking:Ah,WebXRImageTrackingModel:js,WebXRPlaneTracking:Bs,WebXRTrackedImage:Na,XRControllerFollow:Is,XRControllerModel:vs,XRControllerMovement:xi,XRFlag:ji,XRRig:Cf,XRState:Wt,__Ignore:Yx},Symbol.toStringTag,{value:"Module"}));exports.SplineUtils=void 0;(s=>{function e(t,i=!1,n=.75){const o=new zr,r=1-I.clamp(n,0,1);return t.forEach((a,l)=>{const h=new c.Vector3;l<t.length-1?h.subVectors(t[l+1],a).normalize().multiplyScalar(r):i&&t.length>1&&h.subVectors(t[0],a).normalize().multiplyScalar(r);const d=new qn;d.position.copy(a),d.tangentIn.copy(h),d.tangentOut.copy(h),o.addKnot(d)}),o.closed=i,o}s.createFromPoints=e})(exports.SplineUtils||(exports.SplineUtils={}));class MA extends le.WorkerBase{constructor(){super(new Worker(new URL("/generateMeshBVH.worker-DiCnZlf3.js",typeof document>"u"?require("url").pathToFileURL(__filename).href:ya&&ya.tagName.toUpperCase()==="SCRIPT"&&ya.src||new URL("needle-engine.bundle-B5tG2TR8.umd.cjs",document.baseURI).href),{type:"module"})),this.name="GenerateMeshBVHWorker"}runTask(e,t,i={}){return new Promise((n,o)=>{if(t.getAttribute("position").isInterleavedBufferAttribute||t.index&&t.index.isInterleavedBufferAttribute)throw new Error("GenerateMeshBVHWorker: InterleavedBufferAttribute are not supported for the geometry attributes.");e.onerror=h=>{o(new Error(`[GenerateMeshBVHWorker] ${h.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=h=>{const{data:d}=h;if(d.error)o(new Error(d.error)),e.onmessage=null;else if(d.serialized){const{serialized:u,position:p}=d,m=le.MeshBVH.deserialize(u,t,{setIndex:!1}),y=Object.assign({setBoundingBox:!0},i);if(t.attributes.position.array=p,u.index)if(t.index)t.index.array=u.index;else{const _=new c.BufferAttribute(u.index,1,!1);t.setIndex(_)}y.setBoundingBox&&(t.boundingBox=m.getBoundingBox(new c.Box3)),i.onProgress&&i.onProgress(d.progress),n(m),e.onmessage=null}else i.onProgress&&i.onProgress(d.progress)};const r=t.index?t.index.array:null,a=t.attributes.position.array,l=[a];r&&l.push(r),e.postMessage({index:r,position:a,options:{...i,onProgress:null,includedProgressCallback:!!i.onProgress,groups:[...t.groups]}},l.map(h=>h.buffer).filter(h=>typeof SharedArrayBuffer>"u"||!(h instanceof SharedArrayBuffer)))})}}const kA=Object.freeze(Object.defineProperty({__proto__:null,GenerateMeshBVHWorker:MA},Symbol.toStringTag,{value:"Module"}));exports.$componentName=Gv;exports.$physicsKey=TC;exports.ActionBuilder=ue;exports.ActionCollection=ox;exports.ActionModel=Jt;exports.Addressables=f0;exports.AlignmentConstraint=ih;exports.AmbientMode=va;exports.Animation=Tt;exports.AnimationCurve=yh;exports.AnimationExtension=Xu;exports.AnimationTrackHandler=Rc;exports.AnimationUtils=Hn;exports.Animator=lt;exports.AnimatorConditionMode=Zs;exports.AnimatorController=Vi;exports.AnimatorControllerParameterType=wg;exports.AnimatorStateInfo=Vl;exports.Antialiasing=bh;exports.Application=fn;exports.AssetDatabase=N0;exports.AssetReference=Z;exports.Attractor=al;exports.AudioExtension=Mr;exports.AudioListener=ds;exports.AudioSource=vi;exports.AudioTrackHandler=us;exports.Avatar=fo;exports.AvatarBlink_Simple=Sr;exports.AvatarEyeLook_Rotation=Lg;exports.AvatarLoader=Xx;exports.AvatarMarker=Oe;exports.AvatarModel=Xy;exports.Avatar_Brain_LookAt=Ac;exports.Avatar_MouthShapes=sh;exports.Avatar_MustacheShake=Ag;exports.Avatar_POI=lr;exports.Axes=fa;exports.AxesHelper=qa;exports.BUILD_TIME=_c;exports.BaseUIComponent=Wi;exports.BasicIKConstraint=jg;exports.BehaviorExtension=hy;exports.BehaviorModel=St;exports.BloomEffect=hf;exports.BoxCollider=Vu;exports.BoxGizmo=Tr;exports.BoxHelperComponent=bt;exports.Button=Ds;exports.ButtonsFactory=Fi;exports.CallDirection=Sw;exports.CallInfo=ls;exports.Camera=si;exports.CameraTargetReachedEvent=Ec;exports.Canvas=Fa;exports.CanvasGroup=po;exports.CapsuleCollider=bs;exports.ChangeMaterialOnClick=iy;exports.ChangeTransformOnClick=kr;exports.CharacterController=Cr;exports.CharacterControllerInput=Cs;exports.ChromaticAberration=vh;exports.CircularBuffer=_i;exports.ClearFlags=ar;exports.ClickThrough=wf;exports.ClipExtrapolation=Mn;exports.Collider=Xi;exports.Collision=qv;exports.CollisionDetectionMode=Au;exports.ColorAdjustments=ko;exports.ColorBySpeedModule=rl;exports.ColorOverLifetimeModule=af;exports.Component=BP;exports.Component$1=E;exports.ComponentLifecycleEvents=gu;exports.Components=OA;exports.ConnectionEvents=x0;exports.ContactPoint=Hv;exports.ContactShadows=oh;exports.Context=U;exports.ContextArgs=Q1;exports.ContextEvent=ae;exports.ContextRegistry=ce;exports.ControlTrackHandler=Bu;exports.CursorFollow=Vr;exports.CustomBranding=Rr;exports.CustomShader=ve;exports.DefaultReflectionMode=Kd;exports.Deletable=zg;exports.DeleteBox=ro;exports.DepthOfField=bn;exports.DeviceFlag=$u;exports.DocumentExtension=Qx;exports.DragControls=Ko;exports.DragMode=Ng;exports.DropListener=Os;exports.Duplicatable=qg;exports.EffectWrapper=jc;exports.EmissionModule=Rs;exports.EmphasizeOnClick=Ka;exports.EngineLoadingView=Bc;exports.EnvironmentScene=Fu;exports.EventList=ne;exports.EventListEvent=Tu;exports.EventSystem=Gt;exports.EventTrigger=Hu;exports.FieldWithDefault=zw;exports.FileReference=ir;exports.FileReferenceSerializer=m0;exports.FileSpawnModel=xM;exports.File_Event=Tw;exports.FixedJoint=Cy;exports.Fog=il;exports.FrameEvent=ge;exports.GENERATOR=Ea;exports.GameObject=S;exports.Gizmos=B;exports.GltfExport=Zg;exports.GltfExportBox=Yg;exports.Gradient=Dr;exports.Graphic=ph;exports.GraphicRaycaster=Du;exports.Graphics=co;exports.GridHelper=nl;exports.GridLayoutGroup=gy;exports.GroundProjectedEnv=Xn;exports.GroupActionModel=Zo;exports.HideFlags=_u;exports.HideOnStart=Ii;exports.HingeJoint=gh;exports.HorizontalLayoutGroup=my;exports.HostData=$C;exports.Image=dl;exports.ImageReference=tr;exports.ImageReferenceSerializer=p0;exports.InheritVelocityModule=Ey;exports.Input=y0;exports.InputEventQueue=ti;exports.InputEvents=Pe;exports.InputField=zy;exports.InstanceHandle=cr;exports.InstancingHandler=gr;exports.InstancingUtil=Ni;exports.InstantiateEvent=t0;exports.InstantiateIdProvider=xt;exports.InstantiateOptions=gn;exports.Interactable=Ug;exports.JoinedRoomResponse=b1;exports.KeyEventArgs=d1;exports.Keyframe=oi;exports.LODGroup=sf;exports.LODModel=sl;exports.LeftRoomResponse=v1;exports.Light=Ot;exports.LightData=k0;exports.LimitVelocityOverLifetimeModule=nt;exports.LoadingElementOptions=dA;exports.LogStats=Fg;exports.LogType=gi;exports.LookAt=Ny;exports.LookAtConstraint=xr;exports.MODULES=T;exports.MainModule=Lt;exports.MarkerTrackHandler=ju;exports.MarkerType=Pg;exports.MaskableGraphic=mh;exports.MaterialPropertyBlock=ys;exports.Mathf=I;exports.MeshCollider=wo;exports.MeshRenderer=lh;exports.MinMaxCurve=H;exports.MinMaxGradient=Lr;exports.NEEDLE_ENGINE_FEATURE_FLAGS=Xm;exports.NEKeyboardEvent=Fl;exports.NEPointerEvent=ss;exports.NeedleButtonElement=Wx;exports.NeedleEngineWebComponent=qy;exports.NeedleMenu=Yn;exports.NeedlePatchesKey=_d;exports.NeedleXRController=ug;exports.NeedleXRSession=q;exports.NeedleXRSync=F0;exports.NeedleXRUtils=z0;exports.NestedGltf=ol;exports.NetworkConnection=C0;exports.NetworkedStreamEvents=Un;exports.NetworkedStreams=nh;exports.Networking=My;exports.NewInstanceModel=n0;exports.NoiseModule=me;exports.ObjectRaycaster=$i;exports.ObjectUtils=_o;exports.OffsetConstraint=Ar;exports.OneEuroFilter=gd;exports.OneEuroFilterXYZ=Um;exports.OpenURL=ul;exports.OrbitControls=he;exports.Outline=tl;exports.OwnershipEvent=S0;exports.OwnershipModel=lg;exports.PUBLIC_KEY=no;exports.Padding=Er;exports.ParticleBurst=du;exports.ParticleSubEmitter=Ry;exports.ParticleSystem=Ic;exports.ParticleSystemBaseBehaviour=Mo;exports.ParticleSystemRenderer=Yi;exports.ParticleSystemShapeType=hu;exports.PeerHandle=fs;exports.PeerNetworking=w0;exports.Physics=Ia;exports.PhysicsExtension=dy;exports.PhysicsMaterialCombine=st;exports.PixelationEffect=wh;exports.PlayAnimationOnClick=Dc;exports.PlayAudioOnClick=uo;exports.PlayableDirector=ja;exports.PlayerColor=Ua;exports.PlayerState=zi;exports.PlayerStateEvent=lx;exports.PlayerSync=ay;exports.PlayerView=P0;exports.PlayerViewManager=O0;exports.PointerEventData=Zc;exports.PointerType=vu;exports.PostProcessingEffect=Xe;exports.PostProcessingEffectOrder=et;exports.PostProcessingHandler=za;exports.PreliminaryAction=Za;exports.PreliminaryTrigger=hh;exports.PrimitiveType=Va;exports.Progress=oe;exports.PromiseAllWithErrors=Bm;exports.PromiseErrorResult=Lp;exports.RGBAColor=te;exports.RapierPhysics=Oa;exports.RawImage=_f;exports.RaycastOptions=bo;exports.Rect=dx;exports.RectTransform=mn;exports.ReflectionProbe=os;exports.RegisteredAnimationInfo=so;exports.RemoteSkybox=Uu;exports.RenderTexture=Bn;exports.RenderTextureSerializer=pw;exports.Renderer=Ht;exports.RendererData=M0;exports.RendererLightmap=Wg;exports.Rigidbody=$e;exports.RigidbodyConstraints=Ve;exports.RoomEvents=K;exports.RotationBySpeedModule=Qi;exports.RotationOverLifetimeModule=_n;exports.SceneLightSettings=ou;exports.SceneSwitcher=We;exports.ScreenCapture=Eo;exports.ScreenSpaceAmbientOcclusion=Ts;exports.ScreenSpaceAmbientOcclusionN8=vn;exports.ScrollFollow=Ls;exports.SeeThrough=As;exports.SendQueue=ln;exports.SerializationContext=ng;exports.SetActiveOnClick=ny;exports.ShadowCatcher=Ph;exports.ShapeModule=ky;exports.ShapeOverlapResult=Xv;exports.SharpeningEffect=Sh;exports.SignalAsset=Iu;exports.SignalReceiver=eh;exports.SignalReceiverEvent=Jc;exports.SignalTrackHandler=Tc;exports.Size=hx;exports.SizeBySpeedModule=di;exports.SizeOverLifetimeModule=Ir;exports.SkinnedMeshRenderer=Gg;exports.SmoothFollow=ff;exports.SpatialGrabRaycaster=fr;exports.SpatialHtml=Eh;exports.SpatialTrigger=pf;exports.SpatialTriggerReceiver=Gn;exports.SpectatorCamera=mf;exports.SphereCollider=Xa;exports.SphereIntersection=mg;exports.SplineContainer=zr;exports.SplineData=qn;exports.SplineWalker=Zi;exports.Sprite=Ms;exports.SpriteData=Pa;exports.SpriteRenderer=ci;exports.SpriteSheet=Ba;exports.StateMachineBehaviour=VP;exports.StreamEndedEvent=Rg;exports.StreamReceivedEvent=xw;exports.SubEmitterSystem=uu;exports.SyncedCamera=jy;exports.SyncedRoom=wn;exports.SyncedTransform=pn;exports.TapGestureTrigger=oy;exports.TeleportTarget=Ju;exports.TestRunner=By;exports.TestSimulateUserData=Fy;exports.Text=Dt;exports.TextBuilder=fy;exports.TextExtension=tf;exports.TextureSheetAnimationModule=It;exports.TiltShiftEffect=Zn;exports.Time=E0;exports.ToneMappingEffect=mo;exports.TrackHandler=Ha;exports.TrackType=fi;exports.TrailModule=Le;exports.TransformData=Ae;exports.TransformGizmo=Nr;exports.TriggerBuilder=Rt;exports.TriggerModel=ao;exports.TypeStore=P;exports.UIRaycastUtils=xg;exports.UIRootComponent=uh;exports.USDDocument=Jg;exports.USDObject=qe;exports.USDWriter=Yw;exports.USDZExporter=Kw;exports.USDZExporter$1=Wn;exports.USDZText=ma;exports.USDZUIExtension=_y;exports.UriSerializer=mw;exports.UsageMarker=rh;exports.UserJoinedOrLeftRoomModel=w1;exports.VERSION=ii;exports.VariantAction=ty;exports.VelocityOverLifetimeModule=Fe;exports.VerticalLayoutGroup=py;exports.VideoPlayer=tt;exports.ViewDevice=gs;exports.Vignette=Fr;exports.VisibilityAction=dh;exports.Voip=vo;exports.Volume=Ur;exports.VolumeParameter=z;exports.VolumeProfile=lf;exports.WaitForFrames=a1;exports.WaitForPromise=g0;exports.WaitForSeconds=sg;exports.Watch=ms;exports.WebARCameraBackground=Th;exports.WebARSessionRoot=Ui;exports.WebXR=ef;exports.WebXRButtonFactory=lo;exports.WebXRImageTracking=Ah;exports.WebXRImageTrackingModel=js;exports.WebXRPlaneTracking=Bs;exports.WebXRTrackedImage=Na;exports.XRControllerFollow=Is;exports.XRControllerModel=vs;exports.XRControllerMovement=xi;exports.XRFlag=ji;exports.XRRig=Cf;exports.XRState=Wt;exports.XRStateFlag=Ln;exports.__Ignore=Yx;exports.__internalNotifyObjectDestroyed=gP;exports.activeInHierarchyFieldName=jn;exports.addAttributeChangeCallback=Im;exports.addComponent=hn;exports.addCustomExtensionPlugin=HM;exports.addNewComponent=or;exports.addPatch=yu;exports.apply=Ou;exports.applyHMRChanges=jP;exports.applyPrototypeExtensions=Y0;exports.beginListenDestroy=i0;exports.beginListenInstantiate=o0;exports.binaryIdentifierCasts=og;exports.build_scene_functions=X1;exports.builtinComponentKeyName=Ho;exports.calculateProgress01=Hy;exports.clearMessages=PS;exports.colorSerializer=QP;exports.compareAssociation=c0;exports.componentSerializer=Md;exports.copyTexture=Tv;exports.createMotion=uw;exports.debugNet=Yt;exports.debugOwner=Ul;exports.decompressGpuTexture=tx;exports.deepClone=Uc;exports.delay=_s;exports.delayForFrames=zc;exports.deserializeObject=Qd;exports.destroy=bi;exports.destroyComponentInstance=rw;exports.determineMimeTypeFromExtension=Aw;exports.disposeObjectResources=we;exports.disposeStream=zn;exports.editorGuidKeyName=ec;exports.enableSpatialConsole=_a;exports.euler=KP;exports.eventListSerializer=tO;exports.exportAsGLTF=SA;exports.findByGuid=_g;exports.findObjectOfType=Ga;exports.findObjectsOfType=lw;exports.findResourceUsers=gg;exports.fitCamera=gw;exports.fitObjectIntoVolume=Dv;exports.foreachComponent=ur;exports.foreachComponentEnumerator=ku;exports.forward=WS;exports.generateQRCode=L0;exports.generateSeed=s0;exports.getBoundingBox=ri;exports.getCameraController=Sv;exports.getComponent=vr;exports.getComponentInChildren=Yc;exports.getComponentInParent=Pc;exports.getComponents=Qc;exports.getComponentsInChildren=Wa;exports.getComponentsInParent=Eu;exports.getFormattedDate=Hw;exports.getIconElement=wt;exports.getIconTexture=Kp;exports.getLoader=un;exports.getOrAddComponent=Xc;exports.getParam=x;exports.getParentHierarchyPath=qS;exports.getPath=nS;exports.getPeerOptions=m1;exports.getPeerjsInstance=v0;exports.getResourceUserCount=_P;exports.getTempColor=Mv;exports.getTempQuaternion=ei;exports.getTempVector=F;exports.getUrlParams=Fc;exports.getVisibleInCustomShadowRendering=Av;exports.getWorldDirection=kv;exports.getWorldEuler=Vm;exports.getWorldPosition=Y;exports.getWorldQuaternion=pe;exports.getWorldRotation=mu;exports.getWorldScale=je;exports.hasCommercialLicense=$n;exports.hasIndieLicense=Wc;exports.hasPointerEventComponent=iu;exports.hasProLicense=Vn;exports.hideDebugConsole=Bv;exports.imageToCanvas=ix;exports.initEngine=_A;exports.instantiate=ho;exports.invokeLoadedImportPluginHooks=Uw;exports.invokeXRSessionEnd=D0;exports.invokeXRSessionStart=A0;exports.isActiveInHierarchy=K0;exports.isActiveSelf=$a;exports.isAndroidDevice=cS;exports.isAnimationAction=Rv;exports.isComponent=Ym;exports.isDebugMode=Jx;exports.isDesktop=oS;exports.isDestroyed=dr;exports.isDevEnvironment=A;exports.isDisposed=mP;exports.isExporting=wA;exports.isGLTFModel=Wv;exports.isHostedOnGlitch=dv;exports.isHotReloadEnabled=lm;exports.isHotReloading=LP;exports.isIPad=aS;exports.isIconElement=I0;exports.isLocalNetwork=yi;exports.isMacOS=dS;exports.isMobileDevice=rS;exports.isMozillaXR=hS;exports.isQuest=pS;exports.isResourceTrackingEnabled=$0;exports.isSafari=fS;exports.isUsingInstancing=Mu;exports.isiOS=uS;exports.isiPad=lS;exports.loadAsset=nA;exports.loadPMREM=Eg;exports.loadSync=Gy;exports.logHierarchy=$d;exports.lookAtInverse=jS;exports.lookAtObject=Nc;exports.lookAtScreenPoint=BS;exports.makeId=tS;exports.makeIdFromRandomWords=pv;exports.makeNameSafe=wi;exports.markAsInstancedRendered=Z0;exports.microphonePermissionsGranted=mS;exports.nameof=Zx;exports.nameofFactory=uv;exports.objectSerializer=fw;exports.offXRSessionEnd=A1;exports.offXRSessionStart=T1;exports.onAfterRender=IC;exports.onBeforeRender=LC;exports.onClear=AC;exports.onDestroy=DC;exports.onInitialized=Km;exports.onStart=bu;exports.onUpdate=Zv;exports.onXRSessionEnd=hg;exports.onXRSessionStart=xu;exports.parseSync=Vx;exports.placeOnSurface=Lv;exports.postprocessFBXMaterials=Gm;exports.prefix=lO;exports.pushState=fv;exports.randomNumber=iS;exports.registerBinaryType=rg;exports.registerComponent=Cu;exports.registerComponentExtension=Vg;exports.registerCustomEffectType=Ki;exports.registerExportExtensions=$g;exports.registerExtensions=au;exports.registerHotReloadType=cw;exports.registerLoader=Yv;exports.registerPrefabProvider=a0;exports.registerPrototypeExtensions=yg;exports.registerType=qm;exports.relativePathPrefix=gv;exports.removeAttributeChangeCallback=jm;exports.removeComponent=vg;exports.removeCustomImportExtensionType=qM;exports.removePatch=kC;exports.resolveUrl=ws;exports.sanitizeString=mv;exports.saveImage=Ux;exports.screenshot=jT;exports.screenshot2=Wy;exports.sendDestroyed=Jm;exports.serializable=f;exports.serializeObject=d0;exports.serializeable=Be;exports.setActive=sc;exports.setAllowBalloonMessages=vv;exports.setAllowOverlayMessages=wS;exports.setAutoFitEnabled=Nd;exports.setCameraController=Bp;exports.setDestroyed=ew;exports.setDevEnvironment=RS;exports.setDisposable=G0;exports.setDontDestroy=na;exports.setOrAddParamsToUrl=Dp;exports.setParam=eS;exports.setParamWithoutReload=yc;exports.setPeerOptions=g1;exports.setResourceTrackingEnabled=pP;exports.setState=Dm;exports.setVisibleInCustomShadowRendering=Wm;exports.setWorldEuler=$m;exports.setWorldPosition=at;exports.setWorldPositionXYZ=hr;exports.setWorldQuaternion=dn;exports.setWorldQuaternionXYZW=Nm;exports.setWorldRotation=Ev;exports.setWorldRotationXYZ=Vc;exports.setWorldScale=ka;exports.showBalloonError=$c;exports.showBalloonMessage=Se;exports.showBalloonWarning=fe;exports.showDebugConsole=Hm;exports.slerp=Pv;exports.syncDestroy=Gc;exports.syncField=kg;exports.syncInstantiate=eg;exports.textureToCanvas=XS;exports.toSourceId=yv;exports.tryCastBinary=_0;exports.tryDetermineMimetypeFromBinary=Lw;exports.tryDetermineMimetypeFromURL=Dw;exports.tryFindObject=Ma;exports.tryGetGuid=b0;exports.unregisterHotReloadType=hw;exports.unwatchWrite=Lm;exports.useForAutoFit=Cv;exports.validate=Ct;exports.watchWrite=pu;
|
|
1654
|
+
Error:`,r),null}}updateColliderCollisionGroups(e){const t=e[gt],i=e.membership;let n=0;if(i==null)n=65535;else for(let a=0;a<i.length;a++){const l=i[a];l>31?console.error(`Rapier only supports 32 layers, layer ${l} is not supported`):n|=1<<Math.floor(l)}const o=e.filter;let r=0;if(o==null)r=65535;else for(let a=0;a<o.length;a++){const l=o[a];l>31?console.error(`Rapier only supports 32 layers, layer ${l} is not supported`):r|=1<<Math.floor(l)}t.setCollisionGroups(n<<16|r)}getRigidbody(e,t){if(!this.world)throw new Error("Physics world not initialized");let i=null;if(e.attachedRigidbody){const n=e.attachedRigidbody;if(i=n[gt],!i){const o=n.isKinematic&&!Rp;Ee&&console.log("Create rigidbody",o);const r=o?T.RAPIER_PHYSICS.MODULE.RigidBodyDesc.kinematicPositionBased():T.RAPIER_PHYSICS.MODULE.RigidBodyDesc.dynamic(),a=Y(e.attachedRigidbody.gameObject);r.setTranslation(a.x,a.y,a.z),r.setRotation(pe(e.attachedRigidbody.gameObject)),r.centerOfMass=new T.RAPIER_PHYSICS.MODULE.Vector3(n.centerOfMass.x,n.centerOfMass.y,n.centerOfMass.z),i=this.world.createRigidBody(r),this.bodies.push(i),this.objects.push(n)}i[Kt]=n,n[gt]=i,this.internalUpdateRigidbodyProperties(n,i),this.getRigidbodyRelativeMatrix(e.gameObject,n.gameObject,t),e[lv]=i}else{const n=T.RAPIER_PHYSICS.MODULE.RigidBodyDesc.kinematicPositionBased(),o=Y(e.gameObject);n.setTranslation(o.x,o.y,o.z),n.setRotation(pe(e.gameObject)),i=this.world.createRigidBody(n),t.identity(),i[Kt]=null}return i}internal_getRigidbody(e){return e.isCollider===!0?e[lv]:e[gt]}internalUpdateColliderProperties(e,t){const i=t.shape;let n=!1;switch(i.type){case T.RAPIER_PHYSICS.MODULE.ShapeType.Ball:{const p=i,m=e,y=e.gameObject,_=je(y,this._tempPosition),g=Math.abs(m.radius*_.x);n=p.radius!==g,p.radius=g,n&&t.setShape(p);break}case T.RAPIER_PHYSICS.MODULE.ShapeType.Cuboid:const o=i,r=e,a=e.gameObject,l=je(a,this._tempPosition),h=Math.abs(r.size.x*.5*l.x),d=Math.abs(r.size.y*.5*l.y),u=Math.abs(r.size.z*.5*l.z);n=o.halfExtents.x!==h||o.halfExtents.y!==d||o.halfExtents.z!==u,o.halfExtents.x=h,o.halfExtents.y=d,o.halfExtents.z=u,n&&t.setShape(o);break}if(n){const o=e.attachedRigidbody;o?.autoMass&&this.getBody(o)?.recomputeMassPropertiesFromColliders()}this.updateColliderCollisionGroups(e),e.isTrigger!==t.isSensor()&&t.setSensor(e.isTrigger)}internalUpdateRigidbodyProperties(e,t){if(t.enableCcd(e.collisionDetectionMode!==Au.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 i=0;i<t.numColliders();i++)t.collider(i).setDensity(1);t.recomputeMassPropertiesFromColliders()}else{t.setAdditionalMass(e.mass,!1);for(let i=0;i<t.numColliders();i++)t.collider(i).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(T.RAPIER_PHYSICS.MODULE.RigidBodyType.KinematicPositionBased,!1):t.setBodyType(T.RAPIER_PHYSICS.MODULE.RigidBodyType.Dynamic,!1)}lines;disabledLines;step(e){if(this.world&&this.enabled){if(this._isUpdatingPhysicsWorld=!0,this.eventQueue||(this.eventQueue=new T.RAPIER_PHYSICS.MODULE.EventQueue(!1)),e===void 0||e<=0){this._isUpdatingPhysicsWorld=!1;return}else if(e!==void 0){const t=I.lerp(this.world.timestep,e,.8);this.world.timestep=t}try{this.world.step(this.eventQueue)}catch(t){console.warn("Error running physics step",{timestep:this.world.timestep},t)}this._isUpdatingPhysicsWorld=!1}}postStep(){this.world&&this.enabled&&(this._isUpdatingPhysicsWorld=!0,this.syncObjects(),this._isUpdatingPhysicsWorld=!1,this.eventQueue&&!this.collisionHandler&&(this.collisionHandler=new vA(this.world,this.eventQueue)),this.collisionHandler&&(this.collisionHandler.handleCollisionEvents(),this.collisionHandler.update()),this.updateDebugRendering(this.world))}updateDebugRendering(e){if(Ee||Rp||bA||this.debugRenderColliders===!0){if(!this.lines){const n=new c.LineBasicMaterial({color:7855479,fog:!1}),o=new c.BufferGeometry;this.lines=new c.LineSegments(o,n),this.lines.layers.disableAll(),this.lines.layers.enable(2)}if(!this.disabledLines){const n=new c.LineBasicMaterial({color:14514039,fog:!1}),o=new c.BufferGeometry;this.disabledLines=new c.LineSegments(o,n),this.disabledLines.layers.disableAll(),this.disabledLines.layers.enable(2)}this.lines.parent!==this.context?.scene&&this.context?.scene.add(this.lines),this.disabledLines.parent!==this.context?.scene&&this.context?.scene.add(this.disabledLines);const t=e.debugRender(void 0,n=>n.isEnabled());this.lines.geometry.setAttribute("position",new c.BufferAttribute(t.vertices,3)),this.lines.geometry.setAttribute("color",new c.BufferAttribute(t.colors,4));const i=e.debugRender(void 0,n=>!n.isEnabled());this.disabledLines.geometry.setAttribute("position",new c.BufferAttribute(i.vertices,3)),this.disabledLines.geometry.setAttribute("color",new c.BufferAttribute(i.colors,4)),this.disabledLines.visible=i.vertices.length>0,(this.context.time.frame%30===0||this.lines.geometry.boundingSphere?.radius===0)&&(this.lines.geometry.computeBoundingSphere(),this.disabledLines.geometry.computeBoundingSphere())}else this.lines&&this.context?.scene.remove(this.lines),this.disabledLines&&this.context?.scene.remove(this.disabledLines)}syncObjects(){if(!Rp)for(let e=0;e<this.bodies.length;e++){const t=this.objects[e],i=this.bodies[e],n=t;if(n?.isCollider===!0&&!n.attachedRigidbody){const l=i.parent();l?this.syncPhysicsBody(t.gameObject,l,!0,!0):this.syncPhysicsBody(t.gameObject,i,!0,!0);continue}const o=i.translation(),r=i.rotation();if(Number.isNaN(o.x)||Number.isNaN(r.x)){!n.__COLLIDER_NAN&&A()&&(console.warn("Collider has NaN values",n.name,n.gameObject,i),n.__COLLIDER_NAN=!0);continue}const a=t.center;if(a&&a.isVector3){this._tempQuaternion.set(r.x,r.y,r.z,r.w);const l=this._tempPosition.copy(a).applyQuaternion(this._tempQuaternion),h=je(t.gameObject);l.multiply(h),o.x-=l.x,o.y-=l.y,o.z-=l.z}hr(t.gameObject,o.x,o.y,o.z),Nm(t.gameObject,r.x,r.y,r.z,r.w)}}syncPhysicsBody(e,t,i,n){if(t instanceof T.RAPIER_PHYSICS.MODULE.RigidBody){const o=Y(e,this._tempPosition),r=pe(e,this._tempQuaternion);switch(t.bodyType()){case T.RAPIER_PHYSICS.MODULE.RigidBodyType.Fixed:case T.RAPIER_PHYSICS.MODULE.RigidBodyType.KinematicPositionBased:case T.RAPIER_PHYSICS.MODULE.RigidBodyType.KinematicVelocityBased:i&&t.setNextKinematicTranslation(o),n&&t.setNextKinematicRotation(r);break;default:i&&t.setTranslation(o,!1),n&&t.setRotation(r,!1);break}}else if(t instanceof T.RAPIER_PHYSICS.MODULE.Collider){e.matrixWorldNeedsUpdate&&e.updateWorldMatrix(!0,!1),e.matrixWorld.decompose(this._tempPosition,this._tempQuaternion,this._tempScale);const o=this._tempPosition,r=this._tempQuaternion,a=t[Kt];if(this.tryApplyCenter(a,o),i){const l=t.translation();(l.x!==o.x||l.y!==o.y||l.z!==o.z)&&t.setTranslation(o)}if(n){const l=t.rotation();(l.x!==r.x||l.y!==r.y||l.z!==r.z||l.w!==r.w)&&t.setRotation(r)}}}_tempCenterPos=new c.Vector3;_tempCenterVec=new c.Vector3;_tempCenterQuaternion=new c.Quaternion;tryApplyCenter(e,t){const i=e.center;i&&e.gameObject&&(i.x!==0||i.y!==0||i.z!==0)&&(this._tempCenterPos.x=i.x,this._tempCenterPos.y=i.y,this._tempCenterPos.z=i.z,je(e.gameObject,this._tempCenterVec),this._tempCenterPos.multiply(this._tempCenterVec),e.attachedRigidbody?this._tempCenterPos.applyQuaternion(e.gameObject.quaternion):(pe(e.gameObject,this._tempCenterQuaternion),this._tempCenterPos.applyQuaternion(this._tempCenterQuaternion)),t.x+=this._tempCenterPos.x,t.y+=this._tempCenterPos.y,t.z+=this._tempCenterPos.z)}static _matricesBuffer=[];getRigidbodyRelativeMatrix(e,t,i,n){if(n===void 0&&(n=Oa._matricesBuffer,n.length=0),e===t){const o=je(e,this._tempPosition);i.makeScale(o.x,o.y,o.z);for(let r=n.length-1;r>=0;r--)i.multiply(n[r]);return i}return n.push(e.matrix),e.parent&&this.getRigidbodyRelativeMatrix(e.parent,t,i,n),i}static centerConnectionPos={x:0,y:0,z:0};static centerConnectionRot={x:0,y:0,z:0,w:1};addFixedJoint(e,t){if(!this.world){console.error("Physics world not initialized");return}const i=e[gt],n=t[gt];this.calculateJointRelativeMatrices(e.gameObject,t.gameObject,this._tempMatrix),this._tempMatrix.decompose(this._tempPosition,this._tempQuaternion,this._tempScale);const o=T.RAPIER_PHYSICS.MODULE.JointData.fixed(Oa.centerConnectionPos,Oa.centerConnectionRot,this._tempPosition,this._tempQuaternion),r=this.world.createImpulseJoint(o,i,n,!0);Ee&&console.log("ADD FIXED JOINT",r)}addHingeJoint(e,t,i,n){if(!this.world){console.error("Physics world not initialized");return}const o=e[gt],r=t[gt];this.calculateJointRelativeMatrices(e.gameObject,t.gameObject,this._tempMatrix),this._tempMatrix.decompose(this._tempPosition,this._tempQuaternion,this._tempScale);const a=T.RAPIER_PHYSICS.MODULE.JointData.revolute(i,this._tempPosition,n),l=this.world.createImpulseJoint(a,o,r,!0);Ee&&console.log("ADD HINGE JOINT",l)}calculateJointRelativeMatrices(e,t,i){e.updateWorldMatrix(!0,!1),t.updateWorldMatrix(!0,!1);const n=e.matrixWorld,o=t.matrixWorld;n.elements[0]=1,n.elements[5]=1,n.elements[10]=1,o.elements[0]=1,o.elements[5]=1,o.elements[10]=1,i.copy(o).premultiply(n.invert()).invert()}}class vA{world;eventQueue;constructor(e,t){this.world=e,this.eventQueue=t}activeCollisions=[];activeCollisionsStay=[];activeTriggers=[];handleCollisionEvents(){this.eventQueue&&this.world&&this.eventQueue.drainCollisionEvents((e,t,i)=>{const n=this.world.getCollider(e),o=this.world.getCollider(t);if(!n||!o)return;const r=n[Kt],a=o[Kt];Tp&&console.log("EVT",r.name,a.name,i,n,o),r&&a&&(i?(this.onCollisionStarted(r,n,a,o),this.onCollisionStarted(a,o,r,n)):(this.onCollisionEnded(r,a),this.onCollisionEnded(a,r)))})}update(){this.onHandleCollisionStay()}onCollisionStarted(e,t,i,n){let o=null;if(e.isTrigger||i.isTrigger)ur(e.gameObject,r=>{r.onTriggerEnter&&!r.destroyed&&r.onTriggerEnter(i),this.activeTriggers.push({collider:e,component:r,otherCollider:i})});else{const r=e.gameObject;this.world.contactPair(t,n,(a,l)=>{ur(r,h=>{if(h.destroyed)return;const d=h.onCollisionEnter||h.onCollisionStay||h.onCollisionExit;if(d||Tp){if(!o){const u=[],p=a.normal();i instanceof wo&&i.convex&&(p.x=-p.x,p.y=-p.y,p.z=-p.z);for(let m=0;m<a.numSolverContacts();m++){const y=a.solverContactPoint(m),_=a.contactImpulse(m);if(y){const g=a.contactDist(m),v=a.solverContactFriction(m),b=a.solverContactTangentVelocity(m),w=new Hv(y,g,p,_,v,b);u.push(w),Tp&&B.DrawDirection(y,p,16711680,3,!0)}}o=new qv(r,i,u)}if(d){const u={collider:e,component:h,collision:o};this.activeCollisions.push(u),h.onCollisionStay&&this.activeCollisionsStay.push(u),h.onCollisionEnter?.call(h,o)}}})})}}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 i=e.collision;t.onCollisionStay(i)}}for(const e of this.activeTriggers){const t=e.component;if(!t.destroyed&&t.activeAndEnabled&&t.onTriggerStay){const i=e.otherCollider;if(i.destroyed)continue;t.onTriggerStay(i)}}}onCollisionEnded(e,t){if(!(e.destroyed||t.destroyed)){for(let i=0;i<this.activeCollisions.length;i++){const n=this.activeCollisions[i],o=n.collider;if(o.destroyed||n.collision.collider.destroyed){this.activeCollisions.splice(i,1),i--;continue}if(o===e&&n.collision.collider===t){const r=n.component;if(this.activeCollisions.splice(i,1),i--,r.activeAndEnabled&&r.onCollisionExit){const a=n.collision;r.onCollisionExit(a)}}}for(let i=0;i<this.activeCollisionsStay.length;i++){const n=this.activeCollisionsStay[i],o=n.collider;if(o.destroyed||n.collision.collider.destroyed){this.activeCollisionsStay.splice(i,1),i--;continue}if(o===e&&n.collision.collider===t){const r=n.component;if(this.activeCollisionsStay.splice(i,1),i--,r.activeAndEnabled&&r.onCollisionExit){const a=n.collision;r.onCollisionExit(a)}}}for(let i=0;i<this.activeTriggers.length;i++){const n=this.activeTriggers[i],o=n.collider;if(o.destroyed||n.otherCollider.destroyed){this.activeTriggers.splice(i,1),i--;continue}if(o===e&&n.otherCollider===t){const r=n.component;if(this.activeTriggers.splice(i,1),i--,r.activeAndEnabled&&r.onTriggerExit){const a=n.otherCollider;r.onTriggerExit(a)}}}}}}let Am=0;function cv(s){s?Am++:Am--}function wA(){return Am>0}const xA={binary:!0,animations:!0};async function SA(s){if(!s.context)throw new Error("No context provided to exportAsGLTF");s.scene||(s.scene=s.context.scene);const e={...xA,...s},{context:t}=e,i=new X.GLTFExporter;i.register(a=>new Vw(a)),i.register(a=>new ok(a)),i.register(a=>new Ww(a)),$g(i,e.context);const n={binary:e.binary,animations:PA(t,e.scene,[])},o=new CA;console.debug("Exporting GLTF",n),o.onBeforeExport(e),cv(!0);const r=await i.parseAsync(e.scene,n).catch(a=>(console.error(a),null));if(cv(!1),o.onAfterExport(e),!r)throw new Error("Failed to export GLTF");if(e.downloadAs!=null){let a=null;if(r instanceof ArrayBuffer?a=new Blob([r],{type:"application/octet-stream"}):console.error("Can not download GLTF as a blob",r),a){const l=URL.createObjectURL(a),h=document.createElement("a");h.href=l;let d=e.downloadAs;!d.endsWith(".glb")&&!d.endsWith(".gltf")&&(d+=e.binary?".glb":".gltf"),h.download=d,h.click()}}return r}const hv=Symbol("needle:weight");class CA{_undo=[];onBeforeExport(e){e.context.animations.mixers.forEach(t=>{const i=Hn.tryGetActionsFromMixer(t);if(i)for(let n=0;n<i.length;n++){const o=i[n];o[hv]=o.weight,o.weight=0,this._undo.push(()=>{o.weight=o[hv]})}t.update(0)}),e.context.scene.traverse(t=>{if(!mm(t)){const i=t.parent;i&&(t.removeFromParent(),this._undo.push(()=>i.add(t)))}})}onAfterExport(e){this._undo.forEach(t=>t()),this._undo.length=0}}function PA(s,e,t){s.animations.mixers.forEach(n=>{const o=Hn.tryGetActionsFromMixer(n);if(o)for(let r=0;r<o.length;r++){const l=o[r].getClip();t.push(l)}}),Array.isArray(e)||(e=[e]);for(const n of e)Hn.tryGetAnimationClipsFromObjectHierarchy(n,t);const i=new Set(t);return Array.from(i)}const Bl=x("debugavatar");class Xy{root;head;leftHand;rigthHand;get isValid(){return this.head!==null&&this.head!==void 0}constructor(e,t,i,n){this.root=e,this.head=t,this.leftHand=i,this.rigthHand=n,this.root?.traverse(o=>o.layers.set(2))}}class Xx{avatarRegistryUrl=null;async getOrCreateNewAvatarInstance(e,t){if(!t)return console.error("Can not create avatar: failed to provide id or root object"),null;let i=null;if(typeof t=="string"){if(i=await this.loadAvatar(e,t),!i){const o=new gn;i=S.instantiate(Ma(t,e.scene),o)}}else i=t;if(!i)return null;const n=this.findAvatar(i);return n.isValid?(Bl&&console.log("[Custom Avatar] valid config",t,Bl?n:""),n):(console.warn("[Custom Avatar] config isn't valid",t,Bl?n:""),null)}async loadAvatar(e,t){if(console.assert(t!=null&&typeof t=="string","Avatar id must not be null"),t.length<=0||!t)return null;if(Bl&&console.log("[Custom Avatar] "+t+", loading..."),t.endsWith(".glb")||(t+=".glb"),this.avatarRegistryUrl===null){const n=await fetch("./"+t);let o=null;if(n.ok){const a=await n.blob();a&&(o=await a.arrayBuffer())}return o?(await un().parseSync(e,o,null,0))?.scene??null:null}const i=new X.GLTFLoader;return cy(i,e),new Promise((n,o)=>{const r=this.avatarRegistryUrl+"/"+t;i.load(r,async a=>{await un().createBuiltinComponents(e,r,a,null,void 0),n(a.scene)},a=>{Bl&&console.log("[Custom Avatar] "+a.loaded/a.total*100+"% loaded of "+a.total/1024+"kB")},a=>{console.error("[Custom Avatar] Error when loading: "+a),n(null)})})}cacheModel(e,t){}findAvatar(e){const t=e;let i=t;i.children.length==1&&(i=e.children[0]);let n=this.findAvatarPart(i,["head"]);const o=this.findAvatarPart(i,["left","hand"]),r=this.findAvatarPart(i,["right","hand"]);if(!n){n=t;const l=new c.Vector3;new c.Box3().setFromObject(n).getSize(l);const h=Math.max(l.x,l.y,l.z);console.warn("[Custom Avatar] Normalizing head scale, it's too big: "+h+" meters! Should be < 0.3m"),h>.3&&n.scale.multiplyScalar(1/h*.3)}return new Xy(t,n,o,r)}findAvatarPart(e,t){const i=e.name.toLowerCase();let n=!0;for(const o of t){if(!n)break;i.indexOf(o)===-1&&(n=!1)}if(n)return e;if(e.children)for(const o of e.children){const r=this.findAvatarPart(o,t);if(r)return r}return null}handleCustomAvatarErrors(e){if(!e.ok)throw Error(e.statusText);return e}}class Qx{get extensionName(){return"DocumentExtension"}onAfterBuildDocument(e){}}class Yx{}const OA=Object.freeze(Object.defineProperty({__proto__:null,ActionBuilder:ue,ActionCollection:ox,ActionModel:Jt,AlignmentConstraint:ih,Animation:Tt,AnimationCurve:yh,AnimationExtension:Xu,AnimationTrackHandler:Rc,Animator:lt,AnimatorController:Vi,Antialiasing:bh,Attractor:al,AudioExtension:Mr,AudioListener:ds,AudioSource:vi,AudioTrackHandler:us,Avatar:fo,AvatarBlink_Simple:Sr,AvatarEyeLook_Rotation:Lg,AvatarLoader:Xx,AvatarMarker:Oe,AvatarModel:Xy,Avatar_Brain_LookAt:Ac,Avatar_MouthShapes:sh,Avatar_MustacheShake:Ag,Avatar_POI:lr,AxesHelper:qa,BaseUIComponent:Wi,BasicIKConstraint:jg,BehaviorExtension:hy,BehaviorModel:St,BloomEffect:hf,BoxCollider:Vu,BoxGizmo:Tr,BoxHelperComponent:bt,Button:Ds,CallInfo:ls,Camera:si,CameraTargetReachedEvent:Ec,Canvas:Fa,CanvasGroup:po,CapsuleCollider:bs,ChangeMaterialOnClick:iy,ChangeTransformOnClick:kr,CharacterController:Cr,CharacterControllerInput:Cs,ChromaticAberration:vh,ClickThrough:wf,ColorAdjustments:ko,ColorBySpeedModule:rl,ColorOverLifetimeModule:af,ContactShadows:oh,ControlTrackHandler:Bu,CursorFollow:Vr,CustomBranding:Rr,Deletable:zg,DeleteBox:ro,DepthOfField:bn,DeviceFlag:$u,DocumentExtension:Qx,DragControls:Ko,DropListener:Os,Duplicatable:qg,EffectWrapper:jc,EmissionModule:Rs,EmphasizeOnClick:Ka,EnvironmentScene:Fu,EventList:ne,EventListEvent:Tu,EventSystem:Gt,EventTrigger:Hu,FieldWithDefault:zw,FixedJoint:Cy,Fog:il,GltfExport:Zg,GltfExportBox:Yg,Gradient:Dr,Graphic:ph,GraphicRaycaster:Du,GridHelper:nl,GridLayoutGroup:gy,GroundProjectedEnv:Xn,GroupActionModel:Zo,HideOnStart:Ii,HingeJoint:gh,HorizontalLayoutGroup:my,get HoverAnimation(){return exports.HoverAnimation},Image:dl,InheritVelocityModule:Ey,InputField:zy,InstanceHandle:cr,InstancingHandler:gr,Interactable:Ug,Keyframe:oi,LODGroup:sf,LODModel:sl,Light:Ot,LimitVelocityOverLifetimeModule:nt,LogStats:Fg,LookAt:Ny,LookAtConstraint:xr,MainModule:Lt,MarkerTrackHandler:ju,MaskableGraphic:mh,MeshCollider:wo,MeshRenderer:lh,MinMaxCurve:H,MinMaxGradient:Lr,NeedleMenu:Yn,NestedGltf:ol,Networking:My,NoiseModule:me,ObjectRaycaster:$i,OffsetConstraint:Ar,OpenURL:ul,OrbitControls:he,Outline:tl,Padding:Er,ParticleBurst:du,ParticleSubEmitter:Ry,ParticleSystem:Ic,ParticleSystemRenderer:Yi,PhysicsExtension:dy,PixelationEffect:wh,PlayAnimationOnClick:Dc,PlayAudioOnClick:uo,PlayableDirector:ja,PlayerColor:Ua,PointerEventData:Zc,PostProcessingHandler:za,PreliminaryAction:Za,PreliminaryTrigger:hh,RawImage:_f,Rect:dx,RectTransform:mn,ReflectionProbe:os,RegisteredAnimationInfo:so,RemoteSkybox:Uu,Renderer:Ht,RendererLightmap:Wg,Rigidbody:$e,RotationBySpeedModule:Qi,RotationOverLifetimeModule:_n,SceneSwitcher:We,ScreenCapture:Eo,ScreenSpaceAmbientOcclusion:Ts,ScreenSpaceAmbientOcclusionN8:vn,ScrollFollow:Ls,SeeThrough:As,SetActiveOnClick:ny,ShadowCatcher:Ph,ShapeModule:ky,SharpeningEffect:Sh,SignalAsset:Iu,SignalReceiver:eh,SignalReceiverEvent:Jc,SignalTrackHandler:Tc,Size:hx,SizeBySpeedModule:di,SizeOverLifetimeModule:Ir,SkinnedMeshRenderer:Gg,SmoothFollow:ff,SpatialGrabRaycaster:fr,SpatialHtml:Eh,SpatialTrigger:pf,SpatialTriggerReceiver:Gn,SpectatorCamera:mf,SphereCollider:Xa,SplineContainer:zr,SplineData:qn,SplineWalker:Zi,Sprite:Ms,SpriteData:Pa,SpriteRenderer:ci,SpriteSheet:Ba,SubEmitterSystem:uu,SyncedCamera:jy,SyncedRoom:wn,SyncedTransform:pn,TapGestureTrigger:oy,TeleportTarget:Ju,TestRunner:By,TestSimulateUserData:Fy,Text:Dt,TextBuilder:fy,TextExtension:tf,TextureSheetAnimationModule:It,TiltShiftEffect:Zn,ToneMappingEffect:mo,TrailModule:Le,TransformData:Ae,TransformGizmo:Nr,TriggerBuilder:Rt,TriggerModel:ao,UIRaycastUtils:xg,UIRootComponent:uh,USDZExporter:Wn,USDZText:ma,USDZUIExtension:_y,UsageMarker:rh,VariantAction:ty,VelocityOverLifetimeModule:Fe,VerticalLayoutGroup:py,VideoPlayer:tt,get ViewBox(){return exports.ViewBox},Vignette:Fr,VisibilityAction:dh,Voip:vo,Volume:Ur,VolumeParameter:z,VolumeProfile:lf,WebARCameraBackground:Th,WebARSessionRoot:Ui,WebXR:ef,WebXRImageTracking:Ah,WebXRImageTrackingModel:js,WebXRPlaneTracking:Bs,WebXRTrackedImage:Na,XRControllerFollow:Is,XRControllerModel:vs,XRControllerMovement:xi,XRFlag:ji,XRRig:Cf,XRState:Wt,__Ignore:Yx},Symbol.toStringTag,{value:"Module"}));exports.SplineUtils=void 0;(s=>{function e(t,i=!1,n=.75){const o=new zr,r=1-I.clamp(n,0,1);return t.forEach((a,l)=>{const h=new c.Vector3;l<t.length-1?h.subVectors(t[l+1],a).normalize().multiplyScalar(r):i&&t.length>1&&h.subVectors(t[0],a).normalize().multiplyScalar(r);const d=new qn;d.position.copy(a),d.tangentIn.copy(h),d.tangentOut.copy(h),o.addKnot(d)}),o.closed=i,o}s.createFromPoints=e})(exports.SplineUtils||(exports.SplineUtils={}));class MA extends le.WorkerBase{constructor(){super(new Worker(new URL("/generateMeshBVH.worker-DiCnZlf3.js",typeof document>"u"?require("url").pathToFileURL(__filename).href:ya&&ya.tagName.toUpperCase()==="SCRIPT"&&ya.src||new URL("needle-engine.bundle-CzOPcOui.umd.cjs",document.baseURI).href),{type:"module"})),this.name="GenerateMeshBVHWorker"}runTask(e,t,i={}){return new Promise((n,o)=>{if(t.getAttribute("position").isInterleavedBufferAttribute||t.index&&t.index.isInterleavedBufferAttribute)throw new Error("GenerateMeshBVHWorker: InterleavedBufferAttribute are not supported for the geometry attributes.");e.onerror=h=>{o(new Error(`[GenerateMeshBVHWorker] ${h.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=h=>{const{data:d}=h;if(d.error)o(new Error(d.error)),e.onmessage=null;else if(d.serialized){const{serialized:u,position:p}=d,m=le.MeshBVH.deserialize(u,t,{setIndex:!1}),y=Object.assign({setBoundingBox:!0},i);if(t.attributes.position.array=p,u.index)if(t.index)t.index.array=u.index;else{const _=new c.BufferAttribute(u.index,1,!1);t.setIndex(_)}y.setBoundingBox&&(t.boundingBox=m.getBoundingBox(new c.Box3)),i.onProgress&&i.onProgress(d.progress),n(m),e.onmessage=null}else i.onProgress&&i.onProgress(d.progress)};const r=t.index?t.index.array:null,a=t.attributes.position.array,l=[a];r&&l.push(r),e.postMessage({index:r,position:a,options:{...i,onProgress:null,includedProgressCallback:!!i.onProgress,groups:[...t.groups]}},l.map(h=>h.buffer).filter(h=>typeof SharedArrayBuffer>"u"||!(h instanceof SharedArrayBuffer)))})}}const kA=Object.freeze(Object.defineProperty({__proto__:null,GenerateMeshBVHWorker:MA},Symbol.toStringTag,{value:"Module"}));exports.$componentName=Gv;exports.$physicsKey=TC;exports.ActionBuilder=ue;exports.ActionCollection=ox;exports.ActionModel=Jt;exports.Addressables=f0;exports.AlignmentConstraint=ih;exports.AmbientMode=va;exports.Animation=Tt;exports.AnimationCurve=yh;exports.AnimationExtension=Xu;exports.AnimationTrackHandler=Rc;exports.AnimationUtils=Hn;exports.Animator=lt;exports.AnimatorConditionMode=Zs;exports.AnimatorController=Vi;exports.AnimatorControllerParameterType=wg;exports.AnimatorStateInfo=Vl;exports.Antialiasing=bh;exports.Application=fn;exports.AssetDatabase=N0;exports.AssetReference=Z;exports.Attractor=al;exports.AudioExtension=Mr;exports.AudioListener=ds;exports.AudioSource=vi;exports.AudioTrackHandler=us;exports.Avatar=fo;exports.AvatarBlink_Simple=Sr;exports.AvatarEyeLook_Rotation=Lg;exports.AvatarLoader=Xx;exports.AvatarMarker=Oe;exports.AvatarModel=Xy;exports.Avatar_Brain_LookAt=Ac;exports.Avatar_MouthShapes=sh;exports.Avatar_MustacheShake=Ag;exports.Avatar_POI=lr;exports.Axes=fa;exports.AxesHelper=qa;exports.BUILD_TIME=_c;exports.BaseUIComponent=Wi;exports.BasicIKConstraint=jg;exports.BehaviorExtension=hy;exports.BehaviorModel=St;exports.BloomEffect=hf;exports.BoxCollider=Vu;exports.BoxGizmo=Tr;exports.BoxHelperComponent=bt;exports.Button=Ds;exports.ButtonsFactory=Fi;exports.CallDirection=Sw;exports.CallInfo=ls;exports.Camera=si;exports.CameraTargetReachedEvent=Ec;exports.Canvas=Fa;exports.CanvasGroup=po;exports.CapsuleCollider=bs;exports.ChangeMaterialOnClick=iy;exports.ChangeTransformOnClick=kr;exports.CharacterController=Cr;exports.CharacterControllerInput=Cs;exports.ChromaticAberration=vh;exports.CircularBuffer=_i;exports.ClearFlags=ar;exports.ClickThrough=wf;exports.ClipExtrapolation=Mn;exports.Collider=Xi;exports.Collision=qv;exports.CollisionDetectionMode=Au;exports.ColorAdjustments=ko;exports.ColorBySpeedModule=rl;exports.ColorOverLifetimeModule=af;exports.Component=BP;exports.Component$1=E;exports.ComponentLifecycleEvents=gu;exports.Components=OA;exports.ConnectionEvents=x0;exports.ContactPoint=Hv;exports.ContactShadows=oh;exports.Context=U;exports.ContextArgs=Q1;exports.ContextEvent=ae;exports.ContextRegistry=ce;exports.ControlTrackHandler=Bu;exports.CursorFollow=Vr;exports.CustomBranding=Rr;exports.CustomShader=ve;exports.DefaultReflectionMode=Kd;exports.Deletable=zg;exports.DeleteBox=ro;exports.DepthOfField=bn;exports.DeviceFlag=$u;exports.DocumentExtension=Qx;exports.DragControls=Ko;exports.DragMode=Ng;exports.DropListener=Os;exports.Duplicatable=qg;exports.EffectWrapper=jc;exports.EmissionModule=Rs;exports.EmphasizeOnClick=Ka;exports.EngineLoadingView=Bc;exports.EnvironmentScene=Fu;exports.EventList=ne;exports.EventListEvent=Tu;exports.EventSystem=Gt;exports.EventTrigger=Hu;exports.FieldWithDefault=zw;exports.FileReference=ir;exports.FileReferenceSerializer=m0;exports.FileSpawnModel=xM;exports.File_Event=Tw;exports.FixedJoint=Cy;exports.Fog=il;exports.FrameEvent=ge;exports.GENERATOR=Ea;exports.GameObject=S;exports.Gizmos=B;exports.GltfExport=Zg;exports.GltfExportBox=Yg;exports.Gradient=Dr;exports.Graphic=ph;exports.GraphicRaycaster=Du;exports.Graphics=co;exports.GridHelper=nl;exports.GridLayoutGroup=gy;exports.GroundProjectedEnv=Xn;exports.GroupActionModel=Zo;exports.HideFlags=_u;exports.HideOnStart=Ii;exports.HingeJoint=gh;exports.HorizontalLayoutGroup=my;exports.HostData=$C;exports.Image=dl;exports.ImageReference=tr;exports.ImageReferenceSerializer=p0;exports.InheritVelocityModule=Ey;exports.Input=y0;exports.InputEventQueue=ti;exports.InputEvents=Pe;exports.InputField=zy;exports.InstanceHandle=cr;exports.InstancingHandler=gr;exports.InstancingUtil=Ni;exports.InstantiateEvent=t0;exports.InstantiateIdProvider=xt;exports.InstantiateOptions=gn;exports.Interactable=Ug;exports.JoinedRoomResponse=b1;exports.KeyEventArgs=d1;exports.Keyframe=oi;exports.LODGroup=sf;exports.LODModel=sl;exports.LeftRoomResponse=v1;exports.Light=Ot;exports.LightData=k0;exports.LimitVelocityOverLifetimeModule=nt;exports.LoadingElementOptions=dA;exports.LogStats=Fg;exports.LogType=gi;exports.LookAt=Ny;exports.LookAtConstraint=xr;exports.MODULES=T;exports.MainModule=Lt;exports.MarkerTrackHandler=ju;exports.MarkerType=Pg;exports.MaskableGraphic=mh;exports.MaterialPropertyBlock=ys;exports.Mathf=I;exports.MeshCollider=wo;exports.MeshRenderer=lh;exports.MinMaxCurve=H;exports.MinMaxGradient=Lr;exports.NEEDLE_ENGINE_FEATURE_FLAGS=Xm;exports.NEKeyboardEvent=Fl;exports.NEPointerEvent=ss;exports.NeedleButtonElement=Wx;exports.NeedleEngineWebComponent=qy;exports.NeedleMenu=Yn;exports.NeedlePatchesKey=_d;exports.NeedleXRController=ug;exports.NeedleXRSession=q;exports.NeedleXRSync=F0;exports.NeedleXRUtils=z0;exports.NestedGltf=ol;exports.NetworkConnection=C0;exports.NetworkedStreamEvents=Un;exports.NetworkedStreams=nh;exports.Networking=My;exports.NewInstanceModel=n0;exports.NoiseModule=me;exports.ObjectRaycaster=$i;exports.ObjectUtils=_o;exports.OffsetConstraint=Ar;exports.OneEuroFilter=gd;exports.OneEuroFilterXYZ=Um;exports.OpenURL=ul;exports.OrbitControls=he;exports.Outline=tl;exports.OwnershipEvent=S0;exports.OwnershipModel=lg;exports.PUBLIC_KEY=no;exports.Padding=Er;exports.ParticleBurst=du;exports.ParticleSubEmitter=Ry;exports.ParticleSystem=Ic;exports.ParticleSystemBaseBehaviour=Mo;exports.ParticleSystemRenderer=Yi;exports.ParticleSystemShapeType=hu;exports.PeerHandle=fs;exports.PeerNetworking=w0;exports.Physics=Ia;exports.PhysicsExtension=dy;exports.PhysicsMaterialCombine=st;exports.PixelationEffect=wh;exports.PlayAnimationOnClick=Dc;exports.PlayAudioOnClick=uo;exports.PlayableDirector=ja;exports.PlayerColor=Ua;exports.PlayerState=zi;exports.PlayerStateEvent=lx;exports.PlayerSync=ay;exports.PlayerView=P0;exports.PlayerViewManager=O0;exports.PointerEventData=Zc;exports.PointerType=vu;exports.PostProcessingEffect=Xe;exports.PostProcessingEffectOrder=et;exports.PostProcessingHandler=za;exports.PreliminaryAction=Za;exports.PreliminaryTrigger=hh;exports.PrimitiveType=Va;exports.Progress=oe;exports.PromiseAllWithErrors=Bm;exports.PromiseErrorResult=Lp;exports.RGBAColor=te;exports.RapierPhysics=Oa;exports.RawImage=_f;exports.RaycastOptions=bo;exports.Rect=dx;exports.RectTransform=mn;exports.ReflectionProbe=os;exports.RegisteredAnimationInfo=so;exports.RemoteSkybox=Uu;exports.RenderTexture=Bn;exports.RenderTextureSerializer=pw;exports.Renderer=Ht;exports.RendererData=M0;exports.RendererLightmap=Wg;exports.Rigidbody=$e;exports.RigidbodyConstraints=Ve;exports.RoomEvents=K;exports.RotationBySpeedModule=Qi;exports.RotationOverLifetimeModule=_n;exports.SceneLightSettings=ou;exports.SceneSwitcher=We;exports.ScreenCapture=Eo;exports.ScreenSpaceAmbientOcclusion=Ts;exports.ScreenSpaceAmbientOcclusionN8=vn;exports.ScrollFollow=Ls;exports.SeeThrough=As;exports.SendQueue=ln;exports.SerializationContext=ng;exports.SetActiveOnClick=ny;exports.ShadowCatcher=Ph;exports.ShapeModule=ky;exports.ShapeOverlapResult=Xv;exports.SharpeningEffect=Sh;exports.SignalAsset=Iu;exports.SignalReceiver=eh;exports.SignalReceiverEvent=Jc;exports.SignalTrackHandler=Tc;exports.Size=hx;exports.SizeBySpeedModule=di;exports.SizeOverLifetimeModule=Ir;exports.SkinnedMeshRenderer=Gg;exports.SmoothFollow=ff;exports.SpatialGrabRaycaster=fr;exports.SpatialHtml=Eh;exports.SpatialTrigger=pf;exports.SpatialTriggerReceiver=Gn;exports.SpectatorCamera=mf;exports.SphereCollider=Xa;exports.SphereIntersection=mg;exports.SplineContainer=zr;exports.SplineData=qn;exports.SplineWalker=Zi;exports.Sprite=Ms;exports.SpriteData=Pa;exports.SpriteRenderer=ci;exports.SpriteSheet=Ba;exports.StateMachineBehaviour=VP;exports.StreamEndedEvent=Rg;exports.StreamReceivedEvent=xw;exports.SubEmitterSystem=uu;exports.SyncedCamera=jy;exports.SyncedRoom=wn;exports.SyncedTransform=pn;exports.TapGestureTrigger=oy;exports.TeleportTarget=Ju;exports.TestRunner=By;exports.TestSimulateUserData=Fy;exports.Text=Dt;exports.TextBuilder=fy;exports.TextExtension=tf;exports.TextureSheetAnimationModule=It;exports.TiltShiftEffect=Zn;exports.Time=E0;exports.ToneMappingEffect=mo;exports.TrackHandler=Ha;exports.TrackType=fi;exports.TrailModule=Le;exports.TransformData=Ae;exports.TransformGizmo=Nr;exports.TriggerBuilder=Rt;exports.TriggerModel=ao;exports.TypeStore=P;exports.UIRaycastUtils=xg;exports.UIRootComponent=uh;exports.USDDocument=Jg;exports.USDObject=qe;exports.USDWriter=Yw;exports.USDZExporter=Kw;exports.USDZExporter$1=Wn;exports.USDZText=ma;exports.USDZUIExtension=_y;exports.UriSerializer=mw;exports.UsageMarker=rh;exports.UserJoinedOrLeftRoomModel=w1;exports.VERSION=ii;exports.VariantAction=ty;exports.VelocityOverLifetimeModule=Fe;exports.VerticalLayoutGroup=py;exports.VideoPlayer=tt;exports.ViewDevice=gs;exports.Vignette=Fr;exports.VisibilityAction=dh;exports.Voip=vo;exports.Volume=Ur;exports.VolumeParameter=z;exports.VolumeProfile=lf;exports.WaitForFrames=a1;exports.WaitForPromise=g0;exports.WaitForSeconds=sg;exports.Watch=ms;exports.WebARCameraBackground=Th;exports.WebARSessionRoot=Ui;exports.WebXR=ef;exports.WebXRButtonFactory=lo;exports.WebXRImageTracking=Ah;exports.WebXRImageTrackingModel=js;exports.WebXRPlaneTracking=Bs;exports.WebXRTrackedImage=Na;exports.XRControllerFollow=Is;exports.XRControllerModel=vs;exports.XRControllerMovement=xi;exports.XRFlag=ji;exports.XRRig=Cf;exports.XRState=Wt;exports.XRStateFlag=Ln;exports.__Ignore=Yx;exports.__internalNotifyObjectDestroyed=gP;exports.activeInHierarchyFieldName=jn;exports.addAttributeChangeCallback=Im;exports.addComponent=hn;exports.addCustomExtensionPlugin=HM;exports.addNewComponent=or;exports.addPatch=yu;exports.apply=Ou;exports.applyHMRChanges=jP;exports.applyPrototypeExtensions=Y0;exports.beginListenDestroy=i0;exports.beginListenInstantiate=o0;exports.binaryIdentifierCasts=og;exports.build_scene_functions=X1;exports.builtinComponentKeyName=Ho;exports.calculateProgress01=Hy;exports.clearMessages=PS;exports.colorSerializer=QP;exports.compareAssociation=c0;exports.componentSerializer=Md;exports.copyTexture=Tv;exports.createMotion=uw;exports.debugNet=Yt;exports.debugOwner=Ul;exports.decompressGpuTexture=tx;exports.deepClone=Uc;exports.delay=_s;exports.delayForFrames=zc;exports.deserializeObject=Qd;exports.destroy=bi;exports.destroyComponentInstance=rw;exports.determineMimeTypeFromExtension=Aw;exports.disposeObjectResources=we;exports.disposeStream=zn;exports.editorGuidKeyName=ec;exports.enableSpatialConsole=_a;exports.euler=KP;exports.eventListSerializer=tO;exports.exportAsGLTF=SA;exports.findByGuid=_g;exports.findObjectOfType=Ga;exports.findObjectsOfType=lw;exports.findResourceUsers=gg;exports.fitCamera=gw;exports.fitObjectIntoVolume=Dv;exports.foreachComponent=ur;exports.foreachComponentEnumerator=ku;exports.forward=WS;exports.generateQRCode=L0;exports.generateSeed=s0;exports.getBoundingBox=ri;exports.getCameraController=Sv;exports.getComponent=vr;exports.getComponentInChildren=Yc;exports.getComponentInParent=Pc;exports.getComponents=Qc;exports.getComponentsInChildren=Wa;exports.getComponentsInParent=Eu;exports.getFormattedDate=Hw;exports.getIconElement=wt;exports.getIconTexture=Kp;exports.getLoader=un;exports.getOrAddComponent=Xc;exports.getParam=x;exports.getParentHierarchyPath=qS;exports.getPath=nS;exports.getPeerOptions=m1;exports.getPeerjsInstance=v0;exports.getResourceUserCount=_P;exports.getTempColor=Mv;exports.getTempQuaternion=ei;exports.getTempVector=F;exports.getUrlParams=Fc;exports.getVisibleInCustomShadowRendering=Av;exports.getWorldDirection=kv;exports.getWorldEuler=Vm;exports.getWorldPosition=Y;exports.getWorldQuaternion=pe;exports.getWorldRotation=mu;exports.getWorldScale=je;exports.hasCommercialLicense=$n;exports.hasIndieLicense=Wc;exports.hasPointerEventComponent=iu;exports.hasProLicense=Vn;exports.hideDebugConsole=Bv;exports.imageToCanvas=ix;exports.initEngine=_A;exports.instantiate=ho;exports.invokeLoadedImportPluginHooks=Uw;exports.invokeXRSessionEnd=D0;exports.invokeXRSessionStart=A0;exports.isActiveInHierarchy=K0;exports.isActiveSelf=$a;exports.isAndroidDevice=cS;exports.isAnimationAction=Rv;exports.isComponent=Ym;exports.isDebugMode=Jx;exports.isDesktop=oS;exports.isDestroyed=dr;exports.isDevEnvironment=A;exports.isDisposed=mP;exports.isExporting=wA;exports.isGLTFModel=Wv;exports.isHostedOnGlitch=dv;exports.isHotReloadEnabled=lm;exports.isHotReloading=LP;exports.isIPad=aS;exports.isIconElement=I0;exports.isLocalNetwork=yi;exports.isMacOS=dS;exports.isMobileDevice=rS;exports.isMozillaXR=hS;exports.isQuest=pS;exports.isResourceTrackingEnabled=$0;exports.isSafari=fS;exports.isUsingInstancing=Mu;exports.isiOS=uS;exports.isiPad=lS;exports.loadAsset=nA;exports.loadPMREM=Eg;exports.loadSync=Gy;exports.logHierarchy=$d;exports.lookAtInverse=jS;exports.lookAtObject=Nc;exports.lookAtScreenPoint=BS;exports.makeId=tS;exports.makeIdFromRandomWords=pv;exports.makeNameSafe=wi;exports.markAsInstancedRendered=Z0;exports.microphonePermissionsGranted=mS;exports.nameof=Zx;exports.nameofFactory=uv;exports.objectSerializer=fw;exports.offXRSessionEnd=A1;exports.offXRSessionStart=T1;exports.onAfterRender=IC;exports.onBeforeRender=LC;exports.onClear=AC;exports.onDestroy=DC;exports.onInitialized=Km;exports.onStart=bu;exports.onUpdate=Zv;exports.onXRSessionEnd=hg;exports.onXRSessionStart=xu;exports.parseSync=Vx;exports.placeOnSurface=Lv;exports.postprocessFBXMaterials=Gm;exports.prefix=lO;exports.pushState=fv;exports.randomNumber=iS;exports.registerBinaryType=rg;exports.registerComponent=Cu;exports.registerComponentExtension=Vg;exports.registerCustomEffectType=Ki;exports.registerExportExtensions=$g;exports.registerExtensions=au;exports.registerHotReloadType=cw;exports.registerLoader=Yv;exports.registerPrefabProvider=a0;exports.registerPrototypeExtensions=yg;exports.registerType=qm;exports.relativePathPrefix=gv;exports.removeAttributeChangeCallback=jm;exports.removeComponent=vg;exports.removeCustomImportExtensionType=qM;exports.removePatch=kC;exports.resolveUrl=ws;exports.sanitizeString=mv;exports.saveImage=Ux;exports.screenshot=jT;exports.screenshot2=Wy;exports.sendDestroyed=Jm;exports.serializable=f;exports.serializeObject=d0;exports.serializeable=Be;exports.setActive=sc;exports.setAllowBalloonMessages=vv;exports.setAllowOverlayMessages=wS;exports.setAutoFitEnabled=Nd;exports.setCameraController=Bp;exports.setDestroyed=ew;exports.setDevEnvironment=RS;exports.setDisposable=G0;exports.setDontDestroy=na;exports.setOrAddParamsToUrl=Dp;exports.setParam=eS;exports.setParamWithoutReload=yc;exports.setPeerOptions=g1;exports.setResourceTrackingEnabled=pP;exports.setState=Dm;exports.setVisibleInCustomShadowRendering=Wm;exports.setWorldEuler=$m;exports.setWorldPosition=at;exports.setWorldPositionXYZ=hr;exports.setWorldQuaternion=dn;exports.setWorldQuaternionXYZW=Nm;exports.setWorldRotation=Ev;exports.setWorldRotationXYZ=Vc;exports.setWorldScale=ka;exports.showBalloonError=$c;exports.showBalloonMessage=Se;exports.showBalloonWarning=fe;exports.showDebugConsole=Hm;exports.slerp=Pv;exports.syncDestroy=Gc;exports.syncField=kg;exports.syncInstantiate=eg;exports.textureToCanvas=XS;exports.toSourceId=yv;exports.tryCastBinary=_0;exports.tryDetermineMimetypeFromBinary=Lw;exports.tryDetermineMimetypeFromURL=Dw;exports.tryFindObject=Ma;exports.tryGetGuid=b0;exports.unregisterHotReloadType=hw;exports.unwatchWrite=Lm;exports.useForAutoFit=Cv;exports.validate=Ct;exports.watchWrite=pu;
|