@needle-tools/engine 4.16.0-next.bc4d35d → 4.16.1

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.
@@ -141,7 +141,7 @@ void main(){
141
141
  #__vconsole .vc-mask {
142
142
  overflow: hidden;
143
143
  }
144
- `,Or?.prepend(i),o===!0&&o_()<=0&&A_(),console.log("\u{1F335} Debug console has loaded")}},e.onerror=()=>{console.warn("\u{1F335} Debug console failed to load."+(window.crossOriginIsolated?"This page is using cross-origin isolation, so external scripts can't be loaded.":"")),vc=!1,hi=null},e.src="https://cdn.jsdelivr.net/npm/vconsole@3.15.1/dist/vconsole.min.js",document.body.appendChild(e)}function JO(){if(!globalThis.VConsole)return;const o=new VConsole.VConsolePlugin("needle-console","\u{1F335} Inspect glTF"),e=()=>document.querySelector("#__vc_plug_"+o._id+" iframe");return o.on("renderTab",function(t){const i=globalThis["needle:codegen_files"];if(!i||i.length===0)return;let n=globalThis["needle:codegen_files"][0];const s=n.indexOf("?");s>-1&&(n=n.substring(0,s));const r=location.protocol+"//"+location.host+location.pathname+"/"+n,a=encodeURIComponent(r);o.fullUrl="https://viewer.needle.tools?inspect&file="+a;var l='<iframe src="" style="width: 100%; height: 99%; border: none;"></iframe>';t(l)}),o.on("show",function(){const t=e();t&&t.src!==o.fullUrl&&(t.src=o.fullUrl)}),o.on("hide",function(){const t=e();t&&(t.src="")}),o.on("addTopBar",function(t){var i=new Array;i.push({name:"Open in new window \u2197",onClick:function(n){window.open(o.fullUrl,"_blank"),hi?.hide()}}),i.push({name:"Reload",onClick:function(n){const s=e();s&&(s.src=o.fullUrl)}}),i.push({name:"Fullscreen",onClick:function(n){const s=e();s.requestFullscreen?s.requestFullscreen():s.webkitRequestFullscreen instanceof Function&&s.webkitRequestFullscreen()}}),t(i)}),o}const fg="padding: 10px; font-family: monospace;",L_="margin-bottom: 10px;",kr="margin-bottom: 10px; margin-top: 15px;",ek="width: 100%; border-collapse: collapse; border: 1px solid rgba(0,0,0,0.1); table-layout: fixed;",D_="border: 1px solid rgba(0,0,0,0.1); padding: 5px;",tk=D_,ik=D_+" word-break: break-all;";function Hn(o,e=!1){e&&o.sort((i,n)=>(n.value?1:0)-(i.value?1:0));let t=`<table style='${ek}'>`;t+="<tbody>";for(const i of o){const n=typeof i.value=="boolean"?i.value?"\u2705":"\u274C":i.value;t+=`<tr><td style='${tk}'>${i.label}</td><td style='${ik}'>${n}</td></tr>`}return t+="</tbody></table>",t}function j_(){try{if(document.createElement("canvas").getContext("webgl2"))return"\u2705"}catch{}return"\u274C"}function nk(){if(!globalThis.VConsole)return;const o=new VConsole.VConsolePlugin("device-utilities","\u{1F4F1} Device Info");return o.on("renderTab",function(e){let t=`<div style='${fg}'>`;const i=pk();t+=`<h3 style='${L_}'>Device: ${i}</h3>`,t+=Hn([{label:"\u{1F4BB} Desktop",value:I.isDesktop()},{label:"\u{1F4F1} Mobile Device",value:I.isMobileDevice()},{label:"\u{1F34E} iOS",value:I.isiOS()},{label:"\u{1F4F1} iPad",value:I.isiPad()},{label:"\u{1F916} Android",value:I.isAndroidDevice()},{label:"\u{1F98A} Mozilla XR",value:I.isMozillaXR()},{label:"\u{1F335} Needle App Clip",value:I.isNeedleAppClip()},{label:"\u{1F34F} macOS",value:I.isMacOS()},{label:"\u{1F453} VisionOS",value:I.isVisionOS()},{label:"\u{1F9ED} Safari",value:I.isSafari()},{label:"\u{1F576}\uFE0F Meta Quest",value:I.isQuest()},{label:"\u{1F517} QuickLook AR Support",value:I.supportsQuickLookAR()}],!0);const n=[],s=I.getiOSVersion();s&&n.push({label:"\u{1F34E} iOS Version",value:s});const r=I.getChromeVersion();r&&n.push({label:"\u{1F310} Chrome Version",value:r});const a=I.getSafariVersion();a&&n.push({label:"\u{1F9ED} Safari Version",value:a}),n.length>0&&(t+=Hn(n,!1)),t+="</div>",t+=`<div style='${fg} margin-top: 20px;'>`,t+=`<h3 style='${L_}'>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?"\u2705":"\u274C"},{label:"WebGPU",value:"gpu"in navigator?"\u2705":"\u274C"},{label:"WebGL 2",value:j_()}];t+=Hn(l,!1),t+="</div>",e(t)}),o}function ok(){if(!globalThis.VConsole)return;const o=new VConsole.VConsolePlugin("graphics-info","\u{1F3A8} Graphics Info");return o.on("renderTab",async function(e){let t=`<div style='${fg}'>`;const i=sk();i.length>0&&(t+=`<h3 style='${kr}'>General GPU Info</h3>`,t+=Hn(i,!1));const n=ak();n.length>0&&(t+=`<h3 style='${kr}'>WebGL</h3>`,t+=Hn(n,!1));const s=lk();s.length>0&&(t+=`<h3 style='${kr}'>WebGL 2 Features</h3>`,t+=Hn(s,!1));const r=ck();r.length>0&&(t+=`<h3 style='${kr}'>WebGL Limits</h3>`,t+=Hn(r,!1));const a=hk();a.length>0&&(t+=`<h3 style='${kr}'>Texture Formats</h3>`,t+=Hn(a,!1));const l=await dk();if(l.length>0&&(t+=`<h3 style='${kr}'>WebGPU</h3>`,t+=Hn(l,!1)),I.isSafari()){const c=uk();c.length>0&&(t+=`<h3 style='${kr}'>Safari GPU Info</h3>`,t+=Hn(c,!1))}t+="</div>",e(t)}),o}function sk(){const o=[],e=window.devicePixelRatio;o.push({label:"Device Pixel Ratio",value:e.toString()}),o.push({label:"Width (px)",value:(window.innerWidth*e).toString()}),o.push({label:"Height (px)",value:(window.innerHeight*e).toString()});const t=I.isMobileDevice()?150:96,i=screen.width/t,n=screen.height/t,s=i*2.54,r=n*2.54;o.push({label:"Estimated Width (cm)",value:s.toFixed(1)}),o.push({label:"Estimated Height (cm)",value:r.toFixed(1)});const a=B_();if(a){o.push({label:"GPU",value:a.renderer}),o.push({label:"Driver",value:a.vendor}),o.push({label:"ANGLE",value:a.angle||"Not detected"});const l=rk(a.renderer);l&&(l.manufacturer&&o.push({label:"Manufacturer",value:l.manufacturer}),l.cardVersion&&o.push({label:"Card Version",value:l.cardVersion}),l.brand&&o.push({label:"Brand",value:l.brand}),o.push({label:"Integrated",value:l.integrated?"Yes":"No"}),l.layer&&o.push({label:"WebGL Layer",value:l.layer}))}return o}function rk(o){if(!o)return null;const e=(l,c)=>{const h=c.match(l);return h&&h[0]},t=e(/(ANGLE)/g,o)||void 0,i=e(/((NVIDIA|AMD|Intel)[^\d]*[^\s]+)/,o)||o,n=i.split(" ");n.shift();const s=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:s,cardVersion:r,brand:a,integrated:s==="Intel",layer:t,card:i}}function ak(){const o=[],e=B_();return e&&(o.push({label:"\u{1F4CA} WebGL Version",value:e.version}),o.push({label:"\u{1F3AE} WebGL 2 Available",value:j_()})),o}function lk(){const o=[];try{const e=document.createElement("canvas").getContext("webgl2");if(!e)return o;o.push({label:"Float Color Buffer",value:e.getExtension("EXT_color_buffer_float")?"\u2705":"\u274C"}),o.push({label:"Anisotropic Filtering",value:e.getExtension("EXT_texture_filter_anisotropic")?"\u2705":"\u274C"}),o.push({label:"Float Texture Linear",value:e.getExtension("OES_texture_float_linear")?"\u2705":"\u274C"}),o.push({label:"S3TC Compression",value:e.getExtension("WEBGL_compressed_texture_s3tc")?"\u2705":"\u274C"}),o.push({label:"ETC Compression",value:e.getExtension("WEBGL_compressed_texture_etc")?"\u2705":"\u274C"}),o.push({label:"PVRTC Compression",value:e.getExtension("WEBGL_compressed_texture_pvrtc")?"\u2705":"\u274C"}),o.push({label:"ASTC Compression",value:e.getExtension("WEBGL_compressed_texture_astc")?"\u2705":"\u274C"})}catch{}return o}function ck(){const o=[];try{const e=document.createElement("canvas"),t=e.getContext("webgl2")||e.getContext("webgl");if(!t)return o;const i=t instanceof WebGL2RenderingContext;o.push({label:"\u{1F4CF} Max Texture Size",value:t.getParameter(t.MAX_TEXTURE_SIZE).toString()}),o.push({label:"\u{1F3A8} Max Renderbuffer Size",value:t.getParameter(t.MAX_RENDERBUFFER_SIZE).toString()}),o.push({label:"\u{1F517} Max Vertex Attribs",value:t.getParameter(t.MAX_VERTEX_ATTRIBS).toString()}),o.push({label:"\u{1F3AF} Max Texture Units",value:t.getParameter(t.MAX_TEXTURE_IMAGE_UNITS).toString()}),i&&(o.push({label:"\u26A1 Max Samples",value:t.getParameter(t.MAX_SAMPLES).toString()}),o.push({label:"\u{1F504} Max Uniform Buffer Bindings",value:t.getParameter(t.MAX_UNIFORM_BUFFER_BINDINGS).toString()}),o.push({label:"\u{1F4D0} Max 3D Texture Size",value:t.getParameter(t.MAX_3D_TEXTURE_SIZE).toString()}))}catch{}return o}function hk(){const o=[];try{document.createElement("canvas").getContext("webgl")&&(o.push({label:"WebGL 1 RGBA",value:"\u2705"}),o.push({label:"WebGL 1 RGB",value:"\u2705"}));const e=document.createElement("canvas").getContext("webgl2");e&&(o.push({label:"WebGL 2 RGBA32F",value:e.getExtension("EXT_color_buffer_float")?"\u2705":"\u274C"}),o.push({label:"WebGL 2 RGB32F",value:e.getExtension("EXT_color_buffer_float")?"\u2705":"\u274C"}),o.push({label:"WebGL 2 R11F_G11F_B10F",value:"\u2705"}),o.push({label:"WebGL 2 RGB565",value:"\u2705"}),o.push({label:"WebGL 2 RGB5_A1",value:"\u2705"}),o.push({label:"WebGL 2 RGBA4444",value:"\u2705"}))}catch{}return o}async function dk(){const o=[];if(!("gpu"in navigator))return o.push({label:"\u{1F680} WebGPU Support",value:"\u274C Not supported"}),o;o.push({label:"\u{1F680} WebGPU Support",value:"\u2705 Supported"});try{const e=await navigator.gpu.requestAdapter();if(!e)return o.push({label:"\u{1F3AF} Adapter",value:"No adapter available"}),o;o.push({label:"\u{1F3AF} Adapter",value:e.name||"Unknown Adapter"});const t=await e.requestDevice();o.push({label:"\u{1F527} Device",value:t.label||"WebGPU Device"}),o.push({label:"\u{1F4CF} Max Texture 2D",value:t.limits.maxTextureDimension2D.toString()}),o.push({label:"\u{1F4D0} Max Texture 3D",value:t.limits.maxTextureDimension3D.toString()}),o.push({label:"\u{1F4CA} Max Texture Array Layers",value:t.limits.maxTextureArrayLayers.toString()}),o.push({label:"\u{1F4BE} Max Buffer Size",value:`${(t.limits.maxBufferSize/1024/1024).toFixed(1)}MB`}),o.push({label:"\u{1F517} Max Bind Groups",value:t.limits.maxBindGroups.toString()})}catch(e){o.push({label:"\u274C Error",value:e.message})}return o}function B_(){try{const o=document.createElement("canvas"),e=o.getContext("webgl2")||o.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),s=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:s,angle:r}}catch{return null}}function uk(){const o=[];try{const e=document.createElement("canvas").getContext("webgl");if(e){const t=e.getExtension("WEBGL_debug_renderer_info");if(t){const i=e.getParameter(t.UNMASKED_RENDERER_WEBGL);i&&i.includes("Apple")&&o.push({label:"\u{1F34E} Apple GPU",value:i})}}}catch{}try{const e=document.createElement("canvas").getContext("webgl");e&&(e.getSupportedExtensions()||[]).includes("WEBGL_compressed_texture_pvrtc")&&o.push({label:"\u{1F5DC}\uFE0F PVRTC Support",value:"\u2705"})}catch{}return o}function pk(){return I.isQuest()?"Meta Quest":I.isVisionOS()?"Vision Pro":I.isiOS()?I.isiPad()?"iPad":"iPhone/iPod":I.isAndroidDevice()?"Android Device":I.isMozillaXR()?"Mozilla XR Browser":I.isNeedleAppClip()?"Needle App Clip":I.isMacOS()?"Mac":I.isDesktop()?"Desktop PC":"Unknown Device"}function mk(){return document.querySelector("#__vconsole .vc-switch")||null}function gk(){return document.querySelector("#__vconsole")||null}const F_=w("debugdefines");Ss('if(!globalThis["NEEDLE_ENGINE_VERSION"]) globalThis["NEEDLE_ENGINE_VERSION"] = "0.0.0";'),Ss('if(!globalThis["NEEDLE_ENGINE_GENERATOR"]) globalThis["NEEDLE_ENGINE_GENERATOR"] = "unknown";'),Ss('if(!globalThis["NEEDLE_PROJECT_BUILD_TIME"]) globalThis["NEEDLE_PROJECT_BUILD_TIME"] = "unknown";'),Ss('if(!globalThis["NEEDLE_PUBLIC_KEY"]) globalThis["NEEDLE_PUBLIC_KEY"] = "unknown";'),Ss('globalThis["__NEEDLE_ENGINE_VERSION__"] = "4.16.0";'),Ss('globalThis["__NEEDLE_ENGINE_GENERATOR__"] = "undefined";'),Ss('globalThis["__NEEDLE_PROJECT_BUILD_TIME__"] = "Fri Mar 06 2026 15:28:20 GMT+0000 (Coordinated Universal Time)";'),Ss('globalThis["__NEEDLE_PUBLIC_KEY__"] = "'+NEEDLE_PUBLIC_KEY+'";');const Ti="4.16.0",Wa="undefined",wc="Fri Mar 06 2026 15:28:20 GMT+0000 (Coordinated Universal Time)";F_&&console.log(`Engine version: ${Ti} (generator: ${Wa})
144
+ `,Or?.prepend(i),o===!0&&o_()<=0&&A_(),console.log("\u{1F335} Debug console has loaded")}},e.onerror=()=>{console.warn("\u{1F335} Debug console failed to load."+(window.crossOriginIsolated?"This page is using cross-origin isolation, so external scripts can't be loaded.":"")),vc=!1,hi=null},e.src="https://cdn.jsdelivr.net/npm/vconsole@3.15.1/dist/vconsole.min.js",document.body.appendChild(e)}function JO(){if(!globalThis.VConsole)return;const o=new VConsole.VConsolePlugin("needle-console","\u{1F335} Inspect glTF"),e=()=>document.querySelector("#__vc_plug_"+o._id+" iframe");return o.on("renderTab",function(t){const i=globalThis["needle:codegen_files"];if(!i||i.length===0)return;let n=globalThis["needle:codegen_files"][0];const s=n.indexOf("?");s>-1&&(n=n.substring(0,s));const r=location.protocol+"//"+location.host+location.pathname+"/"+n,a=encodeURIComponent(r);o.fullUrl="https://viewer.needle.tools?inspect&file="+a;var l='<iframe src="" style="width: 100%; height: 99%; border: none;"></iframe>';t(l)}),o.on("show",function(){const t=e();t&&t.src!==o.fullUrl&&(t.src=o.fullUrl)}),o.on("hide",function(){const t=e();t&&(t.src="")}),o.on("addTopBar",function(t){var i=new Array;i.push({name:"Open in new window \u2197",onClick:function(n){window.open(o.fullUrl,"_blank"),hi?.hide()}}),i.push({name:"Reload",onClick:function(n){const s=e();s&&(s.src=o.fullUrl)}}),i.push({name:"Fullscreen",onClick:function(n){const s=e();s.requestFullscreen?s.requestFullscreen():s.webkitRequestFullscreen instanceof Function&&s.webkitRequestFullscreen()}}),t(i)}),o}const fg="padding: 10px; font-family: monospace;",L_="margin-bottom: 10px;",kr="margin-bottom: 10px; margin-top: 15px;",ek="width: 100%; border-collapse: collapse; border: 1px solid rgba(0,0,0,0.1); table-layout: fixed;",D_="border: 1px solid rgba(0,0,0,0.1); padding: 5px;",tk=D_,ik=D_+" word-break: break-all;";function Hn(o,e=!1){e&&o.sort((i,n)=>(n.value?1:0)-(i.value?1:0));let t=`<table style='${ek}'>`;t+="<tbody>";for(const i of o){const n=typeof i.value=="boolean"?i.value?"\u2705":"\u274C":i.value;t+=`<tr><td style='${tk}'>${i.label}</td><td style='${ik}'>${n}</td></tr>`}return t+="</tbody></table>",t}function j_(){try{if(document.createElement("canvas").getContext("webgl2"))return"\u2705"}catch{}return"\u274C"}function nk(){if(!globalThis.VConsole)return;const o=new VConsole.VConsolePlugin("device-utilities","\u{1F4F1} Device Info");return o.on("renderTab",function(e){let t=`<div style='${fg}'>`;const i=pk();t+=`<h3 style='${L_}'>Device: ${i}</h3>`,t+=Hn([{label:"\u{1F4BB} Desktop",value:I.isDesktop()},{label:"\u{1F4F1} Mobile Device",value:I.isMobileDevice()},{label:"\u{1F34E} iOS",value:I.isiOS()},{label:"\u{1F4F1} iPad",value:I.isiPad()},{label:"\u{1F916} Android",value:I.isAndroidDevice()},{label:"\u{1F98A} Mozilla XR",value:I.isMozillaXR()},{label:"\u{1F335} Needle App Clip",value:I.isNeedleAppClip()},{label:"\u{1F34F} macOS",value:I.isMacOS()},{label:"\u{1F453} VisionOS",value:I.isVisionOS()},{label:"\u{1F9ED} Safari",value:I.isSafari()},{label:"\u{1F576}\uFE0F Meta Quest",value:I.isQuest()},{label:"\u{1F517} QuickLook AR Support",value:I.supportsQuickLookAR()}],!0);const n=[],s=I.getiOSVersion();s&&n.push({label:"\u{1F34E} iOS Version",value:s});const r=I.getChromeVersion();r&&n.push({label:"\u{1F310} Chrome Version",value:r});const a=I.getSafariVersion();a&&n.push({label:"\u{1F9ED} Safari Version",value:a}),n.length>0&&(t+=Hn(n,!1)),t+="</div>",t+=`<div style='${fg} margin-top: 20px;'>`,t+=`<h3 style='${L_}'>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?"\u2705":"\u274C"},{label:"WebGPU",value:"gpu"in navigator?"\u2705":"\u274C"},{label:"WebGL 2",value:j_()}];t+=Hn(l,!1),t+="</div>",e(t)}),o}function ok(){if(!globalThis.VConsole)return;const o=new VConsole.VConsolePlugin("graphics-info","\u{1F3A8} Graphics Info");return o.on("renderTab",async function(e){let t=`<div style='${fg}'>`;const i=sk();i.length>0&&(t+=`<h3 style='${kr}'>General GPU Info</h3>`,t+=Hn(i,!1));const n=ak();n.length>0&&(t+=`<h3 style='${kr}'>WebGL</h3>`,t+=Hn(n,!1));const s=lk();s.length>0&&(t+=`<h3 style='${kr}'>WebGL 2 Features</h3>`,t+=Hn(s,!1));const r=ck();r.length>0&&(t+=`<h3 style='${kr}'>WebGL Limits</h3>`,t+=Hn(r,!1));const a=hk();a.length>0&&(t+=`<h3 style='${kr}'>Texture Formats</h3>`,t+=Hn(a,!1));const l=await dk();if(l.length>0&&(t+=`<h3 style='${kr}'>WebGPU</h3>`,t+=Hn(l,!1)),I.isSafari()){const c=uk();c.length>0&&(t+=`<h3 style='${kr}'>Safari GPU Info</h3>`,t+=Hn(c,!1))}t+="</div>",e(t)}),o}function sk(){const o=[],e=window.devicePixelRatio;o.push({label:"Device Pixel Ratio",value:e.toString()}),o.push({label:"Width (px)",value:(window.innerWidth*e).toString()}),o.push({label:"Height (px)",value:(window.innerHeight*e).toString()});const t=I.isMobileDevice()?150:96,i=screen.width/t,n=screen.height/t,s=i*2.54,r=n*2.54;o.push({label:"Estimated Width (cm)",value:s.toFixed(1)}),o.push({label:"Estimated Height (cm)",value:r.toFixed(1)});const a=B_();if(a){o.push({label:"GPU",value:a.renderer}),o.push({label:"Driver",value:a.vendor}),o.push({label:"ANGLE",value:a.angle||"Not detected"});const l=rk(a.renderer);l&&(l.manufacturer&&o.push({label:"Manufacturer",value:l.manufacturer}),l.cardVersion&&o.push({label:"Card Version",value:l.cardVersion}),l.brand&&o.push({label:"Brand",value:l.brand}),o.push({label:"Integrated",value:l.integrated?"Yes":"No"}),l.layer&&o.push({label:"WebGL Layer",value:l.layer}))}return o}function rk(o){if(!o)return null;const e=(l,c)=>{const h=c.match(l);return h&&h[0]},t=e(/(ANGLE)/g,o)||void 0,i=e(/((NVIDIA|AMD|Intel)[^\d]*[^\s]+)/,o)||o,n=i.split(" ");n.shift();const s=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:s,cardVersion:r,brand:a,integrated:s==="Intel",layer:t,card:i}}function ak(){const o=[],e=B_();return e&&(o.push({label:"\u{1F4CA} WebGL Version",value:e.version}),o.push({label:"\u{1F3AE} WebGL 2 Available",value:j_()})),o}function lk(){const o=[];try{const e=document.createElement("canvas").getContext("webgl2");if(!e)return o;o.push({label:"Float Color Buffer",value:e.getExtension("EXT_color_buffer_float")?"\u2705":"\u274C"}),o.push({label:"Anisotropic Filtering",value:e.getExtension("EXT_texture_filter_anisotropic")?"\u2705":"\u274C"}),o.push({label:"Float Texture Linear",value:e.getExtension("OES_texture_float_linear")?"\u2705":"\u274C"}),o.push({label:"S3TC Compression",value:e.getExtension("WEBGL_compressed_texture_s3tc")?"\u2705":"\u274C"}),o.push({label:"ETC Compression",value:e.getExtension("WEBGL_compressed_texture_etc")?"\u2705":"\u274C"}),o.push({label:"PVRTC Compression",value:e.getExtension("WEBGL_compressed_texture_pvrtc")?"\u2705":"\u274C"}),o.push({label:"ASTC Compression",value:e.getExtension("WEBGL_compressed_texture_astc")?"\u2705":"\u274C"})}catch{}return o}function ck(){const o=[];try{const e=document.createElement("canvas"),t=e.getContext("webgl2")||e.getContext("webgl");if(!t)return o;const i=t instanceof WebGL2RenderingContext;o.push({label:"\u{1F4CF} Max Texture Size",value:t.getParameter(t.MAX_TEXTURE_SIZE).toString()}),o.push({label:"\u{1F3A8} Max Renderbuffer Size",value:t.getParameter(t.MAX_RENDERBUFFER_SIZE).toString()}),o.push({label:"\u{1F517} Max Vertex Attribs",value:t.getParameter(t.MAX_VERTEX_ATTRIBS).toString()}),o.push({label:"\u{1F3AF} Max Texture Units",value:t.getParameter(t.MAX_TEXTURE_IMAGE_UNITS).toString()}),i&&(o.push({label:"\u26A1 Max Samples",value:t.getParameter(t.MAX_SAMPLES).toString()}),o.push({label:"\u{1F504} Max Uniform Buffer Bindings",value:t.getParameter(t.MAX_UNIFORM_BUFFER_BINDINGS).toString()}),o.push({label:"\u{1F4D0} Max 3D Texture Size",value:t.getParameter(t.MAX_3D_TEXTURE_SIZE).toString()}))}catch{}return o}function hk(){const o=[];try{document.createElement("canvas").getContext("webgl")&&(o.push({label:"WebGL 1 RGBA",value:"\u2705"}),o.push({label:"WebGL 1 RGB",value:"\u2705"}));const e=document.createElement("canvas").getContext("webgl2");e&&(o.push({label:"WebGL 2 RGBA32F",value:e.getExtension("EXT_color_buffer_float")?"\u2705":"\u274C"}),o.push({label:"WebGL 2 RGB32F",value:e.getExtension("EXT_color_buffer_float")?"\u2705":"\u274C"}),o.push({label:"WebGL 2 R11F_G11F_B10F",value:"\u2705"}),o.push({label:"WebGL 2 RGB565",value:"\u2705"}),o.push({label:"WebGL 2 RGB5_A1",value:"\u2705"}),o.push({label:"WebGL 2 RGBA4444",value:"\u2705"}))}catch{}return o}async function dk(){const o=[];if(!("gpu"in navigator))return o.push({label:"\u{1F680} WebGPU Support",value:"\u274C Not supported"}),o;o.push({label:"\u{1F680} WebGPU Support",value:"\u2705 Supported"});try{const e=await navigator.gpu.requestAdapter();if(!e)return o.push({label:"\u{1F3AF} Adapter",value:"No adapter available"}),o;o.push({label:"\u{1F3AF} Adapter",value:e.name||"Unknown Adapter"});const t=await e.requestDevice();o.push({label:"\u{1F527} Device",value:t.label||"WebGPU Device"}),o.push({label:"\u{1F4CF} Max Texture 2D",value:t.limits.maxTextureDimension2D.toString()}),o.push({label:"\u{1F4D0} Max Texture 3D",value:t.limits.maxTextureDimension3D.toString()}),o.push({label:"\u{1F4CA} Max Texture Array Layers",value:t.limits.maxTextureArrayLayers.toString()}),o.push({label:"\u{1F4BE} Max Buffer Size",value:`${(t.limits.maxBufferSize/1024/1024).toFixed(1)}MB`}),o.push({label:"\u{1F517} Max Bind Groups",value:t.limits.maxBindGroups.toString()})}catch(e){o.push({label:"\u274C Error",value:e.message})}return o}function B_(){try{const o=document.createElement("canvas"),e=o.getContext("webgl2")||o.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),s=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:s,angle:r}}catch{return null}}function uk(){const o=[];try{const e=document.createElement("canvas").getContext("webgl");if(e){const t=e.getExtension("WEBGL_debug_renderer_info");if(t){const i=e.getParameter(t.UNMASKED_RENDERER_WEBGL);i&&i.includes("Apple")&&o.push({label:"\u{1F34E} Apple GPU",value:i})}}}catch{}try{const e=document.createElement("canvas").getContext("webgl");e&&(e.getSupportedExtensions()||[]).includes("WEBGL_compressed_texture_pvrtc")&&o.push({label:"\u{1F5DC}\uFE0F PVRTC Support",value:"\u2705"})}catch{}return o}function pk(){return I.isQuest()?"Meta Quest":I.isVisionOS()?"Vision Pro":I.isiOS()?I.isiPad()?"iPad":"iPhone/iPod":I.isAndroidDevice()?"Android Device":I.isMozillaXR()?"Mozilla XR Browser":I.isNeedleAppClip()?"Needle App Clip":I.isMacOS()?"Mac":I.isDesktop()?"Desktop PC":"Unknown Device"}function mk(){return document.querySelector("#__vconsole .vc-switch")||null}function gk(){return document.querySelector("#__vconsole")||null}const F_=w("debugdefines");Ss('if(!globalThis["NEEDLE_ENGINE_VERSION"]) globalThis["NEEDLE_ENGINE_VERSION"] = "0.0.0";'),Ss('if(!globalThis["NEEDLE_ENGINE_GENERATOR"]) globalThis["NEEDLE_ENGINE_GENERATOR"] = "unknown";'),Ss('if(!globalThis["NEEDLE_PROJECT_BUILD_TIME"]) globalThis["NEEDLE_PROJECT_BUILD_TIME"] = "unknown";'),Ss('if(!globalThis["NEEDLE_PUBLIC_KEY"]) globalThis["NEEDLE_PUBLIC_KEY"] = "unknown";'),Ss('globalThis["__NEEDLE_ENGINE_VERSION__"] = "4.16.1";'),Ss('globalThis["__NEEDLE_ENGINE_GENERATOR__"] = "undefined";'),Ss('globalThis["__NEEDLE_PROJECT_BUILD_TIME__"] = "Mon Mar 09 2026 14:22:17 GMT+0000 (Coordinated Universal Time)";'),Ss('globalThis["__NEEDLE_PUBLIC_KEY__"] = "'+NEEDLE_PUBLIC_KEY+'";');const Ti="4.16.1",Wa="undefined",wc="Mon Mar 09 2026 14:22:17 GMT+0000 (Coordinated Universal Time)";F_&&console.log(`Engine version: ${Ti} (generator: ${Wa})
145
145
  Project built at ${wc}`);const xs=NEEDLE_PUBLIC_KEY,Ao="needle_isActiveInHierarchy",Mr="builtin_components",xc="needle_editor_guid";function Ss(o){try{(0,eval)(o)}catch(e){F_&&console.error(e)}}let U_,z_=null;function Cn(){return U_}function yg(o){if(o==null){console.warn("Oh no: someone tried registering a non-existend gltf-loader. When you see this log it might mean that needle-engine is being imported multiple times. Please check your project setup.");return}z_!==o&&(z_=o,U_=new o)}function fk(o,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>o.time.frame)return window.requestAnimationFrame(()=>i());const r=s.captureCanvas(e);r&&r instanceof Promise?r.then(()=>s.displayUI()):s.displayUI()};const n=Number.parseInt(t.get("spector")||"0")||0;console.log("Scheduled Spector capture at frame #"+n);const s=new window.SPECTOR.Spector;s.spyCanvases=!0,i();return}else A()&&console.debug("Spector available: Add '?spector=<frame>' to the URL to enable it and capture a frame.")}}function N_(o){const e=o;return!!(e.parser&&e.parser.json)}var Gd=(o=>(o[o.None=0]="None",o[o.DontExport=1]="DontExport",o))(Gd||{});const W_=Symbol("component-name");function bg(o){return o&&o.isComponent}const yk=Symbol("object"),_g=new Mi(()=>new b,20);class V_{_point;_normal;_tangentVelocity;distance;impulse;friction;get point(){return _g.get().set(this._point.x,this._point.y,this._point.z)}get normal(){return _g.get().set(this._normal.x,this._normal.y,this._normal.z)}get tangentVelocity(){return _g.get().set(this._tangentVelocity.x,this._tangentVelocity.y,this._tangentVelocity.z)}constructor(e,t,i,n,s,r){this._point=e,this.distance=t,this._normal=i,this.impulse=n,this.friction=s,this._tangentVelocity=r}}class $_{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 H_{object;collider;constructor(e,t){this.object=e,this.collider=t}}class wm{constructor(e){this.context=e,this.root.style.cssText=`
146
146
  position: absolute;
147
147
  width: 1px; height: 1px;
@@ -800,11 +800,11 @@ vec3 AgXToneMapping( vec3 color ) {
800
800
  <div class="expanded-click-area"></div>
801
801
  </button>
802
802
  </div>
803
- `;const t=this.attachShadow({mode:"open"});Uw(),Ou(xf,{loadedCallback:()=>{this.handleSizeChange()}}),Ou(xf,{element:t});const i=e.content.cloneNode(!0);t?.appendChild(i),this.root=t.querySelector("#root"),this.wrapper=this.root?.querySelector(".wrapper"),this.options=this.root?.querySelector(".options.main-container"),this.optionsCompactMode=this.root?.querySelector(".options.compact-only"),this.logoContainer=this.root?.querySelector(".logo"),this.compactMenuButton=this.root?.querySelector(".compact-menu-button"),this.compactMenuButton.append(Ot("more_vert")),this.foldout=this.root?.querySelector(".foldout"),this.root?.appendChild(this.wrapper),this.wrapper.classList.add("wrapper");const n=zw.create();n.setType("compact"),n.style.minHeight="1rem",this.logoContainer.append(n),this.logoContainer.addEventListener("click",()=>{globalThis.open("https://needle.tools","_blank")});try{window.requestAnimationFrame(()=>xE(c=>{if(c==!0&&Zn()&&!Ww){let h=this._userRequestedLogoVisible;h===void 0&&(h=!1),this.___onSetLogoVisible(h)}else this.___onSetLogoVisible(!0)}))}catch(c){console.error("[Needle Menu] License check failed.",c)}this.compactMenuButton.addEventListener("click",c=>{c.preventDefault(),this.root.classList.toggle("open")});let s=this._context;setTimeout(()=>s=this._context);let r=0;const a=(c,h)=>{ll&&console.log("Set menu visible",h),s?.isInAR&&s.arOverlayElement?c!=s.arOverlayElement&&s.arOverlayElement.appendChild(this):this.parentNode!=this._domElement?.shadowRoot&&this._domElement?.shadowRoot?.appendChild(this),this.style.display=h?"flex":"none",this.style.visibility="visible",this.style.opacity="1"};let l=!1;new MutationObserver(c=>{if(!l)try{l=!0,this.onChangeDetected(c);const h=this?.parentNode;if((this.style.display!="flex"||this.style.visibility!="visible"||this.style.opacity!="1"||h!=this._domElement?.shadowRoot)&&!Zn()){const d=r++;ki()&&this._userRequestedMenuVisible===!1?(d===0&&a(h,this._userRequestedMenuVisible),d===1&&console.warn("Needle Menu Warning: You need a PRO license to hide the Needle Engine menu \u2192 The menu will be visible in your deployed website if you don't have a PRO license. See https://needle.tools/pricing for details.")):d===0?a(h,!0):setTimeout(()=>a(h,!0),5)}}finally{l=!1}}).observe(this.root,{childList:!0,subtree:!0,attributes:!0}),ll&&this.___insertDebugOptions()}ensureInitialized(){this._didInitialize||(this._didInitialize=!0,this.initializeDom())}_sizeChangeInterval;connectedCallback(){this.ensureInitialized(),window.addEventListener("resize",this.handleSizeChange),this.handleMenuVisible(),this._sizeChangeInterval=setInterval(()=>this.handleSizeChange(void 0,!1),5e3),setTimeout(()=>{this._domElement?.addEventListener("resize",this.handleSizeChange),this._domElement?.addEventListener("click",this.#t)},1)}disconnectedCallback(){window.removeEventListener("resize",this.handleSizeChange),clearInterval(this._sizeChangeInterval),this._domElement?.removeEventListener("resize",this.handleSizeChange),this._context?.domElement.removeEventListener("click",this.#t)}#t=e=>{if(!e.defaultPrevented&&e.target==this._domElement&&e instanceof PointerEvent&&e.button===0&&this.root.classList.contains("open")){const t=this.foldout.getBoundingClientRect(),i=e;i.clientX>t.left&&i.clientX<t.right&&i.clientY>t.top&&i.clientY<t.bottom||this.root.classList.toggle("open",!1)}};_userRequestedLogoVisible=void 0;showNeedleLogo(e){this._userRequestedLogoVisible=e,!(!e&&(!Zn()||Ww)&&(console.warn("[Needle Engine] You need a PRO license to hide the Needle Engine logo in production."),!ki()))&&this.___onSetLogoVisible(e)}get logoIsVisible(){return!this.root.classList.contains("logo-hidden")}___onSetLogoVisible(e){this.logoContainer.style.display="",this.logoContainer.style.opacity="1",this.logoContainer.style.visibility="visible",e?(this.root.classList.remove("logo-hidden"),this.root.classList.add("logo-visible")):(this.root.classList.remove("logo-visible"),this.root.classList.add("logo-hidden"))}setPosition(e){if(e!=="top"&&e!=="bottom")return console.error("NeedleMenu.setPosition: invalid position",e);this.root.classList.remove("top","bottom"),this.root.classList.add(e)}_userRequestedMenuVisible=void 0;setVisible(e){this._userRequestedMenuVisible=e,this.style.display=e?"flex":"none"}closeFoldout(){this.root.classList.remove("open")}root;wrapper;options;optionsCompactMode;logoContainer;compactMenuButton;foldout;trackedElements=new WeakSet;trackElement(e){this.trackedElements.has(e)||(this.trackedElements.add(e),e.addEventListener("click",t=>{pi.sendEvent(this._context,"needle-menu",{action:"button_clicked",element:t.target instanceof Node?t.target.nodeName:e.nodeName,label:e.textContent,title:e instanceof HTMLElement?e.title:void 0,pointerid:t instanceof PointerEvent?t.pointerId:void 0})}))}append(...e){for(const t of e)if(typeof t=="string"){const i=document.createTextNode(t);this.trackElement(i),this.options.appendChild(i)}else this.trackElement(t),this.options.appendChild(t)}appendChild(e){if(!(e instanceof Node)){const t=document.createElement("button");if(t.textContent=e.label,t.onclick=e.onClick,t.setAttribute("priority",e.priority?.toString()??"0"),e.title&&(t.title=e.title),e.icon){const i=Ot(e.icon);e.iconSide==="right"?t.appendChild(i):t.prepend(i)}e.class&&t.classList.add(e.class),e=t}return this.trackElement(e),this.options.appendChild(e)}prepend(...e){for(const t of e)if(typeof t=="string"){const i=document.createTextNode(t);this.trackElement(i),this.options.prepend(i)}else this.trackElement(t),this.options.prepend(t)}_isHandlingChange=!1;_pauseMutationObserverOptionsContainer=!1;onChangeDetected(e){if(!this._isHandlingChange){this._isHandlingChange=!0;try{this.handleMenuVisible();for(const t of e)t.target==this.options&&(this._pauseMutationObserverOptionsContainer||this.onOptionsChildrenChanged(t))}finally{this._isHandlingChange=!1}}}onOptionsChildrenChanged(e){if(this.root.classList.toggle("has-options",this.hasAnyVisibleOptions),this.root.classList.toggle("has-no-options",!this.hasAnyVisibleOptions),this.handleSizeChange(void 0,!0),e.type==="childList"&&e.addedNodes.length>0){const t=Array.from(this.options.children);t.sort((n,s)=>{const r=parseInt(n.getAttribute("priority")||"0"),a=parseInt(s.getAttribute("priority")||"0");return r-a});let i=!1;for(let n=0;n<t.length;n++){const s=this.options.children[n],r=t[n];if(s!==r){i=!0;break}}if(i)for(const n of t)this.options.appendChild(n)}}_didSort=new Map;handleMenuVisible(){ll&&console.log("Update VisibleState: Any Content?",this.hasAnyContent),this.hasAnyContent?this.root.style.display="":this.root.style.display="none",this.root.classList.toggle("has-options",this.hasAnyVisibleOptions),this.root.classList.toggle("has-no-options",!this.hasAnyVisibleOptions)}get hasAnyContent(){return!!(this.logoContainer.style.display!="none"||this.hasAnyVisibleOptions)}get hasAnyVisibleOptions(){for(let e=0;e<this.options.children.length;e++){const t=this.options.children[e];if(t.tagName==="SLOT"){const i=t.assignedNodes();for(const n of i)if(n instanceof HTMLElement&&n.style.display!="none")return!0}else if(t.style.display!="none")return!0}return!1}_lastAvailableWidthChange=0;_timeoutHandleSize=0;_timeoutHandleCompactItems=0;handleSizeChange=(e,t)=>{if(!this._domElement)return;const i=this._domElement.clientWidth;if(i<100){clearTimeout(this._timeoutHandleSize),this.root.classList.add("compact"),this.foldout.classList.add("floating-panel-style");return}const n=i-20;if(!t&&Math.abs(n-this._lastAvailableWidthChange)<1)return;this._lastAvailableWidthChange=n,clearTimeout(this._timeoutHandleSize),this._timeoutHandleSize=setTimeout(()=>{const l=a();l<0?(this.root.classList.add("compact"),this.foldout.classList.add("floating-panel-style")):l>0&&(this.root.classList.remove("compact"),this.foldout.classList.remove("floating-panel-style"),a()<0&&(this.root.classList.add("compact"),this.foldout.classList.add("floating-panel-style"))),this._pauseMutationObserverOptionsContainer=!0,this.updateCompactFoldoutItem(),window.requestAnimationFrame(()=>this._pauseMutationObserverOptionsContainer=!1)},150);const s=()=>{let l=0;return l+=this.options.getBoundingClientRect().width,l+=this.optionsCompactMode.getBoundingClientRect().width,l+=10*this.options.childElementCount,l+=this.logoContainer.style.display!="none"?this.logoContainer.getBoundingClientRect().width:0,l};let r=-1;const a=()=>{const l=n-s();return ll&&l!==r&&(r=l,Oe(`Menu space left: ${l.toFixed(0)}px`)),l}};updateCompactFoldoutItem(){if(this.root.classList.contains("compact")){let e=null,t=-1e7;const i=n=>{if(n instanceof HTMLElement){const s=Ms.getElementPriority(n);if(s!==void 0&&s>=t){const r=window.getComputedStyle(n);if(r.display==="none"||r.visibility==="hidden"||r.opacity==="0")return;e=n,t=s}}};for(let n=0;n<this.options.children.length;n++)i(this.options.children.item(n));for(let n=0;n<this.optionsCompactMode.children.length;n++)i(this.optionsCompactMode.children.item(n));if(e&&!this.optionsCompactMode.contains(e)){this.optionsCompactMode.childNodes.forEach(s=>{this.options.appendChild(s)});const n=e;this.optionsCompactMode.appendChild(n)}else e||this.optionsCompactMode.childNodes.forEach(n=>{this.options.appendChild(n)})}else this.optionsCompactMode.childNodes.forEach(e=>{this.options.appendChild(e)})}___insertDebugOptions(){window.addEventListener("keydown",i=>{i.key==="p"&&this.setPosition(this.root.classList.contains("top")?"bottom":"top")});const e=document.createElement("button");e.textContent="Hide Buttons",e.onclick=()=>{const i=new Array(this.options.children.length);for(let n=0;n<this.options.children.length;n++)i[n]=this.options.children[n];for(const n of i)this.options.removeChild(n);setTimeout(()=>{for(const n of i)this.options.appendChild(n)},1e3)},this.appendChild(e);const t=document.createElement("button");t.textContent="Toggle Logo",t.addEventListener("click",()=>{this.logoContainer.style.display=this.logoContainer.style.display==="none"?"":"none"}),this.appendChild(t)}}customElements.get(al)||customElements.define(al,xm);const Je=w("debugcontext"),uE=w("stats"),pE=w("debugactive"),mE=w("debugframerate"),gE=w("debugcoroutine"),fE={};class yE{name;alias;hash;runInBackground;domElement;renderer;camera;scene}var xe=(o=>(o[o.Start=-1]="Start",o[o.EarlyUpdate=0]="EarlyUpdate",o[o.Update=1]="Update",o[o.LateUpdate=2]="LateUpdate",o[o.OnBeforeRender=3]="OnBeforeRender",o[o.OnAfterRender=4]="OnAfterRender",o[o.PrePhysicsStep=9]="PrePhysicsStep",o[o.PostPhysicsStep=10]="PostPhysicsStep",o[o.Undefined=-1]="Undefined",o))(xe||{});function Mu(o,e){if(!o)return;if(!o.isComponent){(A()||Je)&&console.error(`Registered script is not a Needle Engine component.
803
+ `;const t=this.attachShadow({mode:"open"});Uw(),Ou(xf,{loadedCallback:()=>{this.handleSizeChange()}}),Ou(xf,{element:t});const i=e.content.cloneNode(!0);t?.appendChild(i),this.root=t.querySelector("#root"),this.wrapper=this.root?.querySelector(".wrapper"),this.options=this.root?.querySelector(".options.main-container"),this.optionsCompactMode=this.root?.querySelector(".options.compact-only"),this.logoContainer=this.root?.querySelector(".logo"),this.compactMenuButton=this.root?.querySelector(".compact-menu-button"),this.compactMenuButton.append(Ot("more_vert")),this.foldout=this.root?.querySelector(".foldout"),this.root?.appendChild(this.wrapper),this.wrapper.classList.add("wrapper");const n=zw.create();n.setType("compact"),n.style.minHeight="1rem",this.logoContainer.append(n),this.logoContainer.addEventListener("click",()=>{globalThis.open("https://needle.tools","_blank")});try{window.requestAnimationFrame(()=>xE(c=>{if(c==!0&&Zn()&&!Ww){let h=this._userRequestedLogoVisible;h===void 0&&(h=!1),this.___onSetLogoVisible(h)}else this.___onSetLogoVisible(!0)}))}catch(c){console.error("[Needle Menu] License check failed.",c)}this.compactMenuButton.addEventListener("click",c=>{c.preventDefault(),this.root.classList.toggle("open")});let s=this._context;setTimeout(()=>s=this._context);let r=0;const a=(c,h)=>{ll&&console.log("Set menu visible",h),s?.isInAR&&s.arOverlayElement?c!=s.arOverlayElement&&s.arOverlayElement.appendChild(this):this.parentNode!=this._domElement?.shadowRoot&&this._domElement?.shadowRoot?.appendChild(this),this.style.display=h?"flex":"none",this.style.visibility="visible",this.style.opacity="1"};let l=!1;new MutationObserver(c=>{if(!l)try{l=!0,this.onChangeDetected(c);const h=this?.parentNode;if((this.style.display!="flex"||this.style.visibility!="visible"||this.style.opacity!="1"||h!=this._domElement?.shadowRoot)&&!Zn()){const d=r++;ki()&&this._userRequestedMenuVisible===!1?(d===0&&a(h,this._userRequestedMenuVisible),d===1&&console.warn("Needle Menu Warning: You need a PRO license to hide the Needle Engine menu \u2192 The menu will be visible in your deployed website if you don't have a PRO license. See https://needle.tools/pricing for details.")):d===0?a(h,!0):setTimeout(()=>a(h,!0),5)}}finally{l=!1}}).observe(this.root,{childList:!0,subtree:!0,attributes:!0}),ll&&this.___insertDebugOptions()}ensureInitialized(){this._didInitialize||(this._didInitialize=!0,this.initializeDom())}_sizeChangeInterval;connectedCallback(){this.ensureInitialized(),window.addEventListener("resize",this.handleSizeChange),this.handleMenuVisible(),this._sizeChangeInterval=setInterval(()=>this.handleSizeChange(void 0,!1),5e3),setTimeout(()=>{this._domElement?.addEventListener("resize",this.handleSizeChange),this._domElement?.addEventListener("click",this.#t)},1)}disconnectedCallback(){window.removeEventListener("resize",this.handleSizeChange),clearInterval(this._sizeChangeInterval),this._domElement?.removeEventListener("resize",this.handleSizeChange),this._context?.domElement.removeEventListener("click",this.#t)}#t=e=>{if(!e.defaultPrevented&&e.target==this._domElement&&e instanceof PointerEvent&&e.button===0&&this.root.classList.contains("open")){const t=this.foldout.getBoundingClientRect(),i=e;i.clientX>t.left&&i.clientX<t.right&&i.clientY>t.top&&i.clientY<t.bottom||this.root.classList.toggle("open",!1)}};_userRequestedLogoVisible=void 0;showNeedleLogo(e){this._userRequestedLogoVisible=e,!(!e&&(!Zn()||Ww)&&(console.warn("[Needle Engine] You need a PRO license to hide the Needle Engine logo in production."),!ki()))&&this.___onSetLogoVisible(e)}get logoIsVisible(){return!this.root.classList.contains("logo-hidden")}___onSetLogoVisible(e){this.logoContainer.style.display="",this.logoContainer.style.opacity="1",this.logoContainer.style.visibility="visible",e?(this.root.classList.remove("logo-hidden"),this.root.classList.add("logo-visible")):(this.root.classList.remove("logo-visible"),this.root.classList.add("logo-hidden"))}setPosition(e){if(e!=="top"&&e!=="bottom")return console.error("NeedleMenu.setPosition: invalid position",e);this.root.classList.remove("top","bottom"),this.root.classList.add(e)}_userRequestedMenuVisible=void 0;setVisible(e){this._userRequestedMenuVisible=e,this.style.display=e?"flex":"none"}closeFoldout(){this.root.classList.remove("open")}root;wrapper;options;optionsCompactMode;logoContainer;compactMenuButton;foldout;trackedElements=new WeakSet;trackElement(e){this.trackedElements.has(e)||(this.trackedElements.add(e),e.addEventListener("click",t=>{pi.sendEvent(this._context,"needle-menu",{action:"button_clicked",element:t.target instanceof Node?t.target.nodeName:e.nodeName,label:e.textContent,title:e instanceof HTMLElement?e.title:void 0,pointerid:t instanceof PointerEvent?t.pointerId:void 0})}))}append(...e){for(const t of e)if(typeof t=="string"){const i=document.createTextNode(t);this.trackElement(i),this.options.appendChild(i)}else this.trackElement(t),this.options.appendChild(t)}appendChild(e){if(!(e instanceof Node)){const t=document.createElement("button");if(t.textContent=e.label,t.onclick=e.onClick,t.setAttribute("priority",e.priority?.toString()??"0"),e.title&&(t.title=e.title),e.icon){const i=Ot(e.icon);e.iconSide==="right"?t.appendChild(i):t.prepend(i)}e.class&&t.classList.add(e.class),e=t}return this.trackElement(e),this.options.appendChild(e)}prepend(...e){for(const t of e)if(typeof t=="string"){const i=document.createTextNode(t);this.trackElement(i),this.options.prepend(i)}else this.trackElement(t),this.options.prepend(t)}_isHandlingChange=!1;_pauseMutationObserverOptionsContainer=!1;onChangeDetected(e){if(!this._isHandlingChange){this._isHandlingChange=!0;try{this.handleMenuVisible();for(const t of e)t.target==this.options&&(this._pauseMutationObserverOptionsContainer||this.onOptionsChildrenChanged(t))}finally{this._isHandlingChange=!1}}}onOptionsChildrenChanged(e){if(this.root.classList.toggle("has-options",this.hasAnyVisibleOptions),this.root.classList.toggle("has-no-options",!this.hasAnyVisibleOptions),this.handleSizeChange(void 0,!0),e.type==="childList"&&e.addedNodes.length>0){const t=Array.from(this.options.children);t.sort((n,s)=>{const r=parseInt(n.getAttribute("priority")||"0"),a=parseInt(s.getAttribute("priority")||"0");return r-a});let i=!1;for(let n=0;n<t.length;n++){const s=this.options.children[n],r=t[n];if(s!==r){i=!0;break}}if(i)for(const n of t)this.options.appendChild(n)}}_didSort=new Map;handleMenuVisible(){ll&&console.log("Update VisibleState: Any Content?",this.hasAnyContent),this.hasAnyContent?this.root.style.display="":this.root.style.display="none",this.root.classList.toggle("has-options",this.hasAnyVisibleOptions),this.root.classList.toggle("has-no-options",!this.hasAnyVisibleOptions)}get hasAnyContent(){return!!(this.logoContainer.style.display!="none"||this.hasAnyVisibleOptions)}get hasAnyVisibleOptions(){for(let e=0;e<this.options.children.length;e++){const t=this.options.children[e];if(t.tagName==="SLOT"){const i=t.assignedNodes();for(const n of i)if(n instanceof HTMLElement&&n.style.display!="none")return!0}else if(t.style.display!="none")return!0}return!1}_lastAvailableWidthChange=0;_timeoutHandleSize=0;_timeoutHandleCompactItems=0;handleSizeChange=(e,t)=>{if(!this._domElement)return;const i=this._domElement.clientWidth;if(i<100){clearTimeout(this._timeoutHandleSize),this.root.classList.add("compact"),this.foldout.classList.add("floating-panel-style");return}const n=i-20;if(!t&&Math.abs(n-this._lastAvailableWidthChange)<1)return;this._lastAvailableWidthChange=n,clearTimeout(this._timeoutHandleSize),this._timeoutHandleSize=setTimeout(()=>{const l=a();l<0?(this.root.classList.add("compact"),this.foldout.classList.add("floating-panel-style")):l>0&&(this.root.classList.remove("compact"),this.foldout.classList.remove("floating-panel-style"),a()<0&&(this.root.classList.add("compact"),this.foldout.classList.add("floating-panel-style"))),this._pauseMutationObserverOptionsContainer=!0,this.updateCompactFoldoutItem(),window.requestAnimationFrame(()=>this._pauseMutationObserverOptionsContainer=!1)},150);const s=()=>{let l=0;return l+=this.options.getBoundingClientRect().width,l+=this.optionsCompactMode.getBoundingClientRect().width,l+=10*this.options.childElementCount,l+=this.logoContainer.style.display!="none"?this.logoContainer.getBoundingClientRect().width:0,l};let r=-1;const a=()=>{const l=n-s();return ll&&l!==r&&(r=l,Oe(`Menu space left: ${l.toFixed(0)}px`)),l}};updateCompactFoldoutItem(){if(this.root.classList.contains("compact")){let e=null,t=-1e7;const i=n=>{if(n instanceof HTMLElement){const s=Ms.getElementPriority(n);if(s!==void 0&&s>=t){const r=window.getComputedStyle(n);if(r.display==="none"||r.visibility==="hidden"||r.opacity==="0")return;e=n,t=s}}};for(let n=0;n<this.options.children.length;n++)i(this.options.children.item(n));for(let n=0;n<this.optionsCompactMode.children.length;n++)i(this.optionsCompactMode.children.item(n));if(e&&!this.optionsCompactMode.contains(e)){this.optionsCompactMode.childNodes.forEach(s=>{this.options.appendChild(s)});const n=e;this.optionsCompactMode.appendChild(n)}else e||this.optionsCompactMode.childNodes.forEach(n=>{this.options.appendChild(n)})}else this.optionsCompactMode.childNodes.forEach(e=>{this.options.appendChild(e)})}___insertDebugOptions(){window.addEventListener("keydown",i=>{i.key==="p"&&this.setPosition(this.root.classList.contains("top")?"bottom":"top")});const e=document.createElement("button");e.textContent="Hide Buttons",e.onclick=()=>{const i=new Array(this.options.children.length);for(let n=0;n<this.options.children.length;n++)i[n]=this.options.children[n];for(const n of i)this.options.removeChild(n);setTimeout(()=>{for(const n of i)this.options.appendChild(n)},1e3)},this.appendChild(e);const t=document.createElement("button");t.textContent="Toggle Logo",t.addEventListener("click",()=>{this.logoContainer.style.display=this.logoContainer.style.display==="none"?"":"none"}),this.appendChild(t)}}customElements.get(al)||customElements.define(al,xm);const Qe=w("debugcontext"),uE=w("stats"),pE=w("debugactive"),mE=w("debugframerate"),gE=w("debugcoroutine"),fE={};class yE{name;alias;hash;runInBackground;domElement;renderer;camera;scene}var xe=(o=>(o[o.Start=-1]="Start",o[o.EarlyUpdate=0]="EarlyUpdate",o[o.Update=1]="Update",o[o.LateUpdate=2]="LateUpdate",o[o.OnBeforeRender=3]="OnBeforeRender",o[o.OnAfterRender=4]="OnAfterRender",o[o.PrePhysicsStep=9]="PrePhysicsStep",o[o.PostPhysicsStep=10]="PostPhysicsStep",o[o.Undefined=-1]="Undefined",o))(xe||{});function Mu(o,e){if(!o)return;if(!o.isComponent){(A()||Qe)&&console.error(`Registered script is not a Needle Engine component.
804
804
  The script will be ignored. Please make sure your component extends "Behaviour" imported from "@needle-tools/engine"
805
- `,o);return}e||(e=U.Current,Je&&console.warn("> Registering component without context"));const t=e?.new_scripts;t.includes(o)||t.push(o)}class U{static _defaultTargetFramerate={value:90,toString(){return this.value}};static get DefaultTargetFrameRate(){return U._defaultTargetFramerate.value}static set DefaultTargetFrameRate(e){U._defaultTargetFramerate.value=e}static _defaultWebglRendererParameters={antialias:!0,alpha:!1,powerPreference:I.isiOS()||I.isMacOS()?"default":"high-performance",stencil:!0};static get DefaultWebGLRendererParameters(){return U._defaultWebglRendererParameters}get version(){return Ti}static get Current(){return pe.Current}static set Current(e){pe.Current=e}static get All(){return pe.All}name;alias;isManagedExternally=!1;isPaused=!1;runInBackground=!1;targetFrameRate;physicsSteps=1;hash;domElement;appendHTMLElement(e){return this.domElement.shadowRoot?this.domElement.shadowRoot.appendChild(e):this.domElement.appendChild(e)}get resolutionScaleFactor(){return this._resolutionScaleFactor}set resolutionScaleFactor(e){if(e!==this._resolutionScaleFactor&&typeof e=="number"){if(e<=0){console.error("Invalid resolution scale factor",e);return}this._resolutionScaleFactor=e,this.updateSize()}}_resolutionScaleFactor=1;_boundingClientRectFrame=-1;_boundingClientRect=null;_domX;_domY;calculateBoundingClientRect(){if(this.xr){this._domX=0,this._domY=0;return}this._boundingClientRectFrame!==this.time.frame&&(this._boundingClientRectFrame=this.time.frame,this._boundingClientRect=this.domElement.getBoundingClientRect(),this._domX=this._boundingClientRect.x,this._domY=this._boundingClientRect.y)}get domWidth(){return this.isInAR?window.innerWidth:this.domElement.clientWidth}get domHeight(){return this.isInAR?window.innerHeight:this.domElement.clientHeight}get domX(){return this.calculateBoundingClientRect(),this._domX}get domY(){return this.calculateBoundingClientRect(),this._domY}get isInXR(){return this.renderer?.xr?.isPresenting||!1}xr=null;get xrSessionMode(){return this.xr?.mode}get isInVR(){return this.xrSessionMode==="immersive-vr"}get isInAR(){return this.xrSessionMode==="immersive-ar"}get isInPassThrough(){return this.xr?this.xr.isPassThrough:!1}get xrSession(){return this.renderer?.xr?.getSession()}get xrFrame(){return this._xrFrame}get xrCamera(){return this.renderer.xr.isPresenting?this.renderer?.xr?.getCamera():void 0}_xrFrame=null;get arOverlayElement(){const e=this.domElement;return typeof e.getAROverlayContainer=="function"?e.getAROverlayContainer():this.domElement}get currentFrameEvent(){return this._currentFrameEvent}_currentFrameEvent=-1;scene;renderer;composer=null;scripts=[];scripts_pausedChanged=[];scripts_earlyUpdate=[];scripts_update=[];scripts_lateUpdate=[];scripts_onBeforeRender=[];scripts_onAfterRender=[];scripts_WithCorroutines=[];scripts_immersive_vr=[];scripts_immersive_ar=[];coroutines={};post_setup_callbacks=[];pre_update_callbacks=[];pre_render_callbacks=[];post_render_callbacks=[];pre_update_oneshot_callbacks=[];new_scripts=[];new_script_start=[];new_scripts_pre_setup_callbacks=[];new_scripts_post_setup_callbacks=[];new_scripts_xr=[];mainCameraComponent=void 0;get mainCamera(){if(this._mainCamera)return this._mainCamera;if(this.mainCameraComponent){const e=this.mainCameraComponent;return e.threeCamera||e.buildCamera(),e.threeCamera}return this._fallbackCamera||(this._fallbackCamera=new de(75,this.domWidth/this.domHeight,.1,1e3)),this._fallbackCamera}set mainCamera(e){this._mainCamera=e}_mainCamera=null;_fallbackCamera=null;application;animations;time;input;physics;connection;assets;mainLight=null;get rendererData(){return this.sceneLighting}sceneLighting;addressables;lightmaps;players;lodsManager;menu;accessibility;get isCreated(){return this._isCreated}get rootSourceId(){return this.rootSceneSourceIdentifiers[0]||void 0}_needsUpdateSize=!1;_isCreated=!1;_isCreating=!1;_isVisible=!1;_stats=uE?new pP:null;constructor(e){this.name=e?.name||"",this.alias=e?.alias,this.domElement=e?.domElement||document.body,this.hash=e?.hash,e?.renderer&&(this.renderer=e.renderer,this.isManagedExternally=!0),e?.runInBackground!==void 0&&(this.runInBackground=e.runInBackground),e?.scene?this.scene=e.scene:this.scene=new Hi,e?.camera&&(this._mainCamera=e.camera),this.application=new zn(this),this.time=new Iw,this.input=new K_(this),this.physics=new oc(this),this.connection=new pv(this),this.assets=new kv,this.sceneLighting=new Rw(this),this.addressables=new ww(this),this.lightmaps=new KM(this),this.players=new kw(this),this.menu=new Ms(this),this.lodsManager=new JM(this),this.animations=new QM(this),this.accessibility=new wm(this);const t=()=>this._needsUpdateSize=!0;window.addEventListener("resize",t),this._disposeCallbacks.push(()=>window.removeEventListener("resize",t));const i=new ResizeObserver(n=>this._needsUpdateSize=!0);i.observe(this.domElement),this._disposeCallbacks.push(()=>i.disconnect()),this._intersectionObserver=new IntersectionObserver(n=>{this._isVisible=n[0].isIntersecting}),this._disposeCallbacks.push(()=>this._intersectionObserver?.disconnect()),pe.register(this)}createNewRenderer(e){if(this.renderer?.dispose(),e={...U.DefaultWebGLRendererParameters,...e},!e.canvas){const t=this.domElement?.shadowRoot?.querySelector("canvas");t&&(e.canvas=t,Je&&console.log("Using canvas from shadow root",t))}return Je&&console.log("Using Renderer Parameters:",e,this.domElement),this.renderer=new yr(e),this.renderer.domElement.setAttribute("aria-label","3D rendering"),this.renderer.domElement.setAttribute("role","img"),this.renderer.debug.checkShaderErrors=A()||w("checkshadererrors")===!0,this.renderer.toneMappingExposure=1,this.renderer.toneMapping=Td,this.renderer.setClearColor(new oe("lightgrey"),0),this.renderer.shadowMap.enabled=!0,this.renderer.shadowMap.type=oC,this.renderer.setSize(this.domWidth,this.domHeight),this.renderer.outputColorSpace=ko,this.renderer.nodes={library:new sC,modelViewMatrix:null,modelNormalViewMatrix:null},this.lodsManager.setRenderer(this.renderer),this.input.bindEvents(),fk(this,this.renderer.domElement),this.renderer}_intersectionObserver=null;internalOnUpdateVisible(){this._intersectionObserver?.disconnect(),this._intersectionObserver?.observe(this.domElement)}_disposeCallbacks=[];requestSizeUpdate(){this._needsUpdateSize=!0}maxRenderResolution;get devicePixelRatio(){return this._devicePixelRatio}set devicePixelRatio(e){e!==this._devicePixelRatio&&(this._devicePixelRatio=e,this._needsUpdateSize=!0)}_devicePixelRatio="auto";updateSize(e=!1){if(e||!this.isManagedExternally&&this.renderer.xr?.isPresenting===!1){this._needsUpdateSize=!1;const t=this.resolutionScaleFactor;let i=this.domWidth*t,n=this.domHeight*t;this.maxRenderResolution&&(this.maxRenderResolution.x=Math.max(1,this.maxRenderResolution.x),i=Math.min(this.maxRenderResolution.x,i),this.maxRenderResolution.y=Math.max(1,this.maxRenderResolution.y),n=Math.min(this.maxRenderResolution.y,n));const s=this.mainCamera;this.updateAspect(s),this.renderer.setSize(i,n,!0),this.renderer.domElement.style.width="100%",this.renderer.domElement.style.height="100%";const r=typeof this.devicePixelRatio=="number"?this.devicePixelRatio:this.devicePixelRatio==="auto"?Math.min(2,window.devicePixelRatio):void 0;r!==void 0&&this.renderer.setPixelRatio(r),this.composer&&(this.composer.setSize?.call(this.composer,i,n),r!==void 0&&"setPixelRatio"in this.composer&&typeof this.composer.setPixelRatio=="function"&&this.composer.setPixelRatio?.call(this.composer,window.devicePixelRatio))}}updateAspect(e,t,i){if(!e)return;t===void 0&&(t=this.domWidth),i===void 0&&(i=this.domHeight);const n=t/i;if(e.isPerspectiveCamera){const s=e,r=s.aspect;s.aspect=n,r!==s.aspect&&e.updateProjectionMatrix()}else if(e.isOrthographicCamera){const s=e,r=s.top-s.bottom,a=r*n/2,l=r/2;(s.left!=-a||s.top!=l)&&(s.left=-a,s.right=a,s.top=l,s.bottom=-l,e.updateProjectionMatrix())}}recreate(){this.clear(),this.create(this._originalCreationArgs)}_originalCreationArgs;async onCreate(e){return this.create(e)}async create(e){try{this._isCreating=!0,e!==this._originalCreationArgs&&(this._originalCreationArgs=pc(e)),window.addEventListener("unhandledrejection",this.onUnhandledRejection);const t=await this.internalOnCreate(e);return this._isCreated=t,t}finally{window.removeEventListener("unhandledrejection",this.onUnhandledRejection),this._isCreating=!1}}onUnhandledRejection=e=>{this.onError(e.reason)};onError(e){this.domElement.dispatchEvent(new CustomEvent("error",{detail:e}))}clear(){pe.dispatchCallback(ue.ContextClearing,this),Gn(this,ue.ContextClearing),Ii(this.scene,!0,!0),this.scene=new Hi,this.addressables?.dispose(),this.lightmaps?.clear(),this.physics?.engine?.clearCaches(),this.lodsManager.disable(),this.accessibility?.clear(),this._onBeforeRenderListeners.clear(),this._onAfterRenderListeners.clear(),this.isManagedExternally||this.renderer&&(this.renderer.renderLists.dispose(),this.renderer.state.reset(),this.renderer.resetState()),pe.dispatchCallback(ue.ContextCleared,this)}dispose(){this.internalOnDestroy(),this.accessibility.dispose()}onDestroy(){this.internalOnDestroy()}internalOnDestroy(){U.Current=this,pe.dispatchCallback(ue.ContextDestroying,this),Gn(this,ue.ContextDestroying),this.clear(),this.renderer?.setAnimationLoop(null),this.renderer&&(this.renderer.setClearAlpha(0),this.renderer.clear(),this.isManagedExternally||(Je&&console.log("Disposing renderer"),this.renderer.dispose())),this.scene=null,this.renderer=null,this.input.dispose(),this.menu.onDestroy(),this.animations.onDestroy();for(const e of this._disposeCallbacks)try{e()}catch(t){console.error("Error in on dispose callback:",t,e)}this.domElement?.parentElement&&this.domElement.parentElement.removeChild(this.domElement),this._isCreated=!1,pe.dispatchCallback(ue.ContextDestroyed,this),Gn(this,ue.ContextDestroyed),pe.unregister(this),U.Current===this&&(U.Current=null)}registerCoroutineUpdate(e,t,i){return typeof t?.next!="function"?(console.error("Registered invalid coroutine function from "+e.name+`
805
+ `,o);return}e||(e=U.Current,Qe&&console.warn("> Registering component without context"));const t=e?.new_scripts;t.includes(o)||t.push(o)}class U{static _defaultTargetFramerate={value:90,toString(){return this.value}};static get DefaultTargetFrameRate(){return U._defaultTargetFramerate.value}static set DefaultTargetFrameRate(e){U._defaultTargetFramerate.value=e}static _defaultWebglRendererParameters={antialias:!0,alpha:!1,powerPreference:I.isiOS()||I.isMacOS()?"default":"high-performance",stencil:!0};static get DefaultWebGLRendererParameters(){return U._defaultWebglRendererParameters}get version(){return Ti}static get Current(){return pe.Current}static set Current(e){pe.Current=e}static get All(){return pe.All}name;alias;isManagedExternally=!1;isPaused=!1;runInBackground=!1;targetFrameRate;physicsSteps=1;hash;domElement;appendHTMLElement(e){return this.domElement.shadowRoot?this.domElement.shadowRoot.appendChild(e):this.domElement.appendChild(e)}get resolutionScaleFactor(){return this._resolutionScaleFactor}set resolutionScaleFactor(e){if(e!==this._resolutionScaleFactor&&typeof e=="number"){if(e<=0){console.error("Invalid resolution scale factor",e);return}this._resolutionScaleFactor=e,this.updateSize()}}_resolutionScaleFactor=1;_boundingClientRectFrame=-1;_boundingClientRect=null;_domX;_domY;calculateBoundingClientRect(){if(this.xr){this._domX=0,this._domY=0;return}this._boundingClientRectFrame!==this.time.frame&&(this._boundingClientRectFrame=this.time.frame,this._boundingClientRect=this.domElement.getBoundingClientRect(),this._domX=this._boundingClientRect.x,this._domY=this._boundingClientRect.y)}get domWidth(){return this.isInAR?window.innerWidth:this.domElement.clientWidth}get domHeight(){return this.isInAR?window.innerHeight:this.domElement.clientHeight}get domX(){return this.calculateBoundingClientRect(),this._domX}get domY(){return this.calculateBoundingClientRect(),this._domY}get isInXR(){return this.renderer?.xr?.isPresenting||!1}xr=null;get xrSessionMode(){return this.xr?.mode}get isInVR(){return this.xrSessionMode==="immersive-vr"}get isInAR(){return this.xrSessionMode==="immersive-ar"}get isInPassThrough(){return this.xr?this.xr.isPassThrough:!1}get xrSession(){return this.renderer?.xr?.getSession()}get xrFrame(){return this._xrFrame}get xrCamera(){return this.renderer.xr.isPresenting?this.renderer?.xr?.getCamera():void 0}_xrFrame=null;get arOverlayElement(){const e=this.domElement;return typeof e.getAROverlayContainer=="function"?e.getAROverlayContainer():this.domElement}get currentFrameEvent(){return this._currentFrameEvent}_currentFrameEvent=-1;scene;renderer;composer=null;scripts=[];scripts_pausedChanged=[];scripts_earlyUpdate=[];scripts_update=[];scripts_lateUpdate=[];scripts_onBeforeRender=[];scripts_onAfterRender=[];scripts_WithCorroutines=[];scripts_immersive_vr=[];scripts_immersive_ar=[];coroutines={};post_setup_callbacks=[];pre_update_callbacks=[];pre_render_callbacks=[];post_render_callbacks=[];pre_update_oneshot_callbacks=[];new_scripts=[];new_script_start=[];new_scripts_pre_setup_callbacks=[];new_scripts_post_setup_callbacks=[];new_scripts_xr=[];mainCameraComponent=void 0;get mainCamera(){if(this._mainCamera)return this._mainCamera;if(this.mainCameraComponent){const e=this.mainCameraComponent;return e.threeCamera||e.buildCamera(),e.threeCamera}return this._fallbackCamera||(this._fallbackCamera=new de(75,this.domWidth/this.domHeight,.1,1e3)),this._fallbackCamera}set mainCamera(e){this._mainCamera=e}_mainCamera=null;_fallbackCamera=null;application;animations;time;input;physics;connection;assets;mainLight=null;get rendererData(){return this.sceneLighting}sceneLighting;addressables;lightmaps;players;lodsManager;menu;accessibility;get isCreated(){return this._isCreated}get rootSourceId(){return this.rootSceneSourceIdentifiers[0]||void 0}_needsUpdateSize=!1;_isCreated=!1;_isCreating=!1;_isVisible=!1;_stats=uE?new pP:null;constructor(e){this.name=e?.name||"",this.alias=e?.alias,this.domElement=e?.domElement||document.body,this.hash=e?.hash,e?.renderer&&(this.renderer=e.renderer,this.isManagedExternally=!0),e?.runInBackground!==void 0&&(this.runInBackground=e.runInBackground),e?.scene?this.scene=e.scene:this.scene=new Hi,e?.camera&&(this._mainCamera=e.camera),this.application=new zn(this),this.time=new Iw,this.input=new K_(this),this.physics=new oc(this),this.connection=new pv(this),this.assets=new kv,this.sceneLighting=new Rw(this),this.addressables=new ww(this),this.lightmaps=new KM(this),this.players=new kw(this),this.menu=new Ms(this),this.lodsManager=new JM(this),this.animations=new QM(this),this.accessibility=new wm(this);const t=()=>this._needsUpdateSize=!0;window.addEventListener("resize",t),this._disposeCallbacks.push(()=>window.removeEventListener("resize",t));const i=new ResizeObserver(n=>this._needsUpdateSize=!0);i.observe(this.domElement),this._disposeCallbacks.push(()=>i.disconnect()),this._intersectionObserver=new IntersectionObserver(n=>{this._isVisible=n[0].isIntersecting}),this._disposeCallbacks.push(()=>this._intersectionObserver?.disconnect()),pe.register(this)}createNewRenderer(e){if(this.renderer?.dispose(),e={...U.DefaultWebGLRendererParameters,...e},!e.canvas){const t=this.domElement?.shadowRoot?.querySelector("canvas");t?(e.canvas=t,Qe&&console.log("Using canvas from shadow root",t)):Qe&&console.warn("No canvas found in shadow root, creating new canvas. This may cause input events to not work correctly. To fix this, make sure to use the canvas provided by the Needle Engine Web Component (e.g. by using context.createNewRenderer() without parameters or passing the canvas from the shadow root explicitly).")}return Qe&&console.log("Using Renderer Parameters:",e,this.domElement),this.renderer=new yr(e),this.renderer.domElement.setAttribute("aria-label","3D rendering"),this.renderer.domElement.setAttribute("role","img"),this.renderer.debug.checkShaderErrors=A()||w("checkshadererrors")===!0,this.renderer.toneMappingExposure=1,this.renderer.toneMapping=Td,this.renderer.setClearColor(new oe("lightgrey"),0),this.renderer.shadowMap.enabled=!0,this.renderer.shadowMap.type=oC,this.renderer.setSize(this.domWidth,this.domHeight),this.renderer.outputColorSpace=ko,this.renderer.nodes={library:new sC,modelViewMatrix:null,modelNormalViewMatrix:null},this.lodsManager.setRenderer(this.renderer),this.input.bindEvents(),fk(this,this.renderer.domElement),this.renderer}_intersectionObserver=null;internalOnUpdateVisible(){this._intersectionObserver?.disconnect(),this._intersectionObserver?.observe(this.domElement)}_disposeCallbacks=[];requestSizeUpdate(){this._needsUpdateSize=!0}maxRenderResolution;get devicePixelRatio(){return this._devicePixelRatio}set devicePixelRatio(e){e!==this._devicePixelRatio&&(this._devicePixelRatio=e,this._needsUpdateSize=!0)}_devicePixelRatio="auto";updateSize(e=!1){if(e||!this.isManagedExternally&&this.renderer.xr?.isPresenting===!1){this._needsUpdateSize=!1;const t=this.resolutionScaleFactor;let i=this.domWidth*t,n=this.domHeight*t;this.maxRenderResolution&&(this.maxRenderResolution.x=Math.max(1,this.maxRenderResolution.x),i=Math.min(this.maxRenderResolution.x,i),this.maxRenderResolution.y=Math.max(1,this.maxRenderResolution.y),n=Math.min(this.maxRenderResolution.y,n));const s=this.mainCamera;this.updateAspect(s),this.renderer.setSize(i,n,!0),this.renderer.domElement.style.width="100%",this.renderer.domElement.style.height="100%";const r=typeof this.devicePixelRatio=="number"?this.devicePixelRatio:this.devicePixelRatio==="auto"?Math.min(2,window.devicePixelRatio):void 0;r!==void 0&&this.renderer.setPixelRatio(r),this.composer&&(this.composer.setSize?.call(this.composer,i,n),r!==void 0&&"setPixelRatio"in this.composer&&typeof this.composer.setPixelRatio=="function"&&this.composer.setPixelRatio?.call(this.composer,window.devicePixelRatio))}}updateAspect(e,t,i){if(!e)return;t===void 0&&(t=this.domWidth),i===void 0&&(i=this.domHeight);const n=t/i;if(e.isPerspectiveCamera){const s=e,r=s.aspect;s.aspect=n,r!==s.aspect&&e.updateProjectionMatrix()}else if(e.isOrthographicCamera){const s=e,r=s.top-s.bottom,a=r*n/2,l=r/2;(s.left!=-a||s.top!=l)&&(s.left=-a,s.right=a,s.top=l,s.bottom=-l,e.updateProjectionMatrix())}}recreate(){this.clear(),this.create(this._originalCreationArgs)}_originalCreationArgs;async onCreate(e){return this.create(e)}async create(e){try{this._isCreating=!0,e!==this._originalCreationArgs&&(this._originalCreationArgs=pc(e)),window.addEventListener("unhandledrejection",this.onUnhandledRejection);const t=await this.internalOnCreate(e);return this._isCreated=t,t}finally{window.removeEventListener("unhandledrejection",this.onUnhandledRejection),this._isCreating=!1}}onUnhandledRejection=e=>{this.onError(e.reason)};onError(e){this.domElement.dispatchEvent(new CustomEvent("error",{detail:e}))}clear(){pe.dispatchCallback(ue.ContextClearing,this),Gn(this,ue.ContextClearing),Ii(this.scene,!0,!0),this.scene=new Hi,this.addressables?.dispose(),this.lightmaps?.clear(),this.physics?.engine?.clearCaches(),this.lodsManager.disable(),this.accessibility?.clear(),this._onBeforeRenderListeners.clear(),this._onAfterRenderListeners.clear(),this.isManagedExternally||this.renderer&&(this.renderer.renderLists.dispose(),this.renderer.state.reset(),this.renderer.resetState()),pe.dispatchCallback(ue.ContextCleared,this)}dispose(){this.internalOnDestroy(),this.accessibility.dispose()}onDestroy(){this.internalOnDestroy()}internalOnDestroy(){U.Current=this,pe.dispatchCallback(ue.ContextDestroying,this),Gn(this,ue.ContextDestroying),this.clear(),this.renderer?.setAnimationLoop(null),this.renderer&&(this.renderer.setClearAlpha(0),this.renderer.clear(),this.isManagedExternally||(Qe&&console.log("Disposing renderer"),this.renderer.dispose())),this.scene=null,this.renderer=null,this.input.dispose(),this.menu.onDestroy(),this.animations.onDestroy();for(const e of this._disposeCallbacks)try{e()}catch(t){console.error("Error in on dispose callback:",t,e)}this.domElement?.parentElement&&this.domElement.parentElement.removeChild(this.domElement),this._isCreated=!1,pe.dispatchCallback(ue.ContextDestroyed,this),Gn(this,ue.ContextDestroyed),pe.unregister(this),U.Current===this&&(U.Current=null)}registerCoroutineUpdate(e,t,i){return typeof t?.next!="function"?(console.error("Registered invalid coroutine function from "+e.name+`
806
806
  Coroutine functions must be generators: "*myCoroutine() {...}"
807
- Start a coroutine from a component by calling "this.startCoroutine(myCoroutine())"`),t):(this.coroutines[i]||(this.coroutines[i]=[]),this.coroutines[i].push({comp:e,main:t}),t)}unregisterCoroutineUpdate(e,t){if(!this.coroutines[t])return;const i=this.coroutines[t].findIndex(n=>n.main===e);i>=0&&this.coroutines[t].splice(i,1)}stopAllCoroutinesFrom(e){for(const t in this.coroutines){const i=this.coroutines[t];for(let n=i.length-1;n>=0;n--)i[n].comp===e&&i.splice(n,1)}}_cameraStack=[];setCurrentCamera(e){if(!e)return;if(e.threeCamera||e.buildCamera(),!e.threeCamera){console.warn("Camera component is missing camera",e);return}const t=this._cameraStack.indexOf(e);t>=0&&this._cameraStack.splice(t,1),this._cameraStack.push(e),this.mainCameraComponent=e;const i=e.threeCamera;i.isPerspectiveCamera&&this.updateAspect(i),this.mainCameraComponent?.applyClearFlagsIfIsActiveCamera()}removeCamera(e){if(!e)return;const t=this._cameraStack.indexOf(e);if(t>=0&&this._cameraStack.splice(t,1),this.mainCameraComponent===e&&(this.mainCameraComponent=void 0,this._cameraStack.length>0)){const i=this._cameraStack[this._cameraStack.length-1];this.setCurrentCamera(i)}}_onBeforeRenderListeners=new Map;_onAfterRenderListeners=new Map;addBeforeRenderListener(e,t){if(!this._onBeforeRenderListeners.has(e.uuid)){const i=[];this._onBeforeRenderListeners.set(e.uuid,i),e.onBeforeRender=this._createRenderCallbackWrapper(i)}this._onBeforeRenderListeners.get(e.uuid).push(t)}removeBeforeRenderListener(e,t){if(this._onBeforeRenderListeners.has(e.uuid)){const i=this._onBeforeRenderListeners.get(e.uuid),n=i.indexOf(t);n>=0&&i.splice(n,1)}}addAfterRenderListener(e,t){if(!this._onAfterRenderListeners.has(e.uuid)){const i=[];this._onAfterRenderListeners.set(e.uuid,i),e.onAfterRender=this._createRenderCallbackWrapper(i)}this._onAfterRenderListeners.get(e.uuid)?.push(t)}removeAfterRenderListener(e,t){if(this._onAfterRenderListeners.has(e.uuid)){const i=this._onAfterRenderListeners.get(e.uuid),n=i.indexOf(t);n>=0&&i.splice(n,1)}}_createRenderCallbackWrapper(e){return(t,i,n,s,r,a)=>{for(let l=0;l<e.length;l++){const c=e[l];c(t,i,n,s,r,a)}}}_requireDepthTexture=!1;_requireColorTexture=!1;_renderTarget;_isRendering=!1;get isRendering(){return this._isRendering}setRequireDepth(e){this._requireDepthTexture=e}setRequireColor(e){this._requireColorTexture=e}get depthTexture(){return this._renderTarget?.depthTexture||null}get opaqueColorTexture(){return this._renderTarget?.texture||null}get isVisibleToUser(){if(this.isInXR)return!0;if(!this._isVisible)return!1;if(!this._needsVisibleUpdate&&this._lastStyleComputedResult!==void 0)return this._lastStyleComputedResult;this._needsVisibleUpdate=!1;const e=getComputedStyle(this.domElement);return this._lastStyleComputedResult=e.visibility!=="hidden"&&e.display!=="none"&&e.opacity!=="0",this._lastStyleComputedResult}_needsVisibleUpdate=!0;_lastStyleComputedResult=void 0;_createId=0;async internalOnCreate(e){const t=++this._createId;Je&&console.log("Creating context",this.name,e);const i=globalThis["needle:dependencies:ready"];i instanceof Promise&&(Je&&console.log("Waiting for dependencies to be ready"),await i.catch(h=>{if(Je||A()){if(_c("Needle Engine dependencies failed to load. Please check the console for more details"),h instanceof ReferenceError){let d="YourComponentName";const p=h.message.indexOf("'");if(p>0){const m=h.message.indexOf("'",p+1);if(m>0){const g=h.message.substring(p+1,m);g.length>3&&(d=g)}}console.error(`Needle Engine dependencies failed to load:
807
+ Start a coroutine from a component by calling "this.startCoroutine(myCoroutine())"`),t):(this.coroutines[i]||(this.coroutines[i]=[]),this.coroutines[i].push({comp:e,main:t}),t)}unregisterCoroutineUpdate(e,t){if(!this.coroutines[t])return;const i=this.coroutines[t].findIndex(n=>n.main===e);i>=0&&this.coroutines[t].splice(i,1)}stopAllCoroutinesFrom(e){for(const t in this.coroutines){const i=this.coroutines[t];for(let n=i.length-1;n>=0;n--)i[n].comp===e&&i.splice(n,1)}}_cameraStack=[];setCurrentCamera(e){if(!e)return;if(e.threeCamera||e.buildCamera(),!e.threeCamera){console.warn("Camera component is missing camera",e);return}const t=this._cameraStack.indexOf(e);t>=0&&this._cameraStack.splice(t,1),this._cameraStack.push(e),this.mainCameraComponent=e;const i=e.threeCamera;i.isPerspectiveCamera&&this.updateAspect(i),this.mainCameraComponent?.applyClearFlagsIfIsActiveCamera()}removeCamera(e){if(!e)return;const t=this._cameraStack.indexOf(e);if(t>=0&&this._cameraStack.splice(t,1),this.mainCameraComponent===e&&(this.mainCameraComponent=void 0,this._cameraStack.length>0)){const i=this._cameraStack[this._cameraStack.length-1];this.setCurrentCamera(i)}}_onBeforeRenderListeners=new Map;_onAfterRenderListeners=new Map;addBeforeRenderListener(e,t){if(!this._onBeforeRenderListeners.has(e.uuid)){const i=[];this._onBeforeRenderListeners.set(e.uuid,i),e.onBeforeRender=this._createRenderCallbackWrapper(i)}this._onBeforeRenderListeners.get(e.uuid).push(t)}removeBeforeRenderListener(e,t){if(this._onBeforeRenderListeners.has(e.uuid)){const i=this._onBeforeRenderListeners.get(e.uuid),n=i.indexOf(t);n>=0&&i.splice(n,1)}}addAfterRenderListener(e,t){if(!this._onAfterRenderListeners.has(e.uuid)){const i=[];this._onAfterRenderListeners.set(e.uuid,i),e.onAfterRender=this._createRenderCallbackWrapper(i)}this._onAfterRenderListeners.get(e.uuid)?.push(t)}removeAfterRenderListener(e,t){if(this._onAfterRenderListeners.has(e.uuid)){const i=this._onAfterRenderListeners.get(e.uuid),n=i.indexOf(t);n>=0&&i.splice(n,1)}}_createRenderCallbackWrapper(e){return(t,i,n,s,r,a)=>{for(let l=0;l<e.length;l++){const c=e[l];c(t,i,n,s,r,a)}}}_requireDepthTexture=!1;_requireColorTexture=!1;_renderTarget;_isRendering=!1;get isRendering(){return this._isRendering}setRequireDepth(e){this._requireDepthTexture=e}setRequireColor(e){this._requireColorTexture=e}get depthTexture(){return this._renderTarget?.depthTexture||null}get opaqueColorTexture(){return this._renderTarget?.texture||null}get isVisibleToUser(){if(this.isInXR)return!0;if(!this._isVisible)return!1;if(!this._needsVisibleUpdate&&this._lastStyleComputedResult!==void 0)return this._lastStyleComputedResult;this._needsVisibleUpdate=!1;const e=getComputedStyle(this.domElement);return this._lastStyleComputedResult=e.visibility!=="hidden"&&e.display!=="none"&&e.opacity!=="0",this._lastStyleComputedResult}_needsVisibleUpdate=!0;_lastStyleComputedResult=void 0;_createId=0;async internalOnCreate(e){const t=++this._createId;Qe&&console.log("Creating context",this.name,e);const i=globalThis["needle:dependencies:ready"];i instanceof Promise&&(Qe&&console.log("Waiting for dependencies to be ready"),await i.catch(h=>{if(Qe||A()){if(_c("Needle Engine dependencies failed to load. Please check the console for more details"),h instanceof ReferenceError){let d="YourComponentName";const p=h.message.indexOf("'");if(p>0){const m=h.message.indexOf("'",p+1);if(m>0){const g=h.message.substring(p+1,m);g.length>3&&(d=g)}}console.error(`Needle Engine dependencies failed to load:
808
808
 
809
809
  # Make sure you don't have circular imports in your scripts!
810
810
 
@@ -812,7 +812,7 @@ Possible solutions:
812
812
  \u2192 Replace @serializable(${d}) in your script with @serializable(Behaviour)
813
813
  \u2192 If you only need type information try importing the type only, e.g: import { type ${d} }
814
814
 
815
- ---`,h);return}console.error("Needle Engine dependencies failed to load",h)}}).then(()=>{Je&&console.log("Needle Engine dependencies are ready")})),this.clear();const n=this.renderer,s=!n||n.isDisposed===!0;this.isManagedExternally===!1&&s?this.createNewRenderer():this.lodsManager.setRenderer(this.renderer),this.renderer?.setAnimationLoop(null),U.Current=this,await pe.dispatchCallback(ue.ContextCreationStart,this);let r=!0,a;try{U.Current=this,e?a=await this.internalLoadInitialContent(t,e):a=[]}catch(h){console.error(h),r=!1}if(!r)return this.onError("Failed to load initial content"),!1;if(t!==this._createId||e?.abortSignal?.aborted)return!1;if(this.internalOnUpdateVisible(),!this.renderer)return Je&&console.warn("Context has no renderer (perhaps it was disconnected?",this.domElement.isConnected),!1;!this.isManagedExternally&&!this.domElement.shadowRoot&&this.domElement.prepend(this.renderer.domElement),U.Current=this,U.Current=this;for(let h=0;h<this.new_scripts.length;h++){const d=this.new_scripts[h];if(d.gameObject!==void 0&&d.gameObject!==null){d.gameObject.userData===void 0&&(d.gameObject.userData={}),d.gameObject.userData.components===void 0&&(d.gameObject.userData.components=[]);const p=d.gameObject.userData.components;p.includes(d)||p.push(d)}}if(this.post_setup_callbacks)for(let h=0;h<this.post_setup_callbacks.length;h++)U.Current=this,await this.post_setup_callbacks[h](this);if(!this._mainCamera){U.Current=this;let h=null;Fr(this.scene,d=>{const p=d;if(p?.isCamera){if(Ic(p.gameObject),!p.activeAndEnabled)return;if(p.tag==="MainCamera")return h=p,!0;h=p}}),h?this.setCurrentCamera(h):!pe.dispatchCallback(ue.MissingCamera,this,{files:a})&&!this.mainCamera&&!this.isManagedExternally&&console.warn("Missing camera in main scene",this)}this.input.bindEvents(),U.Current=this,au(this),this.physics.engine&&(this.physics.engine?.step(0),this.physics.engine?.postStep()),!this.isManagedExternally&&this.composer&&this.mainCamera,this._needsUpdateSize=!0,this._stats&&(this._stats.showPanel(0),this._stats.dom.style.position="absolute",this.domElement.shadowRoot?.appendChild(this._stats.dom)),Je&&$d(this.scene,!0),this.targetFrameRate===void 0?(Je&&console.warn("No target framerate set, using default",U.DefaultTargetFrameRate),this.targetFrameRate=U._defaultTargetFramerate):Je&&console.log("Target framerate set to",this.targetFrameRate),this._dispatchReadyAfterFrame=!0;const l=pe.dispatchCallback(ue.ContextCreated,this,{files:a});if(l){const h=this.domElement;"internalSetLoadingMessage"in h&&typeof h.internalSetLoadingMessage=="function"&&h?.internalSetLoadingMessage("finish loading"),await l}if(e?.abortSignal?.aborted)return!1;const c=this.rootSourceId;return c&&this.sceneLighting.enable(c),Gn(this,ue.ContextCreated),Je&&console.log("Context Created...",this.renderer,this.renderer.domElement),this._isCreating=!1,!this.isManagedExternally&&!e?.abortSignal?.aborted&&this.restartRenderLoop(),!0}rootSceneSourceIdentifiers=[];async internalLoadInitialContent(e,t){this.rootSceneSourceIdentifiers.length=0;const i=new Array;if(t.files.length===0)return i;const n=[...t.files];this.rootSceneSourceIdentifiers.push(...n);const s={name:"",progress:null,index:0,count:n.length},r=Cn(),a=0;for(let l=0;l<n.length;l++){if(t.abortSignal?.aborted){Je&&console.log("Aborting loading because of abort signal");break}if(e!==this._createId){Je&&console.log("Aborting loading because create id changed",e,this._createId);break}const c=n[l];t?.onLoadingStart?.call(this,l,c),Je&&console.log("Context Load "+c);const h=await r.loadSync(this,c,c,a,d=>{t.abortSignal?.aborted||(s.name=c,s.progress=d,s.index=l,s.count=n.length,t.onLoadingProgress?.call(this,s))});t?.onLoadingFinished?.call(this,l,c,h??null),h?i.push({src:c,file:h}):console.warn("Could not load file: "+c)}if(e!==this._createId||t.abortSignal?.aborted){Je&&console.log("Aborting loading because create id changed or abort signal was set",e,this._createId);for(const l of i)if(l&&l.file)for(const c of l.file.scenes)Ii(c,!0,!0)}else{let l=!1;for(const c of i)c&&c.file&&(c.file.scene?(l=!0,this.scene.add(c.file.scene)):console.warn("No scene found in loaded file"));if(!l){for(const c of i)if(c&&c.file&&"parser"in c.file){let h=0;if(!Array.isArray(c.file.parser.json.materials))continue;for(let d=0;d<c.file.parser.json.materials.length;d++){const p=await c.file.parser.getDependency("material",d),m=new M;m.position.x=d*1.1,m.position.y=h,this.scene.add(m),Ps.createPrimitive("ShaderBall",{parent:m,material:p})}h+=1}}}return i}restartRenderLoop(){return this.renderer?this._isCreating?(console.warn("Can not start render loop while creating context"),!1):(this.renderer.setAnimationLoop((e,t)=>{this.isManagedExternally||this.update(e,t)}),!0):(console.error("Can not start render loop without renderer"),!1)}_renderlooperrors=0;update(e,t){if(t===void 0&&(t=null),A()||Je||uM())try{this.internalStep(e,t),this._renderlooperrors=0}catch(i){this._renderlooperrors+=1,(A()||Je)&&(i instanceof Error||i instanceof TypeError)&&Oe("Caught unhandled exception during render-loop - see console for details.",{type:Ei.Error}),console.error("Frame #"+this.time.frame+`
815
+ ---`,h);return}console.error("Needle Engine dependencies failed to load",h)}}).then(()=>{Qe&&console.log("Needle Engine dependencies are ready")})),this.clear();const n=this.renderer,s=!n||n.isDisposed===!0;this.isManagedExternally===!1&&s?this.createNewRenderer():this.lodsManager.setRenderer(this.renderer),this.renderer?.setAnimationLoop(null),U.Current=this,await pe.dispatchCallback(ue.ContextCreationStart,this);let r=!0,a;try{U.Current=this,e?a=await this.internalLoadInitialContent(t,e):a=[]}catch(h){console.error(h),r=!1}if(!r)return this.onError("Failed to load initial content"),!1;if(t!==this._createId||e?.abortSignal?.aborted)return!1;if(this.internalOnUpdateVisible(),!this.renderer)return Qe&&console.warn("Context has no renderer (perhaps it was disconnected?",this.domElement.isConnected),!1;!this.isManagedExternally&&!this.domElement.shadowRoot&&this.domElement.prepend(this.renderer.domElement),U.Current=this,U.Current=this;for(let h=0;h<this.new_scripts.length;h++){const d=this.new_scripts[h];if(d.gameObject!==void 0&&d.gameObject!==null){d.gameObject.userData===void 0&&(d.gameObject.userData={}),d.gameObject.userData.components===void 0&&(d.gameObject.userData.components=[]);const p=d.gameObject.userData.components;p.includes(d)||p.push(d)}}if(this.post_setup_callbacks)for(let h=0;h<this.post_setup_callbacks.length;h++)U.Current=this,await this.post_setup_callbacks[h](this);if(!this._mainCamera){U.Current=this;let h=null;Fr(this.scene,d=>{const p=d;if(p?.isCamera){if(Ic(p.gameObject),!p.activeAndEnabled)return;if(p.tag==="MainCamera")return h=p,!0;h=p}}),h?this.setCurrentCamera(h):!pe.dispatchCallback(ue.MissingCamera,this,{files:a})&&!this.mainCamera&&!this.isManagedExternally&&console.warn("Missing camera in main scene",this)}this.input.bindEvents(),U.Current=this,au(this),this.physics.engine&&(this.physics.engine?.step(0),this.physics.engine?.postStep()),!this.isManagedExternally&&this.composer&&this.mainCamera,this._needsUpdateSize=!0,this._stats&&(this._stats.showPanel(0),this._stats.dom.style.position="absolute",this.domElement.shadowRoot?.appendChild(this._stats.dom)),Qe&&$d(this.scene,!0),this.targetFrameRate===void 0?(Qe&&console.warn("No target framerate set, using default",U.DefaultTargetFrameRate),this.targetFrameRate=U._defaultTargetFramerate):Qe&&console.log("Target framerate set to",this.targetFrameRate),this._dispatchReadyAfterFrame=!0;const l=pe.dispatchCallback(ue.ContextCreated,this,{files:a});if(l){const h=this.domElement;"internalSetLoadingMessage"in h&&typeof h.internalSetLoadingMessage=="function"&&h?.internalSetLoadingMessage("finish loading"),await l}if(e?.abortSignal?.aborted)return!1;const c=this.rootSourceId;return c&&this.sceneLighting.enable(c),Gn(this,ue.ContextCreated),Qe&&console.log("Context Created...",this.renderer,this.renderer.domElement),this._isCreating=!1,!this.isManagedExternally&&!e?.abortSignal?.aborted&&this.restartRenderLoop(),!0}rootSceneSourceIdentifiers=[];async internalLoadInitialContent(e,t){this.rootSceneSourceIdentifiers.length=0;const i=new Array;if(t.files.length===0)return i;const n=[...t.files];this.rootSceneSourceIdentifiers.push(...n);const s={name:"",progress:null,index:0,count:n.length},r=Cn(),a=0;for(let l=0;l<n.length;l++){if(t.abortSignal?.aborted){Qe&&console.log("Aborting loading because of abort signal");break}if(e!==this._createId){Qe&&console.log("Aborting loading because create id changed",e,this._createId);break}const c=n[l];t?.onLoadingStart?.call(this,l,c),Qe&&console.log("Context Load "+c);const h=await r.loadSync(this,c,c,a,d=>{t.abortSignal?.aborted||(s.name=c,s.progress=d,s.index=l,s.count=n.length,t.onLoadingProgress?.call(this,s))});t?.onLoadingFinished?.call(this,l,c,h??null),h?i.push({src:c,file:h}):console.warn("Could not load file: "+c)}if(e!==this._createId||t.abortSignal?.aborted){Qe&&console.log("Aborting loading because create id changed or abort signal was set",e,this._createId);for(const l of i)if(l&&l.file)for(const c of l.file.scenes)Ii(c,!0,!0)}else{let l=!1;for(const c of i)c&&c.file&&(c.file.scene?(l=!0,this.scene.add(c.file.scene)):console.warn("No scene found in loaded file"));if(!l){for(const c of i)if(c&&c.file&&"parser"in c.file){let h=0;if(!Array.isArray(c.file.parser.json.materials))continue;for(let d=0;d<c.file.parser.json.materials.length;d++){const p=await c.file.parser.getDependency("material",d),m=new M;m.position.x=d*1.1,m.position.y=h,this.scene.add(m),Ps.createPrimitive("ShaderBall",{parent:m,material:p})}h+=1}}}return i}restartRenderLoop(){return this.renderer?this._isCreating?(console.warn("Can not start render loop while creating context"),!1):(this.renderer.setAnimationLoop((e,t)=>{this.isManagedExternally||this.update(e,t)}),!0):(console.error("Can not start render loop without renderer"),!1)}_renderlooperrors=0;update(e,t){if(t===void 0&&(t=null),A()||Qe||uM())try{this.internalStep(e,t),this._renderlooperrors=0}catch(i){this._renderlooperrors+=1,(A()||Qe)&&(i instanceof Error||i instanceof TypeError)&&Oe("Caught unhandled exception during render-loop - see console for details.",{type:Ei.Error}),console.error("Frame #"+this.time.frame+`
816
816
  `,i),this._renderlooperrors>=3&&(console.warn("Stopping render loop due to error"),this.renderer.setAnimationLoop(null),pi.sendError(U.Current,"renderloop",i instanceof Error?i:new Error(String(i)))),this.domElement.dispatchEvent(new CustomEvent("error",{detail:i}))}else this.internalStep(e,t)}updatePhysics(e){this.internalUpdatePhysics(e)}setCameraFocusRect(e,t){const i=this._focusRect;if(this._focusRect=e,t&&Object.assign(this.focusRectSettings,t),t?.damping===void 0&&i){let n=i;i instanceof HTMLElement&&(n=i.getBoundingClientRect()),n&&"top"in n&&n.bottom>=-100&&n.right>=-100&&n.top<=window.innerHeight+100&&n.left<=window.innerWidth+100&&(this.focusRectSettings.damping=.2)}}get focusRect(){return this._focusRect}get focusRectSize(){const e=this._focusRect;if(e&&(e instanceof DOMRect||"width"in e&&"height"in e&&"x"in e&&"y"in e))return{x:e.x,y:e.y,width:e.width,height:e.height};if(e instanceof HTMLElement){const t=e.getBoundingClientRect();return{x:t.x,y:t.y,width:t.width,height:t.height}}return null}focusRectSettings={damping:0,zoom:1,offsetX:0,offsetY:0};_focusRect=null;_lastTimestamp=0;_accumulatedTime=0;_dispatchReadyAfterFrame=!1;internalStep(e,t){this.internalOnBeforeRender(e,t)!==!1&&(this.internalOnRender(),this.internalOnAfterRender())}internalOnBeforeRender(e,t){this.renderer.info.autoReset=!!t,this.renderer.info.autoReset===!1&&this.renderer.info.reset(),this._needsVisibleUpdate=!0;const i=t!==null&&this._xrFrame===null;if(this._xrFrame=t,i&&this.domElement.dispatchEvent(new CustomEvent("xr-session-started",{detail:{context:this,session:this.xrSession,frame:t}})),this._currentFrameEvent=-1,this.isManagedExternally===!1&&this.isInXR===!1&&this.targetFrameRate!==void 0){this._lastTimestamp===0&&(this._lastTimestamp=e),this._accumulatedTime+=(e-this._lastTimestamp)/1e3,this._lastTimestamp=e;let n=this.targetFrameRate;if(typeof n=="object"&&(n=n.value),this._accumulatedTime<1/(n+1))return!1;this._accumulatedTime=0}if(this._stats?.begin(),U.Current=this,this.onHandlePaused())return!1;for(U.Current=this,this.time.update(),mE&&console.log("FPS",this.time.smoothedFps.toFixed(0)),au(this),lu(this.scene),jv(this),Gn(this,-1);this._cameraStack.length>0&&(!this.mainCameraComponent||this.mainCameraComponent.destroyed);){this._cameraStack.splice(this._cameraStack.length-1,1);const n=this._cameraStack[this._cameraStack.length-1];this.setCurrentCamera(n)}if(this.pre_update_oneshot_callbacks){for(const n in this.pre_update_oneshot_callbacks)this.pre_update_oneshot_callbacks[n]();this.pre_update_oneshot_callbacks.length=0}if(this.pre_update_callbacks)for(const n in this.pre_update_callbacks)this.pre_update_callbacks[n]();this._currentFrameEvent=0;for(let n=0;n<this.scripts_earlyUpdate.length;n++){const s=this.scripts_earlyUpdate[n];s.activeAndEnabled&&s.earlyUpdate!==void 0&&(U.Current=this,s.earlyUpdate())}this.executeCoroutines(0),Gn(this,0),this._currentFrameEvent=1;for(let n=0;n<this.scripts_update.length;n++){const s=this.scripts_update[n];s.activeAndEnabled&&s.update!==void 0&&(U.Current=this,s.update())}this.executeCoroutines(1),Gn(this,1),this._currentFrameEvent=2;for(let n=0;n<this.scripts_lateUpdate.length;n++){const s=this.scripts_lateUpdate[n];s.activeAndEnabled&&s.lateUpdate!==void 0&&(U.Current=this,s.lateUpdate())}if(this.executeCoroutines(2),Gn(this,2),this.physicsSteps===void 0&&(this.physicsSteps=1),this.physics.engine&&this.physicsSteps>0&&this.internalUpdatePhysics(this.physicsSteps),this.isVisibleToUser||this.runInBackground){this._currentFrameEvent=3;for(let n=0;n<this.scripts_onBeforeRender.length;n++){const s=this.scripts_onBeforeRender[n];s.activeAndEnabled&&s.onBeforeRender!==void 0&&(U.Current=this,s.onBeforeRender(t))}if(this.executeCoroutines(3),Gn(this,3),this._needsUpdateSize&&this.updateSize(),this.pre_render_callbacks)for(const n in this.pre_render_callbacks)this.pre_render_callbacks[n](t);if(this._focusRect&&this.mainCamera instanceof de){const n=this.focusRectSettings,s=n.damping>0?this.time.deltaTime/n.damping:1;CO(this._focusRect,this.focusRectSettings,s,this.mainCamera,this.renderer)}}return!0}internalUpdatePhysics(e){if(!this.physics.engine)return!1;const t=e,i=this.time.deltaTime/t;for(let n=0;n<t;n++)this._currentFrameEvent=9,this.executeCoroutines(9),this.physics.engine.step(i),this._currentFrameEvent=10,this.executeCoroutines(10);return this.physics.engine.postStep(),!0}internalOnRender(){this.isManagedExternally||(fM(this),this._currentFrameEvent=-1,Db.camera=this.mainCamera,Db.update(),this.renderNow(),this._currentFrameEvent=4)}internalOnAfterRender(){if(this.isVisibleToUser||this.runInBackground){for(let e=0;e<this.scripts_onAfterRender.length;e++){const t=this.scripts_onAfterRender[e];t.activeAndEnabled&&t.onAfterRender!==void 0&&(U.Current=this,t.onAfterRender())}if(this.executeCoroutines(4),Gn(this,4),this.post_render_callbacks)for(const e in this.post_render_callbacks)this.post_render_callbacks[e]()}if(this._currentFrameEvent=-1,this.connection.sendBufferedMessagesNow(),this._stats){this._stats.end();const e=this.time.fps<20?50:150;if(this.time.frameCount%e===0||this.time.frameCount===1){const t=window.performance&&window.performance.memory?`${(window.performance.memory.usedJSHeapSize/1024/1024).toFixed(2)} MB`:"n/a";console.log(this.renderer.info.render.calls+" DrawCalls",`
817
817
  Render:`,{shaders:this.renderer.info.programs?.length,...this.renderer.info.render},`
818
818
  Memory:`,{usedMemory:t,...this.renderer.info.memory},`
@@ -887,7 +887,7 @@ Target Framerate: `+this.targetFrameRate)}}this._dispatchReadyAfterFrame&&(this.
887
887
  padding-left: 25px;
888
888
  border-radius: .5em;
889
889
  border: 2px solid rgba(160,160,160,.3);
890
- `,i=`Needle Engine \u2014 No license active, commercial use is not allowed. Visit https://needle.tools/pricing for more information and licensing options! v${Ti}`;U.Current?.xr||navigator.webdriver?console.log(i):console.log("%c "+i,t)}async function kE(o){if(!window.crossOriginIsolated){if(!pi.isAllowed(o)){kt&&console.debug("Telemetry is disabled via no-telemetry attribute");return}try{const e="https://needle.tools/api/v1/needle-engine/ping";if(e){const t=window.location.href.split("?")[0],i={license:Rn,url:t,hostname:window.location.hostname,pathname:window.location.pathname,version:Ti,generator:Wa,build_time:wc,public_key:xs},n=navigator.sendBeacon?.(e,JSON.stringify(i));kt&&console.debug("Sent beacon: "+n)}}catch(e){kt&&console.log("Failed to send non-commercial usage message to analytics backend",e)}}}const ME=w("debugdecoders");let Rf=null;function qw(){if(!Rf){const o=Bm(null);Rf={dracoLoader:o.dracoLoader,ktx2Loader:o.ktx2Loader,meshoptDecoder:o.meshoptDecoder}}return Rf}function Xw(o){o!==void 0&&typeof o=="string"&&cP(o)}function Qw(o){if(o!==void 0&&typeof o=="string"&&o!=="js"){const e=qw();ME&&console.log("Setting draco decoder type to",o),e.dracoLoader.setDecoderConfig({type:o})}}function Yw(o){o!==void 0&&typeof o=="string"&&lP(o)}function Tf(o,e){const t=qw();return e.renderer?t.ktx2Loader.detectSupport(e.renderer):console.warn("No renderer provided to detect ktx2 support - loading KTX2 textures will probably fail"),rP(o),o.dracoLoader||o.setDRACOLoader(t.dracoLoader),o.ktx2Loader||o.setKTX2Loader(t.ktx2Loader),o.meshoptDecoder||o.setMeshoptDecoder(t.meshoptDecoder),aP(o,{progressive:!0}),o}const Qe=function(o){return u(o)},u=function(o){if(o===void 0&&(o=null),!Array.isArray(o))o=Zw(o);else for(let e=0;e<o.length;e++){const t=o[e];o[e]=Zw(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]=o}};function Zw(o){switch(o?.prototype?.constructor?.name){case"Number":case"String":case"Boolean":return null}return o}const Es=w("debughotreload");let $c=!1;const Hc=new Map;function EE(){return $c}function Af(){return globalThis.NEEDLE_HOT_RELOAD_ENABLED===!0}function Kw(o){if($c){Es&&console.warn("[Needle Engine] Hot reloading is in progress, not registering instance",o);return}Es&&console.log("[Needle Engine] Registering hot reload instance",o);const e=o.constructor.name;Hc.has(e)?Hc.get(e)?.push(o):Hc.set(e,[o])}function Jw(o){if($c){Es&&console.warn("[Needle Engine] Hot reloading is in progress, not unregistering instance",o);return}Es&&console.log("[Needle Engine] Unregistering hot reload instance",o);const e=o.constructor.name,t=Hc.get(e);if(!t)return;const i=t.indexOf(o);i!==-1&&t.splice(i,1)}let ex=!1;function RE(){if(Es||ex)return;ex=!0;const o=console.error;console.error=(...e)=>{if(e.length){const t=e[0];if(typeof t=="string"&&t.includes("[hmr] Failed to reload ")){console.log("[Needle Engine] Hot reloading failed"),window.location.reload();return}}o.apply(console,e)}}function TE(o){Es&&console.log("[HMR] Apply changes",o,Object.keys(o)),RE();for(const e of Object.keys(o))try{$c=!0;const t=C.get(e);if(!t){Es&&console.log("[HMR] Type not found: "+e);continue}const i=o[e],n=Hc.get(i.name);let s="[Needle Engine] Updating type: "+e;const r=n?.length??-1;r>0?s+=" x"+r:s+=" (No instances registered)",console.log(s);const a=Object.getOwnPropertyNames(t.prototype),l=Object.getOwnPropertyDescriptors(i.prototype);for(const c in l)l[c].writable&&(t.prototype[c]=o[e].prototype[c]);for(const c of a)l[c]||delete t.prototype[c];if(n){const c=new i,h=Object.getOwnPropertyDescriptors(c);for(const d of n){const p=d,m=p.isComponent===!0,g=m?p.activeAndEnabled:!0,f=m?p.context:void 0;try{if(m&&f&&jo(p,f),m&&g&&(p.enabled=!1),d.onBeforeHotReloadFields&&d.onBeforeHotReloadFields()===!1)continue;for(const y in h)if(h[y].writable){if(d[y]===void 0)d[y]=c[y];else if(typeof d[y]=="function"&&!d[y].prototype){const _=d[y],v=_.name,P="bound ";if(v===P)continue;const k=_.name.substring(P.length),O=i.prototype[k];O&&(d[y]=O.bind(d))}}d.onAfterHotReloadFields&&d.onAfterHotReloadFields()}finally{m&&f&&$g(p,f),m&&g&&(p.enabled=!0)}}}}catch(t){if(Es)console.error(t);else return!1}finally{$c=!1,xr(Ei.Log,"Script changes applied (HMR)")}return!0}class S extends M{guid;static isDestroyed(e){return Br(e)}static setActive(e,t,i=!0){e&&(zc(e,t),lu(e),t&&i&&jv(U.Current,e))}static isActiveSelf(e){return il(e)}static isActiveInHierarchy(e){return mw(e)}static markAsInstancedRendered(e,t){gw(e,t)}static isUsingInstancing(e){return yu(e)}static foreachComponent(e,t,i=!0){return Fr(e,t,i)}static instantiateSynced(e,t){return e?Zg(e,t):null}static instantiate(e,t=null){return"isAssetReference"in e,Ur(e,t)}static destroySynced(e,t,i=!0){if(!e)return;const n=e;t=t??U.Current,Lc(n,t.connection,i)}static destroy(e,t=!0){return Ii(e,t)}static add(e,t,i){if(!(!e||!t)){if(e===t){console.warn("Can not add object to self",e);return}i||(i=U.Current),t.add(e),zc(e,!0),lu(e),i?S.foreachComponent(e,n=>{$g(n,i),!n.__internalDidAwakeAndStart&&i.new_script_start.includes(n)===!1&&i.new_script_start.push(n)},!0):console.warn("Missing context")}}static remove(e){e&&(e.parent?.remove(e),zc(e,!1),lu(e),S.foreachComponent(e,t=>{pM(t)},!0))}static invokeOnChildren(e,t,...i){this.invoke(e,t,!0,i)}static invoke(e,t,i=!1,...n){e&&this.foreachComponent(e,s=>{const r=s[t];r&&typeof r=="function"&&r?.call(s,...n)},i)}static addNewComponent(e,t,i,n=!0){return Mn(e,t,i,{callAwake:n})}static addComponent(e,t,i,n){return Mn(e,t,i,n)}static moveComponent(e,t){return Mn(e,t)}static removeComponent(e){return lf(e.gameObject,e),e}static getOrAddComponent(e,t){return jc(e,t)}static getComponent(e,t){return e===null?null:Dr(e,t)}static getComponents(e,t,i=null){return e===null?i??[]:Bc(e,t,i)}static findByGuid(e,t){return cf(e,t)}static findObjectOfType(e,t,i=!0){return tl(e,t??U.Current,i)}static findObjectsOfType(e,t){const i=[];return pw(e,i,t),i}static getComponentInChildren(e,t,i=!1){return Fc(e,t,i)}static getComponentsInChildren(e,t,i=null){return el(e,t,i??void 0)}static getComponentInParent(e,t){return Uc(e,t)}static getComponentsInParent(e,t,i=null){return mu(e,t,i)}static getAllComponents(e){const t=e.userData?.components;return t?[...t]:[]}static*iterateComponents(e){const t=e?.userData?.components;if(t&&Array.isArray(t))for(let i=0;i<t.length;i++)yield t[i]}}class E{get isComponent(){return!0}get[W_](){return C.getKey(this.constructor)||void 0}__context;get context(){return this.__context??U.Current}set context(e){this.__context=e}get scene(){return this.context.scene}get layer(){return this.gameObject?.userData?.layer}get name(){return this.gameObject?.name?this.gameObject.name:this.gameObject?.userData.name}__name;set name(e){this.gameObject?(this.gameObject.userData||(this.gameObject.userData={}),this.gameObject.userData.name=e,this.__name=e):this.__name=e}get tag(){return this.gameObject?.userData.tag}set tag(e){this.gameObject&&(this.gameObject.userData||(this.gameObject.userData={}),this.gameObject.userData.tag=e)}get static(){return this.gameObject?.userData.static}set static(e){this.gameObject&&(this.gameObject.userData||(this.gameObject.userData={}),this.gameObject.userData.static=e)}get activeAndEnabled(){return!(this.destroyed||this.__isEnabled===!1||!this.__isActiveInHierarchy)}get __isActive(){return this.gameObject.visible}get __isActiveInHierarchy(){if(!this.gameObject)return!1;const e=this.gameObject[Ao];return e===void 0?!0:e}set __isActiveInHierarchy(e){this.gameObject&&(this.gameObject[Ao]=e)}gameObject;guid="invalid";sourceId;awake(){}onEnable(){}onDisable(){}onDestroy(){this.__destroyed=!0}startCoroutine(e,t=xe.Update){return this.context.registerCoroutineUpdate(this,e,t)}stopCoroutine(e,t=xe.Update){this.context.unregisterCoroutineUpdate(e,t)}get destroyed(){return this.__destroyed}destroy(){this.__destroyed||this.__internalDestroy()}__didAwake=!1;__didStart=!1;__didEnable=!1;__isEnabled=void 0;__destroyed=!1;get __internalDidAwakeAndStart(){return this.__didAwake&&this.__didStart}constructor(e){this.__didAwake=!1,this.__didStart=!1,this.__didEnable=!1,this.__isEnabled=void 0,this.__destroyed=!1,this._internalInit(e),Af()&&Kw(this)}__internalNewInstanceCreated(e){return this.__didAwake=!1,this.__didStart=!1,this.__didEnable=!1,this.__isEnabled=void 0,this.__destroyed=!1,this._internalInit(e),this}_internalInit(e){if(typeof e=="object")for(const t of Object.keys(e)){const i=e[t];typeof i!="function"&&(this[t]=i)}}__internalAwake(){this.__didAwake||(this.__didAwake=!0,this.awake())}__internalStart(){this.__didStart||(this.__didStart=!0,this.start&&this.start())}__internalEnable(e){return this.__destroyed?(A()&&console.warn("[Needle Engine Dev] Trying to enable destroyed component"),!1):this.__didAwake?this.__didEnable?(e!==!0&&(this.__isEnabled=!0),!1):(this.__didEnable=!0,this.__isEnabled=!0,this.onEnable(),!0):!1}__internalDisable(e){if(this.__didAwake){if(!this.__didEnable){e!==!0&&(this.__isEnabled=!1);return}this.__didEnable=!1,this.__isEnabled=!1,this.onDisable()}}__internalDestroy(){this.__destroyed||(this.__destroyed=!0,this.__didAwake&&(this.onDestroy?.call(this),this.dispatchEvent(new CustomEvent("destroyed",{detail:this}))),hw(this),Af()&&Jw(this))}get enabled(){return typeof this.__isEnabled=="boolean"?this.__isEnabled:!0}set enabled(e){if(this.__destroyed){A()&&console.warn(`[Needle Engine Dev] Trying to ${e?"enable":"disable"} destroyed component`);return}if(typeof e=="number"&&(e>=.5?e=!0:e=!1),!this.__didAwake){this.__isEnabled=e;return}e?this.__internalEnable():this.__internalDisable()}get worldPosition(){return ee(this.gameObject)}set worldPosition(e){yt(this.gameObject,e)}setWorldPosition(e,t,i){Sr(this.gameObject,e,t,i)}get worldQuaternion(){return _e(this.gameObject)}set worldQuaternion(e){Sn(this.gameObject,e)}setWorldQuaternion(e,t,i,n){lg(this.gameObject,e,t,i,n)}get worldEuler(){return cg(this.gameObject)}set worldEuler(e){hg(this.gameObject,e)}get worldRotation(){return this.gameObject.worldRotation}set worldRotation(e){this.setWorldRotation(e.x,e.y,e.z,!0)}setWorldRotation(e,t,i,n=!0){fc(this.gameObject,e,t,i,n)}static _forward=new b;get forward(){return E._forward.set(0,0,-1).applyQuaternion(this.worldQuaternion)}static _right=new b;get right(){return E._right.set(1,0,0).applyQuaternion(this.worldQuaternion)}static _up=new b;get up(){return E._up.set(0,1,0).applyQuaternion(this.worldQuaternion)}_eventListeners=new Map;addEventListener(e,t){this._eventListeners[e]=this._eventListeners[e]||[],this._eventListeners[e].push(t)}removeEventListener(e,t){if(!this._eventListeners[e])return;const i=this._eventListeners[e].indexOf(t);i>=0&&this._eventListeners[e].splice(i,1)}dispatchEvent(e){if(!e||!this._eventListeners[e.type])return!1;const t=this._eventListeners[e.type];for(let i=0;i<t.length;i++)t[i](e);return!1}}const AE=Object.freeze(Object.defineProperty({__proto__:null,Behaviour:E,Component:E,GameObject:S},Symbol.toStringTag,{value:"Module"}));var IE=Object.defineProperty,tx=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&IE(e,t,n),n};class Gc extends E{from;to;width=0;centered=!0;_centerPos;awake(){this._centerPos=new b}update(){if(!this.from||!this.to)return;const e=ee(this.from).clone(),t=ee(this.to).clone(),i=e.distanceTo(t);this._centerPos.copy(e),this._centerPos.add(t),this._centerPos.multiplyScalar(.5),yt(this.gameObject,this.centered?this._centerPos:e),this.gameObject.lookAt(ee(this.to).clone()),this.gameObject.scale.set(this.width,this.width,i)}}tx([u(S)],Gc.prototype,"from"),tx([u(S)],Gc.prototype,"to");var LE=Object.defineProperty,DE=Object.getOwnPropertyDescriptor,Nr=(o,e,t,i)=>{for(var n=i>1?void 0:i?DE(e,t):e,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&LE(e,t,n),n};const Rs=w("debuganimation");let ix=class{x;y};class Ut extends E{get isAnimationComponent(){return!0}addClip(e){this.animations||(this.animations=[]),this.animations.includes(e)||this.animations.push(e)}playAutomatically=!0;randomStartTime=!1;minMaxSpeed;minMaxOffsetNormalized;loop=!0;clampWhenFinished=!1;get time(){if(this.actions){for(const e of this.actions)if(e.isRunning())return e.time}return 0}set time(e){if(this.actions)for(const t of this.actions)t.time=e}get duration(){if(this.actions){for(const e of this.actions)if(e.isRunning())return e.getClip().duration}return 0}_tempAnimationClipBeforeGameObjectExisted=null;get clip(){return this.animations?.length?this.animations[0]:null}set clip(e){if(!this.__didAwake){Rs&&console.warn("Assign clip during serialization",e),this._tempAnimationClipBeforeGameObjectExisted=e;return}e&&(this.gameObject.animations||(this.gameObject.animations=[]),!this.animations.includes(e)&&(this.animations.length>0?this.animations.splice(0,0,e):this.animations.push(e)))}set clips(e){this.animations=e}_tempAnimationsArray;set animations(e){e==null||!Array.isArray(e)||(this.gameObject?this.gameObject.animations=e:this._tempAnimationsArray=e)}get animations(){return this.gameObject?.animations||this._tempAnimationsArray||[]}mixer=void 0;get actions(){return this._actions}set actions(e){this._actions=e}_actions;_handles;awake(){this.mixer=void 0,Rs&&console.log("Animation Awake",this.name,this),this._tempAnimationsArray&&(this.animations=this._tempAnimationsArray,this._tempAnimationsArray=void 0),this._tempAnimationClipBeforeGameObjectExisted&&(this.clip=this._tempAnimationClipBeforeGameObjectExisted,this._tempAnimationClipBeforeGameObjectExisted=null),this.actions=[],this._handles=[]}onEnable(){if(this.playAutomatically&&this.animations?.length>0){const e=Math.floor(Math.random()*this.animations.length),t=this.animations[e];this.play(e,{exclusive:!0,fadeDuration:0,startTime:this.randomStartTime?Math.random()*t.duration:0,loop:this.loop,clampWhenFinished:this.clampWhenFinished})}}update(){this.mixer&&(this.mixer.update(this.context.time.deltaTime),this._handles.forEach(e=>e.update()))}onDisable(){this.mixer&&this.mixer.stopAllAction()}onDestroy(){this.context.animations.unregisterAnimationMixer(this.mixer)}getAction(e){return this.actions?.find(t=>t.getClip().name===e)||null}get isPlaying(){if(this.actions){for(let e=0;e<this.actions.length;e++)if(this.actions[e].isRunning())return!0}return!1}stopAll(e){if(this.actions)for(const t of this.actions)e?.fadeDuration?t.fadeOut(e.fadeDuration):t.stop()}stop(e,t){if(e===void 0){this.stopAll();return}else if(typeof e=="number"){if(e>=this.animations.length){Rs&&console.log("No animation at index",e);return}e=this.animations[e]}else typeof e=="string"&&(e=this.animations.find(n=>n.name===e));if(!e){console.error("Could not find clip",e);return}const i=this.actions.find(n=>n.getClip()===e);if(!i){console.error("Could not find action",e);return}t?.fadeDuration?i.fadeOut(t.fadeDuration):i.stop()}pause(e,t=!1){if(e===void 0){for(const n of this.actions)n.paused=!t;return}else if(typeof e=="number"){if(e>=this.animations.length){Rs&&console.log("No animation at index",e);return}e=this.animations[e]}else typeof e=="string"&&(e=this.animations.find(n=>n.name===e));if(!e){console.error("Could not find clip",e);return}const i=this.actions.find(n=>n.getClip()===e);if(!i){console.error("Could not find action",e);return}i.paused=!t}resume(){for(const e of this.actions)e.paused=!1}play(e=0,t){if(Rs&&console.log("PLAY",e),this.ensureMixer(),!this.mixer){Rs&&console.warn("Missing mixer",this);return}e===void 0&&(e=0);let i=e;if(typeof e=="number"){if(e>=this.animations.length){Rs&&console.log("No animation at index",e);return}i=this.animations[e]}else typeof e=="string"&&(i=this.animations.find(s=>s.name===e));if(!i){console.error("Could not find clip",e);return}t||(t={});for(const s of this.actions)if(s.getClip()===i)return this.internalOnPlay(s,t);if(!i.tracks){console.warn("Clip is no AnimationClip",i);return}const n=this.mixer.clipAction(i);return this.actions.push(n),this.internalOnPlay(n,t)}internalOnPlay(e,t){var i=this.actions.find(s=>s===e);if(i===e&&i.isRunning()&&i.time<i.getClip().duration){const s=this.tryFindHandle(e);if(i.paused&&(i.paused=!1),s)return s.waitForFinish()}if(t.loop===void 0&&(t.loop=this.loop),t.clampWhenFinished===void 0&&(t.clampWhenFinished=this.clampWhenFinished),t.minMaxOffsetNormalized===void 0&&this.randomStartTime&&(t.minMaxOffsetNormalized=this.minMaxOffsetNormalized),t.minMaxSpeed===void 0&&(t.minMaxSpeed=this.minMaxSpeed),t?.exclusive??!0)for(const s of this.actions)s!=i&&(t.fadeDuration?s.fadeOut(t.fadeDuration):s.stop());if(t?.fadeDuration&&e.fadeIn(t.fadeDuration),e.enabled=!0,t?.startTime!=null)e.time=t.startTime;else if(t?.minMaxOffsetNormalized&&t.minMaxOffsetNormalized.x!=0&&t.minMaxOffsetNormalized.y!=0){const s=e.getClip();e.time=j.lerp(t.minMaxOffsetNormalized.x,t.minMaxOffsetNormalized.y,Math.random())*s.duration}else e.time>=e.getClip().duration&&(e.time=0);t?.minMaxSpeed?e.timeScale=j.lerp(t.minMaxSpeed.x,t.minMaxSpeed.y,Math.random()):e.timeScale=t?.speed??1,t?.loop!=null?e.loop=t.loop?rC:Rm:e.loop=Rm,t?.clampWhenFinished&&(e.clampWhenFinished=!0),e.paused=!1,e.play(),window.requestAnimationFrame(()=>Xn.testIfRootCanAnimate(e)),Rs&&console.log("PLAY",e.getClip().name,e);const n=new jE(e,this.mixer,t,s=>{this._handles.splice(this._handles.indexOf(n),1)});return this._handles.push(n),n.waitForFinish()}tryFindHandle(e){for(const t of this._handles)if(t.action===e)return t}ensureMixer(){if(!this.mixer){const e="animationMixer";this.gameObject[e]&&(this.mixer=this.gameObject[e]),(!this.mixer||!this.mixer.clipAction)&&(this.mixer=new Tm(this.gameObject),this.gameObject[e]=this.mixer)}this.context.animations.registerAnimationMixer(this.mixer)}}Nr([u()],Ut.prototype,"playAutomatically",2),Nr([u()],Ut.prototype,"randomStartTime",2),Nr([u(ix)],Ut.prototype,"minMaxSpeed",2),Nr([u(ix)],Ut.prototype,"minMaxOffsetNormalized",2),Nr([u()],Ut.prototype,"loop",2),Nr([u()],Ut.prototype,"clampWhenFinished",2),Nr([u(Oi)],Ut.prototype,"clips",1);class jE{mixer;action;promise=null;_options;_resolveCallback=null;_resolvedOrRejectedCallback;constructor(e,t,i,n){this.action=e,this.mixer=t,this._resolvedOrRejectedCallback=n,this._options=i}waitForFinish(){return this.promise?this.promise:(this.promise=new Promise(e=>{this._resolveCallback=e}),this.mixer.addEventListener("finished",this.onFinished),this.promise)}update(){this._options&&this._options.endTime!==void 0&&this.action.time>this._options.endTime&&(this._options.loop===!0?this.action.time=this._options.startTime??0:(this.action.time=this._options.endTime,this.action.timeScale=0,this.onResolve()))}onResolve(){this.dispose(),this._resolvedOrRejectedCallback?.call(this,this),this._resolveCallback?.call(this,this.action)}onFinished=e=>{e.action===this.action&&this.onResolve()};dispose(){this.mixer.removeEventListener("finished",this.onFinished)}}const Au=Symbol("objectIsAnimatedData");function nx(o,e,t){if(!o)return;if(o[Au]===void 0){if(!t)return;o[Au]=new Set}const i=o[Au];t?i.add(e):i.has(e)&&i.delete(e)}function BE(o){if(!o)return!1;const e=o[Au];return e!==void 0&&e.size>0}class FE{_context;get context(){return this._context??U.Current}get isStateMachineBehaviour(){return!0}}class qc{name;nameHash;normalizedTime;length;speed;action;hasTransitions;constructor(e,t,i,n){this.name=e.name,this.nameHash=e.hash,this.normalizedTime=t,this.length=i,this.speed=n,this.action=e.motion.action||null,this.hasTransitions=e.transitions?.length>0||!1}}function ox(o,e){return{name:"Empty",isLooping:!1,guid:e?.generateUUID()??So.generateUUID(),index:-1,clip:new Oi(o,0,[])}}var Ts=(o=>(o[o.If=1]="If",o[o.IfNot=2]="IfNot",o[o.Greater=3]="Greater",o[o.Less=4]="Less",o[o.Equals=6]="Equals",o[o.NotEqual=7]="NotEqual",o))(Ts||{}),If=(o=>(o[o.Float=1]="Float",o[o.Int=3]="Int",o[o.Bool=4]="Bool",o[o.Trigger=9]="Trigger",o))(If||{});const lt=w("debuganimatorcontroller"),Iu=w("debugrootmotion");class gn{static createFromClips(e,t={looping:!1,autoTransition:!0,transitionDuration:0}){const i=[];for(let s=0;s<e.length;s++){const r=e[s],a=[];if(t.autoTransition!==!1){const c=t.transitionDuration??0,h=c/r.duration;let d=s;(t.autoTransition===void 0||t.autoTransition===!0)&&(d=(s+1)%e.length),a.push({exitTime:1-h,offset:0,duration:c,hasExitTime:!0,destinationState:d,conditions:[]})}const l={name:r.name,hash:s,motion:{name:r.name,clip:r,isLooping:t?.looping??!1},transitions:a,behaviours:[]};i.push(l)}const n={name:"AnimatorController",guid:new Bt(Date.now()).generateUUID(),parameters:[],layers:[{name:"Base Layer",stateMachine:{defaultState:0,states:i}}]};return new gn(n)}play(e,t=-1,i=Number.NEGATIVE_INFINITY,n=0){if(t<0)t=0;else if(t>=this.model.layers.length){console.warn("invalid layer");return}const s=this.model.layers[t].stateMachine;for(const r of s.states)if(r.name===e||r.hash===e){lt&&console.log("transition to ",r),this.transitionTo(r,n,i);return}console.warn("Could not find "+e+" to play")}reset(){this.setStartTransition()}setBool(e,t){const i=typeof e=="string"?"name":"hash";return this.model?.parameters?.filter(n=>n[i]===e).forEach(n=>n.value=t)}getBool(e){const t=typeof e=="string"?"name":"hash";return this.model?.parameters?.find(i=>i[t]===e)?.value??!1}setFloat(e,t){const i=typeof e=="string"?"name":"hash",n=this.model?.parameters?.filter(s=>s[i]===e);return n.forEach(s=>s.value=t),n?.length>0}getFloat(e){const t=typeof e=="string"?"name":"hash";return this.model?.parameters?.find(i=>i[t]===e)?.value??0}setInteger(e,t){const i=typeof e=="string"?"name":"hash";return this.model?.parameters?.filter(n=>n[i]===e).forEach(n=>n.value=t)}getInteger(e){const t=typeof e=="string"?"name":"hash";return this.model?.parameters?.find(i=>i[t]===e)?.value??0}setTrigger(e){lt&&console.log("SET TRIGGER",e);const t=typeof e=="string"?"name":"hash";return this.model?.parameters?.filter(i=>i[t]===e).forEach(i=>i.value=!0)}resetTrigger(e){const t=typeof e=="string"?"name":"hash";return this.model?.parameters?.filter(i=>i[t]===e).forEach(i=>i.value=!1)}getTrigger(e){const t=typeof e=="string"?"name":"hash";return this.model?.parameters?.find(i=>i[t]===e)?.value??!1}isInTransition(){return this._activeStates.length>1}setSpeed(e){this._speed=e}_speed=1;FindState(e){return this.findState(e)}findState(e){if(!e)return null;if(Array.isArray(this.model.layers)){for(const t of this.model.layers)for(const i of t.stateMachine.states)if(i.name===e||i.hash==e)return i}return null}getCurrentStateInfo(){if(!this._activeState)return null;const e=this._activeState.motion.action;if(!e)return null;const t=this._activeState.motion.clip.duration,i=t<=0?0:Math.abs(e.time/t);return new qc(this._activeState,i,t,this._speed)}get currentAction(){return this._activeState&&this._activeState.motion.action||null}normalizedStartOffset=0;animator;model;get context(){return this.animator?.context}get mixer(){return this._mixer}dispose(){if(this._mixer.stopAllAction(),this.animator){this._mixer.uncacheRoot(this.animator.gameObject);for(const e of this._activeStates)e.motion.clip&&this.mixer.uncacheAction(e.motion.clip,this.animator.gameObject)}this.context?.animations.unregisterAnimationMixer(this._mixer)}bind(e){e?this.animator!==e&&(this._mixer&&(this._mixer.stopAllAction(),this.context?.animations.unregisterAnimationMixer(this._mixer)),this.animator=e,this._mixer=new Tm(this.animator.gameObject),this.context?.animations.registerAnimationMixer(this._mixer),this.createActions(this.animator)):console.error("AnimatorController.bind: animator is null")}clone(){if(typeof this.model=="string")return console.warn("AnimatorController has not been resolved, can not create model from string",this.model),null;lt&&console.warn("AnimatorController clone()",this.model);const e=pc(this.model,(t,i,n)=>n==null?!0:!(n.type==="Object3D"||n.isObject3D===!0||C_(n)||n.tracks!==void 0||n instanceof gn));return console.assert(e!==this.model),new gn(e)}update(e){if(!this.animator)return;this.evaluateTransitions(),this.updateActiveStates(e);const t=this.animator.context.time.deltaTime;this.animator.applyRootMotion&&this.rootMotionHandler?.onBeforeUpdate(e),this._mixer.update(t),this.animator.applyRootMotion&&this.rootMotionHandler?.onAfterUpdate(e)}_mixer;_activeState;get activeState(){return this._activeState}constructor(e){this.model=e,lt&&console.log(this)}_activeStates=[];updateActiveStates(e){for(let t=0;t<this._activeStates.length;t++){const i=this._activeStates[t],n=i.motion;if(!n.action)this._activeStates.splice(t,1),t--;else{const s=n.action;s.weight=e,s.getEffectiveWeight()<=0&&!s.isRunning()&&(lt&&console.debug("REMOVE",i.name,s.getEffectiveWeight(),s.isRunning(),s.isScheduled()),this._activeStates.splice(t,1),t--)}}}setStartTransition(){this.model.layers.length>1&&(lt||A())&&console.warn("Multiple layers are not supported yet "+this.animator?.name);for(const e of this.model.layers){const t=e.stateMachine;t.defaultState===void 0&&(lt&&console.warn("AnimatorController default state is undefined, will assign state 0 as default",e),t.defaultState=0);const i=t.states[t.defaultState];this.transitionTo(i,0,this.normalizedStartOffset);break}}evaluateTransitions(){let e=!1;if(!this._activeState){if(this.setStartTransition(),!this._activeState)return;e=!0}const t=this._activeState,i=t.motion.action;for(const s of t.transitions){if(!s.hasExitTime&&s.conditions.length<=0)continue;let r=!0;for(const a of s.conditions)if(!this.evaluateCondition(a)){r=!1;break}if(r)if(i){const a=t.motion.clip.duration,l=a<=0?1:Math.abs(i.time/a);let c=s.exitTime;i.timeScale<0&&(c=1-c);let h=!1;if(s.hasExitTime?i.timeScale>0?h=l>=s.exitTime:i.timeScale<0&&(h=1-l>=s.exitTime):h=!0,h){for(const d of s.conditions){const p=this.model.parameters.find(m=>m.name===d.parameter);p?.type===If.Trigger&&p.value&&(p.value=!1)}if(i.clampWhenFinished=!0,lt){const d=this.getState(s.destinationState,0);console.log(`Transition to ${s.destinationState} / ${d?.name}`,s,`
890
+ `,i=`Needle Engine \u2014 No license active, commercial use is not allowed. Visit https://needle.tools/pricing for more information and licensing options! v${Ti}`;U.Current?.xr||navigator.webdriver?console.log(i):console.log("%c "+i,t)}async function kE(o){if(!window.crossOriginIsolated){if(!pi.isAllowed(o)){kt&&console.debug("Telemetry is disabled via no-telemetry attribute");return}try{const e="https://needle.tools/api/v1/needle-engine/ping";if(e){const t=window.location.href.split("?")[0],i={license:Rn,url:t,hostname:window.location.hostname,pathname:window.location.pathname,version:Ti,generator:Wa,build_time:wc,public_key:xs},n=navigator.sendBeacon?.(e,JSON.stringify(i));kt&&console.debug("Sent beacon: "+n)}}catch(e){kt&&console.log("Failed to send non-commercial usage message to analytics backend",e)}}}const ME=w("debugdecoders");let Rf=null;function qw(){if(!Rf){const o=Bm(null);Rf={dracoLoader:o.dracoLoader,ktx2Loader:o.ktx2Loader,meshoptDecoder:o.meshoptDecoder}}return Rf}function Xw(o){o!==void 0&&typeof o=="string"&&cP(o)}function Qw(o){if(o!==void 0&&typeof o=="string"&&o!=="js"){const e=qw();ME&&console.log("Setting draco decoder type to",o),e.dracoLoader.setDecoderConfig({type:o})}}function Yw(o){o!==void 0&&typeof o=="string"&&lP(o)}function Tf(o,e){const t=qw();return e.renderer?t.ktx2Loader.detectSupport(e.renderer):console.warn("No renderer provided to detect ktx2 support - loading KTX2 textures will probably fail"),rP(o),o.dracoLoader||o.setDRACOLoader(t.dracoLoader),o.ktx2Loader||o.setKTX2Loader(t.ktx2Loader),o.meshoptDecoder||o.setMeshoptDecoder(t.meshoptDecoder),aP(o,{progressive:!0}),o}const Ye=function(o){return u(o)},u=function(o){if(o===void 0&&(o=null),!Array.isArray(o))o=Zw(o);else for(let e=0;e<o.length;e++){const t=o[e];o[e]=Zw(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]=o}};function Zw(o){switch(o?.prototype?.constructor?.name){case"Number":case"String":case"Boolean":return null}return o}const Es=w("debughotreload");let $c=!1;const Hc=new Map;function EE(){return $c}function Af(){return globalThis.NEEDLE_HOT_RELOAD_ENABLED===!0}function Kw(o){if($c){Es&&console.warn("[Needle Engine] Hot reloading is in progress, not registering instance",o);return}Es&&console.log("[Needle Engine] Registering hot reload instance",o);const e=o.constructor.name;Hc.has(e)?Hc.get(e)?.push(o):Hc.set(e,[o])}function Jw(o){if($c){Es&&console.warn("[Needle Engine] Hot reloading is in progress, not unregistering instance",o);return}Es&&console.log("[Needle Engine] Unregistering hot reload instance",o);const e=o.constructor.name,t=Hc.get(e);if(!t)return;const i=t.indexOf(o);i!==-1&&t.splice(i,1)}let ex=!1;function RE(){if(Es||ex)return;ex=!0;const o=console.error;console.error=(...e)=>{if(e.length){const t=e[0];if(typeof t=="string"&&t.includes("[hmr] Failed to reload ")){console.log("[Needle Engine] Hot reloading failed"),window.location.reload();return}}o.apply(console,e)}}function TE(o){Es&&console.log("[HMR] Apply changes",o,Object.keys(o)),RE();for(const e of Object.keys(o))try{$c=!0;const t=C.get(e);if(!t){Es&&console.log("[HMR] Type not found: "+e);continue}const i=o[e],n=Hc.get(i.name);let s="[Needle Engine] Updating type: "+e;const r=n?.length??-1;r>0?s+=" x"+r:s+=" (No instances registered)",console.log(s);const a=Object.getOwnPropertyNames(t.prototype),l=Object.getOwnPropertyDescriptors(i.prototype);for(const c in l)l[c].writable&&(t.prototype[c]=o[e].prototype[c]);for(const c of a)l[c]||delete t.prototype[c];if(n){const c=new i,h=Object.getOwnPropertyDescriptors(c);for(const d of n){const p=d,m=p.isComponent===!0,g=m?p.activeAndEnabled:!0,f=m?p.context:void 0;try{if(m&&f&&jo(p,f),m&&g&&(p.enabled=!1),d.onBeforeHotReloadFields&&d.onBeforeHotReloadFields()===!1)continue;for(const y in h)if(h[y].writable){if(d[y]===void 0)d[y]=c[y];else if(typeof d[y]=="function"&&!d[y].prototype){const _=d[y],v=_.name,P="bound ";if(v===P)continue;const k=_.name.substring(P.length),O=i.prototype[k];O&&(d[y]=O.bind(d))}}d.onAfterHotReloadFields&&d.onAfterHotReloadFields()}finally{m&&f&&$g(p,f),m&&g&&(p.enabled=!0)}}}}catch(t){if(Es)console.error(t);else return!1}finally{$c=!1,xr(Ei.Log,"Script changes applied (HMR)")}return!0}class S extends M{guid;static isDestroyed(e){return Br(e)}static setActive(e,t,i=!0){e&&(zc(e,t),lu(e),t&&i&&jv(U.Current,e))}static isActiveSelf(e){return il(e)}static isActiveInHierarchy(e){return mw(e)}static markAsInstancedRendered(e,t){gw(e,t)}static isUsingInstancing(e){return yu(e)}static foreachComponent(e,t,i=!0){return Fr(e,t,i)}static instantiateSynced(e,t){return e?Zg(e,t):null}static instantiate(e,t=null){return"isAssetReference"in e,Ur(e,t)}static destroySynced(e,t,i=!0){if(!e)return;const n=e;t=t??U.Current,Lc(n,t.connection,i)}static destroy(e,t=!0){return Ii(e,t)}static add(e,t,i){if(!(!e||!t)){if(e===t){console.warn("Can not add object to self",e);return}i||(i=U.Current),t.add(e),zc(e,!0),lu(e),i?S.foreachComponent(e,n=>{$g(n,i),!n.__internalDidAwakeAndStart&&i.new_script_start.includes(n)===!1&&i.new_script_start.push(n)},!0):console.warn("Missing context")}}static remove(e){e&&(e.parent?.remove(e),zc(e,!1),lu(e),S.foreachComponent(e,t=>{pM(t)},!0))}static invokeOnChildren(e,t,...i){this.invoke(e,t,!0,i)}static invoke(e,t,i=!1,...n){e&&this.foreachComponent(e,s=>{const r=s[t];r&&typeof r=="function"&&r?.call(s,...n)},i)}static addNewComponent(e,t,i,n=!0){return Mn(e,t,i,{callAwake:n})}static addComponent(e,t,i,n){return Mn(e,t,i,n)}static moveComponent(e,t){return Mn(e,t)}static removeComponent(e){return lf(e.gameObject,e),e}static getOrAddComponent(e,t){return jc(e,t)}static getComponent(e,t){return e===null?null:Dr(e,t)}static getComponents(e,t,i=null){return e===null?i??[]:Bc(e,t,i)}static findByGuid(e,t){return cf(e,t)}static findObjectOfType(e,t,i=!0){return tl(e,t??U.Current,i)}static findObjectsOfType(e,t){const i=[];return pw(e,i,t),i}static getComponentInChildren(e,t,i=!1){return Fc(e,t,i)}static getComponentsInChildren(e,t,i=null){return el(e,t,i??void 0)}static getComponentInParent(e,t){return Uc(e,t)}static getComponentsInParent(e,t,i=null){return mu(e,t,i)}static getAllComponents(e){const t=e.userData?.components;return t?[...t]:[]}static*iterateComponents(e){const t=e?.userData?.components;if(t&&Array.isArray(t))for(let i=0;i<t.length;i++)yield t[i]}}class E{get isComponent(){return!0}get[W_](){return C.getKey(this.constructor)||void 0}__context;get context(){return this.__context??U.Current}set context(e){this.__context=e}get scene(){return this.context.scene}get layer(){return this.gameObject?.userData?.layer}get name(){return this.gameObject?.name?this.gameObject.name:this.gameObject?.userData.name}__name;set name(e){this.gameObject?(this.gameObject.userData||(this.gameObject.userData={}),this.gameObject.userData.name=e,this.__name=e):this.__name=e}get tag(){return this.gameObject?.userData.tag}set tag(e){this.gameObject&&(this.gameObject.userData||(this.gameObject.userData={}),this.gameObject.userData.tag=e)}get static(){return this.gameObject?.userData.static}set static(e){this.gameObject&&(this.gameObject.userData||(this.gameObject.userData={}),this.gameObject.userData.static=e)}get activeAndEnabled(){return!(this.destroyed||this.__isEnabled===!1||!this.__isActiveInHierarchy)}get __isActive(){return this.gameObject.visible}get __isActiveInHierarchy(){if(!this.gameObject)return!1;const e=this.gameObject[Ao];return e===void 0?!0:e}set __isActiveInHierarchy(e){this.gameObject&&(this.gameObject[Ao]=e)}gameObject;guid="invalid";sourceId;awake(){}onEnable(){}onDisable(){}onDestroy(){this.__destroyed=!0}startCoroutine(e,t=xe.Update){return this.context.registerCoroutineUpdate(this,e,t)}stopCoroutine(e,t=xe.Update){this.context.unregisterCoroutineUpdate(e,t)}get destroyed(){return this.__destroyed}destroy(){this.__destroyed||this.__internalDestroy()}__didAwake=!1;__didStart=!1;__didEnable=!1;__isEnabled=void 0;__destroyed=!1;get __internalDidAwakeAndStart(){return this.__didAwake&&this.__didStart}constructor(e){this.__didAwake=!1,this.__didStart=!1,this.__didEnable=!1,this.__isEnabled=void 0,this.__destroyed=!1,this._internalInit(e),Af()&&Kw(this)}__internalNewInstanceCreated(e){return this.__didAwake=!1,this.__didStart=!1,this.__didEnable=!1,this.__isEnabled=void 0,this.__destroyed=!1,this._internalInit(e),this}_internalInit(e){if(typeof e=="object")for(const t of Object.keys(e)){const i=e[t];typeof i!="function"&&(this[t]=i)}}__internalAwake(){this.__didAwake||(this.__didAwake=!0,this.awake())}__internalStart(){this.__didStart||(this.__didStart=!0,this.start&&this.start())}__internalEnable(e){return this.__destroyed?(A()&&console.warn("[Needle Engine Dev] Trying to enable destroyed component"),!1):this.__didAwake?this.__didEnable?(e!==!0&&(this.__isEnabled=!0),!1):(this.__didEnable=!0,this.__isEnabled=!0,this.onEnable(),!0):!1}__internalDisable(e){if(this.__didAwake){if(!this.__didEnable){e!==!0&&(this.__isEnabled=!1);return}this.__didEnable=!1,this.__isEnabled=!1,this.onDisable()}}__internalDestroy(){this.__destroyed||(this.__destroyed=!0,this.__didAwake&&(this.onDestroy?.call(this),this.dispatchEvent(new CustomEvent("destroyed",{detail:this}))),hw(this),Af()&&Jw(this))}get enabled(){return typeof this.__isEnabled=="boolean"?this.__isEnabled:!0}set enabled(e){if(this.__destroyed){A()&&console.warn(`[Needle Engine Dev] Trying to ${e?"enable":"disable"} destroyed component`);return}if(typeof e=="number"&&(e>=.5?e=!0:e=!1),!this.__didAwake){this.__isEnabled=e;return}e?this.__internalEnable():this.__internalDisable()}get worldPosition(){return ee(this.gameObject)}set worldPosition(e){yt(this.gameObject,e)}setWorldPosition(e,t,i){Sr(this.gameObject,e,t,i)}get worldQuaternion(){return _e(this.gameObject)}set worldQuaternion(e){Sn(this.gameObject,e)}setWorldQuaternion(e,t,i,n){lg(this.gameObject,e,t,i,n)}get worldEuler(){return cg(this.gameObject)}set worldEuler(e){hg(this.gameObject,e)}get worldRotation(){return this.gameObject.worldRotation}set worldRotation(e){this.setWorldRotation(e.x,e.y,e.z,!0)}setWorldRotation(e,t,i,n=!0){fc(this.gameObject,e,t,i,n)}static _forward=new b;get forward(){return E._forward.set(0,0,-1).applyQuaternion(this.worldQuaternion)}static _right=new b;get right(){return E._right.set(1,0,0).applyQuaternion(this.worldQuaternion)}static _up=new b;get up(){return E._up.set(0,1,0).applyQuaternion(this.worldQuaternion)}_eventListeners=new Map;addEventListener(e,t){this._eventListeners[e]=this._eventListeners[e]||[],this._eventListeners[e].push(t)}removeEventListener(e,t){if(!this._eventListeners[e])return;const i=this._eventListeners[e].indexOf(t);i>=0&&this._eventListeners[e].splice(i,1)}dispatchEvent(e){if(!e||!this._eventListeners[e.type])return!1;const t=this._eventListeners[e.type];for(let i=0;i<t.length;i++)t[i](e);return!1}}const AE=Object.freeze(Object.defineProperty({__proto__:null,Behaviour:E,Component:E,GameObject:S},Symbol.toStringTag,{value:"Module"}));var IE=Object.defineProperty,tx=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&IE(e,t,n),n};class Gc extends E{from;to;width=0;centered=!0;_centerPos;awake(){this._centerPos=new b}update(){if(!this.from||!this.to)return;const e=ee(this.from).clone(),t=ee(this.to).clone(),i=e.distanceTo(t);this._centerPos.copy(e),this._centerPos.add(t),this._centerPos.multiplyScalar(.5),yt(this.gameObject,this.centered?this._centerPos:e),this.gameObject.lookAt(ee(this.to).clone()),this.gameObject.scale.set(this.width,this.width,i)}}tx([u(S)],Gc.prototype,"from"),tx([u(S)],Gc.prototype,"to");var LE=Object.defineProperty,DE=Object.getOwnPropertyDescriptor,Nr=(o,e,t,i)=>{for(var n=i>1?void 0:i?DE(e,t):e,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&LE(e,t,n),n};const Rs=w("debuganimation");let ix=class{x;y};class Ut extends E{get isAnimationComponent(){return!0}addClip(e){this.animations||(this.animations=[]),this.animations.includes(e)||this.animations.push(e)}playAutomatically=!0;randomStartTime=!1;minMaxSpeed;minMaxOffsetNormalized;loop=!0;clampWhenFinished=!1;get time(){if(this.actions){for(const e of this.actions)if(e.isRunning())return e.time}return 0}set time(e){if(this.actions)for(const t of this.actions)t.time=e}get duration(){if(this.actions){for(const e of this.actions)if(e.isRunning())return e.getClip().duration}return 0}_tempAnimationClipBeforeGameObjectExisted=null;get clip(){return this.animations?.length?this.animations[0]:null}set clip(e){if(!this.__didAwake){Rs&&console.warn("Assign clip during serialization",e),this._tempAnimationClipBeforeGameObjectExisted=e;return}e&&(this.gameObject.animations||(this.gameObject.animations=[]),!this.animations.includes(e)&&(this.animations.length>0?this.animations.splice(0,0,e):this.animations.push(e)))}set clips(e){this.animations=e}_tempAnimationsArray;set animations(e){e==null||!Array.isArray(e)||(this.gameObject?this.gameObject.animations=e:this._tempAnimationsArray=e)}get animations(){return this.gameObject?.animations||this._tempAnimationsArray||[]}mixer=void 0;get actions(){return this._actions}set actions(e){this._actions=e}_actions;_handles;awake(){this.mixer=void 0,Rs&&console.log("Animation Awake",this.name,this),this._tempAnimationsArray&&(this.animations=this._tempAnimationsArray,this._tempAnimationsArray=void 0),this._tempAnimationClipBeforeGameObjectExisted&&(this.clip=this._tempAnimationClipBeforeGameObjectExisted,this._tempAnimationClipBeforeGameObjectExisted=null),this.actions=[],this._handles=[]}onEnable(){if(this.playAutomatically&&this.animations?.length>0){const e=Math.floor(Math.random()*this.animations.length),t=this.animations[e];this.play(e,{exclusive:!0,fadeDuration:0,startTime:this.randomStartTime?Math.random()*t.duration:0,loop:this.loop,clampWhenFinished:this.clampWhenFinished})}}update(){this.mixer&&(this.mixer.update(this.context.time.deltaTime),this._handles.forEach(e=>e.update()))}onDisable(){this.mixer&&this.mixer.stopAllAction()}onDestroy(){this.context.animations.unregisterAnimationMixer(this.mixer)}getAction(e){return this.actions?.find(t=>t.getClip().name===e)||null}get isPlaying(){if(this.actions){for(let e=0;e<this.actions.length;e++)if(this.actions[e].isRunning())return!0}return!1}stopAll(e){if(this.actions)for(const t of this.actions)e?.fadeDuration?t.fadeOut(e.fadeDuration):t.stop()}stop(e,t){if(e===void 0){this.stopAll();return}else if(typeof e=="number"){if(e>=this.animations.length){Rs&&console.log("No animation at index",e);return}e=this.animations[e]}else typeof e=="string"&&(e=this.animations.find(n=>n.name===e));if(!e){console.error("Could not find clip",e);return}const i=this.actions.find(n=>n.getClip()===e);if(!i){console.error("Could not find action",e);return}t?.fadeDuration?i.fadeOut(t.fadeDuration):i.stop()}pause(e,t=!1){if(e===void 0){for(const n of this.actions)n.paused=!t;return}else if(typeof e=="number"){if(e>=this.animations.length){Rs&&console.log("No animation at index",e);return}e=this.animations[e]}else typeof e=="string"&&(e=this.animations.find(n=>n.name===e));if(!e){console.error("Could not find clip",e);return}const i=this.actions.find(n=>n.getClip()===e);if(!i){console.error("Could not find action",e);return}i.paused=!t}resume(){for(const e of this.actions)e.paused=!1}play(e=0,t){if(Rs&&console.log("PLAY",e),this.ensureMixer(),!this.mixer){Rs&&console.warn("Missing mixer",this);return}e===void 0&&(e=0);let i=e;if(typeof e=="number"){if(e>=this.animations.length){Rs&&console.log("No animation at index",e);return}i=this.animations[e]}else typeof e=="string"&&(i=this.animations.find(s=>s.name===e));if(!i){console.error("Could not find clip",e);return}t||(t={});for(const s of this.actions)if(s.getClip()===i)return this.internalOnPlay(s,t);if(!i.tracks){console.warn("Clip is no AnimationClip",i);return}const n=this.mixer.clipAction(i);return this.actions.push(n),this.internalOnPlay(n,t)}internalOnPlay(e,t){var i=this.actions.find(s=>s===e);if(i===e&&i.isRunning()&&i.time<i.getClip().duration){const s=this.tryFindHandle(e);if(i.paused&&(i.paused=!1),s)return s.waitForFinish()}if(t.loop===void 0&&(t.loop=this.loop),t.clampWhenFinished===void 0&&(t.clampWhenFinished=this.clampWhenFinished),t.minMaxOffsetNormalized===void 0&&this.randomStartTime&&(t.minMaxOffsetNormalized=this.minMaxOffsetNormalized),t.minMaxSpeed===void 0&&(t.minMaxSpeed=this.minMaxSpeed),t?.exclusive??!0)for(const s of this.actions)s!=i&&(t.fadeDuration?s.fadeOut(t.fadeDuration):s.stop());if(t?.fadeDuration&&e.fadeIn(t.fadeDuration),e.enabled=!0,t?.startTime!=null)e.time=t.startTime;else if(t?.minMaxOffsetNormalized&&t.minMaxOffsetNormalized.x!=0&&t.minMaxOffsetNormalized.y!=0){const s=e.getClip();e.time=j.lerp(t.minMaxOffsetNormalized.x,t.minMaxOffsetNormalized.y,Math.random())*s.duration}else e.time>=e.getClip().duration&&(e.time=0);t?.minMaxSpeed?e.timeScale=j.lerp(t.minMaxSpeed.x,t.minMaxSpeed.y,Math.random()):e.timeScale=t?.speed??1,t?.loop!=null?e.loop=t.loop?rC:Rm:e.loop=Rm,t?.clampWhenFinished&&(e.clampWhenFinished=!0),e.paused=!1,e.play(),window.requestAnimationFrame(()=>Xn.testIfRootCanAnimate(e)),Rs&&console.log("PLAY",e.getClip().name,e);const n=new jE(e,this.mixer,t,s=>{this._handles.splice(this._handles.indexOf(n),1)});return this._handles.push(n),n.waitForFinish()}tryFindHandle(e){for(const t of this._handles)if(t.action===e)return t}ensureMixer(){if(!this.mixer){const e="animationMixer";this.gameObject[e]&&(this.mixer=this.gameObject[e]),(!this.mixer||!this.mixer.clipAction)&&(this.mixer=new Tm(this.gameObject),this.gameObject[e]=this.mixer)}this.context.animations.registerAnimationMixer(this.mixer)}}Nr([u()],Ut.prototype,"playAutomatically",2),Nr([u()],Ut.prototype,"randomStartTime",2),Nr([u(ix)],Ut.prototype,"minMaxSpeed",2),Nr([u(ix)],Ut.prototype,"minMaxOffsetNormalized",2),Nr([u()],Ut.prototype,"loop",2),Nr([u()],Ut.prototype,"clampWhenFinished",2),Nr([u(Oi)],Ut.prototype,"clips",1);class jE{mixer;action;promise=null;_options;_resolveCallback=null;_resolvedOrRejectedCallback;constructor(e,t,i,n){this.action=e,this.mixer=t,this._resolvedOrRejectedCallback=n,this._options=i}waitForFinish(){return this.promise?this.promise:(this.promise=new Promise(e=>{this._resolveCallback=e}),this.mixer.addEventListener("finished",this.onFinished),this.promise)}update(){this._options&&this._options.endTime!==void 0&&this.action.time>this._options.endTime&&(this._options.loop===!0?this.action.time=this._options.startTime??0:(this.action.time=this._options.endTime,this.action.timeScale=0,this.onResolve()))}onResolve(){this.dispose(),this._resolvedOrRejectedCallback?.call(this,this),this._resolveCallback?.call(this,this.action)}onFinished=e=>{e.action===this.action&&this.onResolve()};dispose(){this.mixer.removeEventListener("finished",this.onFinished)}}const Au=Symbol("objectIsAnimatedData");function nx(o,e,t){if(!o)return;if(o[Au]===void 0){if(!t)return;o[Au]=new Set}const i=o[Au];t?i.add(e):i.has(e)&&i.delete(e)}function BE(o){if(!o)return!1;const e=o[Au];return e!==void 0&&e.size>0}class FE{_context;get context(){return this._context??U.Current}get isStateMachineBehaviour(){return!0}}class qc{name;nameHash;normalizedTime;length;speed;action;hasTransitions;constructor(e,t,i,n){this.name=e.name,this.nameHash=e.hash,this.normalizedTime=t,this.length=i,this.speed=n,this.action=e.motion.action||null,this.hasTransitions=e.transitions?.length>0||!1}}function ox(o,e){return{name:"Empty",isLooping:!1,guid:e?.generateUUID()??So.generateUUID(),index:-1,clip:new Oi(o,0,[])}}var Ts=(o=>(o[o.If=1]="If",o[o.IfNot=2]="IfNot",o[o.Greater=3]="Greater",o[o.Less=4]="Less",o[o.Equals=6]="Equals",o[o.NotEqual=7]="NotEqual",o))(Ts||{}),If=(o=>(o[o.Float=1]="Float",o[o.Int=3]="Int",o[o.Bool=4]="Bool",o[o.Trigger=9]="Trigger",o))(If||{});const lt=w("debuganimatorcontroller"),Iu=w("debugrootmotion");class gn{static createFromClips(e,t={looping:!1,autoTransition:!0,transitionDuration:0}){const i=[];for(let s=0;s<e.length;s++){const r=e[s],a=[];if(t.autoTransition!==!1){const c=t.transitionDuration??0,h=c/r.duration;let d=s;(t.autoTransition===void 0||t.autoTransition===!0)&&(d=(s+1)%e.length),a.push({exitTime:1-h,offset:0,duration:c,hasExitTime:!0,destinationState:d,conditions:[]})}const l={name:r.name,hash:s,motion:{name:r.name,clip:r,isLooping:t?.looping??!1},transitions:a,behaviours:[]};i.push(l)}const n={name:"AnimatorController",guid:new Bt(Date.now()).generateUUID(),parameters:[],layers:[{name:"Base Layer",stateMachine:{defaultState:0,states:i}}]};return new gn(n)}play(e,t=-1,i=Number.NEGATIVE_INFINITY,n=0){if(t<0)t=0;else if(t>=this.model.layers.length){console.warn("invalid layer");return}const s=this.model.layers[t].stateMachine;for(const r of s.states)if(r.name===e||r.hash===e){lt&&console.log("transition to ",r),this.transitionTo(r,n,i);return}console.warn("Could not find "+e+" to play")}reset(){this.setStartTransition()}setBool(e,t){const i=typeof e=="string"?"name":"hash";return this.model?.parameters?.filter(n=>n[i]===e).forEach(n=>n.value=t)}getBool(e){const t=typeof e=="string"?"name":"hash";return this.model?.parameters?.find(i=>i[t]===e)?.value??!1}setFloat(e,t){const i=typeof e=="string"?"name":"hash",n=this.model?.parameters?.filter(s=>s[i]===e);return n.forEach(s=>s.value=t),n?.length>0}getFloat(e){const t=typeof e=="string"?"name":"hash";return this.model?.parameters?.find(i=>i[t]===e)?.value??0}setInteger(e,t){const i=typeof e=="string"?"name":"hash";return this.model?.parameters?.filter(n=>n[i]===e).forEach(n=>n.value=t)}getInteger(e){const t=typeof e=="string"?"name":"hash";return this.model?.parameters?.find(i=>i[t]===e)?.value??0}setTrigger(e){lt&&console.log("SET TRIGGER",e);const t=typeof e=="string"?"name":"hash";return this.model?.parameters?.filter(i=>i[t]===e).forEach(i=>i.value=!0)}resetTrigger(e){const t=typeof e=="string"?"name":"hash";return this.model?.parameters?.filter(i=>i[t]===e).forEach(i=>i.value=!1)}getTrigger(e){const t=typeof e=="string"?"name":"hash";return this.model?.parameters?.find(i=>i[t]===e)?.value??!1}isInTransition(){return this._activeStates.length>1}setSpeed(e){this._speed=e}_speed=1;FindState(e){return this.findState(e)}findState(e){if(!e)return null;if(Array.isArray(this.model.layers)){for(const t of this.model.layers)for(const i of t.stateMachine.states)if(i.name===e||i.hash==e)return i}return null}getCurrentStateInfo(){if(!this._activeState)return null;const e=this._activeState.motion.action;if(!e)return null;const t=this._activeState.motion.clip.duration,i=t<=0?0:Math.abs(e.time/t);return new qc(this._activeState,i,t,this._speed)}get currentAction(){return this._activeState&&this._activeState.motion.action||null}normalizedStartOffset=0;animator;model;get context(){return this.animator?.context}get mixer(){return this._mixer}dispose(){if(this._mixer.stopAllAction(),this.animator){this._mixer.uncacheRoot(this.animator.gameObject);for(const e of this._activeStates)e.motion.clip&&this.mixer.uncacheAction(e.motion.clip,this.animator.gameObject)}this.context?.animations.unregisterAnimationMixer(this._mixer)}bind(e){e?this.animator!==e&&(this._mixer&&(this._mixer.stopAllAction(),this.context?.animations.unregisterAnimationMixer(this._mixer)),this.animator=e,this._mixer=new Tm(this.animator.gameObject),this.context?.animations.registerAnimationMixer(this._mixer),this.createActions(this.animator)):console.error("AnimatorController.bind: animator is null")}clone(){if(typeof this.model=="string")return console.warn("AnimatorController has not been resolved, can not create model from string",this.model),null;lt&&console.warn("AnimatorController clone()",this.model);const e=pc(this.model,(t,i,n)=>n==null?!0:!(n.type==="Object3D"||n.isObject3D===!0||C_(n)||n.tracks!==void 0||n instanceof gn));return console.assert(e!==this.model),new gn(e)}update(e){if(!this.animator)return;this.evaluateTransitions(),this.updateActiveStates(e);const t=this.animator.context.time.deltaTime;this.animator.applyRootMotion&&this.rootMotionHandler?.onBeforeUpdate(e),this._mixer.update(t),this.animator.applyRootMotion&&this.rootMotionHandler?.onAfterUpdate(e)}_mixer;_activeState;get activeState(){return this._activeState}constructor(e){this.model=e,lt&&console.log(this)}_activeStates=[];updateActiveStates(e){for(let t=0;t<this._activeStates.length;t++){const i=this._activeStates[t],n=i.motion;if(!n.action)this._activeStates.splice(t,1),t--;else{const s=n.action;s.weight=e,s.getEffectiveWeight()<=0&&!s.isRunning()&&(lt&&console.debug("REMOVE",i.name,s.getEffectiveWeight(),s.isRunning(),s.isScheduled()),this._activeStates.splice(t,1),t--)}}}setStartTransition(){this.model.layers.length>1&&(lt||A())&&console.warn("Multiple layers are not supported yet "+this.animator?.name);for(const e of this.model.layers){const t=e.stateMachine;t.defaultState===void 0&&(lt&&console.warn("AnimatorController default state is undefined, will assign state 0 as default",e),t.defaultState=0);const i=t.states[t.defaultState];this.transitionTo(i,0,this.normalizedStartOffset);break}}evaluateTransitions(){let e=!1;if(!this._activeState){if(this.setStartTransition(),!this._activeState)return;e=!0}const t=this._activeState,i=t.motion.action;for(const s of t.transitions){if(!s.hasExitTime&&s.conditions.length<=0)continue;let r=!0;for(const a of s.conditions)if(!this.evaluateCondition(a)){r=!1;break}if(r)if(i){const a=t.motion.clip.duration,l=a<=0?1:Math.abs(i.time/a);let c=s.exitTime;i.timeScale<0&&(c=1-c);let h=!1;if(s.hasExitTime?i.timeScale>0?h=l>=s.exitTime:i.timeScale<0&&(h=1-l>=s.exitTime):h=!0,h){for(const d of s.conditions){const p=this.model.parameters.find(m=>m.name===d.parameter);p?.type===If.Trigger&&p.value&&(p.value=!1)}if(i.clampWhenFinished=!0,lt){const d=this.getState(s.destinationState,0);console.log(`Transition to ${s.destinationState} / ${d?.name}`,s,`
891
891
  Timescale: `+i.timeScale,`
892
892
  Normalized time: `+l.toFixed(3),`
893
893
  Exit Time: `+c,s.hasExitTime)}this.transitionTo(s.destinationState,s.duration,s.offset);return}}else{this.transitionTo(s.destinationState,s.duration,s.offset);return}}i&&this.setTimescale(i,t);let n=!1;if(t.motion.isLooping&&i&&(i.time>=i.getClip().duration?(n=!0,i.reset(),i.time=0,i.play()):i.time<=0&&i.timeScale<0&&(n=!0,i.reset(),i.time=i.getClip().duration,i.play())),!n&&t&&!e&&i&&this.animator&&t.behaviours){const s=i?.getClip().duration,r=i.time/s,a=new qc(this._activeState,r,s,this._speed);for(const l of t.behaviours)l.instance&&l.instance.onStateUpdate?.call(l.instance,this.animator,a,0)}}setTimescale(e,t){let i=t.speed??1;t.speedParameter&&(i*=this.getFloat(t.speedParameter)),i!==void 0&&(e.timeScale=i*this._speed)}getState(e,t){return typeof e=="number"&&(e==-1&&(e=this.model.layers[t].stateMachine.defaultState,e===void 0&&(lt&&console.warn("AnimatorController default state is undefined: ",this.model,"Layer: "+t),e=0)),e=this.model.layers[t].stateMachine.states[e]),e}_heldActions=[];releaseHeldActions(e){for(const t of this._heldActions)t.fadeOut(e);this._heldActions.length=0}transitionTo(e,t,i){if(!this.animator)return;const n=0;if(e=this.getState(e,n),!e?.motion||!e.motion.clip||!(e.motion.clip instanceof Oi))return;const s=this._activeState===e;if(s){const h=e.motion;if(!h.action_loopback&&h.clip){const d=this.rootMotionHandler?this.animator.gameObject.matrix.clone():null;this._mixer.uncacheAction(h.clip,this.animator.gameObject),d&&d.decompose(this.animator.gameObject.position,this.animator.gameObject.quaternion,this.animator.gameObject.scale),h.action_loopback=this.createAction(h.clip)}}if(this._activeState?.behaviours&&this._activeState.motion.action){const h=this._activeState?.motion.clip.duration,d=this._activeState.motion.action.time/h,p=new qc(this._activeState,d,h,this._speed);for(const m of this._activeState.behaviours)m.instance?.onStateExit?.call(m.instance,this.animator,p,n)}const r=this._activeState?.motion.action;s&&(e.motion.action=e.motion.action_loopback,e.motion.action_loopback=r);const a=this._activeState;this._activeState=e;const l=e.motion?.action,c=e.motion.clip;if(c?.duration<=0&&c.tracks.length<=0?r&&this._heldActions.push(r):r&&(r.fadeOut(t),this.releaseHeldActions(t)),l){if(i=Math.max(0,Math.min(1,i)),e.cycleOffsetParameter){let d=this.getFloat(e.cycleOffsetParameter);typeof d=="number"?(d<0&&(d+=1),i+=d,i%=1):lt&&console.warn("AnimatorController cycle offset parameter is not a number",e.cycleOffsetParameter)}else typeof e.cycleOffset=="number"&&(i+=e.cycleOffset,i%=1);l.isRunning()&&l.stop(),l.reset(),l.enabled=!0,this.setTimescale(l,e);const h=e.motion.clip.duration;if(l.time=s?0:i*h,l.timeScale<0&&(l.time=h-l.time),l.clampWhenFinished=!0,l.setLoop(Rm,0),t>0?l.fadeIn(t):l.weight=1,l.play(),window.requestAnimationFrame(()=>Xn.testIfRootCanAnimate(l)),this.rootMotionHandler&&this.rootMotionHandler.onStart(l),this._activeStates.includes(e)||this._activeStates.push(e),this._activeState.behaviours){const d=new qc(e,i,h,this._speed);for(const p of this._activeState.behaviours)p.instance?.onStateEnter?.call(p.instance,this.animator,d,n)}}else lt&&(e.__warned_no_motion||(e.__warned_no_motion=!0,console.warn("No action",e.motion,this)));lt&&console.log("TRANSITION FROM "+a?.name+" TO "+e.name,t,r,l,l?.getEffectiveTimeScale(),l?.getEffectiveWeight(),l?.isRunning(),l?.isScheduled(),l?.paused)}createAction(e){if(this._mixer.existingAction(e)&&this._mixer.uncacheAction(e,this.animator?.gameObject),this.animator?.applyRootMotion){this.rootMotionHandler||(this.rootMotionHandler=new UE(this));const t=this.animator.gameObject;return this.rootMotionHandler.createClip(this._mixer,t,e)}else return this._mixer.clipAction(e)}evaluateCondition(e){const t=this.model.parameters.find(i=>i.name===e.parameter);if(!t)return!1;switch(e.mode){case Ts.If:return t.value===!0;case Ts.IfNot:return t.value===!1;case Ts.Greater:return t.value>e.threshold;case Ts.Less:return t.value<e.threshold;case Ts.Equals:return t.value===e.threshold;case Ts.NotEqual:return t.value!==e.threshold}return!1}createActions(e){lt&&console.log("AnimatorController createActions",this.model);for(const t of this.model.layers){const i=t.stateMachine;for(let n=0;n<i.states.length;n++){const s=i.states[n];s.transitions||(s.transitions=[]);for(const r of s.transitions)r.conditions||(r.conditions=[]);if(s.motion||(lt&&console.warn("No motion",s),s.motion=ox(s.name)),this.animator&&s.motion.clips){const r=s.motion.clips?.find(a=>a.node.name===this.animator?.gameObject?.name);r?s.motion.clip=r.clip:(lt||A())&&console.warn('Could not find clip for animator "'+this.animator?.gameObject?.name+'"',s.motion.clips.map(a=>a.node.name))}if(!s.motion.clip){lt&&console.warn("No clip assigned to state",s);const r=new Oi(void 0,void 0,[]);s.motion.clip=r}if(s.motion?.clip){const r=s.motion.clip;if(r instanceof Oi){const a=this.createAction(r);s.motion.action=a}else(lt||A())&&console.warn("No valid animationclip assigned",s)}if(s.behaviours&&Array.isArray(s.behaviours))for(const r of s.behaviours){if(!r?.typeName)continue;const a=C.get(r.typeName);if(a){const l=new a;l.isStateMachineBehaviour&&(l._context=this.context??void 0,Ja(l,r.properties),r.instance=l),lt&&console.log("Created animator controller behaviour",s.name,r.typeName,r.properties,l)}else(lt||A())&&console.warn("Could not find AnimatorBehaviour type: "+r.typeName)}}}}*enumerateActions(){if(this.model.layers)for(const e of this.model.layers){const t=e.stateMachine;for(let i=0;i<t.states.length;i++){const n=t.states[i];n?.motion&&(n.motion.action&&(yield n.motion.action),n.motion.action_loopback&&(yield n.motion.action_loopback))}}}rootMotionHandler}class sx{track;createdInterpolant;originalEvaluate;customEvaluate;constructor(e,t){this.track=e;const i=e,n=i.createInterpolant.bind(e);i.createInterpolant=()=>(i.createInterpolant=n,this.createdInterpolant=n(),this.originalEvaluate=this.createdInterpolant.evaluate.bind(this.createdInterpolant),this.customEvaluate=s=>{if(!this.originalEvaluate)return;const r=this.originalEvaluate(s);return t(s,r)},this.createdInterpolant.evaluate=this.customEvaluate,this.createdInterpolant)}dispose(){this.createdInterpolant&&this.originalEvaluate&&(this.createdInterpolant.evaluate=this.originalEvaluate),this.track=void 0,this.createdInterpolant=null,this.originalEvaluate=void 0,this.customEvaluate=void 0}}class mt{static lastObjPosition={};static lastObjRotation={};static firstKeyframeRotation={};static spaceRotation={};static effectiveSpaceRotation={};static clipOffsetRotation={};set action(e){this._action=e}get action(){return this._action}get cacheId(){return this.root.uuid}_action;root;clip;positionWrapper=null;rotationWrapper=null;context;positionChange=new b;rotationChange=new N;constructor(e,t,i,n,s){if(this.context=e,this.root=t,this.clip=i,mt.firstKeyframeRotation[this.cacheId]||(mt.firstKeyframeRotation[this.cacheId]=new N),s){const r=s.values;mt.firstKeyframeRotation[this.cacheId].set(r[0],r[1],r[2],r[3])}mt.spaceRotation[this.cacheId]||(mt.spaceRotation[this.cacheId]=new N),mt.effectiveSpaceRotation[this.cacheId]||(mt.effectiveSpaceRotation[this.cacheId]=new N),mt.clipOffsetRotation[this.cacheId]=new N,s&&mt.clipOffsetRotation[this.cacheId].set(s.values[0],s.values[1],s.values[2],s.values[3]).invert(),this.handlePosition(i,n),this.handleRotation(i,s)}onStart(e){if(e.getClip()!==this.clip)return;mt.lastObjRotation[this.cacheId]||(mt.lastObjRotation[this.cacheId]=this.root.quaternion.clone());const t=mt.lastObjRotation[this.cacheId];if(mt.spaceRotation[this.cacheId].copy(t),Iu){const i=new at().setFromQuaternion(t);console.log("START",this.clip.name,j.toDegrees(i.y),this.root.position.z)}}getClipRotationOffset(){return mt.clipOffsetRotation[this.cacheId]}_prevTime=0;handlePosition(e,t){if(t){const i=this.root;Iu&&i.add(new Ci),mt.lastObjPosition[this.cacheId]||(mt.lastObjPosition[this.cacheId]=this.root.position.clone());const n=new b,s=new b;this.positionWrapper=new sx(t,(r,a)=>{const l=this.action.getEffectiveWeight();return Iu&&i.position.length()>8&&i.position.set(0,i.position.y,0),r>this._prevTime&&(n.set(a[0],a[1],a[2]),n.sub(s),n.multiplyScalar(l),n.applyQuaternion(this.getClipRotationOffset()),n.applyQuaternion(i.quaternion),this.positionChange.copy(n)),s.fromArray(a),this._prevTime=r,a[0]=0,a[1]=0,a[2]=0,a})}}static identityQuaternion=new N;handleRotation(e,t){if(t){if(Iu){const r=t.values,a=new at().setFromQuaternion(new N(r[0],r[1],r[2],r[3]));console.log(e.name,t.name,"FIRST ROTATION IN TRACK",j.toDegrees(a.y));const l=t.values.length-4,c=new N().set(r[l],r[l+1],r[l+2],r[l+3]),h=new at().setFromQuaternion(c);console.log(e.name,t.name,"LAST ROTATION IN TRACK",j.toDegrees(h.y))}let i=0;const n=new N,s=new N;this.rotationWrapper=new sx(t,(r,a)=>(r>i&&(s.set(a[0],a[1],a[2],a[3]),n.invert(),s.multiply(n),this.rotationChange.copy(s)),n.fromArray(a),i=r,a[0]=0,a[1]=0,a[2]=0,a[3]=1,a))}}onBeforeUpdate(e){this.positionChange.set(0,0,0),this.rotationChange.set(0,0,0,1)}onAfterUpdate(e){return!this.action||(e*=this.action.getEffectiveWeight(),e<=0)?!1:(this.positionChange.multiplyScalar(e),this.rotationChange.slerp(mt.identityQuaternion,1-e),!0)}}class UE{controller;handler=[];root;basePosition=new b;baseQuaternion=new N;baseRotation=new at;constructor(e){this.controller=e}createClip(e,t,i){this.root=t,t&&"name"in t&&t.name;const n=this.findRootTrack(i,".position"),s=this.findRootTrack(i,".quaternion"),r=new mt(this.controller.context,t,i,n,s);this.handler.push(r);const a=e.clipAction(i);return r.action=a,a}onStart(e){for(const t of this.handler)t.onStart(e)}onBeforeUpdate(e){this.basePosition.copy(this.root.position),this.baseQuaternion.copy(this.root.quaternion);for(const t of this.handler)t.onBeforeUpdate(e)}summedPosition=new b;summedRotation=new N;onAfterUpdate(e){if(!(e<=0)){this.root.position.copy(this.basePosition),this.root.quaternion.copy(this.baseQuaternion),this.summedPosition.set(0,0,0),this.summedRotation.set(0,0,0,1);for(const t of this.handler)t.onAfterUpdate(e)&&(this.summedPosition.add(t.positionChange),this.summedRotation.multiply(t.rotationChange));this.root.position.add(this.summedPosition),this.root.quaternion.multiply(this.summedRotation)}}findRootTrack(e,t){const i=e.tracks;if(!i)return null;for(const n of i)if(n.name.endsWith(t))return n;return null}}class zE extends Zi{onSerialize(e,t){}onDeserialize(e,t){if(t.type===gn&&e?.__type==="AnimatorController")return new gn(e)}}new zE(gn);var NE=Object.defineProperty,WE=Object.getOwnPropertyDescriptor,Lu=(o,e,t,i)=>{for(var n=i>1?void 0:i?WE(e,t):e,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&NE(e,t,n),n};const Ki=w("debuganimator");class _t extends E{get isAnimationComponent(){return!0}applyRootMotion=!1;hasRootMotion=!1;keepAnimatorControllerStateOnDisable=!1;set runtimeAnimatorController(e){this._animatorController&&this._animatorController.model===e||(e?e instanceof gn?(e.animator&&e.animator!==this&&(console.warn("AnimatorController can not be bound to multiple animators",e.model?.name),e.model||console.error("AnimatorController has no model"),e=new gn(e.model)),this._animatorController=e,this._animatorController.bind(this)):(Ki&&console.log("Assign animator controller",e,this),this._animatorController=new gn(e),this.__didAwake&&this._animatorController.bind(this)):this._animatorController=null)}get runtimeAnimatorController(){return this._animatorController}getCurrentStateInfo(){return this.runtimeAnimatorController?.getCurrentStateInfo()}get currentAction(){return this.runtimeAnimatorController?.currentAction||null}get parametersAreDirty(){return this._parametersAreDirty}_parametersAreDirty=!1;get isDirty(){return this._isDirty}_isDirty=!1;Play(e,t=-1,i=Number.NEGATIVE_INFINITY,n=0){this.play(e,t,i,n)}play(e,t=-1,i=Number.NEGATIVE_INFINITY,n=0){this.runtimeAnimatorController?.play(e,t,i,n),this._isDirty=!0}Reset(){this.reset()}reset(){this._animatorController?.reset(),this._isDirty=!0}SetBool(e,t){this.setBool(e,t)}setBool(e,t){Ki&&console.log("setBool",e,t),this.runtimeAnimatorController?.getBool(e)!==t&&(this._parametersAreDirty=!0),this.runtimeAnimatorController?.setBool(e,t)}GetBool(e){return this.getBool(e)}getBool(e){const t=this.runtimeAnimatorController?.getBool(e)??!1;return Ki&&console.log("getBool",e,t),t}toggleBool(e){this.setBool(e,!this.getBool(e))}SetFloat(e,t){this.setFloat(e,t)}setFloat(e,t){this.runtimeAnimatorController?.getFloat(e)!==t&&(this._parametersAreDirty=!0),Ki&&console.log("setFloat",e,t),this.runtimeAnimatorController?.setFloat(e,t)}GetFloat(e){return this.getFloat(e)}getFloat(e){const t=this.runtimeAnimatorController?.getFloat(e)??-1;return Ki&&console.log("getFloat",e,t),t}SetInteger(e,t){this.setInteger(e,t)}setInteger(e,t){this.runtimeAnimatorController?.getInteger(e)!==t&&(this._parametersAreDirty=!0),Ki&&console.log("setInteger",e,t),this.runtimeAnimatorController?.setInteger(e,t)}GetInteger(e){return this.getInteger(e)}getInteger(e){const t=this.runtimeAnimatorController?.getInteger(e)??-1;return Ki&&console.log("getInteger",e,t),t}SetTrigger(e){this.setTrigger(e)}setTrigger(e){this._parametersAreDirty=!0,Ki&&console.log("setTrigger",e),this.runtimeAnimatorController?.setTrigger(e)}ResetTrigger(e){this.resetTrigger(e)}resetTrigger(e){this._parametersAreDirty=!0,Ki&&console.log("resetTrigger",e),this.runtimeAnimatorController?.resetTrigger(e)}GetTrigger(e){this.getTrigger(e)}getTrigger(e){const t=this.runtimeAnimatorController?.getTrigger(e);return Ki&&console.log("getTrigger",e,t),t}IsInTransition(){return this.isInTransition()}isInTransition(){return this.runtimeAnimatorController?.isInTransition()??!1}SetSpeed(e){return this.setSpeed(e)}setSpeed(e){e!==this._speed&&(Ki&&console.log("setSpeed",e),this._speed=e,this._animatorController?.animator==this&&this._animatorController.setSpeed(e))}set minMaxSpeed(e){this._speed=j.lerp(e.x,e.y,Math.random()),this._animatorController?.animator==this&&this._animatorController.setSpeed(this._speed)}set minMaxOffsetNormalized(e){this._normalizedStartOffset=j.lerp(e.x,e.y,Math.random()),this.runtimeAnimatorController?.animator==this&&(this.runtimeAnimatorController.normalizedStartOffset=this._normalizedStartOffset)}_speed=1;_normalizedStartOffset=0;_animatorController=null;awake(){Ki&&console.log("ANIMATOR",this.name,this),this.gameObject&&this.initializeRuntimeAnimatorController()}_initializeWithRuntimeAnimatorController;initializeRuntimeAnimatorController(e=!1){const t=e||this.runtimeAnimatorController!==this._initializeWithRuntimeAnimatorController;if(this.runtimeAnimatorController&&t){const i=this.runtimeAnimatorController.clone();this._initializeWithRuntimeAnimatorController=i,i?(console.assert(this.runtimeAnimatorController!==i),this.runtimeAnimatorController=i,console.assert(this.runtimeAnimatorController===i),this.runtimeAnimatorController.bind(this),this.runtimeAnimatorController.setSpeed(this._speed),this.runtimeAnimatorController.normalizedStartOffset=this._normalizedStartOffset):console.warn("Could not clone animator controller",this.runtimeAnimatorController)}}onDisable(){this.keepAnimatorControllerStateOnDisable||this._animatorController?.reset()}onBeforeRender(){this._isDirty=!1,this._parametersAreDirty=!1,!BE(this.gameObject)&&this._animatorController&&this._animatorController.update(1)}}Lu([u()],_t.prototype,"applyRootMotion",2),Lu([u()],_t.prototype,"hasRootMotion",2),Lu([u()],_t.prototype,"keepAnimatorControllerStateOnDisable",2),Lu([u()],_t.prototype,"runtimeAnimatorController",1);const rx=Symbol("previous-visibility");class wo extends Vn{render(e,t,i){if("addPass"in i)this._unsupported_effectcomposer_warning||(console.warn("RenderTexture.render() does not yet support EffectComposer"),this._unsupported_effectcomposer_warning=!0);else if(i instanceof yr){this.onBeforeRender();const n=i.getRenderTarget(),s=i.xr.enabled;i.xr.enabled=!1,i.setRenderTarget(this),i.clear(!0,!0,!0),i.render(e,t),i.setRenderTarget(n),i.xr.enabled=s,this.onAfterRender()}}static _userSet=new Set;onBeforeRender(){wo._userSet.clear();const e=Ng(this.texture,!0,null,wo._userSet);for(const t of e)t instanceof H&&(t[rx]=t.visible,t.visible=!1)}onAfterRender(){for(const e of wo._userSet)e instanceof H&&(e.visible=e[rx]);wo._userSet.clear()}}var VE=Object.defineProperty,$E=Object.getOwnPropertyDescriptor,Xc=(o,e,t,i)=>{for(var n=i>1?void 0:i?$E(e,t):e,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&VE(e,t,n),n};const Du=w("debuggroundprojection");class Kn extends E{applyOnAwake=!1;autoFit=!0;set radius(e){this._radius=e,this._projection&&this.updateProjection()}get radius(){return this._radius}_radius=50;set height(e){this._height=e,this._projection&&this.updateProjection()}get height(){return this._height}_height=3;set arBlending(e){this._arblending=e,this._needsTextureUpdate=!0}get arBlending(){return this._arblending}_arblending=0;_lastBackground;_lastRadius;_lastHeight;_projection;_watcher;awake(){this.applyOnAwake&&this.updateAndCreate()}onEnable(){this.context.time.frameCount>0&&this.applyOnAwake&&this.updateAndCreate(),this._watcher||(this._watcher=new us(this.context.scene,"background"),this._watcher.subscribeWrite(e=>{Du&&console.log("Background changed",this.context.scene.background),this._needsTextureUpdate=!0}))}onDisable(){this._watcher?.revoke(),this._projection?.removeFromParent()}onEnterXR(){this.activeAndEnabled&&(this._needsTextureUpdate=!0,this.updateProjection())}async onLeaveXR(){this.activeAndEnabled&&(await mc(1),this.updateProjection())}onBeforeRender(){this._projection&&this.scene.backgroundRotation&&this._projection.rotation.copy(this.scene.backgroundRotation),this.context.scene.backgroundBlurriness!==void 0&&this._lastBlurriness!=this.context.scene.backgroundBlurriness&&this.context.scene.backgroundBlurriness>.001?this.updateProjection():this._needsTextureUpdate&&this.context.scene.background instanceof Se&&this.updateBlurriness(this.context.scene.background,this.context.scene.backgroundBlurriness)}updateAndCreate(){this.updateProjection(),this._watcher?.apply()}_needsTextureUpdate=!1;updateProjection(){if(!this.context.scene.background){this._projection?.removeFromParent();return}const e=this.context.scene.background;if(!(e instanceof Se)){this._projection?.removeFromParent();return}if((this.context.xr?.isPassThrough||this.context.xr?.isAR)&&this.arBlending===0){this._projection?.removeFromParent();return}if(!this.gameObject||this.destroyed)return;let t=!0;const i=0,n=e!==this._lastBackground||this._height!==this._lastHeight||this._radius!==this._lastRadius;if(!this._projection||n){Du&&console.log("Create/Update Ground Projection",e.name),this._projection?.removeFromParent();try{this._projection=new ja(e,this._height,this._radius,64)}catch(s){console.error("Error creating three GroundProjection",s);return}this._projection.position.y=this._height-i,this._projection.name="GroundProjection",dg(this._projection,!1)}else t=!1;if(this._projection.parent||this.gameObject.add(this._projection),this.autoFit&&t){this._projection.updateWorldMatrix(!0,!0);const s=Ri(this.context.scene.children,[this._projection]),r=s.min.y;if(r<1/0){const a=F();a.x=s.min.x+(s.max.x-s.min.x)*.5;const l=$e(this.gameObject).x;a.y=r+this._height*l-i,a.z=s.min.z+(s.max.z-s.min.z)*.5,yt(this._projection,a)}Du&&B.DrawWireBox3(s,65280,5)}this.context.scene.backgroundBlurriness>.001&&this._needsTextureUpdate&&this.updateBlurriness(e,this.context.scene.backgroundBlurriness),this._lastBackground=e,this._lastHeight=this._height,this._lastRadius=this._radius,this._needsTextureUpdate=!1}_blurrynessShader=null;_lastBlurriness=-1;updateBlurriness(e,t){if(this._projection){if(!e)return}else return;this._needsTextureUpdate=!1,Du&&console.log("Update Blurriness",t),this._blurrynessShader??=new Wn({name:"GroundProjectionBlurriness",uniforms:{map:{value:e},blurriness:{value:t},blending:{value:0},alphaFactor:{value:1}},vertexShader:HE,fragmentShader:GE}),this._blurrynessShader.depthWrite=!1,this._blurrynessShader.uniforms.map.value=e,this._blurrynessShader.uniforms.blurriness.value=t,this._lastBlurriness=t,e.needsUpdate=!0;const i=this._projection.material.transparent;this._projection.material.transparent=(this.context.xr?.isAR===!0&&this.arBlending>1e-6)??!1,this._projection.material.transparent?this._blurrynessShader.uniforms.blending.value=this.arBlending:this._blurrynessShader.uniforms.blending.value=0,this.context.isInPassThrough?this._blurrynessShader.uniforms.alphaFactor.value=.95:this._blurrynessShader.uniforms.alphaFactor.value=1,i!==this._projection.material.transparent&&(this._projection.material.needsUpdate=!0),this._projection.material.map=pr.copyTexture(e,this._blurrynessShader),this._projection.material.depthTest=!0,this._projection.material.depthWrite=!1}}Xc([u()],Kn.prototype,"applyOnAwake",2),Xc([u()],Kn.prototype,"autoFit",2),Xc([u()],Kn.prototype,"radius",1),Xc([u()],Kn.prototype,"height",1),Xc([u()],Kn.prototype,"arBlending",1);const HE=`
@@ -959,7 +959,7 @@ Exit Time: `+c,s.hasExitTime)}this.transitionTo(s.destinationState,s.duration,s.
959
959
  // Uncomment to visualize blur amount
960
960
  // gl_FragColor = vec4(blurAmount, 0.0, 0.0, 1.0);
961
961
  }
962
- `;function ax(o){if(Z.active)return console.warn("[OrbitControls] Can not fit camera while XR session is active"),null;const e=U.Current;if(!e)return console.warn("[OrbitControls] No context found"),null;const t=o?.camera||e.mainCamera;if(!t)return console.warn("No camera or controls found to fit camera to objects..."),null;o||(o={}),o.autoApply=o.autoApply!==!1,o.minZoom||=0,o.maxZoom||=1/0;const{centerCamera:i,cameraNearFar:n="auto",fitOffset:s=1.1,fov:r=t instanceof de?t?.fov:-1}=o,a=new b,l=new b,c=t instanceof de?t.aspect:1,h=o.objects||e.scene,d=Ri(h,void 0,t?.layers),p=d.clone();d.getCenter(l);const m=new b;if(d.getSize(m),t instanceof de&&t.updateProjectionMatrix(),t.updateMatrixWorld(),d.applyMatrix4(t.matrixWorldInverse),d.getSize(a),d.setFromCenterAndSize(l,a),Number.isNaN(a.x)||Number.isNaN(a.y)||Number.isNaN(a.z))return console.warn("Camera fit size resultet in NaN",t,d),null;if(a.length()<=1e-10)return console.warn("Camera fit size is zero",d),null;const g=r,f=2*Math.atan(Math.tan(g*Math.PI/360/2)*c)/Math.PI*360,y=a.y/(2*Math.atan(Math.PI*g/360)),_=a.x/(2*Math.atan(Math.PI*f/360)),v=s*Math.max(y,_)+a.z/2;o.maxZoom=v*10,o.minZoom=v*.01,o.debug===!0&&console.log("Fit camera to objects",{fitHeightDistance:y,fitWidthDistance:_,distance:v,verticalFov:g,horizontalFov:f});const P=.05,k=l.clone();if(k.y-=a.y*P,o.targetOffset&&(o.targetOffset.x!==void 0&&(k.x+=o.targetOffset.x),o.targetOffset.y!==void 0&&(k.y+=o.targetOffset.y),o.targetOffset.z!==void 0&&(k.z+=o.targetOffset.z)),o.relativeTargetOffset&&(o.relativeTargetOffset.x!==void 0&&(k.x+=o.relativeTargetOffset.x*a.x),o.relativeTargetOffset.y!==void 0&&(k.y+=o.relativeTargetOffset.y*a.y),o.relativeTargetOffset.z!==void 0&&(k.z+=o.relativeTargetOffset.z*a.z)),n==null||n=="auto"){const L=tl(Kn),V=L?L.radius:0,W=Math.max(m.x,m.y,m.z,V);t instanceof de&&(t.near=v/100,t.far=W+v*10,t.updateProjectionMatrix()),L&&(o.maxZoom=Math.max(Math.min(o.maxZoom,V*.5),v))}o.currentZoom!==void 0&&(o.currentZoom<o.minZoom&&(o.minZoom=o.currentZoom*.9),o.currentZoom>o.maxZoom&&(o.maxZoom=o.currentZoom*1.1));const O=l.clone();o.fitDirection?O.sub(new b().copy(o.fitDirection).multiplyScalar(1e6)):O.sub(t.worldPosition),i==="y"&&(O.y=0),O.normalize(),O.multiplyScalar(v),i==="y"&&(O.y+=-P*4*v);let D=l.clone().sub(O);return o.cameraOffset&&(o.cameraOffset.x!==void 0&&(D.x+=o.cameraOffset.x),o.cameraOffset.y!==void 0&&(D.y+=o.cameraOffset.y),o.cameraOffset.z!==void 0&&(D.z+=o.cameraOffset.z)),o.relativeCameraOffset&&(o.relativeCameraOffset.x!==void 0&&(D.x+=o.relativeCameraOffset.x*a.x),o.relativeCameraOffset.y!==void 0&&(D.y+=o.relativeCameraOffset.y*a.y),o.relativeCameraOffset.z!==void 0&&(D.z+=o.relativeCameraOffset.z*a.z)),t.parent&&(D=t.parent.worldToLocal(D)),o.debug&&(B.DrawWireBox3(d,16777011,10),B.DrawWireBox3(p,65280,10)),o.autoApply&&(t.position.copy(D),t.lookAt(k),r>0&&t instanceof de&&(t.fov=r,t.updateProjectionMatrix())),{camera:t,position:D,lookAt:k,fov:o.fov}}var qE=Object.defineProperty,Lf=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&qE(e,t,n),n};class Wr extends E{constraintActive=!0;locked=!1;sources=[];setConstraintPosition(e){const t=this.sources[0];t&&(t.worldPosition=e)}}Lf([u()],Wr.prototype,"constraintActive"),Lf([u()],Wr.prototype,"locked"),Lf([u(M)],Wr.prototype,"sources");let Vr=class{bb=null;bb_pos=0;__init(o,e){return this.bb_pos=o,this.bb=e,this}x(){return this.bb.readFloat32(this.bb_pos)}y(){return this.bb.readFloat32(this.bb_pos+4)}z(){return this.bb.readFloat32(this.bb_pos+8)}static sizeOf(){return 12}static createVec3(o,e,t,i){return o.prep(4,12),o.writeFloat32(i),o.writeFloat32(t),o.writeFloat32(e),o.offset()}};class lx{bb=null;bb_pos=0;__init(e,t){return this.bb_pos=e,this.bb=t,this}position(e){return(e||new Vr).__init(this.bb_pos,this.bb)}rotation(e){return(e||new Vr).__init(this.bb_pos+12,this.bb)}scale(e){return(e||new Vr).__init(this.bb_pos+24,this.bb)}static sizeOf(){return 36}static createTransform(e,t,i,n,s,r,a,l,c,h){return e.prep(4,36),e.prep(4,12),e.writeFloat32(h),e.writeFloat32(c),e.writeFloat32(l),e.prep(4,12),e.writeFloat32(a),e.writeFloat32(r),e.writeFloat32(s),e.prep(4,12),e.writeFloat32(n),e.writeFloat32(i),e.writeFloat32(t),e.offset()}}class ms{bb=null;bb_pos=0;__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsSyncedTransformModel(e,t){return(t||new ms).__init(e.readInt32(e.position())+e.position(),e)}static getSizePrefixedRootAsSyncedTransformModel(e,t){return e.setPosition(e.position()+Wb),(t||new ms).__init(e.readInt32(e.position())+e.position(),e)}guid(e){const t=this.bb.__offset(this.bb_pos,4);return t?this.bb.__string(this.bb_pos+t,e):null}fast(){const e=this.bb.__offset(this.bb_pos,6);return e?!!this.bb.readInt8(this.bb_pos+e):!1}transform(e){const t=this.bb.__offset(this.bb_pos,8);return t?(e||new lx).__init(this.bb_pos+t,this.bb):null}dontSave(){const e=this.bb.__offset(this.bb_pos,10);return e?!!this.bb.readInt8(this.bb_pos+e):!1}static startSyncedTransformModel(e){e.startObject(4)}static addGuid(e,t){e.addFieldOffset(0,t,0)}static addFast(e,t){e.addFieldInt8(1,+t,0)}static addTransform(e,t){e.addFieldStruct(2,t,0)}static addDontSave(e,t){e.addFieldInt8(3,+t,0)}static endSyncedTransformModel(e){return e.endObject()}static finishSyncedTransformModelBuffer(e,t){e.finish(t)}static finishSizePrefixedSyncedTransformModelBuffer(e,t){e.finish(t,void 0,!0)}}var T;(o=>{(e=>{e.MAYBEMODULE=null;const t=[];function i(){return e.MODULE?Promise.resolve(e.MODULE):new Promise(s=>{t.push(s)})}e.ready=i;async function n(){if(e.MODULE)return e.MODULE;const s=await import("./materialx-D_ofN96q.min.js");return e.MODULE=s,e.MAYBEMODULE=s,t.forEach(r=>r(s)),t.length=0,s}e.load=n})(o.MaterialX||(o.MaterialX={})),(e=>{e.MAYBEMODULE=null;const t=[];function i(){return e.MODULE?Promise.resolve(e.MODULE):new Promise(s=>{t.push(s)})}e.ready=i;async function n(){if(e.MODULE)return e.MODULE;const s=await import("./rapier-DJ-luMxr.min.js");return e.MODULE=s,e.MAYBEMODULE=s,t.forEach(r=>r(s)),t.length=0,s}e.load=n})(o.RAPIER_PHYSICS||(o.RAPIER_PHYSICS={})),(e=>{e.MAYBEMODULE=null;const t=[];function i(){return e.MODULE?Promise.resolve(e.MODULE):new Promise(s=>{t.push(s)})}e.ready=i;async function n(){if(e.MODULE)return e.MODULE;const s=await import("./postprocessing-DXm8YKbQ.min.js").then(r=>r.index);return e.MODULE=s,e.MAYBEMODULE=s,t.forEach(r=>r(s)),t.length=0,s}e.load=n})(o.POSTPROCESSING||(o.POSTPROCESSING={})),(e=>{e.MAYBEMODULE=null;const t=[];function i(){return e.MODULE?Promise.resolve(e.MODULE):new Promise(s=>{t.push(s)})}e.ready=i;async function n(){if(e.MODULE)return e.MODULE;const s=await import("./postprocessing-DXm8YKbQ.min.js").then(r=>r.N8AO);return e.MODULE=s,e.MAYBEMODULE=s,t.forEach(r=>r(s)),t.length=0,s}e.load=n})(o.POSTPROCESSING_AO||(o.POSTPROCESSING_AO={}))})(T||(T={}));var vt=(o=>(o[o.Average=0]="Average",o[o.Multiply=1]="Multiply",o[o.Minimum=2]="Minimum",o[o.Maximum=3]="Maximum",o))(vt||{}),ju=(o=>(o[o.Discrete=0]="Discrete",o[o.Continuous=1]="Continuous",o))(ju||{}),Ye=(o=>(o[o.None=0]="None",o[o.FreezePositionX=2]="FreezePositionX",o[o.FreezePositionY=4]="FreezePositionY",o[o.FreezePositionZ=8]="FreezePositionZ",o[o.FreezePosition=14]="FreezePosition",o[o.FreezeRotationX=16]="FreezeRotationX",o[o.FreezeRotationY=32]="FreezeRotationY",o[o.FreezeRotationZ=64]="FreezeRotationZ",o[o.FreezeRotation=112]="FreezeRotation",o[o.FreezeAll=126]="FreezeAll",o))(Ye||{}),cl=(o=>(o[o.None=0]="None",o[o.X=2]="X",o[o.Y=4]="Y",o[o.Z=8]="Z",o[o.All=-1]="All",o))(cl||{});const Mt=function(o,e){return function(t,i,n){XE(t,i,n,o,e)}};function XE(o,e,t,i,n){if(!n&&!i&&!o.onValidate)return;if(t!==void 0){console.error("Invalid usage of validate decorator. Only fields can be validated.",o,e,t),Oe("Invalid usage of validate decorator. Only fields can be validated. Property: "+e,{type:Ei.Error});return}let s="";if(typeof e=="string"?s=e:s=e.name,o.__internalAwake){const r=Symbol(s),a=o.__internalAwake;o.__internalAwake=function(){if(!this.onValidate){A()&&console.warn('Usage of @validate decorate detected but there is no onValidate method in your class: "'+o.constructor?.name+'"');return}if(this[r]===void 0){this[r]=this[s];const l=this[s];if(l instanceof K||l instanceof b||l instanceof ye||l instanceof N){const c=this[s];Bd(c,()=>{this.onValidate(s)})}Object.defineProperty(this,s,{set:function(c){if(this[af]===!0)this[r]=c;else{i?.call(this,c);const h=this[r];this[r]=c,this.onValidate?.call(this,s,h)}},get:function(){return n?.call(this),this[r]}})}a.call(this)}}}const QE=function(o){return function(e,t,i){let n="";typeof t=="string"?n=t:n=t.name;const s=o.prototype,r=Object.getOwnPropertyDescriptor(s,n);if(!r?.value){console.warn("Can not apply prefix: type does not have method named",t,o);return}const a=r.value,l=e[n];Object.defineProperty(s,n,{value:function(...c){const h=l?.call(this,...c);if(h instanceof Promise){h.then(d=>{if(d!==!1)return a.call(this,...c)});return}if(h!==!1)return a.call(this,...c)}})}};var YE=Object.defineProperty,ZE=Object.getOwnPropertyDescriptor,Li=(o,e,t,i)=>{for(var n=i>1?void 0:i?ZE(e,t):e,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&YE(e,t,n),n};class KE{get isDirty(){return this.positionChanged||this.rotationChanged}positionChanged=!1;rotationChanged=!1;position;quaternion;_positionKeys=["x","y","z"];_quaternionKeys=["_x","_y","_z","_w"];reset(e=!1){if(this.positionChanged=!1,this.rotationChanged=!1,this.mute=!1,e){if(this.position)for(const t of this._positionKeys)delete this.position[t];if(this.quaternion)for(const t of this._quaternionKeys)delete this.quaternion[t]}}syncValues(){for(const e of this._positionKeys)this.position[e]=this.obj.position[e];for(const e of this._quaternionKeys)this.quaternion[e]=this.obj.quaternion[e]}mute=!1;applyValues(){if(this.positionChanged&&this.position)for(const e of this._positionKeys){const t=this.position[e];t!==void 0&&(this.obj.position[e]=t)}if(this.rotationChanged&&this.quaternion)for(const e of this._quaternionKeys){const t=this.quaternion[e];t!==void 0&&(this.obj.quaternion[e]=t)}}context;obj;_positionWatch;_rotationWatch;constructor(e,t){this.context=t,this.obj=e}start(e,t){this.reset(),e&&(this._positionWatch||(this._positionWatch=new us(this.obj.position,["x","y","z"])),this._positionWatch.apply(),this.position={},this._positionWatch.subscribeWrite((s,r)=>{if(this.context.physics.engine?.isUpdating||this.mute)return;const a=this.position[r];Math.abs(a-s)<1e-5||(this.position[r]=s,this.positionChanged=!0)})),t&&(this._rotationWatch||(this._rotationWatch=new us(this.obj.quaternion,["_x","_y","_z","_w"])),this._rotationWatch.apply(),this.quaternion={},this._rotationWatch.subscribeWrite((s,r)=>{if(this.context.physics.engine?.isUpdating||this.mute)return;const a=this.quaternion[r];Math.abs(a-s)<1e-5||(this.quaternion[r]=s,this.rotationChanged=!0)}));const i=this.obj.matrixWorld.multiplyMatrices.bind(this.obj.matrixWorld),n=new J;this.obj.matrixWorld.multiplyMatrices=(s,r)=>(this.context.physics.engine?.isUpdating||this.mute||n.equals(s)||(this.positionChanged=!0,this.rotationChanged=!0,n.copy(s)),i(s,r))}stop(){this._positionWatch?.revoke(),this._rotationWatch?.revoke()}}const mi=class fm extends E{get isRigidbody(){return!0}autoMass=!0;set mass(e){e!==this._mass&&(this._mass=e,this._propertiesChanged=!0,this.__didAwake&&(this.autoMass=!1))}get mass(){return this.autoMass?this.context.physics.engine?.getBody(this)?.mass()??-1:this._mass}_mass=0;useGravity=!0;centerOfMass=new b(0,0,0);constraints=Ye.None;isKinematic=!1;drag=0;angularDrag=1;detectCollisions=!0;sleepThreshold=.01;collisionDetectionMode=ju.Discrete;get lockPositionX(){return(this.constraints&Ye.FreezePositionX)!==0}get lockPositionY(){return(this.constraints&Ye.FreezePositionY)!==0}get lockPositionZ(){return(this.constraints&Ye.FreezePositionZ)!==0}get lockRotationX(){return(this.constraints&Ye.FreezeRotationX)!==0}get lockRotationY(){return(this.constraints&Ye.FreezeRotationY)!==0}get lockRotationZ(){return(this.constraints&Ye.FreezeRotationZ)!==0}set lockPositionX(e){e?this.constraints|=Ye.FreezePositionX:this.constraints&=~Ye.FreezePositionX}set lockPositionY(e){e?this.constraints|=Ye.FreezePositionY:this.constraints&=~Ye.FreezePositionY}set lockPositionZ(e){e?this.constraints|=Ye.FreezePositionZ:this.constraints&=~Ye.FreezePositionZ}set lockRotationX(e){e?this.constraints|=Ye.FreezeRotationX:this.constraints&=~Ye.FreezeRotationX}set lockRotationY(e){e?this.constraints|=Ye.FreezeRotationY:this.constraints&=~Ye.FreezeRotationY}set lockRotationZ(e){e?this.constraints|=Ye.FreezeRotationZ:this.constraints&=~Ye.FreezeRotationZ}set gravityScale(e){this._gravityScale=e}get gravityScale(){return this._gravityScale}_gravityScale=1;dominanceGroup=0;static tempPosition=new b;_propertiesChanged=!1;_currentVelocity=new b;_smoothedVelocity=new b;_smoothedVelocityGetter=new b;_lastPosition=new b;_watch;awake(){this._watch=void 0,this._propertiesChanged=!1}onEnable(){this._watch||(this._watch=new KE(this.gameObject,this.context)),this._watch.start(!0,!0),this.startCoroutine(this.beforePhysics(),xe.LateUpdate),A()&&(globalThis.NEEDLE_USE_RAPIER?T.RAPIER_PHYSICS.ready().then(async()=>{await mc(3),this.context.physics.engine?.getBody(this)||console.warn(`Rigidbody could not be created. Ensure "${this.name}" has a Collider component.`)}):console.warn("Rigidbody could not be created: Rapier physics are explicitly disabled."))}onDisable(){this._watch?.stop(),this.context.physics.engine?.removeBody(this)}onDestroy(){this.context.physics.engine?.removeBody(this)}onValidate(){this._propertiesChanged=!0}*beforePhysics(){for(;;)this._propertiesChanged&&(this._propertiesChanged=!1,this.context.physics.engine?.updateProperties(this)),this._watch?.isDirty?(this._watch.mute=!0,this._watch.applyValues(),this.context.physics.engine?.updateBody(this,this._watch.positionChanged,this._watch.rotationChanged),this._watch.reset()):this._watch?.syncValues(),this.captureVelocity(),yield}teleport(e,t=!0){this._watch?.reset(!0),t?this.gameObject.position.set(e.x,e.y,e.z):this.setWorldPosition(e.x,e.y,e.z),this.resetForcesAndTorques(),this.resetVelocities()}resetForces(e=!0){this.context.physics.engine?.resetForces(this,e)}resetTorques(e=!0){this.context.physics.engine?.resetTorques(this,e)}resetVelocities(){this.setVelocity(0,0,0),this.setAngularVelocity(0,0,0)}resetForcesAndTorques(){this.resetForces(),this.resetTorques()}wakeUp(){this.context.physics.engine?.wakeup(this)}get isSleeping(){return this.context.physics.engine?.isSleeping(this)}updateProperties(){return this._propertiesChanged=!1,this.context.physics.engine?.updateProperties(this)}applyForce(e,t,i=!0){this._propertiesChanged&&this.updateProperties(),this.context.physics.engine?.addForce(this,e,i)}applyImpulse(e,t=!0){this._propertiesChanged&&this.updateProperties(),this.context.physics.engine?.applyImpulse(this,e,t)}setForce(e,t,i,n=!0){this.context.physics.engine?.resetForces(this,n),typeof e=="number"?(t??=0,i??=0,this.context.physics.engine?.addForce(this,{x:e,y:t,z:i},n)):this.context.physics.engine?.addForce(this,e,n)}getVelocity(){const e=this.context.physics.engine?.getLinearVelocity(this);return e?(this._currentVelocity.x=e.x,this._currentVelocity.y=e.y,this._currentVelocity.z=e.z,this._currentVelocity):this._currentVelocity.set(0,0,0)}setVelocity(e,t,i,n=!0){if(e instanceof b){const s=e;this.context.physics.engine?.setLinearVelocity(this,s,n);return}t===void 0||i===void 0||this.context.physics.engine?.setLinearVelocity(this,{x:e,y:t,z:i},n)}getAngularVelocity(){const e=this.context.physics.engine?.getAngularVelocity(this);return e?(this._currentVelocity.x=e.x,this._currentVelocity.y=e.y,this._currentVelocity.z=e.z,this._currentVelocity):this._currentVelocity.set(0,0,0)}setAngularVelocity(e,t,i,n=!0){if(typeof e=="object"){const s=e;this.context.physics.engine?.setAngularVelocity(this,s,n);return}if(t===void 0||i===void 0||typeof t=="boolean"){console.warn("setAngularVelocity expects either a Vec3 or 3 numbers");return}this.context.physics.engine?.setAngularVelocity(this,{x:e,y:t,z:i},n)}setTorque(e,t,i){typeof e=="number"?this.setAngularVelocity(e,t,i):this.setAngularVelocity(e)}get smoothedVelocity(){return this._smoothedVelocityGetter.copy(this._smoothedVelocity),this._smoothedVelocityGetter.multiplyScalar(1/this.context.time.deltaTime)}setBodyFromGameObject(e=null){}captureVelocity(){const e=this.gameObject.matrixWorld;fm.tempPosition.setFromMatrixPosition(e);const t=fm.tempPosition.sub(this._lastPosition);this._lastPosition.copy(fm.tempPosition),this._smoothedVelocity.lerp(t,this.context.time.deltaTime/.1)}};Li([Mt()],mi.prototype,"autoMass",2),Li([u()],mi.prototype,"mass",1),Li([Mt(),u()],mi.prototype,"useGravity",2),Li([u(b)],mi.prototype,"centerOfMass",2),Li([Mt(),u()],mi.prototype,"constraints",2),Li([Mt(),u()],mi.prototype,"isKinematic",2),Li([Mt(),u()],mi.prototype,"drag",2),Li([Mt(),u()],mi.prototype,"angularDrag",2),Li([Mt(),u()],mi.prototype,"detectCollisions",2),Li([Mt(),u()],mi.prototype,"sleepThreshold",2),Li([Mt(),u()],mi.prototype,"collisionDetectionMode",2),Li([Mt()],mi.prototype,"_gravityScale",2),Li([Mt()],mi.prototype,"dominanceGroup",2);let Ze=mi;new b,new b;const As=w("debugsync"),Qc="STRS";kg(Qc,ms.getRootAsSyncedTransformModel);const Jn=new zm;function cx(o,e,t=!0){Jn.clear();const i=Jn.createString(o);ms.startSyncedTransformModel(Jn),ms.addGuid(Jn,i),ms.addFast(Jn,t);const n=e.worldPosition,s=e.worldEuler,r=e.gameObject.scale;ms.addTransform(Jn,lx.createTransform(Jn,n.x,n.y,n.z,s.x,s.y,s.z,r.x,r.y,r.z));const a=ms.endSyncedTransformModel(Jn);return Jn.finish(a,Qc),Jn.asUint8Array()}let Df=0,Yc=0;Vw(o=>{const e=o.connection.currentServerUrl?.includes("glitch")?10:40;Yc=Math.floor(Df/e),Df=0,As&&Yc>0&&console.log("Sync Transform Fast Interval",Yc)});class Tn extends E{overridePhysics=!0;interpolatePosition=!0;interpolateRotation=!0;fastMode=!1;syncDestroy=!1;_model=null;_needsUpdate=!0;rb=null;_wasKinematic=!1;_receivedDataBefore=!1;_targetPosition;_targetRotation;_receivedFastUpdate=!1;_shouldRequestOwnership=!1;requestOwnership(){As&&console.log("Request ownership"),this._model?this._model.requestOwnership():(this._shouldRequestOwnership=!0,this._needsUpdate=!0)}freeOwnership(){this._model?.freeOwnership()}hasOwnership(){return this._model?.hasOwnership??void 0}isOwned(){return this._model?.isOwned}joinedRoomCallback=null;receivedDataCallback=null;awake(){As&&console.log("new instance",this.guid,this),this._receivedDataBefore=!1,this._targetPosition=new b,this._targetRotation=new N,this.lastPosition=new b,this.lastRotation=new N,this.lastScale=new b,this.rb=S.getComponentInChildren(this.gameObject,Ze),this.rb&&(this._wasKinematic=this.rb.isKinematic),this.receivedUpdate=!0,this._model=new Eg(this.context.connection,this.guid),this.context.connection.isConnected&&this.tryGetLastState(),this.joinedRoomCallback=this.tryGetLastState.bind(this),this.context.connection.beginListen(ie.JoinedRoom,this.joinedRoomCallback),this.receivedDataCallback=this.onReceivedData.bind(this),this.context.connection.beginListenBinary(Qc,this.receivedDataCallback)}onDestroy(){this.syncDestroy&&Yg(this.guid,this.context.connection),this._model=null,this.context.connection.stopListen(ie.JoinedRoom,this.joinedRoomCallback),this.context.connection.stopListenBinary(Qc,this.receivedDataCallback)}tryGetLastState(){const e=this.context.connection.tryGetState(this.guid);e&&this.onReceivedData(e)}tempEuler=new at;onReceivedData(e){if(!this.destroyed&&typeof e.guid=="function"&&e.guid()===this.guid){As&&console.log("new data",this.context.connection.connectionId,this.context.time.frameCount,this.guid,e),this.receivedUpdate=!0,this._receivedFastUpdate=e.fast();const t=e.transform();if(t){pn.markDirty(this.gameObject,!0);const i=t.position();i&&(this.interpolatePosition&&this._targetPosition?.set(i.x(),i.y(),i.z()),(!this.interpolatePosition||!this._receivedDataBefore)&&this.setWorldPosition(i.x(),i.y(),i.z()));const n=t.rotation();n&&(this.tempEuler.set(n.x(),n.y(),n.z()),this.interpolateRotation&&this._targetRotation.setFromEuler(this.tempEuler),(!this.interpolateRotation||!this._receivedDataBefore)&&hg(this.gameObject,this.tempEuler));const s=t.scale();s&&this.gameObject.scale.set(s.x(),s.y(),s.z())}this._receivedDataBefore=!0}}onEnable(){this.lastPosition.copy(this.worldPosition),this.lastRotation.copy(this.worldQuaternion),this.lastScale.copy(this.gameObject.scale),this._needsUpdate=!0,this._model&&this._model.updateIsOwned()}onDisable(){this._model&&this._model.freeOwnership()}receivedUpdate=!1;lastPosition;lastRotation;lastScale;onBeforeRender(){if(!this.activeAndEnabled||!this.context.connection.isConnected)return;if(!this.context.connection.isInRoom||!this._model){As&&console.log("no model or room",this.name,this.guid,this.context.connection.isInRoom);return}this._shouldRequestOwnership&&(this._shouldRequestOwnership=!1,this._model.requestOwnership());const e=this.worldPosition,t=this.worldQuaternion,i=this.gameObject.scale;if(this._model.isOwned&&!this.receivedUpdate){const r=this._model.hasOwnership||this.fastMode?1e-4:.001;(e.distanceTo(this.lastPosition)>r||t.angleTo(this.lastRotation)>r||i.distanceTo(this.lastScale)>r)&&(this._model.hasOwnership?this._needsUpdate=!0:(As&&console.log(this.guid,"reset because not owned but",this.gameObject.name,this.lastPosition),this.worldPosition=this.lastPosition,e.copy(this.lastPosition),this.worldQuaternion=this.lastRotation,t.copy(this.lastRotation),this.gameObject.scale.copy(this.lastScale),pn.markDirty(this.gameObject,!0),this._needsUpdate=!1))}if(this._model&&!this._model.hasOwnership&&this._model.isOwned&&this._receivedDataBefore){const r=this._receivedFastUpdate||this.fastMode?.5:.3;let a=!1;if(this.interpolatePosition&&this._targetPosition){const l=this.worldPosition;l.lerp(this._targetPosition,r),this.worldPosition=l,a=!0}if(this.interpolateRotation&&this._targetRotation){const l=this.worldQuaternion;l.slerp(this._targetRotation,r),this.worldQuaternion=l,a=!0}a&&pn.markDirty(this.gameObject,!0)}if(this.receivedUpdate=!1,this.lastPosition.copy(e),this.lastRotation.copy(t),this.lastScale.copy(i),!this._model||!this._model||this._model.hasOwnership===void 0||!this._model.hasOwnership)return;this.rb&&this.overridePhysics&&this._wasKinematic!==void 0&&(As&&console.log("reset kinematic",this.rb.name,this._wasKinematic),this.rb.isKinematic=this._wasKinematic);const n=10,s=this.rb||this.fastMode;if(this._needsUpdate&&(this.context.time.frameCount%n===0||s)){if(Df++,s&&Yc>0&&this.context.time.frameCount%Yc!==0)return;As&&console.debug("[SyncedTransform] Send update",this.context.connection.connectionId,this.guid,this.gameObject.name,this.gameObject.guid),this._needsUpdate=!1;const r=cx(this.guid,this,!!s);this.context.connection.sendBinary(r)}}}class vd{event;get deviceIndex(){return this.event.deviceIndex}get pointerId(){return this.event.pointerId}button;buttonName;get pressure(){return this.event.pressure}get used(){return this._used}_used=!1;use(){this._used||(this._used=!0,this.event.use())}_propagationStopped=!1;get propagationStopped(){return this._propagationStopped}stopPropagation(){this._propagationStopped=!0,this.event.stopImmediatePropagation()}stopImmediatePropagation(){this._propagationStopped=!0,this.event.stopImmediatePropagation()}z__pointer_ctured=!1;setPointerCapture(){this.z__pointer_ctured=!0}z__pointer_cture_rleased=!1;releasePointerCapture(){this.z__pointer_cture_rleased=!0}inputSource;get mode(){return this.event.mode}object;point;normal;face;distance;instanceId;intersection;isDown;isUp;isPressed;isClick;isDoubleClick;input;constructor(e,t){this.event=t,this.input=e,this.button=t.button}clone(){const e=new vd(this.input,this.event);return Object.assign(e,this),e}Use(){this.use()}StopPropagation(){this.event.stopImmediatePropagation()}}function Bu(o,e){return S.foreachComponent(o,t=>{if(!t.enabled)return;const i=t;if(e)switch(e){case"pointerdown":if(i.onPointerDown)return!0;break;case"pointerup":if(i.onPointerUp||i.onPointerClick)return!0;break;case"pointermove":if(i.onPointerEnter||i.onPointerExit||i.onPointerMove)return!0;break}else if(i.onPointerDown||i.onPointerUp||i.onPointerEnter||i.onPointerExit||i.onPointerClick)return!0},!1)===!0}const Uo=new Array;class zo{enabled=!0;target;methodName;arguments;get canClone(){return this.target instanceof Object}constructor(e,t,i,n){this.target=e,this.methodName=t||null,this.arguments=i,n!=null&&(this.enabled=n)}invoke(...e){if(this.enabled!==!1){if(typeof this.target=="function")this.arguments?(Uo.length=0,e!==void 0&&e.length>0&&Uo.push(...e),Uo.push(...this.arguments),this.target(...this.arguments),Uo.length=0):this.target(...e);else if(this.methodName!=null){const t=this.target[this.methodName];typeof t=="function"?this.arguments?(Uo.length=0,e!==void 0&&e.length>0&&Uo.push(...e),Uo.push(...this.arguments),t.call(this.target,...Uo),Uo.length=0):t.call(this.target,...e):this.arguments?e!==void 0&&e.length>0?this.target[this.methodName]=e[0]:this.target[this.methodName]=this.arguments[0]:this.target[this.methodName]=e[0]}}}}const JE=o=>/^[A-Z]*$/.test(o);class Fu extends Event{args}class ae{isEventList=!0;__internalOnInstantiate(e){const t=new Array;for(let i=0;i<this.methods.length;i++){const n=this.methods[i];if(!(n.target instanceof Function)){const s=n.target;let r=s?.uuid;if(s&&(r=s.guid),r){const a=e[r];if(a){const l=n.arguments?.map(c=>c instanceof Object&&c.uuid?e[c.uuid].clone:c?.isComponent?e[c.guid].clone:c);t.push(new zo(a.clone,n.methodName,l,n.enabled))}else A()&&console.warn("Could not find target for event listener")}}}return new ae(t)}target;key;setEventTarget(e,t){if(this.key=e,this.target=t,this.key!==void 0){let i="",n=!1;for(const s of this.key)n&&JE(s)&&(i+="-"),n=!0,i+=s.toLowerCase();this.key=i}}get listenerCount(){return this.methods?.length??0}get isInvoking(){return this._isInvoking}_isInvoking=!1;methods=[];_methodsCopy=[];static from(...e){return new ae(e)}constructor(e){if(this.methods=[],Array.isArray(e))for(const t of e)t instanceof zo?this.methods.push(t):typeof t=="function"&&this.methods.push(new zo(t));else typeof e=="function"&&this.methods.push(new zo(e))}invoke(...e){if(this._isInvoking)return console.warn("Circular event invocation detected. Please check your event listeners for circular references.",this),!1;if(this.methods?.length<=0)return!1;this._isInvoking=!0;try{this._methodsCopy.length=0,this._methodsCopy.push(...this.methods);for(const t of this._methodsCopy)t.invoke(...e);if(typeof this.target=="object"&&typeof this.key=="string"){const t=this.target.dispatchEvent;if(typeof t=="function"){const i=new Fu(this.key);i.args=e,t.call(this.target,i)}}}finally{this._isInvoking=!1,this._methodsCopy.length=0}return!0}addEventListener(e){return this.methods.push(new zo(e)),e}removeEventListener(e){if(e)for(let t=this.methods.length-1;t>=0;t--)this.methods[t].target===e&&(this.methods[t].enabled=!1,this.methods.splice(t,1))}removeAllEventListeners(){this.methods.length=0}}class eR extends Zi{constructor(){super([oe,se],"ColorSerializer")}onDeserialize(e){if(e!=null)return e.a!==void 0?new se(e.r,e.g,e.b,e.a):e.alpha!==void 0?new se(e.r,e.g,e.b,e.alpha):new oe(e.r,e.g,e.b)}onSerialize(e){if(e!=null)return e.a!==void 0?{r:e.r,g:e.g,b:e.b,a:e.a}:{r:e.r,g:e.g,b:e.b}}}const tR=new eR;class iR extends Zi{constructor(){super([at],"EulerSerializer")}onDeserialize(e,t){if(e!=null){if(e.order)return new at(e.x,e.y,e.z,e.order);if(e.x!=null)return new at(e.x,e.y,e.z)}}onSerialize(e,t){return{x:e.x,y:e.y,z:e.z,order:e.order}}}const nR=new iR;class oR extends Zi{constructor(){super(M,"ObjectSerializer")}onSerialize(e,t){if(t.objectToNode!==void 0&&e.uuid){const i=t.objectToNode[e.uuid];return bt&&console.log(i,e.name,e.uuid),{node:i}}}onDeserialize(e,t){if(typeof e=="string"){if(e.endsWith(".glb")||e.endsWith(".gltf")){if(t.serializable instanceof Array&&t.serializable.includes(ne))return;A()&&be("Detected wrong usage of @serializable with Object3D or GameObject. Instead you should use AssetReference here! Please see the console for details.");const i=t.target?.constructor?.name;console.warn(`Wrong usage of @serializable detected in your script "${i}"
962
+ `;function ax(o){if(Z.active)return console.warn("[OrbitControls] Can not fit camera while XR session is active"),null;const e=U.Current;if(!e)return console.warn("[OrbitControls] No context found"),null;const t=o?.camera||e.mainCamera;if(!t)return console.warn("No camera or controls found to fit camera to objects..."),null;o||(o={}),o.autoApply=o.autoApply!==!1,o.minZoom||=0,o.maxZoom||=1/0;const{centerCamera:i,cameraNearFar:n="auto",fitOffset:s=1.1,fov:r=t instanceof de?t?.fov:-1}=o,a=new b,l=new b,c=t instanceof de?t.aspect:1,h=o.objects||e.scene,d=Ri(h,void 0,t?.layers),p=d.clone();d.getCenter(l);const m=new b;if(d.getSize(m),t instanceof de&&t.updateProjectionMatrix(),t.updateMatrixWorld(),d.applyMatrix4(t.matrixWorldInverse),d.getSize(a),d.setFromCenterAndSize(l,a),Number.isNaN(a.x)||Number.isNaN(a.y)||Number.isNaN(a.z))return console.warn("Camera fit size resultet in NaN",t,d),null;if(a.length()<=1e-10)return console.warn("Camera fit size is zero",d),null;const g=r,f=2*Math.atan(Math.tan(g*Math.PI/360/2)*c)/Math.PI*360,y=a.y/(2*Math.atan(Math.PI*g/360)),_=a.x/(2*Math.atan(Math.PI*f/360)),v=s*Math.max(y,_)+a.z/2;o.maxZoom=v*10,o.minZoom=v*.01,o.debug===!0&&console.log("Fit camera to objects",{fitHeightDistance:y,fitWidthDistance:_,distance:v,verticalFov:g,horizontalFov:f});const P=.05,k=l.clone();if(k.y-=a.y*P,o.targetOffset&&(o.targetOffset.x!==void 0&&(k.x+=o.targetOffset.x),o.targetOffset.y!==void 0&&(k.y+=o.targetOffset.y),o.targetOffset.z!==void 0&&(k.z+=o.targetOffset.z)),o.relativeTargetOffset&&(o.relativeTargetOffset.x!==void 0&&(k.x+=o.relativeTargetOffset.x*a.x),o.relativeTargetOffset.y!==void 0&&(k.y+=o.relativeTargetOffset.y*a.y),o.relativeTargetOffset.z!==void 0&&(k.z+=o.relativeTargetOffset.z*a.z)),n==null||n=="auto"){const L=tl(Kn),V=L?L.radius:0,W=Math.max(m.x,m.y,m.z,V);t instanceof de&&(t.near=v/100,t.far=W+v*10,t.updateProjectionMatrix()),L&&(o.maxZoom=Math.max(Math.min(o.maxZoom,V*.5),v))}o.currentZoom!==void 0&&(o.currentZoom<o.minZoom&&(o.minZoom=o.currentZoom*.9),o.currentZoom>o.maxZoom&&(o.maxZoom=o.currentZoom*1.1));const O=l.clone();o.fitDirection?O.sub(new b().copy(o.fitDirection).multiplyScalar(1e6)):O.sub(t.worldPosition),i==="y"&&(O.y=0),O.normalize(),O.multiplyScalar(v),i==="y"&&(O.y+=-P*4*v);let D=l.clone().sub(O);return o.cameraOffset&&(o.cameraOffset.x!==void 0&&(D.x+=o.cameraOffset.x),o.cameraOffset.y!==void 0&&(D.y+=o.cameraOffset.y),o.cameraOffset.z!==void 0&&(D.z+=o.cameraOffset.z)),o.relativeCameraOffset&&(o.relativeCameraOffset.x!==void 0&&(D.x+=o.relativeCameraOffset.x*a.x),o.relativeCameraOffset.y!==void 0&&(D.y+=o.relativeCameraOffset.y*a.y),o.relativeCameraOffset.z!==void 0&&(D.z+=o.relativeCameraOffset.z*a.z)),t.parent&&(D=t.parent.worldToLocal(D)),o.debug&&(B.DrawWireBox3(d,16777011,10),B.DrawWireBox3(p,65280,10)),o.autoApply&&(t.position.copy(D),t.lookAt(k),r>0&&t instanceof de&&(t.fov=r,t.updateProjectionMatrix())),{camera:t,position:D,lookAt:k,fov:o.fov}}var qE=Object.defineProperty,Lf=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&qE(e,t,n),n};class Wr extends E{constraintActive=!0;locked=!1;sources=[];setConstraintPosition(e){const t=this.sources[0];t&&(t.worldPosition=e)}}Lf([u()],Wr.prototype,"constraintActive"),Lf([u()],Wr.prototype,"locked"),Lf([u(M)],Wr.prototype,"sources");let Vr=class{bb=null;bb_pos=0;__init(o,e){return this.bb_pos=o,this.bb=e,this}x(){return this.bb.readFloat32(this.bb_pos)}y(){return this.bb.readFloat32(this.bb_pos+4)}z(){return this.bb.readFloat32(this.bb_pos+8)}static sizeOf(){return 12}static createVec3(o,e,t,i){return o.prep(4,12),o.writeFloat32(i),o.writeFloat32(t),o.writeFloat32(e),o.offset()}};class lx{bb=null;bb_pos=0;__init(e,t){return this.bb_pos=e,this.bb=t,this}position(e){return(e||new Vr).__init(this.bb_pos,this.bb)}rotation(e){return(e||new Vr).__init(this.bb_pos+12,this.bb)}scale(e){return(e||new Vr).__init(this.bb_pos+24,this.bb)}static sizeOf(){return 36}static createTransform(e,t,i,n,s,r,a,l,c,h){return e.prep(4,36),e.prep(4,12),e.writeFloat32(h),e.writeFloat32(c),e.writeFloat32(l),e.prep(4,12),e.writeFloat32(a),e.writeFloat32(r),e.writeFloat32(s),e.prep(4,12),e.writeFloat32(n),e.writeFloat32(i),e.writeFloat32(t),e.offset()}}class ms{bb=null;bb_pos=0;__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsSyncedTransformModel(e,t){return(t||new ms).__init(e.readInt32(e.position())+e.position(),e)}static getSizePrefixedRootAsSyncedTransformModel(e,t){return e.setPosition(e.position()+Wb),(t||new ms).__init(e.readInt32(e.position())+e.position(),e)}guid(e){const t=this.bb.__offset(this.bb_pos,4);return t?this.bb.__string(this.bb_pos+t,e):null}fast(){const e=this.bb.__offset(this.bb_pos,6);return e?!!this.bb.readInt8(this.bb_pos+e):!1}transform(e){const t=this.bb.__offset(this.bb_pos,8);return t?(e||new lx).__init(this.bb_pos+t,this.bb):null}dontSave(){const e=this.bb.__offset(this.bb_pos,10);return e?!!this.bb.readInt8(this.bb_pos+e):!1}static startSyncedTransformModel(e){e.startObject(4)}static addGuid(e,t){e.addFieldOffset(0,t,0)}static addFast(e,t){e.addFieldInt8(1,+t,0)}static addTransform(e,t){e.addFieldStruct(2,t,0)}static addDontSave(e,t){e.addFieldInt8(3,+t,0)}static endSyncedTransformModel(e){return e.endObject()}static finishSyncedTransformModelBuffer(e,t){e.finish(t)}static finishSizePrefixedSyncedTransformModelBuffer(e,t){e.finish(t,void 0,!0)}}var T;(o=>{(e=>{e.MAYBEMODULE=null;const t=[];function i(){return e.MODULE?Promise.resolve(e.MODULE):new Promise(s=>{t.push(s)})}e.ready=i;async function n(){if(e.MODULE)return e.MODULE;const s=await import("./materialx-D_ofN96q.min.js");return e.MODULE=s,e.MAYBEMODULE=s,t.forEach(r=>r(s)),t.length=0,s}e.load=n})(o.MaterialX||(o.MaterialX={})),(e=>{e.MAYBEMODULE=null;const t=[];function i(){return e.MODULE?Promise.resolve(e.MODULE):new Promise(s=>{t.push(s)})}e.ready=i;async function n(){if(e.MODULE)return e.MODULE;const s=await import("./rapier-DJ-luMxr.min.js");return e.MODULE=s,e.MAYBEMODULE=s,t.forEach(r=>r(s)),t.length=0,s}e.load=n})(o.RAPIER_PHYSICS||(o.RAPIER_PHYSICS={})),(e=>{e.MAYBEMODULE=null;const t=[];function i(){return e.MODULE?Promise.resolve(e.MODULE):new Promise(s=>{t.push(s)})}e.ready=i;async function n(){if(e.MODULE)return e.MODULE;const s=await import("./postprocessing-DXm8YKbQ.min.js").then(r=>r.index);return e.MODULE=s,e.MAYBEMODULE=s,t.forEach(r=>r(s)),t.length=0,s}e.load=n})(o.POSTPROCESSING||(o.POSTPROCESSING={})),(e=>{e.MAYBEMODULE=null;const t=[];function i(){return e.MODULE?Promise.resolve(e.MODULE):new Promise(s=>{t.push(s)})}e.ready=i;async function n(){if(e.MODULE)return e.MODULE;const s=await import("./postprocessing-DXm8YKbQ.min.js").then(r=>r.N8AO);return e.MODULE=s,e.MAYBEMODULE=s,t.forEach(r=>r(s)),t.length=0,s}e.load=n})(o.POSTPROCESSING_AO||(o.POSTPROCESSING_AO={}))})(T||(T={}));var vt=(o=>(o[o.Average=0]="Average",o[o.Multiply=1]="Multiply",o[o.Minimum=2]="Minimum",o[o.Maximum=3]="Maximum",o))(vt||{}),ju=(o=>(o[o.Discrete=0]="Discrete",o[o.Continuous=1]="Continuous",o))(ju||{}),Ze=(o=>(o[o.None=0]="None",o[o.FreezePositionX=2]="FreezePositionX",o[o.FreezePositionY=4]="FreezePositionY",o[o.FreezePositionZ=8]="FreezePositionZ",o[o.FreezePosition=14]="FreezePosition",o[o.FreezeRotationX=16]="FreezeRotationX",o[o.FreezeRotationY=32]="FreezeRotationY",o[o.FreezeRotationZ=64]="FreezeRotationZ",o[o.FreezeRotation=112]="FreezeRotation",o[o.FreezeAll=126]="FreezeAll",o))(Ze||{}),cl=(o=>(o[o.None=0]="None",o[o.X=2]="X",o[o.Y=4]="Y",o[o.Z=8]="Z",o[o.All=-1]="All",o))(cl||{});const Mt=function(o,e){return function(t,i,n){XE(t,i,n,o,e)}};function XE(o,e,t,i,n){if(!n&&!i&&!o.onValidate)return;if(t!==void 0){console.error("Invalid usage of validate decorator. Only fields can be validated.",o,e,t),Oe("Invalid usage of validate decorator. Only fields can be validated. Property: "+e,{type:Ei.Error});return}let s="";if(typeof e=="string"?s=e:s=e.name,o.__internalAwake){const r=Symbol(s),a=o.__internalAwake;o.__internalAwake=function(){if(!this.onValidate){A()&&console.warn('Usage of @validate decorate detected but there is no onValidate method in your class: "'+o.constructor?.name+'"');return}if(this[r]===void 0){this[r]=this[s];const l=this[s];if(l instanceof K||l instanceof b||l instanceof ye||l instanceof N){const c=this[s];Bd(c,()=>{this.onValidate(s)})}Object.defineProperty(this,s,{set:function(c){if(this[af]===!0)this[r]=c;else{i?.call(this,c);const h=this[r];this[r]=c,this.onValidate?.call(this,s,h)}},get:function(){return n?.call(this),this[r]}})}a.call(this)}}}const QE=function(o){return function(e,t,i){let n="";typeof t=="string"?n=t:n=t.name;const s=o.prototype,r=Object.getOwnPropertyDescriptor(s,n);if(!r?.value){console.warn("Can not apply prefix: type does not have method named",t,o);return}const a=r.value,l=e[n];Object.defineProperty(s,n,{value:function(...c){const h=l?.call(this,...c);if(h instanceof Promise){h.then(d=>{if(d!==!1)return a.call(this,...c)});return}if(h!==!1)return a.call(this,...c)}})}};var YE=Object.defineProperty,ZE=Object.getOwnPropertyDescriptor,Li=(o,e,t,i)=>{for(var n=i>1?void 0:i?ZE(e,t):e,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&YE(e,t,n),n};class KE{get isDirty(){return this.positionChanged||this.rotationChanged}positionChanged=!1;rotationChanged=!1;position;quaternion;_positionKeys=["x","y","z"];_quaternionKeys=["_x","_y","_z","_w"];reset(e=!1){if(this.positionChanged=!1,this.rotationChanged=!1,this.mute=!1,e){if(this.position)for(const t of this._positionKeys)delete this.position[t];if(this.quaternion)for(const t of this._quaternionKeys)delete this.quaternion[t]}}syncValues(){for(const e of this._positionKeys)this.position[e]=this.obj.position[e];for(const e of this._quaternionKeys)this.quaternion[e]=this.obj.quaternion[e]}mute=!1;applyValues(){if(this.positionChanged&&this.position)for(const e of this._positionKeys){const t=this.position[e];t!==void 0&&(this.obj.position[e]=t)}if(this.rotationChanged&&this.quaternion)for(const e of this._quaternionKeys){const t=this.quaternion[e];t!==void 0&&(this.obj.quaternion[e]=t)}}context;obj;_positionWatch;_rotationWatch;constructor(e,t){this.context=t,this.obj=e}start(e,t){this.reset(),e&&(this._positionWatch||(this._positionWatch=new us(this.obj.position,["x","y","z"])),this._positionWatch.apply(),this.position={},this._positionWatch.subscribeWrite((s,r)=>{if(this.context.physics.engine?.isUpdating||this.mute)return;const a=this.position[r];Math.abs(a-s)<1e-5||(this.position[r]=s,this.positionChanged=!0)})),t&&(this._rotationWatch||(this._rotationWatch=new us(this.obj.quaternion,["_x","_y","_z","_w"])),this._rotationWatch.apply(),this.quaternion={},this._rotationWatch.subscribeWrite((s,r)=>{if(this.context.physics.engine?.isUpdating||this.mute)return;const a=this.quaternion[r];Math.abs(a-s)<1e-5||(this.quaternion[r]=s,this.rotationChanged=!0)}));const i=this.obj.matrixWorld.multiplyMatrices.bind(this.obj.matrixWorld),n=new J;this.obj.matrixWorld.multiplyMatrices=(s,r)=>(this.context.physics.engine?.isUpdating||this.mute||n.equals(s)||(this.positionChanged=!0,this.rotationChanged=!0,n.copy(s)),i(s,r))}stop(){this._positionWatch?.revoke(),this._rotationWatch?.revoke()}}const mi=class fm extends E{get isRigidbody(){return!0}autoMass=!0;set mass(e){e!==this._mass&&(this._mass=e,this._propertiesChanged=!0,this.__didAwake&&(this.autoMass=!1))}get mass(){return this.autoMass?this.context.physics.engine?.getBody(this)?.mass()??-1:this._mass}_mass=0;useGravity=!0;centerOfMass=new b(0,0,0);constraints=Ze.None;isKinematic=!1;drag=0;angularDrag=1;detectCollisions=!0;sleepThreshold=.01;collisionDetectionMode=ju.Discrete;get lockPositionX(){return(this.constraints&Ze.FreezePositionX)!==0}get lockPositionY(){return(this.constraints&Ze.FreezePositionY)!==0}get lockPositionZ(){return(this.constraints&Ze.FreezePositionZ)!==0}get lockRotationX(){return(this.constraints&Ze.FreezeRotationX)!==0}get lockRotationY(){return(this.constraints&Ze.FreezeRotationY)!==0}get lockRotationZ(){return(this.constraints&Ze.FreezeRotationZ)!==0}set lockPositionX(e){e?this.constraints|=Ze.FreezePositionX:this.constraints&=~Ze.FreezePositionX}set lockPositionY(e){e?this.constraints|=Ze.FreezePositionY:this.constraints&=~Ze.FreezePositionY}set lockPositionZ(e){e?this.constraints|=Ze.FreezePositionZ:this.constraints&=~Ze.FreezePositionZ}set lockRotationX(e){e?this.constraints|=Ze.FreezeRotationX:this.constraints&=~Ze.FreezeRotationX}set lockRotationY(e){e?this.constraints|=Ze.FreezeRotationY:this.constraints&=~Ze.FreezeRotationY}set lockRotationZ(e){e?this.constraints|=Ze.FreezeRotationZ:this.constraints&=~Ze.FreezeRotationZ}set gravityScale(e){this._gravityScale=e}get gravityScale(){return this._gravityScale}_gravityScale=1;dominanceGroup=0;static tempPosition=new b;_propertiesChanged=!1;_currentVelocity=new b;_smoothedVelocity=new b;_smoothedVelocityGetter=new b;_lastPosition=new b;_watch;awake(){this._watch=void 0,this._propertiesChanged=!1}onEnable(){this._watch||(this._watch=new KE(this.gameObject,this.context)),this._watch.start(!0,!0),this.startCoroutine(this.beforePhysics(),xe.LateUpdate),A()&&(globalThis.NEEDLE_USE_RAPIER?T.RAPIER_PHYSICS.ready().then(async()=>{await mc(3),this.context.physics.engine?.getBody(this)||console.warn(`Rigidbody could not be created. Ensure "${this.name}" has a Collider component.`)}):console.warn("Rigidbody could not be created: Rapier physics are explicitly disabled."))}onDisable(){this._watch?.stop(),this.context.physics.engine?.removeBody(this)}onDestroy(){this.context.physics.engine?.removeBody(this)}onValidate(){this._propertiesChanged=!0}*beforePhysics(){for(;;)this._propertiesChanged&&(this._propertiesChanged=!1,this.context.physics.engine?.updateProperties(this)),this._watch?.isDirty?(this._watch.mute=!0,this._watch.applyValues(),this.context.physics.engine?.updateBody(this,this._watch.positionChanged,this._watch.rotationChanged),this._watch.reset()):this._watch?.syncValues(),this.captureVelocity(),yield}teleport(e,t=!0){this._watch?.reset(!0),t?this.gameObject.position.set(e.x,e.y,e.z):this.setWorldPosition(e.x,e.y,e.z),this.resetForcesAndTorques(),this.resetVelocities()}resetForces(e=!0){this.context.physics.engine?.resetForces(this,e)}resetTorques(e=!0){this.context.physics.engine?.resetTorques(this,e)}resetVelocities(){this.setVelocity(0,0,0),this.setAngularVelocity(0,0,0)}resetForcesAndTorques(){this.resetForces(),this.resetTorques()}wakeUp(){this.context.physics.engine?.wakeup(this)}get isSleeping(){return this.context.physics.engine?.isSleeping(this)}updateProperties(){return this._propertiesChanged=!1,this.context.physics.engine?.updateProperties(this)}applyForce(e,t,i=!0){this._propertiesChanged&&this.updateProperties(),this.context.physics.engine?.addForce(this,e,i)}applyImpulse(e,t=!0){this._propertiesChanged&&this.updateProperties(),this.context.physics.engine?.applyImpulse(this,e,t)}setForce(e,t,i,n=!0){this.context.physics.engine?.resetForces(this,n),typeof e=="number"?(t??=0,i??=0,this.context.physics.engine?.addForce(this,{x:e,y:t,z:i},n)):this.context.physics.engine?.addForce(this,e,n)}getVelocity(){const e=this.context.physics.engine?.getLinearVelocity(this);return e?(this._currentVelocity.x=e.x,this._currentVelocity.y=e.y,this._currentVelocity.z=e.z,this._currentVelocity):this._currentVelocity.set(0,0,0)}setVelocity(e,t,i,n=!0){if(e instanceof b){const s=e;this.context.physics.engine?.setLinearVelocity(this,s,n);return}t===void 0||i===void 0||this.context.physics.engine?.setLinearVelocity(this,{x:e,y:t,z:i},n)}getAngularVelocity(){const e=this.context.physics.engine?.getAngularVelocity(this);return e?(this._currentVelocity.x=e.x,this._currentVelocity.y=e.y,this._currentVelocity.z=e.z,this._currentVelocity):this._currentVelocity.set(0,0,0)}setAngularVelocity(e,t,i,n=!0){if(typeof e=="object"){const s=e;this.context.physics.engine?.setAngularVelocity(this,s,n);return}if(t===void 0||i===void 0||typeof t=="boolean"){console.warn("setAngularVelocity expects either a Vec3 or 3 numbers");return}this.context.physics.engine?.setAngularVelocity(this,{x:e,y:t,z:i},n)}setTorque(e,t,i){typeof e=="number"?this.setAngularVelocity(e,t,i):this.setAngularVelocity(e)}get smoothedVelocity(){return this._smoothedVelocityGetter.copy(this._smoothedVelocity),this._smoothedVelocityGetter.multiplyScalar(1/this.context.time.deltaTime)}setBodyFromGameObject(e=null){}captureVelocity(){const e=this.gameObject.matrixWorld;fm.tempPosition.setFromMatrixPosition(e);const t=fm.tempPosition.sub(this._lastPosition);this._lastPosition.copy(fm.tempPosition),this._smoothedVelocity.lerp(t,this.context.time.deltaTime/.1)}};Li([Mt()],mi.prototype,"autoMass",2),Li([u()],mi.prototype,"mass",1),Li([Mt(),u()],mi.prototype,"useGravity",2),Li([u(b)],mi.prototype,"centerOfMass",2),Li([Mt(),u()],mi.prototype,"constraints",2),Li([Mt(),u()],mi.prototype,"isKinematic",2),Li([Mt(),u()],mi.prototype,"drag",2),Li([Mt(),u()],mi.prototype,"angularDrag",2),Li([Mt(),u()],mi.prototype,"detectCollisions",2),Li([Mt(),u()],mi.prototype,"sleepThreshold",2),Li([Mt(),u()],mi.prototype,"collisionDetectionMode",2),Li([Mt()],mi.prototype,"_gravityScale",2),Li([Mt()],mi.prototype,"dominanceGroup",2);let Ke=mi;new b,new b;const As=w("debugsync"),Qc="STRS";kg(Qc,ms.getRootAsSyncedTransformModel);const Jn=new zm;function cx(o,e,t=!0){Jn.clear();const i=Jn.createString(o);ms.startSyncedTransformModel(Jn),ms.addGuid(Jn,i),ms.addFast(Jn,t);const n=e.worldPosition,s=e.worldEuler,r=e.gameObject.scale;ms.addTransform(Jn,lx.createTransform(Jn,n.x,n.y,n.z,s.x,s.y,s.z,r.x,r.y,r.z));const a=ms.endSyncedTransformModel(Jn);return Jn.finish(a,Qc),Jn.asUint8Array()}let Df=0,Yc=0;Vw(o=>{const e=o.connection.currentServerUrl?.includes("glitch")?10:40;Yc=Math.floor(Df/e),Df=0,As&&Yc>0&&console.log("Sync Transform Fast Interval",Yc)});class Tn extends E{overridePhysics=!0;interpolatePosition=!0;interpolateRotation=!0;fastMode=!1;syncDestroy=!1;_model=null;_needsUpdate=!0;rb=null;_wasKinematic=!1;_receivedDataBefore=!1;_targetPosition;_targetRotation;_receivedFastUpdate=!1;_shouldRequestOwnership=!1;requestOwnership(){As&&console.log("Request ownership"),this._model?this._model.requestOwnership():(this._shouldRequestOwnership=!0,this._needsUpdate=!0)}freeOwnership(){this._model?.freeOwnership()}hasOwnership(){return this._model?.hasOwnership??void 0}isOwned(){return this._model?.isOwned}joinedRoomCallback=null;receivedDataCallback=null;awake(){As&&console.log("new instance",this.guid,this),this._receivedDataBefore=!1,this._targetPosition=new b,this._targetRotation=new N,this.lastPosition=new b,this.lastRotation=new N,this.lastScale=new b,this.rb=S.getComponentInChildren(this.gameObject,Ke),this.rb&&(this._wasKinematic=this.rb.isKinematic),this.receivedUpdate=!0,this._model=new Eg(this.context.connection,this.guid),this.context.connection.isConnected&&this.tryGetLastState(),this.joinedRoomCallback=this.tryGetLastState.bind(this),this.context.connection.beginListen(ie.JoinedRoom,this.joinedRoomCallback),this.receivedDataCallback=this.onReceivedData.bind(this),this.context.connection.beginListenBinary(Qc,this.receivedDataCallback)}onDestroy(){this.syncDestroy&&Yg(this.guid,this.context.connection),this._model=null,this.context.connection.stopListen(ie.JoinedRoom,this.joinedRoomCallback),this.context.connection.stopListenBinary(Qc,this.receivedDataCallback)}tryGetLastState(){const e=this.context.connection.tryGetState(this.guid);e&&this.onReceivedData(e)}tempEuler=new at;onReceivedData(e){if(!this.destroyed&&typeof e.guid=="function"&&e.guid()===this.guid){As&&console.log("new data",this.context.connection.connectionId,this.context.time.frameCount,this.guid,e),this.receivedUpdate=!0,this._receivedFastUpdate=e.fast();const t=e.transform();if(t){pn.markDirty(this.gameObject,!0);const i=t.position();i&&(this.interpolatePosition&&this._targetPosition?.set(i.x(),i.y(),i.z()),(!this.interpolatePosition||!this._receivedDataBefore)&&this.setWorldPosition(i.x(),i.y(),i.z()));const n=t.rotation();n&&(this.tempEuler.set(n.x(),n.y(),n.z()),this.interpolateRotation&&this._targetRotation.setFromEuler(this.tempEuler),(!this.interpolateRotation||!this._receivedDataBefore)&&hg(this.gameObject,this.tempEuler));const s=t.scale();s&&this.gameObject.scale.set(s.x(),s.y(),s.z())}this._receivedDataBefore=!0}}onEnable(){this.lastPosition.copy(this.worldPosition),this.lastRotation.copy(this.worldQuaternion),this.lastScale.copy(this.gameObject.scale),this._needsUpdate=!0,this._model&&this._model.updateIsOwned()}onDisable(){this._model&&this._model.freeOwnership()}receivedUpdate=!1;lastPosition;lastRotation;lastScale;onBeforeRender(){if(!this.activeAndEnabled||!this.context.connection.isConnected)return;if(!this.context.connection.isInRoom||!this._model){As&&console.log("no model or room",this.name,this.guid,this.context.connection.isInRoom);return}this._shouldRequestOwnership&&(this._shouldRequestOwnership=!1,this._model.requestOwnership());const e=this.worldPosition,t=this.worldQuaternion,i=this.gameObject.scale;if(this._model.isOwned&&!this.receivedUpdate){const r=this._model.hasOwnership||this.fastMode?1e-4:.001;(e.distanceTo(this.lastPosition)>r||t.angleTo(this.lastRotation)>r||i.distanceTo(this.lastScale)>r)&&(this._model.hasOwnership?this._needsUpdate=!0:(As&&console.log(this.guid,"reset because not owned but",this.gameObject.name,this.lastPosition),this.worldPosition=this.lastPosition,e.copy(this.lastPosition),this.worldQuaternion=this.lastRotation,t.copy(this.lastRotation),this.gameObject.scale.copy(this.lastScale),pn.markDirty(this.gameObject,!0),this._needsUpdate=!1))}if(this._model&&!this._model.hasOwnership&&this._model.isOwned&&this._receivedDataBefore){const r=this._receivedFastUpdate||this.fastMode?.5:.3;let a=!1;if(this.interpolatePosition&&this._targetPosition){const l=this.worldPosition;l.lerp(this._targetPosition,r),this.worldPosition=l,a=!0}if(this.interpolateRotation&&this._targetRotation){const l=this.worldQuaternion;l.slerp(this._targetRotation,r),this.worldQuaternion=l,a=!0}a&&pn.markDirty(this.gameObject,!0)}if(this.receivedUpdate=!1,this.lastPosition.copy(e),this.lastRotation.copy(t),this.lastScale.copy(i),!this._model||!this._model||this._model.hasOwnership===void 0||!this._model.hasOwnership)return;this.rb&&this.overridePhysics&&this._wasKinematic!==void 0&&(As&&console.log("reset kinematic",this.rb.name,this._wasKinematic),this.rb.isKinematic=this._wasKinematic);const n=10,s=this.rb||this.fastMode;if(this._needsUpdate&&(this.context.time.frameCount%n===0||s)){if(Df++,s&&Yc>0&&this.context.time.frameCount%Yc!==0)return;As&&console.debug("[SyncedTransform] Send update",this.context.connection.connectionId,this.guid,this.gameObject.name,this.gameObject.guid),this._needsUpdate=!1;const r=cx(this.guid,this,!!s);this.context.connection.sendBinary(r)}}}class vd{event;get deviceIndex(){return this.event.deviceIndex}get pointerId(){return this.event.pointerId}button;buttonName;get pressure(){return this.event.pressure}get used(){return this._used}_used=!1;use(){this._used||(this._used=!0,this.event.use())}_propagationStopped=!1;get propagationStopped(){return this._propagationStopped}stopPropagation(){this._propagationStopped=!0,this.event.stopImmediatePropagation()}stopImmediatePropagation(){this._propagationStopped=!0,this.event.stopImmediatePropagation()}z__pointer_ctured=!1;setPointerCapture(){this.z__pointer_ctured=!0}z__pointer_cture_rleased=!1;releasePointerCapture(){this.z__pointer_cture_rleased=!0}inputSource;get mode(){return this.event.mode}object;point;normal;face;distance;instanceId;intersection;isDown;isUp;isPressed;isClick;isDoubleClick;input;constructor(e,t){this.event=t,this.input=e,this.button=t.button}clone(){const e=new vd(this.input,this.event);return Object.assign(e,this),e}Use(){this.use()}StopPropagation(){this.event.stopImmediatePropagation()}}function Bu(o,e){return S.foreachComponent(o,t=>{if(!t.enabled)return;const i=t;if(e)switch(e){case"pointerdown":if(i.onPointerDown)return!0;break;case"pointerup":if(i.onPointerUp||i.onPointerClick)return!0;break;case"pointermove":if(i.onPointerEnter||i.onPointerExit||i.onPointerMove)return!0;break}else if(i.onPointerDown||i.onPointerUp||i.onPointerEnter||i.onPointerExit||i.onPointerClick)return!0},!1)===!0}const Uo=new Array;class zo{enabled=!0;target;methodName;arguments;get canClone(){return this.target instanceof Object}constructor(e,t,i,n){this.target=e,this.methodName=t||null,this.arguments=i,n!=null&&(this.enabled=n)}invoke(...e){if(this.enabled!==!1){if(typeof this.target=="function")this.arguments?(Uo.length=0,e!==void 0&&e.length>0&&Uo.push(...e),Uo.push(...this.arguments),this.target(...this.arguments),Uo.length=0):this.target(...e);else if(this.methodName!=null){const t=this.target[this.methodName];typeof t=="function"?this.arguments?(Uo.length=0,e!==void 0&&e.length>0&&Uo.push(...e),Uo.push(...this.arguments),t.call(this.target,...Uo),Uo.length=0):t.call(this.target,...e):this.arguments?e!==void 0&&e.length>0?this.target[this.methodName]=e[0]:this.target[this.methodName]=this.arguments[0]:this.target[this.methodName]=e[0]}}}}const JE=o=>/^[A-Z]*$/.test(o);class Fu extends Event{args}class ae{isEventList=!0;__internalOnInstantiate(e){const t=new Array;for(let i=0;i<this.methods.length;i++){const n=this.methods[i];if(!(n.target instanceof Function)){const s=n.target;let r=s?.uuid;if(s&&(r=s.guid),r){const a=e[r];if(a){const l=n.arguments?.map(c=>c instanceof Object&&c.uuid?e[c.uuid].clone:c?.isComponent?e[c.guid].clone:c);t.push(new zo(a.clone,n.methodName,l,n.enabled))}else A()&&console.warn("Could not find target for event listener")}}}return new ae(t)}target;key;setEventTarget(e,t){if(this.key=e,this.target=t,this.key!==void 0){let i="",n=!1;for(const s of this.key)n&&JE(s)&&(i+="-"),n=!0,i+=s.toLowerCase();this.key=i}}get listenerCount(){return this.methods?.length??0}get isInvoking(){return this._isInvoking}_isInvoking=!1;methods=[];_methodsCopy=[];static from(...e){return new ae(e)}constructor(e){if(this.methods=[],Array.isArray(e))for(const t of e)t instanceof zo?this.methods.push(t):typeof t=="function"&&this.methods.push(new zo(t));else typeof e=="function"&&this.methods.push(new zo(e))}invoke(...e){if(this._isInvoking)return console.warn("Circular event invocation detected. Please check your event listeners for circular references.",this),!1;if(this.methods?.length<=0)return!1;this._isInvoking=!0;try{this._methodsCopy.length=0,this._methodsCopy.push(...this.methods);for(const t of this._methodsCopy)t.invoke(...e);if(typeof this.target=="object"&&typeof this.key=="string"){const t=this.target.dispatchEvent;if(typeof t=="function"){const i=new Fu(this.key);i.args=e,t.call(this.target,i)}}}finally{this._isInvoking=!1,this._methodsCopy.length=0}return!0}addEventListener(e){return this.methods.push(new zo(e)),e}removeEventListener(e){if(e)for(let t=this.methods.length-1;t>=0;t--)this.methods[t].target===e&&(this.methods[t].enabled=!1,this.methods.splice(t,1))}removeAllEventListeners(){this.methods.length=0}}class eR extends Zi{constructor(){super([oe,se],"ColorSerializer")}onDeserialize(e){if(e!=null)return e.a!==void 0?new se(e.r,e.g,e.b,e.a):e.alpha!==void 0?new se(e.r,e.g,e.b,e.alpha):new oe(e.r,e.g,e.b)}onSerialize(e){if(e!=null)return e.a!==void 0?{r:e.r,g:e.g,b:e.b,a:e.a}:{r:e.r,g:e.g,b:e.b}}}const tR=new eR;class iR extends Zi{constructor(){super([at],"EulerSerializer")}onDeserialize(e,t){if(e!=null){if(e.order)return new at(e.x,e.y,e.z,e.order);if(e.x!=null)return new at(e.x,e.y,e.z)}}onSerialize(e,t){return{x:e.x,y:e.y,z:e.z,order:e.order}}}const nR=new iR;class oR extends Zi{constructor(){super(M,"ObjectSerializer")}onSerialize(e,t){if(t.objectToNode!==void 0&&e.uuid){const i=t.objectToNode[e.uuid];return bt&&console.log(i,e.name,e.uuid),{node:i}}}onDeserialize(e,t){if(typeof e=="string"){if(e.endsWith(".glb")||e.endsWith(".gltf")){if(t.serializable instanceof Array&&t.serializable.includes(ne))return;A()&&be("Detected wrong usage of @serializable with Object3D or GameObject. Instead you should use AssetReference here! Please see the console for details.");const i=t.target?.constructor?.name;console.warn(`Wrong usage of @serializable detected in your script "${i}"
963
963
 
964
964
  It looks like you used @serializable(Object3D) or @serializable(GameObject) for a prefab or scene reference which is exported to a separate glTF file.
965
965
 
@@ -976,10 +976,10 @@ Using the assigned clip instead:`,this.clip),e=this.clip);let t=!this.sound||e&&
976
976
  Audio:`,s.getAudioTracks(),`
977
977
  Video:`,s.getVideoTracks()),this._stream=s,i==="incoming"){const r=new gx(e,s,this);this.dispatchEvent(r)}}),t.on("close",()=>{this.dispatchEvent(new Nf(e,i))})}}function yx(o){return o=o.replace("a=fmtp:111 minptime=10;useinbandfec=1","a=fmtp:111 ptime=5;useinbandfec=1;stereo=1;maxplaybackrate=48000;maxaveragebitrat=128000;sprop-stereo=1"),o}class gs extends Im{static instances=new Map;static getOrCreate(e,t){if(gs.instances.has(t))return gs.instances.get(t);const i=new gs(e,t);return gs.instances.set(t,i),i}getMyPeerId(){if(this.context.connection.connectionId)return this.getPeerIdFromUserId(this.context.connection.connectionId)}getPeerIdFromUserId(e){return this.id+"-"+e}getUserIdFromPeerId(e){return e.substring(this.id.length+1)}makeCall(e,t){if(!t?.id){De?console.warn("Can not make a call: mediastream has no id or is undefined"):console.debug("Can not make a call: mediastream has no id or is undefined");return}const i={metadata:{userId:this.context.connection.connectionId,streamId:t.id},sdpTransform:s=>yx(s)},n=this._peer?.call(e,t,i);if(n){const s=this.registerCall(n,"outgoing",t);return De&&console.warn(`\u{1F4DE} CALL ${e}`,`
978
978
  Outgoing:`,this._outgoingCalls,`
979
- Incoming:`,this._incomingCalls),s}else De&&console.error("Failed to make call",e,t,this._peer)}closeAll(){for(const e of this._incomingCalls)e.close();for(const e of this._outgoingCalls)e.close();this.updateCalls()}updateCalls=()=>{for(let e=this._incomingCalls.length-1;e>=0;e--){const t=this._incomingCalls[e];t.isClosed&&!t.isOpening&&this._incomingCalls.splice(e,1)}for(let e=this._outgoingCalls.length-1;e>=0;e--){const t=this._outgoingCalls[e];let i=!1;t.isClosed&&!t.isOpening&&(t.stream?.active?De&&console.warn("!!! Stream is still active, don't remove call",t.userId,"Your id: "+this.context.connection.connectionId):(De&&console.warn("!!! Remove closed call",t.userId),i=!0)),this.context.connection.userIsInRoom(t.userId)===!1&&(De&&console.warn("!!! User is not in room anymore, remove call",t.userId),i=!0),i&&(t.close(),this._outgoingCalls.splice(e,1))}};get peer(){return this._peer}get incomingCalls(){return this._incomingCalls}id;context;_incomingCalls=[];_outgoingCalls=[];_peer;constructor(e,t){super(),this.context=e,this.id=t,this.setupPeer();const i=Object.getOwnPropertyDescriptor(navigator,"getUserMedia")?.writable;try{i?navigator.getUserMedia=navigator.getUserMedia||navigator.webkitGetUserMedia||navigator.mozGetUserMedia||navigator.msGetUserMedia:De&&console.warn("[PeerJs] getUserMedia is not writable")}catch(n){De&&console.error("[PeerJs] Error setting getUserMedia",n)}}_enabled=!1;_enabledPeer=!1;onConnectRoomFn=this.onConnectRoom.bind(this);enable(){this._enabled||(this._enabled=!0,this.context.connection.beginListen(ie.JoinedRoom,this.onConnectRoomFn),this.subscribePeerEvents())}disable(){this._enabled&&(this._enabled=!1,this.context.connection.stopListen(ie.JoinedRoom,this.onConnectRoomFn),this.unsubscribePeerEvents())}onConnectRoom(){this.setupPeer()}setupPeer(){if(this.context.connection.connectionId&&!this._enabledPeer){if(this._enabledPeer=!0,!this._peer){const e=this.getMyPeerId();e?this._peer=av(e):console.error("Failed to setup peerjs because we dont have a connection id",this.context.connection.connectionId)}this._enabled&&this.subscribePeerEvents()}}subscribePeerEvents(){this._peer&&(this._peer.on("open",this.onPeerConnect),this._peer.on("close",this.onPeerClose),this._peer.on("call",this.onPeerReceivingCall),this._peer.on("disconnected",this.onPeerDisconnected),this._peer.on("error",this.onPeerError))}unsubscribePeerEvents(){this._peer&&(this._peer.off("open",this.onPeerConnect),this._peer.off("close",this.onPeerClose),this._peer.off("call",this.onPeerReceivingCall),this._peer.off("disconnected",this.onPeerDisconnected),this._peer.off("error",this.onPeerError))}onPeerConnect=e=>{if(De&&console.log("PEER opened as",e),e===null){console.error("Peer connection failed",e);return}this.context.connection.send("peer-user-connected",new PR(this,e))};onPeerClose=()=>{De&&console.log("PEER closed"),this.updateCalls()};onPeerDisconnected=()=>{De&&console.log("PEER disconnected"),this.updateCalls()};onPeerError=e=>{De&&console.error("PEER error",e)};onPeerReceivingCall=e=>{e.answer(void 0,{sdpTransform:t=>yx(t)}),this.registerCall(e,"incoming",null)};registerCall(e,t,i){const n=e.metadata;(!n||!n.userId)&&console.error("Missing call metadata",e);const s=n.userId;t==="incoming"&&De?console.warn("\u2190 Receive call from",e.metadata,e.connectionId):De&&console.warn("\u2192 Make call to",e.metadata);const r=t==="incoming"?this._incomingCalls:this._outgoingCalls,a=new OR(s,e,t,i);return r.push(a),e.on("error",l=>{console.error("Call error",l)}),e.on("close",()=>{De&&console.log("Call ended",e.metadata);const l=r.indexOf(a);l!==-1&&r.splice(l,1),a.close(),this.dispatchEvent(new Nf(s,t))}),a.addEventListener("call-ended",l=>{this.dispatchEvent(l)}),t==="incoming"&&(a.addEventListener("receive-stream",l=>{this.dispatchEvent(l)}),e.on("stream",()=>{De&&console.log("Received stream for call",e.metadata);let l=0;const c=setInterval(()=>{const h=l===0;!a.isOpen&&h&&(De&&console.warn("Close call because stream is not active",e.metadata),l+=1,clearInterval(c),a.close())},2e3)})),a}}class wd extends Im{static create(e,t){const i=gs.getOrCreate(e.context,t||e.context.connection.connectionId||e.guid);return new wd(e.context,i)}context;peer;_sendingStreams=new Map;debug=!1;constructor(e,t){if(super(),bg(e)){const i=e;e=i.context,t=gs.getOrCreate(i.context,i.guid)}else typeof t=="string"&&(t=gs.getOrCreate(e,t));if(e){if(!(e instanceof U))throw new Error("Failed to create NetworkedStreams because context is not an instance of Context")}else throw new Error("Failed to create NetworkedStreams because context is undefined");if(!t)throw new Error("Failed to create NetworkedStreams because peer is undefined");this.context=e,this.peer=t,De&&(this.debug=!0)}startSendingStream(e){this._sendingStreams.has(e)?console.warn("Received start sending stream with stream that is already being sent"):(this._sendingStreams.set(e,[]),this.updateSendingCalls())}stopSendingStream(e){if(e){const t=this._sendingStreams.get(e);if(t){for(const i of t)i.close();t.length=0}this._sendingStreams.delete(e),t&&this.debug&&this.debugLogCurrentState()}this.updateSendingCalls()}_enabled=!1;get enabled(){return this._enabled}enable(){this._enabled||(this._enabled=!0,this.peer.enable(),this.peer.addEventListener("receive-stream",this.onCallStreamReceived),this.peer.addEventListener("call-ended",this.onCallEnded),this.context.connection.beginListen("peer-user-connected",this.onUserConnected),this.context.connection.beginListen(ie.JoinedRoom,this.onJoinedRoom),this.context.connection.beginListen(ie.UserJoinedRoom,this.onJoinedRoom),this.context.connection.beginListen(ie.UserLeftRoom,this.onUserLeft),this.context.connection.beginListen(ie.LeftRoom,this.onLeftRoom),this._tickIntervalId=setInterval(this.tick,5e3))}disable(){this._enabled&&(this._enabled=!1,this.peer.disable(),this.peer.removeEventListener("receive-stream",this.onCallStreamReceived),this.peer.removeEventListener("call-ended",this.onCallEnded),this.context.connection.stopListen("peer-user-connected",this.onUserConnected),this.context.connection.stopListen(ie.JoinedRoom,this.onJoinedRoom),this.context.connection.stopListen(ie.UserJoinedRoom,this.onJoinedRoom),this.context.connection.stopListen(ie.UserLeftRoom,this.onUserLeft),this.context.connection.stopListen(ie.LeftRoom,this.onLeftRoom),this._tickIntervalId!=null&&(clearInterval(this._tickIntervalId),this._tickIntervalId=void 0))}_tickIntervalId;tick=()=>{this.updateSendingCalls()};onJoinedRoom=e=>{this._sendingStreams.size>0&&(this.debug&&console.warn(`${e?.userId?`User ${e.userId}`:"You"} joined room`,e,this._sendingStreams.size),this.updateSendingCalls())};onLeftRoom=e=>{this.debug&&console.warn(`${e?.userId||"You"} left room`,e),this.stopCallsToUsersThatAreNotInTheRoomAnymore(),this.peer.closeAll()};onCallStreamReceived=e=>{this.debug&&console.log("Call with "+e.userId+" started"),this.dispatchEvent({type:"receive-stream",target:this,stream:e.stream,userId:e.userId}),this.debug&&this.debugLogCurrentState()};onCallEnded=e=>{this.debug&&console.log("Call with "+e.userId+" ended"),this.dispatchEvent(e),this.debug&&this.debugLogCurrentState()};onUserConnected=e=>{if(this.peer.id===e.guid){this.debug&&console.log("PEER USER CONNECTED",e.guid,e,this._sendingStreams.size);const t=this._sendingStreams.keys().next().value;if(!t)return;this.peer.makeCall(e.peerId,t)}else De&&console.log("Unknown user connected",e.guid,e.peerId)};onUserLeft=e=>{this.debug&&console.log("User left room: "+e.userId),this.stopCallsToUsersThatAreNotInTheRoomAnymore()};updateSendingCalls(){const e=this.context.connection.connectionId;for(const t of this._sendingStreams.keys()){const i=this._sendingStreams.get(t)||[];for(const n of this.context.connection.usersInRoom()){if(n===e)continue;const s=this.peer.getPeerIdFromUserId(n);if(i.find(r=>r.peerId===s&&r.direction==="outgoing"&&!r.isClosed&&r.stream?.active))De&&console.debug("Already have a call with user "+n+" / peer "+s);else{const r=this.peer.makeCall(s,t);r&&i.push(r)}}this._sendingStreams.set(t,i)}this.stopCallsToUsersThatAreNotInTheRoomAnymore()}stopCallsToUsersThatAreNotInTheRoomAnymore(){for(const e of this._sendingStreams.keys()){const t=this._sendingStreams.get(e);if(t)for(let i=t.length-1;i>=0;i--){const n=t[i];this.context.connection.userIsInRoom(n.userId)?De&&(this.context.connection.connectionId===n.userId?console.warn(`You are still in the room [${i}] ${n.userId}`):console.log(`User is still in room [${i}] ${n.userId}`)):(De&&console.log(`Remove call ${[i]} to user that is not in room anymore ${n.userId}`),n.close(),t.splice(i,1))}}this.peer.updateCalls(),this.debug&&this.debugLogCurrentState()}debugLogCurrentState(){console.warn(`You (${this.context.connection.connectionId}) are currently sending ${this._sendingStreams.size} and receiving ${this.peer.incomingCalls.length} calls (${this.peer.incomingCalls.map(e=>e.userId).join(", ")})`,this.peer.incomingCalls)}}function to(o){if(o&&o instanceof MediaStream)for(const e of o.getTracks())e.stop()}var kR=Object.defineProperty,Wf=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&kR(e,t,n),n};const MR="noVoip",ER=w("debugvoip");class Ds extends E{autoConnect=!0;runInBackground=!0;createMenuButton=!0;debug=!1;_net;_menubutton;awake(){ER&&(this.debug=!0),this.debug&&(console.log("VOIP debugging: press 'v' to toggle mute or 'c' to toggle connect/disconnect"),window.addEventListener("keydown",async e=>{switch(e.key.toLowerCase()){case"v":console.log("MUTE?",!this.isMuted),this.setMuted(!this.isMuted);break;case"c":this.isSending?this.disconnect():this.connect();break}}),window.addEventListener("blur",()=>{console.log("VOIP: MUTE ON BLUR"),this.setMuted(!0)}),window.addEventListener("focus",()=>{console.log("VOIP: UNMUTE ON FOCUS"),this.setMuted(!1)}))}onEnable(){this._net||(this._net=wd.create(this)),this.debug&&(this._net.debug=!0),this._net.addEventListener(eo.StreamReceived,this.onReceiveStream),this._net.addEventListener(eo.StreamEnded,this.onStreamEnded),this._net.enable(),this.autoConnect&&this.context.connection.isConnected&&this.connect(),this.context.connection.beginListen(ie.JoinedRoom,this.onJoinedRoom),this.context.connection.beginListen(ie.LeftRoom,this.onLeftRoom),this.onEnabledChanged(),this.updateButton(),window.addEventListener("visibilitychange",this.onVisibilityChanged)}onDisable(){this._net&&(this._net.stopSendingStream(this._outputStream),this._net.removeEventListener(eo.StreamReceived,this.onReceiveStream),this._net.removeEventListener(eo.StreamEnded,this.onStreamEnded),this._net?.disable()),this.context.connection.stopListen(ie.JoinedRoom,this.onJoinedRoom),this.context.connection.stopListen(ie.LeftRoom,this.onLeftRoom),this.onEnabledChanged(),this.updateButton(),window.removeEventListener("visibilitychange",this.onVisibilityChanged)}onDestroy(){this._menubutton?.remove(),this._menubutton=void 0}_allowSending=!0;_outputStream=null;get isSending(){return this._outputStream!=null&&this._outputStream.active}async connect(e){if(!this._net)return console.error("Cannot connect to voice chat - NetworkedStreams not initialized. Make sure the component is enabled before calling this method."),!1;if(this.context.connection.isConnected){if(!await I.microphonePermissionsGranted())return console.error("Cannot connect to voice chat - microphone permissions not granted"),this.updateButton(),!1}else return console.error("Cannot connect to voice chat - not connected to server"),this.updateButton(),!1;return this._allowSending=!0,this._net?.stopSendingStream(this._outputStream),to(this._outputStream),this._outputStream=await this.getAudioStream(e),this._outputStream?(this.debug&&console.log("VOIP: Got audio stream"),this._net?.startSendingStream(this._outputStream),this.updateButton(),!0):(this.updateButton(),await I.microphonePermissionsGranted()?console.error("VOIP: Could not get audio stream - please make sure to connect an audio device and grant microphone permissions"):_c("Microphone permissions not granted: Please grant microphone permissions to use voice chat"),(this.debug||A())&&console.log("VOIP: Failed to get audio stream"),!1)}disconnect(e){e?.remember&&(this._allowSending=!1),this._net?.stopSendingStream(this._outputStream),to(this._outputStream),this._outputStream=null,this.updateButton()}setMuted(e){const t=this._outputStream?.getAudioTracks();if(t)for(const i of t)i.enabled=!e}get isMuted(){if(this._outputStream===null)return!1;const e=this._outputStream?.getAudioTracks();if(e){for(const t of e)if(!t.enabled)return!0}return!1}async updateButton(){if(this.createMenuButton){if(this._menubutton||(this._menubutton=document.createElement("button"),this._menubutton.addEventListener("click",()=>{this.isSending?this.disconnect({remember:!0}):this.connect(),I.microphonePermissionsGranted().then(e=>{e||be("<strong>Microphone permissions not granted</strong>. Please allow your browser to use the microphone to be able to talk. Click on the button on the left side of your browser's address bar to allow microphone permissions.")})})),this._menubutton){this.context.menu.appendChild(this._menubutton),this.activeAndEnabled?this._menubutton.style.display="":this._menubutton.style.display="none",this._menubutton.title=this.isSending?"Click to disable your microphone":"Click to enable your microphone";let e=(this.isSending,""),t=this.isSending?"mic":"mic_off";await I.microphonePermissionsGranted()||(e="No Permission",t="mic_off",this._menubutton.title="Microphone permissions not granted. Please allow your browser to use the microphone to be able to talk. This can usually be done in the addressbar of the webpage."),this._menubutton.innerText=e,this._menubutton.prepend(Ot(t)),this.context.connection.isConnected==!1?this._menubutton.setAttribute("disabled",""):this._menubutton.removeAttribute("disabled")}}else this.activeAndEnabled||this._menubutton?.remove()}getFrequency(e){return this.unsupported_getfrequency||(this.unsupported_getfrequency=!0,A()&&be("VOIP: getFrequency is currently not supported"),console.warn("VOIP: getFrequency is currently not supported")),null}async getAudioStream(e){if(!navigator.mediaDevices.getUserMedia)return console.error("No getDisplayMedia support"),null;const t=async n=>await navigator.mediaDevices.getUserMedia({audio:n??!0,video:!1}).catch(s=>(console.warn("VOIP failed getting audio stream",s),null)),i=await t(e);if(!i)return null;if(I.isiOS()&&e?.deviceId===void 0){const n=(await navigator.mediaDevices.enumerateDevices()).find(s=>(s.kind==="audioinput"||s.kind==="audiooutput")&&!s.label.includes("iPhone"));if(n){const s=Object.assign({},e);return s.deviceId=n.deviceId,await t(s)}}return i}onJoinedRoom=async()=>{this.debug&&console.log("VOIP: Joined room"),await Ro(300),this.autoConnect&&!this.isSending&&this._allowSending&&this.connect()};onLeftRoom=()=>{this.debug&&console.log("VOIP: Left room"),this.disconnect();for(const e of this._incomingStreams.values())to(e.srcObject);this._incomingStreams.clear()};_incomingStreams=new Map;onReceiveStream=e=>{const t=e.target.userId,i=e.stream;let n=this._incomingStreams.get(t);n||(n=new Audio,this._incomingStreams.set(t,n)),n.srcObject=i,n.setAttribute("autoplay","true"),zn.registerWaitForInteraction(()=>{n?.play().catch(s=>{console.error("VOIP: Failed to play audio",s)})})};onStreamEnded=e=>{const t=this._incomingStreams.get(e.userId);to(t?.srcObject),this._incomingStreams.delete(e.userId)};onEnabledChanged=()=>{for(const e of this._incomingStreams){const t=e[1];t.muted=!this.enabled}};onVisibilityChanged=()=>{if(this.runInBackground)return;const e=document.visibilityState!=="visible";this.setMuted(e);for(const t of this._incomingStreams){const i=t[1];i.muted=e}}}Wf([u()],Ds.prototype,"autoConnect"),Wf([u()],Ds.prototype,"runInBackground"),Wf([u()],Ds.prototype,"createMenuButton");var RR=Object.defineProperty,bx=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&RR(e,t,n),n};const TR=w("debugmouth");class th extends E{idle=[];talking=[];marker=null;voip=null;lastMouthChangeTime=0;mouthChangeLength=0;awake(){setTimeout(()=>{this.voip=S.findObjectOfType(Ds,this.context),this.marker||(this.marker=S.getComponentInParent(this.gameObject,Le))},3e3)}update(){if(!this.voip||this.context.time.frameCount%10!==0)return;let e=this.marker?.connectionId??null;if(!e){TR&&(e=null);return}const t=this.voip.getFrequency(e)??0;this.updateLips(t)}updateLips(e){if(this.context.time.time-this.lastMouthChangeTime>this.mouthChangeLength){if(this.mouthChangeLength=.05+Math.random()*.1,this.talking&&this.talking.length>0&&e>30){this.lastMouthChangeTime=this.context.time.time;const t=Math.floor(Math.random()*this.talking.length);this.setMouthShapeActive(this.talking,t)}else if(this.idle.length>0&&this.context.time.time-this.lastMouthChangeTime>.5){this.lastMouthChangeTime=this.context.time.time;const t=Math.floor(Math.random()*this.idle.length);this.setMouthShapeActive(this.idle,t)}}}setMouthShapeActive(e,t){if(e){e!=this.idle?this.idle.map(i=>i.visible=!1):this.talking.map(i=>i.visible=!1);for(let i=0;i<e.length;i++){const n=e[i];n&&(n.visible=i===t)}}}}bx([u(M)],th.prototype,"idle"),bx([u(M)],th.prototype,"talking");class Vf extends E{voip=null;marker=null;_startPosition=null;awake(){this.voip=S.findObjectOfType(Ds,this.context),this.marker=S.getComponentInParent(this.gameObject,Le)}update(){if(!this.voip||!this.marker||this.context.time.frameCount%10!==0)return;const e=this.marker.connectionId,t=this.voip.getFrequency(e);if(t==null)return;this._startPosition||(this._startPosition=this.gameObject.position.clone());const i=t/100;this.gameObject.position.y=this._startPosition.y+i*.07}}var AR=Object.defineProperty,IR=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&AR(e,t,n),n};const dl=w("debugxrflags"),_x=w("disablexrflags");_x&&console.warn("XRFlags are disabled");var io=(o=>(o[o.Never=0]="Never",o[o.Browser=1]="Browser",o[o.AR=2]="AR",o[o.VR=4]="VR",o[o.FirstPerson=8]="FirstPerson",o[o.ThirdPerson=16]="ThirdPerson",o[o.All=4294967295]="All",o))(io||{});class ri{static Global=new ri;Mask=17;Has(e){return(this.Mask&e)!==0}Set(e){dl&&console.warn("Set XR flag state to",e),this.Mask=e,tn.Apply()}Enable(e){this.Mask|=e,tn.Apply()}Disable(e){this.Mask&=~e,tn.Apply()}Toggle(e){this.Mask^=e,tn.Apply()}EnableAll(){this.Mask=-1,tn.Apply()}DisableAll(){this.Mask=0,tn.Apply()}}const vx=class hs extends E{static registry=[];static Apply(){for(const e of this.registry)e.UpdateVisible(ri.Global)}static firstApply;static buffer=new ri;visibleIn;awake(){hs.registry.push(this)}onEnable(){hs.firstApply?this.UpdateVisible(ri.Global):(hs.firstApply=!0,hs.Apply())}onDestroy(){const e=hs.registry.indexOf(this);e>=0&&hs.registry.splice(e,1)}get isOn(){return this.gameObject.visible}UpdateVisible(e=null){if(_x)return;let t;const i=e;if(i&&typeof i=="number"&&(console.assert(typeof i=="number","XRFlag.UpdateVisible: state must be a number",i),dl&&console.log(i),hs.buffer.Mask=i,e=hs.buffer),e instanceof ri?(dl&&console.warn(this.name,"use passed in mask",e.Mask,this.visibleIn),t=e.Has(this.visibleIn)):(dl&&console.log(this.name,"use global mask"),ri.Global.Has(this.visibleIn)),t!==void 0)if(t)dl&&console.log(this.name,"is visible",this.gameObject.uuid),S.setActive(this.gameObject,!0);else{if(dl&&console.log(this.name,"is not visible",this.gameObject.uuid),!this.gameObject.visible)return;this.gameObject.visible=!1}}};IR([u()],vx.prototype,"visibleIn");let tn=vx;var LR=Object.defineProperty,$u=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&LR(e,t,n),n};class Gr extends E{eyes=[];lastBlinkTime=0;blinkLength=0;eyesOpen=!0;state=null;awake(){this.state=S.getComponentInParent(this.gameObject,tn)}update(){if(!(!this.gameObject||!this.gameObject.visible||!this.eyes||!Array.isArray(this.eyes)||this.eyes.length===0)&&this.context.time.time-this.lastBlinkTime>this.blinkLength){if(this.lastBlinkTime=this.context.time.time,this.state&&!this.state.isOn||!this.activeAndEnabled)return;if(this.eyesOpen=!this.eyesOpen,this.blinkLength=Math.random(),this.eyesOpen?(this.blinkLength*=3,this.blinkLength+=.5,Math.random()<.1&&(this.blinkLength=.1+Math.random()*.2)):(this.blinkLength*=Math.random()*.2,this.blinkLength+=.1),Math.random()<.1&&(this.blinkLength*=3),this.blinkLength=Math.max(.2,this.blinkLength),this.blinkLength=Math.min(3,this.blinkLength),this.eyes)for(const e of this.eyes)e&&(e.visible=this.eyesOpen)}}}$u([u(M)],Gr.prototype,"eyes"),$u([u()],Gr.prototype,"lastBlinkTime"),$u([u()],Gr.prototype,"blinkLength"),$u([u()],Gr.prototype,"eyesOpen");var DR=Object.defineProperty,$f=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&DR(e,t,n),n};const Hu=class LS extends E{head=null;eyes=null;target=null;brain=null;awake(){this.brain||(this.brain=S.getComponentInParent(this.gameObject,eh)),this.brain||(this.brain=S.addComponent(this.gameObject,eh)),this.brain&&this.target&&(this.brain.controlledTarget=this.target)}vec=new b;static forward=new b(0,0,1);currentTargetPoint=new b;update(){const e=this.target;if(e&&this.head){const t=this.eyes;if(t){const i=ee(e);this.currentTargetPoint.lerp(i,this.context.time.deltaTime/.1);const n=ee(this.head),s=this.vec.copy(this.currentTargetPoint).sub(n).normalize();if(s.length()<.1)return;const r=LS.forward;if(r.set(0,0,1),r.applyQuaternion(_e(this.head)),r.dot(s)>.45)for(let a=0;a<t.length;a++)t[a].lookAt(this.currentTargetPoint)}}}};$f([u(M)],Hu.prototype,"head"),$f([u(M)],Hu.prototype,"eyes"),$f([u(M)],Hu.prototype,"target");let Hf=Hu;var jR=Object.defineProperty,Gf=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&jR(e,t,n),n};class ul extends E{length=1;depthTest=!0;isGizmo=!1;_axes=null;onEnable(){if(this.isGizmo&&!Dc)return;this._axes||(this._axes=new Ci(this.length)),this._axes.layers.disableAll(),this._axes.layers.set(this.layer),this.gameObject.add(this._axes);const e=this._axes.material;e&&e.depthTest!==void 0&&(e.depthTest=this.depthTest)}onDisable(){this._axes&&this.gameObject.remove(this._axes)}}Gf([u()],ul.prototype,"length"),Gf([u()],ul.prototype,"depthTest"),Gf([u()],ul.prototype,"isGizmo");class qf extends E{from;to;hint;desiredDistance=1;onEnable(){}update(){if(!this.from||!this.to||!this.hint)return;const e=ee(this.to).clone(),t=ee(this.from).clone(),i=e.distanceTo(t),n=e.clone();n.sub(t);const s=t.clone();s.add(e),s.multiplyScalar(.5);const r=ee(this.hint).clone();r.sub(s);const a=new b;a.crossVectors(r,n),a.crossVectors(n,a),a.normalize();const l=i*.5,c=Math.max(this.desiredDistance,l),h=Math.sqrt(c*c-l*l),d=a.clone();d.multiplyScalar(h),d.add(s),yt(this.gameObject,d);const p=s.clone();p.sub(a),this.gameObject.lookAt(p)}}const BR=w("gizmos"),FR=w("debugboxhelper");class Pt extends E{box=null;static testBox=new Si;_lastMatrixUpdateFrame=-1;static _position=new b;static _size=new b(.01,.01,.01);static _emptyObjectSize=new b(.01,.01,.01);isInBox(e){if(!e)return;if(this.box||(this.box=new Si),Ri([e],void 0,void 0,Pt.testBox),Pt.testBox.isEmpty()){const i=ee(e,Pt._position);Pt.testBox.setFromCenterAndSize(i,Pt._emptyObjectSize)}this.updateBox();const t=this.box?.intersectsBox(Pt.testBox);return t&&FR&&B.DrawWireBox3(Pt.testBox,16711680,5),t}intersects(e){return e?this.updateBox(!1).intersectsBox(e):!1}updateBox(e=!1){if(this.box||(this.box=new Si),e||this.context.time.frameCount!=this._lastMatrixUpdateFrame){const t=this._lastMatrixUpdateFrame<0;this._lastMatrixUpdateFrame=this.context.time.frameCount;const i=t,n=ee(this.gameObject,Pt._position,i),s=$e(this.gameObject,Pt._size);this.box.setFromCenterAndSize(n,s)}return this.box}_helper=null;_color=null;awake(){this._helper=null,this._color=null,this.box=null}showHelper(e=null,t=!1){if(!(!BR&&!t)){if(this._helper){e&&this._color?.set(e),this.gameObject.add(this._helper);return}this._helper=Fg(e),this.gameObject.add(this._helper)}}}var UR=Object.defineProperty,fi=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&UR(e,t,n),n};class nn extends E{get isCollider(){return!0}attachedRigidbody=null;isTrigger=!1;sharedMaterial;membership=[0];filter;awake(){super.awake(),this.attachedRigidbody||(this.attachedRigidbody=this.gameObject.getComponentInParent(Ze))}start(){this.attachedRigidbody||(this.attachedRigidbody=this.gameObject.getComponentInParent(Ze))}onEnable(){this.attachedRigidbody||(this.attachedRigidbody=this.gameObject.getComponentInParent(Ze))}onDisable(){this.context.physics.engine?.removeBody(this)}get body(){return this.context.physics.engine?.getBody(this)}updateProperties=()=>{this.context.physics.engine?.updateProperties(this)};updatePhysicsMaterial(){this.context.physics.engine?.updatePhysicsMaterial(this)}}fi([u(Ze)],nn.prototype,"attachedRigidbody"),fi([u()],nn.prototype,"isTrigger"),fi([u()],nn.prototype,"sharedMaterial"),fi([u()],nn.prototype,"membership"),fi([u()],nn.prototype,"filter");class pl extends nn{radius=.5;center=new b(0,0,0);onEnable(){super.onEnable(),this.context.physics.engine?.addSphereCollider(this),Bd(this.gameObject.scale,this.updateProperties)}onDisable(){super.onDisable(),qm(this.gameObject.scale,this.updateProperties)}onValidate(){this.updateProperties()}}fi([Mt(),u()],pl.prototype,"radius"),fi([u(b)],pl.prototype,"center");const Xf=class DS extends nn{static add(e,t){const i=Mn(e,DS);return i.autoFit(),t?.rigidbody===!0&&Mn(e,Ze,{isKinematic:!1}),i}size=new b(1,1,1);center=new b(0,0,0);onEnable(){super.onEnable(),this.context.physics.engine?.addBoxCollider(this,this.size),Bd(this.gameObject.scale,this.updateProperties)}onDisable(){super.onDisable(),qm(this.gameObject.scale,this.updateProperties)}onValidate(){this.updateProperties()}autoFit(e){const t=this.gameObject,i=t.position.clone(),n=t.quaternion.clone(),s=t.scale.clone(),r=t.parent;t.position.set(0,0,0),t.quaternion.set(0,0,0,1),t.scale.set(1,1,1),t.parent=null,t.updateMatrix();const a=Ri([t]);t.position.copy(i),t.quaternion.copy(n),t.scale.copy(s),t.parent=r,e?.debug===!0&&B.DrawWireBox3(a,16768256,20),this.size=a.getSize(new b)||new b(1,1,1),this.center=a.getCenter(new b)||new b(0,0,0),this.size.length()<=0&&this.size.set(.01,.01,.01)}};fi([Mt(),u(b)],Xf.prototype,"size"),fi([u(b)],Xf.prototype,"center");let Gu=Xf;class js extends nn{sharedMesh;convex=!1;onEnable(){if(super.onEnable(),!this.context.physics.engine)return;this.sharedMesh?.isMesh||(this.gameObject instanceof H||this.gameObject instanceof Co)&&(this.sharedMesh=this.gameObject);const e=0;if(this.sharedMesh?.isMesh)this.context.physics.engine.addMeshCollider(this,this.sharedMesh,this.convex),Ve.assignMeshLOD(this.sharedMesh,e).then(t=>{t&&this.activeAndEnabled&&this.context.physics.engine&&this.sharedMesh&&(this.context.physics.engine.removeBody(this),this.sharedMesh.geometry=t,this.context.physics.engine.addMeshCollider(this,this.sharedMesh,this.convex))});else{const t=this.sharedMesh;if(t?.isGroup){console.warn(`MeshCollider mesh is a group "${this.sharedMesh?.name||this.gameObject.name}", adding all children as colliders. This is currently not fully supported (colliders can not be removed from world again)`,this);const i=new Array;for(const n in t.children){const s=t.children[n];s.isMesh&&(this.context.physics.engine.addMeshCollider(this,s,this.convex),i.push(Ve.assignMeshLOD(s,e)))}Promise.all(i).then(n=>{if(n.some(r=>r)==!1)return;this.context.physics.engine?.removeBody(this);const s=new H;for(const r of n)r&&this.activeAndEnabled&&(s.geometry=r,this.context.physics.engine?.addMeshCollider(this,s,this.convex))})}else(A()||w("showcolliders"))&&console.warn(`[MeshCollider] A MeshCollider mesh is assigned to an unknown object on "${this.gameObject.name}", but it's neither a Mesh nor a Group. Please double check that you attached the collider component to the right object and report a bug otherwise!`,this)}}}fi([u(H)],js.prototype,"sharedMesh"),fi([u()],js.prototype,"convex");class Wo extends nn{center=new b(0,0,0);radius=.5;height=2;onEnable(){super.onEnable(),this.context.physics.engine?.addCapsuleCollider(this,this.height,this.radius)}}fi([u(b)],Wo.prototype,"center"),fi([u()],Wo.prototype,"radius"),fi([u()],Wo.prototype,"height");var zR=Object.defineProperty,Vo=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&zR(e,t,n),n};const wx=w("debugcharactercontroller");class qr extends E{center=new b(0,0,0);radius=.5;height=2;_rigidbody=null;get rigidbody(){return this._rigidbody?this._rigidbody:(this._rigidbody=this.gameObject.getComponent(Ze),this._rigidbody||(this._rigidbody=this.gameObject.addComponent(Ze)),this.rigidbody)}_activeGroundCollisions;awake(){this._activeGroundCollisions=new Set}onEnable(){const e=this.rigidbody;let t=this.gameObject.getComponent(Wo);t||(t=this.gameObject.addComponent(Wo)),t.center.copy(this.center),t.radius=this.radius,t.height=this.height;const i=new b(0,0,1),n=new b(1,0,0),s=new b(0,1,0),r=this.gameObject.getWorldDirection(new b);r.y=0;const a=n.dot(r)<0?-1:1,l=i.angleTo(r)*a;this.gameObject.setRotationFromAxisAngle(s,l),e.lockRotationX=!0,e.lockRotationY=!0,e.lockRotationZ=!0}move(e){this.gameObject.position.add(e)}onCollisionEnter(e){(e.contacts.length==0||e.contacts.some(t=>t.normal.y>.2))&&(this._activeGroundCollisions.add(e),wx&&console.log(`Collision(${this._activeGroundCollisions.size}): ${e.contacts.map(t=>t.normal.y.toFixed(2)).join(", ")} - ${this.isGrounded}`))}onCollisionExit(e){this._activeGroundCollisions.delete(e),wx&&console.log(`Collision(${this._activeGroundCollisions.size}) - ${this.isGrounded}`)}get isGrounded(){return this._activeGroundCollisions.size>0}_contactVelocity=new b;get contactVelocity(){this._contactVelocity.set(0,0,0);for(const e of this._activeGroundCollisions){const t=this.context.physics.engine?.getLinearVelocity(e.collider);t&&(this._contactVelocity.x+=t.x,this._contactVelocity.y+=t.y,this._contactVelocity.z+=t.z)}return this._contactVelocity}}Vo([u(b)],qr.prototype,"center"),Vo([u()],qr.prototype,"radius"),Vo([u()],qr.prototype,"height");class $o extends E{controller;movementSpeed=2;rotationSpeed=2;jumpForce=1;doubleJumpForce=2;animator;lookForward=!0;awake(){this._currentRotation=new N}update(){const e=this.context.input;e.isKeyPressed("KeyW")?this.moveInput.y+=1:e.isKeyPressed("KeyS")&&(this.moveInput.y-=1),e.isKeyPressed("KeyD")?this.lookInput.x+=1:e.isKeyPressed("KeyA")&&(this.lookInput.x-=1),this.jumpInput||=e.isKeyDown("Space")}move(e){this.moveInput.add(e)}look(e){this.lookInput.add(e)}jump(){this.jumpInput=!0}lookInput=new K(0,0);moveInput=new K(0,0);jumpInput=!1;onBeforeRender(){this.handleInput(this.moveInput,this.lookInput,this.jumpInput),this.lookInput.set(0,0),this.moveInput.set(0,0),this.jumpInput=!1}_currentSpeed=new b(0,0,0);_currentAngularSpeed=new b(0,0,0);_temp=new b(0,0,0);_jumpCount=0;_currentRotation;handleInput(e,t,i){if(this.controller?.isGrounded&&(this._jumpCount=0,this.doubleJumpForce>0&&this.animator?.setBool("doubleJump",!1)),this._currentSpeed.z+=e.y*this.movementSpeed*this.context.time.deltaTime,this.animator?.setBool("running",e.length()>.01),this.animator?.setBool("jumping",this.controller?.isGrounded===!0&&i),this._temp.copy(this._currentSpeed),this._temp.applyQuaternion(this.gameObject.quaternion),this.controller?this.controller.move(this._temp):this.gameObject.position.add(this._temp),this._currentAngularSpeed.y+=j.toRadians(-t.x*this.rotationSpeed)*this.context.time.deltaTime,this.lookForward&&Math.abs(this._currentAngularSpeed.y)<.01){const n=this.context.mainCameraComponent.forward;n.y=0,n.normalize(),this._currentRotation.setFromUnitVectors(new b(0,0,1),n),this.gameObject.quaternion.slerp(this._currentRotation,this.context.time.deltaTime*10)}if(this.gameObject.rotateY(this._currentAngularSpeed.y),this._currentSpeed.multiplyScalar(1-this.context.time.deltaTime*10),this._currentAngularSpeed.y*=1-this.context.time.deltaTime*10,this.controller&&i&&this.jumpForce>0){let n=this.controller?.isGrounded;if(this.doubleJumpForce>0&&!this.controller?.isGrounded&&this._jumpCount===1&&(n=!0,this.animator?.setBool("doubleJump",!0)),n){this._jumpCount+=1;const s=this.controller.rigidbody,r=this._jumpCount===2?this.doubleJumpForce:this.jumpForce;s.applyImpulse(new b(0,1,0).multiplyScalar(r))}}if(this.controller){const n=this.controller?.rigidbody.getVelocity().y;if(n<-1){this._raycastOptions.ray||(this._raycastOptions.ray=new xo),this._raycastOptions.ray.origin.copy(ee(this.gameObject)),this._raycastOptions.ray.direction.set(0,-1,0);const s=this.layer;this.gameObject.layers.disableAll(),this.gameObject.layers.set(2);const r=this.context.physics.raycast(this._raycastOptions);this.gameObject.layers.set(s),(r.length&&r[0].distance>2||n<-10)&&this.animator?.setBool("falling",!0)}else this.animator?.setBool("falling",!1)}}_raycastOptions=new Os}Vo([u(qr)],$o.prototype,"controller"),Vo([u()],$o.prototype,"movementSpeed"),Vo([u()],$o.prototype,"rotationSpeed"),Vo([u()],$o.prototype,"jumpForce"),Vo([u()],$o.prototype,"doubleJumpForce"),Vo([u(_t)],$o.prototype,"animator");var NR=Object.defineProperty,ml=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&NR(e,t,n),n};const ih=w("debugcontactshadows");Eu(o=>{const e=o.domElement.getAttribute("contactshadows")||o.domElement.getAttribute("contact-shadows");if(e!=null&&e!="0"&&e!="false"){console.debug("Auto-creating ContactShadows because of `contactshadows` attribute");const t=nh.auto(o),i=parseFloat(e);isNaN(i)||(t.opacity=i,t.darkness=i)}});const Xr=class gd extends E{static _instances=new Map;static auto(e,t){if(e||(e=U.Current),!e)throw new Error("No context provided and no current context set.");let i=this._instances.get(e);if(!i||i.destroyed){const n=new M;n.name="ContactShadows",i=Mn(n,gd,{autoFit:!1,occludeBelowGround:!1}),this._instances.set(e,i)}return e.scene.add(i.gameObject),i.fitShadows(t),i}autoFit=!1;darkness=.5;opacity=.5;blur=4;occludeBelowGround=!1;backfaceShadows=!0;minSize;manualUpdate=!1;set needsUpdate(e){this._needsUpdate=e}get needsUpdate(){return this._needsUpdate}_needsUpdate=!1;shadowsRoot=new M;shadowCamera;shadowGroup=new Co;renderTarget;renderTargetBlur;plane;occluderMesh;blurPlane;planeMaterial;depthMaterial;horizontalBlurMaterial;verticalBlurMaterial;textureSize=512;fitShadows(e={}){ih&&console.warn("Fitting shadows to scene"),Nd(this.shadowsRoot,!1);const t=e.object||this.context.scene,i=Ri(t,[this.shadowsRoot]),n=Math.max(1,this.blur/32),s=i.max.x-i.min.x,r=i.max.z-i.min.z;i.expandByVector(new b(n*s,0,n*r)),ih&&B.DrawWireBox3(i,16776960,60),this.gameObject.parent&&i.applyMatrix4(this.gameObject.parent.matrixWorld.clone().invert());const a=i.min,l=Math.max(1e-5,(i.max.y-a.y)*.002);i.max.y+=l,this.shadowsRoot.position.set((a.x+i.max.x)/2,a.y-l,(a.z+i.max.z)/2),this.shadowsRoot.scale.set(i.max.x-a.x,i.max.y-a.y,i.max.z-a.z),e.positionOffset&&(e.positionOffset.x!==void 0&&(this.shadowsRoot.position.x+=e.positionOffset.x),e.positionOffset.y!==void 0&&(this.shadowsRoot.position.y+=e.positionOffset.y),e.positionOffset.z!==void 0&&(this.shadowsRoot.position.z+=e.positionOffset.z)),e.scaleFactor&&(e.scaleFactor.x!==void 0&&(this.shadowsRoot.scale.x*=e.scaleFactor.x),e.scaleFactor.y!==void 0&&(this.shadowsRoot.scale.y*=e.scaleFactor.y),e.scaleFactor.z!==void 0&&(this.shadowsRoot.scale.z*=e.scaleFactor.z)),this.applyMinSize(),this.shadowsRoot.matrixWorldNeedsUpdate=!0,ih&&console.log("Fitted shadows to scene",this.shadowsRoot.scale.clone())}awake(){gd._instances.set(this.context,this),this.shadowsRoot.hideFlags=Gd.DontExport,Nd(this.shadowsRoot,!1)}start(){ih&&console.log("Create ContactShadows on "+this.gameObject.name,this),this.gameObject.add(this.shadowsRoot),this.shadowsRoot.add(this.shadowGroup),this.renderTarget=new Vn(this.textureSize,this.textureSize),this.renderTarget.texture.generateMipmaps=!1,this.renderTargetBlur=new Vn(this.textureSize,this.textureSize),this.renderTargetBlur.texture.generateMipmaps=!1;const e=new vn(1,1).rotateX(Math.PI/2);this.gameObject instanceof H&&(console.warn("ContactShadows can not be added to a Mesh. Please add it to a Group or an empty Object"),Bo(this.gameObject,!1));const t=this.planeMaterial=new Ce({map:this.renderTarget.texture,opacity:this.opacity,color:0,transparent:!0,depthWrite:!1,side:vs});this.plane=new H(e,t),this.plane.scale.y=-1,this.plane.layers.set(2),this.shadowsRoot.add(this.plane),this.plane&&(this.plane.renderOrder=1),this.occluderMesh=new H(this.plane.geometry,new Ce({depthWrite:!0,stencilWrite:!0,colorWrite:!1,side:Id})).translateY(-1e-4),this.occluderMesh.renderOrder=-100,this.occluderMesh.layers.set(2),this.shadowsRoot.add(this.occluderMesh),this.blurPlane=new H(e),this.blurPlane.visible=!1,this.shadowGroup.add(this.blurPlane);const i=0,n=1;this.shadowCamera=new Cd(-1/2,1/2,1/2,-1/2,i,n),this.shadowCamera.layers.enableAll(),this.shadowCamera.rotation.x=Math.PI/2,this.shadowCamera.matrixWorldAutoUpdate=!1,this.shadowGroup.add(this.shadowCamera),this.shadowCamera.updateMatrix(),this.depthMaterial=new dC,this.depthMaterial.userData.darkness={value:this.darkness},this.depthMaterial.blending=uC,this.depthMaterial.blendEquation=pC,this.depthMaterial.onBeforeCompile=s=>{this.depthMaterial&&(s.uniforms.darkness=this.depthMaterial.userData.darkness,s.fragmentShader=`
979
+ Incoming:`,this._incomingCalls),s}else De&&console.error("Failed to make call",e,t,this._peer)}closeAll(){for(const e of this._incomingCalls)e.close();for(const e of this._outgoingCalls)e.close();this.updateCalls()}updateCalls=()=>{for(let e=this._incomingCalls.length-1;e>=0;e--){const t=this._incomingCalls[e];t.isClosed&&!t.isOpening&&this._incomingCalls.splice(e,1)}for(let e=this._outgoingCalls.length-1;e>=0;e--){const t=this._outgoingCalls[e];let i=!1;t.isClosed&&!t.isOpening&&(t.stream?.active?De&&console.warn("!!! Stream is still active, don't remove call",t.userId,"Your id: "+this.context.connection.connectionId):(De&&console.warn("!!! Remove closed call",t.userId),i=!0)),this.context.connection.userIsInRoom(t.userId)===!1&&(De&&console.warn("!!! User is not in room anymore, remove call",t.userId),i=!0),i&&(t.close(),this._outgoingCalls.splice(e,1))}};get peer(){return this._peer}get incomingCalls(){return this._incomingCalls}id;context;_incomingCalls=[];_outgoingCalls=[];_peer;constructor(e,t){super(),this.context=e,this.id=t,this.setupPeer();const i=Object.getOwnPropertyDescriptor(navigator,"getUserMedia")?.writable;try{i?navigator.getUserMedia=navigator.getUserMedia||navigator.webkitGetUserMedia||navigator.mozGetUserMedia||navigator.msGetUserMedia:De&&console.warn("[PeerJs] getUserMedia is not writable")}catch(n){De&&console.error("[PeerJs] Error setting getUserMedia",n)}}_enabled=!1;_enabledPeer=!1;onConnectRoomFn=this.onConnectRoom.bind(this);enable(){this._enabled||(this._enabled=!0,this.context.connection.beginListen(ie.JoinedRoom,this.onConnectRoomFn),this.subscribePeerEvents())}disable(){this._enabled&&(this._enabled=!1,this.context.connection.stopListen(ie.JoinedRoom,this.onConnectRoomFn),this.unsubscribePeerEvents())}onConnectRoom(){this.setupPeer()}setupPeer(){if(this.context.connection.connectionId&&!this._enabledPeer){if(this._enabledPeer=!0,!this._peer){const e=this.getMyPeerId();e?this._peer=av(e):console.error("Failed to setup peerjs because we dont have a connection id",this.context.connection.connectionId)}this._enabled&&this.subscribePeerEvents()}}subscribePeerEvents(){this._peer&&(this._peer.on("open",this.onPeerConnect),this._peer.on("close",this.onPeerClose),this._peer.on("call",this.onPeerReceivingCall),this._peer.on("disconnected",this.onPeerDisconnected),this._peer.on("error",this.onPeerError))}unsubscribePeerEvents(){this._peer&&(this._peer.off("open",this.onPeerConnect),this._peer.off("close",this.onPeerClose),this._peer.off("call",this.onPeerReceivingCall),this._peer.off("disconnected",this.onPeerDisconnected),this._peer.off("error",this.onPeerError))}onPeerConnect=e=>{if(De&&console.log("PEER opened as",e),e===null){console.error("Peer connection failed",e);return}this.context.connection.send("peer-user-connected",new PR(this,e))};onPeerClose=()=>{De&&console.log("PEER closed"),this.updateCalls()};onPeerDisconnected=()=>{De&&console.log("PEER disconnected"),this.updateCalls()};onPeerError=e=>{De&&console.error("PEER error",e)};onPeerReceivingCall=e=>{e.answer(void 0,{sdpTransform:t=>yx(t)}),this.registerCall(e,"incoming",null)};registerCall(e,t,i){const n=e.metadata;(!n||!n.userId)&&console.error("Missing call metadata",e);const s=n.userId;t==="incoming"&&De?console.warn("\u2190 Receive call from",e.metadata,e.connectionId):De&&console.warn("\u2192 Make call to",e.metadata);const r=t==="incoming"?this._incomingCalls:this._outgoingCalls,a=new OR(s,e,t,i);return r.push(a),e.on("error",l=>{console.error("Call error",l)}),e.on("close",()=>{De&&console.log("Call ended",e.metadata);const l=r.indexOf(a);l!==-1&&r.splice(l,1),a.close(),this.dispatchEvent(new Nf(s,t))}),a.addEventListener("call-ended",l=>{this.dispatchEvent(l)}),t==="incoming"&&(a.addEventListener("receive-stream",l=>{this.dispatchEvent(l)}),e.on("stream",()=>{De&&console.log("Received stream for call",e.metadata);let l=0;const c=setInterval(()=>{const h=l===0;!a.isOpen&&h&&(De&&console.warn("Close call because stream is not active",e.metadata),l+=1,clearInterval(c),a.close())},2e3)})),a}}class wd extends Im{static create(e,t){const i=gs.getOrCreate(e.context,t||e.context.connection.connectionId||e.guid);return new wd(e.context,i)}context;peer;_sendingStreams=new Map;debug=!1;constructor(e,t){if(super(),bg(e)){const i=e;e=i.context,t=gs.getOrCreate(i.context,i.guid)}else typeof t=="string"&&(t=gs.getOrCreate(e,t));if(e){if(!(e instanceof U))throw new Error("Failed to create NetworkedStreams because context is not an instance of Context")}else throw new Error("Failed to create NetworkedStreams because context is undefined");if(!t)throw new Error("Failed to create NetworkedStreams because peer is undefined");this.context=e,this.peer=t,De&&(this.debug=!0)}startSendingStream(e){this._sendingStreams.has(e)?console.warn("Received start sending stream with stream that is already being sent"):(this._sendingStreams.set(e,[]),this.updateSendingCalls())}stopSendingStream(e){if(e){const t=this._sendingStreams.get(e);if(t){for(const i of t)i.close();t.length=0}this._sendingStreams.delete(e),t&&this.debug&&this.debugLogCurrentState()}this.updateSendingCalls()}_enabled=!1;get enabled(){return this._enabled}enable(){this._enabled||(this._enabled=!0,this.peer.enable(),this.peer.addEventListener("receive-stream",this.onCallStreamReceived),this.peer.addEventListener("call-ended",this.onCallEnded),this.context.connection.beginListen("peer-user-connected",this.onUserConnected),this.context.connection.beginListen(ie.JoinedRoom,this.onJoinedRoom),this.context.connection.beginListen(ie.UserJoinedRoom,this.onJoinedRoom),this.context.connection.beginListen(ie.UserLeftRoom,this.onUserLeft),this.context.connection.beginListen(ie.LeftRoom,this.onLeftRoom),this._tickIntervalId=setInterval(this.tick,5e3))}disable(){this._enabled&&(this._enabled=!1,this.peer.disable(),this.peer.removeEventListener("receive-stream",this.onCallStreamReceived),this.peer.removeEventListener("call-ended",this.onCallEnded),this.context.connection.stopListen("peer-user-connected",this.onUserConnected),this.context.connection.stopListen(ie.JoinedRoom,this.onJoinedRoom),this.context.connection.stopListen(ie.UserJoinedRoom,this.onJoinedRoom),this.context.connection.stopListen(ie.UserLeftRoom,this.onUserLeft),this.context.connection.stopListen(ie.LeftRoom,this.onLeftRoom),this._tickIntervalId!=null&&(clearInterval(this._tickIntervalId),this._tickIntervalId=void 0))}_tickIntervalId;tick=()=>{this.updateSendingCalls()};onJoinedRoom=e=>{this._sendingStreams.size>0&&(this.debug&&console.warn(`${e?.userId?`User ${e.userId}`:"You"} joined room`,e,this._sendingStreams.size),this.updateSendingCalls())};onLeftRoom=e=>{this.debug&&console.warn(`${e?.userId||"You"} left room`,e),this.stopCallsToUsersThatAreNotInTheRoomAnymore(),this.peer.closeAll()};onCallStreamReceived=e=>{this.debug&&console.log("Call with "+e.userId+" started"),this.dispatchEvent({type:"receive-stream",target:this,stream:e.stream,userId:e.userId}),this.debug&&this.debugLogCurrentState()};onCallEnded=e=>{this.debug&&console.log("Call with "+e.userId+" ended"),this.dispatchEvent(e),this.debug&&this.debugLogCurrentState()};onUserConnected=e=>{if(this.peer.id===e.guid){this.debug&&console.log("PEER USER CONNECTED",e.guid,e,this._sendingStreams.size);const t=this._sendingStreams.keys().next().value;if(!t)return;this.peer.makeCall(e.peerId,t)}else De&&console.log("Unknown user connected",e.guid,e.peerId)};onUserLeft=e=>{this.debug&&console.log("User left room: "+e.userId),this.stopCallsToUsersThatAreNotInTheRoomAnymore()};updateSendingCalls(){const e=this.context.connection.connectionId;for(const t of this._sendingStreams.keys()){const i=this._sendingStreams.get(t)||[];for(const n of this.context.connection.usersInRoom()){if(n===e)continue;const s=this.peer.getPeerIdFromUserId(n);if(i.find(r=>r.peerId===s&&r.direction==="outgoing"&&!r.isClosed&&r.stream?.active))De&&console.debug("Already have a call with user "+n+" / peer "+s);else{const r=this.peer.makeCall(s,t);r&&i.push(r)}}this._sendingStreams.set(t,i)}this.stopCallsToUsersThatAreNotInTheRoomAnymore()}stopCallsToUsersThatAreNotInTheRoomAnymore(){for(const e of this._sendingStreams.keys()){const t=this._sendingStreams.get(e);if(t)for(let i=t.length-1;i>=0;i--){const n=t[i];this.context.connection.userIsInRoom(n.userId)?De&&(this.context.connection.connectionId===n.userId?console.warn(`You are still in the room [${i}] ${n.userId}`):console.log(`User is still in room [${i}] ${n.userId}`)):(De&&console.log(`Remove call ${[i]} to user that is not in room anymore ${n.userId}`),n.close(),t.splice(i,1))}}this.peer.updateCalls(),this.debug&&this.debugLogCurrentState()}debugLogCurrentState(){console.warn(`You (${this.context.connection.connectionId}) are currently sending ${this._sendingStreams.size} and receiving ${this.peer.incomingCalls.length} calls (${this.peer.incomingCalls.map(e=>e.userId).join(", ")})`,this.peer.incomingCalls)}}function to(o){if(o&&o instanceof MediaStream)for(const e of o.getTracks())e.stop()}var kR=Object.defineProperty,Wf=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&kR(e,t,n),n};const MR="noVoip",ER=w("debugvoip");class Ds extends E{autoConnect=!0;runInBackground=!0;createMenuButton=!0;debug=!1;_net;_menubutton;awake(){ER&&(this.debug=!0),this.debug&&(console.log("VOIP debugging: press 'v' to toggle mute or 'c' to toggle connect/disconnect"),window.addEventListener("keydown",async e=>{switch(e.key.toLowerCase()){case"v":console.log("MUTE?",!this.isMuted),this.setMuted(!this.isMuted);break;case"c":this.isSending?this.disconnect():this.connect();break}}),window.addEventListener("blur",()=>{console.log("VOIP: MUTE ON BLUR"),this.setMuted(!0)}),window.addEventListener("focus",()=>{console.log("VOIP: UNMUTE ON FOCUS"),this.setMuted(!1)}))}onEnable(){this._net||(this._net=wd.create(this)),this.debug&&(this._net.debug=!0),this._net.addEventListener(eo.StreamReceived,this.onReceiveStream),this._net.addEventListener(eo.StreamEnded,this.onStreamEnded),this._net.enable(),this.autoConnect&&this.context.connection.isConnected&&this.connect(),this.context.connection.beginListen(ie.JoinedRoom,this.onJoinedRoom),this.context.connection.beginListen(ie.LeftRoom,this.onLeftRoom),this.onEnabledChanged(),this.updateButton(),window.addEventListener("visibilitychange",this.onVisibilityChanged)}onDisable(){this._net&&(this._net.stopSendingStream(this._outputStream),this._net.removeEventListener(eo.StreamReceived,this.onReceiveStream),this._net.removeEventListener(eo.StreamEnded,this.onStreamEnded),this._net?.disable()),this.context.connection.stopListen(ie.JoinedRoom,this.onJoinedRoom),this.context.connection.stopListen(ie.LeftRoom,this.onLeftRoom),this.onEnabledChanged(),this.updateButton(),window.removeEventListener("visibilitychange",this.onVisibilityChanged)}onDestroy(){this._menubutton?.remove(),this._menubutton=void 0}_allowSending=!0;_outputStream=null;get isSending(){return this._outputStream!=null&&this._outputStream.active}async connect(e){if(!this._net)return console.error("Cannot connect to voice chat - NetworkedStreams not initialized. Make sure the component is enabled before calling this method."),!1;if(this.context.connection.isConnected){if(!await I.microphonePermissionsGranted())return console.error("Cannot connect to voice chat - microphone permissions not granted"),this.updateButton(),!1}else return console.error("Cannot connect to voice chat - not connected to server"),this.updateButton(),!1;return this._allowSending=!0,this._net?.stopSendingStream(this._outputStream),to(this._outputStream),this._outputStream=await this.getAudioStream(e),this._outputStream?(this.debug&&console.log("VOIP: Got audio stream"),this._net?.startSendingStream(this._outputStream),this.updateButton(),!0):(this.updateButton(),await I.microphonePermissionsGranted()?console.error("VOIP: Could not get audio stream - please make sure to connect an audio device and grant microphone permissions"):_c("Microphone permissions not granted: Please grant microphone permissions to use voice chat"),(this.debug||A())&&console.log("VOIP: Failed to get audio stream"),!1)}disconnect(e){e?.remember&&(this._allowSending=!1),this._net?.stopSendingStream(this._outputStream),to(this._outputStream),this._outputStream=null,this.updateButton()}setMuted(e){const t=this._outputStream?.getAudioTracks();if(t)for(const i of t)i.enabled=!e}get isMuted(){if(this._outputStream===null)return!1;const e=this._outputStream?.getAudioTracks();if(e){for(const t of e)if(!t.enabled)return!0}return!1}async updateButton(){if(this.createMenuButton){if(this._menubutton||(this._menubutton=document.createElement("button"),this._menubutton.addEventListener("click",()=>{this.isSending?this.disconnect({remember:!0}):this.connect(),I.microphonePermissionsGranted().then(e=>{e||be("<strong>Microphone permissions not granted</strong>. Please allow your browser to use the microphone to be able to talk. Click on the button on the left side of your browser's address bar to allow microphone permissions.")})})),this._menubutton){this.context.menu.appendChild(this._menubutton),this.activeAndEnabled?this._menubutton.style.display="":this._menubutton.style.display="none",this._menubutton.title=this.isSending?"Click to disable your microphone":"Click to enable your microphone";let e=(this.isSending,""),t=this.isSending?"mic":"mic_off";await I.microphonePermissionsGranted()||(e="No Permission",t="mic_off",this._menubutton.title="Microphone permissions not granted. Please allow your browser to use the microphone to be able to talk. This can usually be done in the addressbar of the webpage."),this._menubutton.innerText=e,this._menubutton.prepend(Ot(t)),this.context.connection.isConnected==!1?this._menubutton.setAttribute("disabled",""):this._menubutton.removeAttribute("disabled")}}else this.activeAndEnabled||this._menubutton?.remove()}getFrequency(e){return this.unsupported_getfrequency||(this.unsupported_getfrequency=!0,A()&&be("VOIP: getFrequency is currently not supported"),console.warn("VOIP: getFrequency is currently not supported")),null}async getAudioStream(e){if(!navigator.mediaDevices.getUserMedia)return console.error("No getDisplayMedia support"),null;const t=async n=>await navigator.mediaDevices.getUserMedia({audio:n??!0,video:!1}).catch(s=>(console.warn("VOIP failed getting audio stream",s),null)),i=await t(e);if(!i)return null;if(I.isiOS()&&e?.deviceId===void 0){const n=(await navigator.mediaDevices.enumerateDevices()).find(s=>(s.kind==="audioinput"||s.kind==="audiooutput")&&!s.label.includes("iPhone"));if(n){const s=Object.assign({},e);return s.deviceId=n.deviceId,await t(s)}}return i}onJoinedRoom=async()=>{this.debug&&console.log("VOIP: Joined room"),await Ro(300),this.autoConnect&&!this.isSending&&this._allowSending&&this.connect()};onLeftRoom=()=>{this.debug&&console.log("VOIP: Left room"),this.disconnect();for(const e of this._incomingStreams.values())to(e.srcObject);this._incomingStreams.clear()};_incomingStreams=new Map;onReceiveStream=e=>{const t=e.target.userId,i=e.stream;let n=this._incomingStreams.get(t);n||(n=new Audio,this._incomingStreams.set(t,n)),n.srcObject=i,n.setAttribute("autoplay","true"),zn.registerWaitForInteraction(()=>{n?.play().catch(s=>{console.error("VOIP: Failed to play audio",s)})})};onStreamEnded=e=>{const t=this._incomingStreams.get(e.userId);to(t?.srcObject),this._incomingStreams.delete(e.userId)};onEnabledChanged=()=>{for(const e of this._incomingStreams){const t=e[1];t.muted=!this.enabled}};onVisibilityChanged=()=>{if(this.runInBackground)return;const e=document.visibilityState!=="visible";this.setMuted(e);for(const t of this._incomingStreams){const i=t[1];i.muted=e}}}Wf([u()],Ds.prototype,"autoConnect"),Wf([u()],Ds.prototype,"runInBackground"),Wf([u()],Ds.prototype,"createMenuButton");var RR=Object.defineProperty,bx=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&RR(e,t,n),n};const TR=w("debugmouth");class th extends E{idle=[];talking=[];marker=null;voip=null;lastMouthChangeTime=0;mouthChangeLength=0;awake(){setTimeout(()=>{this.voip=S.findObjectOfType(Ds,this.context),this.marker||(this.marker=S.getComponentInParent(this.gameObject,Le))},3e3)}update(){if(!this.voip||this.context.time.frameCount%10!==0)return;let e=this.marker?.connectionId??null;if(!e){TR&&(e=null);return}const t=this.voip.getFrequency(e)??0;this.updateLips(t)}updateLips(e){if(this.context.time.time-this.lastMouthChangeTime>this.mouthChangeLength){if(this.mouthChangeLength=.05+Math.random()*.1,this.talking&&this.talking.length>0&&e>30){this.lastMouthChangeTime=this.context.time.time;const t=Math.floor(Math.random()*this.talking.length);this.setMouthShapeActive(this.talking,t)}else if(this.idle.length>0&&this.context.time.time-this.lastMouthChangeTime>.5){this.lastMouthChangeTime=this.context.time.time;const t=Math.floor(Math.random()*this.idle.length);this.setMouthShapeActive(this.idle,t)}}}setMouthShapeActive(e,t){if(e){e!=this.idle?this.idle.map(i=>i.visible=!1):this.talking.map(i=>i.visible=!1);for(let i=0;i<e.length;i++){const n=e[i];n&&(n.visible=i===t)}}}}bx([u(M)],th.prototype,"idle"),bx([u(M)],th.prototype,"talking");class Vf extends E{voip=null;marker=null;_startPosition=null;awake(){this.voip=S.findObjectOfType(Ds,this.context),this.marker=S.getComponentInParent(this.gameObject,Le)}update(){if(!this.voip||!this.marker||this.context.time.frameCount%10!==0)return;const e=this.marker.connectionId,t=this.voip.getFrequency(e);if(t==null)return;this._startPosition||(this._startPosition=this.gameObject.position.clone());const i=t/100;this.gameObject.position.y=this._startPosition.y+i*.07}}var AR=Object.defineProperty,IR=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&AR(e,t,n),n};const dl=w("debugxrflags"),_x=w("disablexrflags");_x&&console.warn("XRFlags are disabled");var io=(o=>(o[o.Never=0]="Never",o[o.Browser=1]="Browser",o[o.AR=2]="AR",o[o.VR=4]="VR",o[o.FirstPerson=8]="FirstPerson",o[o.ThirdPerson=16]="ThirdPerson",o[o.All=4294967295]="All",o))(io||{});class ri{static Global=new ri;Mask=17;Has(e){return(this.Mask&e)!==0}Set(e){dl&&console.warn("Set XR flag state to",e),this.Mask=e,tn.Apply()}Enable(e){this.Mask|=e,tn.Apply()}Disable(e){this.Mask&=~e,tn.Apply()}Toggle(e){this.Mask^=e,tn.Apply()}EnableAll(){this.Mask=-1,tn.Apply()}DisableAll(){this.Mask=0,tn.Apply()}}const vx=class hs extends E{static registry=[];static Apply(){for(const e of this.registry)e.UpdateVisible(ri.Global)}static firstApply;static buffer=new ri;visibleIn;awake(){hs.registry.push(this)}onEnable(){hs.firstApply?this.UpdateVisible(ri.Global):(hs.firstApply=!0,hs.Apply())}onDestroy(){const e=hs.registry.indexOf(this);e>=0&&hs.registry.splice(e,1)}get isOn(){return this.gameObject.visible}UpdateVisible(e=null){if(_x)return;let t;const i=e;if(i&&typeof i=="number"&&(console.assert(typeof i=="number","XRFlag.UpdateVisible: state must be a number",i),dl&&console.log(i),hs.buffer.Mask=i,e=hs.buffer),e instanceof ri?(dl&&console.warn(this.name,"use passed in mask",e.Mask,this.visibleIn),t=e.Has(this.visibleIn)):(dl&&console.log(this.name,"use global mask"),ri.Global.Has(this.visibleIn)),t!==void 0)if(t)dl&&console.log(this.name,"is visible",this.gameObject.uuid),S.setActive(this.gameObject,!0);else{if(dl&&console.log(this.name,"is not visible",this.gameObject.uuid),!this.gameObject.visible)return;this.gameObject.visible=!1}}};IR([u()],vx.prototype,"visibleIn");let tn=vx;var LR=Object.defineProperty,$u=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&LR(e,t,n),n};class Gr extends E{eyes=[];lastBlinkTime=0;blinkLength=0;eyesOpen=!0;state=null;awake(){this.state=S.getComponentInParent(this.gameObject,tn)}update(){if(!(!this.gameObject||!this.gameObject.visible||!this.eyes||!Array.isArray(this.eyes)||this.eyes.length===0)&&this.context.time.time-this.lastBlinkTime>this.blinkLength){if(this.lastBlinkTime=this.context.time.time,this.state&&!this.state.isOn||!this.activeAndEnabled)return;if(this.eyesOpen=!this.eyesOpen,this.blinkLength=Math.random(),this.eyesOpen?(this.blinkLength*=3,this.blinkLength+=.5,Math.random()<.1&&(this.blinkLength=.1+Math.random()*.2)):(this.blinkLength*=Math.random()*.2,this.blinkLength+=.1),Math.random()<.1&&(this.blinkLength*=3),this.blinkLength=Math.max(.2,this.blinkLength),this.blinkLength=Math.min(3,this.blinkLength),this.eyes)for(const e of this.eyes)e&&(e.visible=this.eyesOpen)}}}$u([u(M)],Gr.prototype,"eyes"),$u([u()],Gr.prototype,"lastBlinkTime"),$u([u()],Gr.prototype,"blinkLength"),$u([u()],Gr.prototype,"eyesOpen");var DR=Object.defineProperty,$f=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&DR(e,t,n),n};const Hu=class LS extends E{head=null;eyes=null;target=null;brain=null;awake(){this.brain||(this.brain=S.getComponentInParent(this.gameObject,eh)),this.brain||(this.brain=S.addComponent(this.gameObject,eh)),this.brain&&this.target&&(this.brain.controlledTarget=this.target)}vec=new b;static forward=new b(0,0,1);currentTargetPoint=new b;update(){const e=this.target;if(e&&this.head){const t=this.eyes;if(t){const i=ee(e);this.currentTargetPoint.lerp(i,this.context.time.deltaTime/.1);const n=ee(this.head),s=this.vec.copy(this.currentTargetPoint).sub(n).normalize();if(s.length()<.1)return;const r=LS.forward;if(r.set(0,0,1),r.applyQuaternion(_e(this.head)),r.dot(s)>.45)for(let a=0;a<t.length;a++)t[a].lookAt(this.currentTargetPoint)}}}};$f([u(M)],Hu.prototype,"head"),$f([u(M)],Hu.prototype,"eyes"),$f([u(M)],Hu.prototype,"target");let Hf=Hu;var jR=Object.defineProperty,Gf=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&jR(e,t,n),n};class ul extends E{length=1;depthTest=!0;isGizmo=!1;_axes=null;onEnable(){if(this.isGizmo&&!Dc)return;this._axes||(this._axes=new Ci(this.length)),this._axes.layers.disableAll(),this._axes.layers.set(this.layer),this.gameObject.add(this._axes);const e=this._axes.material;e&&e.depthTest!==void 0&&(e.depthTest=this.depthTest)}onDisable(){this._axes&&this.gameObject.remove(this._axes)}}Gf([u()],ul.prototype,"length"),Gf([u()],ul.prototype,"depthTest"),Gf([u()],ul.prototype,"isGizmo");class qf extends E{from;to;hint;desiredDistance=1;onEnable(){}update(){if(!this.from||!this.to||!this.hint)return;const e=ee(this.to).clone(),t=ee(this.from).clone(),i=e.distanceTo(t),n=e.clone();n.sub(t);const s=t.clone();s.add(e),s.multiplyScalar(.5);const r=ee(this.hint).clone();r.sub(s);const a=new b;a.crossVectors(r,n),a.crossVectors(n,a),a.normalize();const l=i*.5,c=Math.max(this.desiredDistance,l),h=Math.sqrt(c*c-l*l),d=a.clone();d.multiplyScalar(h),d.add(s),yt(this.gameObject,d);const p=s.clone();p.sub(a),this.gameObject.lookAt(p)}}const BR=w("gizmos"),FR=w("debugboxhelper");class Pt extends E{box=null;static testBox=new Si;_lastMatrixUpdateFrame=-1;static _position=new b;static _size=new b(.01,.01,.01);static _emptyObjectSize=new b(.01,.01,.01);isInBox(e){if(!e)return;if(this.box||(this.box=new Si),Ri([e],void 0,void 0,Pt.testBox),Pt.testBox.isEmpty()){const i=ee(e,Pt._position);Pt.testBox.setFromCenterAndSize(i,Pt._emptyObjectSize)}this.updateBox();const t=this.box?.intersectsBox(Pt.testBox);return t&&FR&&B.DrawWireBox3(Pt.testBox,16711680,5),t}intersects(e){return e?this.updateBox(!1).intersectsBox(e):!1}updateBox(e=!1){if(this.box||(this.box=new Si),e||this.context.time.frameCount!=this._lastMatrixUpdateFrame){const t=this._lastMatrixUpdateFrame<0;this._lastMatrixUpdateFrame=this.context.time.frameCount;const i=t,n=ee(this.gameObject,Pt._position,i),s=$e(this.gameObject,Pt._size);this.box.setFromCenterAndSize(n,s)}return this.box}_helper=null;_color=null;awake(){this._helper=null,this._color=null,this.box=null}showHelper(e=null,t=!1){if(!(!BR&&!t)){if(this._helper){e&&this._color?.set(e),this.gameObject.add(this._helper);return}this._helper=Fg(e),this.gameObject.add(this._helper)}}}var UR=Object.defineProperty,fi=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&UR(e,t,n),n};class nn extends E{get isCollider(){return!0}attachedRigidbody=null;isTrigger=!1;sharedMaterial;membership=[0];filter;awake(){super.awake(),this.attachedRigidbody||(this.attachedRigidbody=this.gameObject.getComponentInParent(Ke))}start(){this.attachedRigidbody||(this.attachedRigidbody=this.gameObject.getComponentInParent(Ke))}onEnable(){this.attachedRigidbody||(this.attachedRigidbody=this.gameObject.getComponentInParent(Ke))}onDisable(){this.context.physics.engine?.removeBody(this)}get body(){return this.context.physics.engine?.getBody(this)}updateProperties=()=>{this.context.physics.engine?.updateProperties(this)};updatePhysicsMaterial(){this.context.physics.engine?.updatePhysicsMaterial(this)}}fi([u(Ke)],nn.prototype,"attachedRigidbody"),fi([u()],nn.prototype,"isTrigger"),fi([u()],nn.prototype,"sharedMaterial"),fi([u()],nn.prototype,"membership"),fi([u()],nn.prototype,"filter");class pl extends nn{radius=.5;center=new b(0,0,0);onEnable(){super.onEnable(),this.context.physics.engine?.addSphereCollider(this),Bd(this.gameObject.scale,this.updateProperties)}onDisable(){super.onDisable(),qm(this.gameObject.scale,this.updateProperties)}onValidate(){this.updateProperties()}}fi([Mt(),u()],pl.prototype,"radius"),fi([u(b)],pl.prototype,"center");const Xf=class DS extends nn{static add(e,t){const i=Mn(e,DS);return i.autoFit(),t?.rigidbody===!0&&Mn(e,Ke,{isKinematic:!1}),i}size=new b(1,1,1);center=new b(0,0,0);onEnable(){super.onEnable(),this.context.physics.engine?.addBoxCollider(this,this.size),Bd(this.gameObject.scale,this.updateProperties)}onDisable(){super.onDisable(),qm(this.gameObject.scale,this.updateProperties)}onValidate(){this.updateProperties()}autoFit(e){const t=this.gameObject,i=t.position.clone(),n=t.quaternion.clone(),s=t.scale.clone(),r=t.parent;t.position.set(0,0,0),t.quaternion.set(0,0,0,1),t.scale.set(1,1,1),t.parent=null,t.updateMatrix();const a=Ri([t]);t.position.copy(i),t.quaternion.copy(n),t.scale.copy(s),t.parent=r,e?.debug===!0&&B.DrawWireBox3(a,16768256,20),this.size=a.getSize(new b)||new b(1,1,1),this.center=a.getCenter(new b)||new b(0,0,0),this.size.length()<=0&&this.size.set(.01,.01,.01)}};fi([Mt(),u(b)],Xf.prototype,"size"),fi([u(b)],Xf.prototype,"center");let Gu=Xf;class js extends nn{sharedMesh;convex=!1;onEnable(){if(super.onEnable(),!this.context.physics.engine)return;this.sharedMesh?.isMesh||(this.gameObject instanceof H||this.gameObject instanceof Co)&&(this.sharedMesh=this.gameObject);const e=0;if(this.sharedMesh?.isMesh)this.context.physics.engine.addMeshCollider(this,this.sharedMesh,this.convex),Ve.assignMeshLOD(this.sharedMesh,e).then(t=>{t&&this.activeAndEnabled&&this.context.physics.engine&&this.sharedMesh&&(this.context.physics.engine.removeBody(this),this.sharedMesh.geometry=t,this.context.physics.engine.addMeshCollider(this,this.sharedMesh,this.convex))});else{const t=this.sharedMesh;if(t?.isGroup){console.warn(`MeshCollider mesh is a group "${this.sharedMesh?.name||this.gameObject.name}", adding all children as colliders. This is currently not fully supported (colliders can not be removed from world again)`,this);const i=new Array;for(const n in t.children){const s=t.children[n];s.isMesh&&(this.context.physics.engine.addMeshCollider(this,s,this.convex),i.push(Ve.assignMeshLOD(s,e)))}Promise.all(i).then(n=>{if(n.some(r=>r)==!1)return;this.context.physics.engine?.removeBody(this);const s=new H;for(const r of n)r&&this.activeAndEnabled&&(s.geometry=r,this.context.physics.engine?.addMeshCollider(this,s,this.convex))})}else(A()||w("showcolliders"))&&console.warn(`[MeshCollider] A MeshCollider mesh is assigned to an unknown object on "${this.gameObject.name}", but it's neither a Mesh nor a Group. Please double check that you attached the collider component to the right object and report a bug otherwise!`,this)}}}fi([u(H)],js.prototype,"sharedMesh"),fi([u()],js.prototype,"convex");class Wo extends nn{center=new b(0,0,0);radius=.5;height=2;onEnable(){super.onEnable(),this.context.physics.engine?.addCapsuleCollider(this,this.height,this.radius)}}fi([u(b)],Wo.prototype,"center"),fi([u()],Wo.prototype,"radius"),fi([u()],Wo.prototype,"height");var zR=Object.defineProperty,Vo=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&zR(e,t,n),n};const wx=w("debugcharactercontroller");class qr extends E{center=new b(0,0,0);radius=.5;height=2;_rigidbody=null;get rigidbody(){return this._rigidbody?this._rigidbody:(this._rigidbody=this.gameObject.getComponent(Ke),this._rigidbody||(this._rigidbody=this.gameObject.addComponent(Ke)),this.rigidbody)}_activeGroundCollisions;awake(){this._activeGroundCollisions=new Set}onEnable(){const e=this.rigidbody;let t=this.gameObject.getComponent(Wo);t||(t=this.gameObject.addComponent(Wo)),t.center.copy(this.center),t.radius=this.radius,t.height=this.height;const i=new b(0,0,1),n=new b(1,0,0),s=new b(0,1,0),r=this.gameObject.getWorldDirection(new b);r.y=0;const a=n.dot(r)<0?-1:1,l=i.angleTo(r)*a;this.gameObject.setRotationFromAxisAngle(s,l),e.lockRotationX=!0,e.lockRotationY=!0,e.lockRotationZ=!0}move(e){this.gameObject.position.add(e)}onCollisionEnter(e){(e.contacts.length==0||e.contacts.some(t=>t.normal.y>.2))&&(this._activeGroundCollisions.add(e),wx&&console.log(`Collision(${this._activeGroundCollisions.size}): ${e.contacts.map(t=>t.normal.y.toFixed(2)).join(", ")} - ${this.isGrounded}`))}onCollisionExit(e){this._activeGroundCollisions.delete(e),wx&&console.log(`Collision(${this._activeGroundCollisions.size}) - ${this.isGrounded}`)}get isGrounded(){return this._activeGroundCollisions.size>0}_contactVelocity=new b;get contactVelocity(){this._contactVelocity.set(0,0,0);for(const e of this._activeGroundCollisions){const t=this.context.physics.engine?.getLinearVelocity(e.collider);t&&(this._contactVelocity.x+=t.x,this._contactVelocity.y+=t.y,this._contactVelocity.z+=t.z)}return this._contactVelocity}}Vo([u(b)],qr.prototype,"center"),Vo([u()],qr.prototype,"radius"),Vo([u()],qr.prototype,"height");class $o extends E{controller;movementSpeed=2;rotationSpeed=2;jumpForce=1;doubleJumpForce=2;animator;lookForward=!0;awake(){this._currentRotation=new N}update(){const e=this.context.input;e.isKeyPressed("KeyW")?this.moveInput.y+=1:e.isKeyPressed("KeyS")&&(this.moveInput.y-=1),e.isKeyPressed("KeyD")?this.lookInput.x+=1:e.isKeyPressed("KeyA")&&(this.lookInput.x-=1),this.jumpInput||=e.isKeyDown("Space")}move(e){this.moveInput.add(e)}look(e){this.lookInput.add(e)}jump(){this.jumpInput=!0}lookInput=new K(0,0);moveInput=new K(0,0);jumpInput=!1;onBeforeRender(){this.handleInput(this.moveInput,this.lookInput,this.jumpInput),this.lookInput.set(0,0),this.moveInput.set(0,0),this.jumpInput=!1}_currentSpeed=new b(0,0,0);_currentAngularSpeed=new b(0,0,0);_temp=new b(0,0,0);_jumpCount=0;_currentRotation;handleInput(e,t,i){if(this.controller?.isGrounded&&(this._jumpCount=0,this.doubleJumpForce>0&&this.animator?.setBool("doubleJump",!1)),this._currentSpeed.z+=e.y*this.movementSpeed*this.context.time.deltaTime,this.animator?.setBool("running",e.length()>.01),this.animator?.setBool("jumping",this.controller?.isGrounded===!0&&i),this._temp.copy(this._currentSpeed),this._temp.applyQuaternion(this.gameObject.quaternion),this.controller?this.controller.move(this._temp):this.gameObject.position.add(this._temp),this._currentAngularSpeed.y+=j.toRadians(-t.x*this.rotationSpeed)*this.context.time.deltaTime,this.lookForward&&Math.abs(this._currentAngularSpeed.y)<.01){const n=this.context.mainCameraComponent.forward;n.y=0,n.normalize(),this._currentRotation.setFromUnitVectors(new b(0,0,1),n),this.gameObject.quaternion.slerp(this._currentRotation,this.context.time.deltaTime*10)}if(this.gameObject.rotateY(this._currentAngularSpeed.y),this._currentSpeed.multiplyScalar(1-this.context.time.deltaTime*10),this._currentAngularSpeed.y*=1-this.context.time.deltaTime*10,this.controller&&i&&this.jumpForce>0){let n=this.controller?.isGrounded;if(this.doubleJumpForce>0&&!this.controller?.isGrounded&&this._jumpCount===1&&(n=!0,this.animator?.setBool("doubleJump",!0)),n){this._jumpCount+=1;const s=this.controller.rigidbody,r=this._jumpCount===2?this.doubleJumpForce:this.jumpForce;s.applyImpulse(new b(0,1,0).multiplyScalar(r))}}if(this.controller){const n=this.controller?.rigidbody.getVelocity().y;if(n<-1){this._raycastOptions.ray||(this._raycastOptions.ray=new xo),this._raycastOptions.ray.origin.copy(ee(this.gameObject)),this._raycastOptions.ray.direction.set(0,-1,0);const s=this.layer;this.gameObject.layers.disableAll(),this.gameObject.layers.set(2);const r=this.context.physics.raycast(this._raycastOptions);this.gameObject.layers.set(s),(r.length&&r[0].distance>2||n<-10)&&this.animator?.setBool("falling",!0)}else this.animator?.setBool("falling",!1)}}_raycastOptions=new Os}Vo([u(qr)],$o.prototype,"controller"),Vo([u()],$o.prototype,"movementSpeed"),Vo([u()],$o.prototype,"rotationSpeed"),Vo([u()],$o.prototype,"jumpForce"),Vo([u()],$o.prototype,"doubleJumpForce"),Vo([u(_t)],$o.prototype,"animator");var NR=Object.defineProperty,ml=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&NR(e,t,n),n};const ih=w("debugcontactshadows");Eu(o=>{const e=o.domElement.getAttribute("contactshadows")||o.domElement.getAttribute("contact-shadows");if(e!=null&&e!="0"&&e!="false"){console.debug("Auto-creating ContactShadows because of `contactshadows` attribute");const t=nh.auto(o),i=parseFloat(e);isNaN(i)||(t.opacity=i,t.darkness=i)}});const Xr=class gd extends E{static _instances=new Map;static auto(e,t){if(e||(e=U.Current),!e)throw new Error("No context provided and no current context set.");let i=this._instances.get(e);if(!i||i.destroyed){const n=new M;n.name="ContactShadows",i=Mn(n,gd,{autoFit:!1,occludeBelowGround:!1}),this._instances.set(e,i)}return e.scene.add(i.gameObject),i.fitShadows(t),i}autoFit=!1;darkness=.5;opacity=.5;blur=4;occludeBelowGround=!1;backfaceShadows=!0;minSize;manualUpdate=!1;set needsUpdate(e){this._needsUpdate=e}get needsUpdate(){return this._needsUpdate}_needsUpdate=!1;shadowsRoot=new M;shadowCamera;shadowGroup=new Co;renderTarget;renderTargetBlur;plane;occluderMesh;blurPlane;planeMaterial;depthMaterial;horizontalBlurMaterial;verticalBlurMaterial;textureSize=512;fitShadows(e={}){ih&&console.warn("Fitting shadows to scene"),Nd(this.shadowsRoot,!1);const t=e.object||this.context.scene,i=Ri(t,[this.shadowsRoot]),n=Math.max(1,this.blur/32),s=i.max.x-i.min.x,r=i.max.z-i.min.z;i.expandByVector(new b(n*s,0,n*r)),ih&&B.DrawWireBox3(i,16776960,60),this.gameObject.parent&&i.applyMatrix4(this.gameObject.parent.matrixWorld.clone().invert());const a=i.min,l=Math.max(1e-5,(i.max.y-a.y)*.002);i.max.y+=l,this.shadowsRoot.position.set((a.x+i.max.x)/2,a.y-l,(a.z+i.max.z)/2),this.shadowsRoot.scale.set(i.max.x-a.x,i.max.y-a.y,i.max.z-a.z),e.positionOffset&&(e.positionOffset.x!==void 0&&(this.shadowsRoot.position.x+=e.positionOffset.x),e.positionOffset.y!==void 0&&(this.shadowsRoot.position.y+=e.positionOffset.y),e.positionOffset.z!==void 0&&(this.shadowsRoot.position.z+=e.positionOffset.z)),e.scaleFactor&&(e.scaleFactor.x!==void 0&&(this.shadowsRoot.scale.x*=e.scaleFactor.x),e.scaleFactor.y!==void 0&&(this.shadowsRoot.scale.y*=e.scaleFactor.y),e.scaleFactor.z!==void 0&&(this.shadowsRoot.scale.z*=e.scaleFactor.z)),this.applyMinSize(),this.shadowsRoot.matrixWorldNeedsUpdate=!0,ih&&console.log("Fitted shadows to scene",this.shadowsRoot.scale.clone())}awake(){gd._instances.set(this.context,this),this.shadowsRoot.hideFlags=Gd.DontExport,Nd(this.shadowsRoot,!1)}start(){ih&&console.log("Create ContactShadows on "+this.gameObject.name,this),this.gameObject.add(this.shadowsRoot),this.shadowsRoot.add(this.shadowGroup),this.renderTarget=new Vn(this.textureSize,this.textureSize),this.renderTarget.texture.generateMipmaps=!1,this.renderTargetBlur=new Vn(this.textureSize,this.textureSize),this.renderTargetBlur.texture.generateMipmaps=!1;const e=new vn(1,1).rotateX(Math.PI/2);this.gameObject instanceof H&&(console.warn("ContactShadows can not be added to a Mesh. Please add it to a Group or an empty Object"),Bo(this.gameObject,!1));const t=this.planeMaterial=new Ce({map:this.renderTarget.texture,opacity:this.opacity,color:0,transparent:!0,depthWrite:!1,side:vs});this.plane=new H(e,t),this.plane.scale.y=-1,this.plane.layers.set(2),this.shadowsRoot.add(this.plane),this.plane&&(this.plane.renderOrder=1),this.occluderMesh=new H(this.plane.geometry,new Ce({depthWrite:!0,stencilWrite:!0,colorWrite:!1,side:Id})).translateY(-1e-4),this.occluderMesh.renderOrder=-100,this.occluderMesh.layers.set(2),this.shadowsRoot.add(this.occluderMesh),this.blurPlane=new H(e),this.blurPlane.visible=!1,this.shadowGroup.add(this.blurPlane);const i=0,n=1;this.shadowCamera=new Cd(-1/2,1/2,1/2,-1/2,i,n),this.shadowCamera.layers.enableAll(),this.shadowCamera.rotation.x=Math.PI/2,this.shadowCamera.matrixWorldAutoUpdate=!1,this.shadowGroup.add(this.shadowCamera),this.shadowCamera.updateMatrix(),this.depthMaterial=new dC,this.depthMaterial.userData.darkness={value:this.darkness},this.depthMaterial.blending=uC,this.depthMaterial.blendEquation=pC,this.depthMaterial.onBeforeCompile=s=>{this.depthMaterial&&(s.uniforms.darkness=this.depthMaterial.userData.darkness,s.fragmentShader=`
980
980
  uniform float darkness;
981
981
  ${s.fragmentShader.replace("gl_FragColor = vec4( vec3( 1.0 - fragCoordZ ), opacity );","gl_FragColor = vec4( vec3( 1.0 ), ( 1.0 - fragCoordZ ) * darkness * opacity * (gl_FrontFacing ? 1.0 : 0.66) );")}
982
- `)},this.depthMaterial.depthTest=!1,this.depthMaterial.depthWrite=!1,this.horizontalBlurMaterial=new Wn(fP),this.horizontalBlurMaterial.depthTest=!1,this.verticalBlurMaterial=new Wn(yP),this.verticalBlurMaterial.depthTest=!1,this.shadowGroup.visible=!1,this.autoFit?this.fitShadows():this.applyMinSize()}onEnable(){this._needsUpdate=!0}onDestroy(){gd._instances.get(this.context)===this&&gd._instances.delete(this.context),this.renderTarget?.dispose(),this.renderTargetBlur?.dispose(),this.depthMaterial?.dispose(),this.horizontalBlurMaterial?.dispose(),this.verticalBlurMaterial?.dispose(),this.blurPlane?.geometry.dispose(),this.plane?.geometry.dispose(),this.occluderMesh?.geometry.dispose()}onBeforeRender(e){if(this.manualUpdate&&!this._needsUpdate)return;if(this._needsUpdate=!1,!this.renderTarget||!this.renderTargetBlur||!this.depthMaterial||!this.shadowCamera||!this.blurPlane||!this.shadowGroup||!this.plane||!this.horizontalBlurMaterial||!this.verticalBlurMaterial||!this.planeMaterial){ih&&console.error("ContactShadows: not initialized yet");return}this.depthMaterial.userData.darkness.value=this.darkness,this.planeMaterial.opacity=this.opacity;const t=this.context.scene,i=this.context.renderer,n=i.getRenderTarget();this.shadowGroup.visible=!0,this.occluderMesh&&(this.occluderMesh.visible=!1);const s=this.plane.visible;this.plane.visible=!1,this.gameObject instanceof H&&Bo(this.gameObject,!1);const r=t.background;t.background=null,t.overrideMaterial=this.depthMaterial,this.backfaceShadows?this.depthMaterial.side=Pi:this.depthMaterial.side=vs;const a=i.getClearAlpha();i.setClearAlpha(0);const l=i.xr.enabled;i.xr.enabled=!1;const c=this.context.scene.matrixWorldAutoUpdate;this.context.scene.matrixWorldAutoUpdate=!1;const h=i.renderLists.get(t,0),d=h.transparent;xx.length=0,h.transparent=xx,Qf.length=0;for(const m of h.opaque){if(!m.object.visible)continue;const g=m.material;let f=m.material.colorWrite==!1||g.wireframe===!0||O_(m.object)===!1;!f&&m.material.isLineMaterial&&(f=!0),!f&&m.material.isPointsMaterial&&(f=!0),f&&(Qf.push(m.object),m.object["needle:visible"]=m.object.visible,m.object.visible=!1)}this.shadowCamera.parent?this.shadowCamera.matrixWorld.multiplyMatrices(this.shadowCamera.parent.matrixWorld,this.shadowCamera.matrix):this.shadowCamera.matrixWorld.copy(this.shadowCamera.matrix),this.shadowCamera.matrixWorldInverse.copy(this.shadowCamera.matrixWorld).invert(),i.setRenderTarget(this.renderTarget),i.clear(),i.render(t,this.shadowCamera),h.transparent=d;for(const m of Qf)m["needle:visible"]!=null&&(m.visible=m["needle:visible"]);t.overrideMaterial=null;const p=Math.max(this.blur,.05);this.blurShadow(p*2),this.blurShadow(p*.5),this.shadowGroup.visible=!1,this.occluderMesh&&(this.occluderMesh.visible=this.occludeBelowGround),this.plane.visible=s,i.setRenderTarget(n),i.setClearAlpha(a),t.background=r,i.xr.enabled=l,this.context.scene.matrixWorldAutoUpdate=c}blurShadow(e){if(!this.blurPlane||!this.shadowCamera||!this.renderTarget||!this.renderTargetBlur||!this.horizontalBlurMaterial||!this.verticalBlurMaterial)return;this.blurPlane.visible=!0;const t=this.shadowsRoot.worldScale,i=(t.x+t.z)/2,n=t.z/i,s=t.x/i;this.blurPlane.material=this.horizontalBlurMaterial,this.blurPlane.material.uniforms.tDiffuse.value=this.renderTarget.texture,this.horizontalBlurMaterial.uniforms.h.value=e*1/this.textureSize*n;const r=this.context.renderer,a=r.getRenderTarget();r.setRenderTarget(this.renderTargetBlur),r.render(this.blurPlane,this.shadowCamera),this.blurPlane.material=this.verticalBlurMaterial,this.blurPlane.material.uniforms.tDiffuse.value=this.renderTargetBlur.texture,this.verticalBlurMaterial.uniforms.v.value=e*1/this.textureSize*s,r.setRenderTarget(this.renderTarget),r.render(this.blurPlane,this.shadowCamera),this.blurPlane.visible=!1,r.setRenderTarget(a)}applyMinSize(){this.minSize&&this.shadowsRoot.scale.set(Math.max(this.minSize.x||0,this.shadowsRoot.scale.x),Math.max(this.minSize.y||0,this.shadowsRoot.scale.y),Math.max(this.minSize.z||0,this.shadowsRoot.scale.z))}};ml([u()],Xr.prototype,"autoFit"),ml([u()],Xr.prototype,"darkness"),ml([u()],Xr.prototype,"opacity"),ml([u()],Xr.prototype,"blur"),ml([u()],Xr.prototype,"occludeBelowGround"),ml([u()],Xr.prototype,"backfaceShadows");let nh=Xr;const xx=[],Qf=new Array,WR=w("logstats");class Yf extends E{onEnable(){console.log(this),WR&&this.startCoroutine(this.run(),xe.OnAfterRender)}*run(){for(;this.enabled;){const e=this.context.renderer.info;console.log(e.memory,e.render,e.programs),yield}}}class oh extends E{isUsed=!0;usedBy=null}class Zf extends E{}const Sx=w("debugdeletable");class gr extends Pt{static _instances=[];onEnable(){gr._instances.push(this)}onDisable(){const e=gr._instances.indexOf(this);e>=0&&gr._instances.splice(e,1)}}class Kf extends E{update(){for(const e of gr._instances){const t=this.gameObject;if(e.isInBox(t)===!0){const i=S.getComponentInParent(this.gameObject,oh);if(i)Sx&&console.warn("DeleteBox: Not deleting object with usage marker",this.guid,i);else{if(Sx)try{if(e.box){const n=e.box,s=Pt.testBox;B.DrawWireBox3(n,16711680,5),B.DrawWireBox3(s,255,5),console.log("DeleteBox: Destroying",this.gameObject,{deleteBoxArea:n,deletedObjectArea:s})}else console.log("DeleteBox: Destroying",this.gameObject)}catch{}Lc(this.gameObject,this.context.connection)}}}}}var VR=Object.defineProperty,$R=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&VR(e,t,n),n};class qu extends E{visibleOn;onEnable(){this.apply()}apply(){this.test()||S.setActive(this.gameObject,!1)}test(){return this.visibleOn<0?!0:I.isMobileDevice()?(this.visibleOn&2)!==0:(this.visibleOn&1)!==0}}$R([u()],qu.prototype,"visibleOn");var HR=Object.defineProperty,Qr=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&HR(e,t,n),n};const no=w("debugdrag"),Jf=[];var ey=(o=>(o[o.XZPlane=0]="XZPlane",o[o.Attached=1]="Attached",o[o.HitNormal=2]="HitNormal",o[o.DynamicViewAngle=3]="DynamicViewAngle",o[o.SnapToSurfaces=4]="SnapToSurfaces",o[o.None=5]="None",o))(ey||{});const Bs=class dn extends E{static get HasAnySelected(){return this._active>0}static _active=0;static get CurrentlySelected(){Jf.length=0;for(const e of this._instances)e._isDragging&&Jf.push(e);return Jf}static _instances=[];dragMode=3;snapGridResolution=0;keepRotation=!0;xrDragMode=1;xrKeepRotation=!1;xrDistanceDragFactor=1;showGizmo=!1;get draggedObject(){return this._targetObject}setTargetObject(e){this._targetObject=e;for(const i of this._dragHandlers.values())i.setTargetObject(e);const t="_rigidbody-was-kinematic";this._rigidbody?.[t]===!1&&(this._rigidbody.isKinematic=!1,this._rigidbody[t]=void 0),this._rigidbody=null,e&&(this._rigidbody=S.getComponentInChildren(e,Ze),this._rigidbody?.isKinematic===!1&&(this._rigidbody.isKinematic=!0,this._rigidbody[t]=!1))}_rigidbody=null;_targetObject=null;_dragHelper=null;static lastHovered;_draggingRigidbodies=[];_potentialDragStartEvt=null;_dragHandlers=new Map;_totalMovement=new b;_marker=null;_isDragging=!1;_didDrag=!1;awake(){this._potentialDragStartEvt=null,this._dragHandlers=new Map,this._totalMovement=new b,this._marker=null,this._isDragging=!1,this._didDrag=!1,this._dragHelper=null,this._draggingRigidbodies=[]}start(){this.gameObject.getComponentInParent(Ji)||this.gameObject.addComponent(Ji)}onEnable(){dn._instances.push(this),this.context.accessibility.updateElement(this,{role:"button",label:"Drag "+(this.gameObject.name||"object"),hidden:!1})}onDisable(){this.context.accessibility.updateElement(this,{hidden:!0}),dn._instances=dn._instances.filter(e=>e!==this)}onDestroy(){this.context.accessibility.removeElement(this)}allowEdit(e=null){return this.context.connection.allowEditing}onPointerEnter(e){if(!this.allowEdit(this.gameObject)||e.mode!=="screen"||(e.event.mode==="tracked-pointer"||e.event.mode==="transient-pointer"?this.xrDragMode:this.dragMode)===5)return;const t=S.getComponentInParent(e.object,dn);!t||t!==this||(dn.lastHovered=e.object,this.context.domElement.style.cursor="pointer",this.context.accessibility.hover(this,`Draggable ${e.object?.name}`))}onPointerMove(e){(this._isDragging||this._potentialDragStartEvt!==null)&&e.use()}onPointerExit(e){this.allowEdit(this.gameObject)&&e.mode==="screen"&&dn.lastHovered===e.object&&(this.context.domElement.style.cursor="auto")}onPointerDown(e){if(!(!this.allowEdit(this.gameObject)||e.used||(e.mode==="tracked-pointer"||e.mode==="transient-pointer"?this.xrDragMode:this.dragMode)===5)&&(dn.lastHovered=e.object,e.button===0)){this._dragHandlers.size===0&&(this._didDrag=!1,this._totalMovement.set(0,0,0),this._potentialDragStartEvt=e),this._targetObject||this.setTargetObject(this.gameObject),dn._active+=1;const t=new ty(this,this._targetObject);if(this._dragHandlers.set(e.event.space,t),t.onDragStart(e),this._dragHandlers.size===2){const i=this._dragHandlers.values(),n=i.next().value,s=i.next().value;if(n instanceof ty&&s instanceof ty){const r=new GR(this,this._targetObject,n,s);this._dragHandlers.set(this.gameObject,r),r.onDragStart(e)}else console.error("Attempting to construct a MultiTouchDragHandler with invalid DragPointerHandlers. This is likely a bug.",{a:n,b:s})}e.use(),this.context.accessibility.updateElement(this,{role:"button",label:"Dragging "+(this.gameObject.name||"object"),hidden:!1,busy:!0}),this.context.accessibility.focus(this)}}onPointerUp(e){if(no&&B.DrawLabel(e.point??this.gameObject.worldPosition,"POINTERUP:"+e.pointerId+", "+e.button,.03,3),!this.allowEdit(this.gameObject)||e.button!==0)return;this._potentialDragStartEvt=null;const t=this._dragHandlers.get(e.event.space),i=this._dragHandlers.get(this.gameObject);i&&(i.handlerA===t||i.handlerB===t)&&(this._dragHandlers.delete(this.gameObject),i.onDragEnd(e)),t&&(dn._active>0&&(dn._active-=1),this.setTargetObject(null),t.onDragEnd&&t.onDragEnd(e),this._dragHandlers.delete(e.event.space),this._dragHandlers.size===0&&this.onLastDragEnd(e),e.use()),this.context.accessibility.unfocus(this),this.context.accessibility.updateElement(this,{busy:!1})}update(){for(const e of this._dragHandlers.values())e.collectMovementInfo&&e.collectMovementInfo(),e.getTotalMovement&&this._totalMovement.add(e.getTotalMovement());if(this._potentialDragStartEvt){if(!this._didDrag)if(this._totalMovement.length()>3e-4)this._didDrag=!0;else return;const e=this._potentialDragStartEvt;this._potentialDragStartEvt=null,this.onFirstDragStart(e)}for(const e of this._dragHandlers.values())e.onDragUpdate&&e.onDragUpdate(this._dragHandlers.size);this._dragHelper&&this._dragHelper.hasSelected&&this.onAnyDragUpdate()}onFirstDragStart(e){if(!e||!e.object)return;const t=S.getComponentInParent(e.object,dn);if(!t||t!==this&&t._isDragging)return;const i=this._targetObject||this.gameObject;if(!i)return;this._isDragging=!0;const n=S.getComponentInChildren(i,Tn);no&&console.log("DRAG START",n,i),n&&(n.fastMode=!0,n?.requestOwnership()),this._marker=S.addComponent(i,oh),this._draggingRigidbodies.length=0;const s=S.getComponentsInChildren(i,Ze);s&&this._draggingRigidbodies.push(...s),i.matrixAutoUpdate===!1&&!globalThis["DragControls:MatrixWarningShown"]&&(globalThis["DragControls:MatrixWarningShown"]=!0,console.warn("Dragging an object with matrixAutoUpdate=false can lead to unexpected behavior. Consider enabling matrixAutoUpdate or updating the matrix manually during dragging."))}onAnyDragUpdate(){if(!this._dragHelper)return;this._dragHelper.showGizmo=this.showGizmo,this._dragHelper.onUpdate(this.context);for(const t of this._draggingRigidbodies)t.wakeUp(),t.resetVelocities(),t.resetForcesAndTorques();const e=this._targetObject||this.gameObject;pn.markDirty(e)}onLastDragEnd(e){if(!this||!this._isDragging)return;this._isDragging=!1;for(const i of this._draggingRigidbodies)i.setVelocity(i.smoothedVelocity.multiplyScalar(this.context.time.deltaTime));if(this._draggingRigidbodies.length=0,this._targetObject=null,e?.object){const i=S.getComponentInChildren(e.object,Tn);i&&(i.fastMode=!1)}if(this._marker&&this._marker.destroy(),!this._dragHelper)return;const t=this._dragHelper.selected;no&&console.log("DRAG END",t,t?.visible),this._dragHelper.setSelected(null,this.context)}};Qr([u()],Bs.prototype,"dragMode"),Qr([u()],Bs.prototype,"snapGridResolution"),Qr([u()],Bs.prototype,"keepRotation"),Qr([u()],Bs.prototype,"xrDragMode"),Qr([u()],Bs.prototype,"xrKeepRotation"),Qr([u()],Bs.prototype,"xrDistanceDragFactor"),Qr([u()],Bs.prototype,"showGizmo");let Yr=Bs;class GR{handlerA;handlerB;context;settings;gameObject;_handlerAAttachmentPoint=new b;_handlerBAttachmentPoint=new b;_followObject;_manipulatorObject;_deviceMode;_followObjectStartWorldQuaternion=new N;constructor(e,t,i,n){this.context=e.context,this.settings=e,this.gameObject=t,this.handlerA=i,this.handlerB=n,this._followObject=new M,this._manipulatorObject=new M,this.context.scene.add(this._manipulatorObject);const s=Z.active?.rig?.gameObject;if(!this.handlerA||!this.handlerB||!this.handlerA.hitPointInLocalSpace||!this.handlerB.hitPointInLocalSpace){console.error("Invalid: MultiTouchDragHandler needs two valid DragPointerHandlers with hitPointInLocalSpace set.");return}if(this._tempVec1.copy(this.handlerA.hitPointInLocalSpace),this._tempVec2.copy(this.handlerB.hitPointInLocalSpace),this.gameObject.localToWorld(this._tempVec1),this.gameObject.localToWorld(this._tempVec2),s&&(s.worldToLocal(this._tempVec1),s.worldToLocal(this._tempVec2)),this._initialDistance=this._tempVec1.distanceTo(this._tempVec2),this._initialDistance<.02?(no&&console.log("Finding alternative drag attachment points since initial distance is too low: "+this._initialDistance.toFixed(2)),this.handlerA.followObject.parent.getWorldPosition(this._tempVec1),this.handlerB.followObject.parent.getWorldPosition(this._tempVec2),this._handlerAAttachmentPoint.copy(this._tempVec1),this._handlerBAttachmentPoint.copy(this._tempVec2),this.gameObject.worldToLocal(this._handlerAAttachmentPoint),this.gameObject.worldToLocal(this._handlerBAttachmentPoint),this._initialDistance=this._tempVec1.distanceTo(this._tempVec2),this._initialDistance<.001&&(console.warn("Not supported right now \u2013 controller drag points for multitouch are too close!"),this._initialDistance=1)):(this._handlerAAttachmentPoint.copy(this.handlerA.hitPointInLocalSpace),this._handlerBAttachmentPoint.copy(this.handlerB.hitPointInLocalSpace)),this._tempVec3.lerpVectors(this._tempVec1,this._tempVec2,.5),this._initialScale.copy(t.scale),no){this._followObject.add(new Ci(2)),this._manipulatorObject.add(new Ci(5));const r=a=>`${a.x.toFixed(2)}, ${a.y.toFixed(2)}, ${a.z.toFixed(2)}`;B.DrawLine(this._tempVec1,this._tempVec2,65535,0,!1),B.DrawLabel(this._tempVec3,"A:B "+this._initialDistance.toFixed(2)+`
982
+ `)},this.depthMaterial.depthTest=!1,this.depthMaterial.depthWrite=!1,this.horizontalBlurMaterial=new Wn(fP),this.horizontalBlurMaterial.depthTest=!1,this.verticalBlurMaterial=new Wn(yP),this.verticalBlurMaterial.depthTest=!1,this.shadowGroup.visible=!1,this.autoFit?this.fitShadows():this.applyMinSize()}onEnable(){this._needsUpdate=!0}onDestroy(){gd._instances.get(this.context)===this&&gd._instances.delete(this.context),this.renderTarget?.dispose(),this.renderTargetBlur?.dispose(),this.depthMaterial?.dispose(),this.horizontalBlurMaterial?.dispose(),this.verticalBlurMaterial?.dispose(),this.blurPlane?.geometry.dispose(),this.plane?.geometry.dispose(),this.occluderMesh?.geometry.dispose()}onBeforeRender(e){if(this.manualUpdate&&!this._needsUpdate)return;if(this._needsUpdate=!1,!this.renderTarget||!this.renderTargetBlur||!this.depthMaterial||!this.shadowCamera||!this.blurPlane||!this.shadowGroup||!this.plane||!this.horizontalBlurMaterial||!this.verticalBlurMaterial||!this.planeMaterial){ih&&console.error("ContactShadows: not initialized yet");return}this.depthMaterial.userData.darkness.value=this.darkness,this.planeMaterial.opacity=this.opacity;const t=this.context.scene,i=this.context.renderer,n=i.getRenderTarget();this.shadowGroup.visible=!0,this.occluderMesh&&(this.occluderMesh.visible=!1);const s=this.plane.visible;this.plane.visible=!1,this.gameObject instanceof H&&Bo(this.gameObject,!1);const r=t.background;t.background=null,t.overrideMaterial=this.depthMaterial,this.backfaceShadows?this.depthMaterial.side=Pi:this.depthMaterial.side=vs;const a=i.getClearAlpha();i.setClearAlpha(0);const l=i.xr.enabled;i.xr.enabled=!1;const c=this.context.scene.matrixWorldAutoUpdate;this.context.scene.matrixWorldAutoUpdate=!1;const h=i.renderLists.get(t,0),d=h.transparent;xx.length=0,h.transparent=xx,Qf.length=0;for(const m of h.opaque){if(!m.object.visible)continue;const g=m.material;let f=m.material.colorWrite==!1||g.wireframe===!0||O_(m.object)===!1;!f&&m.material.isLineMaterial&&(f=!0),!f&&m.material.isPointsMaterial&&(f=!0),f&&(Qf.push(m.object),m.object["needle:visible"]=m.object.visible,m.object.visible=!1)}this.shadowCamera.parent?this.shadowCamera.matrixWorld.multiplyMatrices(this.shadowCamera.parent.matrixWorld,this.shadowCamera.matrix):this.shadowCamera.matrixWorld.copy(this.shadowCamera.matrix),this.shadowCamera.matrixWorldInverse.copy(this.shadowCamera.matrixWorld).invert(),i.setRenderTarget(this.renderTarget),i.clear(),i.render(t,this.shadowCamera),h.transparent=d;for(const m of Qf)m["needle:visible"]!=null&&(m.visible=m["needle:visible"]);t.overrideMaterial=null;const p=Math.max(this.blur,.05);this.blurShadow(p*2),this.blurShadow(p*.5),this.shadowGroup.visible=!1,this.occluderMesh&&(this.occluderMesh.visible=this.occludeBelowGround),this.plane.visible=s,i.setRenderTarget(n),i.setClearAlpha(a),t.background=r,i.xr.enabled=l,this.context.scene.matrixWorldAutoUpdate=c}blurShadow(e){if(!this.blurPlane||!this.shadowCamera||!this.renderTarget||!this.renderTargetBlur||!this.horizontalBlurMaterial||!this.verticalBlurMaterial)return;this.blurPlane.visible=!0;const t=this.shadowsRoot.worldScale,i=(t.x+t.z)/2,n=t.z/i,s=t.x/i;this.blurPlane.material=this.horizontalBlurMaterial,this.blurPlane.material.uniforms.tDiffuse.value=this.renderTarget.texture,this.horizontalBlurMaterial.uniforms.h.value=e*1/this.textureSize*n;const r=this.context.renderer,a=r.getRenderTarget();r.setRenderTarget(this.renderTargetBlur),r.render(this.blurPlane,this.shadowCamera),this.blurPlane.material=this.verticalBlurMaterial,this.blurPlane.material.uniforms.tDiffuse.value=this.renderTargetBlur.texture,this.verticalBlurMaterial.uniforms.v.value=e*1/this.textureSize*s,r.setRenderTarget(this.renderTarget),r.render(this.blurPlane,this.shadowCamera),this.blurPlane.visible=!1,r.setRenderTarget(a)}applyMinSize(){this.minSize&&this.shadowsRoot.scale.set(Math.max(this.minSize.x||0,this.shadowsRoot.scale.x),Math.max(this.minSize.y||0,this.shadowsRoot.scale.y),Math.max(this.minSize.z||0,this.shadowsRoot.scale.z))}};ml([u()],Xr.prototype,"autoFit"),ml([u()],Xr.prototype,"darkness"),ml([u()],Xr.prototype,"opacity"),ml([u()],Xr.prototype,"blur"),ml([u()],Xr.prototype,"occludeBelowGround"),ml([u()],Xr.prototype,"backfaceShadows");let nh=Xr;const xx=[],Qf=new Array,WR=w("logstats");class Yf extends E{onEnable(){console.log(this),WR&&this.startCoroutine(this.run(),xe.OnAfterRender)}*run(){for(;this.enabled;){const e=this.context.renderer.info;console.log(e.memory,e.render,e.programs),yield}}}class oh extends E{isUsed=!0;usedBy=null}class Zf extends E{}const Sx=w("debugdeletable");class gr extends Pt{static _instances=[];onEnable(){gr._instances.push(this)}onDisable(){const e=gr._instances.indexOf(this);e>=0&&gr._instances.splice(e,1)}}class Kf extends E{update(){for(const e of gr._instances){const t=this.gameObject;if(e.isInBox(t)===!0){const i=S.getComponentInParent(this.gameObject,oh);if(i)Sx&&console.warn("DeleteBox: Not deleting object with usage marker",this.guid,i);else{if(Sx)try{if(e.box){const n=e.box,s=Pt.testBox;B.DrawWireBox3(n,16711680,5),B.DrawWireBox3(s,255,5),console.log("DeleteBox: Destroying",this.gameObject,{deleteBoxArea:n,deletedObjectArea:s})}else console.log("DeleteBox: Destroying",this.gameObject)}catch{}Lc(this.gameObject,this.context.connection)}}}}}var VR=Object.defineProperty,$R=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&VR(e,t,n),n};class qu extends E{visibleOn;onEnable(){this.apply()}apply(){this.test()||S.setActive(this.gameObject,!1)}test(){return this.visibleOn<0?!0:I.isMobileDevice()?(this.visibleOn&2)!==0:(this.visibleOn&1)!==0}}$R([u()],qu.prototype,"visibleOn");var HR=Object.defineProperty,Qr=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&HR(e,t,n),n};const no=w("debugdrag"),Jf=[];var ey=(o=>(o[o.XZPlane=0]="XZPlane",o[o.Attached=1]="Attached",o[o.HitNormal=2]="HitNormal",o[o.DynamicViewAngle=3]="DynamicViewAngle",o[o.SnapToSurfaces=4]="SnapToSurfaces",o[o.None=5]="None",o))(ey||{});const Bs=class dn extends E{static get HasAnySelected(){return this._active>0}static _active=0;static get CurrentlySelected(){Jf.length=0;for(const e of this._instances)e._isDragging&&Jf.push(e);return Jf}static _instances=[];dragMode=3;snapGridResolution=0;keepRotation=!0;xrDragMode=1;xrKeepRotation=!1;xrDistanceDragFactor=1;showGizmo=!1;get draggedObject(){return this._targetObject}setTargetObject(e){this._targetObject=e;for(const i of this._dragHandlers.values())i.setTargetObject(e);const t="_rigidbody-was-kinematic";this._rigidbody?.[t]===!1&&(this._rigidbody.isKinematic=!1,this._rigidbody[t]=void 0),this._rigidbody=null,e&&(this._rigidbody=S.getComponentInChildren(e,Ke),this._rigidbody?.isKinematic===!1&&(this._rigidbody.isKinematic=!0,this._rigidbody[t]=!1))}_rigidbody=null;_targetObject=null;_dragHelper=null;static lastHovered;_draggingRigidbodies=[];_potentialDragStartEvt=null;_dragHandlers=new Map;_totalMovement=new b;_marker=null;_isDragging=!1;_didDrag=!1;awake(){this._potentialDragStartEvt=null,this._dragHandlers=new Map,this._totalMovement=new b,this._marker=null,this._isDragging=!1,this._didDrag=!1,this._dragHelper=null,this._draggingRigidbodies=[]}start(){this.gameObject.getComponentInParent(Ji)||this.gameObject.addComponent(Ji)}onEnable(){dn._instances.push(this),this.context.accessibility.updateElement(this,{role:"button",label:"Drag "+(this.gameObject.name||"object"),hidden:!1})}onDisable(){this.context.accessibility.updateElement(this,{hidden:!0}),dn._instances=dn._instances.filter(e=>e!==this)}onDestroy(){this.context.accessibility.removeElement(this)}allowEdit(e=null){return this.context.connection.allowEditing}onPointerEnter(e){if(!this.allowEdit(this.gameObject)||e.mode!=="screen"||(e.event.mode==="tracked-pointer"||e.event.mode==="transient-pointer"?this.xrDragMode:this.dragMode)===5)return;const t=S.getComponentInParent(e.object,dn);!t||t!==this||(dn.lastHovered=e.object,this.context.domElement.style.cursor="pointer",this.context.accessibility.hover(this,`Draggable ${e.object?.name}`))}onPointerMove(e){(this._isDragging||this._potentialDragStartEvt!==null)&&e.use()}onPointerExit(e){this.allowEdit(this.gameObject)&&e.mode==="screen"&&dn.lastHovered===e.object&&(this.context.domElement.style.cursor="auto")}onPointerDown(e){if(!(!this.allowEdit(this.gameObject)||e.used||(e.mode==="tracked-pointer"||e.mode==="transient-pointer"?this.xrDragMode:this.dragMode)===5)&&(dn.lastHovered=e.object,e.button===0)){this._dragHandlers.size===0&&(this._didDrag=!1,this._totalMovement.set(0,0,0),this._potentialDragStartEvt=e),this._targetObject||this.setTargetObject(this.gameObject),dn._active+=1;const t=new ty(this,this._targetObject);if(this._dragHandlers.set(e.event.space,t),t.onDragStart(e),this._dragHandlers.size===2){const i=this._dragHandlers.values(),n=i.next().value,s=i.next().value;if(n instanceof ty&&s instanceof ty){const r=new GR(this,this._targetObject,n,s);this._dragHandlers.set(this.gameObject,r),r.onDragStart(e)}else console.error("Attempting to construct a MultiTouchDragHandler with invalid DragPointerHandlers. This is likely a bug.",{a:n,b:s})}e.use(),this.context.accessibility.updateElement(this,{role:"button",label:"Dragging "+(this.gameObject.name||"object"),hidden:!1,busy:!0}),this.context.accessibility.focus(this)}}onPointerUp(e){if(no&&B.DrawLabel(e.point??this.gameObject.worldPosition,"POINTERUP:"+e.pointerId+", "+e.button,.03,3),!this.allowEdit(this.gameObject)||e.button!==0)return;this._potentialDragStartEvt=null;const t=this._dragHandlers.get(e.event.space),i=this._dragHandlers.get(this.gameObject);i&&(i.handlerA===t||i.handlerB===t)&&(this._dragHandlers.delete(this.gameObject),i.onDragEnd(e)),t&&(dn._active>0&&(dn._active-=1),this.setTargetObject(null),t.onDragEnd&&t.onDragEnd(e),this._dragHandlers.delete(e.event.space),this._dragHandlers.size===0&&this.onLastDragEnd(e),e.use()),this.context.accessibility.unfocus(this),this.context.accessibility.updateElement(this,{busy:!1})}update(){for(const e of this._dragHandlers.values())e.collectMovementInfo&&e.collectMovementInfo(),e.getTotalMovement&&this._totalMovement.add(e.getTotalMovement());if(this._potentialDragStartEvt){if(!this._didDrag)if(this._totalMovement.length()>3e-4)this._didDrag=!0;else return;const e=this._potentialDragStartEvt;this._potentialDragStartEvt=null,this.onFirstDragStart(e)}for(const e of this._dragHandlers.values())e.onDragUpdate&&e.onDragUpdate(this._dragHandlers.size);this._dragHelper&&this._dragHelper.hasSelected&&this.onAnyDragUpdate()}onFirstDragStart(e){if(!e||!e.object)return;const t=S.getComponentInParent(e.object,dn);if(!t||t!==this&&t._isDragging)return;const i=this._targetObject||this.gameObject;if(!i)return;this._isDragging=!0;const n=S.getComponentInChildren(i,Tn);no&&console.log("DRAG START",n,i),n&&(n.fastMode=!0,n?.requestOwnership()),this._marker=S.addComponent(i,oh),this._draggingRigidbodies.length=0;const s=S.getComponentsInChildren(i,Ke);s&&this._draggingRigidbodies.push(...s),i.matrixAutoUpdate===!1&&!globalThis["DragControls:MatrixWarningShown"]&&(globalThis["DragControls:MatrixWarningShown"]=!0,console.warn("Dragging an object with matrixAutoUpdate=false can lead to unexpected behavior. Consider enabling matrixAutoUpdate or updating the matrix manually during dragging."))}onAnyDragUpdate(){if(!this._dragHelper)return;this._dragHelper.showGizmo=this.showGizmo,this._dragHelper.onUpdate(this.context);for(const t of this._draggingRigidbodies)t.wakeUp(),t.resetVelocities(),t.resetForcesAndTorques();const e=this._targetObject||this.gameObject;pn.markDirty(e)}onLastDragEnd(e){if(!this||!this._isDragging)return;this._isDragging=!1;for(const i of this._draggingRigidbodies)i.setVelocity(i.smoothedVelocity.multiplyScalar(this.context.time.deltaTime));if(this._draggingRigidbodies.length=0,this._targetObject=null,e?.object){const i=S.getComponentInChildren(e.object,Tn);i&&(i.fastMode=!1)}if(this._marker&&this._marker.destroy(),!this._dragHelper)return;const t=this._dragHelper.selected;no&&console.log("DRAG END",t,t?.visible),this._dragHelper.setSelected(null,this.context)}};Qr([u()],Bs.prototype,"dragMode"),Qr([u()],Bs.prototype,"snapGridResolution"),Qr([u()],Bs.prototype,"keepRotation"),Qr([u()],Bs.prototype,"xrDragMode"),Qr([u()],Bs.prototype,"xrKeepRotation"),Qr([u()],Bs.prototype,"xrDistanceDragFactor"),Qr([u()],Bs.prototype,"showGizmo");let Yr=Bs;class GR{handlerA;handlerB;context;settings;gameObject;_handlerAAttachmentPoint=new b;_handlerBAttachmentPoint=new b;_followObject;_manipulatorObject;_deviceMode;_followObjectStartWorldQuaternion=new N;constructor(e,t,i,n){this.context=e.context,this.settings=e,this.gameObject=t,this.handlerA=i,this.handlerB=n,this._followObject=new M,this._manipulatorObject=new M,this.context.scene.add(this._manipulatorObject);const s=Z.active?.rig?.gameObject;if(!this.handlerA||!this.handlerB||!this.handlerA.hitPointInLocalSpace||!this.handlerB.hitPointInLocalSpace){console.error("Invalid: MultiTouchDragHandler needs two valid DragPointerHandlers with hitPointInLocalSpace set.");return}if(this._tempVec1.copy(this.handlerA.hitPointInLocalSpace),this._tempVec2.copy(this.handlerB.hitPointInLocalSpace),this.gameObject.localToWorld(this._tempVec1),this.gameObject.localToWorld(this._tempVec2),s&&(s.worldToLocal(this._tempVec1),s.worldToLocal(this._tempVec2)),this._initialDistance=this._tempVec1.distanceTo(this._tempVec2),this._initialDistance<.02?(no&&console.log("Finding alternative drag attachment points since initial distance is too low: "+this._initialDistance.toFixed(2)),this.handlerA.followObject.parent.getWorldPosition(this._tempVec1),this.handlerB.followObject.parent.getWorldPosition(this._tempVec2),this._handlerAAttachmentPoint.copy(this._tempVec1),this._handlerBAttachmentPoint.copy(this._tempVec2),this.gameObject.worldToLocal(this._handlerAAttachmentPoint),this.gameObject.worldToLocal(this._handlerBAttachmentPoint),this._initialDistance=this._tempVec1.distanceTo(this._tempVec2),this._initialDistance<.001&&(console.warn("Not supported right now \u2013 controller drag points for multitouch are too close!"),this._initialDistance=1)):(this._handlerAAttachmentPoint.copy(this.handlerA.hitPointInLocalSpace),this._handlerBAttachmentPoint.copy(this.handlerB.hitPointInLocalSpace)),this._tempVec3.lerpVectors(this._tempVec1,this._tempVec2,.5),this._initialScale.copy(t.scale),no){this._followObject.add(new Ci(2)),this._manipulatorObject.add(new Ci(5));const r=a=>`${a.x.toFixed(2)}, ${a.y.toFixed(2)}, ${a.z.toFixed(2)}`;B.DrawLine(this._tempVec1,this._tempVec2,65535,0,!1),B.DrawLabel(this._tempVec3,"A:B "+this._initialDistance.toFixed(2)+`
983
983
  `+r(this._tempVec1)+`
984
984
  `+r(this._tempVec2),.03,5)}}onDragStart(e){this.gameObject.add(this._followObject),this._followObject.matrixAutoUpdate=!1,this._followObject.matrix.identity(),this._deviceMode=e.mode,this._followObjectStartWorldQuaternion.copy(this._followObject.worldQuaternion),this.alignManipulator(),this._manipulatorObject.attach(this._followObject),this._manipulatorPosOffset.copy(this._followObject.position),this._manipulatorRotOffset.copy(this._followObject.quaternion),this._manipulatorScaleOffset.copy(this._followObject.scale)}onDragEnd(e){if(!this.handlerA||!this.handlerB){console.error("onDragEnd called on MultiTouchDragHandler without valid handlers. This is likely a bug.");return}this.handlerA.recenter(),this.handlerB.recenter(),this._manipulatorObject.removeFromParent(),this._followObject.removeFromParent(),this._manipulatorObject.destroy(),this._followObject.destroy()}_manipulatorPosOffset=new b;_manipulatorRotOffset=new N;_manipulatorScaleOffset=new b;_tempVec1=new b;_tempVec2=new b;_tempVec3=new b;tempLookMatrix=new J;_initialScale=new b;_initialDistance=0;alignManipulator(){if(!this.handlerA||!this.handlerB){console.error("alignManipulator called on MultiTouchDragHandler without valid handlers. This is likely a bug.",this);return}if(!this.handlerA.followObject||!this.handlerB.followObject){console.error("alignManipulator called on MultiTouchDragHandler without valid follow objects. This is likely a bug.",this.handlerA,this.handlerB);return}this._tempVec1.copy(this._handlerAAttachmentPoint),this._tempVec2.copy(this._handlerBAttachmentPoint),this.handlerA.followObject.localToWorld(this._tempVec1),this.handlerB.followObject.localToWorld(this._tempVec2),this._tempVec3.lerpVectors(this._tempVec1,this._tempVec2,.5),this._manipulatorObject.position.copy(this._tempVec3);const e=this.context.mainCamera;this.tempLookMatrix.lookAt(this._tempVec3,this._tempVec2,e.worldUp),this._manipulatorObject.quaternion.setFromRotationMatrix(this.tempLookMatrix);const t=this._tempVec1.distanceTo(this._tempVec2);this._manipulatorObject.scale.copy(this._initialScale).multiplyScalar(t/this._initialDistance),this._manipulatorObject.updateMatrix(),this._manipulatorObject.updateMatrixWorld(!0),no&&(B.DrawLabel(this._tempVec3.clone().add(new b(0,.2,0)),"A:B "+t.toFixed(2),.03),B.DrawLine(this._tempVec1,this._tempVec2,65280,0,!1))}onDragUpdate(){this.alignManipulator();const e=30,t=1;this._followObject.position.copy(this._manipulatorPosOffset),this._followObject.quaternion.copy(this._manipulatorRotOffset),this._followObject.scale.copy(this._manipulatorScaleOffset);const i=this.gameObject,n=this._followObject;if(!i){console.error("MultiTouchDragHandler has no dragged object. This is likely a bug.");return}n.updateMatrix(),n.updateMatrixWorld(!0);const s=this._deviceMode==="tracked-pointer"||this._deviceMode==="transient-pointer"?this.settings.xrKeepRotation:this.settings.keepRotation;if(this.settings.snapGridResolution>0){const h=this._followObject.worldPosition,d=this.settings.snapGridResolution;h.x=Math.round(h.x/d)*d,h.y=Math.round(h.y/d)*d,h.z=Math.round(h.z/d)*d,this._followObject.worldPosition=h,this._followObject.updateMatrix()}s&&(this._followObject.worldQuaternion=this._followObjectStartWorldQuaternion,this._followObject.updateMatrix());const r=j.clamp01(this.context.time.deltaTime*e*t),a=i.worldPosition;a.lerp(n.worldPosition,r),i.worldPosition=a;const l=i.worldQuaternion;l.slerp(n.worldQuaternion,r),i.worldQuaternion=l;const c=i.worldScale;c.lerp(n.worldScale,r),i.worldScale=c,i.matrixAutoUpdate===!1&&i.updateMatrix()}setTargetObject(e){this.gameObject=e}}class ty{getTotalMovement(){return this._totalMovement}get followObject(){return this._followObject}get hitPointInLocalSpace(){return this._hitPointInLocalSpace}context;gameObject;settings;_lastRig=void 0;_followObject;_totalMovement=new b;_totalMovementAlongRayDirection=0;_grabStartDistance=0;_deviceMode;_followObjectStartPosition=new b;_followObjectStartQuaternion=new N;_followObjectStartWorldQuaternion=new N;_lastDragPosRigSpace;_tempVec=new b;_tempMat=new J;_hitPointInLocalSpace=new b;_hitNormalInLocalSpace=new b;_bottomCenter=new b;_backCenter=new b;_backBottomCenter=new b;_bounds=new Si;_dragPlane=new _r(new b(0,1,0));_draggedOverObject=null;_draggedOverObjectLastSetUp=null;_draggedOverObjectLastNormal=new b;_draggedOverObjectDuration=0;setTargetObject(e){this.gameObject=e}constructor(e,t){this.settings=e,this.context=e.context,this.gameObject=t,this._followObject=new M}recenter(){if(!this._followObject.parent){console.warn("Error: space follow object doesn't have parent but recenter() is called. This is likely a bug");return}if(!this.gameObject){console.warn("Error: space follow object doesn't have a gameObject");return}const e=this._followObject.parent;this.gameObject.add(this._followObject),this._followObject.matrixAutoUpdate=!1,this._followObject.position.set(0,0,0),this._followObject.quaternion.set(0,0,0,1),this._followObject.scale.set(1,1,1),this._followObject.updateMatrix(),this._followObject.updateMatrixWorld(!0),e.attach(this._followObject),this._followObjectStartPosition.copy(this._followObject.position),this._followObjectStartQuaternion.copy(this._followObject.quaternion),this._followObjectStartWorldQuaternion.copy(this._followObject.worldQuaternion),this._followObject.updateMatrix(),this._followObject.updateMatrixWorld(!0);const t=this._hitPointInLocalSpace.clone();this.gameObject.localToWorld(t),this._grabStartDistance=t.distanceTo(e.worldPosition);const i=Z.active?.rig?.gameObject?.worldScale.x||1;this._grabStartDistance/=i,this._totalMovementAlongRayDirection=0,this._lastDragPosRigSpace=void 0,no&&(B.DrawLine(t,e.worldPosition,65280,.5,!1),B.DrawLabel(e.worldPosition.add(new b(0,.1,0)),this._grabStartDistance.toFixed(2),.03,.5))}onDragStart(e){if(!this.gameObject){console.warn("Error: space follow object doesn't have a gameObject");return}if(e.event.space.add(this._followObject),this._lastDragPosRigSpace=void 0,e.point&&e.normal)this._hitPointInLocalSpace.copy(e.point),this.gameObject.worldToLocal(this._hitPointInLocalSpace),this._hitNormalInLocalSpace.copy(e.normal);else if(e){const m=e.event.space,g=m.worldPosition;this.gameObject.worldToLocal(g),this._hitPointInLocalSpace.copy(g);const f=m.worldUp;this._tempMat.copy(this.gameObject.matrixWorld).invert(),f.transformDirection(this._tempMat),this._hitNormalInLocalSpace.copy(f)}this.recenter(),this._totalMovement.set(0,0,0),this._deviceMode=e.mode;const t=this._followObject.parent.worldForward,i=this._deviceMode==="tracked-pointer"||this._deviceMode==="transient-pointer"?this.settings.xrDragMode:this.settings.dragMode,n=this._hitPointInLocalSpace.clone();switch(this.gameObject.localToWorld(n),i){case 0:const m=new b(0,1,0);this.gameObject.parent&&m.transformDirection(this.gameObject.parent.matrixWorld.clone().invert()),this._dragPlane.setFromNormalAndCoplanarPoint(m,n);break;case 2:const g=this._hitNormalInLocalSpace.clone();g.transformDirection(this.gameObject.matrixWorld),this._dragPlane.setFromNormalAndCoplanarPoint(g,n);break;case 1:this._dragPlane.setFromNormalAndCoplanarPoint(t,n);break;case 3:this.setPlaneViewAligned(n,!0);break;case 4:this.setPlaneViewAligned(n,!1);break}const s=this.gameObject.parent,r=this.gameObject.position.clone(),a=this.gameObject.quaternion.clone(),l=this.gameObject.scale.clone(),c=this.gameObject.matrixWorld.clone();s&&s.remove(this.gameObject),this.gameObject.position.set(0,0,0),this.gameObject.quaternion.set(0,0,0,1),this.gameObject.scale.set(1,1,1);const h=Ri([this.gameObject]);h.expandByPoint(this.gameObject.worldPosition);const d=new b;h.getCenter(d);const p=new b;h.getSize(p),this._bottomCenter.copy(d.clone().add(new b(0,-p.y/2,0))),this._backCenter.copy(d.clone().add(new b(0,0,p.z/2))),this._backBottomCenter.copy(d.clone().add(new b(0,-p.y/2,p.z/2))),this._bounds.copy(h),s&&s.add(this.gameObject),this.gameObject.position.copy(r),this.gameObject.quaternion.copy(a),this.gameObject.scale.copy(l),this.gameObject.matrixWorld.copy(c),this._draggedOverObject=null,this._draggedOverObjectLastSetUp=null,this._draggedOverObjectLastNormal.set(0,1,0),this._draggedOverObjectDuration=0}collectMovementInfo(){if(!this._followObject.parent)return;const e=this._followObject.parent;this._followObject.updateMatrix();const t=e.worldPosition,i=Z.active?.rig?.gameObject;i&&i.worldToLocal(t),(this._lastDragPosRigSpace===void 0||i!=this._lastRig)&&(this._lastDragPosRigSpace=t.clone(),this._lastRig=i),this._tempVec.copy(t).sub(this._lastDragPosRigSpace);const n=e.worldForward;if(i&&(this._tempMat.copy(i.matrixWorld).invert(),n.transformDirection(this._tempMat)),this._totalMovementAlongRayDirection+=n.dot(this._tempVec),this._tempVec.x=Math.abs(this._tempVec.x),this._tempVec.y=Math.abs(this._tempVec.y),this._tempVec.z=Math.abs(this._tempVec.z),this._totalMovement.add(this._tempVec),this._lastDragPosRigSpace.copy(t),no){let s=t;i&&(s=s.clone(),s.transformDirection(i.matrixWorld)),B.DrawRay(s,n,255)}}onDragUpdate(e){if(e>1)return;const t=this.gameObject;if(!t||!this._followObject){console.warn("Warning: DragPointerHandler doesn't have a dragged object. This is likely a bug.");return}const i=this._followObject.parent;if(!i){console.warn("Warning: DragPointerHandler doesn't have a drag source. This is likely a bug.");return}this._followObject.updateMatrix();const n=i.worldPosition,s=i.worldForward,r=this._deviceMode==="tracked-pointer"||this._deviceMode==="transient-pointer",a=r?this.settings.xrKeepRotation:this.settings.keepRotation,l=r?this.settings.xrDragMode:this.settings.dragMode;if(l===5)return;const c=10;a&&(this._followObject.worldQuaternion=this._followObjectStartWorldQuaternion),this._followObject.updateMatrix(),this._followObject.updateMatrixWorld(!0);let h=1,d=2;if(r&&this._grabStartDistance>.5){const v=1+this._totalMovementAlongRayDirection*(2*this.settings.xrDistanceDragFactor);h=Math.max(0,v),h=h*h*h}else this._grabStartDistance<=.5&&(d=3);this._followObject.position.copy(this._followObjectStartPosition),a||this._followObject.quaternion.copy(this._followObjectStartQuaternion),this._followObject.position.multiplyScalar(h),this._followObject.updateMatrix();const p=this._hasLastSurfaceHitPoint;this._hasLastSurfaceHitPoint=!1;const m=new xo(n,s);if(l==4){const v=this.context.physics.raycastFromRay(m,{testObject:P=>P!==this.followObject&&P!==i&&P!==t});if(v.length>0){const P=v[0];if(this._draggedOverObject===P.object?this._draggedOverObjectDuration+=this.context.time.deltaTime:(this._draggedOverObject=P.object,this._draggedOverObjectDuration=0),P.face){this._hasLastSurfaceHitPoint=!0,this._lastSurfaceHitPoint.copy(P.point);const k=this._draggedOverObjectDuration>=.15,O=this._totalMovement.length()>=.001,D=F(P.normal||P.face.normal).applyQuaternion(P.object.worldQuaternion);if((k||O)&&(this._draggedOverObjectLastSetUp!==this._draggedOverObject||this._draggedOverObjectLastNormal.dot(D)<.999999||this.context.time.frame%60===0)){this._draggedOverObjectLastSetUp=this._draggedOverObject,this._draggedOverObjectLastNormal.copy(P.face.normal);const L=F(),V=F();this._bounds.getCenter(L),this._bounds.getSize(V),L.sub(V.multiplyScalar(.5).multiply(D)),this._hitPointInLocalSpace.copy(L),this._hitNormalInLocalSpace.copy(P.face.normal),this._bounds.getCenter(L),this._bounds.getSize(V),L.add(V.multiplyScalar(.5).multiply(P.face.normal));const W=F(this._hitPointInLocalSpace).add(L);this._followObject.localToWorld(W);const G=P.point;this._dragPlane.setFromNormalAndCoplanarPoint(D,G)}else if(!(k||O))return}}else p&&this.gameObject&&this.setPlaneViewAligned(this.gameObject.worldPosition,!1)}if(l!==1&&m.intersectPlane(this._dragPlane,this._tempVec)){this._followObject.worldPosition=this._tempVec,this._followObject.updateMatrix(),this._followObject.updateMatrixWorld(!0);const v=F(this._hitPointInLocalSpace);this._followObject.localToWorld(v),no&&B.DrawLine(v,this._tempVec,65535,0,!1),this._followObject.worldPosition=this._tempVec.multiplyScalar(2).sub(v),this._followObject.updateMatrix(),this._followObject.updateMatrix()}if(this.settings.snapGridResolution>0){const v=this._followObject.worldPosition,P=this.settings.snapGridResolution;v.x=Math.round(v.x/P)*P,v.y=Math.round(v.y/P)*P,v.z=Math.round(v.z/P)*P,this._followObject.worldPosition=v,this._followObject.updateMatrix()}a&&(this._followObject.worldQuaternion=this._followObjectStartWorldQuaternion,this._followObject.updateMatrix());const g=j.clamp01(this.context.time.deltaTime*c*d),f=j.clamp01(this.context.time.deltaTime*c*.5*d),y=t.worldPosition;y.lerp(this._followObject.worldPosition,g),t.worldPosition=y;const _=t.worldQuaternion;if(_.slerp(this._followObject.worldQuaternion,f),t.worldQuaternion=_,t.matrixAutoUpdate===!1&&t.updateMatrix(),no){const v=this._hitPointInLocalSpace.clone();t.localToWorld(v),B.DrawSphere(v,.02,16711680);const P=this._hitNormalInLocalSpace.clone();P.applyQuaternion(_),B.DrawRay(v,P,16711680),B.DrawLabel(y.add(new b(0,.25,0)),`Distance: ${this._totalMovement.length().toFixed(2)}
985
985
 
@@ -1286,7 +1286,7 @@ ${r.join(`
1286
1286
  `)}`:""}
1287
1287
  }`}function u1(o){return`(${o.r}, ${o.g}, ${o.b})`}function p1(o){return`(${o.x}, ${o.y})`}const ky=[1023,33777,33778,33779,35842,35843,37496,37808,37809,37810,37811,37812,37813,37814,37815,37816,37817,37818,37819,37820,37821,36492];w("debugusdz");class jt{static global_id=0;id;trigger;action;exclusive=!1;makeExclusive(e){return this.exclusive=e,this}constructor(e,t,i){this.id="Behavior_"+ji(e)+"_"+jt.global_id++,this.trigger=t,this.action=i}writeTo(e,t,i){if(!this.trigger||!this.action)return;i.beginBlock(`def Preliminary_Behavior "${this.id}"`);let n="";if(Array.isArray(this.trigger)){n="[";for(let s=0;s<this.trigger.length;s++){const r=this.trigger[s];n+="<"+r.id+">",s+1<this.trigger.length&&(n+=", ")}n+="]"}else n=`<${this.trigger.id}>`;if(i.appendLine(`rel triggers = ${n}`),i.appendLine(`rel actions = <${this.action.id}>`),i.appendLine(`uniform bool exclusive = ${this.exclusive?1:0}`),i.appendLine(),Array.isArray(this.trigger))for(const s of this.trigger)s.writeTo(t,i),i.appendLine();else this.trigger.writeTo(t,i);i.appendLine(),this.action.writeTo(t,i),i.closeBlock()}}const Pl=new Set;function My(o,e){let t="";if(Array.isArray(o)){Pl.clear();let i="[ ";for(let n=0;n<o.length;n++){let s=o[n];if(!s){console.warn("Invalid target object in behavior",o+". Is the object exported?");continue}if(typeof s=="string"){if(Pl.has(s))continue;i+=s,Pl.add(s)}else if(typeof s=="object"){if(s.isObject3D&&(s=e.findById(s.uuid),!s)){console.warn("Invalid target object in behavior",o+". Is the object exported?");continue}const r=s.getPath?.call(s);if(Pl.has(r))continue;i+=r,Pl.add(r)}n+1<o.length&&(i+=", ")}i+=" ]",t=i,Pl.clear()}else if(typeof o=="object"){const i=o;if(i.isObject3D&&(o=e.findById(i.uuid)),!o)throw console.error("Invalid target object in behavior, the target object is likely missing from USDZ export. Is the object exported?",i),new Error(`Invalid target object in behavior, the target object is likely missing from USDZ export. Please report a bug. uuid: ${i.uuid}.`);t=o.getPath?.call(o)}return t}class dr{static global_id=0;id;targetId;tokenId;type;distance;constructor(e,t){e&&(this.targetId=e),t?this.id=t:this.id="Trigger_"+dr.global_id++}writeTo(e,t){t.beginBlock(`def Preliminary_Trigger "${this.id}"`),this.targetId&&(typeof this.targetId!="string"&&(this.targetId=My(this.targetId,e)),t.appendLine("rel affectedObjects = "+this.targetId)),this.tokenId&&t.appendLine(`token info:id = "${this.tokenId}"`),this.type&&t.appendLine(`token type = "${this.type}"`),typeof this.distance=="number"&&t.appendLine(`double distance = ${this.distance}`),t.closeBlock()}}function m1(o,e={direct:!0,indirect:!0}){const t=rt.createEmpty();t.name="InputTarget_"+t.name,t.displayName=void 0,t.type="RealityKitComponent",t.onSerialize=i=>{i.appendLine("bool allowsDirectInput = "+(e.direct?1:0)),i.appendLine("bool allowsIndirectInput = "+(e.indirect?1:0)),i.appendLine('uniform token info:id = "RealityKit.InputTarget"')},o.add(t)}class $t{static __sceneStartTrigger;static sceneStartTrigger(){if(this.__sceneStartTrigger!==void 0)return this.__sceneStartTrigger;const e=new dr(void 0,"SceneStart");return e.tokenId="SceneTransition",e.type="enter",this.__sceneStartTrigger=e,e}static tapTrigger(e,t={direct:!0,indirect:!0}){const i=new dr(e);if(Array.isArray(e)&&e.length>1)for(const n of e)n instanceof rt&&m1(n,t);else e instanceof rt&&m1(e,t);return i.tokenId="TapGesture",i}static isTapTrigger(e){return e?.tokenId==="TapGesture"}static proximityToCameraTrigger(e,t){const i=new dr(e);return i.tokenId="ProximityToCamera",i.distance=t,i}}class Jr{static global_id=0;static getId(){return this.global_id++}id;actions;loops=0;performCount=1;type="serial";multiplePerformOperation=void 0;constructor(e,t){this.id=e,this.actions=t}addAction(e){return this.actions.push(e),this}makeParallel(){return this.type="parallel",this}makeSequence(){return this.type="serial",this}makeLooping(){return this.loops=1,this.performCount=0,this}makeRepeat(e){return this.performCount=e,this}writeTo(e,t){t.beginBlock(`def Preliminary_Action "${this.id}"`),t.beginArray("rel actions");for(const i of this.actions){if(!i)continue;const n=i===this.actions[this.actions.length-1];t.appendLine("<"+i.id+">"+(n?"":", "))}t.closeArray(),t.appendLine(),t.appendLine('token info:id = "Group"'),t.appendLine(`bool loops = ${this.loops}`),t.appendLine(`int performCount = ${this.loops>0?0:Math.max(0,this.performCount)}`),t.appendLine(`token type = "${this.type}"`),typeof this.multiplePerformOperation=="string"&&t.appendLine(`token multiplePerformOperation = "${this.multiplePerformOperation}"`),t.appendLine();for(const i of this.actions)i&&(i.writeTo(e,t),t.appendLine());t.closeBlock()}}class xi{static global_id=0;id;tokenId;affectedObjects;easeType;motionType=void 0;duration;moveDistance;style;type;front;up;start;animationSpeed;reversed;pingPong;xFormTarget;audio;gain;auralMode;multiplePerformOperation;velocity;comment;animationName;clone(){const e=new xi,t=e.id;return Object.assign(e,this),e.id=t,e}constructor(e,t){e&&(this.affectedObjects=e),t?this.id=t:this.id="Action",this.id+="_"+xi.global_id++}writeTo(e,t){t.beginBlock(`def Preliminary_Action "${this.id}"`),this.comment&&t.appendLine(`# ${this.comment}`),this.affectedObjects&&(typeof this.affectedObjects!="string"&&(this.affectedObjects=My(this.affectedObjects,e)),t.appendLine("rel affectedObjects = "+this.affectedObjects)),typeof this.duration=="number"&&(typeof this.animationSpeed=="number"&&this.animationSpeed!==1?t.appendLine(`double duration = ${this.duration/this.animationSpeed} `):t.appendLine(`double duration = ${this.duration} `)),this.easeType&&t.appendLine(`token easeType = "${this.easeType}"`),this.tokenId&&t.appendLine(`token info:id = "${this.tokenId}"`),this.tokenId==="ChangeScene"&&t.appendLine("rel scene = </StageRoot/Scenes/Scene>"),this.motionType!==void 0&&t.appendLine(`token motionType = "${this.motionType}"`),typeof this.moveDistance=="number"&&t.appendLine(`double moveDistance = ${this.moveDistance} `),this.style&&t.appendLine(`token style = "${this.style}"`),this.type&&t.appendLine(`token type = "${this.type}"`),this.front&&t.appendLine(`vector3d front = (${this.front.x}, ${this.front.y}, ${this.front.z})`),this.up&&t.appendLine(`vector3d upVector = (${this.up.x}, ${this.up.y}, ${this.up.z})`),typeof this.start=="number"&&t.appendLine(`double start = ${this.start} `),typeof this.animationSpeed=="number"&&t.appendLine(`double animationSpeed = ${this.animationSpeed.toFixed(2)} `),typeof this.reversed=="boolean"&&t.appendLine(`bool reversed = ${this.reversed}`),typeof this.pingPong=="boolean"&&t.appendLine(`bool reverses = ${this.pingPong}`),this.xFormTarget&&(typeof this.xFormTarget!="string"&&(this.xFormTarget=My(this.xFormTarget,e)),t.appendLine(`rel xformTarget = ${this.xFormTarget}`)),typeof this.audio=="string"&&t.appendLine(`asset audio = @${this.audio}@`),typeof this.gain=="number"&&t.appendLine(`double gain = ${this.gain}`),typeof this.auralMode=="string"&&t.appendLine(`token auralMode = "${this.auralMode}"`),typeof this.multiplePerformOperation=="string"&&t.appendLine(`token multiplePerformOperation = "${this.multiplePerformOperation}"`),typeof this.velocity=="object"&&t.appendLine(`vector3d velocity = (${this.velocity.x}, ${this.velocity.y}, ${this.velocity.z})`),t.closeBlock()}}class bn{x=0;y=0;z=0;constructor(e,t,i){this.x=e,this.y=t,this.z=i}static get up(){return new bn(0,1,0)}static get right(){return new bn(1,0,0)}static get forward(){return new bn(0,0,1)}static get back(){return new bn(0,0,-1)}static get zero(){return new bn(0,0,0)}}class fe{static sequence(...e){return new Jr("Group_"+Jr.getId(),e).makeSequence()}static parallel(...e){return new Jr("Group_"+Jr.getId(),e).makeParallel()}static fadeAction(e,t,i){const n=new xi(e);return n.tokenId="Visibility",n.type=i?"show":"hide",n.duration=t,n.style="basic",n.motionType="none",n.moveDistance=0,n.easeType="none",n}static startAnimationAction(e,t,i=!1,n=!1){const s=new xi(e);s.tokenId="StartAnimation";const r=t.start,a=t.duration,l=t.speed,c=t.clipName;if(s.comment=`Animation: ${c}, start=${r*60}, length=${a*60}, end=${(r+a)*60}`,s.animationName=c,s.start=r,s.duration=a,s.animationSpeed=l,s.reversed=i,s.pingPong=n,s.multiplePerformOperation="allow",i&&(s.start-=a),n){s.pingPong=!1;const h=s.clone();return h.reversed=!i,h.start=s.start,h.reversed&&(h.start-=a),fe.sequence(s,h)}return s}static waitAction(e){const t=new xi;return t.tokenId="Wait",t.duration=e,t.motionType=void 0,t}static lookAtCameraAction(e,t,i,n){const s=new xi(e);return s.tokenId="LookAtCamera",s.duration=t===void 0?9999999999999:t,s.front=i??bn.forward,s.up=n??bn.up,s}static emphasize(e,t,i="bounce",n=1,s="basic"){const r=new xi(e);return r.tokenId="Emphasize",r.duration=t,r.style=s??"basic",r.motionType=i,r.moveDistance=n,r}static transformAction(e,t,i,n,s="inout"){const r=new xi(e);return r.tokenId="Transform",r.duration=i,r.duration=Math.max(1e-6,i),r.type=n,r.easeType=i>0?s:"none",Array.isArray(t)&&console.error("Transform target must not be an array",t),r.xFormTarget=t,r}static playAudioAction(e,t,i="play",n=1,s="spatial"){const r=new xi(e);return r.tokenId="Audio",r.type=i,r.audio=t,r.gain=n,r.auralMode=s,r.multiplePerformOperation="allow",r}static impulseAction(e,t){const i=new xi(e);return i.tokenId="Impulse",i.velocity=t,i}}class eA{get id(){return this.object.uuid}object;model;constructor(e){this.object=e}apply(e){if(!this.model&&(this.model=e.findById(this.object.uuid),!this.model)){console.error("could not find model with id "+this.object.uuid);return}this.onApply(e)}}class Ey extends eA{constructor(e,t,i,n){super(e),this.matrix=t,this.material=i,this.geometry=n}matrix;material;geometry;onApply(e){const t=this.model;if(!t)return;t.parent?.isDynamic||rt.createEmptyParent(t);const i=t.clone();this.matrix&&i.setMatrix(this.matrix),this.material&&(i.material=this.material),this.geometry&&(i.geometry=this.geometry),t.parent?.add(i)}_enableAction;_disableAction;enable(){return this._enableAction?this._enableAction:(this._enableAction=fe.fadeAction(this.object,0,!0),this._enableAction)}disable(){return this._disableAction?this._disableAction:(this._disableAction=fe.fadeAction(this.object,0,!1),this._disableAction)}}class g1{actions;sortedActions;constructor(e){this.actions=[...e]}organize(){this.sortedActions={};for(const e of this.actions){const t=e.id;this.sortedActions[t]||(this.sortedActions[t]=[]),this.sortedActions[t].push(e)}}getActions(e){return this.sortedActions||this.organize(),this.sortedActions[e.uuid]}}const ao=w("debugusdzanimation"),Ry=w("debugusdzanimationserialization");class fr{_start;get start(){return this._start===void 0&&(this._start=this.ext.getStartTimeByClip(this.clip)),this._start}get duration(){return this.clip?.duration??Ne.restPoseClipDuration}get nearestAnimatedRoot(){return this._nearestAnimatedRoot}get clipName(){return this.clip?.name??"rest"}ext;root;_nearestAnimatedRoot=void 0;clip;speed;constructor(e,t,i){this.ext=e,this.root=t,this.clip=i,this._nearestAnimatedRoot=this.getNearestAnimatedRoot()}static isDescendantOf(e,t){let i=t;if(!i||!e)return!1;for(;i;){if(!i)return!1;if(i===e)return!0;i=i.parent}return!1}getNearestAnimatedRoot(){let e;try{for(const t of this.clip?.tracks??[]){const i=La.parseTrackName(t.name);let n=La.findNode(this.root,i.nodeName);if(n)if(!e)e=n;else{if(n===e||fr.isDescendantOf(e,n))continue;if(!fr.isDescendantOf(n,e)){for(;!fr.isDescendantOf(n,e)&&n.parent;)n=n.parent;fr.isDescendantOf(n,e)||console.error("USDZExporter: Animation clip targets multiple roots that are not parent/child. Please report a bug",this.root,this.clip,e,n)}e=n}}}catch(t){console.error("USDZExporter: Exception when trying to find nearest animated root. Please report a bug",t),e=void 0}return e}}class Ne{clip;pos;rot;scale;root;target;duration=0;useRootMotion=!1;static frameRate=60;static animationDurationPadding=6/60;static restPoseClipDuration=6/60;constructor(e,t,i){if(this.root=e,this.target=t,this.clip=i,i?this.duration=i.duration:this.duration=Ne.restPoseClipDuration,i&&i.tracks){const s=Math.max(...i.tracks.map(r=>r.times[r.times.length-1]));s!==this.duration&&(console.warn("USDZExporter: Animation clip duration does not match the maximum time value in the tracks.",i,s,this.duration),this.duration=s)}const n=S.getComponent(e,_t);n&&(this.useRootMotion=n.applyRootMotion)}addTrack(e){if(!this.clip){console.error("This is a rest clip but you're trying to add tracks to it \u2013 this is likely a bug");return}e.name.endsWith("position")?this.pos=e:e.name.endsWith("quaternion")?this.rot=e:e.name.endsWith("scale")?this.scale=e:(e.name.endsWith("activeSelf")?console.warn("[USDZ] Animation of enabled/disabled state is not supported for USDZ export and will NOT be exported: "+e.name+" on "+(this.root?.name??this.target.name)+". Animate scale 0/1 instead."):console.warn("[USDZ] Animation track type not supported for USDZ export and will NOT be exported: "+e.name+" on "+(this.root?.name??this.target.name)+". Only .position, .rotation, .scale are supported."),A()&&be("[USDZ] Some animations can't be exported. See console for details."))}getFrames(){return this.clip?Math.max(this.pos?.times?.length??0,this.rot?.times?.length??0,this.scale?.times?.length??0):2}getDuration(){return this.duration}getSortedTimesArray(e=!0,t=!0,i=!0){if(!this.clip)return[0,this.duration];const n=this.pos?.times,s=this.rot?.times,r=this.scale?.times,a=[];if(e&&n)for(const l of n)a.push(l);if(t&&s)for(const l of s)a.push(l);if(i&&r)for(const l of r)a.push(l);return a.includes(0)||a.push(0),a.sort((l,c)=>l-c),[...new Set(a)]}*getValues(e,t=!0,i=!0,n=!0){const s=new b,r=new N,a=new b(1,1,1),l=this.target,c=t?this.pos?.createInterpolant():void 0,h=i?this.rot?.createInterpolant():void 0,d=n?this.scale?.createInterpolant():void 0;c||s.set(l.position.x,l.position.y,l.position.z),h||r.set(l.quaternion.x,l.quaternion.y,l.quaternion.z,l.quaternion.w),d||a.set(l.scale.x,l.scale.y,l.scale.z),c&&c.valueSize!==3&&(c.valueSize=3),h&&h.valueSize!==4&&(h.valueSize=4),d&&d.valueSize!==3&&(d.valueSize=3);const p=0;for(let m=0-p;m<e.length+p;m++){let g=0,f=0;if(m<0?(g=e[0],f=g-Ne.animationDurationPadding/2+1/60):m>=e.length?(g=e[e.length-1],f=g+Ne.animationDurationPadding/2-1/60):(g=e[m],f=g),c){const y=c.evaluate(g);s.set(y[0],y[1],y[2])}if(h){const y=h.evaluate(g);r.set(y[0],y[1],y[2],y[3])}if(d){const y=d.evaluate(g);a.set(y[0],y[1],y[2])}if(this.useRootMotion&&l===this.root){const y=new J;y.compose(s,r,a),y.multiply(l.matrix),y.decompose(s,r,a)}yield{time:f,translation:s,rotation:r,scale:a,index:m}}}}class yp{get extensionName(){return"animation"}get animationData(){return this.dict}get registeredClips(){return this.clipToStartTime.keys()}get animatedRoots(){return this.rootTargetMap.keys()}get holdClipMap(){return this.clipToHoldClip}dict=new Map;rootTargetMap=new Map;rootAndClipToRegisteredAnimationMap=new Map;rootToRegisteredClip=new Map;lastClipEndTime=0;clipToStartTime=new Map;clipToHoldClip=new Map;serializers=[];injectRestPoses=!1;injectImplicitBehaviours=!1;constructor(e){this.injectRestPoses=e,this.injectImplicitBehaviours=e}getStartTimeCode(){return!this.injectRestPoses||this.rootAndClipToRegisteredAnimationMap.size===0?0:(Ne.restPoseClipDuration+Ne.animationDurationPadding)*60}getEndTimeCode(){let e=0;for(const[t,i]of this.rootAndClipToRegisteredAnimationMap){const n=i.start+i.duration;n>e&&(e=n)}return e*60}getClipCount(e){return this.rootToRegisteredClip.get(e)?.length??0??0}getStartTimeByClip(e){return e?this.clipToStartTime.has(e)?this.clipToStartTime.get(e):(console.error("USDZExporter: Missing start time for clip \u2013 please report a bug.",e),0):0}registerAnimation(e,t){if(!e)return null;this.rootTargetMap.has(e)||this.rootTargetMap.set(e,[]);const i=e.uuid+(t?.uuid??"-rest");if(this.rootAndClipToRegisteredAnimationMap.has(i))return this.rootAndClipToRegisteredAnimationMap.get(i);ao&&console.log("registerAnimation",e,t);const n=this.injectRestPoses?1:0,s=(this.rootToRegisteredClip.get(e)?.length??0)+n,r=this.rootTargetMap.get(e),a=new Set(r);if(t&&t.tracks)for(const c of t.tracks){const h=La.parseTrackName(c.name),d=La.findNode(e,h.nodeName);if(!d){console.warn("no object found for track",c.name,"using "+e.name+" instead");continue}this.dict.has(d)||this.dict.set(d,[]);const p=this.dict.get(d);if(!p){console.warn("no transform data found for target ",d,"at slot "+s+", this is likely a bug");continue}a.delete(d),this.injectRestPoses&&!p[0]&&(console.log("Injecting rest pose",d,t,"at slot",s),p[0]=new Ne(null,d,null));let m=p[s];m||(m=new Ne(e,d,t),p[s]=m),m.addTrack(c),r?.includes(d)||r?.push(d)}ao&&console.log("Unregistered nodes for this clip",a,"clip",t,"at slot",s,"for root",e,"targets",r);for(const c of a){const h=this.dict.get(c);if(!h)continue;if(this.injectRestPoses&&!h[0]){console.warn("Adding rest pose for ",c,t,"at slot",s,"This is likely a bug, should have been added earlier.");const p=new Ne(null,c,null);h[0]=p}let d=h[s];d||(ao&&console.log("Adding padding clip for ",c,t,"at slot",s),d=new Ne(e,c,t),h[s]=d)}const l=new fr(this,e,t);if(this.rootAndClipToRegisteredAnimationMap.set(i,l),ao&&console.log({root:e,clip:t,info:l}),t){const c=this.rootToRegisteredClip.get(e);if(c?c.push(t):this.rootToRegisteredClip.set(e,[t]),!this.clipToStartTime.get(t)){this.lastClipEndTime==null&&(this.lastClipEndTime=Ne.restPoseClipDuration);let h=this.lastClipEndTime+Ne.animationDurationPadding,d=h+t.duration;const p=Math.round(h*60)/60,m=Math.round(d*60)/60;Math.abs(p-h)<.01&&(h=p),Math.abs(m-d)<.01&&(d=m),h=Math.ceil(h),d=h+t.duration,this.clipToStartTime.set(t,h),this.lastClipEndTime=d}}return l}onAfterHierarchy(e){ao&&console.log("Animation clips per animation target node",this.dict)}onAfterBuildDocument(e){ao&&console.log("Animation data",{dict:this.dict,rootTargetMap:this.rootTargetMap,rootToRegisteredClip:this.rootToRegisteredClip});for(const t of this.rootTargetMap.keys()){const i=this.rootTargetMap.get(t);if(!i)continue;let n;const s=[];for(const r of i){const a=this.dict.get(r);if(!a){console.error("No data found for target on USDZ export \u2013 please report a bug!",r);continue}n===void 0&&(n=a?.length),n!==a?.length&&console.error("Different array lengths for targets \u2013 please report a bug!",a);for(let l=0;l<a.length;l++){let c=a[l];if(!c){const d=l-(this.injectRestPoses?1:0);a[l]=new Ne(null,r,this.rootToRegisteredClip.get(t)[d]),c=a[l]}const h=c.getDuration();if(s[l]===void 0)s[l]=h;else if(s[l]!==h){console.error("Error during UDSZ export: Encountered different animation durations for animated targets. Please report a bug!",{datas:a,target:r}),s[l]=h;continue}}}}for(const t of this.serializers){const i=t.model?.parent,n=i?.isDynamic===!0;Ry&&console.log(n,t.model?.parent),n&&t.registerCallback(i)}}onExportObject(e,t,i){S.foreachComponent(e,s=>{const r=s;typeof r.createAnimation=="function"&&r.createAnimation(this,t,i)},!1);const n=new tA(e,this);this.serializers.push(n),n.registerCallback(t)}}class tA{model=void 0;object;animationData;ext;callback;constructor(e,t){this.object=e,this.animationData=t.animationData,this.ext=t}registerCallback(e){this.model&&this.callback&&this.model.removeEventListener("serialize",this.callback),this.callback||(this.callback=this.onSerialize.bind(this)),Ry&&console.log("REPARENT",e),this.model=e,this.callback&&this.model.addEventListener("serialize",this.callback)}skinnedMeshExport(e,t,i){const n=this.model,s=this.animationData;if(n&&n.skinnedMesh){let r=function(R){const $=[];for(const[q,he]of R){let re=`${q} : [`;const me=[];for(const te of he)me.push(`(${ce(te.x)}, ${ce(te.y)}, ${ce(te.z)})`);re=re.concat(me.join(", ")),re=re.concat("],"),$.push(re)}return $},a=function(R){const $=[];for(const[q,he]of R){let re=`${q} : [`;const me=[];for(const te of he)me.push(`(${ce(te.w)}, ${ce(te.x)}, ${ce(te.y)}, ${ce(te.z)})`);re=re.concat(me.join(", ")),re=re.concat("],"),$.push(re)}return $},l=function(R){let $,q=!0;const he=new Map;for(const[me,te]of R){$===void 0&&($=te.length),$!==te.length&&(q=!1);let We=0;for(const li of te)We++,li||(he.has(me)||he.set(me,[]),he.get(me).push(We))}ao&&console.log("Bone count: ",R.size,"TransformData entries per bone: ",$,"Undefined bone entries: ",he),console.assert(q,"All bones should have the same number of TransformData entries",R),console.assert(he.size===0,"All TransformData entries should be set",he);const re=[];for(const[me,te]of R)for(let We=0;We<te.length;We++){const li=te[We],Sd=i.getStartTimeByClip(li.clip);re.length<=We&&re.push({pos:[],rot:[],scale:[],timeOffset:Sd});const ys=re[We];ys.pos.push(...li.getSortedTimesArray(!0,!1,!1)),ys.rot.push(...li.getSortedTimesArray(!1,!0,!1)),ys.scale.push(...li.getSortedTimesArray(!1,!1,!0))}for(const me of re)me.pos.sort((te,We)=>te-We),me.rot.sort((te,We)=>te-We),me.scale.sort((te,We)=>te-We),me.pos=[...new Set(me.pos)],me.rot=[...new Set(me.rot)],me.scale=[...new Set(me.scale)];return re},c=function(R,$,q){const he=new Map,re=new Map,me=new Map,te=$.length;for(const We of q){const li=R.get(We);let Sd;li?console.assert(li.length===te,"We should have the same number of TransformData entries for each bone",li,$):Sd=new Ne(null,We,null);for(let ys=0;ys<te;ys++){const Cm=li?li[ys]:Sd,Ta=$[ys];for(const{time:cc,translation:hc}of Cm.getValues(Ta.pos,!0,!1,!1)){const _n=(cc+Ta.timeOffset)*60;he.has(_n)||he.set(_n,new Array),he.get(_n).push(hc.clone())}for(const{time:cc,rotation:hc}of Cm.getValues(Ta.rot,!1,!0,!1)){const _n=(cc+Ta.timeOffset)*60;re.has(_n)||re.set(_n,new Array),re.get(_n).push(hc.clone())}for(const{time:cc,scale:hc}of Cm.getValues(Ta.scale,!1,!1,!0)){const _n=(cc+Ta.timeOffset)*60;me.has(_n)||me.set(_n,new Array),me.get(_n).push(hc.clone())}}}return{position:he.size==0?void 0:he,quaternion:re.size==0?void 0:re,scale:me.size==0?void 0:me}},h=function(R){const $=[];for(const q of R)$.push(`(${ce(q.x)}, ${ce(q.y)}, ${ce(q.z)})`);return $.join(", ")},d=function(R){const $=[];for(const q of R)$.push(`(${ce(q.w)}, ${ce(q.x)}, ${ce(q.y)}, ${ce(q.z)})`);return $.join(", ")},p=function(R){const $=new Map;if(ao){const q=new Array;for(const[he,re]of s)q.push(he.uuid+": "+re.length+" "+re.map(me=>me.clip?.uuid.substring(0,6)).join(" "));console.log(`getPerBoneTransformData
1288
1288
  `+q.join(`
1289
- `))}for(const q of R){const he=s.get(q);he&&$.set(q,he)}return $},m=function(R){const $=p(R),q=l($);return c($,q,R)};const g=n.skinnedMesh.skeleton,f=new Array,y=[],_=[];for(const R of g.bones){y.push(R),_.push(R.uuid);const $=g.boneInverses[g.bones.indexOf(R)];f.push({bone:R,inverse:$})}let v=1e4;for(;_.length<g.bones.length&&v-- >0;)for(const R of y){const $=R.children;for(const q of $)if(_.indexOf(q.uuid)===-1&&g.bones.indexOf(q)!==-1){y.push(q),_.push(q.uuid);const he=g.boneInverses[g.bones.indexOf(q)];f.push({bone:q,inverse:he})}}v<=0&&console.error("Failed to sort bones in skinned mesh",n.skinnedMesh,g.bones,_);for(const R of Zx(g.bones))f.push({bone:R,inverse:R.matrixWorld.clone().invert()});const P=f[0].bone.parent;P||console.error("No bone parent found for skinned mesh during USDZ export",n.skinnedMesh),f.sort((R,$)=>Cl(R.bone,P)>Cl($.bone,P)?1:-1);const k=t.quickLookCompatible,O=[],D=[],L=[],V=[];for(const{bone:R}of f){if(k){const $=R.scale;$.x==0&&($.x=1e-5),$.y==0&&($.y=1e-5),$.z==0&&($.z=1e-5),O.push(new J().compose(R.position,R.quaternion,R.scale))}else O.push(R.matrix.clone());D.push(R.position),L.push(R.quaternion),V.push(R.scale)}const W=f.map(R=>'"'+Cl(R.bone,P)+'"').join(", "),G=f.map(R=>c1(R.inverse.clone().invert())).join(", ");e.beginBlock('def Skeleton "Rig"'),e.appendLine(`uniform matrix4d[] bindTransforms = [${G}]`),e.appendLine(`uniform token[] joints = [${W}]`),e.appendLine('uniform token purpose = "guide"'),e.appendLine(`uniform matrix4d[] restTransforms = [${O.map(R=>c1(R)).join(", ")}]`);const X=m(f.map(R=>R.bone));if(ao){let R=1e7,$=0;for(const q of X.position?.keys()??[])R=Math.min(R,q),$=Math.max($,q);console.log("Time samples",R,$,X)}if(e.beginBlock('def SkelAnimation "_anim"'),e.appendLine(`uniform token[] joints = [${W}]`),e.appendLine(`quatf[] rotations = [${d(L)}]`),X&&X.quaternion){e.beginBlock("quatf[] rotations.timeSamples = {","");const R=a(X.quaternion);for(const $ of R)e.appendLine($);e.closeBlock()}if(e.appendLine(`half3[] scales = [${h(V)}]`),X&&X.scale){e.beginBlock("half3[] scales.timeSamples = {","");const R=r(X.scale);for(const $ of R)e.appendLine($);e.closeBlock()}if(e.appendLine(`float3[] translations = [${h(D)}]`),X&&X.position){e.beginBlock("float3[] translations.timeSamples = {","");const R=r(X.position);for(const $ of R)e.appendLine($);e.closeBlock()}e.closeBlock(),e.closeBlock()}}onSerialize(e,t){if(!this.model)return;const i=this.animationData.get(this.object);if(i)for(let h=0;h<i.length;h++)i[h]===void 0&&(i[h]=new Ne(null,this.object,null));const n=this.ext;this.skinnedMeshExport(e,t,n);const s=this.object,r=this.model,a=this.animationData.get(s);if(!a||s.isSkinnedMesh)return;Ry&&console.log("SERIALIZE",this.model.name,this.object.type,a);const l=Intl.NumberFormat("en-US",{maximumFractionDigits:3,minimumFractionDigits:0,useGrouping:!1});function c(h,d){if(h.some(p=>p&&{position:p.pos,rotation:p.rot,scale:p.scale}[d])){switch(d){case"position":r.needsTranslate=!0,e.beginBlock("double3 xformOp:translate.timeSamples = {","");break;case"rotation":r.needsOrient=!0,e.beginBlock("quatf xformOp:orient.timeSamples = {","");break;case"scale":r.needsScale=!0,e.beginBlock("double3 xformOp:scale.timeSamples = {","");break}for(let p=0;p<h.length;p++){const m=h[p];if(!m)continue;const g=n.getStartTimeByClip(m.clip),f=m.getSortedTimesArray(d==="position",d==="rotation",d==="scale");if(!f||f.length===0){console.error("got an animated object but no time values?",s,m);continue}const y=!m.clip,_=d==="position"&&(m.pos||y),v=d==="rotation"&&(m.rot||y),P=d==="scale"&&(m.scale||y);if(_||v||P){const k=m.clip?.name??"rest",O=m.getDuration();ao&&console.log("Write .timeSamples:",k,g,O,h),e.appendLine("# "+k+": start="+l.format(g*Ne.frameRate)+", length="+l.format(O*Ne.frameRate)+", frames="+m.getFrames())}if(_)for(const{time:k,translation:O}of m.getValues(f,!0,!1,!1)){const D=`${l.format((g+k)*Ne.frameRate)}: (${ce(O.x)}, ${ce(O.y)}, ${ce(O.z)}),`;e.appendLine(D)}if(v)for(const{time:k,rotation:O}of m.getValues(f,!1,!0,!1)){const D=`${l.format((g+k)*Ne.frameRate)}: (${ce(O.w)}, ${ce(O.x)}, ${ce(O.y)}, ${ce(O.z)}),`;e.appendLine(D)}if(P)for(const{time:k,scale:O}of m.getValues(f,!1,!1,!0)){const D=`${l.format((g+k)*Ne.frameRate)}: (${ce(O.x)}, ${ce(O.y)}, ${ce(O.z)}),`;e.appendLine(D)}}e.closeBlock()}}c(a,"position"),c(a,"rotation"),c(a,"scale")}}const iA=w("debugusdz");class Pa{static getName(e){const t=e.split(".").pop();let i=e.split(".").slice(0,-1).join(".").split("/").pop()?.replace(".","_");return i||(i="Audio_"+Math.random().toString(36).substring(2,15)),ji(i)+"."+t}get extensionName(){return"Audio"}files=new Array;onExportObject(e,t,i){const n=S.getComponents(e,Di);if(n.length)for(const s of n){if(!s.clip||typeof s.clip!="string"||!s.playOnAwake)continue;const r=s.clip.split("/").pop()||"Audio",a=Pa.getName(s.clip),l=ji(a);if(!this.files.some(c=>c.path===s.clip)){this.files.push({path:s.clip,name:a});const c=a.toLowerCase();i.quickLookCompatible&&!c.endsWith(".mp3")&&!c.endsWith(".wav")&&!c.endsWith(".m4a")&&console.error("Audio file "+s.clip+" from "+s.name+" is not an MP3 or WAV file. QuickLook may not support playing it.")}i.quickLookCompatible||t.addEventListener("serialize",(c,h)=>{c.appendLine(),c.beginBlock(`def SpatialAudio "${l}"`,"(",!1),c.appendLine(`displayName = "${r}"`),c.closeBlock(")"),c.beginBlock(),c.appendLine(`uniform asset filePath = @audio/${a}@`),c.appendLine(`uniform token auralMode = "${s.spatialBlend>0?"spatial":"nonSpatial"}"`),c.appendLine(`uniform token playbackMode = "${s.loop?"loopFromStage":"onceFromStart"}"`),c.appendLine(`uniform float gain = ${s.volume}`),c.closeBlock()})}}async onAfterSerialize(e){for(const t of this.files){const i="audio/"+t.name;if(e.files[i]){iA&&console.warn("Audio file with name "+i+" already exists in the context. Skipping.");continue}const n=await(await(await fetch(t.path)).blob()).arrayBuffer(),s=new Uint8Array(n);e.files[i]=s}}}var nA=Object.defineProperty,Be=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&nA(e,t,n),n};const f1=w("debugusdzbehaviours");class ea extends E{object;target;duration=1;relativeMotion=!1;coroutine=null;targetPos=new b;targetRot=new N;targetScale=new b;onEnable(){this.context.accessibility.updateElement(this,{role:"button",label:"Move "+(this.object?.name||"object")+" to "+(this.target?.name||"target")+" on click",hidden:!1})}onDisable(){this.context.accessibility.updateElement(this,{hidden:!0})}onDestroy(){this.context.accessibility.removeElement(this)}onPointerEnter(){this.context.input.setCursor("pointer")}onPointerExit(){this.context.input.unsetCursor("pointer")}onPointerClick(e){const t=this.object?.getComponentsInChildren(Ze);if(t)for(const i of t)i.resetVelocities(),i.resetForcesAndTorques();e.use(),this.coroutine&&this.stopCoroutine(this.coroutine),this.relativeMotion?this.coroutine=this.startCoroutine(this.moveRelative()):this.coroutine=this.startCoroutine(this.moveToTarget())}*moveToTarget(){if(!this.target||!this.object)return;const e=ee(this.object).clone(),t=ee(this.target).clone(),i=_e(this.object).clone(),n=_e(this.target).clone(),s=$e(this.object).clone(),r=$e(this.target).clone(),a=e.distanceTo(t),l=i.angleTo(n),c=s.distanceTo(r);if(a<.01&&l<.01&&c<.01){yt(this.object,t),Sn(this.object,n),za(this.object,r),this.coroutine=null;return}let h=0,d=0;for(;h<1;)h+=this.context.time.deltaTime/this.duration,h>1&&(h=1),d=h<.5?4*h*h*h:1-Math.pow(-2*h+2,3)/2,this.targetPos.lerpVectors(e,t,d),this.targetRot.slerpQuaternions(i,n,d),this.targetScale.lerpVectors(s,r,d),yt(this.object,this.targetPos),Sn(this.object,this.targetRot),za(this.object,this.targetScale),yield;this.coroutine=null}*moveRelative(){if(!this.target||!this.object)return;const e=this.object.position.clone(),t=this.object.quaternion.clone(),i=this.object.scale.clone(),n=this.target.position.clone(),s=this.target.quaternion.clone(),r=this.target.scale.clone();n.applyQuaternion(this.object.quaternion),this.targetPos.copy(this.object.position).add(n),this.targetRot.copy(this.object.quaternion).multiply(s),this.targetScale.copy(this.object.scale).multiply(r);let a=0,l=0;for(;a<1;)a+=this.context.time.deltaTime/this.duration,a>1&&(a=1),l=a<.5?4*a*a*a:1-Math.pow(-2*a+2,3)/2,this.object.position.lerpVectors(e,this.targetPos,l),this.object.quaternion.slerpQuaternions(t,this.targetRot,l),this.object.scale.lerpVectors(i,this.targetScale,l),yield;this.coroutine=null}beforeCreateDocument(e){if(this.target&&this.object&&this.gameObject){const t=new jt("Move to "+this.target?.name,$t.tapTrigger(this.gameObject),fe.transformAction(this.object,this.target,this.duration,this.relativeMotion?"relative":"absolute"));e.addBehavior(t)}}}Be([u(M)],ea.prototype,"object"),Be([u(M)],ea.prototype,"target"),Be([u()],ea.prototype,"duration"),Be([u()],ea.prototype,"relativeMotion");const bp=class si extends E{materialToSwitch;variantMaterial;fadeDuration=0;start(){this._objectsWithThisMaterial=this.objectsWithThisMaterial,A()&&this._objectsWithThisMaterial.length<=0&&console.warn('ChangeMaterialOnClick: No objects found with material "'+this.materialToSwitch?.name+'"')}onEnable(){this.context.accessibility.updateElement(this,{role:"button",label:"Change material to "+(this.variantMaterial?.name||"unknown material"),hidden:!1})}onDisable(){this.context.accessibility.updateElement(this,{hidden:!0})}onDestroy(){this.context.accessibility.removeElement(this)}onPointerEnter(e){this.context.input.setCursor("pointer")}onPointerExit(e){this.context.input.unsetCursor("pointer")}onPointerClick(e){if(e.use(),!!this.variantMaterial)for(let t=0;t<this.objectsWithThisMaterial.length;t++){const i=this.objectsWithThisMaterial[t];i.material=this.variantMaterial}}_objectsWithThisMaterial=null;get objectsWithThisMaterial(){return this._objectsWithThisMaterial!=null?this._objectsWithThisMaterial:(this._objectsWithThisMaterial=[],this.variantMaterial&&this.materialToSwitch&&this.context.scene.traverse(e=>{if(e instanceof H)if(Array.isArray(e.material)){for(const t of e.material)if(t===this.materialToSwitch){this.objectsWithThisMaterial.push(e);break}}else e.material===this.materialToSwitch?this.objectsWithThisMaterial.push(e):Yv(e.material,this.materialToSwitch)&&this.objectsWithThisMaterial.push(e)}),this._objectsWithThisMaterial)}selfModel;targetModels;static _materialTriggersPerId={};static _startHiddenBehaviour=null;static _parallelStartHiddenActions=[];async beforeCreateDocument(e,t){this.targetModels=[],si._materialTriggersPerId={},si.variantSwitchIndex=0,this.materialToSwitch&&await Ve.assignTextureLOD(this.materialToSwitch,0),this.variantMaterial&&await Ve.assignTextureLOD(this.variantMaterial,0)}createBehaviours(e,t,i){this.objectsWithThisMaterial.find(n=>n.uuid===t.uuid)&&this.targetModels.push(t),this.gameObject.uuid===t.uuid&&(this.selfModel=t,this.materialToSwitch&&(si._materialTriggersPerId[this.materialToSwitch.uuid]||(si._materialTriggersPerId[this.materialToSwitch.uuid]=[]),si._materialTriggersPerId[this.materialToSwitch.uuid].push(this)))}afterCreateDocument(e,t){if(!this.materialToSwitch)return;const i=si._materialTriggersPerId[this.materialToSwitch.uuid];if(i){const n={};for(const s of i){const r=s.createVariants();r&&r.length>0&&(n[s.selfModel.uuid]=r)}for(const s of i){const r=[];for(const a in n)a!==s.selfModel.uuid&&r.push(...n[a]);s.createAndAttachBehaviors(e,n[s.selfModel.uuid],r)}}delete si._materialTriggersPerId[this.materialToSwitch.uuid]}createAndAttachBehaviors(e,t,i){const n=[],s=Math.max(0,this.fadeDuration);n.push(fe.fadeAction([...this.targetModels,...i],s,!1)),n.push(fe.fadeAction(t,s,!0)),e.addBehavior(new jt("Select_"+this.selfModel.name,$t.tapTrigger(this.selfModel),fe.parallel(...n))),si._parallelStartHiddenActions.push(...t),si._startHiddenBehaviour||(si._startHiddenBehaviour=new jt("StartHidden_"+this.selfModel.name,$t.sceneStartTrigger(),fe.fadeAction(si._parallelStartHiddenActions,s,!1)),e.addBehavior(si._startHiddenBehaviour))}static getMaterialName(e){return ji(e.name||"Material")+"_"+e.id}static variantSwitchIndex=0;createVariants(){if(!this.variantMaterial)return null;const e=[];for(const t of this.targetModels){const i=t.clone();i.name+="_Variant_"+si.variantSwitchIndex+++"_"+si.getMaterialName(this.variantMaterial),i.displayName=i.displayName+": Variant with material "+this.variantMaterial.name,i.material=this.variantMaterial,i.geometry=t.geometry,i.transform=t.transform,(!t.parent||!t.parent.isEmpty())&&rt.createEmptyParent(t),t.parent&&t.parent.add(i),e.push(i)}return e}};Be([u(we)],bp.prototype,"materialToSwitch"),Be([u(we)],bp.prototype,"variantMaterial"),Be([u()],bp.prototype,"fadeDuration");let Ty=bp;const ch=class ze extends E{target;toggleOnClick=!1;targetState=!0;hideSelf=!0;onPointerEnter(){this.context.input.setCursor("pointer")}onPointerExit(){this.context.input.unsetCursor("pointer")}onPointerClick(e){e.use(),!this.toggleOnClick&&this.hideSelf&&(this.gameObject.visible=!1),this.target&&(this.target.visible=this.toggleOnClick?!this.target.visible:this.targetState)}selfModel;selfModelClone;targetModel;toggleModel;createBehaviours(e,t,i){t.uuid===this.gameObject.uuid&&(this.selfModel=t,this.selfModelClone=t.clone())}stateBeforeCreatingDocument=!1;targetStateBeforeCreatingDocument=!1;static clonedToggleIndex=0;static wasVisible=Symbol("usdz_SetActiveOnClick_wasVisible");static toggleClone=Symbol("clone for toggling");static reverseToggleClone=Symbol("clone for reverse toggling");beforeCreateDocument(){this.target&&(this.gameObject[ze.wasVisible]===void 0&&(this.gameObject[ze.wasVisible]=this.gameObject.activeSelf),this.target[ze.wasVisible]===void 0&&(this.target[ze.wasVisible]=this.target.activeSelf),this.stateBeforeCreatingDocument=this.gameObject[ze.wasVisible],this.targetStateBeforeCreatingDocument=this.target[ze.wasVisible],this.gameObject.visible=!0,this.target.visible=!0)}afterCreateDocument(e,t){if(!this.target)return;this.targetModel=t.document.findById(this.target.uuid);const i=this.selfModel;if(this.selfModel&&this.targetModel){let n=this.selfModel,s=this.targetState;if(this.toggleOnClick)if(s=!this.targetStateBeforeCreatingDocument,!this.selfModelClone.geometry)(!this.selfModel.parent||this.selfModel.parent.isEmpty())&&wy.createEmptyParent(this.selfModel),this.toggleModel=this.selfModel.deepClone(),this.toggleModel.name+="_toggle",this.selfModel.parent.add(this.toggleModel);else{if(!this.gameObject[ze.toggleClone]){const l=this.selfModelClone.clone();l.setMatrix(new J),l.name+="_toggle"+ze.clonedToggleIndex++,i.add(l),this.gameObject[ze.toggleClone]=l,console.warn("USDZExport: Toggle "+this.gameObject.name+" doesn't have geometry. It will be deep cloned and nested behaviours will likely not work.")}const a=this.gameObject[ze.toggleClone];if(!this.gameObject[ze.reverseToggleClone]){const l=this.selfModelClone.clone();l.setMatrix(new J),l.name+="_toggleReverse"+ze.clonedToggleIndex++,i.add(l),this.gameObject[ze.reverseToggleClone]=l}this.toggleModel=this.gameObject[ze.reverseToggleClone],(!this.toggleModel.geometry||!a.geometry)&&console.error("triggers without childs and without geometry won't work!",this,i.geometry),n=a,i.geometry=null,i.material=null}if(this.toggleModel){if(this.toggleOnClick){const a=[];a.push(fe.fadeAction(n,0,!1)),a.push(fe.fadeAction(this.toggleModel,0,!0)),a.push(fe.fadeAction(this.targetModel,0,s)),e.addBehavior(new jt("Toggle_"+n.name+"_ToggleTo"+(s?"On":"Off"),$t.tapTrigger(n),fe.parallel(...a)));const l=[];l.push(fe.fadeAction(this.toggleModel,0,!1)),l.push(fe.fadeAction(n,0,!0)),l.push(fe.fadeAction(this.targetModel,0,!s)),e.addBehavior(new jt("Toggle_"+n.name+"_ToggleTo"+(s?"Off":"On"),$t.tapTrigger(this.toggleModel),fe.parallel(...l)))}}else{const a=[];this.hideSelf&&a.push(fe.fadeAction(n,0,!1)),a.push(fe.fadeAction(this.targetModel,0,s)),e.addBehavior(new jt("Toggle_"+n.name+"_ToggleTo"+(s?"On":"Off"),$t.tapTrigger(n),a.length>1?fe.parallel(...a):a[0]))}const r=new Array;this.targetStateBeforeCreatingDocument||r.push(this.targetModel),this.stateBeforeCreatingDocument||r.push(i),this.toggleModel&&r.push(this.toggleModel),fn.add(r,e)}}afterSerialize(e,t){this.gameObject[ze.wasVisible]!==void 0&&(this.gameObject.visible=this.gameObject[ze.wasVisible],delete this.gameObject[ze.wasVisible]),this.target&&this.target[ze.wasVisible]!==void 0&&(this.target.visible=this.target[ze.wasVisible],delete this.target[ze.wasVisible]),delete this.gameObject[ze.toggleClone],delete this.gameObject[ze.reverseToggleClone]}};Be([u(M)],ch.prototype,"target"),Be([u()],ch.prototype,"toggleOnClick"),Be([u()],ch.prototype,"targetState"),Be([u()],ch.prototype,"hideSelf");let Ay=ch;class fn extends E{static _fadeBehaviour;static _fadeObjects=[];static add(e,t){const i=Array.isArray(e)?e:[e];for(const n of i)fn._fadeObjects.includes(n)||(console.log("adding hide on start",n),fn._fadeObjects.push(n));fn._fadeBehaviour===void 0&&(fn._fadeBehaviour=new jt("HideOnStart",$t.sceneStartTrigger(),fe.fadeAction(fn._fadeObjects,0,!1)),t.addBehavior(fn._fadeBehaviour))}start(){S.setActive(this.gameObject,!1)}createBehaviours(e,t,i){t.uuid===this.gameObject.uuid&&(this.wasVisible||fn.add(t,e))}wasVisible=!1;beforeCreateDocument(){this.wasVisible=S.isActiveSelf(this.gameObject)}}class Ol extends E{target;duration=.5;motionType="bounce";onEnable(){this.context.accessibility.updateElement(this,{role:"button",label:"Emphasize "+this.target?.name+" on click",hidden:!1})}onDisable(){this.context.accessibility.updateElement(this,{hidden:!0})}onDestroy(){this.context.accessibility.removeElement(this)}beforeCreateDocument(){}createBehaviours(e,t,i){if(this.target&&t.uuid===this.gameObject.uuid){const n=new jt("emphasize "+this.name,$t.tapTrigger(this.gameObject),fe.emphasize(this.target,this.duration,this.motionType,void 0,"basic"));e.addBehavior(n)}}afterCreateDocument(e,t){}}Be([u()],Ol.prototype,"target"),Be([u()],Ol.prototype,"duration"),Be([u()],Ol.prototype,"motionType");class zs extends E{target;clip="";toggleOnClick=!1;trigger="tap";ensureAudioSource(){if(!this.target){const e=this.gameObject.addComponent(Di);e&&(this.target=e,e.spatialBlend=1,e.volume=1,e.loop=!1,e.preload=!0)}}onEnable(){this.context.accessibility.updateElement(this,{role:"button",label:"Play audio: "+(this.clip||this.target?.clip||"unknown clip"),hidden:!1})}onDisable(){this.context.accessibility.updateElement(this,{hidden:!0})}onDestroy(){this.context.accessibility.removeElement(this)}onPointerEnter(){this.context.input.setCursor("pointer")}onPointerExit(){this.context.input.unsetCursor("pointer")}onPointerClick(e){e.use(),!(!this.target?.clip&&!this.clip)&&(this.ensureAudioSource(),this.target&&(this.target.isPlaying&&this.toggleOnClick?this.target.stop():(!this.toggleOnClick&&this.target.isPlaying&&this.target.stop(),this.clip?this.target.play(this.clip):this.target.play())))}createBehaviours(e,t,i){if(!(!this.target&&!this.clip)&&t.uuid===this.gameObject.uuid){const n=this.clip?this.clip:this.target?this.target.clip:void 0;if(!n||typeof n!="string")return;const s=this.target?this.target.gameObject:this.gameObject;Pa.getName(n);const r=this.target?this.target.volume:1,a=this.target&&this.target.spatialBlend==0?"nonSpatial":"spatial";let l=!1;this.gameObject.traverse(p=>{p instanceof H&&p.visible&&(l=!0)}),l=!0;const c=e.addAudioClip(n);let h=fe.playAudioAction(s,c,"play",r,a);this.target&&this.target.loop&&(h=fe.sequence(h).makeLooping());const d=this.name?"_"+this.name:"";if(l&&this.trigger==="tap"){this.toggleOnClick&&(h.multiplePerformOperation="stop");const p=new jt("playAudio"+d,$t.tapTrigger(t),h);e.addBehavior(p)}if(this.target&&this.target.playOnAwake&&this.target.enabled)if(l&&this.trigger==="tap")console.warn("USDZExport: Audio sources that are played on tap can't also auto-play at scene start due to a QuickLook bug.");else{const p=new jt("playAudioOnStart"+d,$t.sceneStartTrigger(),h);e.addBehavior(p)}}}}Be([u(Di)],zs.prototype,"target"),Be([u(URL)],zs.prototype,"clip"),Be([u()],zs.prototype,"toggleOnClick");const Iy=class _o extends E{animator;stateName;trigger="tap";animation;get target(){return this.animator?.gameObject||this.animation?.gameObject}onEnable(){this.context.accessibility.updateElement(this,{role:"button",label:"Plays animation "+(this.stateName||"")+" on "+(this.target?this.target.name:""),hidden:!1})}onDisable(){this.context.accessibility.updateElement(this,{hidden:!0})}onDestroy(){this.context.accessibility.removeElement(this)}onPointerEnter(){this.context.input.setCursor("pointer"),this.context.accessibility.hover(this,"Click to play animation "+(this.stateName||"")+" on "+(this.target?this.target.name:""))}onPointerExit(){this.context.input.unsetCursor("pointer")}onPointerClick(e){e.use(),this.target&&this.stateName&&(this.context.accessibility.focus(this),this.animator?.play(this.stateName,0,0,.1))}selfModel;stateAnimationModel;animationSequence=new Array;animationLoopAfterSequence=new Array;randomOffsetNormalized=0;createBehaviours(e,t,i){t.uuid===this.gameObject.uuid&&(this.selfModel=t)}static animationActions=[];static rootsWithExclusivePlayback=new Set;afterSerialize(){if(_o.rootsWithExclusivePlayback.size>1){const e='Multiple root objects targeted by more than one animation. To work around QuickLook bug FB13410767, animations will be set as "exclusive" and activating them will stop other animations being marked as exclusive.';A()&&be(e),console.warn(e,..._o.rootsWithExclusivePlayback)}_o.animationActions=[],_o.rootsWithExclusivePlayback=new Set}afterCreateDocument(e,t){if(this.animationSequence===void 0&&this.animationLoopAfterSequence===void 0||!this.stateAnimationModel||!this.target)return;const i=t.document,n=t.extensions.find(a=>a instanceof yp);if(!n)return;const s=n.getClipCount(this.target)>1;s&&(A()&&console.warn("Setting exclusive playback for "+this.target.name+"@"+this.stateName+" because it has "+n.getClipCount(this.target)+" animations. This works around QuickLook bug FB13410767."),_o.rootsWithExclusivePlayback.add(this.target));const r=this.name?this.name:"";i.traverse(a=>{if(a.uuid===this.target?.uuid){const l=_o.getActionForSequences(i,a,this.animationSequence,this.animationLoopAfterSequence,this.randomOffsetNormalized),c=new jt(this.trigger+"_"+r+"_toPlayAnimation_"+this.stateName+"_on_"+this.target?.name,this.trigger=="tap"?$t.tapTrigger(this.selfModel):$t.sceneStartTrigger(),l);s&&c.makeExclusive(!0),e.addBehavior(c)}})}static getActionForSequences(e,t,i,n,s){const r=(l,c)=>{let h=_o.animationActions.find(d=>d.affectedObjects==l&&d.start==c.start&&d.duration==c.duration&&d.animationSpeed==c.speed);return h||(h=fe.startAnimationAction(l,c),_o.animationActions.push(h)),h},a=fe.sequence();if(i&&i.length>0)for(const l of i)a.addAction(r(t,l));if(n&&n.length>0){const l=a.actions.length==0?a:fe.sequence();for(const c of n)l.addAction(r(t,c));l.makeLooping(),a!==l&&a.addAction(l)}return s&&s>0&&a.actions.unshift(fe.waitAction(s)),a}static getAndRegisterAnimationSequences(e,t,i){if(!t)return;const n=t.getComponent(_t),s=t.getComponent(Ut);if(!n&&!s)return;if(n&&!i)throw new Error("PlayAnimationOnClick: No stateName specified for animator "+n.name+" on "+t.name);let r=[],a=[];if(s){const g=e.registerAnimation(t,s.clip);g&&(s.loop?a.push(g):r.push(g));let f=0;if(s.minMaxOffsetNormalized){const y=s.minMaxOffsetNormalized.x,_=s.minMaxOffsetNormalized.y;f=(s.clip?.duration||1)*(y+Math.random()*(_-y))}return{animationSequence:r,animationLoopAfterSequence:a,randomTimeOffset:f}}const l=n?.runtimeAnimatorController;let c=l?.findState(i),h=[],d=[];if(l&&c){const g=new Array;g.push(c);let f=!1;for(;g.length<100;){if(!c||c===null||!c.transitions||c.transitions.length===0){c.motion?.isLooping&&(f=!0);break}const y=c.transitions.find(v=>v.conditions.length===0),_=y?l.getState(y.destinationState,0):null;if(_&&g.includes(_)){c=_,f=!0;break}else if(y){if(c=_,!c)break;g.push(c)}else{f=c.motion?.isLooping??!1;break}}if(f&&c){const y=g.indexOf(c);h=g.slice(0,y),d=g.slice(y),f1&&console.log("found loop from "+i,"states until loop",h,"states looping",d)}else h=g,d=[],f1&&console.log("found no loop from "+i,"states",h);if(!d.length){const y=h[h.length-1],_=y.motion?.clip;if(_){let v;if(e.holdClipMap.has(_))v=e.holdClipMap.get(_);else{const P=y.name+"_hold";v=_.clone(),v.duration=1,v.name=P;const k=_.duration;v.tracks=_.tracks.map(O=>{const D=O.clone();D.times=new Float32Array([0,k]);const L=O.values.length,V=O.getValueSize(),W=O.values.slice(L-V,L);return D.values=new Float32Array(2*V),D.values.set(W,0),D.values.set(W,V),D}),v.name=P,e.holdClipMap.set(_,v)}if(v){const P={name:v.name,motion:{clip:v,isLooping:!1,name:v.name},speed:1,transitions:[],behaviours:[],hash:y.hash+1};d.push(P)}}}}if(h.length===1&&(!h[0].motion?.clip||h[0].motion?.clip.tracks?.length===0)){r=new Array;const g=e.registerAnimation(t,null);g&&r.push(g);return}if(h=h.filter(g=>g.motion?.clip&&g.motion?.clip.tracks?.length>0),d=d.filter(g=>g.motion?.clip&&g.motion?.clip.tracks?.length>0),h.length===0&&d.length===0){console.warn("No clips found for state "+i+" on "+n?.name+", can't export animation data");return}const p=(g,f)=>{if(!t)return;const y=e.registerAnimation(t,g.motion.clip??null);y?(y.speed=g.speed,f.push(y)):console.warn("Couldn't register animation for state "+g.name+" on "+n?.name)};if(h.length>0){r=new Array;for(const g of h)p(g,r)}if(d.length>0){a=new Array;for(const g of d)p(g,a)}let m=0;if(n&&l&&n.minMaxOffsetNormalized){const g=n.minMaxOffsetNormalized.x,f=n.minMaxOffsetNormalized.y;m=((h.length?h[0]:d.length?d[0]:null)?.motion.clip?.duration||1)*(g+Math.random()*(f-g))}return{animationSequence:r,animationLoopAfterSequence:a,randomTimeOffset:m}}createAnimation(e,t,i){if(!this.target||!this.animator&&!this.animation)return;const n=_o.getAndRegisterAnimationSequences(e,this.target,this.stateName);n&&(this.animationSequence=n.animationSequence,this.animationLoopAfterSequence=n.animationLoopAfterSequence,this.randomOffsetNormalized=n.randomTimeOffset,this.stateAnimationModel=t)}};Be([u(_t)],Iy.prototype,"animator"),Be([u()],Iy.prototype,"stateName");let hh=Iy;class kl extends E{getType(){}target;getDuration(){}}Be([u(M)],kl.prototype,"target");class dh extends E{target}Be([u(kl)],dh.prototype,"target");class uh extends kl{type=1;duration=1;getType(){switch(this.type){case 1:return"hide";case 0:return"show"}}getDuration(){return this.duration}}Be([u()],uh.prototype,"type"),Be([u()],uh.prototype,"duration");class Ly extends dh{}const oA=100,sA=200,rA=300;class ur{static _instance;static create(){return new ur}static getOrCreate(){return this._instance||(this._instance=this.create()),this._instance}get isSecureConnection(){return window.location.protocol==="https:"}get quicklookButton(){return this._quicklookButton}_quicklookButton;get arButton(){return this._arButton}_arButton;get vrButton(){return this._vrButton}_vrButton;get sendToQuestButton(){return this._sendToQuestButton}_sendToQuestButton;get qrButton(){return mn.getOrCreate().createQRCode()}createQuicklookButton(){if(this._quicklookButton)return this._quicklookButton;const e=document.createElement("button");this._quicklookButton=e,e.dataset.needle="quicklook-button";const t=I.supportsQuickLookAR();let i="View in AR";I.isVisionOS()?i="View in AR":(t||I.isiOS())&&(i="Open in Quicklook"),e.innerText=i,e.prepend(Ot("view_in_ar")),Ms.setElementPriority(e,sA);let n=!1,s=null;return e.addEventListener("click",()=>{s=tl(ho),s||(n=!0,s=new ho),n&&(s.objectToExport=U.Current.scene),s?(e.classList.add("this-mode-is-requested"),s.exportAndOpen().then(()=>{e.classList.remove("this-mode-is-requested")}).catch(r=>{e.classList.remove("this-mode-is-requested"),console.error(r)})):console.warn("No USDZExporter component found in the scene")}),this.hideElementDuringXRSession(e),e}createARButton(e){if(this._arButton)return this._arButton;const t="immersive-ar",i=document.createElement("button");return this._arButton=i,i.classList.add("webxr-button"),i.dataset.needle="webxr-ar-button",i.innerText="Enter AR",i.prepend(Ot("view_in_ar")),i.title="Click to start an AR session",i.addEventListener("click",()=>Z.start(t,e)),Ms.setElementPriority(i,rA),this.updateSessionSupported(i,t),this.listenToXRSessionState(i,t),this.hideElementDuringXRSession(i),this.isSecureConnection||(i.disabled=!0,i.title="WebXR requires a secure connection (HTTPS)"),I.isMozillaXR()||navigator.xr?.addEventListener("devicechange",()=>this.updateSessionSupported(i,t)),i}createVRButton(e){if(this._vrButton)return this._vrButton;const t="immersive-vr",i=document.createElement("button");return this._vrButton=i,i.classList.add("webxr-button"),i.dataset.needle="webxr-vr-button",i.innerText="Enter VR",i.prepend(Ot("panorama_photosphere")),i.title="Click to start a VR session",i.addEventListener("click",()=>Z.start(t,e)),Ms.setElementPriority(i,oA),this.updateSessionSupported(i,t),this.listenToXRSessionState(i,t),this.hideElementDuringXRSession(i),this.isSecureConnection||(i.disabled=!0,i.title="WebXR requires a secure connection (HTTPS)"),I.isMozillaXR()||navigator.xr?.addEventListener("devicechange",()=>this.updateSessionSupported(i,t)),i}createSendToQuestButton(){if(this._sendToQuestButton)return this._sendToQuestButton;const e="https://oculus.com/open_url/?url=",t=document.createElement("button");return this._sendToQuestButton=t,t.dataset.needle="webxr-sendtoquest-button",t.innerText="Open on Quest",t.prepend(Ot("share_windows")),t.title="Click to send this page to the Oculus Browser on your Quest",t.addEventListener("click",()=>{const i=encodeURIComponent(window.location.href),n=e+i;window.open(n)==null&&Oe("This page doesn't allow popups. Please paste "+n+" into your browser.")}),this.listenToXRSessionState(t),this.hideElementDuringXRSession(t),I.isMozillaXR()||navigator.xr?.addEventListener("devicechange",()=>{navigator.xr?.isSessionSupported("immersive-vr")?t.style.display="none":t.style.display=""}),t}createQRCode(){return mn.getOrCreate().createQRCode()}updateSessionSupported(e,t){if(!(t==="immersive-ar"&&I.isiOS()&&!I.isVisionOS())){if(!("xr"in navigator)){e.style.display="none";return}Z.isSessionSupported(t).then(i=>{e.style.display=i?"":"none",A()&&!i&&console.log('[WebXR] "'+t+'" is not supported on this device. Make sure your server runs using HTTPS and you have a device connected that supports '+t)})}}hideElementDuringXRSession(e){Qd(t=>{e["previous-display"]=e.style.display,e.style.setProperty("display","none","important")}),xg(t=>{e["previous-display"]!=null&&(e.style.display=e["previous-display"])})}listenToXRSessionState(e,t){t&&(Z.onSessionRequestStart(i=>{i.mode===t?e.classList.add("this-mode-is-requested"):(e["was-disabled"]=e.disabled,e.disabled=!0,e.classList.add("other-mode-is-requested"))}),Z.onSessionRequestEnd(i=>{e.classList.remove("this-mode-is-requested"),e.classList.remove("other-mode-is-requested"),e.disabled=e["was-disabled"]}))}}var aA=Object.defineProperty,lA=Object.getOwnPropertyDescriptor,wt=(o,e,t,i)=>{for(var n=i>1?void 0:i?lA(e,t):e,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&aA(e,t,n),n};const ph=w("debugspriterenderer"),cA=w("wireframe");class ka{static cache={};static getOrCreateGeometry(e){if(e.__cached_geometry)return e.__cached_geometry;if(e.guid&&ka.cache[e.guid])return ph&&console.log("Take cached geometry for sprite",e.guid),ka.cache[e.guid];const t=new wn;e.__cached_geometry=t;const i=new Float32Array(e.triangles.length*3),n=new Float32Array(e.triangles.length*2);for(let s=0;s<e.triangles.length;s+=1){const r=e.triangles[s];i[s*3]=-e.vertices[r].x,i[s*3+1]=e.vertices[r].y,i[s*3+2]=0;const a=e.uv[r];n[s*2]=a.x,n[s*2+1]=1-a.y}return t.setAttribute("position",new ft(i,3)),t.setAttribute("uv",new ft(n,2)),e.guid&&(this.cache[e.guid]=t),ph&&console.log("Built sprite geometry",e,t),t}}class hA{x;y}function y1(o){o&&(o.colorSpace!=ko&&(o.colorSpace=ko,o.needsUpdate=!0),o.minFilter==Ad&&o.magFilter==Ad&&(o.anisotropy=1,o.needsUpdate=!0))}let Yo=class{constructor(o){o&&(this.texture=o,this.triangles=[0,1,2,0,2,3],this.uv=[{x:0,y:0},{x:1,y:0},{x:1,y:1},{x:0,y:1}],this.vertices=[{x:-.5,y:-.5},{x:.5,y:-.5},{x:.5,y:.5},{x:-.5,y:.5}])}guid;texture;triangles;uv;vertices;__cached_geometry;get mesh(){return this._mesh||(this._mesh=new H(ka.getOrCreateGeometry(this),this.material)),this._mesh}_mesh;get material(){return this._material||(this.texture&&y1(this.texture),this._material=new Ce({map:this.texture,color:16777215,side:Pi,transparent:!0})),this._material}_material;getGeometry(){return ka.getOrCreateGeometry(this)}};wt([u()],Yo.prototype,"guid",2),wt([u(Se)],Yo.prototype,"texture",2),wt([Qe()],Yo.prototype,"triangles",2),wt([Qe()],Yo.prototype,"uv",2),wt([Qe()],Yo.prototype,"vertices",2);const Dy=Symbol("spriteOwner");class Ml{sprites;constructor(){this.sprites=[]}}wt([u(Yo)],Ml.prototype,"sprites",2);const jy=class hb{static create(){const e=new hb;return e.spriteSheet=new Ml,e}constructor(){}clone(){const e=new hb;return e.index=this.index,e.spriteSheet=this.spriteSheet,e}set sprite(e){e&&(this.spriteSheet?((this.index===null||this.index===void 0)&&(this.index=0),this.spriteSheet.sprites[this.index]=e):(this.spriteSheet=new Ml,this.spriteSheet.sprites=[e],this.index=0))}get sprite(){if(this.spriteSheet)return this.spriteSheet.sprites[this.index]}spriteSheet;index=0;update(e){if(!this.spriteSheet)return;const t=this.index;if(t<0||t>=this.spriteSheet.sprites.length)return;const i=this.spriteSheet.sprites[t],n=i?.texture;if(n&&(y1(n),!i.__hasLoadedProgressive)){i.__hasLoadedProgressive=!0;const s=n;Ve.assignTextureLOD(n,0).then(r=>{r instanceof Se&&(i.texture=r,e?.map===s&&(e.map=r,e.needsUpdate=!0))})}}};wt([u(Ml)],jy.prototype,"spriteSheet",2),wt([u()],jy.prototype,"index",2);let El=jy;class yi extends E{drawMode=0;size={x:1,y:1};color;sharedMaterial;transparent=!0;cutoutThreshold=0;castShadows=!1;renderOrder=0;toneMapped=!0;set texture(e){if(!this._spriteSheet)return;const t=this._spriteSheet.spriteSheet?.sprites[this.spriteIndex];t&&(t.texture=e,this.updateSprite())}addSprite(e,t=!1){if(this._spriteSheet||(this._spriteSheet=El.create()),!this._spriteSheet.spriteSheet)return-1;this._spriteSheet.spriteSheet?.sprites.push(e);const i=this._spriteSheet.spriteSheet?.sprites.length-1;return t&&(this.spriteIndex=i),i}get sprite(){return this._spriteSheet}set sprite(e){if(e!==this._spriteSheet)if(typeof e=="number"){const t=Math.round(e);ph&&console.log("[SpriteSheet] Set index to "+t+" (was "+this.spriteIndex+")",e),this.spriteIndex=t}else e instanceof Yo?(this._spriteSheet||(this._spriteSheet=El.create()),this._spriteSheet.sprite!=e&&(this._spriteSheet.sprite=e),this.updateSprite()):e!=this._spriteSheet&&(this._spriteSheet=e,this.updateSprite())}set spriteIndex(e){this._spriteSheet&&(this._spriteSheet.index=e,this.updateSprite())}get spriteIndex(){return this._spriteSheet?.index??0}get spriteFrames(){return this._spriteSheet?.spriteSheet?.sprites.length??0}_spriteSheet;_currentSprite;awake(){this._currentSprite=void 0,this._spriteSheet?this._spriteSheet=this._spriteSheet.clone():this._spriteSheet=El.create(),ph&&console.log("Awake",this.name,this,this.sprite)}start(){this._currentSprite?this.gameObject&&this.gameObject.add(this._currentSprite):this.updateSprite()}updateSprite(e=!1){if(!this.__didAwake&&!e)return!1;const t=this._spriteSheet;if(!t?.spriteSheet?.sprites)return console.warn("SpriteRenderer has no data or spritesheet assigned..."),!1;const i=t.spriteSheet.sprites[this.spriteIndex];if(!i)return ph&&console.warn("Sprite not found",this.spriteIndex,t.spriteSheet.sprites),!1;if(this._currentSprite)this._currentSprite.geometry=ka.getOrCreateGeometry(i),this._currentSprite.material.map=i.texture;else{const n=new Ce({color:16777215,side:Pi});if(cA&&(n.wireframe=!0),this.color&&(n.color||(n.color=new oe),n.color.copy(this.color),n.opacity=this.color.alpha),n.transparent=!0,n.toneMapped=this.toneMapped,n.depthWrite=!1,i.texture&&!n.wireframe){let s=i.texture;s[Dy]!==void 0&&s[Dy]!==this&&this.spriteFrames>1&&(s=i.texture=s.clone()),s[Dy]=this,n.map=s}this.sharedMaterial=n,this._currentSprite=new H(ka.getOrCreateGeometry(i),n),this._currentSprite.renderOrder=Math.round(this.renderOrder),Ve.assignTextureLOD(n,0)}return this._currentSprite.parent!==this.gameObject&&(this.drawMode===2&&this._currentSprite.scale.set(this.size.x,this.size.y,1),this.gameObject&&this.gameObject.add(this._currentSprite)),this._currentSprite&&this._currentSprite.layers.set(this.layer),this.sharedMaterial&&(this.sharedMaterial.alphaTest=this.cutoutThreshold,this.sharedMaterial.transparent=this.transparent),this._currentSprite.castShadow=this.castShadows,t?.update(this.sharedMaterial),!0}}wt([u()],yi.prototype,"drawMode",2),wt([u(hA)],yi.prototype,"size",2),wt([u(se)],yi.prototype,"color",2),wt([u(we)],yi.prototype,"sharedMaterial",2),wt([u()],yi.prototype,"transparent",2),wt([u()],yi.prototype,"cutoutThreshold",2),wt([u()],yi.prototype,"castShadows",2),wt([u()],yi.prototype,"renderOrder",2),wt([u()],yi.prototype,"toneMapped",2),wt([u(El)],yi.prototype,"sprite",1);const b1=w("debugwebxr"),dA=new J().makeRotationY(Math.PI);class yn extends E{static _eventListeners={};static onPlaced(e){const t="placed";return this._eventListeners[t]||(this._eventListeners[t]=[]),this._eventListeners[t].push(e),()=>{const i=this._eventListeners[t].indexOf(e);i>=0&&this._eventListeners[t].splice(i,1)}}static _hasPlaced=!1;static get hasPlaced(){return this._hasPlaced}get arScale(){return this._arScale}set arScale(e){this._arScale=Math.max(1e-6,e),this.onSetScale()}_arScale=1;invertForward=!1;customReticle;arTouchTransform=!0;autoPlace=!1;autoCenter=!1;useXRAnchor=!1;_isPlacing=!0;_startOffset=new J;_createdPlacementObject=null;_reparentedComponents=[];_placementScene=new Hi;_reticle=[];_hits=[];_placementStartTime=-1;_rigPlacementMatrix;_anchor=null;userInput;onEnable(){this.customReticle?.preload()}supportsXR(e){return e==="immersive-ar"}onEnterXR(e){b1&&console.log("ENTER WEBXR: SessionRoot start..."),this._anchor=null,yn._hasPlaced=!1,this.gameObject.updateMatrixWorld(),this._startOffset.copy(this.gameObject.matrixWorld);const t=new M;this._createdPlacementObject=t,t.name="AR Session Root",this._placementScene.name="AR Placement Scene",this._placementScene.children.length=0;for(let i=this.context.scene.children.length-1;i>=0;i--){const n=this.context.scene.children[i];this._placementScene.add(n)}if(this.context.scene.add(t),this.autoCenter){const i=Ri(this._placementScene.children),n=i.getCenter(new b),s=i.getSize(new b),r=new J;r.makeTranslation(n.x,n.y-s.y*.5,n.z),this._startOffset.multiply(r)}this._reparentedComponents.length=0,this._reparentedComponents.push({comp:this,originalObject:this.gameObject}),S.addComponent(t,this);for(const i of this._reticle)Ii(i);this._reticle.length=0,this._isPlacing=!0,this.context.input.addEventListener("pointerup",this.onPlaceScene,{queue:di.Early})}onLeaveXR(){this.context.input.removeEventListener("pointerup",this.onPlaceScene,{queue:di.Early}),this.onRevertSceneChanges(),this._anchor=null,yn._hasPlaced=!1,this._rigPlacementMatrix=void 0}onUpdateXR(e){if(e.xr.isTrackingImages){for(const t of this._reticle)t.visible=!1;return}if(this._isPlacing){const t=e.xr.rig?.gameObject;t&&t.parent!==this.context.scene&&this.context.scene.add(t);let i=!1;if(e.xr.isPassThrough&&e.xr.controllers.length>0&&!this.autoPlace)for(const n of e.xr.controllers){const s=n.getHitTest();s&&(i=!0,this.updateReticleAndHits(e.xr,n.index,s,e.xr.rigScale))}if(!i){const n=e.xr.getHitTest();n&&this.updateReticleAndHits(e.xr,0,n,e.xr.rigScale)}}else{if(this._anchor&&e.xr.referenceSpace){const t=e.xr.frame.getPose(this._anchor.anchorSpace,e.xr.referenceSpace);if(t&&this.context.time.frame%20===0){const i=e.xr.convertSpace(t.transform),n=this._reticle[0];n&&(n.position.copy(i.position),n.quaternion.copy(i.quaternion),this.onApplyPose(n))}}if(this.arTouchTransform?(this.userInput||(this.userInput=new Sm(this.context)),this.userInput?.enable()):this.userInput?.disable(),this.arTouchTransform&&this.userInput?.hasChanged){if(e.xr.rig){const t=e.xr.rig.gameObject;this.userInput.applyMatrixTo(t.matrix,!0),t.matrix.decompose(t.position,t.quaternion,t.scale),this.userInput.factor=t.scale.x}this.userInput.reset()}}}updateReticleAndHits(e,t,i,n){this._hits[t]=i.hit;let s=this._reticle[t];if(!s){if(this.customReticle)if(this.customReticle.asset)s=Ur(this.customReticle.asset);else{this.customReticle.loadAssetAsync();return}else s=new H(new NC(.07,.09,32).rotateX(-Math.PI/2),new Ce({side:Pi,depthTest:!1,depthWrite:!1,transparent:!0,opacity:1,color:15658734})),s.name="AR Placement Reticle";if(b1){const r=new Ci(1);r.position.y+=.01,s.add(r)}this._reticle[t]=s,s.matrixAutoUpdate=!1,s.visible=!1}if(s.lastPos=s.lastPos||i.position.clone(),s.lastQuat=s.lastQuat||i.quaternion.clone(),s.position.copy(s.lastPos.lerp(i.position,this.context.time.deltaTime/.1)),s.lastPos.copy(s.position),s.quaternion.copy(s.lastQuat.slerp(i.quaternion,this.context.time.deltaTime/.05)),s.lastQuat.copy(s.quaternion),s.scale.set(n,n,n),this.customReticle&&this.applyViewBasedTransform(s),s.updateMatrix(),s.visible=!0,s.parent!==this.context.scene&&this.context.scene.add(s),this._placementStartTime<0&&(this._placementStartTime=this.context.time.realtimeSinceStartup),this.autoPlace)if(this.upVec.set(0,1,0).applyQuaternion(s.quaternion),this.upVec.dot(F(0,1,0))>.9){let r=s["autoplace:timer"]||0;r>=1?(s.visible=!1,this.onPlaceScene(null)):(r+=this.context.time.deltaTime,s["autoplace:timer"]=r)}else s["autoplace:timer"]=0}onPlaceScene=e=>{if(this._isPlacing==!1||e?.used)return;let t=this._reticle[0];if(!t){console.warn("No reticle to place...");return}if(!t.visible&&!this.autoPlace){console.warn("Reticle is not visible (can not place)");return}if(Z.active?.isTrackingImages){console.warn("Scene Placement is disabled while images are being tracked");return}let i=this._hits[0];if(e&&e.origin instanceof Sg){const n=this._reticle[e.origin.index];n&&(t=n,i=this._hits[e.origin.index])}if(e&&(e.stopImmediatePropagation(),e.stopPropagation(),e.use()),this._isPlacing=!1,this.context.input.removeEventListener("pointerup",this.onPlaceScene),this.onRevertSceneChanges(),t.position.copy(t.lastPos),t.quaternion.copy(t.lastQuat),this.onApplyPose(t),yn._hasPlaced=!0,this.useXRAnchor&&this.onCreateAnchor(Z.active,i),this.context.xr)for(const n of this.context.xr.controllers)n.cancelHitTestSource()};onSetScale(){if(!yn._hasPlaced)return;const e=Z.active?.rig?.gameObject;if(e){const t=Z.active?.rigScale||1,i=1/this._arScale*t,n=new J().makeScale(i,i,i).invert();e.matrix.premultiply(n),e.matrix.decompose(e.position,e.quaternion,e.scale)}}onRevertSceneChanges(){for(const e of this._reticle)e&&(e.visible=!1,e?.removeFromParent());this._reticle.length=0;for(let e=this._placementScene.children.length-1;e>=0;e--){const t=this._placementScene.children[e];this.context.scene.add(t)}this._createdPlacementObject?.removeFromParent();for(const e of this._reparentedComponents)S.addComponent(e.originalObject,e.comp)}async onCreateAnchor(e,t){if(t.createAnchor===void 0){console.warn("Hit does not support creating an anchor",t),A()&&be("Hit does not support creating an anchor");return}else{const i=await t.createAnchor(e.viewerPose.transform);e.running&&i&&(this._anchor=i)}}upVec=new b(0,1,0);lookPoint=new b;worldUpVec=new b(0,1,0);applyViewBasedTransform(e){const t=this.context.mainCamera,i=e,n=t.worldPosition,s=i.worldPosition;this.upVec.set(0,1,0).applyQuaternion(e.quaternion);const r=t.worldPosition;r&&e.position.clone().sub(r).angleTo(this.upVec)<Math.PI/2&&this.upVec.negate();const a=this.upVec.angleTo(this.worldUpVec)*180/Math.PI,l=30;a>l&&a<180-l||a<-l&&a>-180+l?(this.lookPoint.copy(e.position).add(this.upVec),this.lookPoint.y=e.position.y,e.lookAt(this.lookPoint)):(n.y=s.y,e.lookAt(n))}onApplyPose(e){const t=Z.active?.rig?.gameObject;if(!t){console.warn("No rig object to place");return}const i=t.parent||this.context.scene;this._rigPlacementMatrix?this._rigPlacementMatrix?.decompose(t.position,t.quaternion,t.scale):this._rigPlacementMatrix=t.matrix.clone(),this.applyViewBasedTransform(e),e.updateMatrix(),this.context.scene.add(e),e.attach(t),e.removeFromParent(),t.scale.set(this.arScale,this.arScale,this.arScale),t.position.multiplyScalar(this.arScale),t.updateMatrix(),this.invertForward&&t.matrix.premultiply(dA),t.matrix.premultiply(this._startOffset),t.matrix.decompose(t.position,t.quaternion,t.scale),i.add(t)}}class Sm{static up=new b(0,1,0);static zero=new b(0,0,0);static one=new b(1,1,1);oneFingerDrag=!0;twoFingerRotate=!0;twoFingerScale=!0;factor=1;context;offset;plane;_scale=1;_hasChanged=!1;get scale(){return this._scale}constructor(e){this.context=e,this.offset=new J,this.plane=new _r,this.plane.setFromNormalAndCoplanarPoint(Sm.up,Sm.zero)}_enabled=!1;reset(){this._scale=1,this.offset.identity(),this._hasChanged=!0}get hasChanged(){return this._hasChanged}applyMatrixTo(e,t){this._hasChanged=!1,t?(this.offset.invert(),e.premultiply(this.offset)):e.multiply(this.offset)}currentlyUsedPointerIds=new Set;currentlyUnusedPointerIds=new Set;get isActive(){return this.currentlyUsedPointerIds.size<=0&&this.currentlyUnusedPointerIds.size>0}enable(){this._enabled||(this._enabled=!0,this.context.input.addEventListener("pointerdown",this.onPointerDownEarly,{queue:di.Early}),this.context.input.addEventListener("pointerdown",this.onPointerDownLate,{queue:di.Late}),this.context.input.addEventListener("pointerup",this.onPointerUpEarly,{queue:di.Early}),window.addEventListener("touchstart",this.touchStart,{passive:!1}),window.addEventListener("touchmove",this.touchMove,{passive:!1}),window.addEventListener("touchend",this.touchEnd,{passive:!1}))}disable(){this._enabled&&(this._enabled=!1,this.context.input.removeEventListener("pointerdown",this.onPointerDownEarly,{queue:di.Early}),this.context.input.removeEventListener("pointerdown",this.onPointerDownLate,{queue:di.Late}),this.context.input.removeEventListener("pointerup",this.onPointerUpEarly,{queue:di.Early}),window.removeEventListener("touchstart",this.touchStart),window.removeEventListener("touchmove",this.touchMove),window.removeEventListener("touchend",this.touchEnd))}onPointerDownEarly=e=>{this.isActive&&e.stopPropagation()};onPointerDownLate=e=>{e.used?this.currentlyUsedPointerIds.add(e.pointerId):this.currentlyUsedPointerIds.size<=0&&this.currentlyUnusedPointerIds.add(e.pointerId)};onPointerUpEarly=e=>{this.currentlyUsedPointerIds.delete(e.pointerId),this.currentlyUnusedPointerIds.delete(e.pointerId)};prev=new Map;_didMultitouch=!1;touchStart=e=>{if(!e.defaultPrevented)for(let t=0;t<e.changedTouches.length;t++){const i=e.changedTouches[t],n=I.isAndroidDevice()&&i.clientY<window.innerHeight*.1;this.prev.has(i.identifier)||this.prev.set(i.identifier,{ignore:n,x:0,z:0,screenx:0,screeny:0});const s=this.prev.get(i.identifier);if(s){const r=this.getPositionOnPlane(i.clientX,i.clientY);s.x=r.x,s.z=r.z,s.screenx=i.clientX,s.screeny=i.clientY}}};touchEnd=e=>{e.touches.length<=0&&(this._didMultitouch=!1);for(let t=0;t<e.changedTouches.length;t++){const i=e.changedTouches[t];this.prev.delete(i.identifier)}};touchMove=e=>{if(!e.defaultPrevented&&this.isActive){if(e.touches.length===1){if(this._didMultitouch)return;const t=e.touches[0],i=this.prev.get(t.identifier);if(!i||i.ignore)return;const n=this.getPositionOnPlane(t.clientX,t.clientY),s=n.x-i.x,r=n.z-i.z;if(s===0&&r===0)return;this.oneFingerDrag&&this.addMovement(s,r),i.x=n.x,i.z=n.z,i.screenx=t.clientX,i.screeny=t.clientY;return}else if(e.touches.length===2){this._didMultitouch=!0;const t=e.touches[0],i=e.touches[1],n=this.prev.get(t.identifier),s=this.prev.get(i.identifier);if(!n||!s)return;if(this.twoFingerRotate){const r=Math.atan2(t.clientY-i.clientY,t.clientX-i.clientX),a=Math.atan2(n.screeny-s.screeny,n.screenx-s.screenx),l=r-a;Math.abs(l)>.001&&this.addRotation(l)}if(this.twoFingerScale){const r=t.clientX-i.clientX,a=t.clientY-i.clientY,l=Math.sqrt(r*r+a*a),c=n.screenx-s.screenx,h=n.screeny-s.screeny,d=Math.sqrt(c*c+h*h),p=l-d;Math.abs(p)>2&&this.addScale(p)}n.screenx=t.clientX,n.screeny=t.clientY,s.screenx=i.clientX,s.screeny=i.clientY}}};_raycaster=new Od;_intersection=new b;_screenPos=new b;getPositionOnPlane(e,t){const i=this.context.mainCamera;return this._screenPos.x=e/window.innerWidth*2-1,this._screenPos.y=-(t/window.innerHeight)*2+1,this._screenPos.z=1,this._screenPos.unproject(i),this._raycaster.set(i.position,this._screenPos.sub(i.position)),this._raycaster.ray.intersectPlane(this.plane,this._intersection),this._intersection}addMovement(e,t){e/=this._scale,t/=this._scale,e*=this.factor,t*=this.factor,this.offset.elements[12]+=e,this.offset.elements[14]+=t,(e!==0||t!==0)&&(this._hasChanged=!0)}_tempMatrix=new J;addScale(e){e/=window.innerWidth,e*=-1,this._scale*=1+e,this._tempMatrix.makeScale(1-e,1-e,1-e),this.offset.premultiply(this._tempMatrix),e!==0&&(this._hasChanged=!0)}addRotation(e){e*=-1,this._tempMatrix.makeRotationY(e),this.offset.premultiply(this._tempMatrix),e!==0&&(this._hasChanged=!0)}}const Ns=w("debugautosync"),By=Symbol("syncerId");class uA{_syncers={};getOrCreateSyncer(e){if(!e.guid)return null;if(this._syncers[e.guid])return this._syncers[e.guid];const t=new pA(e);return t[By]=e.guid,this._syncers[t[By]]=t,t}removeSyncer(e){delete this._syncers[e[By]]}}const Fy=new uA;class pA{comp;constructor(e){this.comp=e}hasChanges=!1;changedProperties={};get networkingKey(){return this.comp.guid}_isReceiving=!1;_isInit=!1;init(e){if(this._isInit)return;this._isInit=!0,this.comp=e,this.comp.context.post_render_callbacks.push(this.onHandleSending),this.comp.context.connection.beginListen(this.networkingKey,this.onHandleReceiving);const t=this.comp.context.connection.tryGetState(this.comp.guid);t&&this.onHandleReceiving(t)}destroy(){this._isInit&&(this.comp.context.post_render_callbacks.splice(this.comp.context.post_render_callbacks.indexOf(this.onHandleSending),1),this.comp.context.connection.stopListen(this.networkingKey,this.onHandleReceiving),this.comp=null,this._isInit=!1)}notifyChanged(e,t){this._isReceiving||(Ns&&console.log("Property changed: "+e,t),this.hasChanges=!0,this.changedProperties[e]=t)}onHandleSending=()=>{if(!this.hasChanges)return;this.hasChanges=!1;const e=this.comp.context.connection;if(!e||!e.isConnected||!e.isInRoom){for(const t in this.changedProperties)delete this.changedProperties[t];return}for(const t in this.changedProperties){const i=this.changedProperties[t];Ns&&console.log("SEND",this.comp.guid,this.networkingKey),e.send(this.networkingKey,{guid:this.comp.guid,property:t,data:i},Pn.Queued),delete this.changedProperties[t]}};onHandleReceiving=e=>{if(Ns&&console.log("SYNCFIELD RECEIVE",this.comp.name,this.comp.guid,e),!!this._isInit&&this.comp&&e.guid===this.comp.guid)try{this._isReceiving=!0,this.comp[e.property]=e.data}catch(t){console.error(t)}finally{this._isReceiving=!1}}}function mA(o,e){let t=e!==o;return!t&&o&&e&&(Array.isArray(o)&&Array.isArray(e)||typeof o=="object"&&typeof e=="object")&&(t=!0),t}const mh=Symbol("AutoSyncHandler");function gA(o){if(o[mh])return o[mh];const e=Fy.getOrCreateSyncer(o);return e?.init(o),o[mh]=e,e}function fA(o){const e=o[mh];e&&(Fy.removeSyncer(e),e.destroy(),delete o[mh])}const Uy=function(o=null){return function(e,t){let i="";typeof t=="string"?i=t:i=t.name;let n=null,s;typeof o=="string"?s=e[o]:typeof o=="function"&&(s=o),s==null&&(A()||Ns)&&o!=null&&console.warn('syncField: no callback function found for property "'+i+'"','"'+o+'"');const r=e,a=r.__internalAwake;if(typeof a!="function"){(Ns||A())&&console.error('@syncField can currently only used on Needle Engine Components, custom object of type "'+e?.constructor?.name+'" is not supported',e);return}Ns&&console.log(i);const l=Symbol(i);r.__internalAwake=function(){if(this[l]===void 0){if(this[l]=this[i],n=Fy.getOrCreateSyncer(this),Object.getOwnPropertyDescriptor(this,i)?.set===void 0){let h=!1;Object.defineProperty(this,i,{set:function(d){const p=this[l];if(this[l]=d,h){(A()||Ns)&&console.warn("Recursive call detected",i);return}h=!0;try{const m=mA(d,p);Ns&&console.log("SyncField assignment",i,"changed?",m,d,s),m&&s?.call(this,d,p)!==!1&&gA(this)?.notifyChanged(i,d)}finally{h=!1}},get:function(){return this[l]},configurable:!0,enumerable:!0})}n?.init(this),a.call(this)}};const c=r.__internalDestroy;r.__internalDestroy=function(){fA(this),c.call(this)}}};var yA=Object.defineProperty,_p=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&yA(e,t,n),n};const ni=w("debugplayersync"),vp=class FS extends E{static async setupFrom(e,t){const i=ne.getOrCreateFromUrl(e);if(!i.asset){const r=await i.loadAssetAsync();r&&S.getOrAddComponent(r,sn)}const n=new FS;n._internalInit(t),n.asset=i;const s=new M;return s.guid=e,S.addComponent(s,n),n}autoSync=!0;asset;onPlayerSpawned;_localInstance;awake(){this.watchTabVisible(),this.onPlayerSpawned||(this.onPlayerSpawned=new ae)}onEnable(){this.context.connection.beginListen(ie.RoomStateSent,this.onJoinedRoom),this.context.connection.beginListen(ie.JoinedRoom,this.onJoinedRoom),this.context.connection.beginListen(ie.LeftRoom,this.destroyInstance),this.context.connection.isInRoom&&this.onJoinedRoom()}onDisable(){this.context.connection.stopListen(ie.RoomStateSent,this.onJoinedRoom),this.context.connection.stopListen(ie.JoinedRoom,this.onJoinedRoom),this.context.connection.stopListen(ie.LeftRoom,this.destroyInstance)}onJoinedRoom=()=>{ni&&console.log("PlayerSync.joinedRoom. autoSync is set to "+this.autoSync),this.autoSync&&this.getInstance()};async getInstance(){if(this._localInstance)return this._localInstance;if(ni&&console.log("PlayerSync.createInstance",this.asset?.url),!this.asset?.asset&&!this.asset?.url)return console.error('PlayerSync: can not create an instance because "asset" is not set and or has no URL!'),null;this.gameObject.guid||console.warn("PlayerSync: gameObject has no guid! This might cause issues with syncing the player state."),this._localInstance=this.asset?.instantiateSynced({parent:this.gameObject,deleteOnDisconnect:!0},!0);const e=await this._localInstance;if(e){const t=S.getComponentsInChildren(e,sn);if(ni&&console.log(`PlayerSync.createInstance: found ${t?.length} PlayerState components. Owner: ${this.context.connection.connectionId}`),t?.length){for(const i of t)i.owner=this.context.connection.connectionId;this.onPlayerSpawned?.invoke(e)}else this._localInstance=void 0,console.error("<strong>Failed finding PlayerState on "+this.asset?.url+"</strong>: please make sure the asset has a PlayerState component!"),S.destroySynced(e)}else this._localInstance=void 0,console.warn("PlayerSync: failed instantiating asset!");return this._localInstance}destroyInstance=()=>{this._localInstance?.then(e=>{ni&&console.log("PlayerSync.destroyInstance",e),Lc(e,this.context.connection,!0,{saveInRoom:!1})}),this._localInstance=void 0};watchTabVisible(){window.addEventListener("visibilitychange",e=>{if(document.visibilityState==="visible")for(let t=sn.all.length-1;t>=0;t--){const i=sn.all[t];(!i.owner||!this.context.connection.userIsInRoom(i.owner))&&i.doDestroy()}})}};_p([u()],vp.prototype,"autoSync"),_p([u(ne)],vp.prototype,"asset"),_p([u(ae)],vp.prototype,"onPlayerSpawned");let zy=vp;var _1=(o=>(o.OwnerChanged="ownerChanged",o))(_1||{});const Ny=class Lt extends E{static _all=[];static get all(){return Lt._all}static _local=[];static get local(){return Lt._local}static getFor(e){if(e instanceof M)return S.getComponentInParent(e,Lt);if(e instanceof E)return S.getComponentInParent(e.gameObject,Lt)}static isLocalPlayer(e){return Lt.getFor(e)?.isLocalPlayer??!1}static _callbacks={};static addEventListener(e,t){return this._callbacks[e]||(this._callbacks[e]=[]),this._callbacks[e].push(t),t}static removeEventListener(e,t){if(!this._callbacks[e])return;const i=this._callbacks[e].indexOf(t);i>=0&&this._callbacks[e].splice(i,1)}static dispatchEvent(e,t){if(this._callbacks[e])for(const i of this._callbacks[e])i(t)}onOwnerChangeEvent=new ae;onFirstOwnerChangeEvent=new ae;hasOwner=!1;owner;dontDestroy=!1;get isLocalPlayer(){return this.owner===this.context.connection.connectionId}onOwnerChange(e,t){ni&&console.log(`PlayerSync.onOwnerChange: ${t} \u2192 ${e} (me: ${this.context.connection.connectionId})`);const i=Lt._local.indexOf(this);i>=0&&Lt._local.splice(i,1);const n={playerState:this,oldValue:t,newValue:e};if(this.hasOwner||(this.hasOwner=!0,this.onFirstOwnerChangeEvent?.invoke(n)),this.onOwnerChangeEvent?.invoke(n),this.owner===this.context.connection.connectionId){Lt._local.push(this);const r=new CustomEvent("local-owner-changed",{detail:n});this.dispatchEvent(r)}const s=new CustomEvent("owner-changed",{detail:n});this.dispatchEvent(s),Lt.dispatchEvent("ownerChanged",s)}awake(){Lt.all.push(this),ni&&console.log("Registered new PlayerState",this.guid,Lt.all.length-1,Lt.all),this.context.connection.beginListen(ie.UserLeftRoom,this.onUserLeftRoom)}async start(){ni&&console.log("PLAYERSTATE.START, owner: "+this.owner,this.context.connection.usersInRoom([])),this.owner?(this.context.connection.isInRoom||await Ro(300),this.context.connection.userIsInRoom(this.owner)==!1&&(ni&&console.log(`PlayerSync.start \u2192 doDestroy "${this.name}" because user "${this.owner}" is not in room anymore...`,"Currently in room:",...this.context.connection.usersInRoom()),this.doDestroy())):this.owner||(ni&&console.warn("PlayerState.start \u2192 owner is undefined!",this.name),setTimeout(()=>{!this.destroyed&&!this.owner?this.dontDestroy?ni&&console.warn("PlayerState.start \u2192 owner is still undefined but dontDestroy is set to true",this.name):(ni&&console.warn(`PlayerState.start \u2192 owner is still undefined: destroying "${this.name}" instance now`),this.doDestroy()):ni&&console.log("PlayerState.start \u2192 owner is assigned",this.owner)},2e3))}doDestroy(){ni&&console.log("PlayerSync.doDestroy \u2192 syncDestroy",this.name),Lc(this.gameObject,this.context.connection,!0,{saveInRoom:!1})}onDestroy(){if(ni&&console.warn("PlayerState.onDestroy",this.owner),this.context.connection.stopListen(ie.UserLeftRoom,this.onUserLeftRoom),Lt.all.splice(Lt.all.indexOf(this),1),this.isLocalPlayer){const e=Lt._local.indexOf(this);e>=0&&Lt._local.splice(e,1)}}onUserLeftRoom=e=>{if(e.userId===this.owner){ni&&console.log("PLAYERSYNC LEFT",this.owner),this.doDestroy();return}}};_p([Uy(Ny.prototype.onOwnerChange)],Ny.prototype,"owner");let sn=Ny;var bA=Object.defineProperty,Rl=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&bA(e,t,n),n};class lo extends E{position="bottom";showNeedleLogo=!1;showSpatialMenu;createFullscreenButton;createMuteButton;createQRCodeButton;onEnable(){this.applyOptions()}applyOptions(){this.context.menu.setPosition(this.position),this.context.menu.showNeedleLogo(this.showNeedleLogo),this.createFullscreenButton===!0&&this.context.menu.showFullscreenOption(!0),this.createMuteButton===!0&&this.context.menu.showAudioPlaybackOption(!0),this.showSpatialMenu===!0&&this.context.menu.showSpatialMenu(this.showSpatialMenu),this.createQRCodeButton===!0&&(I.isMobileDevice()||this.context.menu.showQRCodeButton(!0))}}Rl([u()],lo.prototype,"position"),Rl([u()],lo.prototype,"showNeedleLogo"),Rl([u()],lo.prototype,"showSpatialMenu"),Rl([u()],lo.prototype,"createFullscreenButton"),Rl([u()],lo.prototype,"createMuteButton"),Rl([u()],lo.prototype,"createQRCodeButton");var _A=Object.defineProperty,Wy=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&_A(e,t,n),n};const gh=w("debugwebxr"),v1=new N().setFromAxisAngle(new b(0,1,0),Math.PI);class Ws extends E{head;leftHand;rightHand;_leftHandMeshes;_rightHandMeshes;_syncTransforms;async onEnterXR(e){if(!this.activeAndEnabled)return;gh&&console.warn("AVATAR ENTER XR",this.guid,this.sourceId,this,this.activeAndEnabled),this._syncTransforms&&(this._syncTransforms.length=0),await this.prepareAvatar();const t=sn.getFor(this);if(t?.owner){const i=this.gameObject.addComponent(Le);i.avatar=this.gameObject,i.connectionId=t.owner,this.context.players.setPlayerView(t.owner,this.head?.asset,Fo.Headset)}else this.context.connection.isConnected?console.error("No player state found for avatar",this):t&&!this.context.connection.isConnected&&(t.dontDestroy=!0)}onLeaveXR(e){const t=this.gameObject.getComponent(Le);t&&t.destroy()}onUpdateXR(e){if(!this.activeAndEnabled)return;const t=sn.isLocalPlayer(this);if(!t)return;const i=e.xr;if(i.rig&&i.rig.gameObject!==this.gameObject.parent&&(this.gameObject.position.set(0,0,0),this.gameObject.rotation.set(0,0,0),this.gameObject.scale.set(1,1,1),i.rig.gameObject.add(this.gameObject)),this._syncTransforms&&t)for(const l of this._syncTransforms)l.fastMode=!0,l.isOwned()||l.requestOwnership();if(this.head&&this.context.mainCamera){const l=this.head.asset;if(l.position.copy(this.context.mainCamera.position),l.position.x*=-1,l.position.z*=-1,l.quaternion.copy(this.context.mainCamera.quaternion),l.quaternion.x*=-1,this.context.time.frameCount%10===0&&this.head.asset){const c=S.getComponentsInChildren(this.head.asset,tn);for(const h of c)h.enabled=!1,h.gameObject.visible=!1}}const n=e.xr.leftController,s=this.leftHand?.asset;n&&s?(s.position.copy(n.gripPosition),s.quaternion.copy(n.gripQuaternion),s.quaternion.multiply(v1),s.visible=n.isTracking,this.updateHandVisibility(n,s,this._leftHandMeshes)):s&&s.visible&&(s.visible=!1);const r=e.xr.rightController,a=this.rightHand?.asset;r&&a?(a.position.copy(r.gripPosition),a.quaternion.copy(r.gripQuaternion),a.quaternion.multiply(v1),a.visible=r.isTracking,this.updateHandVisibility(r,a,this._rightHandMeshes)):a&&a.visible&&(a.visible=!1)}onBeforeRender(){this.context.xr&&this.context.time.frame%10===0&&this.updateRemoteAvatarVisibility()}updateHandVisibility(e,t,i){if(i){const n=e.model&&e.model.visible&&e.model!==t;i.forEach(s=>{Bo(s,!n)})}}updateRemoteAvatarVisibility(){if(this.context.connection.isConnected){const e=sn.getFor(this);if(e&&e.isLocalPlayer==!1){const t=Z.getXRSync(this.context);if(t&&t.hasState(e.owner)){this.tryFindAvatarObjectsIfMissing();const i=this.leftHand?.asset;i&&(i.visible=t?.isTracking(e.owner,"left")??!1);const n=this.rightHand?.asset;n&&(n.visible=t?.isTracking(e.owner,"right")??!1)}if(this.head?.asset){const i=S.getComponentsInChildren(this.head.asset,tn);for(const n of i)n.enabled=!1,n.gameObject.visible=!0}}}}tryFindAvatarObjectsIfMissing(){if(!this.head||!this.leftHand||!this.rightHand){const e={head:this.head,leftHand:this.leftHand,rightHand:this.rightHand};wv.tryFindAvatarObjects(this.gameObject,this.sourceId||"",e),e.head&&(this.head=e.head),e.leftHand&&(this.leftHand=e.leftHand),e.rightHand&&(this.rightHand=e.rightHand)}}async prepareAvatar(){if(this.tryFindAvatarObjectsIfMissing(),this.head)this.head instanceof M&&(this.head=new ne("",this.sourceId,this.head));else{const e=new M;e.name="Head";const t=Ps.createPrimitive(Qa.Cube);e.add(t),this.gameObject.add(e),this.head=new ne("",this.sourceId,e),gh&&console.log("Create head",e)}if(this.rightHand)this.rightHand instanceof M&&(this.rightHand=new ne("",this.sourceId,this.rightHand));else{const e=new M;e.name="Right Hand",this.gameObject.add(e),this.rightHand=new ne("",this.sourceId,e),gh&&console.log("Create right hand",e)}if(this.leftHand)this.leftHand instanceof M&&(this.leftHand=new ne("",this.sourceId,this.leftHand));else{const e=new M;e.name="Left Hand",this.gameObject.add(e),this.leftHand=new ne("",this.sourceId,e),gh&&console.log("Create left hand",e)}await this.loadAvatarObjects(this.head,this.leftHand,this.rightHand),this._leftHandMeshes=[],this.leftHand.asset?.traverse(e=>{e?.isMesh&&this._leftHandMeshes.push(e)}),this._rightHandMeshes=[],this.rightHand.asset?.traverse(e=>{e?.isMesh&&this._rightHandMeshes.push(e)}),sn.isLocalPlayer(this.gameObject)&&(this._syncTransforms=S.getComponentsInChildren(this.gameObject,Tn))}async loadAvatarObjects(e,t,i){const n=e.loadAssetAsync(),s=t.loadAssetAsync(),r=i.loadAssetAsync(),a=new Array;n&&a.push(n),s&&a.push(s),r&&a.push(r);const l=await Zm(a);gh&&console.log("Avatar loaded results:",l)}}Wy([u(ne)],Ws.prototype,"head"),Wy([u(ne)],Ws.prototype,"leftHand"),Wy([u(ne)],Ws.prototype,"rightHand");var vA=Object.defineProperty,wp=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&vA(e,t,n),n};const Vs=w("debugwebxr"),$s=new Array;class Zo extends E{createControllerModel=!0;createHandModel=!0;customLeftHand;customRightHand;static factory=new _P;supportsXR(e){return e==="immersive-vr"||e==="immersive-ar"}_models=new Array;async onXRControllerAdded(e){if(!(e.xr.isVR||e.xr.isPassThrough))return;console.debug("XR Controller Added",e.controller.side,e.controller.index);const{controller:t}=e;if(this.createControllerModel||this.createHandModel){if(t.hand){if(this.createHandModel){const i=await this.loadHandModel(this,t);if(!i||!t.connected||!t.isHand){i?.handObject&&nl(i.handObject,!1),i?.handObject?.destroy();return}this._models.push({controller:t,model:i.handObject,handmesh:i.handmesh}),this._models.sort((n,s)=>n.controller.index-s.controller.index),this.scene.add(i.handObject),t.model=i.handObject}}else if(this.createControllerModel){const i=await t.getModelUrl();if(i){const n=await this.loadModel(t,i);if(!n||!t.connected||t.isHand)return;this._models.push({controller:t,model:n}),this._models.sort((s,r)=>s.controller.index-r.controller.index),this.scene.add(n),n.traverse(s=>{s.layers.set(2),s.matrixAutoUpdate=!1,s.updateMatrix()}),t.model=n}else t.targetRayMode!=="transient-pointer"&&console.warn("XRControllerModel: no model found for "+t.side)}}}onXRControllerRemoved(e){console.debug("XR Controller Removed",e.controller.side,e.controller.index);const t=this._models.findIndex(n=>n.controller===e.controller),i=this._models[t];i&&(this._models.splice(t,1),i.model&&(nl(i.model,!1),i.model.destroy(),i.model=void 0))}onBeforeXR(e,t){this.createHandModel&&(this.customLeftHand||this.customRightHand)&&(t.optionalFeatures=t.optionalFeatures||[],t.optionalFeatures.includes("hand-tracking")||t.optionalFeatures.push("hand-tracking"))}onLeaveXR(e){for(const t of this._models)t&&(t.model&&(nl(t.model,!1),t.model.destroy(),t.model=void 0),t.controller.model===t.model&&(t.controller.model=null));this._models.length=0}onBeforeRender(){if(Z.active&&(Vs&&($s[0]=Date.now()),this.updateRendering(Z.active),Vs)){const e=Date.now()-$s[0];$s.push(e),$s.length>=30&&($s[0]=0,$s.reduce((t,i)=>t+i,0)/$s.length,$s.length=0)}}updateRendering(e){for(let t=0;t<this._models.length;t++){const i=this._models[t];if(!i)continue;const n=i.controller;if(!n.connected){Vs&&console.warn("XRControllerModel.onUpdateXR: controller is not connected anymore",n.side,n.hand);continue}if(i.model&&!i.handmesh)i.model.matrixAutoUpdate=!1,i.model.matrix.copy(n.gripMatrix),i.model.visible=n.isTracking,e.rig?.gameObject.add(i.model);else if(n.inputSource.hand&&i.handmesh){const s=e.referenceSpace,r=this.context.renderer.xr.getHand(n.index);if(s&&e.frame.getJointPose){for(const a of n.inputSource.hand.values()){const l=r.joints[a.jointName];if(l){const c=n.getHandJointPose(a);if(c){const h=c.transform.position,d=c.transform.orientation;l.position.copy(h),l.quaternion.copy(d),l.matrixAutoUpdate=!1}l.visible=c!=null}}i.model&&(i.model.visible=n.isTracking,i.model.visible&&i.model.parent!==e.rig?.gameObject&&e.rig?.gameObject.add(i.model)),i.model?.visible&&(i.handmesh?.updateMesh(),i.model.matrixAutoUpdate=!1,i.model.matrix.identity(),i.model.applyMatrix4(Ha))}}}}async loadModel(e,t){if(!e.connected)return console.warn("XRControllerModel.onXRControllerAdded: controller is not connected anymore",e.side),null;const i=await ne.getOrCreate("",t).instantiate();return nl(i),Z.active?.isPassThrough&&i.traverseVisible(n=>{this.makeOccluder(n)}),i}async loadHandModel(e,t){const i=this.context,n=i.renderer.xr.getHand(t.index);n||(Vs?B.DrawLabel(t.rayWorldPosition,"No hand found for index "+t.index,.05,5):console.warn("No hand found for index "+t.index));const s=new Mo;Tf(s,i),await np(s,i,this.sourceId??"",this.sourceId??"");const r=cy(s);let a="";const l=t.side==="left"?this.customLeftHand:this.customRightHand;l?(a=l.url.split(".").slice(0,-1).join("."),s.setPath("")):(a=t.inputSource.handedness==="left"?"left":"right",s.setPath("https://cdn.jsdelivr.net/npm/@webxr-input-profiles/assets@1.0/dist/profiles/generic-hand/"));const c=new M;nl(c);const h=new vP(c,n,s.path,a,s,d=>{const p=r?.gltf;p?.scene.children?.length===0&&(p.scene.children[0]=d),r?.gltf&&Cn().createBuiltinComponents(e.context,e.sourceId||a,r.gltf,null,r),d.traverse(m=>{m.layers.set(2),Z.active?.isPassThrough&&!l&&this.makeOccluder(m),m instanceof H&&Ve.assignMeshLOD(m,0)}),t.connected||(Vs&&B.DrawLabel(t.rayWorldPosition,"Hand is loaded but not connected anymore",.05,5),d.removeFromParent())});if(Vs&&c.add(new Ci(.5)),t.inputSource.hand){Vs&&console.log(t.inputSource.hand);for(const d of t.inputSource.hand.values())if(n.joints[d.jointName]===void 0){const p=new Co;p.matrixAutoUpdate=!1,p.visible=!0,n.joints[d.jointName]=p,n.add(p)}}else Vs&&B.DrawLabel(t.rayWorldPosition,"No inputSource.hand found for index "+t.index,.05,5);return{handObject:c,handmesh:h}}makeOccluder(e){if(e instanceof H){let t=e.material;t instanceof we&&(t=e.material=t.clone(),t.depthWrite=!0,t.depthTest=!0,t.colorWrite=!1,e.receiveShadow=!1,e.renderOrder=-100)}}}wp([u()],Zo.prototype,"createControllerModel"),wp([u()],Zo.prototype,"createHandModel"),wp([u(ne)],Zo.prototype,"customLeftHand"),wp([u(ne)],Zo.prototype,"customRightHand");class xp extends E{}var wA=Object.defineProperty,Hs=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&wA(e,t,n),n};const Vy=w("debugwebxr");class Bi extends E{movementSpeed=1.5;rotationStep=30;useTeleport=!0;usePinchToTeleport=!0;useTeleportTarget=!1;useTeleportFade=!1;showRays=!0;showHits=!0;isXRMovementHandler=!0;xrSessionMode="immersive-vr";_didApplyRotation=!1;_didTeleport=!1;onUpdateXR(e){const t=e.xr.rig;if(!t?.gameObject||e.xr.isPassThrough)return;const i=e.xr.leftController,n=e.xr.rightController;i&&this.onHandleMovement(i,t.gameObject),n&&(this.onHandleRotation(n,t.gameObject),this.useTeleport&&this.onHandleTeleport(n,t.gameObject))}onLeaveXR(e){for(const t of this._lines)t.removeFromParent();for(const t of this._hitDiscs)t?.removeFromParent()}onBeforeRender(){this.context.xr?.running&&(this.showRays&&this.renderRays(this.context.xr),this.showHits&&this.renderHits(this.context.xr))}onHandleMovement(e,t){const i=e.getStick("xr-standard-thumbstick");if(i.x!=0||i.y!=0){const n=F(i.x,0,i.y);n.multiplyScalar(this.context.time.deltaTimeUnscaled*this.movementSpeed);const s=$e(t);n.multiplyScalar(s.x),n.applyQuaternion(e.xr.poseOrientation),n.y=0,n.applyQuaternion(t.worldQuaternion),A()&&Number.isNaN(n.x)&&console.error("Stick movement resulted in NaN",{stick:i,vec:n}),t.position.add(n),t.updateWorldMatrix(!1,!1);for(const r of t.children)r.updateWorldMatrix(!1,!1)}}onHandleRotation(e,t){if(e._isMxInk)return;const i=e.getStick("xr-standard-thumbstick").x;if(this._didApplyRotation)Math.abs(i)<.3&&(this._didApplyRotation=!1);else if(Math.abs(i)>.5){this._didApplyRotation=!0;const n=i>0?1:-1,s=ee(this.context.mainCamera).clone();t.rotateY(n*j.toRadians(this.rotationStep));const r=ee(this.context.mainCamera).clone().sub(s);r.y=0,t.position.sub(r)}}_teleportBuffer=new Array;onHandleTeleport(e,t){let i=0;if(e.hand&&this.usePinchToTeleport&&e.isTeleportGesture){const n=e.getPointerId("primary");if(n!=null&&this.context.input.getIsPointerIdInUse(n))return;const s=e.getGesture("pinch");s&&(i=s.value)}else i=e.getStick("xr-standard-thumbstick")?.y;if(this._didTeleport)i>=0&&i<.4?this._didTeleport=!1:i<0&&i>-.4&&(this._didTeleport=!1);else if(i>.8){this._didTeleport=!0;const n=this.context.physics.raycastFromRay(e.ray)[0];if(n&&n.object instanceof ja){const r=n.normal?.dot(F(0,1,0));if(r!==void 0&&r<.4)return}let s=n?.point;if(!s&&!this.useTeleportTarget){this._plane||(this._plane=new _r(new b(0,1,0),0));const r=t.worldPosition;this._plane.setFromNormalAndCoplanarPoint(new b(0,1,0),r);const a=e.ray;s=r.clone(),this._plane.intersectLine(new WC(a.origin,F(a.direction).multiplyScalar(1e4).add(a.origin)),s),s.distanceTo(r)>t.scale.x*10&&(s=null)}if(s){if(this.useTeleportTarget&&!S.getComponentInParent(n.object,xp))return;const r=s.clone();if(Vy&&B.DrawSphere(s,.025,16711680,5),this.context.mainCamera?.position){const a=this.context.xr?.getUserOffsetInRig();a&&(a.y=0,r.sub(a),Vy&&B.DrawWireSphere(a.add(r),.025,65280,5))}this._teleportBuffer.push(t.matrix.clone()),this._teleportBuffer.length>10&&this._teleportBuffer.shift(),this.useTeleportFade?e.xr.fadeTransition()?.then(()=>{t.worldPosition=r}):t.worldPosition=r}}else if(i<-.8&&(this._didTeleport=!0,this._teleportBuffer.length>0)){const n=this._teleportBuffer.pop();n&&n.decompose(t.position,t.quaternion,t.scale)}}_plane=null;_lines=[];_hitDiscs=[];_hitDistances=[];_lastHitDistances=[];renderRays(e){for(let t=0;t<this._lines.length;t++){const i=this._lines[t];i&&(i.visible=!1)}for(let t=0;t<e.controllers.length;t++){const i=e.controllers[t];let n=this._lines[t];if(!i.connected||!i.isTracking||!i.ray||i.targetRayMode==="transient-pointer"||!i.hasSelectEvent){n&&(n.visible=!1);continue}n||(n=this.createRayLineObject(),n.scale.z=.5,this._lines[t]=n),i.updateRayWorldPosition(),i.updateRayWorldQuaternion();const s=i.rayWorldPosition,r=i.rayWorldQuaternion;n.position.copy(s),n.quaternion.copy(r);const a=e.rigScale,l=this.usePinchToTeleport&&i.isTeleportGesture,c=this._lastHitDistances[t],h=this._hitDistances[t]!=null,d=c??a;n.scale.set(a,a,d),n.visible=!0,n.layers.disableAll(),n.layers.enable(2);let p=n.material.opacity;l?p=1:this.showHits&&d<e.rigScale*.5?p=0:i.getButton("primary")?.pressed?p=.5:p=h?.2:.1,n.material.opacity=j.lerp(n.material.opacity,p,this.context.time.deltaTimeUnscaled/.1),n.parent!==this.context.scene&&this.context.scene.add(n)}}renderHits(e){for(const t of this._hitDiscs){if(!t)continue;const i=t.controller;if(!i||!i.connected||!i.isTracking){t.visible=!1;continue}}for(let t=0;t<e.controllers.length;t++){const i=e.controllers[t];if(!i.connected||!i.isTracking||!i.ray||!i.hasSelectEvent)continue;let n=this._hitDiscs[t],s=!0;const r=i.getPointerId("primary");r!=null&&this.context.input.getIsPointerIdInUse(r)&&(n&&(n.visible=!1),this._hitDistances[t]=null,this._lastHitDistances[t]=0,s=!1);const a=this.context.time.smoothedFps>=59?1:10;if((this.context.time.frame+i.index)%a!==0&&(s=!1),!s){const h=this._hitDiscs[t];h&&h.visible&&h.hit&&this.updateHitPointerPosition(i,h,h.hit.distance);continue}const l=this.context.physics.raycastFromRay(i.ray,{testObject:this.hitPointRaycastFilter,precise:!1});let c=l.find(h=>this.usePinchToTeleport&&i.isTeleportGesture?!0:this.isObjectWithInteractiveComponent(h.object));if(c||(c=l[0]),n&&(n.controller=i,n.hit=c),this._hitDistances[t]=c?.distance||null,c){this._lastHitDistances[t]=c.distance;const h=e.rigScale??1;Vy&&(B.DrawWireSphere(c.point,.025*h,16711680),B.DrawLabel(F(0,.2,0).add(c.point),c.object.name,.02,0)),n||(n=this.createHitPointObject(),this._hitDiscs[t]=n),n.hit=c,n.visible=c.distance>h*.05;let d=.01*(h+c.distance);const p=i.getButton("primary")?.pressed;p&&(d*=1.1),n.scale.set(d,d,d),n.layers.set(2);let m=n.material.opacity;if(p?m=1:m=c.distance<.15*h?.2:.6,n.material.opacity=j.lerp(n.material.opacity,m,this.context.time.deltaTimeUnscaled/.1),n.visible){if(c.normal){this.updateHitPointerPosition(i,n,c.distance);const g=c.normal.applyQuaternion(_e(c.object));n.quaternion.setFromUnitVectors(xA,g)}else this.updateHitPointerPosition(i,n,c.distance);n.parent!==this.context.scene&&this.context.scene.add(n)}}else this._hitDiscs[t]&&(this._hitDiscs[t].visible=!1)}}isObjectWithInteractiveComponent(e,t=0){return Bu(e)||e.isUI===!0?!0:e.isScene?!1:e.parent?this.isObjectWithInteractiveComponent(e.parent,t+1):!1}updateHitPointerPosition(e,t,i){const n=F(e.rayWorldPosition);n.add(F(0,0,i-.01).applyQuaternion(e.rayWorldQuaternion)),t.position.lerp(n,this.context.time.deltaTimeUnscaled/.05)}hitPointRaycastFilter=e=>e.type==="SkinnedMesh"?"continue in children":!0;createHitPointObject(){const e=new H(new Pd(.3,6,6),new Ce({color:15658734,opacity:.7,transparent:!0,depthTest:!1,depthWrite:!1,side:Pi}));return e.layers.disableAll(),e.layers.enable(2),e}createRayLineObject(){const e=new wP;e.layers.disableAll(),e.layers.enable(2);const t=new xP;e.geometry=t;const i=new Float32Array(9);i.set([0,0,.02,0,0,.4,0,0,1]),t.setPositions(i);const n=new Float32Array(9);n.set([1,1,1,.1,.1,.1,0,0,0]),t.setColors(n);const s=new SP({color:16777215,vertexColors:!0,worldUnits:!0,linewidth:.004,transparent:!0,depthWrite:!1,blending:Eb,dashed:!1});return e.material=s,e}}Hs([u()],Bi.prototype,"movementSpeed"),Hs([u()],Bi.prototype,"rotationStep"),Hs([u()],Bi.prototype,"useTeleport"),Hs([u()],Bi.prototype,"usePinchToTeleport"),Hs([u()],Bi.prototype,"useTeleportTarget"),Hs([u()],Bi.prototype,"useTeleportFade"),Hs([u()],Bi.prototype,"showRays"),Hs([u()],Bi.prototype,"showHits");const xA=new b(0,1,0);var SA=Object.defineProperty,xt=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&SA(e,t,n),n};const fh=w("debugwebxr"),CA=w("debugusdz"),ct=class ic extends E{createVRButton=!0;createARButton=!0;createSendToQuestButton=!0;createQRCode=!0;useDefaultControls=!0;showControllerModels=!0;showHandModels=!0;usePlacementReticle=!0;customARPlacementReticle;usePlacementAdjustment=!0;arScale=1;useXRAnchor=!1;autoPlace=!1;autoCenter=!1;useQuicklookExport=!1;useDepthSensing=!1;useSpatialGrab=!0;defaultAvatar;_playerSync;_createdComponentsInSession=[];_usdzExporter;static activeWebXRComponent=null;awake(){Z.getXRSync(this.context)}onEnable(){window.location.protocol!=="https:"&&be('<a href="https://developer.mozilla.org/en-US/docs/Web/API/WebXR_Device_API" target="_blank">WebXR</a> only works on secure connections (https).'),navigator.xr?.isSessionSupported("immersive-ar").catch(()=>!1).then(e=>{const t=I.isVisionOS()&&!e;(this.useQuicklookExport||t)&&(S.findObjectOfType(ho)||(fh&&console.log("WebXR: Adding USDZExporter"),this._usdzExporter=S.addComponent(this.gameObject,ho),this._usdzExporter.objectToExport=this.context.scene,this._usdzExporter.autoExportAnimations=!0,this._usdzExporter.autoExportAudioSources=!0))}),this.handleCreatingHTML(),this.handleOfferSession(),this.defaultAvatar===!0&&(fh&&console.warn("WebXR: No default avatar set, using static default avatar"),this.defaultAvatar=new ne("https://cdn.needle.tools/static/avatars/DefaultAvatar.glb")),this.defaultAvatar&&(this._playerSync=this.gameObject.getOrAddComponent(zy),this._playerSync.autoSync=!1),this._playerSync&&typeof this.defaultAvatar!="boolean"&&(this._playerSync.asset=this.defaultAvatar,this._playerSync.onPlayerSpawned?.removeEventListener(this.onAvatarSpawned),this._playerSync.onPlayerSpawned?.addEventListener(this.onAvatarSpawned))}onDisable(){this._usdzExporter?.destroy(),this.removeButtons()}async handleOfferSession(){return this.createVRButton&&await Z.isVRSupported()&&this.createVRButton?Z.offerSession("immersive-vr","default",this.context):this.createARButton&&await Z.isARSupported()&&this.createARButton?Z.offerSession("immersive-ar","default",this.context):!1}get session(){return Z.active??null}get sessionMode(){return Z.activeMode??null}get arSessionRoot(){return this._activeWebARSessionRoot}async enterVR(e){return Z.start("immersive-vr",e,this.context)}async enterAR(e){return Z.start("immersive-ar",e,this.context)}exitXR(){Z.stop()}_exitXRMenuButton;_previousXRState=0;_spatialGrabRaycaster;_activeWebARSessionRoot=null;get isActiveWebXR(){return!ic.activeWebXRComponent||ic.activeWebXRComponent===this}onBeforeXR(e,t){if(!this.isActiveWebXR){console.warn(`WebXR: another WebXR component is already active (${ic.activeWebXRComponent?.name}). This is ignored: ${this.name}`);return}if(this.activeAndEnabled===!1||this.destroyed){console.debug("[WebXR] onBeforeXR called on disabled or destroyed component");return}ic.activeWebXRComponent=this,e=="immersive-ar"&&this.useDepthSensing&&(t.optionalFeatures=t.optionalFeatures||[],t.optionalFeatures.push("depth-sensing"))}async onEnterXR(e){if(!this.isActiveWebXR)return;fh&&console.log("WebXR onEnterXR"),this._previousXRState=ri.Global.Mask;const t=e.xr.isVR;if(ri.Global.Set(t?io.VR:io.AR),e.xr.isAR){let i=S.findObjectOfType(yn,this.context,!1);if(!i)if(this.usePlacementReticle){const n=new M;for(const s of this.context.scene.children)n.add(s);this.context.scene.add(n),i=S.addComponent(n,yn),this._createdComponentsInSession.push(i)}else(fh||A())&&console.warn("WebXR: No WebARSessionRoot found in scene and usePlacementReticle is disabled in WebXR component.");this._activeWebARSessionRoot=i,i&&(i.customReticle=this.customARPlacementReticle,i.arScale=this.arScale,i.arTouchTransform=this.usePlacementAdjustment,i.autoPlace=this.autoPlace,i.autoCenter=this.autoCenter,i.useXRAnchor=this.useXRAnchor)}this.useDefaultControls&&this.setDefaultMovementEnabled(!0),(this.showControllerModels||this.showHandModels)&&this.setDefaultControllerRenderingEnabled(!0),this.useSpatialGrab&&(this._spatialGrabRaycaster=S.findObjectOfType(Ca)??void 0,this._spatialGrabRaycaster||(this._spatialGrabRaycaster=this.gameObject.addComponent(Ca))),this.createLocalAvatar(e.xr),e.xr.isScreenBasedAR||(this._exitXRMenuButton=this.context.menu.appendChild({label:"Quit XR",onClick:()=>this.exitXR(),icon:"exit_to_app",priority:2e4}))}onUpdateXR(e){this.isActiveWebXR&&this._spatialGrabRaycaster&&(this._spatialGrabRaycaster.enabled=this.useSpatialGrab)}onLeaveXR(e){if(this._exitXRMenuButton?.remove(),!!this.isActiveWebXR){ri.Global.Set(this._previousXRState),this._playerSync?.destroyInstance();for(const t of this._createdComponentsInSession)t.destroy();this._createdComponentsInSession.length=0,this._activeWebARSessionRoot=null,this.handleOfferSession(),mc(1).then(()=>ic.activeWebXRComponent=null)}}setDefaultMovementEnabled(e){let t=this.gameObject.getComponent(Bi);return!t&&e&&(t=this.gameObject.addComponent(Bi),this._createdComponentsInSession.push(t)),t&&(t.enabled=e),t}setDefaultControllerRenderingEnabled(e){let t=this.gameObject.getComponent(Zo);return!t&&e&&(t=this.gameObject.addComponent(Zo),this._createdComponentsInSession.push(t),t.createControllerModel=this.showControllerModels,t.createHandModel==this.showHandModels),t&&(t.enabled=e),t}async createLocalAvatar(e){this._playerSync&&e.running&&typeof this.defaultAvatar!="boolean"&&(this._playerSync.asset=this.defaultAvatar,await this._playerSync.getInstance())}onAvatarSpawned=e=>{fh&&console.log("WebXR.onAvatarSpawned",e);let t=S.getComponentInChildren(e,Ws);t??=S.addComponent(e,Ws)};getButtonsContainer(){return this.getButtonsFactory()}getButtonsFactory(){return this._buttonFactory||(this._buttonFactory=ur.getOrCreate()),this._buttonFactory}_buttonFactory;handleCreatingHTML(){if(this.createARButton||this.createVRButton||this.useQuicklookExport){if((I.isiOS()&&I.isSafari()||CA)&&this.useQuicklookExport){const e=S.findObjectOfType(ho);if(!e||e&&e.allowCreateQuicklookButton){const t=this.getButtonsFactory().createQuicklookButton();this.addButton(t)}}if(this.createARButton){const e=this.getButtonsFactory().createARButton();this.addButton(e)}if(this.createVRButton){const e=this.getButtonsFactory().createVRButton();this.addButton(e)}}if(this.createSendToQuestButton&&!I.isQuest()&&Z.isVRSupported().then(e=>{if(!e){const t=this.getButtonsFactory().createSendToQuestButton();this.addButton(t)}}),this.createQRCode){const e=tl(lo);if(e&&e.createQRCodeButton===!1)A()&&console.warn("WebXR: QRCode button is disabled in the Needle Menu component");else if(!I.isMobileDevice()){const t=mn.getOrCreate().createQRCode();this.addButton(t)}}}_buttons=[];addButton(e){this._buttons.push(e),this.context.menu.appendChild(e)}removeButtons(){for(const e of this._buttons)e.remove();this._buttons.length=0}};xt([u()],ct.prototype,"createVRButton"),xt([u()],ct.prototype,"createARButton"),xt([u()],ct.prototype,"createSendToQuestButton"),xt([u()],ct.prototype,"createQRCode"),xt([u()],ct.prototype,"useDefaultControls"),xt([u()],ct.prototype,"showControllerModels"),xt([u()],ct.prototype,"showHandModels"),xt([u()],ct.prototype,"usePlacementReticle"),xt([u(ne)],ct.prototype,"customARPlacementReticle"),xt([u()],ct.prototype,"usePlacementAdjustment"),xt([u()],ct.prototype,"arScale"),xt([u()],ct.prototype,"useXRAnchor"),xt([u()],ct.prototype,"autoPlace"),xt([u()],ct.prototype,"autoCenter"),xt([u()],ct.prototype,"useQuicklookExport"),xt([u()],ct.prototype,"useDepthSensing"),xt([u()],ct.prototype,"useSpatialGrab"),xt([u(ne)],ct.prototype,"defaultAvatar");let Sp=ct;const Cp=w("debugusdzbehaviours");class $y{get extensionName(){return"Behaviour"}behaviours=[];addBehavior(e){this.behaviours.push(e)}addAudioClip(e){if(!e||typeof e!="string")return"";const t="audio/"+Pa.getName(e);return this.audioClips.push({clipUrl:e,filesKey:t}),t}behaviourComponents=[];behaviourComponentsCopy=[];audioClips=[];audioClipsCopy=[];targetUuids=new Set;getAllTargetUuids(){return this.targetUuids}onBeforeBuildDocument(e){if(!e.root)return Promise.resolve();const t=[];return e.root.traverse(i=>{S.foreachComponent(i,n=>{const s=n;if(typeof s.createBehaviours=="function"||typeof s.beforeCreateDocument=="function"||typeof s.afterCreateDocument=="function"||typeof s.afterSerialize=="function"){this.behaviourComponents.push(s);const r=s.beforeCreateDocument?.call(s,this,e);r instanceof Promise&&t.push(r)}},!1)}),Cp&&console.log("onBeforeBuildDocument: all components",this.behaviourComponents),Promise.all(t)}onExportObject(e,t,i){for(const n of this.behaviourComponents)n.createBehaviours?.call(n,this,t,i)}onAfterBuildDocument(e){for(const d of this.behaviourComponents)typeof d.afterCreateDocument=="function"&&d.afterCreateDocument(this,e);this.behaviourComponentsCopy=this.behaviourComponents.slice(),this.behaviourComponents.length=0,this.audioClipsCopy=this.audioClips.slice(),this.audioClips.length=0;const t=new Set,i=new Set,n=new Set,s=new Set,r=Cp;let a=`graph LR
1289
+ `))}for(const q of R){const he=s.get(q);he&&$.set(q,he)}return $},m=function(R){const $=p(R),q=l($);return c($,q,R)};const g=n.skinnedMesh.skeleton,f=new Array,y=[],_=[];for(const R of g.bones){y.push(R),_.push(R.uuid);const $=g.boneInverses[g.bones.indexOf(R)];f.push({bone:R,inverse:$})}let v=1e4;for(;_.length<g.bones.length&&v-- >0;)for(const R of y){const $=R.children;for(const q of $)if(_.indexOf(q.uuid)===-1&&g.bones.indexOf(q)!==-1){y.push(q),_.push(q.uuid);const he=g.boneInverses[g.bones.indexOf(q)];f.push({bone:q,inverse:he})}}v<=0&&console.error("Failed to sort bones in skinned mesh",n.skinnedMesh,g.bones,_);for(const R of Zx(g.bones))f.push({bone:R,inverse:R.matrixWorld.clone().invert()});const P=f[0].bone.parent;P||console.error("No bone parent found for skinned mesh during USDZ export",n.skinnedMesh),f.sort((R,$)=>Cl(R.bone,P)>Cl($.bone,P)?1:-1);const k=t.quickLookCompatible,O=[],D=[],L=[],V=[];for(const{bone:R}of f){if(k){const $=R.scale;$.x==0&&($.x=1e-5),$.y==0&&($.y=1e-5),$.z==0&&($.z=1e-5),O.push(new J().compose(R.position,R.quaternion,R.scale))}else O.push(R.matrix.clone());D.push(R.position),L.push(R.quaternion),V.push(R.scale)}const W=f.map(R=>'"'+Cl(R.bone,P)+'"').join(", "),G=f.map(R=>c1(R.inverse.clone().invert())).join(", ");e.beginBlock('def Skeleton "Rig"'),e.appendLine(`uniform matrix4d[] bindTransforms = [${G}]`),e.appendLine(`uniform token[] joints = [${W}]`),e.appendLine('uniform token purpose = "guide"'),e.appendLine(`uniform matrix4d[] restTransforms = [${O.map(R=>c1(R)).join(", ")}]`);const X=m(f.map(R=>R.bone));if(ao){let R=1e7,$=0;for(const q of X.position?.keys()??[])R=Math.min(R,q),$=Math.max($,q);console.log("Time samples",R,$,X)}if(e.beginBlock('def SkelAnimation "_anim"'),e.appendLine(`uniform token[] joints = [${W}]`),e.appendLine(`quatf[] rotations = [${d(L)}]`),X&&X.quaternion){e.beginBlock("quatf[] rotations.timeSamples = {","");const R=a(X.quaternion);for(const $ of R)e.appendLine($);e.closeBlock()}if(e.appendLine(`half3[] scales = [${h(V)}]`),X&&X.scale){e.beginBlock("half3[] scales.timeSamples = {","");const R=r(X.scale);for(const $ of R)e.appendLine($);e.closeBlock()}if(e.appendLine(`float3[] translations = [${h(D)}]`),X&&X.position){e.beginBlock("float3[] translations.timeSamples = {","");const R=r(X.position);for(const $ of R)e.appendLine($);e.closeBlock()}e.closeBlock(),e.closeBlock()}}onSerialize(e,t){if(!this.model)return;const i=this.animationData.get(this.object);if(i)for(let h=0;h<i.length;h++)i[h]===void 0&&(i[h]=new Ne(null,this.object,null));const n=this.ext;this.skinnedMeshExport(e,t,n);const s=this.object,r=this.model,a=this.animationData.get(s);if(!a||s.isSkinnedMesh)return;Ry&&console.log("SERIALIZE",this.model.name,this.object.type,a);const l=Intl.NumberFormat("en-US",{maximumFractionDigits:3,minimumFractionDigits:0,useGrouping:!1});function c(h,d){if(h.some(p=>p&&{position:p.pos,rotation:p.rot,scale:p.scale}[d])){switch(d){case"position":r.needsTranslate=!0,e.beginBlock("double3 xformOp:translate.timeSamples = {","");break;case"rotation":r.needsOrient=!0,e.beginBlock("quatf xformOp:orient.timeSamples = {","");break;case"scale":r.needsScale=!0,e.beginBlock("double3 xformOp:scale.timeSamples = {","");break}for(let p=0;p<h.length;p++){const m=h[p];if(!m)continue;const g=n.getStartTimeByClip(m.clip),f=m.getSortedTimesArray(d==="position",d==="rotation",d==="scale");if(!f||f.length===0){console.error("got an animated object but no time values?",s,m);continue}const y=!m.clip,_=d==="position"&&(m.pos||y),v=d==="rotation"&&(m.rot||y),P=d==="scale"&&(m.scale||y);if(_||v||P){const k=m.clip?.name??"rest",O=m.getDuration();ao&&console.log("Write .timeSamples:",k,g,O,h),e.appendLine("# "+k+": start="+l.format(g*Ne.frameRate)+", length="+l.format(O*Ne.frameRate)+", frames="+m.getFrames())}if(_)for(const{time:k,translation:O}of m.getValues(f,!0,!1,!1)){const D=`${l.format((g+k)*Ne.frameRate)}: (${ce(O.x)}, ${ce(O.y)}, ${ce(O.z)}),`;e.appendLine(D)}if(v)for(const{time:k,rotation:O}of m.getValues(f,!1,!0,!1)){const D=`${l.format((g+k)*Ne.frameRate)}: (${ce(O.w)}, ${ce(O.x)}, ${ce(O.y)}, ${ce(O.z)}),`;e.appendLine(D)}if(P)for(const{time:k,scale:O}of m.getValues(f,!1,!1,!0)){const D=`${l.format((g+k)*Ne.frameRate)}: (${ce(O.x)}, ${ce(O.y)}, ${ce(O.z)}),`;e.appendLine(D)}}e.closeBlock()}}c(a,"position"),c(a,"rotation"),c(a,"scale")}}const iA=w("debugusdz");class Pa{static getName(e){const t=e.split(".").pop();let i=e.split(".").slice(0,-1).join(".").split("/").pop()?.replace(".","_");return i||(i="Audio_"+Math.random().toString(36).substring(2,15)),ji(i)+"."+t}get extensionName(){return"Audio"}files=new Array;onExportObject(e,t,i){const n=S.getComponents(e,Di);if(n.length)for(const s of n){if(!s.clip||typeof s.clip!="string"||!s.playOnAwake)continue;const r=s.clip.split("/").pop()||"Audio",a=Pa.getName(s.clip),l=ji(a);if(!this.files.some(c=>c.path===s.clip)){this.files.push({path:s.clip,name:a});const c=a.toLowerCase();i.quickLookCompatible&&!c.endsWith(".mp3")&&!c.endsWith(".wav")&&!c.endsWith(".m4a")&&console.error("Audio file "+s.clip+" from "+s.name+" is not an MP3 or WAV file. QuickLook may not support playing it.")}i.quickLookCompatible||t.addEventListener("serialize",(c,h)=>{c.appendLine(),c.beginBlock(`def SpatialAudio "${l}"`,"(",!1),c.appendLine(`displayName = "${r}"`),c.closeBlock(")"),c.beginBlock(),c.appendLine(`uniform asset filePath = @audio/${a}@`),c.appendLine(`uniform token auralMode = "${s.spatialBlend>0?"spatial":"nonSpatial"}"`),c.appendLine(`uniform token playbackMode = "${s.loop?"loopFromStage":"onceFromStart"}"`),c.appendLine(`uniform float gain = ${s.volume}`),c.closeBlock()})}}async onAfterSerialize(e){for(const t of this.files){const i="audio/"+t.name;if(e.files[i]){iA&&console.warn("Audio file with name "+i+" already exists in the context. Skipping.");continue}const n=await(await(await fetch(t.path)).blob()).arrayBuffer(),s=new Uint8Array(n);e.files[i]=s}}}var nA=Object.defineProperty,Be=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&nA(e,t,n),n};const f1=w("debugusdzbehaviours");class ea extends E{object;target;duration=1;relativeMotion=!1;coroutine=null;targetPos=new b;targetRot=new N;targetScale=new b;onEnable(){this.context.accessibility.updateElement(this,{role:"button",label:"Move "+(this.object?.name||"object")+" to "+(this.target?.name||"target")+" on click",hidden:!1})}onDisable(){this.context.accessibility.updateElement(this,{hidden:!0})}onDestroy(){this.context.accessibility.removeElement(this)}onPointerEnter(){this.context.input.setCursor("pointer")}onPointerExit(){this.context.input.unsetCursor("pointer")}onPointerClick(e){const t=this.object?.getComponentsInChildren(Ke);if(t)for(const i of t)i.resetVelocities(),i.resetForcesAndTorques();e.use(),this.coroutine&&this.stopCoroutine(this.coroutine),this.relativeMotion?this.coroutine=this.startCoroutine(this.moveRelative()):this.coroutine=this.startCoroutine(this.moveToTarget())}*moveToTarget(){if(!this.target||!this.object)return;const e=ee(this.object).clone(),t=ee(this.target).clone(),i=_e(this.object).clone(),n=_e(this.target).clone(),s=$e(this.object).clone(),r=$e(this.target).clone(),a=e.distanceTo(t),l=i.angleTo(n),c=s.distanceTo(r);if(a<.01&&l<.01&&c<.01){yt(this.object,t),Sn(this.object,n),za(this.object,r),this.coroutine=null;return}let h=0,d=0;for(;h<1;)h+=this.context.time.deltaTime/this.duration,h>1&&(h=1),d=h<.5?4*h*h*h:1-Math.pow(-2*h+2,3)/2,this.targetPos.lerpVectors(e,t,d),this.targetRot.slerpQuaternions(i,n,d),this.targetScale.lerpVectors(s,r,d),yt(this.object,this.targetPos),Sn(this.object,this.targetRot),za(this.object,this.targetScale),yield;this.coroutine=null}*moveRelative(){if(!this.target||!this.object)return;const e=this.object.position.clone(),t=this.object.quaternion.clone(),i=this.object.scale.clone(),n=this.target.position.clone(),s=this.target.quaternion.clone(),r=this.target.scale.clone();n.applyQuaternion(this.object.quaternion),this.targetPos.copy(this.object.position).add(n),this.targetRot.copy(this.object.quaternion).multiply(s),this.targetScale.copy(this.object.scale).multiply(r);let a=0,l=0;for(;a<1;)a+=this.context.time.deltaTime/this.duration,a>1&&(a=1),l=a<.5?4*a*a*a:1-Math.pow(-2*a+2,3)/2,this.object.position.lerpVectors(e,this.targetPos,l),this.object.quaternion.slerpQuaternions(t,this.targetRot,l),this.object.scale.lerpVectors(i,this.targetScale,l),yield;this.coroutine=null}beforeCreateDocument(e){if(this.target&&this.object&&this.gameObject){const t=new jt("Move to "+this.target?.name,$t.tapTrigger(this.gameObject),fe.transformAction(this.object,this.target,this.duration,this.relativeMotion?"relative":"absolute"));e.addBehavior(t)}}}Be([u(M)],ea.prototype,"object"),Be([u(M)],ea.prototype,"target"),Be([u()],ea.prototype,"duration"),Be([u()],ea.prototype,"relativeMotion");const bp=class si extends E{materialToSwitch;variantMaterial;fadeDuration=0;start(){this._objectsWithThisMaterial=this.objectsWithThisMaterial,A()&&this._objectsWithThisMaterial.length<=0&&console.warn('ChangeMaterialOnClick: No objects found with material "'+this.materialToSwitch?.name+'"')}onEnable(){this.context.accessibility.updateElement(this,{role:"button",label:"Change material to "+(this.variantMaterial?.name||"unknown material"),hidden:!1})}onDisable(){this.context.accessibility.updateElement(this,{hidden:!0})}onDestroy(){this.context.accessibility.removeElement(this)}onPointerEnter(e){this.context.input.setCursor("pointer")}onPointerExit(e){this.context.input.unsetCursor("pointer")}onPointerClick(e){if(e.use(),!!this.variantMaterial)for(let t=0;t<this.objectsWithThisMaterial.length;t++){const i=this.objectsWithThisMaterial[t];i.material=this.variantMaterial}}_objectsWithThisMaterial=null;get objectsWithThisMaterial(){return this._objectsWithThisMaterial!=null?this._objectsWithThisMaterial:(this._objectsWithThisMaterial=[],this.variantMaterial&&this.materialToSwitch&&this.context.scene.traverse(e=>{if(e instanceof H)if(Array.isArray(e.material)){for(const t of e.material)if(t===this.materialToSwitch){this.objectsWithThisMaterial.push(e);break}}else e.material===this.materialToSwitch?this.objectsWithThisMaterial.push(e):Yv(e.material,this.materialToSwitch)&&this.objectsWithThisMaterial.push(e)}),this._objectsWithThisMaterial)}selfModel;targetModels;static _materialTriggersPerId={};static _startHiddenBehaviour=null;static _parallelStartHiddenActions=[];async beforeCreateDocument(e,t){this.targetModels=[],si._materialTriggersPerId={},si.variantSwitchIndex=0,this.materialToSwitch&&await Ve.assignTextureLOD(this.materialToSwitch,0),this.variantMaterial&&await Ve.assignTextureLOD(this.variantMaterial,0)}createBehaviours(e,t,i){this.objectsWithThisMaterial.find(n=>n.uuid===t.uuid)&&this.targetModels.push(t),this.gameObject.uuid===t.uuid&&(this.selfModel=t,this.materialToSwitch&&(si._materialTriggersPerId[this.materialToSwitch.uuid]||(si._materialTriggersPerId[this.materialToSwitch.uuid]=[]),si._materialTriggersPerId[this.materialToSwitch.uuid].push(this)))}afterCreateDocument(e,t){if(!this.materialToSwitch)return;const i=si._materialTriggersPerId[this.materialToSwitch.uuid];if(i){const n={};for(const s of i){const r=s.createVariants();r&&r.length>0&&(n[s.selfModel.uuid]=r)}for(const s of i){const r=[];for(const a in n)a!==s.selfModel.uuid&&r.push(...n[a]);s.createAndAttachBehaviors(e,n[s.selfModel.uuid],r)}}delete si._materialTriggersPerId[this.materialToSwitch.uuid]}createAndAttachBehaviors(e,t,i){const n=[],s=Math.max(0,this.fadeDuration);n.push(fe.fadeAction([...this.targetModels,...i],s,!1)),n.push(fe.fadeAction(t,s,!0)),e.addBehavior(new jt("Select_"+this.selfModel.name,$t.tapTrigger(this.selfModel),fe.parallel(...n))),si._parallelStartHiddenActions.push(...t),si._startHiddenBehaviour||(si._startHiddenBehaviour=new jt("StartHidden_"+this.selfModel.name,$t.sceneStartTrigger(),fe.fadeAction(si._parallelStartHiddenActions,s,!1)),e.addBehavior(si._startHiddenBehaviour))}static getMaterialName(e){return ji(e.name||"Material")+"_"+e.id}static variantSwitchIndex=0;createVariants(){if(!this.variantMaterial)return null;const e=[];for(const t of this.targetModels){const i=t.clone();i.name+="_Variant_"+si.variantSwitchIndex+++"_"+si.getMaterialName(this.variantMaterial),i.displayName=i.displayName+": Variant with material "+this.variantMaterial.name,i.material=this.variantMaterial,i.geometry=t.geometry,i.transform=t.transform,(!t.parent||!t.parent.isEmpty())&&rt.createEmptyParent(t),t.parent&&t.parent.add(i),e.push(i)}return e}};Be([u(we)],bp.prototype,"materialToSwitch"),Be([u(we)],bp.prototype,"variantMaterial"),Be([u()],bp.prototype,"fadeDuration");let Ty=bp;const ch=class ze extends E{target;toggleOnClick=!1;targetState=!0;hideSelf=!0;onPointerEnter(){this.context.input.setCursor("pointer")}onPointerExit(){this.context.input.unsetCursor("pointer")}onPointerClick(e){e.use(),!this.toggleOnClick&&this.hideSelf&&(this.gameObject.visible=!1),this.target&&(this.target.visible=this.toggleOnClick?!this.target.visible:this.targetState)}selfModel;selfModelClone;targetModel;toggleModel;createBehaviours(e,t,i){t.uuid===this.gameObject.uuid&&(this.selfModel=t,this.selfModelClone=t.clone())}stateBeforeCreatingDocument=!1;targetStateBeforeCreatingDocument=!1;static clonedToggleIndex=0;static wasVisible=Symbol("usdz_SetActiveOnClick_wasVisible");static toggleClone=Symbol("clone for toggling");static reverseToggleClone=Symbol("clone for reverse toggling");beforeCreateDocument(){this.target&&(this.gameObject[ze.wasVisible]===void 0&&(this.gameObject[ze.wasVisible]=this.gameObject.activeSelf),this.target[ze.wasVisible]===void 0&&(this.target[ze.wasVisible]=this.target.activeSelf),this.stateBeforeCreatingDocument=this.gameObject[ze.wasVisible],this.targetStateBeforeCreatingDocument=this.target[ze.wasVisible],this.gameObject.visible=!0,this.target.visible=!0)}afterCreateDocument(e,t){if(!this.target)return;this.targetModel=t.document.findById(this.target.uuid);const i=this.selfModel;if(this.selfModel&&this.targetModel){let n=this.selfModel,s=this.targetState;if(this.toggleOnClick)if(s=!this.targetStateBeforeCreatingDocument,!this.selfModelClone.geometry)(!this.selfModel.parent||this.selfModel.parent.isEmpty())&&wy.createEmptyParent(this.selfModel),this.toggleModel=this.selfModel.deepClone(),this.toggleModel.name+="_toggle",this.selfModel.parent.add(this.toggleModel);else{if(!this.gameObject[ze.toggleClone]){const l=this.selfModelClone.clone();l.setMatrix(new J),l.name+="_toggle"+ze.clonedToggleIndex++,i.add(l),this.gameObject[ze.toggleClone]=l,console.warn("USDZExport: Toggle "+this.gameObject.name+" doesn't have geometry. It will be deep cloned and nested behaviours will likely not work.")}const a=this.gameObject[ze.toggleClone];if(!this.gameObject[ze.reverseToggleClone]){const l=this.selfModelClone.clone();l.setMatrix(new J),l.name+="_toggleReverse"+ze.clonedToggleIndex++,i.add(l),this.gameObject[ze.reverseToggleClone]=l}this.toggleModel=this.gameObject[ze.reverseToggleClone],(!this.toggleModel.geometry||!a.geometry)&&console.error("triggers without childs and without geometry won't work!",this,i.geometry),n=a,i.geometry=null,i.material=null}if(this.toggleModel){if(this.toggleOnClick){const a=[];a.push(fe.fadeAction(n,0,!1)),a.push(fe.fadeAction(this.toggleModel,0,!0)),a.push(fe.fadeAction(this.targetModel,0,s)),e.addBehavior(new jt("Toggle_"+n.name+"_ToggleTo"+(s?"On":"Off"),$t.tapTrigger(n),fe.parallel(...a)));const l=[];l.push(fe.fadeAction(this.toggleModel,0,!1)),l.push(fe.fadeAction(n,0,!0)),l.push(fe.fadeAction(this.targetModel,0,!s)),e.addBehavior(new jt("Toggle_"+n.name+"_ToggleTo"+(s?"Off":"On"),$t.tapTrigger(this.toggleModel),fe.parallel(...l)))}}else{const a=[];this.hideSelf&&a.push(fe.fadeAction(n,0,!1)),a.push(fe.fadeAction(this.targetModel,0,s)),e.addBehavior(new jt("Toggle_"+n.name+"_ToggleTo"+(s?"On":"Off"),$t.tapTrigger(n),a.length>1?fe.parallel(...a):a[0]))}const r=new Array;this.targetStateBeforeCreatingDocument||r.push(this.targetModel),this.stateBeforeCreatingDocument||r.push(i),this.toggleModel&&r.push(this.toggleModel),fn.add(r,e)}}afterSerialize(e,t){this.gameObject[ze.wasVisible]!==void 0&&(this.gameObject.visible=this.gameObject[ze.wasVisible],delete this.gameObject[ze.wasVisible]),this.target&&this.target[ze.wasVisible]!==void 0&&(this.target.visible=this.target[ze.wasVisible],delete this.target[ze.wasVisible]),delete this.gameObject[ze.toggleClone],delete this.gameObject[ze.reverseToggleClone]}};Be([u(M)],ch.prototype,"target"),Be([u()],ch.prototype,"toggleOnClick"),Be([u()],ch.prototype,"targetState"),Be([u()],ch.prototype,"hideSelf");let Ay=ch;class fn extends E{static _fadeBehaviour;static _fadeObjects=[];static add(e,t){const i=Array.isArray(e)?e:[e];for(const n of i)fn._fadeObjects.includes(n)||(console.log("adding hide on start",n),fn._fadeObjects.push(n));fn._fadeBehaviour===void 0&&(fn._fadeBehaviour=new jt("HideOnStart",$t.sceneStartTrigger(),fe.fadeAction(fn._fadeObjects,0,!1)),t.addBehavior(fn._fadeBehaviour))}start(){S.setActive(this.gameObject,!1)}createBehaviours(e,t,i){t.uuid===this.gameObject.uuid&&(this.wasVisible||fn.add(t,e))}wasVisible=!1;beforeCreateDocument(){this.wasVisible=S.isActiveSelf(this.gameObject)}}class Ol extends E{target;duration=.5;motionType="bounce";onEnable(){this.context.accessibility.updateElement(this,{role:"button",label:"Emphasize "+this.target?.name+" on click",hidden:!1})}onDisable(){this.context.accessibility.updateElement(this,{hidden:!0})}onDestroy(){this.context.accessibility.removeElement(this)}beforeCreateDocument(){}createBehaviours(e,t,i){if(this.target&&t.uuid===this.gameObject.uuid){const n=new jt("emphasize "+this.name,$t.tapTrigger(this.gameObject),fe.emphasize(this.target,this.duration,this.motionType,void 0,"basic"));e.addBehavior(n)}}afterCreateDocument(e,t){}}Be([u()],Ol.prototype,"target"),Be([u()],Ol.prototype,"duration"),Be([u()],Ol.prototype,"motionType");class zs extends E{target;clip="";toggleOnClick=!1;trigger="tap";ensureAudioSource(){if(!this.target){const e=this.gameObject.addComponent(Di);e&&(this.target=e,e.spatialBlend=1,e.volume=1,e.loop=!1,e.preload=!0)}}onEnable(){this.context.accessibility.updateElement(this,{role:"button",label:"Play audio: "+(this.clip||this.target?.clip||"unknown clip"),hidden:!1})}onDisable(){this.context.accessibility.updateElement(this,{hidden:!0})}onDestroy(){this.context.accessibility.removeElement(this)}onPointerEnter(){this.context.input.setCursor("pointer")}onPointerExit(){this.context.input.unsetCursor("pointer")}onPointerClick(e){e.use(),!(!this.target?.clip&&!this.clip)&&(this.ensureAudioSource(),this.target&&(this.target.isPlaying&&this.toggleOnClick?this.target.stop():(!this.toggleOnClick&&this.target.isPlaying&&this.target.stop(),this.clip?this.target.play(this.clip):this.target.play())))}createBehaviours(e,t,i){if(!(!this.target&&!this.clip)&&t.uuid===this.gameObject.uuid){const n=this.clip?this.clip:this.target?this.target.clip:void 0;if(!n||typeof n!="string")return;const s=this.target?this.target.gameObject:this.gameObject;Pa.getName(n);const r=this.target?this.target.volume:1,a=this.target&&this.target.spatialBlend==0?"nonSpatial":"spatial";let l=!1;this.gameObject.traverse(p=>{p instanceof H&&p.visible&&(l=!0)}),l=!0;const c=e.addAudioClip(n);let h=fe.playAudioAction(s,c,"play",r,a);this.target&&this.target.loop&&(h=fe.sequence(h).makeLooping());const d=this.name?"_"+this.name:"";if(l&&this.trigger==="tap"){this.toggleOnClick&&(h.multiplePerformOperation="stop");const p=new jt("playAudio"+d,$t.tapTrigger(t),h);e.addBehavior(p)}if(this.target&&this.target.playOnAwake&&this.target.enabled)if(l&&this.trigger==="tap")console.warn("USDZExport: Audio sources that are played on tap can't also auto-play at scene start due to a QuickLook bug.");else{const p=new jt("playAudioOnStart"+d,$t.sceneStartTrigger(),h);e.addBehavior(p)}}}}Be([u(Di)],zs.prototype,"target"),Be([u(URL)],zs.prototype,"clip"),Be([u()],zs.prototype,"toggleOnClick");const Iy=class _o extends E{animator;stateName;trigger="tap";animation;get target(){return this.animator?.gameObject||this.animation?.gameObject}onEnable(){this.context.accessibility.updateElement(this,{role:"button",label:"Plays animation "+(this.stateName||"")+" on "+(this.target?this.target.name:""),hidden:!1})}onDisable(){this.context.accessibility.updateElement(this,{hidden:!0})}onDestroy(){this.context.accessibility.removeElement(this)}onPointerEnter(){this.context.input.setCursor("pointer"),this.context.accessibility.hover(this,"Click to play animation "+(this.stateName||"")+" on "+(this.target?this.target.name:""))}onPointerExit(){this.context.input.unsetCursor("pointer")}onPointerClick(e){e.use(),this.target&&this.stateName&&(this.context.accessibility.focus(this),this.animator?.play(this.stateName,0,0,.1))}selfModel;stateAnimationModel;animationSequence=new Array;animationLoopAfterSequence=new Array;randomOffsetNormalized=0;createBehaviours(e,t,i){t.uuid===this.gameObject.uuid&&(this.selfModel=t)}static animationActions=[];static rootsWithExclusivePlayback=new Set;afterSerialize(){if(_o.rootsWithExclusivePlayback.size>1){const e='Multiple root objects targeted by more than one animation. To work around QuickLook bug FB13410767, animations will be set as "exclusive" and activating them will stop other animations being marked as exclusive.';A()&&be(e),console.warn(e,..._o.rootsWithExclusivePlayback)}_o.animationActions=[],_o.rootsWithExclusivePlayback=new Set}afterCreateDocument(e,t){if(this.animationSequence===void 0&&this.animationLoopAfterSequence===void 0||!this.stateAnimationModel||!this.target)return;const i=t.document,n=t.extensions.find(a=>a instanceof yp);if(!n)return;const s=n.getClipCount(this.target)>1;s&&(A()&&console.warn("Setting exclusive playback for "+this.target.name+"@"+this.stateName+" because it has "+n.getClipCount(this.target)+" animations. This works around QuickLook bug FB13410767."),_o.rootsWithExclusivePlayback.add(this.target));const r=this.name?this.name:"";i.traverse(a=>{if(a.uuid===this.target?.uuid){const l=_o.getActionForSequences(i,a,this.animationSequence,this.animationLoopAfterSequence,this.randomOffsetNormalized),c=new jt(this.trigger+"_"+r+"_toPlayAnimation_"+this.stateName+"_on_"+this.target?.name,this.trigger=="tap"?$t.tapTrigger(this.selfModel):$t.sceneStartTrigger(),l);s&&c.makeExclusive(!0),e.addBehavior(c)}})}static getActionForSequences(e,t,i,n,s){const r=(l,c)=>{let h=_o.animationActions.find(d=>d.affectedObjects==l&&d.start==c.start&&d.duration==c.duration&&d.animationSpeed==c.speed);return h||(h=fe.startAnimationAction(l,c),_o.animationActions.push(h)),h},a=fe.sequence();if(i&&i.length>0)for(const l of i)a.addAction(r(t,l));if(n&&n.length>0){const l=a.actions.length==0?a:fe.sequence();for(const c of n)l.addAction(r(t,c));l.makeLooping(),a!==l&&a.addAction(l)}return s&&s>0&&a.actions.unshift(fe.waitAction(s)),a}static getAndRegisterAnimationSequences(e,t,i){if(!t)return;const n=t.getComponent(_t),s=t.getComponent(Ut);if(!n&&!s)return;if(n&&!i)throw new Error("PlayAnimationOnClick: No stateName specified for animator "+n.name+" on "+t.name);let r=[],a=[];if(s){const g=e.registerAnimation(t,s.clip);g&&(s.loop?a.push(g):r.push(g));let f=0;if(s.minMaxOffsetNormalized){const y=s.minMaxOffsetNormalized.x,_=s.minMaxOffsetNormalized.y;f=(s.clip?.duration||1)*(y+Math.random()*(_-y))}return{animationSequence:r,animationLoopAfterSequence:a,randomTimeOffset:f}}const l=n?.runtimeAnimatorController;let c=l?.findState(i),h=[],d=[];if(l&&c){const g=new Array;g.push(c);let f=!1;for(;g.length<100;){if(!c||c===null||!c.transitions||c.transitions.length===0){c.motion?.isLooping&&(f=!0);break}const y=c.transitions.find(v=>v.conditions.length===0),_=y?l.getState(y.destinationState,0):null;if(_&&g.includes(_)){c=_,f=!0;break}else if(y){if(c=_,!c)break;g.push(c)}else{f=c.motion?.isLooping??!1;break}}if(f&&c){const y=g.indexOf(c);h=g.slice(0,y),d=g.slice(y),f1&&console.log("found loop from "+i,"states until loop",h,"states looping",d)}else h=g,d=[],f1&&console.log("found no loop from "+i,"states",h);if(!d.length){const y=h[h.length-1],_=y.motion?.clip;if(_){let v;if(e.holdClipMap.has(_))v=e.holdClipMap.get(_);else{const P=y.name+"_hold";v=_.clone(),v.duration=1,v.name=P;const k=_.duration;v.tracks=_.tracks.map(O=>{const D=O.clone();D.times=new Float32Array([0,k]);const L=O.values.length,V=O.getValueSize(),W=O.values.slice(L-V,L);return D.values=new Float32Array(2*V),D.values.set(W,0),D.values.set(W,V),D}),v.name=P,e.holdClipMap.set(_,v)}if(v){const P={name:v.name,motion:{clip:v,isLooping:!1,name:v.name},speed:1,transitions:[],behaviours:[],hash:y.hash+1};d.push(P)}}}}if(h.length===1&&(!h[0].motion?.clip||h[0].motion?.clip.tracks?.length===0)){r=new Array;const g=e.registerAnimation(t,null);g&&r.push(g);return}if(h=h.filter(g=>g.motion?.clip&&g.motion?.clip.tracks?.length>0),d=d.filter(g=>g.motion?.clip&&g.motion?.clip.tracks?.length>0),h.length===0&&d.length===0){console.warn("No clips found for state "+i+" on "+n?.name+", can't export animation data");return}const p=(g,f)=>{if(!t)return;const y=e.registerAnimation(t,g.motion.clip??null);y?(y.speed=g.speed,f.push(y)):console.warn("Couldn't register animation for state "+g.name+" on "+n?.name)};if(h.length>0){r=new Array;for(const g of h)p(g,r)}if(d.length>0){a=new Array;for(const g of d)p(g,a)}let m=0;if(n&&l&&n.minMaxOffsetNormalized){const g=n.minMaxOffsetNormalized.x,f=n.minMaxOffsetNormalized.y;m=((h.length?h[0]:d.length?d[0]:null)?.motion.clip?.duration||1)*(g+Math.random()*(f-g))}return{animationSequence:r,animationLoopAfterSequence:a,randomTimeOffset:m}}createAnimation(e,t,i){if(!this.target||!this.animator&&!this.animation)return;const n=_o.getAndRegisterAnimationSequences(e,this.target,this.stateName);n&&(this.animationSequence=n.animationSequence,this.animationLoopAfterSequence=n.animationLoopAfterSequence,this.randomOffsetNormalized=n.randomTimeOffset,this.stateAnimationModel=t)}};Be([u(_t)],Iy.prototype,"animator"),Be([u()],Iy.prototype,"stateName");let hh=Iy;class kl extends E{getType(){}target;getDuration(){}}Be([u(M)],kl.prototype,"target");class dh extends E{target}Be([u(kl)],dh.prototype,"target");class uh extends kl{type=1;duration=1;getType(){switch(this.type){case 1:return"hide";case 0:return"show"}}getDuration(){return this.duration}}Be([u()],uh.prototype,"type"),Be([u()],uh.prototype,"duration");class Ly extends dh{}const oA=100,sA=200,rA=300;class ur{static _instance;static create(){return new ur}static getOrCreate(){return this._instance||(this._instance=this.create()),this._instance}get isSecureConnection(){return window.location.protocol==="https:"}get quicklookButton(){return this._quicklookButton}_quicklookButton;get arButton(){return this._arButton}_arButton;get vrButton(){return this._vrButton}_vrButton;get sendToQuestButton(){return this._sendToQuestButton}_sendToQuestButton;get qrButton(){return mn.getOrCreate().createQRCode()}createQuicklookButton(){if(this._quicklookButton)return this._quicklookButton;const e=document.createElement("button");this._quicklookButton=e,e.dataset.needle="quicklook-button";const t=I.supportsQuickLookAR();let i="View in AR";I.isVisionOS()?i="View in AR":(t||I.isiOS())&&(i="Open in Quicklook"),e.innerText=i,e.prepend(Ot("view_in_ar")),Ms.setElementPriority(e,sA);let n=!1,s=null;return e.addEventListener("click",()=>{s=tl(ho),s||(n=!0,s=new ho),n&&(s.objectToExport=U.Current.scene),s?(e.classList.add("this-mode-is-requested"),s.exportAndOpen().then(()=>{e.classList.remove("this-mode-is-requested")}).catch(r=>{e.classList.remove("this-mode-is-requested"),console.error(r)})):console.warn("No USDZExporter component found in the scene")}),this.hideElementDuringXRSession(e),e}createARButton(e){if(this._arButton)return this._arButton;const t="immersive-ar",i=document.createElement("button");return this._arButton=i,i.classList.add("webxr-button"),i.dataset.needle="webxr-ar-button",i.innerText="Enter AR",i.prepend(Ot("view_in_ar")),i.title="Click to start an AR session",i.addEventListener("click",()=>Z.start(t,e)),Ms.setElementPriority(i,rA),this.updateSessionSupported(i,t),this.listenToXRSessionState(i,t),this.hideElementDuringXRSession(i),this.isSecureConnection||(i.disabled=!0,i.title="WebXR requires a secure connection (HTTPS)"),I.isMozillaXR()||navigator.xr?.addEventListener("devicechange",()=>this.updateSessionSupported(i,t)),i}createVRButton(e){if(this._vrButton)return this._vrButton;const t="immersive-vr",i=document.createElement("button");return this._vrButton=i,i.classList.add("webxr-button"),i.dataset.needle="webxr-vr-button",i.innerText="Enter VR",i.prepend(Ot("panorama_photosphere")),i.title="Click to start a VR session",i.addEventListener("click",()=>Z.start(t,e)),Ms.setElementPriority(i,oA),this.updateSessionSupported(i,t),this.listenToXRSessionState(i,t),this.hideElementDuringXRSession(i),this.isSecureConnection||(i.disabled=!0,i.title="WebXR requires a secure connection (HTTPS)"),I.isMozillaXR()||navigator.xr?.addEventListener("devicechange",()=>this.updateSessionSupported(i,t)),i}createSendToQuestButton(){if(this._sendToQuestButton)return this._sendToQuestButton;const e="https://oculus.com/open_url/?url=",t=document.createElement("button");return this._sendToQuestButton=t,t.dataset.needle="webxr-sendtoquest-button",t.innerText="Open on Quest",t.prepend(Ot("share_windows")),t.title="Click to send this page to the Oculus Browser on your Quest",t.addEventListener("click",()=>{const i=encodeURIComponent(window.location.href),n=e+i;window.open(n)==null&&Oe("This page doesn't allow popups. Please paste "+n+" into your browser.")}),this.listenToXRSessionState(t),this.hideElementDuringXRSession(t),I.isMozillaXR()||navigator.xr?.addEventListener("devicechange",()=>{navigator.xr?.isSessionSupported("immersive-vr")?t.style.display="none":t.style.display=""}),t}createQRCode(){return mn.getOrCreate().createQRCode()}updateSessionSupported(e,t){if(!(t==="immersive-ar"&&I.isiOS()&&!I.isVisionOS())){if(!("xr"in navigator)){e.style.display="none";return}Z.isSessionSupported(t).then(i=>{e.style.display=i?"":"none",A()&&!i&&console.log('[WebXR] "'+t+'" is not supported on this device. Make sure your server runs using HTTPS and you have a device connected that supports '+t)})}}hideElementDuringXRSession(e){Qd(t=>{e["previous-display"]=e.style.display,e.style.setProperty("display","none","important")}),xg(t=>{e["previous-display"]!=null&&(e.style.display=e["previous-display"])})}listenToXRSessionState(e,t){t&&(Z.onSessionRequestStart(i=>{i.mode===t?e.classList.add("this-mode-is-requested"):(e["was-disabled"]=e.disabled,e.disabled=!0,e.classList.add("other-mode-is-requested"))}),Z.onSessionRequestEnd(i=>{e.classList.remove("this-mode-is-requested"),e.classList.remove("other-mode-is-requested"),e.disabled=e["was-disabled"]}))}}var aA=Object.defineProperty,lA=Object.getOwnPropertyDescriptor,wt=(o,e,t,i)=>{for(var n=i>1?void 0:i?lA(e,t):e,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&aA(e,t,n),n};const ph=w("debugspriterenderer"),cA=w("wireframe");class ka{static cache={};static getOrCreateGeometry(e){if(e.__cached_geometry)return e.__cached_geometry;if(e.guid&&ka.cache[e.guid])return ph&&console.log("Take cached geometry for sprite",e.guid),ka.cache[e.guid];const t=new wn;e.__cached_geometry=t;const i=new Float32Array(e.triangles.length*3),n=new Float32Array(e.triangles.length*2);for(let s=0;s<e.triangles.length;s+=1){const r=e.triangles[s];i[s*3]=-e.vertices[r].x,i[s*3+1]=e.vertices[r].y,i[s*3+2]=0;const a=e.uv[r];n[s*2]=a.x,n[s*2+1]=1-a.y}return t.setAttribute("position",new ft(i,3)),t.setAttribute("uv",new ft(n,2)),e.guid&&(this.cache[e.guid]=t),ph&&console.log("Built sprite geometry",e,t),t}}class hA{x;y}function y1(o){o&&(o.colorSpace!=ko&&(o.colorSpace=ko,o.needsUpdate=!0),o.minFilter==Ad&&o.magFilter==Ad&&(o.anisotropy=1,o.needsUpdate=!0))}let Yo=class{constructor(o){o&&(this.texture=o,this.triangles=[0,1,2,0,2,3],this.uv=[{x:0,y:0},{x:1,y:0},{x:1,y:1},{x:0,y:1}],this.vertices=[{x:-.5,y:-.5},{x:.5,y:-.5},{x:.5,y:.5},{x:-.5,y:.5}])}guid;texture;triangles;uv;vertices;__cached_geometry;get mesh(){return this._mesh||(this._mesh=new H(ka.getOrCreateGeometry(this),this.material)),this._mesh}_mesh;get material(){return this._material||(this.texture&&y1(this.texture),this._material=new Ce({map:this.texture,color:16777215,side:Pi,transparent:!0})),this._material}_material;getGeometry(){return ka.getOrCreateGeometry(this)}};wt([u()],Yo.prototype,"guid",2),wt([u(Se)],Yo.prototype,"texture",2),wt([Ye()],Yo.prototype,"triangles",2),wt([Ye()],Yo.prototype,"uv",2),wt([Ye()],Yo.prototype,"vertices",2);const Dy=Symbol("spriteOwner");class Ml{sprites;constructor(){this.sprites=[]}}wt([u(Yo)],Ml.prototype,"sprites",2);const jy=class hb{static create(){const e=new hb;return e.spriteSheet=new Ml,e}constructor(){}clone(){const e=new hb;return e.index=this.index,e.spriteSheet=this.spriteSheet,e}set sprite(e){e&&(this.spriteSheet?((this.index===null||this.index===void 0)&&(this.index=0),this.spriteSheet.sprites[this.index]=e):(this.spriteSheet=new Ml,this.spriteSheet.sprites=[e],this.index=0))}get sprite(){if(this.spriteSheet)return this.spriteSheet.sprites[this.index]}spriteSheet;index=0;update(e){if(!this.spriteSheet)return;const t=this.index;if(t<0||t>=this.spriteSheet.sprites.length)return;const i=this.spriteSheet.sprites[t],n=i?.texture;if(n&&(y1(n),!i.__hasLoadedProgressive)){i.__hasLoadedProgressive=!0;const s=n;Ve.assignTextureLOD(n,0).then(r=>{r instanceof Se&&(i.texture=r,e?.map===s&&(e.map=r,e.needsUpdate=!0))})}}};wt([u(Ml)],jy.prototype,"spriteSheet",2),wt([u()],jy.prototype,"index",2);let El=jy;class yi extends E{drawMode=0;size={x:1,y:1};color;sharedMaterial;transparent=!0;cutoutThreshold=0;castShadows=!1;renderOrder=0;toneMapped=!0;set texture(e){if(!this._spriteSheet)return;const t=this._spriteSheet.spriteSheet?.sprites[this.spriteIndex];t&&(t.texture=e,this.updateSprite())}addSprite(e,t=!1){if(this._spriteSheet||(this._spriteSheet=El.create()),!this._spriteSheet.spriteSheet)return-1;this._spriteSheet.spriteSheet?.sprites.push(e);const i=this._spriteSheet.spriteSheet?.sprites.length-1;return t&&(this.spriteIndex=i),i}get sprite(){return this._spriteSheet}set sprite(e){if(e!==this._spriteSheet)if(typeof e=="number"){const t=Math.round(e);ph&&console.log("[SpriteSheet] Set index to "+t+" (was "+this.spriteIndex+")",e),this.spriteIndex=t}else e instanceof Yo?(this._spriteSheet||(this._spriteSheet=El.create()),this._spriteSheet.sprite!=e&&(this._spriteSheet.sprite=e),this.updateSprite()):e!=this._spriteSheet&&(this._spriteSheet=e,this.updateSprite())}set spriteIndex(e){this._spriteSheet&&(this._spriteSheet.index=e,this.updateSprite())}get spriteIndex(){return this._spriteSheet?.index??0}get spriteFrames(){return this._spriteSheet?.spriteSheet?.sprites.length??0}_spriteSheet;_currentSprite;awake(){this._currentSprite=void 0,this._spriteSheet?this._spriteSheet=this._spriteSheet.clone():this._spriteSheet=El.create(),ph&&console.log("Awake",this.name,this,this.sprite)}start(){this._currentSprite?this.gameObject&&this.gameObject.add(this._currentSprite):this.updateSprite()}updateSprite(e=!1){if(!this.__didAwake&&!e)return!1;const t=this._spriteSheet;if(!t?.spriteSheet?.sprites)return console.warn("SpriteRenderer has no data or spritesheet assigned..."),!1;const i=t.spriteSheet.sprites[this.spriteIndex];if(!i)return ph&&console.warn("Sprite not found",this.spriteIndex,t.spriteSheet.sprites),!1;if(this._currentSprite)this._currentSprite.geometry=ka.getOrCreateGeometry(i),this._currentSprite.material.map=i.texture;else{const n=new Ce({color:16777215,side:Pi});if(cA&&(n.wireframe=!0),this.color&&(n.color||(n.color=new oe),n.color.copy(this.color),n.opacity=this.color.alpha),n.transparent=!0,n.toneMapped=this.toneMapped,n.depthWrite=!1,i.texture&&!n.wireframe){let s=i.texture;s[Dy]!==void 0&&s[Dy]!==this&&this.spriteFrames>1&&(s=i.texture=s.clone()),s[Dy]=this,n.map=s}this.sharedMaterial=n,this._currentSprite=new H(ka.getOrCreateGeometry(i),n),this._currentSprite.renderOrder=Math.round(this.renderOrder),Ve.assignTextureLOD(n,0)}return this._currentSprite.parent!==this.gameObject&&(this.drawMode===2&&this._currentSprite.scale.set(this.size.x,this.size.y,1),this.gameObject&&this.gameObject.add(this._currentSprite)),this._currentSprite&&this._currentSprite.layers.set(this.layer),this.sharedMaterial&&(this.sharedMaterial.alphaTest=this.cutoutThreshold,this.sharedMaterial.transparent=this.transparent),this._currentSprite.castShadow=this.castShadows,t?.update(this.sharedMaterial),!0}}wt([u()],yi.prototype,"drawMode",2),wt([u(hA)],yi.prototype,"size",2),wt([u(se)],yi.prototype,"color",2),wt([u(we)],yi.prototype,"sharedMaterial",2),wt([u()],yi.prototype,"transparent",2),wt([u()],yi.prototype,"cutoutThreshold",2),wt([u()],yi.prototype,"castShadows",2),wt([u()],yi.prototype,"renderOrder",2),wt([u()],yi.prototype,"toneMapped",2),wt([u(El)],yi.prototype,"sprite",1);const b1=w("debugwebxr"),dA=new J().makeRotationY(Math.PI);class yn extends E{static _eventListeners={};static onPlaced(e){const t="placed";return this._eventListeners[t]||(this._eventListeners[t]=[]),this._eventListeners[t].push(e),()=>{const i=this._eventListeners[t].indexOf(e);i>=0&&this._eventListeners[t].splice(i,1)}}static _hasPlaced=!1;static get hasPlaced(){return this._hasPlaced}get arScale(){return this._arScale}set arScale(e){this._arScale=Math.max(1e-6,e),this.onSetScale()}_arScale=1;invertForward=!1;customReticle;arTouchTransform=!0;autoPlace=!1;autoCenter=!1;useXRAnchor=!1;_isPlacing=!0;_startOffset=new J;_createdPlacementObject=null;_reparentedComponents=[];_placementScene=new Hi;_reticle=[];_hits=[];_placementStartTime=-1;_rigPlacementMatrix;_anchor=null;userInput;onEnable(){this.customReticle?.preload()}supportsXR(e){return e==="immersive-ar"}onEnterXR(e){b1&&console.log("ENTER WEBXR: SessionRoot start..."),this._anchor=null,yn._hasPlaced=!1,this.gameObject.updateMatrixWorld(),this._startOffset.copy(this.gameObject.matrixWorld);const t=new M;this._createdPlacementObject=t,t.name="AR Session Root",this._placementScene.name="AR Placement Scene",this._placementScene.children.length=0;for(let i=this.context.scene.children.length-1;i>=0;i--){const n=this.context.scene.children[i];this._placementScene.add(n)}if(this.context.scene.add(t),this.autoCenter){const i=Ri(this._placementScene.children),n=i.getCenter(new b),s=i.getSize(new b),r=new J;r.makeTranslation(n.x,n.y-s.y*.5,n.z),this._startOffset.multiply(r)}this._reparentedComponents.length=0,this._reparentedComponents.push({comp:this,originalObject:this.gameObject}),S.addComponent(t,this);for(const i of this._reticle)Ii(i);this._reticle.length=0,this._isPlacing=!0,this.context.input.addEventListener("pointerup",this.onPlaceScene,{queue:di.Early})}onLeaveXR(){this.context.input.removeEventListener("pointerup",this.onPlaceScene,{queue:di.Early}),this.onRevertSceneChanges(),this._anchor=null,yn._hasPlaced=!1,this._rigPlacementMatrix=void 0}onUpdateXR(e){if(e.xr.isTrackingImages){for(const t of this._reticle)t.visible=!1;return}if(this._isPlacing){const t=e.xr.rig?.gameObject;t&&t.parent!==this.context.scene&&this.context.scene.add(t);let i=!1;if(e.xr.isPassThrough&&e.xr.controllers.length>0&&!this.autoPlace)for(const n of e.xr.controllers){const s=n.getHitTest();s&&(i=!0,this.updateReticleAndHits(e.xr,n.index,s,e.xr.rigScale))}if(!i){const n=e.xr.getHitTest();n&&this.updateReticleAndHits(e.xr,0,n,e.xr.rigScale)}}else{if(this._anchor&&e.xr.referenceSpace){const t=e.xr.frame.getPose(this._anchor.anchorSpace,e.xr.referenceSpace);if(t&&this.context.time.frame%20===0){const i=e.xr.convertSpace(t.transform),n=this._reticle[0];n&&(n.position.copy(i.position),n.quaternion.copy(i.quaternion),this.onApplyPose(n))}}if(this.arTouchTransform?(this.userInput||(this.userInput=new Sm(this.context)),this.userInput?.enable()):this.userInput?.disable(),this.arTouchTransform&&this.userInput?.hasChanged){if(e.xr.rig){const t=e.xr.rig.gameObject;this.userInput.applyMatrixTo(t.matrix,!0),t.matrix.decompose(t.position,t.quaternion,t.scale),this.userInput.factor=t.scale.x}this.userInput.reset()}}}updateReticleAndHits(e,t,i,n){this._hits[t]=i.hit;let s=this._reticle[t];if(!s){if(this.customReticle)if(this.customReticle.asset)s=Ur(this.customReticle.asset);else{this.customReticle.loadAssetAsync();return}else s=new H(new NC(.07,.09,32).rotateX(-Math.PI/2),new Ce({side:Pi,depthTest:!1,depthWrite:!1,transparent:!0,opacity:1,color:15658734})),s.name="AR Placement Reticle";if(b1){const r=new Ci(1);r.position.y+=.01,s.add(r)}this._reticle[t]=s,s.matrixAutoUpdate=!1,s.visible=!1}if(s.lastPos=s.lastPos||i.position.clone(),s.lastQuat=s.lastQuat||i.quaternion.clone(),s.position.copy(s.lastPos.lerp(i.position,this.context.time.deltaTime/.1)),s.lastPos.copy(s.position),s.quaternion.copy(s.lastQuat.slerp(i.quaternion,this.context.time.deltaTime/.05)),s.lastQuat.copy(s.quaternion),s.scale.set(n,n,n),this.customReticle&&this.applyViewBasedTransform(s),s.updateMatrix(),s.visible=!0,s.parent!==this.context.scene&&this.context.scene.add(s),this._placementStartTime<0&&(this._placementStartTime=this.context.time.realtimeSinceStartup),this.autoPlace)if(this.upVec.set(0,1,0).applyQuaternion(s.quaternion),this.upVec.dot(F(0,1,0))>.9){let r=s["autoplace:timer"]||0;r>=1?(s.visible=!1,this.onPlaceScene(null)):(r+=this.context.time.deltaTime,s["autoplace:timer"]=r)}else s["autoplace:timer"]=0}onPlaceScene=e=>{if(this._isPlacing==!1||e?.used)return;let t=this._reticle[0];if(!t){console.warn("No reticle to place...");return}if(!t.visible&&!this.autoPlace){console.warn("Reticle is not visible (can not place)");return}if(Z.active?.isTrackingImages){console.warn("Scene Placement is disabled while images are being tracked");return}let i=this._hits[0];if(e&&e.origin instanceof Sg){const n=this._reticle[e.origin.index];n&&(t=n,i=this._hits[e.origin.index])}if(e&&(e.stopImmediatePropagation(),e.stopPropagation(),e.use()),this._isPlacing=!1,this.context.input.removeEventListener("pointerup",this.onPlaceScene),this.onRevertSceneChanges(),t.position.copy(t.lastPos),t.quaternion.copy(t.lastQuat),this.onApplyPose(t),yn._hasPlaced=!0,this.useXRAnchor&&this.onCreateAnchor(Z.active,i),this.context.xr)for(const n of this.context.xr.controllers)n.cancelHitTestSource()};onSetScale(){if(!yn._hasPlaced)return;const e=Z.active?.rig?.gameObject;if(e){const t=Z.active?.rigScale||1,i=1/this._arScale*t,n=new J().makeScale(i,i,i).invert();e.matrix.premultiply(n),e.matrix.decompose(e.position,e.quaternion,e.scale)}}onRevertSceneChanges(){for(const e of this._reticle)e&&(e.visible=!1,e?.removeFromParent());this._reticle.length=0;for(let e=this._placementScene.children.length-1;e>=0;e--){const t=this._placementScene.children[e];this.context.scene.add(t)}this._createdPlacementObject?.removeFromParent();for(const e of this._reparentedComponents)S.addComponent(e.originalObject,e.comp)}async onCreateAnchor(e,t){if(t.createAnchor===void 0){console.warn("Hit does not support creating an anchor",t),A()&&be("Hit does not support creating an anchor");return}else{const i=await t.createAnchor(e.viewerPose.transform);e.running&&i&&(this._anchor=i)}}upVec=new b(0,1,0);lookPoint=new b;worldUpVec=new b(0,1,0);applyViewBasedTransform(e){const t=this.context.mainCamera,i=e,n=t.worldPosition,s=i.worldPosition;this.upVec.set(0,1,0).applyQuaternion(e.quaternion);const r=t.worldPosition;r&&e.position.clone().sub(r).angleTo(this.upVec)<Math.PI/2&&this.upVec.negate();const a=this.upVec.angleTo(this.worldUpVec)*180/Math.PI,l=30;a>l&&a<180-l||a<-l&&a>-180+l?(this.lookPoint.copy(e.position).add(this.upVec),this.lookPoint.y=e.position.y,e.lookAt(this.lookPoint)):(n.y=s.y,e.lookAt(n))}onApplyPose(e){const t=Z.active?.rig?.gameObject;if(!t){console.warn("No rig object to place");return}const i=t.parent||this.context.scene;this._rigPlacementMatrix?this._rigPlacementMatrix?.decompose(t.position,t.quaternion,t.scale):this._rigPlacementMatrix=t.matrix.clone(),this.applyViewBasedTransform(e),e.updateMatrix(),this.context.scene.add(e),e.attach(t),e.removeFromParent(),t.scale.set(this.arScale,this.arScale,this.arScale),t.position.multiplyScalar(this.arScale),t.updateMatrix(),this.invertForward&&t.matrix.premultiply(dA),t.matrix.premultiply(this._startOffset),t.matrix.decompose(t.position,t.quaternion,t.scale),i.add(t)}}class Sm{static up=new b(0,1,0);static zero=new b(0,0,0);static one=new b(1,1,1);oneFingerDrag=!0;twoFingerRotate=!0;twoFingerScale=!0;factor=1;context;offset;plane;_scale=1;_hasChanged=!1;get scale(){return this._scale}constructor(e){this.context=e,this.offset=new J,this.plane=new _r,this.plane.setFromNormalAndCoplanarPoint(Sm.up,Sm.zero)}_enabled=!1;reset(){this._scale=1,this.offset.identity(),this._hasChanged=!0}get hasChanged(){return this._hasChanged}applyMatrixTo(e,t){this._hasChanged=!1,t?(this.offset.invert(),e.premultiply(this.offset)):e.multiply(this.offset)}currentlyUsedPointerIds=new Set;currentlyUnusedPointerIds=new Set;get isActive(){return this.currentlyUsedPointerIds.size<=0&&this.currentlyUnusedPointerIds.size>0}enable(){this._enabled||(this._enabled=!0,this.context.input.addEventListener("pointerdown",this.onPointerDownEarly,{queue:di.Early}),this.context.input.addEventListener("pointerdown",this.onPointerDownLate,{queue:di.Late}),this.context.input.addEventListener("pointerup",this.onPointerUpEarly,{queue:di.Early}),window.addEventListener("touchstart",this.touchStart,{passive:!1}),window.addEventListener("touchmove",this.touchMove,{passive:!1}),window.addEventListener("touchend",this.touchEnd,{passive:!1}))}disable(){this._enabled&&(this._enabled=!1,this.context.input.removeEventListener("pointerdown",this.onPointerDownEarly,{queue:di.Early}),this.context.input.removeEventListener("pointerdown",this.onPointerDownLate,{queue:di.Late}),this.context.input.removeEventListener("pointerup",this.onPointerUpEarly,{queue:di.Early}),window.removeEventListener("touchstart",this.touchStart),window.removeEventListener("touchmove",this.touchMove),window.removeEventListener("touchend",this.touchEnd))}onPointerDownEarly=e=>{this.isActive&&e.stopPropagation()};onPointerDownLate=e=>{e.used?this.currentlyUsedPointerIds.add(e.pointerId):this.currentlyUsedPointerIds.size<=0&&this.currentlyUnusedPointerIds.add(e.pointerId)};onPointerUpEarly=e=>{this.currentlyUsedPointerIds.delete(e.pointerId),this.currentlyUnusedPointerIds.delete(e.pointerId)};prev=new Map;_didMultitouch=!1;touchStart=e=>{if(!e.defaultPrevented)for(let t=0;t<e.changedTouches.length;t++){const i=e.changedTouches[t],n=I.isAndroidDevice()&&i.clientY<window.innerHeight*.1;this.prev.has(i.identifier)||this.prev.set(i.identifier,{ignore:n,x:0,z:0,screenx:0,screeny:0});const s=this.prev.get(i.identifier);if(s){const r=this.getPositionOnPlane(i.clientX,i.clientY);s.x=r.x,s.z=r.z,s.screenx=i.clientX,s.screeny=i.clientY}}};touchEnd=e=>{e.touches.length<=0&&(this._didMultitouch=!1);for(let t=0;t<e.changedTouches.length;t++){const i=e.changedTouches[t];this.prev.delete(i.identifier)}};touchMove=e=>{if(!e.defaultPrevented&&this.isActive){if(e.touches.length===1){if(this._didMultitouch)return;const t=e.touches[0],i=this.prev.get(t.identifier);if(!i||i.ignore)return;const n=this.getPositionOnPlane(t.clientX,t.clientY),s=n.x-i.x,r=n.z-i.z;if(s===0&&r===0)return;this.oneFingerDrag&&this.addMovement(s,r),i.x=n.x,i.z=n.z,i.screenx=t.clientX,i.screeny=t.clientY;return}else if(e.touches.length===2){this._didMultitouch=!0;const t=e.touches[0],i=e.touches[1],n=this.prev.get(t.identifier),s=this.prev.get(i.identifier);if(!n||!s)return;if(this.twoFingerRotate){const r=Math.atan2(t.clientY-i.clientY,t.clientX-i.clientX),a=Math.atan2(n.screeny-s.screeny,n.screenx-s.screenx),l=r-a;Math.abs(l)>.001&&this.addRotation(l)}if(this.twoFingerScale){const r=t.clientX-i.clientX,a=t.clientY-i.clientY,l=Math.sqrt(r*r+a*a),c=n.screenx-s.screenx,h=n.screeny-s.screeny,d=Math.sqrt(c*c+h*h),p=l-d;Math.abs(p)>2&&this.addScale(p)}n.screenx=t.clientX,n.screeny=t.clientY,s.screenx=i.clientX,s.screeny=i.clientY}}};_raycaster=new Od;_intersection=new b;_screenPos=new b;getPositionOnPlane(e,t){const i=this.context.mainCamera;return this._screenPos.x=e/window.innerWidth*2-1,this._screenPos.y=-(t/window.innerHeight)*2+1,this._screenPos.z=1,this._screenPos.unproject(i),this._raycaster.set(i.position,this._screenPos.sub(i.position)),this._raycaster.ray.intersectPlane(this.plane,this._intersection),this._intersection}addMovement(e,t){e/=this._scale,t/=this._scale,e*=this.factor,t*=this.factor,this.offset.elements[12]+=e,this.offset.elements[14]+=t,(e!==0||t!==0)&&(this._hasChanged=!0)}_tempMatrix=new J;addScale(e){e/=window.innerWidth,e*=-1,this._scale*=1+e,this._tempMatrix.makeScale(1-e,1-e,1-e),this.offset.premultiply(this._tempMatrix),e!==0&&(this._hasChanged=!0)}addRotation(e){e*=-1,this._tempMatrix.makeRotationY(e),this.offset.premultiply(this._tempMatrix),e!==0&&(this._hasChanged=!0)}}const Ns=w("debugautosync"),By=Symbol("syncerId");class uA{_syncers={};getOrCreateSyncer(e){if(!e.guid)return null;if(this._syncers[e.guid])return this._syncers[e.guid];const t=new pA(e);return t[By]=e.guid,this._syncers[t[By]]=t,t}removeSyncer(e){delete this._syncers[e[By]]}}const Fy=new uA;class pA{comp;constructor(e){this.comp=e}hasChanges=!1;changedProperties={};get networkingKey(){return this.comp.guid}_isReceiving=!1;_isInit=!1;init(e){if(this._isInit)return;this._isInit=!0,this.comp=e,this.comp.context.post_render_callbacks.push(this.onHandleSending),this.comp.context.connection.beginListen(this.networkingKey,this.onHandleReceiving);const t=this.comp.context.connection.tryGetState(this.comp.guid);t&&this.onHandleReceiving(t)}destroy(){this._isInit&&(this.comp.context.post_render_callbacks.splice(this.comp.context.post_render_callbacks.indexOf(this.onHandleSending),1),this.comp.context.connection.stopListen(this.networkingKey,this.onHandleReceiving),this.comp=null,this._isInit=!1)}notifyChanged(e,t){this._isReceiving||(Ns&&console.log("Property changed: "+e,t),this.hasChanges=!0,this.changedProperties[e]=t)}onHandleSending=()=>{if(!this.hasChanges)return;this.hasChanges=!1;const e=this.comp.context.connection;if(!e||!e.isConnected||!e.isInRoom){for(const t in this.changedProperties)delete this.changedProperties[t];return}for(const t in this.changedProperties){const i=this.changedProperties[t];Ns&&console.log("SEND",this.comp.guid,this.networkingKey),e.send(this.networkingKey,{guid:this.comp.guid,property:t,data:i},Pn.Queued),delete this.changedProperties[t]}};onHandleReceiving=e=>{if(Ns&&console.log("SYNCFIELD RECEIVE",this.comp.name,this.comp.guid,e),!!this._isInit&&this.comp&&e.guid===this.comp.guid)try{this._isReceiving=!0,this.comp[e.property]=e.data}catch(t){console.error(t)}finally{this._isReceiving=!1}}}function mA(o,e){let t=e!==o;return!t&&o&&e&&(Array.isArray(o)&&Array.isArray(e)||typeof o=="object"&&typeof e=="object")&&(t=!0),t}const mh=Symbol("AutoSyncHandler");function gA(o){if(o[mh])return o[mh];const e=Fy.getOrCreateSyncer(o);return e?.init(o),o[mh]=e,e}function fA(o){const e=o[mh];e&&(Fy.removeSyncer(e),e.destroy(),delete o[mh])}const Uy=function(o=null){return function(e,t){let i="";typeof t=="string"?i=t:i=t.name;let n=null,s;typeof o=="string"?s=e[o]:typeof o=="function"&&(s=o),s==null&&(A()||Ns)&&o!=null&&console.warn('syncField: no callback function found for property "'+i+'"','"'+o+'"');const r=e,a=r.__internalAwake;if(typeof a!="function"){(Ns||A())&&console.error('@syncField can currently only used on Needle Engine Components, custom object of type "'+e?.constructor?.name+'" is not supported',e);return}Ns&&console.log(i);const l=Symbol(i);r.__internalAwake=function(){if(this[l]===void 0){if(this[l]=this[i],n=Fy.getOrCreateSyncer(this),Object.getOwnPropertyDescriptor(this,i)?.set===void 0){let h=!1;Object.defineProperty(this,i,{set:function(d){const p=this[l];if(this[l]=d,h){(A()||Ns)&&console.warn("Recursive call detected",i);return}h=!0;try{const m=mA(d,p);Ns&&console.log("SyncField assignment",i,"changed?",m,d,s),m&&s?.call(this,d,p)!==!1&&gA(this)?.notifyChanged(i,d)}finally{h=!1}},get:function(){return this[l]},configurable:!0,enumerable:!0})}n?.init(this),a.call(this)}};const c=r.__internalDestroy;r.__internalDestroy=function(){fA(this),c.call(this)}}};var yA=Object.defineProperty,_p=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&yA(e,t,n),n};const ni=w("debugplayersync"),vp=class FS extends E{static async setupFrom(e,t){const i=ne.getOrCreateFromUrl(e);if(!i.asset){const r=await i.loadAssetAsync();r&&S.getOrAddComponent(r,sn)}const n=new FS;n._internalInit(t),n.asset=i;const s=new M;return s.guid=e,S.addComponent(s,n),n}autoSync=!0;asset;onPlayerSpawned;_localInstance;awake(){this.watchTabVisible(),this.onPlayerSpawned||(this.onPlayerSpawned=new ae)}onEnable(){this.context.connection.beginListen(ie.RoomStateSent,this.onJoinedRoom),this.context.connection.beginListen(ie.JoinedRoom,this.onJoinedRoom),this.context.connection.beginListen(ie.LeftRoom,this.destroyInstance),this.context.connection.isInRoom&&this.onJoinedRoom()}onDisable(){this.context.connection.stopListen(ie.RoomStateSent,this.onJoinedRoom),this.context.connection.stopListen(ie.JoinedRoom,this.onJoinedRoom),this.context.connection.stopListen(ie.LeftRoom,this.destroyInstance)}onJoinedRoom=()=>{ni&&console.log("PlayerSync.joinedRoom. autoSync is set to "+this.autoSync),this.autoSync&&this.getInstance()};async getInstance(){if(this._localInstance)return this._localInstance;if(ni&&console.log("PlayerSync.createInstance",this.asset?.url),!this.asset?.asset&&!this.asset?.url)return console.error('PlayerSync: can not create an instance because "asset" is not set and or has no URL!'),null;this.gameObject.guid||console.warn("PlayerSync: gameObject has no guid! This might cause issues with syncing the player state."),this._localInstance=this.asset?.instantiateSynced({parent:this.gameObject,deleteOnDisconnect:!0},!0);const e=await this._localInstance;if(e){const t=S.getComponentsInChildren(e,sn);if(ni&&console.log(`PlayerSync.createInstance: found ${t?.length} PlayerState components. Owner: ${this.context.connection.connectionId}`),t?.length){for(const i of t)i.owner=this.context.connection.connectionId;this.onPlayerSpawned?.invoke(e)}else this._localInstance=void 0,console.error("<strong>Failed finding PlayerState on "+this.asset?.url+"</strong>: please make sure the asset has a PlayerState component!"),S.destroySynced(e)}else this._localInstance=void 0,console.warn("PlayerSync: failed instantiating asset!");return this._localInstance}destroyInstance=()=>{this._localInstance?.then(e=>{ni&&console.log("PlayerSync.destroyInstance",e),Lc(e,this.context.connection,!0,{saveInRoom:!1})}),this._localInstance=void 0};watchTabVisible(){window.addEventListener("visibilitychange",e=>{if(document.visibilityState==="visible")for(let t=sn.all.length-1;t>=0;t--){const i=sn.all[t];(!i.owner||!this.context.connection.userIsInRoom(i.owner))&&i.doDestroy()}})}};_p([u()],vp.prototype,"autoSync"),_p([u(ne)],vp.prototype,"asset"),_p([u(ae)],vp.prototype,"onPlayerSpawned");let zy=vp;var _1=(o=>(o.OwnerChanged="ownerChanged",o))(_1||{});const Ny=class Lt extends E{static _all=[];static get all(){return Lt._all}static _local=[];static get local(){return Lt._local}static getFor(e){if(e instanceof M)return S.getComponentInParent(e,Lt);if(e instanceof E)return S.getComponentInParent(e.gameObject,Lt)}static isLocalPlayer(e){return Lt.getFor(e)?.isLocalPlayer??!1}static _callbacks={};static addEventListener(e,t){return this._callbacks[e]||(this._callbacks[e]=[]),this._callbacks[e].push(t),t}static removeEventListener(e,t){if(!this._callbacks[e])return;const i=this._callbacks[e].indexOf(t);i>=0&&this._callbacks[e].splice(i,1)}static dispatchEvent(e,t){if(this._callbacks[e])for(const i of this._callbacks[e])i(t)}onOwnerChangeEvent=new ae;onFirstOwnerChangeEvent=new ae;hasOwner=!1;owner;dontDestroy=!1;get isLocalPlayer(){return this.owner===this.context.connection.connectionId}onOwnerChange(e,t){ni&&console.log(`PlayerSync.onOwnerChange: ${t} \u2192 ${e} (me: ${this.context.connection.connectionId})`);const i=Lt._local.indexOf(this);i>=0&&Lt._local.splice(i,1);const n={playerState:this,oldValue:t,newValue:e};if(this.hasOwner||(this.hasOwner=!0,this.onFirstOwnerChangeEvent?.invoke(n)),this.onOwnerChangeEvent?.invoke(n),this.owner===this.context.connection.connectionId){Lt._local.push(this);const r=new CustomEvent("local-owner-changed",{detail:n});this.dispatchEvent(r)}const s=new CustomEvent("owner-changed",{detail:n});this.dispatchEvent(s),Lt.dispatchEvent("ownerChanged",s)}awake(){Lt.all.push(this),ni&&console.log("Registered new PlayerState",this.guid,Lt.all.length-1,Lt.all),this.context.connection.beginListen(ie.UserLeftRoom,this.onUserLeftRoom)}async start(){ni&&console.log("PLAYERSTATE.START, owner: "+this.owner,this.context.connection.usersInRoom([])),this.owner?(this.context.connection.isInRoom||await Ro(300),this.context.connection.userIsInRoom(this.owner)==!1&&(ni&&console.log(`PlayerSync.start \u2192 doDestroy "${this.name}" because user "${this.owner}" is not in room anymore...`,"Currently in room:",...this.context.connection.usersInRoom()),this.doDestroy())):this.owner||(ni&&console.warn("PlayerState.start \u2192 owner is undefined!",this.name),setTimeout(()=>{!this.destroyed&&!this.owner?this.dontDestroy?ni&&console.warn("PlayerState.start \u2192 owner is still undefined but dontDestroy is set to true",this.name):(ni&&console.warn(`PlayerState.start \u2192 owner is still undefined: destroying "${this.name}" instance now`),this.doDestroy()):ni&&console.log("PlayerState.start \u2192 owner is assigned",this.owner)},2e3))}doDestroy(){ni&&console.log("PlayerSync.doDestroy \u2192 syncDestroy",this.name),Lc(this.gameObject,this.context.connection,!0,{saveInRoom:!1})}onDestroy(){if(ni&&console.warn("PlayerState.onDestroy",this.owner),this.context.connection.stopListen(ie.UserLeftRoom,this.onUserLeftRoom),Lt.all.splice(Lt.all.indexOf(this),1),this.isLocalPlayer){const e=Lt._local.indexOf(this);e>=0&&Lt._local.splice(e,1)}}onUserLeftRoom=e=>{if(e.userId===this.owner){ni&&console.log("PLAYERSYNC LEFT",this.owner),this.doDestroy();return}}};_p([Uy(Ny.prototype.onOwnerChange)],Ny.prototype,"owner");let sn=Ny;var bA=Object.defineProperty,Rl=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&bA(e,t,n),n};class lo extends E{position="bottom";showNeedleLogo=!1;showSpatialMenu;createFullscreenButton;createMuteButton;createQRCodeButton;onEnable(){this.applyOptions()}applyOptions(){this.context.menu.setPosition(this.position),this.context.menu.showNeedleLogo(this.showNeedleLogo),this.createFullscreenButton===!0&&this.context.menu.showFullscreenOption(!0),this.createMuteButton===!0&&this.context.menu.showAudioPlaybackOption(!0),this.showSpatialMenu===!0&&this.context.menu.showSpatialMenu(this.showSpatialMenu),this.createQRCodeButton===!0&&(I.isMobileDevice()||this.context.menu.showQRCodeButton(!0))}}Rl([u()],lo.prototype,"position"),Rl([u()],lo.prototype,"showNeedleLogo"),Rl([u()],lo.prototype,"showSpatialMenu"),Rl([u()],lo.prototype,"createFullscreenButton"),Rl([u()],lo.prototype,"createMuteButton"),Rl([u()],lo.prototype,"createQRCodeButton");var _A=Object.defineProperty,Wy=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&_A(e,t,n),n};const gh=w("debugwebxr"),v1=new N().setFromAxisAngle(new b(0,1,0),Math.PI);class Ws extends E{head;leftHand;rightHand;_leftHandMeshes;_rightHandMeshes;_syncTransforms;async onEnterXR(e){if(!this.activeAndEnabled)return;gh&&console.warn("AVATAR ENTER XR",this.guid,this.sourceId,this,this.activeAndEnabled),this._syncTransforms&&(this._syncTransforms.length=0),await this.prepareAvatar();const t=sn.getFor(this);if(t?.owner){const i=this.gameObject.addComponent(Le);i.avatar=this.gameObject,i.connectionId=t.owner,this.context.players.setPlayerView(t.owner,this.head?.asset,Fo.Headset)}else this.context.connection.isConnected?console.error("No player state found for avatar",this):t&&!this.context.connection.isConnected&&(t.dontDestroy=!0)}onLeaveXR(e){const t=this.gameObject.getComponent(Le);t&&t.destroy()}onUpdateXR(e){if(!this.activeAndEnabled)return;const t=sn.isLocalPlayer(this);if(!t)return;const i=e.xr;if(i.rig&&i.rig.gameObject!==this.gameObject.parent&&(this.gameObject.position.set(0,0,0),this.gameObject.rotation.set(0,0,0),this.gameObject.scale.set(1,1,1),i.rig.gameObject.add(this.gameObject)),this._syncTransforms&&t)for(const l of this._syncTransforms)l.fastMode=!0,l.isOwned()||l.requestOwnership();if(this.head&&this.context.mainCamera){const l=this.head.asset;if(l.position.copy(this.context.mainCamera.position),l.position.x*=-1,l.position.z*=-1,l.quaternion.copy(this.context.mainCamera.quaternion),l.quaternion.x*=-1,this.context.time.frameCount%10===0&&this.head.asset){const c=S.getComponentsInChildren(this.head.asset,tn);for(const h of c)h.enabled=!1,h.gameObject.visible=!1}}const n=e.xr.leftController,s=this.leftHand?.asset;n&&s?(s.position.copy(n.gripPosition),s.quaternion.copy(n.gripQuaternion),s.quaternion.multiply(v1),s.visible=n.isTracking,this.updateHandVisibility(n,s,this._leftHandMeshes)):s&&s.visible&&(s.visible=!1);const r=e.xr.rightController,a=this.rightHand?.asset;r&&a?(a.position.copy(r.gripPosition),a.quaternion.copy(r.gripQuaternion),a.quaternion.multiply(v1),a.visible=r.isTracking,this.updateHandVisibility(r,a,this._rightHandMeshes)):a&&a.visible&&(a.visible=!1)}onBeforeRender(){this.context.xr&&this.context.time.frame%10===0&&this.updateRemoteAvatarVisibility()}updateHandVisibility(e,t,i){if(i){const n=e.model&&e.model.visible&&e.model!==t;i.forEach(s=>{Bo(s,!n)})}}updateRemoteAvatarVisibility(){if(this.context.connection.isConnected){const e=sn.getFor(this);if(e&&e.isLocalPlayer==!1){const t=Z.getXRSync(this.context);if(t&&t.hasState(e.owner)){this.tryFindAvatarObjectsIfMissing();const i=this.leftHand?.asset;i&&(i.visible=t?.isTracking(e.owner,"left")??!1);const n=this.rightHand?.asset;n&&(n.visible=t?.isTracking(e.owner,"right")??!1)}if(this.head?.asset){const i=S.getComponentsInChildren(this.head.asset,tn);for(const n of i)n.enabled=!1,n.gameObject.visible=!0}}}}tryFindAvatarObjectsIfMissing(){if(!this.head||!this.leftHand||!this.rightHand){const e={head:this.head,leftHand:this.leftHand,rightHand:this.rightHand};wv.tryFindAvatarObjects(this.gameObject,this.sourceId||"",e),e.head&&(this.head=e.head),e.leftHand&&(this.leftHand=e.leftHand),e.rightHand&&(this.rightHand=e.rightHand)}}async prepareAvatar(){if(this.tryFindAvatarObjectsIfMissing(),this.head)this.head instanceof M&&(this.head=new ne("",this.sourceId,this.head));else{const e=new M;e.name="Head";const t=Ps.createPrimitive(Qa.Cube);e.add(t),this.gameObject.add(e),this.head=new ne("",this.sourceId,e),gh&&console.log("Create head",e)}if(this.rightHand)this.rightHand instanceof M&&(this.rightHand=new ne("",this.sourceId,this.rightHand));else{const e=new M;e.name="Right Hand",this.gameObject.add(e),this.rightHand=new ne("",this.sourceId,e),gh&&console.log("Create right hand",e)}if(this.leftHand)this.leftHand instanceof M&&(this.leftHand=new ne("",this.sourceId,this.leftHand));else{const e=new M;e.name="Left Hand",this.gameObject.add(e),this.leftHand=new ne("",this.sourceId,e),gh&&console.log("Create left hand",e)}await this.loadAvatarObjects(this.head,this.leftHand,this.rightHand),this._leftHandMeshes=[],this.leftHand.asset?.traverse(e=>{e?.isMesh&&this._leftHandMeshes.push(e)}),this._rightHandMeshes=[],this.rightHand.asset?.traverse(e=>{e?.isMesh&&this._rightHandMeshes.push(e)}),sn.isLocalPlayer(this.gameObject)&&(this._syncTransforms=S.getComponentsInChildren(this.gameObject,Tn))}async loadAvatarObjects(e,t,i){const n=e.loadAssetAsync(),s=t.loadAssetAsync(),r=i.loadAssetAsync(),a=new Array;n&&a.push(n),s&&a.push(s),r&&a.push(r);const l=await Zm(a);gh&&console.log("Avatar loaded results:",l)}}Wy([u(ne)],Ws.prototype,"head"),Wy([u(ne)],Ws.prototype,"leftHand"),Wy([u(ne)],Ws.prototype,"rightHand");var vA=Object.defineProperty,wp=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&vA(e,t,n),n};const Vs=w("debugwebxr"),$s=new Array;class Zo extends E{createControllerModel=!0;createHandModel=!0;customLeftHand;customRightHand;static factory=new _P;supportsXR(e){return e==="immersive-vr"||e==="immersive-ar"}_models=new Array;async onXRControllerAdded(e){if(!(e.xr.isVR||e.xr.isPassThrough))return;console.debug("XR Controller Added",e.controller.side,e.controller.index);const{controller:t}=e;if(this.createControllerModel||this.createHandModel){if(t.hand){if(this.createHandModel){const i=await this.loadHandModel(this,t);if(!i||!t.connected||!t.isHand){i?.handObject&&nl(i.handObject,!1),i?.handObject?.destroy();return}this._models.push({controller:t,model:i.handObject,handmesh:i.handmesh}),this._models.sort((n,s)=>n.controller.index-s.controller.index),this.scene.add(i.handObject),t.model=i.handObject}}else if(this.createControllerModel){const i=await t.getModelUrl();if(i){const n=await this.loadModel(t,i);if(!n||!t.connected||t.isHand)return;this._models.push({controller:t,model:n}),this._models.sort((s,r)=>s.controller.index-r.controller.index),this.scene.add(n),n.traverse(s=>{s.layers.set(2),s.matrixAutoUpdate=!1,s.updateMatrix()}),t.model=n}else t.targetRayMode!=="transient-pointer"&&console.warn("XRControllerModel: no model found for "+t.side)}}}onXRControllerRemoved(e){console.debug("XR Controller Removed",e.controller.side,e.controller.index);const t=this._models.findIndex(n=>n.controller===e.controller),i=this._models[t];i&&(this._models.splice(t,1),i.model&&(nl(i.model,!1),i.model.destroy(),i.model=void 0))}onBeforeXR(e,t){this.createHandModel&&(this.customLeftHand||this.customRightHand)&&(t.optionalFeatures=t.optionalFeatures||[],t.optionalFeatures.includes("hand-tracking")||t.optionalFeatures.push("hand-tracking"))}onLeaveXR(e){for(const t of this._models)t&&(t.model&&(nl(t.model,!1),t.model.destroy(),t.model=void 0),t.controller.model===t.model&&(t.controller.model=null));this._models.length=0}onBeforeRender(){if(Z.active&&(Vs&&($s[0]=Date.now()),this.updateRendering(Z.active),Vs)){const e=Date.now()-$s[0];$s.push(e),$s.length>=30&&($s[0]=0,$s.reduce((t,i)=>t+i,0)/$s.length,$s.length=0)}}updateRendering(e){for(let t=0;t<this._models.length;t++){const i=this._models[t];if(!i)continue;const n=i.controller;if(!n.connected){Vs&&console.warn("XRControllerModel.onUpdateXR: controller is not connected anymore",n.side,n.hand);continue}if(i.model&&!i.handmesh)i.model.matrixAutoUpdate=!1,i.model.matrix.copy(n.gripMatrix),i.model.visible=n.isTracking,e.rig?.gameObject.add(i.model);else if(n.inputSource.hand&&i.handmesh){const s=e.referenceSpace,r=this.context.renderer.xr.getHand(n.index);if(s&&e.frame.getJointPose){for(const a of n.inputSource.hand.values()){const l=r.joints[a.jointName];if(l){const c=n.getHandJointPose(a);if(c){const h=c.transform.position,d=c.transform.orientation;l.position.copy(h),l.quaternion.copy(d),l.matrixAutoUpdate=!1}l.visible=c!=null}}i.model&&(i.model.visible=n.isTracking,i.model.visible&&i.model.parent!==e.rig?.gameObject&&e.rig?.gameObject.add(i.model)),i.model?.visible&&(i.handmesh?.updateMesh(),i.model.matrixAutoUpdate=!1,i.model.matrix.identity(),i.model.applyMatrix4(Ha))}}}}async loadModel(e,t){if(!e.connected)return console.warn("XRControllerModel.onXRControllerAdded: controller is not connected anymore",e.side),null;const i=await ne.getOrCreate("",t).instantiate();return nl(i),Z.active?.isPassThrough&&i.traverseVisible(n=>{this.makeOccluder(n)}),i}async loadHandModel(e,t){const i=this.context,n=i.renderer.xr.getHand(t.index);n||(Vs?B.DrawLabel(t.rayWorldPosition,"No hand found for index "+t.index,.05,5):console.warn("No hand found for index "+t.index));const s=new Mo;Tf(s,i),await np(s,i,this.sourceId??"",this.sourceId??"");const r=cy(s);let a="";const l=t.side==="left"?this.customLeftHand:this.customRightHand;l?(a=l.url.split(".").slice(0,-1).join("."),s.setPath("")):(a=t.inputSource.handedness==="left"?"left":"right",s.setPath("https://cdn.jsdelivr.net/npm/@webxr-input-profiles/assets@1.0/dist/profiles/generic-hand/"));const c=new M;nl(c);const h=new vP(c,n,s.path,a,s,d=>{const p=r?.gltf;p?.scene.children?.length===0&&(p.scene.children[0]=d),r?.gltf&&Cn().createBuiltinComponents(e.context,e.sourceId||a,r.gltf,null,r),d.traverse(m=>{m.layers.set(2),Z.active?.isPassThrough&&!l&&this.makeOccluder(m),m instanceof H&&Ve.assignMeshLOD(m,0)}),t.connected||(Vs&&B.DrawLabel(t.rayWorldPosition,"Hand is loaded but not connected anymore",.05,5),d.removeFromParent())});if(Vs&&c.add(new Ci(.5)),t.inputSource.hand){Vs&&console.log(t.inputSource.hand);for(const d of t.inputSource.hand.values())if(n.joints[d.jointName]===void 0){const p=new Co;p.matrixAutoUpdate=!1,p.visible=!0,n.joints[d.jointName]=p,n.add(p)}}else Vs&&B.DrawLabel(t.rayWorldPosition,"No inputSource.hand found for index "+t.index,.05,5);return{handObject:c,handmesh:h}}makeOccluder(e){if(e instanceof H){let t=e.material;t instanceof we&&(t=e.material=t.clone(),t.depthWrite=!0,t.depthTest=!0,t.colorWrite=!1,e.receiveShadow=!1,e.renderOrder=-100)}}}wp([u()],Zo.prototype,"createControllerModel"),wp([u()],Zo.prototype,"createHandModel"),wp([u(ne)],Zo.prototype,"customLeftHand"),wp([u(ne)],Zo.prototype,"customRightHand");class xp extends E{}var wA=Object.defineProperty,Hs=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&wA(e,t,n),n};const Vy=w("debugwebxr");class Bi extends E{movementSpeed=1.5;rotationStep=30;useTeleport=!0;usePinchToTeleport=!0;useTeleportTarget=!1;useTeleportFade=!1;showRays=!0;showHits=!0;isXRMovementHandler=!0;xrSessionMode="immersive-vr";_didApplyRotation=!1;_didTeleport=!1;onUpdateXR(e){const t=e.xr.rig;if(!t?.gameObject||e.xr.isPassThrough)return;const i=e.xr.leftController,n=e.xr.rightController;i&&this.onHandleMovement(i,t.gameObject),n&&(this.onHandleRotation(n,t.gameObject),this.useTeleport&&this.onHandleTeleport(n,t.gameObject))}onLeaveXR(e){for(const t of this._lines)t.removeFromParent();for(const t of this._hitDiscs)t?.removeFromParent()}onBeforeRender(){this.context.xr?.running&&(this.showRays&&this.renderRays(this.context.xr),this.showHits&&this.renderHits(this.context.xr))}onHandleMovement(e,t){const i=e.getStick("xr-standard-thumbstick");if(i.x!=0||i.y!=0){const n=F(i.x,0,i.y);n.multiplyScalar(this.context.time.deltaTimeUnscaled*this.movementSpeed);const s=$e(t);n.multiplyScalar(s.x),n.applyQuaternion(e.xr.poseOrientation),n.y=0,n.applyQuaternion(t.worldQuaternion),A()&&Number.isNaN(n.x)&&console.error("Stick movement resulted in NaN",{stick:i,vec:n}),t.position.add(n),t.updateWorldMatrix(!1,!1);for(const r of t.children)r.updateWorldMatrix(!1,!1)}}onHandleRotation(e,t){if(e._isMxInk)return;const i=e.getStick("xr-standard-thumbstick").x;if(this._didApplyRotation)Math.abs(i)<.3&&(this._didApplyRotation=!1);else if(Math.abs(i)>.5){this._didApplyRotation=!0;const n=i>0?1:-1,s=ee(this.context.mainCamera).clone();t.rotateY(n*j.toRadians(this.rotationStep));const r=ee(this.context.mainCamera).clone().sub(s);r.y=0,t.position.sub(r)}}_teleportBuffer=new Array;onHandleTeleport(e,t){let i=0;if(e.hand&&this.usePinchToTeleport&&e.isTeleportGesture){const n=e.getPointerId("primary");if(n!=null&&this.context.input.getIsPointerIdInUse(n))return;const s=e.getGesture("pinch");s&&(i=s.value)}else i=e.getStick("xr-standard-thumbstick")?.y;if(this._didTeleport)i>=0&&i<.4?this._didTeleport=!1:i<0&&i>-.4&&(this._didTeleport=!1);else if(i>.8){this._didTeleport=!0;const n=this.context.physics.raycastFromRay(e.ray)[0];if(n&&n.object instanceof ja){const r=n.normal?.dot(F(0,1,0));if(r!==void 0&&r<.4)return}let s=n?.point;if(!s&&!this.useTeleportTarget){this._plane||(this._plane=new _r(new b(0,1,0),0));const r=t.worldPosition;this._plane.setFromNormalAndCoplanarPoint(new b(0,1,0),r);const a=e.ray;s=r.clone(),this._plane.intersectLine(new WC(a.origin,F(a.direction).multiplyScalar(1e4).add(a.origin)),s),s.distanceTo(r)>t.scale.x*10&&(s=null)}if(s){if(this.useTeleportTarget&&!S.getComponentInParent(n.object,xp))return;const r=s.clone();if(Vy&&B.DrawSphere(s,.025,16711680,5),this.context.mainCamera?.position){const a=this.context.xr?.getUserOffsetInRig();a&&(a.y=0,r.sub(a),Vy&&B.DrawWireSphere(a.add(r),.025,65280,5))}this._teleportBuffer.push(t.matrix.clone()),this._teleportBuffer.length>10&&this._teleportBuffer.shift(),this.useTeleportFade?e.xr.fadeTransition()?.then(()=>{t.worldPosition=r}):t.worldPosition=r}}else if(i<-.8&&(this._didTeleport=!0,this._teleportBuffer.length>0)){const n=this._teleportBuffer.pop();n&&n.decompose(t.position,t.quaternion,t.scale)}}_plane=null;_lines=[];_hitDiscs=[];_hitDistances=[];_lastHitDistances=[];renderRays(e){for(let t=0;t<this._lines.length;t++){const i=this._lines[t];i&&(i.visible=!1)}for(let t=0;t<e.controllers.length;t++){const i=e.controllers[t];let n=this._lines[t];if(!i.connected||!i.isTracking||!i.ray||i.targetRayMode==="transient-pointer"||!i.hasSelectEvent){n&&(n.visible=!1);continue}n||(n=this.createRayLineObject(),n.scale.z=.5,this._lines[t]=n),i.updateRayWorldPosition(),i.updateRayWorldQuaternion();const s=i.rayWorldPosition,r=i.rayWorldQuaternion;n.position.copy(s),n.quaternion.copy(r);const a=e.rigScale,l=this.usePinchToTeleport&&i.isTeleportGesture,c=this._lastHitDistances[t],h=this._hitDistances[t]!=null,d=c??a;n.scale.set(a,a,d),n.visible=!0,n.layers.disableAll(),n.layers.enable(2);let p=n.material.opacity;l?p=1:this.showHits&&d<e.rigScale*.5?p=0:i.getButton("primary")?.pressed?p=.5:p=h?.2:.1,n.material.opacity=j.lerp(n.material.opacity,p,this.context.time.deltaTimeUnscaled/.1),n.parent!==this.context.scene&&this.context.scene.add(n)}}renderHits(e){for(const t of this._hitDiscs){if(!t)continue;const i=t.controller;if(!i||!i.connected||!i.isTracking){t.visible=!1;continue}}for(let t=0;t<e.controllers.length;t++){const i=e.controllers[t];if(!i.connected||!i.isTracking||!i.ray||!i.hasSelectEvent)continue;let n=this._hitDiscs[t],s=!0;const r=i.getPointerId("primary");r!=null&&this.context.input.getIsPointerIdInUse(r)&&(n&&(n.visible=!1),this._hitDistances[t]=null,this._lastHitDistances[t]=0,s=!1);const a=this.context.time.smoothedFps>=59?1:10;if((this.context.time.frame+i.index)%a!==0&&(s=!1),!s){const h=this._hitDiscs[t];h&&h.visible&&h.hit&&this.updateHitPointerPosition(i,h,h.hit.distance);continue}const l=this.context.physics.raycastFromRay(i.ray,{testObject:this.hitPointRaycastFilter,precise:!1});let c=l.find(h=>this.usePinchToTeleport&&i.isTeleportGesture?!0:this.isObjectWithInteractiveComponent(h.object));if(c||(c=l[0]),n&&(n.controller=i,n.hit=c),this._hitDistances[t]=c?.distance||null,c){this._lastHitDistances[t]=c.distance;const h=e.rigScale??1;Vy&&(B.DrawWireSphere(c.point,.025*h,16711680),B.DrawLabel(F(0,.2,0).add(c.point),c.object.name,.02,0)),n||(n=this.createHitPointObject(),this._hitDiscs[t]=n),n.hit=c,n.visible=c.distance>h*.05;let d=.01*(h+c.distance);const p=i.getButton("primary")?.pressed;p&&(d*=1.1),n.scale.set(d,d,d),n.layers.set(2);let m=n.material.opacity;if(p?m=1:m=c.distance<.15*h?.2:.6,n.material.opacity=j.lerp(n.material.opacity,m,this.context.time.deltaTimeUnscaled/.1),n.visible){if(c.normal){this.updateHitPointerPosition(i,n,c.distance);const g=c.normal.applyQuaternion(_e(c.object));n.quaternion.setFromUnitVectors(xA,g)}else this.updateHitPointerPosition(i,n,c.distance);n.parent!==this.context.scene&&this.context.scene.add(n)}}else this._hitDiscs[t]&&(this._hitDiscs[t].visible=!1)}}isObjectWithInteractiveComponent(e,t=0){return Bu(e)||e.isUI===!0?!0:e.isScene?!1:e.parent?this.isObjectWithInteractiveComponent(e.parent,t+1):!1}updateHitPointerPosition(e,t,i){const n=F(e.rayWorldPosition);n.add(F(0,0,i-.01).applyQuaternion(e.rayWorldQuaternion)),t.position.lerp(n,this.context.time.deltaTimeUnscaled/.05)}hitPointRaycastFilter=e=>e.type==="SkinnedMesh"?"continue in children":!0;createHitPointObject(){const e=new H(new Pd(.3,6,6),new Ce({color:15658734,opacity:.7,transparent:!0,depthTest:!1,depthWrite:!1,side:Pi}));return e.layers.disableAll(),e.layers.enable(2),e}createRayLineObject(){const e=new wP;e.layers.disableAll(),e.layers.enable(2);const t=new xP;e.geometry=t;const i=new Float32Array(9);i.set([0,0,.02,0,0,.4,0,0,1]),t.setPositions(i);const n=new Float32Array(9);n.set([1,1,1,.1,.1,.1,0,0,0]),t.setColors(n);const s=new SP({color:16777215,vertexColors:!0,worldUnits:!0,linewidth:.004,transparent:!0,depthWrite:!1,blending:Eb,dashed:!1});return e.material=s,e}}Hs([u()],Bi.prototype,"movementSpeed"),Hs([u()],Bi.prototype,"rotationStep"),Hs([u()],Bi.prototype,"useTeleport"),Hs([u()],Bi.prototype,"usePinchToTeleport"),Hs([u()],Bi.prototype,"useTeleportTarget"),Hs([u()],Bi.prototype,"useTeleportFade"),Hs([u()],Bi.prototype,"showRays"),Hs([u()],Bi.prototype,"showHits");const xA=new b(0,1,0);var SA=Object.defineProperty,xt=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&SA(e,t,n),n};const fh=w("debugwebxr"),CA=w("debugusdz"),ct=class ic extends E{createVRButton=!0;createARButton=!0;createSendToQuestButton=!0;createQRCode=!0;useDefaultControls=!0;showControllerModels=!0;showHandModels=!0;usePlacementReticle=!0;customARPlacementReticle;usePlacementAdjustment=!0;arScale=1;useXRAnchor=!1;autoPlace=!1;autoCenter=!1;useQuicklookExport=!1;useDepthSensing=!1;useSpatialGrab=!0;defaultAvatar;_playerSync;_createdComponentsInSession=[];_usdzExporter;static activeWebXRComponent=null;awake(){Z.getXRSync(this.context)}onEnable(){window.location.protocol!=="https:"&&be('<a href="https://developer.mozilla.org/en-US/docs/Web/API/WebXR_Device_API" target="_blank">WebXR</a> only works on secure connections (https).'),navigator.xr?.isSessionSupported("immersive-ar").catch(()=>!1).then(e=>{const t=I.isVisionOS()&&!e;(this.useQuicklookExport||t)&&(S.findObjectOfType(ho)||(fh&&console.log("WebXR: Adding USDZExporter"),this._usdzExporter=S.addComponent(this.gameObject,ho),this._usdzExporter.objectToExport=this.context.scene,this._usdzExporter.autoExportAnimations=!0,this._usdzExporter.autoExportAudioSources=!0))}),this.handleCreatingHTML(),this.handleOfferSession(),this.defaultAvatar===!0&&(fh&&console.warn("WebXR: No default avatar set, using static default avatar"),this.defaultAvatar=new ne("https://cdn.needle.tools/static/avatars/DefaultAvatar.glb")),this.defaultAvatar&&(this._playerSync=this.gameObject.getOrAddComponent(zy),this._playerSync.autoSync=!1),this._playerSync&&typeof this.defaultAvatar!="boolean"&&(this._playerSync.asset=this.defaultAvatar,this._playerSync.onPlayerSpawned?.removeEventListener(this.onAvatarSpawned),this._playerSync.onPlayerSpawned?.addEventListener(this.onAvatarSpawned))}onDisable(){this._usdzExporter?.destroy(),this.removeButtons()}async handleOfferSession(){return this.createVRButton&&await Z.isVRSupported()&&this.createVRButton?Z.offerSession("immersive-vr","default",this.context):this.createARButton&&await Z.isARSupported()&&this.createARButton?Z.offerSession("immersive-ar","default",this.context):!1}get session(){return Z.active??null}get sessionMode(){return Z.activeMode??null}get arSessionRoot(){return this._activeWebARSessionRoot}async enterVR(e){return Z.start("immersive-vr",e,this.context)}async enterAR(e){return Z.start("immersive-ar",e,this.context)}exitXR(){Z.stop()}_exitXRMenuButton;_previousXRState=0;_spatialGrabRaycaster;_activeWebARSessionRoot=null;get isActiveWebXR(){return!ic.activeWebXRComponent||ic.activeWebXRComponent===this}onBeforeXR(e,t){if(!this.isActiveWebXR){console.warn(`WebXR: another WebXR component is already active (${ic.activeWebXRComponent?.name}). This is ignored: ${this.name}`);return}if(this.activeAndEnabled===!1||this.destroyed){console.debug("[WebXR] onBeforeXR called on disabled or destroyed component");return}ic.activeWebXRComponent=this,e=="immersive-ar"&&this.useDepthSensing&&(t.optionalFeatures=t.optionalFeatures||[],t.optionalFeatures.push("depth-sensing"))}async onEnterXR(e){if(!this.isActiveWebXR)return;fh&&console.log("WebXR onEnterXR"),this._previousXRState=ri.Global.Mask;const t=e.xr.isVR;if(ri.Global.Set(t?io.VR:io.AR),e.xr.isAR){let i=S.findObjectOfType(yn,this.context,!1);if(!i)if(this.usePlacementReticle){const n=new M;for(const s of this.context.scene.children)n.add(s);this.context.scene.add(n),i=S.addComponent(n,yn),this._createdComponentsInSession.push(i)}else(fh||A())&&console.warn("WebXR: No WebARSessionRoot found in scene and usePlacementReticle is disabled in WebXR component.");this._activeWebARSessionRoot=i,i&&(i.customReticle=this.customARPlacementReticle,i.arScale=this.arScale,i.arTouchTransform=this.usePlacementAdjustment,i.autoPlace=this.autoPlace,i.autoCenter=this.autoCenter,i.useXRAnchor=this.useXRAnchor)}this.useDefaultControls&&this.setDefaultMovementEnabled(!0),(this.showControllerModels||this.showHandModels)&&this.setDefaultControllerRenderingEnabled(!0),this.useSpatialGrab&&(this._spatialGrabRaycaster=S.findObjectOfType(Ca)??void 0,this._spatialGrabRaycaster||(this._spatialGrabRaycaster=this.gameObject.addComponent(Ca))),this.createLocalAvatar(e.xr),e.xr.isScreenBasedAR||(this._exitXRMenuButton=this.context.menu.appendChild({label:"Quit XR",onClick:()=>this.exitXR(),icon:"exit_to_app",priority:2e4}))}onUpdateXR(e){this.isActiveWebXR&&this._spatialGrabRaycaster&&(this._spatialGrabRaycaster.enabled=this.useSpatialGrab)}onLeaveXR(e){if(this._exitXRMenuButton?.remove(),!!this.isActiveWebXR){ri.Global.Set(this._previousXRState),this._playerSync?.destroyInstance();for(const t of this._createdComponentsInSession)t.destroy();this._createdComponentsInSession.length=0,this._activeWebARSessionRoot=null,this.handleOfferSession(),mc(1).then(()=>ic.activeWebXRComponent=null)}}setDefaultMovementEnabled(e){let t=this.gameObject.getComponent(Bi);return!t&&e&&(t=this.gameObject.addComponent(Bi),this._createdComponentsInSession.push(t)),t&&(t.enabled=e),t}setDefaultControllerRenderingEnabled(e){let t=this.gameObject.getComponent(Zo);return!t&&e&&(t=this.gameObject.addComponent(Zo),this._createdComponentsInSession.push(t),t.createControllerModel=this.showControllerModels,t.createHandModel==this.showHandModels),t&&(t.enabled=e),t}async createLocalAvatar(e){this._playerSync&&e.running&&typeof this.defaultAvatar!="boolean"&&(this._playerSync.asset=this.defaultAvatar,await this._playerSync.getInstance())}onAvatarSpawned=e=>{fh&&console.log("WebXR.onAvatarSpawned",e);let t=S.getComponentInChildren(e,Ws);t??=S.addComponent(e,Ws)};getButtonsContainer(){return this.getButtonsFactory()}getButtonsFactory(){return this._buttonFactory||(this._buttonFactory=ur.getOrCreate()),this._buttonFactory}_buttonFactory;handleCreatingHTML(){if(this.createARButton||this.createVRButton||this.useQuicklookExport){if((I.isiOS()&&I.isSafari()||CA)&&this.useQuicklookExport){const e=S.findObjectOfType(ho);if(!e||e&&e.allowCreateQuicklookButton){const t=this.getButtonsFactory().createQuicklookButton();this.addButton(t)}}if(this.createARButton){const e=this.getButtonsFactory().createARButton();this.addButton(e)}if(this.createVRButton){const e=this.getButtonsFactory().createVRButton();this.addButton(e)}}if(this.createSendToQuestButton&&!I.isQuest()&&Z.isVRSupported().then(e=>{if(!e){const t=this.getButtonsFactory().createSendToQuestButton();this.addButton(t)}}),this.createQRCode){const e=tl(lo);if(e&&e.createQRCodeButton===!1)A()&&console.warn("WebXR: QRCode button is disabled in the Needle Menu component");else if(!I.isMobileDevice()){const t=mn.getOrCreate().createQRCode();this.addButton(t)}}}_buttons=[];addButton(e){this._buttons.push(e),this.context.menu.appendChild(e)}removeButtons(){for(const e of this._buttons)e.remove();this._buttons.length=0}};xt([u()],ct.prototype,"createVRButton"),xt([u()],ct.prototype,"createARButton"),xt([u()],ct.prototype,"createSendToQuestButton"),xt([u()],ct.prototype,"createQRCode"),xt([u()],ct.prototype,"useDefaultControls"),xt([u()],ct.prototype,"showControllerModels"),xt([u()],ct.prototype,"showHandModels"),xt([u()],ct.prototype,"usePlacementReticle"),xt([u(ne)],ct.prototype,"customARPlacementReticle"),xt([u()],ct.prototype,"usePlacementAdjustment"),xt([u()],ct.prototype,"arScale"),xt([u()],ct.prototype,"useXRAnchor"),xt([u()],ct.prototype,"autoPlace"),xt([u()],ct.prototype,"autoCenter"),xt([u()],ct.prototype,"useQuicklookExport"),xt([u()],ct.prototype,"useDepthSensing"),xt([u()],ct.prototype,"useSpatialGrab"),xt([u(ne)],ct.prototype,"defaultAvatar");let Sp=ct;const Cp=w("debugusdzbehaviours");class $y{get extensionName(){return"Behaviour"}behaviours=[];addBehavior(e){this.behaviours.push(e)}addAudioClip(e){if(!e||typeof e!="string")return"";const t="audio/"+Pa.getName(e);return this.audioClips.push({clipUrl:e,filesKey:t}),t}behaviourComponents=[];behaviourComponentsCopy=[];audioClips=[];audioClipsCopy=[];targetUuids=new Set;getAllTargetUuids(){return this.targetUuids}onBeforeBuildDocument(e){if(!e.root)return Promise.resolve();const t=[];return e.root.traverse(i=>{S.foreachComponent(i,n=>{const s=n;if(typeof s.createBehaviours=="function"||typeof s.beforeCreateDocument=="function"||typeof s.afterCreateDocument=="function"||typeof s.afterSerialize=="function"){this.behaviourComponents.push(s);const r=s.beforeCreateDocument?.call(s,this,e);r instanceof Promise&&t.push(r)}},!1)}),Cp&&console.log("onBeforeBuildDocument: all components",this.behaviourComponents),Promise.all(t)}onExportObject(e,t,i){for(const n of this.behaviourComponents)n.createBehaviours?.call(n,this,t,i)}onAfterBuildDocument(e){for(const d of this.behaviourComponents)typeof d.afterCreateDocument=="function"&&d.afterCreateDocument(this,e);this.behaviourComponentsCopy=this.behaviourComponents.slice(),this.behaviourComponents.length=0,this.audioClipsCopy=this.audioClips.slice(),this.audioClips.length=0;const t=new Set,i=new Set,n=new Set,s=new Set,r=Cp;let a=`graph LR
1290
1290
  `,l="";function c(d){if(d instanceof Jr){r&&(a+=`subgraph Group_${d.id}
1291
1291
  `);for(const p of d.actions)r&&(a+=`${d.id}[${d.id}] -- ${d.type},loops:${d.loops} --> ${p.id}[${p.id}]
1292
1292
  `),c(p);r&&(a+=`end
@@ -1308,7 +1308,7 @@ dateFormat X
1308
1308
  axisFormat %s
1309
1309
  `;const p=Array.from(s),m=new Set;for(const _ of p)if(_.affectedObjects&&typeof _.affectedObjects!="string"){if(Array.isArray(_.affectedObjects))for(const v of _.affectedObjects)m.add(v);else m.add(_.affectedObjects);r&&(d+=`section ${_.animationName} (${_.id})
1310
1310
  `,d+=`${_.id} : ${_.start}, ${_.duration}s
1311
- `)}r&&s.size&&console.log(d);const g=new Set;for(const _ of m){_.getPath||console.error("USDZExporter: Animation target object has no getPath method. This is likely a bug",_);let v=_.getPath();v.startsWith("<")&&(v=v.substring(1)),v.endsWith(">")&&(v=v.substring(0,v.length-1)),g.add({path:v,obj:_})}const f=Array.from(g).sort((_,v)=>_.path.length-v.path.length),y=new Array;for(let _=0;_<f.length;_++)for(let v=_+1;v<f.length;v++)if(f[v].path.startsWith(f[_].path)){const P=f[v],k=f[_];y.push({child:P.obj.displayName+" ("+P.path+")",parent:k.obj.displayName+" ("+k.path+")"})}y.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:y,playAnimationActions:s})}for(const d of new Set([...t,...i]))if(Array.isArray(d))for(const p of d)n.add(p.uuid);else n.add(d.uuid);Cp&&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){Cp&&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 n=await(await(await fetch(t)).blob()).arrayBuffer(),s=new Uint8Array(n);e.files[i]=s}this.behaviourComponentsCopy.length=0,this.audioClipsCopy.length=0}}class Hy{get extensionName(){return"Physics"}onExportObject(e,t,i){const n=S.getComponents(e,Ze).filter(l=>l.enabled),s=S.getComponents(e,nn).filter(l=>l.enabled&&!l.isTrigger);let r=n.length>0?n[0]:null;const a=s.length>0?s[0]:null;a&&!r&&(r=new Ze,r.isKinematic=!0),r&&t.addEventListener("serialize",(l,c)=>{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("}"),s.length>0){const h=s[0];l.beginBlock('def RealityKitStruct "material"',"{",!0);const d=h.sharedMaterial;d&&d.dynamicFriction!==void 0&&l.appendLine(`double dynamicFriction = ${h.sharedMaterial?.dynamicFriction}`),d&&d.bounciness!==void 0&&l.appendLine(`double restitution = ${h.sharedMaterial?.bounciness}`),d&&d.staticFriction!==void 0&&l.appendLine(`double staticFriction = ${h.sharedMaterial?.staticFriction}`),l.closeBlock("}")}l.closeBlock("}")}}),a&&(t.addEventListener("serialize",(l,c)=>{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 h=a.isTrigger?"Trigger":"Default";if(l.appendLine(`token type = "${h}"`),l.beginBlock('def RealityKitStruct "Shape"',"{",!0),a instanceof pl){const d=a;l.appendLine('token shapeType = "Sphere"'),l.appendLine(`float radius = ${d.radius}`)}else if(a instanceof Gu){const d=a;l.appendLine('token shapeType = "Box"'),l.appendLine(`float3 extent = (${d.size.x}, ${d.size.y}, ${d.size.z})`)}else if(a instanceof Wo){const d=a;l.appendLine('token shapeType = "Capsule"'),l.appendLine(`float radius = ${d.radius}`),l.appendLine(`float height = ${d.height}`)}else if(a instanceof js&&a.sharedMesh?.geometry){const d=a.sharedMesh.geometry;d.boundingBox||d.computeBoundingBox();const p=a.sharedMesh.geometry.boundingBox;p&&(l.appendLine('token shapeType = "Box"'),l.appendLine(`float3 extent = (${p.max.x-p.min.x}, ${p.max.y-p.min.y}, ${p.max.z-p.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("}")}),s.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 PA=w("debugshadowcomponents");Hb.prototype.interactable={get(){return this.interactive},set(o){this.interactable=o}};class un 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(){ai.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,yh)),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,un),!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[Ai]=this,this.setShadowComponentOwner(e);let n=!1;if(this.Root?.gameObject===this.gameObject)this.gameObject.add(e);else{const s=this._parentComponent.shadowComponent;s&&(s?.add(e),n=!0)}this.shadowComponent=e,t&&t.shadowComponent&&this.shadowComponent&&t.shadowComponent.add(this.shadowComponent),Dc&&e.add(new Ci(.5)),this.onAfterAddedToScene(),n&&zP(),PA&&console.warn("Added shadow component",this.shadowComponent)}setShadowComponentOwner(e){if(e&&(e[Ai]===void 0||e[Ai]===this)&&(e[Ai]=this,e.children))for(const t of e.children)this.setShadowComponentOwner(t)}traverseOwnedShadowComponents(e,t,i){if(e&&e[Ai]===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 yh extends un{awake(){super.awake()}}var OA=Object.defineProperty,kA=Object.getOwnPropertyDescriptor,bh=(o,e,t,i)=>{for(var n=i>1?void 0:i?kA(e,t):e,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&OA(e,t,n),n};const Gy=w("debugui"),qy=w("debuguilayout");class w1{width;height}class x1{x;y;width;height}const In=new b,_h=new J,Pp=new N,Tl=class US extends un{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 K),this._anchoredPosition}set anchoredPosition(e){this._anchoredPosition=e}sizeDelta=new K(100,100);pivot=new K(.5,.5);anchorMin=new K(0,0);anchorMax=new K(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 M,this.rectBlock.name=this.name,this.lastMatrix=new J,this._lastAnchoring=null,this._initialPosition=this.gameObject.position.clone(),this._initialPosition.z=0,this._anchoredPosition||(this._anchoredPosition=new K),hl(this,"_anchoredPosition",()=>{this.markDirty()}),hl(this,"sizeDelta",()=>{this.markDirty()}),hl(this,"pivot",()=>{this.markDirty()}),hl(this,"anchorMin",()=>{this.markDirty()}),hl(this,"anchorMax",()=>{this.markDirty()})}onEnable(){super.onEnable(),this.rectBlock||(this.rectBlock=new M),this.lastMatrix||(this.lastMatrix=new J),this._lastAnchoring||(this._lastAnchoring=new K),this._initialPosition||(this._initialPosition=new b),this._anchoredPosition||(this._anchoredPosition=new K),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(qy?`${e.name} changed`:void 0)}get isDirty(){return this._transformNeedsUpdate||(this._transformNeedsUpdate=!this.lastMatrix.equals(this.gameObject.matrix)),this._transformNeedsUpdate}markDirty(){this._transformNeedsUpdate||(qy&&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,US):this._parentRectTransform=void 0,this._transformNeedsUpdate=!1,qy&&console.warn("RectTransform \u2192 ApplyTransform",this.name+" because "+e),this.isRoot()?this.Root.screenspace||(t.rotation.y=Math.PI):(t.matrix.identity(),t.matrixAutoUpdate=!1,In.set(0,0,0),this.applyPivot(In),t.matrix.setPosition(In.x,In.y,0),(this.gameObject.quaternion.x||this.gameObject.quaternion.y||this.gameObject.quaternion.z)&&(Pp.copy(this.gameObject.quaternion),Pp.x*=-1,Pp.z*=-1,_h.makeRotationFromQuaternion(Pp),t.matrix.premultiply(_h)),In.set(0,0,0),this.applyAnchoring(In),this.canvas?.screenspace?In.z+=.1:In.z+=.01,_h.identity(),_h.setPosition(In.x,In.y,In.z),t.matrix.premultiply(_h),t.matrix.scale(this.gameObject.scale)),this.lastMatrix.copy(this.gameObject.matrix);const i=!0;for(const n of vu(this.gameObject,un,i,1)){if(n===this||!n.activeAndEnabled)continue;const s=n;s.onParentRectTransformChanged&&s.onParentRectTransformChanged(this)}}_lastAnchoring;applyAnchoring(e){this._lastAnchoring||(this._lastAnchoring=new K);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 s=1-this.anchorMax.y-this.anchorMin.y;n-=i.height*.5*s,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},Gy&&console.log(this.name,e);const t=new Hb(e);return this._createdBlocks.push(t),t}createNewText(e){Gy&&console.log(e),e={...this.getBasicOptions(),...e},Gy&&console.log(this.name,e);const t=new $b(e);return this._createdTextBlocks.push(t),t}};bh([u(K)],Tl.prototype,"anchoredPosition",1),bh([u(K)],Tl.prototype,"sizeDelta",2),bh([u(K)],Tl.prototype,"pivot",2),bh([u(K)],Tl.prototype,"anchorMin",2),bh([u(K)],Tl.prototype,"anchorMax",2);let Ln=Tl;var MA=Object.defineProperty,S1=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&MA(e,t,n),n};class Al extends E{effectColor;effectDistance}S1([u(se)],Al.prototype,"effectColor"),S1([u(K)],Al.prototype,"effectDistance");var EA=Object.defineProperty,RA=Object.getOwnPropertyDescriptor,C1=(o,e,t,i)=>{for(var n=i>1?void 0:i?RA(e,t):e,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&EA(e,t,n),n};const ta={backgroundColor:new oe(1,1,1),backgroundOpacity:1,borderColor:new oe(1,1,1),borderOpacity:1},Xy=class fd extends un{get isGraphic(){return!0}get color(){return this._color||(this._color=new se(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 se(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 oe(1,0,1);onColorChanged(){if(this.uiObject){this.sRGBColor.copy(this._color),this.sRGBColor.convertLinearToSRGB(),ta.backgroundColor=this.sRGBColor,ta.backgroundOpacity=this._color.alpha;const e=this.uiObject._simpleState__activeStates?.[0];if(e){const t=this.uiObject._simpleState__states?.[e];t&&("backgroundColor"in t&&(ta.backgroundColor=t.backgroundColor),"backgroundOpacity"in t&&(ta.backgroundOpacity=t.backgroundOpacity))}ta.backgroundOpacity*=this._alphaFactor,this.applyEffects(ta,this._alphaFactor),this.uiObject.set(ta),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,Ln)),!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 NP(this.uiObject)),this.uiObject.setupState(e.state,e.attributes))}setOptions(e){this.makePanel(),this.uiObject&&this.uiObject.set(e)}awake(){super.awake(),this.makePanel(),hl(this,"_color",()=>uR(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 e={backgroundColor:this.color,backgroundOpacity:this.color.alpha,offset:.015};this.onBeforeCreate(e),this.applyEffects(e),this.onCreate(e),this.controlsChildLayout=!1,this._currentlyCreatingPanel=!1,this.onAfterCreated(),this.onColorChanged()}onBeforeCreate(e){}onCreate(e){this.uiObject=this.rectTransform.createNewBlock(e),this.uiObject.name=this.name}onAfterCreated(){}applyEffects(e,t=1){const i=this.gameObject?.getComponent(Al);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(fd.textureCache.has(e))e=fd.textureCache.get(e);else if(!e.isRenderTargetTexture){const t=e.clone();t.colorSpace=Po,fd.textureCache.set(e,t),e=t}this.setOptions({backgroundImage:e,borderRadius:0,backgroundOpacity:this.color.alpha,backgroundSize:"stretch"}),Ve.assignTextureLOD(e,0).then(t=>{t instanceof Se&&(e&&fd.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)}};C1([u(se)],Xy.prototype,"color",1),C1([u()],Xy.prototype,"raycastTarget",2);let vh=Xy;class wh extends vh{_flippedObject=!1;onAfterCreated(){this.uiObject&&!this._flippedObject&&(this._flippedObject=!0,this.uiObject.scale.y*=-1)}}var TA=Object.defineProperty,AA=Object.getOwnPropertyDescriptor,Ko=(o,e,t,i)=>{for(var n=i>1?void 0:i?AA(e,t):e,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&TA(e,t,n),n};const ia=w("debugtext");var ht=(o=>(o[o.UpperLeft=0]="UpperLeft",o[o.UpperCenter=1]="UpperCenter",o[o.UpperRight=2]="UpperRight",o[o.MiddleLeft=3]="MiddleLeft",o[o.MiddleCenter=4]="MiddleCenter",o[o.MiddleRight=5]="MiddleRight",o[o.LowerLeft=6]="LowerLeft",o[o.LowerCenter=7]="LowerCenter",o[o.LowerRight=8]="LowerRight",o))(ht||{}),P1=(o=>(o[o.Normal=0]="Normal",o[o.Bold=1]="Bold",o[o.Italic=2]="Italic",o[o.BoldAndItalic=3]="BoldAndItalic",o))(P1||{});class Ht extends vh{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 oe(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){ia&&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,ia&&(e.backgroundColor=16750848,e.backgroundOpacity=.5);const t=this.rectTransform;e={...e,...this.getTextOpts()},this.getAlignment(e),ia&&(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(ia&&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 s=new Wm({textContent:e.substring(0,i.startIndex),color:"inherit"});this.uiObject.add(s)}}else{this.uiObject.textContent="",this.setOptions({textContent:e});return}const n=[];for(;i;){const s=this.getNextTag(e,i.endIndex),r={fontFamily:this.uiObject?.get("fontFamily"),color:"inherit",textContent:""};if(s){r.textContent=this.getText(e,i,s),this.handleTag(i,r,n);const a=new Wm(r);this.uiObject?.add(a)}else{r.textContent=e.substring(i.endIndex),this.handleTag(i,r,n);const a=new Wm(r);this.uiObject?.add(a)}i=s}}}_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 s=0;s<this._textMeshUi.length;s++){if(e[s]===!0)continue;n=!0;const r=this._textMeshUi[s];r.textContent&&(Wu(r,i),e[s]=!0)}if(!n)break;yield}}handleTag(e,t,i){if(!e.isEndTag){if(e.type.includes("color")){const n=new Qy(e,{color:t.color});if(i.push(n),e.type.length>6){const s=parseInt("0x"+e.type.substring(7));t.color=s}else t.color=new oe(1,1,1)}else if(e.type=="b"){this.setFont(t,1);const n=new Qy(e,{fontWeight:700});i.push(n)}else if(e.type=="i"){this.setFont(t,2);const n=new Qy(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 s=e.substring(i+1,n);return{type:s,startIndex:i,endIndex:n+1,isEndTag:s.startsWith("/")}}return null}setFont(e,t){if(!this.font)return;const i=this.font,n=this.getFamilyNameWithCorrectSuffix(i,t);ia&&console.log("Selected font family:"+n);let s=Gb.getFontFamily(n);switch(s||(s=Gb.addFontFamily(n)),e.fontFamily=s,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=s.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=s.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(IA.includes(n))return ia&&console.warn("Unsupported font style: "+n),e;const s=e.lastIndexOf("/");let r=e;s>=0&&(r=r.substring(s+1));const a=r[0]===r[0].toUpperCase(),l=e.substring(0,i>s?i:e.length);switch(ia&&console.log("Select font: ",e,P1[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}}}Ko([u()],Ht.prototype,"alignment",2),Ko([u()],Ht.prototype,"verticalOverflow",2),Ko([u()],Ht.prototype,"horizontalOverflow",2),Ko([u()],Ht.prototype,"lineSpacing",2),Ko([u()],Ht.prototype,"supportRichText",2),Ko([u(URL)],Ht.prototype,"font",2),Ko([u()],Ht.prototype,"fontStyle",2),Ko([u()],Ht.prototype,"text",1),Ko([u()],Ht.prototype,"fontSize",1);class Qy{tag;previousValues;constructor(e,t){this.tag=e,this.previousValues=t}}const IA=["medium","mediumitalic","black","blackitalic","thin","thinitalic","extrabold","light","lightitalic","semibold"];class Il{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/${mp(this.material)}>`),t.closeBlock()}}class Yy{static singleLine(e,t,i){const n=new Il("text_"+Il.getId());return n.content=e,t&&(n.pointSize=t),i&&(n.depth=i),n}static multiLine(e,t,i,n,s,r){const a=new Il("text_"+Il.getId());return a.content=e,a.width=t,a.height=i,a.horizontalAlignment=n,a.verticalAlignment=s,r!==void 0&&(a.wrapMode=r),a}}const LA=new J().makeRotationY(Math.PI),DA=new J().makeScale(-1,1,-1);class Op{get extensionName(){return"text"}exportText(e,t,i){const n=S.getComponent(e,Ht);if(!n)return;const s=S.getComponent(e,Ln);let r=100,a=100;s&&(r=s.width,a=s.height);const l=LA.clone();s&&l.premultiply(DA),t.setMatrix(l);const c=n.color.clone();t.material=new gt({color:c,emissive:c}),t.addEventListener("serialize",(h,d)=>{let p=n.text;p=p.replace(/\r/g,""),p=p.replace(/\n/g,"\\n");const m=Yy.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,h)})}convertToTextSize(e){return 1/.0502*144*e}setOverflow(e,t){t.horizontalOverflow?e.wrapMode="singleLine":e.wrapMode="flowing"}setTextAlignment(e,t){switch(t){case ht.LowerLeft:case ht.MiddleLeft:case ht.UpperLeft:e.horizontalAlignment="left";break;case ht.LowerCenter:case ht.MiddleCenter:case ht.UpperCenter:e.horizontalAlignment="center";break;case ht.LowerRight:case ht.MiddleRight:case ht.UpperRight:e.horizontalAlignment="right";break}switch(t){case ht.LowerLeft:case ht.LowerCenter:case ht.LowerRight:e.verticalAlignment="bottom";break;case ht.MiddleLeft:case ht.MiddleCenter:case ht.MiddleRight:e.verticalAlignment="middle";break;case ht.UpperLeft:case ht.UpperCenter:case ht.UpperRight:e.verticalAlignment="top";break}}}var jA=Object.defineProperty,et=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&jA(e,t,n),n};const O1=w("debuguilayout");class na{left=0;right=0;top=0;bottom=0;get vertical(){return this.top+this.bottom}get horizontal(){return this.left+this.right}}et([u()],na.prototype,"left"),et([u()],na.prototype,"right"),et([u()],na.prototype,"top"),et([u()],na.prototype,"bottom");class Fi 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&&(O1&&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(){O1&&console.log(this.name,this),this._rectTransform=this.gameObject.getComponent(Ln);const e=this.gameObject.getComponentInParent(Ll);e&&e.registerLayoutGroup(this),this._needsUpdate=!0}onDisable(){const e=this.gameObject.getComponentInParent(Ll);e&&e.unregisterLayoutGroup(this)}set m_Spacing(e){e!==this.spacing&&(this._needsUpdate=!0,this.spacing=e)}get m_Spacing(){return this.spacing}}et([u()],Fi.prototype,"childAlignment"),et([u()],Fi.prototype,"reverseArrangement"),et([u()],Fi.prototype,"spacing"),et([u(na)],Fi.prototype,"padding"),et([u()],Fi.prototype,"minWidth"),et([u()],Fi.prototype,"minHeight"),et([u()],Fi.prototype,"flexibleHeight"),et([u()],Fi.prototype,"flexibleWidth"),et([u()],Fi.prototype,"preferredHeight"),et([u()],Fi.prototype,"preferredWidth");class Gs extends Fi{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 s=e.height;let r=s;n-=this.padding.horizontal,r-=this.padding.vertical,t==="x"?this.padding.horizontal:this.padding.vertical;const a=t==="x",l=a?"y":"x",c=a?this.childControlWidth:this.childControlHeight,h=a?this.childControlHeight:this.childControlWidth,d=a?this.childForceExpandWidth:this.childForceExpandHeight,p=a?this.childForceExpandHeight:this.childForceExpandWidth,m=a?r:n,g=a?i:s,f=.5*(a?this.childAlignment%3:Math.floor(this.childAlignment/3));let y=0;a?y+=this.padding.left:y+=this.padding.top;let _=0,v=0;for(let L=0;L<this.gameObject.children.length;L++){const V=this.gameObject.children[L],W=S.getComponent(V,Ln);W?.activeAndEnabled&&(v+=1,a?_+=W.width:_+=W.height)}let P=0;const k=this.spacing*(v-1);if(d||c){let L=0;a?L=n-=k:L=r-=k,v>0&&(P=L/v)}let O=0;O+=this.padding.left,O-=this.padding.right,f!==0&&(y=g-_,y*=f,y-=k*f,a?(y-=this.padding.right*f,y+=this.padding.left*(1-f),y<this.padding.left&&(y=this.padding.left)):(y-=this.padding.bottom*f,y+=this.padding.top*(1-f),y<this.padding.top&&(y=this.padding.top)));let D=1;for(let L=0;L<this.gameObject.children.length;L++){const V=this.gameObject.children[L],W=S.getComponent(V,Ln);if(W?.activeAndEnabled){W.pivot?.set(.5,.5),W.anchorMin.set(0,1),W.anchorMax.set(0,1);const G=i*.5+O*.5;W.anchoredPosition.x!==G&&(W.anchoredPosition.x=G);const X=s*-.5;W.anchoredPosition.y!==X&&(W.anchoredPosition.y=X),p&&h&&W.sizeDelta[l]!==m&&(W.sizeDelta[l]=m),d&&c&&W.sizeDelta[t]!==P&&(W.sizeDelta[t]=P);const R=a?W.width:W.height,$=R*.5;if(y+=$,d){const he=P*D-P*.5;he>y&&(y=he-P*.5+R+this.padding.left,y-=$)}let q=y;t==="y"&&(q=-q),W.anchoredPosition[t]!==q&&(W.anchoredPosition[t]=q),y+=$,y+=this.spacing,D+=1}}}}et([u()],Gs.prototype,"childControlHeight"),et([u()],Gs.prototype,"childControlWidth"),et([u()],Gs.prototype,"childForceExpandHeight"),et([u()],Gs.prototype,"childForceExpandWidth"),et([u()],Gs.prototype,"childScaleHeight"),et([u()],Gs.prototype,"childScaleWidth");class Zy extends Gs{get primaryAxis(){return"y"}}class Ky extends Gs{get primaryAxis(){return"x"}}class Jy extends Fi{onCalculateLayout(){}}var BA=Object.defineProperty,FA=Object.getOwnPropertyDescriptor,co=(o,e,t,i)=>{for(var n=i>1?void 0:i?FA(e,t):e,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&BA(e,t,n),n},k1=(o=>(o[o.ScreenSpaceOverlay=0]="ScreenSpaceOverlay",o[o.ScreenSpaceCamera=1]="ScreenSpaceCamera",o[o.WorldSpace=2]="WorldSpace",o[o.Undefined=-1]="Undefined",o))(k1||{});const e0=w("debuguilayout"),rn=class zS extends yh{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 zS||(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,e0&&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 J,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 mc(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(),ai.ensureUpdateMeshUI(qb,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(),ai.ensureUpdateMeshUI(qb,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 J);const e=!this._lastMatrixWorld.equals(this.gameObject.matrixWorld);e0&&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(Fi)),(t.isDirty||i?.isDirty)&&(e0&&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(),xe.OnBeforeRender))}*_updateRenderSettingsDelayed(){if(yield,this._updateRenderSettingsRoutine=void 0,this.shadowComponent){this.onUpdateRenderMode(),Wu(this.shadowComponent,this);for(const e of S.getComponentsInChildren(this.gameObject,un))Wu(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=j.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 s=this.gameObject.getComponent(Ln);let r=!1;s.sizeDelta.x!==this.context.domWidth&&(r=!0),s.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&&(s.sizeDelta.x=this.context.domWidth,s.sizeDelta.y=this.context.domHeight,s?.markDirty());break;case 2:this._lastWidth=-1,this._lastHeight=-1;break}}};co([u()],rn.prototype,"renderOnTop",1),co([u()],rn.prototype,"depthWrite",1),co([u()],rn.prototype,"doubleSided",1),co([u()],rn.prototype,"castShadows",1),co([u()],rn.prototype,"receiveShadows",1),co([u()],rn.prototype,"renderMode",1),co([u(rn)],rn.prototype,"rootCanvas",1),co([u()],rn.prototype,"scaleFactor",1),co([u(gi)],rn.prototype,"worldCamera",2),co([u()],rn.prototype,"planeDistance",2);let Ll=rn;var UA=Object.defineProperty,zA=Object.getOwnPropertyDescriptor,t0=(o,e,t,i)=>{for(var n=i>1?void 0:i?zA(e,t):e,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&UA(e,t,n),n};class qs 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(),xe.OnBeforeRender))}*applyChangesDelayed(){this._isDirty=!1,this.applyChangesNow()}_buffer=[];applyChangesNow(){this._buffer.length=0;for(const e of S.getComponentsInChildren(this.gameObject,un,this._buffer)){const t=e;t.setAlphaFactor&&t.setAlphaFactor(this._alpha)}}}t0([u()],qs.prototype,"alpha",1),t0([u()],qs.prototype,"interactable",2),t0([u()],qs.prototype,"blocksRaycasts",2);class i0{get extensionName(){return"tmui"}onExportObject(e,t,i){const n=S.getComponent(e,Ll);if(n&&n.enabled&&n.renderMode===k1.WorldSpace){const s=new Op,r=S.getComponent(e,Ln),a=S.getComponent(e,qs),l=new Array;if(r){if(!S.isActiveSelf(e)){const d=S.isActiveSelf(e);S.setActive(e,!0),r.onEnable(),r.updateTransform(),l.push(()=>{r.onDisable(),S.setActive(e,d)})}e.traverse(d=>{if(!S.isActiveInHierarchy(d)){const p=S.isActiveSelf(d);S.setActive(d,!0);const m=S.getComponent(d,un);m&&(m.onEnable(),l.push(()=>{m.onDisable()}));const g=S.getComponent(d,Ln);g&&(g.onEnable(),g.updateTransform(),g.onApplyTransform(),l.push(()=>{g.onDisable()}));const f=S.getComponent(d,Ht);f&&(f.onEnable(),l.push(()=>{f.onDisable()})),l.push(()=>{S.setActive(d,p)})}}),r.width,r.height;const c=rt.createEmpty(),h=r.shadowComponent;if(t.add(c),h){const d=h.matrix;c.setMatrix(d);const p=new Map,m=new Map;p.set(h,c),m.set(h,a?a.alpha:1),h.traverse(g=>{if(g===h)return;const f=rt.createEmpty();f.setMatrix(g.matrix);const y=g.parent,_=!!y&&typeof y.textContent=="string"&&y.textContent.length>0;let v=m.get(y)||1;const P=S.getComponent(g,qs);if(P&&(v*=P.alpha),g instanceof H&&_){const O=g[Ai];O?s.exportText(O.gameObject,f,i):console.error("Error when exporting UI: shadow component owner not found. This is likely a bug.",g)}if(g instanceof H&&!_){const O=g.geometry.clone();O.scale(1,1,-1),this.flipWindingOrder(O),f.geometry=O;const D=new oe,L=g.material.opacity;D.copy(g.material.color),f.material=new Ce({color:D,opacity:L*v,map:g.material.map,transparent:!0})}p.set(g,f),m.set(g,v);const k=p.get(y);if(!k){console.error("Error when exporting UI: shadow component parent not found!",g,g.parent);return}k.add(f)})}}for(const c of l)c()}}flipWindingOrder(e){const t=e.index.array;for(let i=0,n=t.length/3;i<n;i++){const s=t[i*3];t[i*3]=t[i*3+2],t[i*3+2]=s}e.index.needsUpdate=!0}}const xh=w("debugusdz");function NA(o,e){const t=[],i=S.getComponentsInChildren(o,_t),n=S.getComponentsInChildren(o,Ut),s=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||s.includes(a))continue;const c=new hh;c.animator=a,c.stateName=l.name,c.trigger="start",c.name="PlayAnimationOnClick_implicitAtStart_"+c.stateName;const h=new M;S.addComponent(h,c),r.push(h),s.push(a),o.add(h)}else for(const a of i){if(!a||!a.runtimeAnimatorController||!a.enabled)continue;xh&&console.log(a);const l=[];for(const c of a.runtimeAnimatorController.enumerateActions()){xh&&console.log(c);const h=c.getClip();l.includes(h)||l.push(h)}t.push({root:a.gameObject,clips:l})}if(e.injectImplicitBehaviours)for(const a of n){if(!a||!a.clip||!a.enabled||!a.playAutomatically||s.includes(a))continue;const l=new hh;l.animation=a,l.stateName=a.clip.name,l.trigger="start",l.name="PlayAnimationOnClick_implicitAtStart_"+l.stateName;const c=new M;S.addComponent(c,l),r.push(c),s.push(a),o.add(c)}else for(const a of n){xh&&console.log(a);const l=[];for(const c of a.animations)l.includes(c)||l.push(c);t.push({root:a.gameObject,clips:l})}xh&&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 WA(o,e){const t=S.getComponentsInChildren(o,Di),i=S.getComponentsInChildren(o,zs),n=new Array,s=new Array;xh&&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 zs;a.target=r,a.name="PlayAudioOnClick_implicitAtStart_",a.trigger="start";const l=new M;S.addComponent(l,a),console.log("implicit PlayAudioOnStart",l,a),s.push(l),n.push(r),o.add(l)}return s}function VA(o){return new jt("DisableAtStart",$t.sceneStartTrigger(),fe.fadeAction(o,0,!1))}function M1(o,e){const t=o.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 s=document.createElement("a");s.id="needle-usdz-link",s.style.display="none",s.rel="ar",s.href="",s.target="_blank",i.appendChild(s);const r=document.createElement("img");return r.id="button",s.appendChild(r),o.domElement.shadowRoot.appendChild(i),s}var $A=Object.defineProperty,Rt=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&$A(e,t,n),n};const Tt=w("debugusdz"),HA=w("debugusdzpruning");class oa{callToAction;checkoutTitle;checkoutSubtitle;callToActionURL}Rt([u()],oa.prototype,"callToAction"),Rt([u()],oa.prototype,"checkoutTitle"),Rt([u()],oa.prototype,"checkoutSubtitle"),Rt([u()],oa.prototype,"callToActionURL");const bi=class Sa extends E{static beforeExport=new ae;static afterExport=new ae;static beforeLODExport=new ae;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(){Tt&&(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=I.supportsQuickLookAR(),t=I.isiOS()||I.isiPad();!this.button&&(Tt||e||t)&&(this.allowCreateQuicklookButton&&(this.button=this.createQuicklookButton()),this.lastCallback=this.quicklookCallback.bind(this),this.link=M1(this.context,e),this.link.addEventListener("message",this.lastCallback)),Tt&&Oe("USDZ Exporter enabled: "+this.name),document.getElementById("open-in-ar")?.addEventListener("click",this.onClickedOpenInARElement),kc.registerExporter(this)}onDisable(){this.button?.remove(),this.link?.removeEventListener("message",this.lastCallback),Tt&&Oe("USDZ Exporter disabled: "+this.name),document.getElementById("open-in-ar")?.removeEventListener("click",this.onClickedOpenInARElement),kc.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+="-"+Xx(),Yn()||(e!==""&&(e+="-"),e+="MadeWithNeedle"),this.link||(this.link=M1(this.context,I.supportsQuickLookAR())),this.customUsdzFile)return Tt&&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;Sa.beforeExport.invoke({exporter:this});const t=await this.export(this.objectToExport).finally(()=>{Sa.afterExport.invoke({exporter:this})});return t?(Tt&&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 \u2013 please report a bug!",n),null))):i}_currentExportTasks=new Map;_previousTimeScale=1;async internalExport(e){le.start("export-usdz",{onProgress:k=>{this.dispatchEvent(new CustomEvent("export-progress",{detail:{progress:k}}))}}),le.report("export-usdz",{message:"Starting export",totalSteps:40,currentStep:0}),le.report("export-usdz",{message:"Load progressive textures",autoStep:5}),le.start("export-usdz-textures","export-usdz");const t=S.getComponentsInChildren(e,yi);for(const k of t)k&&k.enabled&&k.updateSprite(!0);const i=S.getComponentsInChildren(e,ei),n=new Array;let s=0;for(const k of i){for(const O of k.sharedMeshes)if(O){let D=0;const L={exporter:this,type:"mesh",object:k.gameObject,mesh:O};if(Sa.beforeLODExport.invoke(L),L.overrideLevel!==void 0)if(L.overrideLevel===-1){Tt&&console.warn("Skipping LOD export for mesh due to overrideLevel -1",k.gameObject,O);continue}else L.overrideLevel>=0&&(D=L.overrideLevel,Tt&&console.log("Overriding LOD level for mesh export to level "+D+" "+O.name));const V=Ve.assignMeshLOD(O,D);V instanceof Promise&&n.push(new Promise((W,G)=>{V.then(()=>{s++,le.report("export-usdz-textures",{message:"Loaded progressive mesh",currentStep:s,totalSteps:n.length}),W()}).catch(X=>G(X))}))}for(const O of k.sharedMaterials)if(O){let D=0;const L={exporter:this,type:"texture",object:k.gameObject,material:O};if(Sa.beforeLODExport.invoke(L),L.overrideLevel!==void 0)if(L.overrideLevel===-1){Tt&&console.warn("Skipping LOD assignment due to overrideLevel -1",k.gameObject,O);continue}else L.overrideLevel>=0&&(D=L.overrideLevel,Tt&&console.log("Overriding LOD level for texture export to level "+D+" "+O.name));const V=Ve.assignTextureLOD(O,D);V instanceof Promise&&n.push(new Promise((W,G)=>{V.then(()=>{s++,le.report("export-usdz-textures",{message:"Loaded progressive texture",currentStep:s,totalSteps:n.length}),W()}).catch(X=>G(X))}))}}Tt&&Oe("Progressive Loading: "+n.length),await Promise.all(n),Tt&&Oe("Progressive Loading: done"),le.end("export-usdz-textures");const r=ri.Global.Mask;ri.Global.Set(io.AR);const a=new e1,l=new yp(this.quickLookCompatible);let c;const h=[];this.interactive&&(h.push(new $y),h.push(new Pa),globalThis.NEEDLE_USE_RAPIER&&S.getComponentsInChildren(e,Ze).length>0&&(this.physics?(c=new Hy,h.push(c)):A()&&console.warn("USDZExporter: Physics export is disabled, but there are active Rigidbody components in the scene. They will not be exported.")),h.push(new Op),h.push(new i0));const d=[l,...h,...this.extensions],p={self:this,exporter:a,extensions:d,object:e};le.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,le.report("export-usdz","auto export animations and audio sources");const m=new Array;this.autoExportAnimations&&m.push(...NA(e,l)),d.find(k=>k.extensionName==="Audio")&&this.autoExportAudioSources&&m.push(...WA(e)),a.debug=Tt,a.pruneUnusedNodes=!HA;const g=Oa.instance.objs.map(k=>k.batchedMesh);a.keepObject=k=>{let O=!0;const D=S.getComponent(k,ei);return D&&!D.enabled&&(O=!1),O&&g.includes(k)&&(O=!1),O&&S.getComponentInParent(k,nh)&&(O=!1),O&&S.getComponentInParent(k,Kn)&&(O=!1),Tt&&!O&&console.log("USDZExporter: Discarding object",k),O},a.beforeWritingDocument=()=>{if(A()&&l&&c){const k=l.animatedRoots;for(const O of k){const D=S.getComponentsInChildren(O,Ze).filter(V=>V.enabled),L=S.getComponents(O,nn).filter(V=>V.enabled&&!V.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.",O)}}};const f=new Array;this.objectToExport&&this.quickLookCompatible&&this.interactive&&this.objectToExport.traverse(k=>{k.visible||f.push(k)});const y=d.find(k=>k.extensionName==="Behaviour");this.interactive&&y&&f.length>0&&y.addBehavior(VA(f));let _=!0;this.quickLookCompatible&&!this.interactive&&(_=!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"),le.report("export-usdz","Invoking exporter.parse");const v=await a.parse(this.objectToExport,{ar:{anchoring:{type:this.anchoringType},planeAnchoring:{alignment:this.planeAnchoringAlignment}},extensions:d,quickLookCompatible:this.quickLookCompatible,maxTextureSize:this.maxTextureSize,exportInvisible:_}),P=new Blob([v],{type:"model/vnd.usdz+zip"});this.revertWebARSessionRoot(),this.context.time.timeScale=this._previousTimeScale,le.report("export-usdz","Invoking after-export"),this.dispatchEvent(new CustomEvent("after-export",{detail:p}));for(const k of m)S.destroy(k);return ri.Global.Set(r),le.end("export-usdz"),P}openInQuickLook(e,t){const i=e instanceof Blob?URL.createObjectURL(e):e,n=this.buildQuicklookOverlay();Tt&&console.log("QuickLook Overlay",n);const s=n.callToAction?encodeURIComponent(n.callToAction):"",r=n.checkoutTitle?encodeURIComponent(n.checkoutTitle):"",a=n.checkoutSubtitle?encodeURIComponent(n.checkoutSubtitle):"";this.link.href=i+`#callToAction=${s}&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){Sa.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"){Tt&&be("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");Tt&&Oe("Quicklook url: "+n),n&&(Yn()?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),Yn()||(console.log("Custom Quicklook banner text requires pro license: https://needle.tools/pricing"),e.callToAction="Close",e.checkoutTitle="\u{1F335} 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 J().makeRotationY(Math.PI);static invertForwardQuaternion=new N().setFromEuler(new at(0,Math.PI,0));_rootSessionRootWasAppliedTo=null;_rootPositionBeforeExport=new b;_rootRotationBeforeExport=new N;_rootScaleBeforeExport=new b;getARScaleAndTarget(){if(!this.objectToExport)return{scale:1,_invertForward:!1,target:this.gameObject,sessionRoot:null};const e=S.findObjectOfType(Sp);let t=S.getComponentInParent(this.objectToExport,yn);t||(t=S.getComponentInChildren(this.objectToExport,yn));let i=1,n=!1;const s=this.objectToExport;return e?i=e.arScale:t&&(i=t.arScale,n=t.invertForward),{scale:1/i,_invertForward:n,target:s,sessionRoot:t?.gameObject??null}}applyWebARSessionRoot(){if(!this.objectToExport)return;const{scale:e,_invertForward:t,target:i,sessionRoot:n}=this.getARScaleAndTarget(),s=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(Sa.invertForwardQuaternion),i.updateMatrix(),i.updateMatrixWorld(!0),n&&s&&i.matrix.premultiply(s)}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 e=ur.getOrCreate().createQuicklookButton();return e.parentNode||this.context.menu.appendChild(e),e}};Rt([u(M)],bi.prototype,"objectToExport"),Rt([u()],bi.prototype,"autoExportAnimations"),Rt([u()],bi.prototype,"autoExportAudioSources"),Rt([u()],bi.prototype,"exportFileName"),Rt([u(URL)],bi.prototype,"customUsdzFile"),Rt([u(oa)],bi.prototype,"customBranding"),Rt([u()],bi.prototype,"anchoringType"),Rt([u()],bi.prototype,"maxTextureSize"),Rt([u()],bi.prototype,"planeAnchoringAlignment"),Rt([u()],bi.prototype,"interactive"),Rt([u()],bi.prototype,"physics"),Rt([u()],bi.prototype,"allowCreateQuicklookButton"),Rt([u()],bi.prototype,"quickLookCompatible");let ho=bi;var GA=Object.defineProperty,qA=Object.getOwnPropertyDescriptor,n0=(o,e,t,i)=>{for(var n=qA(e,t),s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&GA(e,t,n),n};class Dl extends E{get fog(){return this._fog||(this._fog=new bb(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)}}n0([u()],Dl.prototype,"near"),n0([u()],Dl.prototype,"far"),n0([u(oe)],Dl.prototype,"color");var XA=Object.defineProperty,o0=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&XA(e,t,n),n};class sa extends E{objectBounds=!1;color;isGizmo=!0;_gizmoObject=null;_boxHelper=null;onEnable(){this.isGizmo&&!Dc||(this._gizmoObject||(this.objectBounds?this._gizmoObject=new VC(this.gameObject,this.color??16776960):(this.objectBounds=!1,this._gizmoObject=Fg(this.color??16776960))),this.objectBounds?(this.scene.add(this._gizmoObject),this._boxHelper=this._gizmoObject,this.startCoroutine(this.syncObjectBounds(),xe.OnBeforeRender)):this.gameObject.add(this._gizmoObject))}onDisable(){this._gizmoObject&&this.gameObject.remove(this._gizmoObject)}*syncObjectBounds(){for(;this._boxHelper;)this._boxHelper?.update(),yield}}o0([u()],sa.prototype,"objectBounds"),o0([u(oe)],sa.prototype,"color"),o0([u()],sa.prototype,"isGizmo");var QA=Object.defineProperty,s0=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&QA(e,t,n),n};class jl extends E{isGizmo=!1;color0;color1;gridHelper;size;divisions;offset;onEnable(){if(this.isGizmo&&!Dc)return;const e=this.size,t=this.divisions;this.gridHelper||(this.gridHelper=new gb(e,t,this.color0??new oe(.4,.4,.4),this.color1??new oe(.6,.6,.6)),this.offset!==void 0&&(this.gridHelper.position.y+=this.offset)),this.gridHelper&&this.gameObject.add(this.gridHelper)}onDisable(){this.gridHelper&&(this.gameObject.remove(this.gridHelper),this.gridHelper=null)}}s0([u()],jl.prototype,"isGizmo"),s0([u(oe)],jl.prototype,"color0"),s0([u(oe)],jl.prototype,"color1");var YA=Object.defineProperty,r0=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&YA(e,t,n),n};class a0 extends E{connectedBody;get rigidBody(){return this._rigidBody}_rigidBody=null;onEnable(){this._rigidBody||(this._rigidBody=this.gameObject.getComponent(Ze)),this.rigidBody&&this.connectedBody&&this.startCoroutine(this.create())}*create(){yield,this.rigidBody&&this.connectedBody&&this.activeAndEnabled&&this.createJoint(this.rigidBody,this.connectedBody)}}r0([u(Ze)],a0.prototype,"connectedBody");class l0 extends a0{createJoint(e,t){this.context.physics.engine?.addFixedJoint(e,t)}}class Sh extends a0{anchor;axis;createJoint(e,t){this.axis&&this.anchor&&this.context.physics.engine?.addHingeJoint(e,t,this.anchor,this.axis)}}r0([u(b)],Sh.prototype,"anchor"),r0([u(b)],Sh.prototype,"axis");var ZA=Object.defineProperty,KA=Object.getOwnPropertyDescriptor,Ui=(o,e,t,i)=>{for(var n=i>1?void 0:i?KA(e,t):e,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&ZA(e,t,n),n};function Bl(o){return o*Math.PI/180}const E1=300,Xs=w("debuglights");class At 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=Bl(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,i=1-Bl(e/2)/Bl(t/2);this.light.penumbra=i}}_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 oe(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),Xs&&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 oe(this.color??16777215),Xs&&console.log(this.name,this)}onEnable(){Xs&&console.log("ENABLE LIGHT",this.name),this.createLight(),!this.isBaked&&(this.light&&(this.light.visible=!0,this.light.intensity=this._intensity,Xs&&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(),xe.LateUpdate))}onDisable(){Xs&&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 Pm(this.color,this.intensity*Math.PI);if(t.position.set(0,0,-E1*.5).applyQuaternion(this.gameObject.quaternion),this.gameObject.add(t.target),Sr(t.target,0,0,0),this.light=t,this.gameObject.position.set(0,0,0),this.gameObject.rotation.set(0,0,0),Xs){const r=new HC(this.light,.2,this.color);this.context.scene.add(r)}break;case 0:const i=new $C(this.color,this.intensity*Math.PI,this.range,Bl(this.spotAngle/2),1-Bl(this.innerSpotAngle/2)/Bl(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 s=new Om(this.color,this.intensity*Math.PI,this.range);this.light=s;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),Xs&&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=E1*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,Xs&&this.context.scene.add(new GC(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)}}Ui([u()],At.prototype,"type",2),Ui([u()],At.prototype,"range",1),Ui([u()],At.prototype,"spotAngle",1),Ui([u()],At.prototype,"innerSpotAngle",1),Ui([u(oe)],At.prototype,"color",1),Ui([u()],At.prototype,"shadowNearPlane",1),Ui([u()],At.prototype,"shadowBias",1),Ui([u()],At.prototype,"shadowNormalBias",1),Ui([u()],At.prototype,"shadows",1),Ui([u()],At.prototype,"lightmapBakeType",2),Ui([u()],At.prototype,"intensity",1),Ui([u()],At.prototype,"shadowDistance",1),Ui([u()],At.prototype,"shadowResolution",1),new b(0,0,0);var JA=Object.defineProperty,kp=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&JA(e,t,n),n};const c0=w("debuglods"),e2=w("nolods");class Fl{screenRelativeTransitionHeight;distance;renderers}kp([u()],Fl.prototype,"screenRelativeTransitionHeight"),kp([u()],Fl.prototype,"distance"),kp([u(ei)],Fl.prototype,"renderers");class t2{model;get renderers(){return this.model.renderers}constructor(e){this.model=e}}class Mp extends E{lodModels=[];_lods=[];_settings=[];_lodsHandler;start(){if(c0&&console.log("LODGROUP",this.name,this.lodModels,this),!e2&&!this._lodsHandler&&this.gameObject&&this.lodModels&&Array.isArray(this.lodModels)){const e=[];for(const i of this.lodModels){const n=new t2(i);this._lods.push(n);for(const s of n.renderers)e.includes(s)||e.push(s)}this._lodsHandler=new Array;for(let i=0;i<e.length;i++){const n=new qC;this._lodsHandler.push(n),this.gameObject.add(n)}const t=new M;t.name="Cull "+this.name;for(let i=0;i<e.length;i++){const n=e[i],s=this._lodsHandler[i],r=n.gameObject;c0&&console.log(i,r.name);for(const a of this._lods){const l=a.model.distance;let c=null;if(a.renderers.includes(n)?c=r:c=t,c.type==="Group"){console.warn(`LODGroup ${this.name}: Group or MultiMaterial object's are not supported as LOD object: ${c.name}`);continue}c0&&console.log("LEVEL",c.name,l),s.autoUpdate=!1,this.onAddLodLevel(s,c,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}}}}kp([u(Fl)],Mp.prototype,"lodModels");var i2=Object.defineProperty,h0=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&i2(e,t,n),n};const Ep=w("debugnestedgltf");class Ul extends E{filePath;loaded=new ae;loadAssetInParent=!0;_isLoadingOrDoneLoading=!1;listenToProgress(e){this.filePath?.beginListenDownload(e)}preload(){return this.filePath?.preload()||null}async start(){if(this._isLoadingOrDoneLoading)return;Ep&&console.log(this,this.guid);const e=this.gameObject.parent;if(e&&this.filePath){this._isLoadingOrDoneLoading=!0;const t=new Nn;t.idProvider=new Bt(this.hash(this.guid)),t.parent=this.loadAssetInParent!==!1?e:this.gameObject,this.gameObject.updateMatrix();const i=this.gameObject.matrix;Ep&&console.log("Load nested:",this.filePath?.url??this.filePath,this.gameObject.position);const n=await this.filePath?.instantiate?.call(this.filePath,t);Ep&&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})),Ep&&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}}h0([u(ne)],Ul.prototype,"filePath"),h0([u(ae)],Ul.prototype,"loaded"),h0([u()],Ul.prototype,"loadAssetInParent");var n2=Object.defineProperty,d0=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&n2(e,t,n),n};const o2=w("debugnet"),Rp=class db extends E{url=null;urlParameterName=null;localhost=null;awake(){o2&&console.log(this),this.context.connection.registerProvider(this)}getWebsocketUrl(){let e=this.url?db.GetUrl(this.url,this.localhost):null;if(this.urlParameterName){const i=w(this.urlParameterName);i&&typeof i=="string"&&(e=i)}if(!e)return null;const t=new RegExp("(((https?)|(?<socket_prefix>wss?))://)?(www.)?(?<url>.+)","gm").exec(e);return t?.groups?t?.groups.socket_prefix?e:"wss://"+t?.groups.url:null}static GetUrl(e,t){let i=e;const n=db.IsLocalNetwork()&&t;if(n&&(i=t),e?.startsWith("/")){const s=n?i:window.location.origin;s?.endsWith("/")&&e.startsWith("/")&&(e=e.substring(1)),i=s+e}return i}static IsLocalNetwork(e=window.location.hostname){return ki(e)}};d0([u()],Rp.prototype,"url"),d0([u()],Rp.prototype,"urlParameterName"),d0([u()],Rp.prototype,"localhost");let u0=Rp;var s2=Object.defineProperty,Tp=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&s2(e,t,n),n};class ra extends E{referenceSpace;from;affectPosition=!1;affectRotation=!1;alignLookDirection=!1;levelLookDirection=!1;levelPosition=!1;positionOffset=new b(0,0,0);rotationOffset=new b(0,0,0);offset=new b(0,0,0);update(){if(!this.from)return;var e=ee(this.from),t=_e(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 _r(this.gameObject.up,0),l=ee(this.referenceSpace);a.setFromNormalAndCoplanarPoint(this.gameObject.up,l);const c=new b(0,0,0);a.projectPoint(e,c),e.copy(c)}this.affectPosition&&yt(this.gameObject,e);const n=new at(this.rotationOffset.x,this.rotationOffset.y,this.rotationOffset.z),s=new N().setFromEuler(n);this.affectRotation&&Sn(this.gameObject,t.multiply(s));const r=new b;this.from.getWorldDirection(r).multiplyScalar(50),this.levelLookDirection&&(r.y=0),this.alignLookDirection&&this.gameObject.lookAt(r)}}Tp([u(S)],ra.prototype,"referenceSpace"),Tp([u(S)],ra.prototype,"from"),Tp([u(b)],ra.prototype,"positionOffset"),Tp([u(b)],ra.prototype,"rotationOffset");var r2=Object.defineProperty,Qs=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&r2(e,t,n),n};class _i{time=0;value=0;inTangent=1/0;inWeight;outTangent=1/0;outWeight;weightedMode;constructor(e=0,t=0){this.time=e,this.value=t}}Qs([u()],_i.prototype,"time"),Qs([u()],_i.prototype,"value"),Qs([u()],_i.prototype,"inTangent"),Qs([u()],_i.prototype,"inWeight"),Qs([u()],_i.prototype,"outTangent"),Qs([u()],_i.prototype,"outWeight"),Qs([u()],_i.prototype,"weightedMode");const R1=class yd{static linearFromTo(e,t,i){const n=new yd,s=new _i;s.time=0,s.value=e;const r=new _i;return r.time=i,r.value=t,n.keys.push(s,r),n}static constant(e){const t=new yd,i=new _i;return i.time=0,i.value=e,t.keys.push(i),t}keys=[];clone(){const e=new yd;return e.keys=this.keys?.map(t=>{const i=new _i;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 n=this.keys[t+1];if(n.time<e)continue;return!isFinite(i.outTangent)||!isFinite(n.inTangent)?i.value:yd.interpolateValue(e,i,n)}else return i.value}return this.keys[this.keys.length-1].value}static interpolateValue(e,t,i){const n=t.time,s=t.value,r=t.outTangent,a=i.time,l=i.value,c=i.inTangent,h=a-n,d=h*h,p=d*h,m=((r+c)*h-2*(l-s))/p,g=(3*(l-s)-(c+2*r)*h)/d,f=r,y=s,_=e-n,v=_*_,P=v*_;return m*P+g*v+f*_+y}};Qs([u(_i)],R1.prototype,"keys");let Ch=R1;var a2=Object.defineProperty,x=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&a2(e,t,n),n};const Ap=w("debugparticles");var Jo=(o=>(o[o.Billboard=0]="Billboard",o[o.Stretch=1]="Stretch",o[o.HorizontalBillboard=2]="HorizontalBillboard",o[o.VerticalBillboard=3]="VerticalBillboard",o[o.Mesh=4]="Mesh",o))(Jo||{});class aa{alphaKeys=[];colorKeys=[];get duration(){return 1}evaluate(e,t){let i,n=0,s=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||!s)&&(s=l,r=a)}if(s)if(r+1<this.colorKeys.length){const a=this.colorKeys[r+1],l=j.remap(e,s.time,a.time,0,1);t.r=j.lerp(s.color.r,a.color.r,l),t.g=j.lerp(s.color.g,a.color.g,l),t.b=j.lerp(s.color.b,a.color.b,l)}else t.r=s.color.r,t.g=s.color.g,t.b=s.color.b;if(i)if(n+1<this.alphaKeys.length){const a=this.alphaKeys[n+1],l=j.remap(e,i.time,a.time,0,1);t.alpha=j.lerp(i.alpha,a.alpha,l)}else t.alpha=i.alpha;return t}}x([u()],aa.prototype,"alphaKeys"),x([u()],aa.prototype,"colorKeys");var Ph=(o=>(o[o.Local=0]="Local",o[o.World=1]="World",o[o.Custom=2]="Custom",o))(Ph||{}),Ip=(o=>(o[o.Sphere=0]="Sphere",o[o.SphereShell=1]="SphereShell",o[o.Hemisphere=2]="Hemisphere",o[o.HemisphereShell=3]="HemisphereShell",o[o.Cone=4]="Cone",o[o.Box=5]="Box",o[o.Mesh=6]="Mesh",o[o.ConeShell=7]="ConeShell",o[o.ConeVolume=8]="ConeVolume",o[o.ConeVolumeShell=9]="ConeVolumeShell",o[o.Circle=10]="Circle",o[o.CircleEdge=11]="CircleEdge",o[o.SingleSidedEdge=12]="SingleSidedEdge",o[o.MeshRenderer=13]="MeshRenderer",o[o.SkinnedMeshRenderer=14]="SkinnedMeshRenderer",o[o.BoxShell=15]="BoxShell",o[o.BoxEdge=16]="BoxEdge",o[o.Donut=17]="Donut",o[o.Rectangle=18]="Rectangle",o[o.Sprite=19]="Sprite",o[o.SpriteRenderer=20]="SpriteRenderer",o))(Ip||{});const es=class bd{static constant(e){const t=new bd;return t.setConstant(e),t}static betweenTwoConstants(e,t){const i=new bd;return i.setMinMaxConstant(e,t),i}static curve(e,t=1){const i=new bd;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 bd;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=j.clamp01(e),this.curve.evaluate(e)*this.curveMultiplier;case 2:case"TwoCurves":const n=e*this.curveMin.duration,s=e*this.curveMax.duration;return j.lerp(this.curveMin.evaluate(n),this.curveMax.evaluate(s),i%1)*this.curveMultiplier;case 3:case"TwoConstants":return j.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}};x([u()],es.prototype,"mode"),x([u()],es.prototype,"constant"),x([u()],es.prototype,"constantMin"),x([u()],es.prototype,"constantMax"),x([u(Ch)],es.prototype,"curve"),x([u(Ch)],es.prototype,"curveMin"),x([u(Ch)],es.prototype,"curveMax"),x([u()],es.prototype,"curveMultiplier");let Y=es;const Ys=class Dt{static constant(e){const t=new Dt;return t.constant(e),t}static betweenTwoColors(e,t){const i=new Dt;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 se(0,0,0,1);static _temp2=new se(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,Dt._temp),Dt._temp;case 2:case"TwoColors":return Dt._temp.lerpColors(this.colorMin,this.colorMax,i);case 3:case"TwoGradients":return this.gradientMin.evaluate(e,Dt._temp),this.gradientMax.evaluate(e,Dt._temp2),Dt._temp.lerp(Dt._temp2,i);case 4:case"RandomColor":const n=Math.random();return this.gradientMin.evaluate(e,Dt._temp),this.gradientMax.evaluate(e,Dt._temp2),Dt._temp.lerp(Dt._temp2,n)}return Dt._temp.set(16777215),Dt._temp.alpha=1,Dt._temp}};x([u()],Ys.prototype,"mode"),x([u(se)],Ys.prototype,"color"),x([u(se)],Ys.prototype,"colorMin"),x([u(se)],Ys.prototype,"colorMax"),x([u(aa)],Ys.prototype,"gradient"),x([u(aa)],Ys.prototype,"gradientMin"),x([u(aa)],Ys.prototype,"gradientMax");let la=Ys;var p0=(o=>(o[o.Hierarchy=0]="Hierarchy",o[o.Local=1]="Local",o[o.Shape=2]="Shape",o))(p0||{});class Gt{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}x([u(Y)],Gt.prototype,"gravityModifier"),x([u(la)],Gt.prototype,"startColor"),x([u(Y)],Gt.prototype,"startDelay"),x([u(Y)],Gt.prototype,"startLifetime"),x([u(Y)],Gt.prototype,"startRotation"),x([u(Y)],Gt.prototype,"startRotationX"),x([u(Y)],Gt.prototype,"startRotationY"),x([u(Y)],Gt.prototype,"startRotationZ"),x([u(Y)],Gt.prototype,"startSize"),x([u(Y)],Gt.prototype,"startSizeX"),x([u(Y)],Gt.prototype,"startSizeY"),x([u(Y)],Gt.prototype,"startSizeZ"),x([u(Y)],Gt.prototype,"startSpeed");class Lp{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=j.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=j.lerp(this.count.curveMin.evaluate(n),this.count.curveMax.evaluate(n),Math.random());break}}return t}}class ts{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}}x([u()],ts.prototype,"enabled"),x([u()],ts.prototype,"bursts"),x([u(Y)],ts.prototype,"rateOverTime"),x([u()],ts.prototype,"rateOverTimeMultiplier"),x([u(Y)],ts.prototype,"rateOverDistance"),x([u()],ts.prototype,"rateOverDistanceMultiplier");class Dp{enabled;color}x([u(la)],Dp.prototype,"color");class ca{enabled;separateAxes;size;sizeMultiplier;x;xMultiplier;y;yMultiplier;z;zMultiplier;_time=0;_temp=new b;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}}x([u(Y)],ca.prototype,"size"),x([u(Y)],ca.prototype,"x"),x([u(Y)],ca.prototype,"y"),x([u(Y)],ca.prototype,"z");const tt=class _d{get type(){return Ip[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 _d}shapeType=5;enabled=!0;alignToDirection=!1;angle=0;arc=360;arcSpread;arcSpeedMultiplier;arcMode;boxThickness;position;rotation;_rotation=new at;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 J;_worldSpaceMatrixInverse=new J;constructor(){Ap&&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=j.toRadians(this.rotation.x),this._rotation.y=j.toRadians(this.rotation.y),this._rotation.z=j.toRadians(this.rotation.z),this._rotation.order="ZYX",e.applyEuler(this._rotation)),t}_vector=new b(0,0,0);_temp=new b(0,0,0);_triangle=new XC;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:Ap&&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 s=this.meshRenderer;s?.destroyed==!1&&this.setMesh(s);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"),c=Math.floor(Math.random()*l.count);this._vector.fromBufferAttribute(l,c),this._vector.applyMatrix4(r.matrixWorld),e.mesh_normal=c}break;case 1:break;case 2:{const l=a.index;if(l){let c=Math.random(),h=Math.random();c+h>1&&(c=1-c,h=1-h);const d=Math.floor(Math.random()*(l.count/3));let p=d*3,m=d*3+1,g=d*3+2;p=l.getX(p),m=l.getX(m),g=l.getX(g);const f=a.getAttribute("position");this._triangle.a.fromBufferAttribute(f,p),this._triangle.b.fromBufferAttribute(f,m),this._triangle.c.fromBufferAttribute(f,g),this._vector.set(0,0,0).addScaledVector(this._triangle.a,c).addScaledVector(this._triangle.b,h).addScaledVector(this._triangle.c,1-(c+h)),this._vector.applyMatrix4(r.matrixWorld),e.mesh_normal=d}}break}break;default:this._vector.set(0,0,0),A()&&!globalThis.__particlesystem_shapetype_unsupported&&(console.warn("ParticleSystem ShapeType is not supported:",Ip[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)),Ap&&B.DrawSphere(this._vector,.03,16711680,.5,!0)}_dir=new b;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,s=t.z;this._dir.set(i,n,s),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"),c=e.mesh_normal;this._dir.fromBufferAttribute(l,c)}break;case 1:break;case 2:{const l=a.index;if(l){const c=e.mesh_normal,h=l.getX(c*3),d=l.getX(c*3+1),p=l.getX(c*3+2),m=a.getAttribute("position"),g=F(),f=F(),y=F();g.fromBufferAttribute(m,h),f.fromBufferAttribute(m,d),y.fromBufferAttribute(m,p),g.sub(f),y.sub(f),g.cross(y),this._dir.copy(g).multiplyScalar(-1);const _=_e(r);this._dir.applyQuaternion(_)}}break}break;default:this._dir.set(0,0,1);break}return this._space===1&&this._dir.applyQuaternion(this.system.worldQuaternion),this.applyRotation(this._dir),this._dir.normalize(),this.spherizeDirection(this._dir,this.sphericalDirectionAmount),this.randomizeDirection(this._dir,this.randomDirectionAmount),Ap&&(B.DrawSphere(t,.01,8925952,.5,!0),B.DrawDirection(t,this._dir,8925952,.5,!0)),this._dir}static _randomQuat=new N;static _tempVec=new b;randomizePosition(e,t){if(t<=0)return;const i=_d._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=_d._randomQuat,n=_d._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),s=Math.sin(n)*Math.cos(i),r=Math.sin(n)*Math.sin(i),a=Math.cos(n),l=new b(s,r,a);e.lerp(l,t)}randomSpherePoint(e,t,i,n,s){const r=Math.random(),a=Math.random(),l=2*Math.PI*r*(n/360),c=Math.acos(2*a-1),h=j.lerp(1,1-Math.pow(1-Math.random(),Math.PI),i)*t,d=e.x+this.scale.x*(-h*Math.sin(c)*Math.cos(l)),p=e.y+this.scale.y*(h*Math.sin(c)*Math.sin(l)),m=e.z+this.scale.z*(h*Math.cos(c));s.x=d,s.y=p,s.z=m}randomCirclePoint(e,t,i,n,s){const r=Math.random(),a=2*Math.PI*r*(n/360),l=j.lerp(1,1-Math.pow(1-Math.random(),Math.PI),i)*t,c=e.x+this.scale.x*l*Math.cos(a),h=e.y+this.scale.y*l*Math.sin(a),d=e.z;s.x=c,s.y=h,s.z=d}_loopTime=0;_loopDirection=1;randomConePoint(e,t,i,n,s,r,a){let l=0,c=0;switch(r){case 0:l=Math.random(),c=Math.random();break;case 2:this._loopTime>1&&(this._loopDirection=-1),this._loopTime<0&&(this._loopDirection=1);case 1:l=.5,c=Math.random(),this._loopTime+=this.system.deltaTime*this._loopDirection;break}let h=2*Math.PI*l*(s/360);switch(r){case 2:case 1:h+=Math.PI+.5,h+=this._loopTime*Math.PI*2,h%=j.toRadians(s);break}const d=Math.acos(2*c-1),p=j.lerp(1,1-Math.pow(1-Math.random(),Math.PI),n)*i,m=e.x+-p*Math.sin(d)*Math.cos(h),g=e.y+p*Math.sin(d)*Math.sin(h),f=e.z;a.x=m*this.scale.x,a.y=g*this.scale.y,a.z=f*this.scale.z}};x([u()],tt.prototype,"shapeType"),x([u()],tt.prototype,"enabled"),x([u()],tt.prototype,"alignToDirection"),x([u()],tt.prototype,"angle"),x([u()],tt.prototype,"arc"),x([u()],tt.prototype,"arcSpread"),x([u()],tt.prototype,"arcSpeedMultiplier"),x([u()],tt.prototype,"arcMode"),x([u(b)],tt.prototype,"boxThickness"),x([u(b)],tt.prototype,"position"),x([u(b)],tt.prototype,"rotation"),x([u(b)],tt.prototype,"scale"),x([u()],tt.prototype,"radius"),x([u()],tt.prototype,"radiusThickness"),x([u()],tt.prototype,"sphericalDirectionAmount"),x([u()],tt.prototype,"randomDirectionAmount"),x([u()],tt.prototype,"randomPositionAmount"),x([u()],tt.prototype,"meshShapeType"),x([u(ah)],tt.prototype,"meshRenderer");let m0=tt;class ve{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 b;apply(e,t,i,n,s,r){if(!this.enabled)return;this._noise||(this._noise=AP(()=>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),c=this._noise(a.x,a.y,a.z,this._time+1e3*this.frequency),h=this._noise(a.x,a.y,a.z,this._time+2e3*this.frequency);this._temp.set(l,c,h).normalize();const d=s/r;let p=this.positionAmount.evaluate(d);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(d)*1.5),this._temp.multiplyScalar(p)),i.x+=this._temp.x,i.y+=this._temp.y,i.z+=this._temp.z}}x([u()],ve.prototype,"damping"),x([u()],ve.prototype,"enabled"),x([u()],ve.prototype,"frequency"),x([u()],ve.prototype,"octaveCount"),x([u()],ve.prototype,"octaveMultiplier"),x([u()],ve.prototype,"octaveScale"),x([u(Y)],ve.prototype,"positionAmount"),x([u()],ve.prototype,"quality"),x([u(Y)],ve.prototype,"remap"),x([u()],ve.prototype,"remapEnabled"),x([u()],ve.prototype,"remapMultiplier"),x([u(Y)],ve.prototype,"remapX"),x([u()],ve.prototype,"remapXMultiplier"),x([u(Y)],ve.prototype,"remapY"),x([u()],ve.prototype,"remapYMultiplier"),x([u(Y)],ve.prototype,"remapZ"),x([u()],ve.prototype,"remapZMultiplier"),x([u()],ve.prototype,"scrollSpeedMultiplier"),x([u()],ve.prototype,"separateAxes"),x([u()],ve.prototype,"strengthMultiplier"),x([u(Y)],ve.prototype,"strengthX"),x([u()],ve.prototype,"strengthXMultiplier"),x([u(Y)],ve.prototype,"strengthY"),x([u()],ve.prototype,"strengthYMultiplier"),x([u(Y)],ve.prototype,"strengthZ"),x([u()],ve.prototype,"strengthZMultiplier");class Fe{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 s=this.widthOverTrail.evaluate(i,n);return e*=s,e}getColor(e,t,i){const n=this.colorOverTrail.evaluate(i),s=this.colorOverLifetime.evaluate(t);e.x*=n.r*s.r,e.y*=n.g*s.g,e.z*=n.b*s.b,"alpha"in n&&"alpha"in s&&(e.w*=n.alpha*s.alpha)}}x([u()],Fe.prototype,"enabled"),x([u()],Fe.prototype,"attachRibbonToTransform"),x([u(la)],Fe.prototype,"colorOverLifetime"),x([u(la)],Fe.prototype,"colorOverTrail"),x([u()],Fe.prototype,"dieWithParticles"),x([u()],Fe.prototype,"inheritParticleColor"),x([u(Y)],Fe.prototype,"lifetime"),x([u()],Fe.prototype,"lifetimeMultiplier"),x([u()],Fe.prototype,"minVertexDistance"),x([u()],Fe.prototype,"mode"),x([u()],Fe.prototype,"ratio"),x([u()],Fe.prototype,"ribbonCount"),x([u()],Fe.prototype,"shadowBias"),x([u()],Fe.prototype,"sizeAffectsLifetime"),x([u()],Fe.prototype,"sizeAffectsWidth"),x([u()],Fe.prototype,"splitSubEmitterRibbons"),x([u()],Fe.prototype,"textureMode"),x([u(Y)],Fe.prototype,"widthOverTrail"),x([u()],Fe.prototype,"widthOverTrailMultiplier"),x([u()],Fe.prototype,"worldSpace");class He{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 b;_temp2=new b;_temp3=new b;_hasOrbital=!1;_index=0;_orbitalMatrix=new J;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,s,r,a){if(!this.enabled)return;const l=r/a,c=this.speedModifier.evaluate(l)*this.speedModifierMultiplier,h=this.x.evaluate(l),d=this.y.evaluate(l),p=this.z.evaluate(l);if(this._temp.set(-h,d,p),this._system&&this._system.main.simulationSpace===1&&this._temp.applyQuaternion(this._system.worldQuaternion),this._hasOrbital&&this._system?.worldPos){const m=this._temp2.set(i.x,i.y,i.z),g=this.orbitalXMultiplier,f=this.orbitalYMultiplier,y=this.orbitalZMultiplier,_=c*Math.PI*2*10,v=Math.cos(_*g),P=Math.sin(_*g),k=Math.cos(_*f),O=Math.sin(_*f),D=Math.cos(_*y),L=Math.sin(_*y),V=m.x*(k*D)+m.y*(k*L)+m.z*-O,W=m.x*(P*O*D-v*L)+m.y*(P*O*L+v*D)+m.z*(P*k),G=m.x*(v*O*D+P*L)+m.y*(v*O*L-P*D)+m.z*(v*k),X=this._temp3.set(m.x-V,m.y-W,m.z-G);X.normalize(),X.multiplyScalar(.2/s*Math.max(this.orbitalXMultiplier,this.orbitalYMultiplier,this.orbitalZMultiplier)),n.x+=X.x,n.y+=X.y,n.z+=X.z}n.x+=this._temp.x,n.y+=this._temp.y,n.z+=this._temp.z,n.x*=c,n.y*=c,n.z*=c}}x([u()],He.prototype,"enabled"),x([u()],He.prototype,"space"),x([u(Y)],He.prototype,"orbitalX"),x([u(Y)],He.prototype,"orbitalY"),x([u(Y)],He.prototype,"orbitalZ"),x([u()],He.prototype,"orbitalXMultiplier"),x([u()],He.prototype,"orbitalYMultiplier"),x([u()],He.prototype,"orbitalZMultiplier"),x([u()],He.prototype,"orbitalOffsetX"),x([u()],He.prototype,"orbitalOffsetY"),x([u()],He.prototype,"orbitalOffsetZ"),x([u(Y)],He.prototype,"speedModifier"),x([u()],He.prototype,"speedModifierMultiplier"),x([u(Y)],He.prototype,"x"),x([u()],He.prototype,"xMultiplier"),x([u(Y)],He.prototype,"y"),x([u()],He.prototype,"yMultiplier"),x([u(Y)],He.prototype,"z"),x([u()],He.prototype,"zMultiplier");class qt{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}}x([u()],qt.prototype,"animation"),x([u()],qt.prototype,"enabled"),x([u()],qt.prototype,"cycleCount"),x([u(Y)],qt.prototype,"frameOverTime"),x([u()],qt.prototype,"frameOverTimeMultiplier"),x([u()],qt.prototype,"numTilesX"),x([u()],qt.prototype,"numTilesY"),x([u(Y)],qt.prototype,"startFrame"),x([u()],qt.prototype,"startFrameMultiplier"),x([u()],qt.prototype,"rowMode"),x([u()],qt.prototype,"rowIndex"),x([u()],qt.prototype,"spriteCount"),x([u()],qt.prototype,"timeMode");class Dn{enabled;separateAxes;x;xMultiplier;y;yMultiplier;z;zMultiplier;evaluate(e,t){return this.enabled?this.separateAxes?0:this.z.evaluate(e,t)*-1:0}}x([u()],Dn.prototype,"enabled"),x([u()],Dn.prototype,"separateAxes"),x([u(Y)],Dn.prototype,"x"),x([u()],Dn.prototype,"xMultiplier"),x([u(Y)],Dn.prototype,"y"),x([u()],Dn.prototype,"yMultiplier"),x([u(Y)],Dn.prototype,"z"),x([u()],Dn.prototype,"zMultiplier");class an{enabled;range;separateAxes;x;xMultiplier;y;yMultiplier;z;zMultiplier;evaluate(e,t){if(!this.enabled)return 0;if(!this.separateAxes){const i=j.lerp(this.range.x,this.range.y,t);return this.z.evaluate(i)*-1}return 0}}x([u()],an.prototype,"enabled"),x([u()],an.prototype,"range"),x([u()],an.prototype,"separateAxes"),x([u(Y)],an.prototype,"x"),x([u()],an.prototype,"xMultiplier"),x([u(Y)],an.prototype,"y"),x([u()],an.prototype,"yMultiplier"),x([u(Y)],an.prototype,"z"),x([u()],an.prototype,"zMultiplier");class dt{enabled;dampen;drag;dragMultiplier;limit;limitMultiplier;separateAxes;limitX;limitXMultiplier;limitY;limitYMultiplier;limitZ;limitZMultiplier;multiplyDragByParticleSize=!1;multiplyDragByParticleVelocity=!1;space;_temp=new b;_temp2=new b;apply(e,t,i,n,s,r,a){if(this.enabled){const l=this.limit.evaluate(s)*this.limitMultiplier;if(t.length()>l){this._temp.copy(t).normalize().multiplyScalar(l);const c=this.dampen*.5;t.x=j.lerp(t.x,this._temp.x,c),t.y=j.lerp(t.y,this._temp.y,c),t.z=j.lerp(t.z,this._temp.z,c),i.x=j.lerp(i.x,this._temp.x,c),i.y=j.lerp(i.y,this._temp.y,c),i.z=j.lerp(i.z,this._temp.z,c)}}}}x([u()],dt.prototype,"enabled"),x([u()],dt.prototype,"dampen"),x([u(Y)],dt.prototype,"drag"),x([u()],dt.prototype,"dragMultiplier"),x([u(Y)],dt.prototype,"limit"),x([u()],dt.prototype,"limitMultiplier"),x([u()],dt.prototype,"separateAxes"),x([u(Y)],dt.prototype,"limitX"),x([u()],dt.prototype,"limitXMultiplier"),x([u(Y)],dt.prototype,"limitY"),x([u()],dt.prototype,"limitYMultiplier"),x([u(Y)],dt.prototype,"limitZ"),x([u()],dt.prototype,"limitZMultiplier"),x([u()],dt.prototype,"multiplyDragByParticleSize"),x([u()],dt.prototype,"multiplyDragByParticleVelocity"),x([u()],dt.prototype,"space");const Oh=class NS{enabled;curve;curveMultiplier;mode;clone(){const e=new NS;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 b),this.system._iv_lastWorldPosition}get _velocity(){return this.system._iv_velocity||(this.system._iv_velocity=new b),this.system._iv_velocity}_temp=new b;_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}}};x([u()],Oh.prototype,"enabled"),x([u(Y)],Oh.prototype,"curve"),x([u()],Oh.prototype,"curveMultiplier"),x([u()],Oh.prototype,"mode");let g0=Oh;class vi{enabled;range;separateAxes;size;sizeMultiplier;x;xMultiplier;y;yMultiplier;z;zMultiplier;evaluate(e,t,i,n){const s=e.length(),r=j.remap(s,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}}x([u()],vi.prototype,"enabled"),x([u(K)],vi.prototype,"range"),x([u()],vi.prototype,"separateAxes"),x([u(Y)],vi.prototype,"size"),x([u()],vi.prototype,"sizeMultiplier"),x([u(Y)],vi.prototype,"x"),x([u()],vi.prototype,"xMultiplier"),x([u(Y)],vi.prototype,"y"),x([u()],vi.prototype,"yMultiplier"),x([u(Y)],vi.prototype,"z"),x([u()],vi.prototype,"zMultiplier");class zl{enabled;range;color;evaluate(e,t,i){const n=e.length(),s=j.remap(n,this.range.x,this.range.y,0,1),r=this.color.evaluate(s,t);i.x*=r.r,i.y*=r.g,i.z*=r.b,"alpha"in r&&(i.w*=r.alpha)}}x([u()],zl.prototype,"enabled"),x([u(K)],zl.prototype,"range"),x([u(la)],zl.prototype,"color"),new b(1,1,1),new b(0,0,1);class f0{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 s=1e3;this._circularBuffer=new Mi(()=>new Nm,s)}type="NeedleParticleSubEmitter";emitterType;emitterProbability;q_=new N;v_=new b;v2_=new b;_emitterMatrix=new Nm;_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===y0.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===y0.Death){let n=e.life;if(e[Nl]!==void 0&&(n=e[Nl]),!(e.age+t*1.2>=n))return;const s=this.subSystem.main.maxParticles-this.subSystem.currentParticles;e.emissionState.waitEmiting=s}const i=new Nm;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 l2=Object.defineProperty,Ue=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&l2(e,t,n),n};const Zs=w("debugparticles"),c2=w("noprogressive"),h2=w("debugprogressive");var y0=(o=>(o[o.Birth=0]="Birth",o[o.Collision=1]="Collision",o[o.Death=2]="Death",o[o.Trigger=3]="Trigger",o[o.Manual=4]="Manual",o))(y0||{});class ln 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"){Zs&&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=Po,t.map.premultiplyAlpha=!1);const i=new Ce;i.copy(t),e?this.trailMaterial=i:this.particleMaterial=i}t.map&&(t.map.colorSpace=Po,t.map.premultiplyAlpha=!1),e&&t.side===vs&&(t=t.clone(),t.side=Id,e?this.trailMaterial=t:this.particleMaterial=t)}return t&&!c2&&t._didRequestTextureLOD===void 0&&(t._didRequestTextureLOD=0,h2&&console.log("Load material LOD",t.name),Ve.assignTextureLOD(t,0)),t}getMesh(e){let t=null;if(!t&&(this.particleMesh instanceof H&&(t=this.particleMesh.geometry),t===null)){t=new vn(1,1);const i=t.attributes.uv;for(let n=0;n<i.count;n++)i.setX(n,1-i.getX(n))}return new H(t,this.getMaterial())}}Ue([u()],ln.prototype,"renderMode"),Ue([u(we)],ln.prototype,"particleMaterial"),Ue([u(we)],ln.prototype,"trailMaterial"),Ue([u()],ln.prototype,"maxParticleSize"),Ue([u()],ln.prototype,"minParticleSize"),Ue([u()],ln.prototype,"velocityScale"),Ue([u()],ln.prototype,"cameraVelocityScale"),Ue([u()],ln.prototype,"lengthScale");class jp{_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 b0{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 d2 extends b0{genValue(){return this.system.textureSheetAnimation.getStartIndex()}}class u2 extends b0{_lastPosition=new b;_lastDistance=0;update(){const e=ee(this.system.gameObject);this._lastDistance=this._lastPosition.distanceTo(e),this._lastPosition.copy(e)}genValue(){if(!this.system.isPlaying||!this.system.emission.enabled||this.system.currentParticles>=this.system.maxParticles)return 0;let e=this.system.emission.rateOverTime.evaluate(this.system.time/this.system.duration,Math.random());if(this.system.deltaTime>0){const n=this.system.emission.rateOverDistance.evaluate(this.system.time/this.system.duration,Math.random());let s=this._lastDistance/this.system.deltaTime*n;Number.isFinite(s)||(s=0),e+=s}const t=this.system.emission.getBurst();t>0&&(e+=t/this.system.deltaTime);const i=this.system.maxParticles-this.system.currentParticles;return j.clamp(e,0,i/this.system.deltaTime)}}class p2 extends b0{genValue(){return this.system.isPlaying,0}}class Ks{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 m2 extends Ks{type="NeedleTextureSheet";update(e,t){const i=this.system.textureSheetAnimation;if(i.enabled){const n=e.age/e.life,s=i.evaluate(n);s!==void 0&&(e.uvTile=s)}}}const T1=Symbol("particleRotation");class g2 extends Ks{type="NeedleRotation";initialize(e){e[T1]=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[T1])*t:this.system.renderer.renderMode===Jo.Billboard&&(e.rotation=Math.PI),this.system.rotationBySpeed.enabled)){const n=e.velocity.length();e.rotation+=this.system.rotationBySpeed.evaluate(i,n)*t}}}const A1=Symbol("sizeLerpFactor"),f2=new b;class y2 extends Ks{type="NeedleSize";_minSize=0;_maxSize=1;initialize(e){e[A1]=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[A1]).x);let s=1;this.system.renderer.renderMode!==Jo.Mesh&&(s=this.system.worldScale.x/this.system.cameraScale);const r=F(e.startSize).multiplyScalar(n*s);if(e.size.set(r.x,r.y,r.z),this.system.localspace){const a=B1(this.system,f2);e.size.x*=a.x,e.size.y*=a.y,e.size.z*=a.z}}}const Nl=Symbol("particleLife"),_0=Symbol("trailLifetime"),I1=Symbol("trailStartLength"),v0=Symbol("trailWidthRandom");class b2 extends Ks{type="NeedleTrail";initialize(e){e instanceof Vb&&(e[Nl]=e.life,this.system.trails.enabled&&this.system.trails.dieWithParticles===!1&&(e[_0]=this.system.trails.lifetime.evaluate(Math.random(),Math.random()),e.life+=e[_0]),e[I1]=e.length,e[v0]=Math.random())}update(e){if(this.system.trails?.enabled&&e instanceof Vb){const t=e,i=e.age/e[Nl],n=e.previous.values(),s=e.previous.length;for(let r=0;r<s;r++){const a=n.next().value,l=1-r/(s-1),c=e.size;if(c.x<=0&&!this.system.trails.sizeAffectsWidth){const h=20*this.system.trails.widthOverTrail.evaluate(.5,t[v0]);c.x=h,c.y=h,c.z=h}a.size=this.system.trails.getWidth(c.x,i,l,t[v0]),a.color.copy(e.color),this.system.trails.getColor(a.color,i,l)}if(e.age>e[Nl]){e.velocity.set(0,0,0);const r=(e.age-e[Nl])/e[_0];t.length=j.lerp(e[I1],0,r)}}}}const Bp=Symbol("startVelocity"),L1=Symbol("gravityModifier"),w0=Symbol("gravitySpeed"),Fp=Symbol("velocity lerp factor"),x0=new b;class _2 extends Ks{type="NeedleVelocity";_gravityDirection=new b;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[Bp]?e[Bp].copy(e.velocity):e[Bp]=e.velocity.clone();const n=this.system.main.gravityModifier.evaluate(Math.random(),Math.random());e[L1]=n*t,e[w0]=n*t*.5,e[Fp]=Math.random(),this.system.velocityOverLifetime?.init(e),this._gravityDirection.set(0,-1,0),this.system.main.simulationSpace===Ph.Local&&this._gravityDirection.applyQuaternion(this.system.worldQuaternionInverted).normalize()}update(e,t){const i=e[Bp],n=e[L1];if(n!==0){const d=n*e[w0];x0.copy(this._gravityDirection).multiplyScalar(d),e[w0]+=t*.05,i.add(x0)}e.velocity.copy(i);const s=e.age/e.life;this.system.inheritVelocity?.enabled&&this.system.inheritVelocity.applyCurrent(e.velocity,s,e[Fp]);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,s,e[Fp],e.size));const l=this.system.colorBySpeed;l?.enabled&&l.evaluate(e.velocity,e[Fp],e.color);const c=this.system.velocityOverLifetime;c.enabled&&c.apply(e,0,e.position,e.velocity,t,e.age,e.life);const h=this.system.limitVelocityOverLifetime;if(h.enabled&&h.apply(e.position,i,e.velocity,e.size,s,t,1),this.system.worldspace){const d=this.system.worldScale;e.velocity.x*=d.x,e.velocity.y*=d.y,e.velocity.z*=d.z}}}const D1=Symbol("colorLerpFactor"),j1=new se(1,1,1,1),ha=new se(1,1,1,1);class v2 extends Ks{type="NeedleColor";initialize(e){}_init(e){const t=this.system.renderer.particleMaterial;ha.copy(this.system.main.startColor.evaluate(Math.random())),t?.color&&(j1.copy(t.color),ha.multiply(j1)),ha.convertLinearToSRGB(),e.startColor.set(ha.r,ha.g,ha.b,ha.alpha),e.color.copy(e.startColor),e[D1]=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[D1]);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 w2{system;emission;get anim(){return this.system.textureSheetAnimation}constructor(e){this.system=e,this.emission=new u2(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 jp(this.system.main.startLifetime)}get startSpeed(){return new jp(this.system.main.startSpeed)}get startRotation(){return new jp(this.system.main.startRotation)}get startSize(){return new jp(this.system.main.startSize)}startLength;get startColor(){return new DP(new jP(1,1,1,1))}get emissionOverTime(){return this.emission}get emissionOverDistance(){return new p2(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 Eo.Trail;switch(this.system.renderer.renderMode){case Jo.Billboard:return Eo.BillBoard;case Jo.Stretch:return Eo.StretchedBillBoard;case Jo.HorizontalBillboard:return Eo.HorizontalBillBoard;case Jo.VerticalBillboard:return Eo.VerticalBillBoard;case Jo.Mesh:return Eo.Mesh}return Eo.BillBoard}rendererEmitterSettings={startLength:new BP(220),followLocalOrigin:!1};get speedFactor(){let e=this.system.main.simulationSpeed;return this.system.renderer?.renderMode===Jo.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=Po,this.clonedTexture.original=t,this.clonedTexture.clone=i}return this.clonedTexture.clone}return this.flatWhiteTexture||(this.flatWhiteTexture=gf(new se(1,1,1,1),1)),this.flatWhiteTexture}get startTileIndex(){return new d2(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??QC}get transparent(){return this.system.renderer.transparent}get worldSpace(){return this.system.main.simulationSpace===Ph.World}}class x2{burstParticleIndex=0;burstParticleCount=0;isBursting=!1;travelDistance=0;previousWorldPos;burstIndex=0;burstWaveIndex=0;time=0;waitEmiting=0}const Xt=class bm extends E{play(e=!1){e&&S.foreachComponent(this.gameObject,t=>{t instanceof bm&&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 bm&&t!==this&&t.pause(!1)},!0),this._isPlaying=!1}stop(e=!0,t=!1){e&&S.foreachComponent(this.gameObject,i=>{i instanceof bm&&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 x2),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===Ph.World}get localspace(){return this.main.simulationSpace===Ph.Local}__worldQuaternion=new N;get worldQuaternion(){return this.__worldQuaternion}_worldQuaternionInverted=new N;get worldQuaternionInverted(){return this._worldQuaternionInverted}_worldScale=new b;get worldScale(){return this._worldScale}_worldPositionFrame=-1;_worldPos=new b;get worldPos(){return this._worldPositionFrame!==this.context.time.frame&&(this._worldPositionFrame=this.context.time.frame,ee(this.gameObject,this._worldPos)),this._worldPos}get matrixWorld(){return this._container.matrixWorld}get isSubsystem(){return this._isUsedAsSubsystem}addBehaviour(e){return this._particleSystem?(e instanceof Ks&&(e.system=this),Zs&&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()||Zs)&&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 Lp)){const n=new Lp;Ja(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 Up)){const n=new Up;Ja(n,i),e[t]=n}}Zs&&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(ln),!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 M,this._container.matrixAutoUpdate=!1,this.context.scene.add(this._container),this._batchSystem=new IP,this._batchSystem.name=this.gameObject.name,this._container.add(this._batchSystem),this._interface=new w2(this),this._particleSystem=new LP(this._interface),this._particleSystem.addBehavior(new y2(this)),this._particleSystem.addBehavior(new v2(this)),this._particleSystem.addBehavior(new m2(this)),this._particleSystem.addBehavior(new g2(this)),this._particleSystem.addBehavior(new _2(this)),this._particleSystem.addBehavior(new b2(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),Zs&&(console.log(this),this.gameObject.add(new Ci(1)))}start(){this.addSubParticleSystems(),this.updateLayers(),this.renderer.particleMesh instanceof H&&this._interface.renderMode==Eo.Mesh&&Ve.assignMeshLOD(this.renderer.particleMesh,0).then(e=>{e&&this.particleSystem&&this._interface.renderMode==Eo.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 e=1/60,t=this.main.duration,i=this.main.startLifetime.getMax(),n=Math.min(Math.max(t,i)/Math.max(.01,this.main.simulationSpeed),1e3),s=Math.ceil(n/e),r=Date.now();Zs&&console.log(`Particles ${this.name} - Prewarm for ${s} frames (${n} sec). Duration: ${t}, Lifetime: ${i}`);for(let a=0;a<s&&!(this.currentParticles>=this.maxParticles);a++){const l=Date.now()-r;if(l>2e3){console.warn(`Particles ${this.name} - Prewarm took too long. Aborting: ${l}`);break}this.onUpdate(),this.onSimulate(e)}}_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=$e(e);this._cameraScale=n.x}const t=!this.worldspace,i=this.gameObject;if(_e(i,this.__worldQuaternion),this._worldQuaternionInverted.copy(this.__worldQuaternion).invert(),$e(this.gameObject,this._worldScale),t&&this._container&&this.gameObject?.parent){const n=B1(this,x0);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 f0(this,this._particleSystem,e.particleSystem,t);i.emitterType=e.type,i.emitterProbability=e.emitProbability,this._particleSystem.addBehavior(i)}else Zs&&console.warn("Could not add SubParticleSystem",e,this)}}};Ue([u(Dp)],Xt.prototype,"colorOverLifetime"),Ue([u(Gt)],Xt.prototype,"main"),Ue([u(ts)],Xt.prototype,"emission"),Ue([u(ca)],Xt.prototype,"sizeOverLifetime"),Ue([u(m0)],Xt.prototype,"shape"),Ue([u(ve)],Xt.prototype,"noise"),Ue([u(Fe)],Xt.prototype,"trails"),Ue([u(He)],Xt.prototype,"velocityOverLifetime"),Ue([u(dt)],Xt.prototype,"limitVelocityOverLifetime"),Ue([u(g0)],Xt.prototype,"inheritVelocity"),Ue([u(zl)],Xt.prototype,"colorBySpeed"),Ue([u(qt)],Xt.prototype,"textureSheetAnimation"),Ue([u(Dn)],Xt.prototype,"rotationOverLifetime"),Ue([u(an)],Xt.prototype,"rotationBySpeed"),Ue([u(vi)],Xt.prototype,"sizeBySpeed");let kh=Xt;class Up{particleSystem;emitProbability=1;properties;type;_deserialize(e,t){const i=this.particleSystem;if(i instanceof kh)return;let n="";i&&typeof i.guid=="string"&&(n=i.guid,this.particleSystem=S.findByGuid(n,t)),Zs&&!(this.particleSystem instanceof kh)&&console.warn("Could not find particle system for sub emitter",n,t,this)}}function B1(o,e){if(e.set(1,1,1),o.gameObject.parent&&o.localspace)switch(o.main.scalingMode){case p0.Local:e=$e(o.gameObject.parent,e),e.x=1/e.x,e.y=1/e.y,e.z=1/e.z;break;default:if(!o.unsupported_scaling_mode){o.unsupported_scaling_mode=!0;const t="ParticleSystem scale mode "+p0[o.main.scalingMode]+" is not supported";A()&&be(t),console.warn(t,o.name,o)}e=$e(o.gameObject,e);break}return e}var S2=Object.defineProperty,S0=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&S2(e,t,n),n};class Wl 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),s=n.length();if(s>this.radius)return;let r=t;s>1?r/=s*s:r/=Math.max(.05,s),i.applyImpulse(n.multiplyScalar(r))})}}S0([u()],Wl.prototype,"strength"),S0([u()],Wl.prototype,"radius"),S0([u(Ze)],Wl.prototype,"targets");class rc extends E{_didAssignPlayerColor=!1;onEnable(){this.context.connection.beginListen(ie.JoinedRoom,this.tryAssignColor),this._didAssignPlayerColor||this.startCoroutine(this.waitForConnection())}onDisable(){this.context.connection.stopListen(ie.JoinedRoom,this.tryAssignColor)}*waitForConnection(){for(;!this.destroyed&&this.activeAndEnabled&&(yield pf(.2),!this.tryAssignColor()););}tryAssignColor=()=>{const e=S.getComponentInParent(this.gameObject,sn);if(e&&e.owner)return this._didAssignPlayerColor=!0,this.assignUserColor(e.owner),!0;const t=S.getComponentInParent(this.gameObject,Le);return t?.connectionId?(this._didAssignPlayerColor=!0,this.assignUserColor(t.connectionId),!0):!1};assignUserColor(e){const t=rc.hashCode(e),i=rc.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 s=n;s.material&&s.material.color&&this.assignColor(i,e,s)}}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 oe(t/255,i/255,n/255)}}const Mh=w("debugpost");let C0=null;function C2(o){C0=o}function F1(o){let e=o.gameObject;for(;e;){for(const t of vu(e))if(t.isPostProcessingManager===!0)return t;e=e.parent}return null}function P2(o){let e=F1(o);if(!e)if(C0){Mh&&console.warn("Adding postprocessing manager to the scene.");const t=o.scene;e=Mn(t,C0)}else A()&&console.warn("No post processing manager found");return e}const ut={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 it=null;function O2(o){Mh==="verbose"&&console.debug("Before ordering effects",[...o]),it||(it=new Map,it.set(T.POSTPROCESSING.MODULE.NormalPass,ut.NormalPass),it.set(T.POSTPROCESSING.MODULE.DepthDownsamplingPass,ut.DepthDownsamplingPass),it.set(T.POSTPROCESSING.MODULE.SMAAEffect,ut.SMAA),it.set(T.POSTPROCESSING.MODULE.SSAOEffect,ut.SSAO),it.set(T.POSTPROCESSING_AO.MODULE.N8AOPostPass,ut.SSAO),it.set(T.POSTPROCESSING_AO.MODULE.N8AOPass,ut.SSAO),it.set(T.POSTPROCESSING.MODULE.TiltShiftEffect,ut.TiltShift),it.set(T.POSTPROCESSING.MODULE.DepthOfFieldEffect,ut.DepthOfField),it.set(T.POSTPROCESSING.MODULE.ChromaticAberrationEffect,ut.ChromaticAberration),it.set(T.POSTPROCESSING.MODULE.BloomEffect,ut.Bloom),it.set(T.POSTPROCESSING.MODULE.SelectiveBloomEffect,ut.Bloom),it.set(T.POSTPROCESSING.MODULE.VignetteEffect,ut.Vignette),it.set(T.POSTPROCESSING.MODULE.PixelationEffect,ut.Pixelation),it.set(T.POSTPROCESSING.MODULE.ToneMappingEffect,ut.ToneMapping),it.set(T.POSTPROCESSING.MODULE.HueSaturationEffect,ut.HueSaturation),it.set(T.POSTPROCESSING.MODULE.BrightnessContrastEffect,ut.BrightnessContrast)),o.sort((e,t)=>{const i=typeof e.priority=="number"?e.priority:it.get(e.effect.constructor)??Number.NEGATIVE_INFINITY,n=typeof t.priority=="number"?t.priority:it.get(t.effect.constructor)??Number.NEGATIVE_INFINITY;return i===Number.NEGATIVE_INFINITY?(Mh&&console.warn("Unknown effect found: ",e.constructor.name,e),1):n===Number.NEGATIVE_INFINITY?(Mh&&console.warn("Unknown effect found: ",t.constructor.name,t),-1):i-n}),Mh==="verbose"&&console.debug("After ordering effects",[...o])}var k2=Object.defineProperty,M2=Object.getOwnPropertyDescriptor,U1=(o,e,t,i)=>{for(var n=M2(e,t),s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&k2(e,t,n),n};const E2=w("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;E2&&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}}U1([u()],z.prototype,"overrideState"),U1([u()],z.prototype,"value");class R2 extends Zi{constructor(){super([z])}onSerialize(e,t){}onDeserialize(e,t){const i=t.target,n=t.path;let s;if(i&&n&&(s=i[n]),(typeof s!="object"||typeof s=="object"&&s.isVolumeParameter!==!0)&&(s=new z),typeof e=="object"&&"value"in e){const r=e.value;s.initialize(r),s.overrideState=e.overrideState}else s.value=e;return s}}new R2;var T2=Object.defineProperty,A2=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&T2(e,t,n),n};const P0=w("debugpost");class nt 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(),P0&&console.warn("Enable",this.constructor.name+(this.__internalDidAwakeAndStart?"":" (awake)")),this.__internalDidAwakeAndStart&&(this.active=!0),this.onEffectEnabled()}onDisable(){super.onDisable(),P0&&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=P2(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(){P0&&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}}}A2([u()],nt.prototype,"active");var I2=Object.defineProperty,L2=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&I2(e,t,n),n};const D2=w("debugpost"),O0={};function cn(o,e){O0[o]=e}function j2(o){return o.__type in O0?O0[o.__type]:(D2&&o.__type&&console.warn("Unknown postprocessing type",o.__type,o),nt)}class zp{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)}}L2([Qe([o=>j2(o),nt])],zp.prototype,"components");var B2=Object.defineProperty,F2=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&B2(e,t,n),n};const U2=w("debugpost");class Eh extends nt{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=>{U2&&console.log("Antialiasing preset changed to",t),e.applyPreset(t)},e}}F2([u(z)],Eh.prototype,"preset"),cn("Antialiasing",Eh);var z2=Object.defineProperty,k0=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&z2(e,t,n),n};const Np=class WS extends nt{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=WS.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=So.lerp(.1,.9,t))},e}};k0([u(z)],Np.prototype,"threshold"),k0([u(z)],Np.prototype,"intensity"),k0([u(z)],Np.prototype,"scatter");let Wp=Np;cn("Bloom",Wp);var N2=Object.defineProperty,W2=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&N2(e,t,n),n};class Rh extends nt{get typeName(){return"ChromaticAberration"}intensity=new z(0);onCreateEffect(){const e=new T.POSTPROCESSING.MODULE.ChromaticAberrationEffect;return e.offset=new K(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}}W2([u(z)],Rh.prototype,"intensity"),cn("ChromaticAberration",Rh);var Th=(o=>(o[o.None=0]="None",o[o.Neutral=1]="Neutral",o[o.ACES=2]="ACES",o[o.AgX=3]="AgX",o[o.KhronosNeutral=4]="KhronosNeutral",o))(Th||{});const z1=new Map;function M0(o){switch(o){case 0:return Dm;case 1:return Lm;case 2:return Rd;case 3:return Ed;case 4:return Da;default:return z1.has(o)||(z1.set(o,!0),console.warn("[Postprocessing] Unknown tone mapping mode",o)),Da}}function V2(o){switch(o){case Dm:return 0;case Rd:return 2;case Ed:return 3;case Da:return 1;case Lm:return 1;default:return 0}}function Vp(o){switch(o){case Dm:return T.POSTPROCESSING.MODULE.ToneMappingMode.LINEAR;case Rd:return T.POSTPROCESSING.MODULE.ToneMappingMode.ACES_FILMIC;case Ed:return T.POSTPROCESSING.MODULE.ToneMappingMode.AGX;case Da:return T.POSTPROCESSING.MODULE.ToneMappingMode.NEUTRAL;case Lm:return T.POSTPROCESSING.MODULE.ToneMappingMode.REINHARD;default:return T.POSTPROCESSING.MODULE.ToneMappingMode.LINEAR}}var $2=Object.defineProperty,N1=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&$2(e,t,n),n};const E0=w("debugpost");class Js extends nt{get typeName(){return"ToneMapping"}mode=new z(void 0);exposure=new z(1);setMode(e){const t=Th[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=F1(this);e&&super.onEffectEnabled(e)}_tonemappingEffect=null;onCreateEffect(){if(this.mode.isInitialized==!1){const i=V2(this.context.renderer.toneMapping);E0&&console.log("[PostProcessing] Initializing ToneMapping mode to renderer.toneMapping",this.context.renderer.toneMapping+" \u2192 "+i),this.mode.initialize(i)}this._tonemappingEffect?.dispose();const e=M0(this.mode.value),t=this._tonemappingEffect=new T.POSTPROCESSING.MODULE.ToneMappingEffect({mode:Vp(e)});return this.mode.onValueChanged=i=>{if(typeof i=="string")i=jw(i),t.mode=Vp(i);else{const n=M0(i);t.mode=Vp(n)}t.name="ToneMapping ("+Th[i]+")",E0&&console.log("[PostProcessing] ToneMapping mode changed to",Th[i],e,t.mode)},E0&&console.log("[PostProcessing] Use ToneMapping",Th[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=M0(this.mode.value)),this.exposure.overrideState&&this.exposure.value!==void 0)){const e=Math.max(0,this.exposure.value);this.context.renderer.toneMappingExposure=e}}}N1([u(z)],Js.prototype,"mode"),N1([u(z)],Js.prototype,"exposure"),cn("Tonemapping",Js);var H2=Object.defineProperty,$p=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&H2(e,t,n),n};class er extends nt{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(s=>s instanceof Js);t||(t=new Js,this.postprocessingContext?.components.push(t)),this.postExposure.onValueChanged=s=>{this.postExposure.overrideState&&t?t.exposure.value=s: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=s=>i.contrast=s;const n=new T.POSTPROCESSING.MODULE.HueSaturationEffect;return this.hueShift.onValueChanged=s=>n.hue=s,this.saturation.onValueChanged=s=>n.saturation=s,e.push(i),e.push(n),e}}$p([u(z)],er.prototype,"postExposure"),$p([u(z)],er.prototype,"contrast"),$p([u(z)],er.prototype,"hueShift"),$p([u(z)],er.prototype,"saturation"),cn("ColorAdjustments",er);var G2=Object.defineProperty,da=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&G2(e,t,n),n};const q2=w("debugpost");class jn extends nt{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 j.lerp(2,.01,i)};const e=20;this.aperture.valueProcessor=t=>{const i=1-t/32;return j.lerp(1,e,i)}}onCreateEffect(){if(this.mode===0){q2&&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(){}}da([u()],jn.prototype,"mode"),da([u(z)],jn.prototype,"focusDistance"),da([u(z)],jn.prototype,"focalLength"),da([u(z)],jn.prototype,"aperture"),da([u(z)],jn.prototype,"gaussianMaxRadius"),da([u(z)],jn.prototype,"resolutionScale"),da([u(z)],jn.prototype,"bokehScale"),cn("DepthOfField",jn);class Ah extends nt{effect;constructor(e){super(),this.effect=e}get typeName(){return this.effect.constructor.name}onCreateEffect(){return this.effect}}var X2=Object.defineProperty,Q2=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&X2(e,t,n),n};class Ih extends nt{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}}Q2([u(z)],Ih.prototype,"granularity"),cn("PixelationEffect",Ih);var Y2=Object.defineProperty,Lh=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&Y2(e,t,n),n};class is extends nt{get typeName(){return"ScreenSpaceAmbientOcclusion"}intensity=new z(2);falloff=new z(1);samples=new z(9);color=new z(new oe(0,0,0));luminanceInfluence=new z(.7);onBeforeRender(){if(this._ssao&&this.context.mainCamera instanceof de){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 oe),n.color.copy(r)},this.luminanceInfluence.onValueChanged=r=>{n.luminanceInfluence=r};const s=new Array;return s.push(t),s.push(i),s.push(n),s}}Lh([u(z)],is.prototype,"intensity"),Lh([u(z)],is.prototype,"falloff"),Lh([u(z)],is.prototype,"samples"),Lh([u(z)],is.prototype,"color"),Lh([u(z)],is.prototype,"luminanceInfluence"),cn("ScreenSpaceAmbientOcclusion",is);var Z2=Object.defineProperty,ua=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&Z2(e,t,n),n};const K2=w("debugN8AO");var R0=(o=>(o[o.Performance=0]="Performance",o[o.Low=1]="Low",o[o.Medium=2]="Medium",o[o.High=3]="High",o[o.Ultra=4]="Ultra",o))(R0||{});class Bn extends nt{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 oe(0,0,0));screenspaceRadius=!1;quality=2;_ssao;onValidate(){this._ssao&&(this._ssao.setQualityMode(R0[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 s=R0[this.quality];n.setQualityMode(s),n.configuration.transparencyAware=!1;const r=new Vn(t,i);return n.configuration.beautyRenderTarget=r,n.configuration.autoRenderBeauty=!1,n.configuration.gammaCorrection=this.gammaCorrection,n.configuration.screenSpaceRadius=this.screenspaceRadius,K2&&(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 oe),n.configuration.color.copy(a)},n}}ua([Mt(),u()],Bn.prototype,"gammaCorrection"),ua([u(z)],Bn.prototype,"aoRadius"),ua([u(z)],Bn.prototype,"falloff"),ua([u(z)],Bn.prototype,"intensity"),ua([u(z)],Bn.prototype,"color"),ua([Mt(),u()],Bn.prototype,"screenspaceRadius"),ua([Mt(),u()],Bn.prototype,"quality"),cn("ScreenSpaceAmbientOcclusionN8",Bn);var J2=Object.defineProperty,eI=Object.getOwnPropertyDescriptor,W1=(o,e,t,i)=>{for(var n=eI(e,t),s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&J2(e,t,n),n};class Dh extends nt{get typeName(){return"Sharpening"}order=ut.Sharpening;_effect;onCreateEffect(){return this._effect??=new(tI()),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}W1([u()],Dh.prototype,"amount"),W1([u()],Dh.prototype,"radius");function tI(){const o=`
1311
+ `)}r&&s.size&&console.log(d);const g=new Set;for(const _ of m){_.getPath||console.error("USDZExporter: Animation target object has no getPath method. This is likely a bug",_);let v=_.getPath();v.startsWith("<")&&(v=v.substring(1)),v.endsWith(">")&&(v=v.substring(0,v.length-1)),g.add({path:v,obj:_})}const f=Array.from(g).sort((_,v)=>_.path.length-v.path.length),y=new Array;for(let _=0;_<f.length;_++)for(let v=_+1;v<f.length;v++)if(f[v].path.startsWith(f[_].path)){const P=f[v],k=f[_];y.push({child:P.obj.displayName+" ("+P.path+")",parent:k.obj.displayName+" ("+k.path+")"})}y.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:y,playAnimationActions:s})}for(const d of new Set([...t,...i]))if(Array.isArray(d))for(const p of d)n.add(p.uuid);else n.add(d.uuid);Cp&&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){Cp&&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 n=await(await(await fetch(t)).blob()).arrayBuffer(),s=new Uint8Array(n);e.files[i]=s}this.behaviourComponentsCopy.length=0,this.audioClipsCopy.length=0}}class Hy{get extensionName(){return"Physics"}onExportObject(e,t,i){const n=S.getComponents(e,Ke).filter(l=>l.enabled),s=S.getComponents(e,nn).filter(l=>l.enabled&&!l.isTrigger);let r=n.length>0?n[0]:null;const a=s.length>0?s[0]:null;a&&!r&&(r=new Ke,r.isKinematic=!0),r&&t.addEventListener("serialize",(l,c)=>{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("}"),s.length>0){const h=s[0];l.beginBlock('def RealityKitStruct "material"',"{",!0);const d=h.sharedMaterial;d&&d.dynamicFriction!==void 0&&l.appendLine(`double dynamicFriction = ${h.sharedMaterial?.dynamicFriction}`),d&&d.bounciness!==void 0&&l.appendLine(`double restitution = ${h.sharedMaterial?.bounciness}`),d&&d.staticFriction!==void 0&&l.appendLine(`double staticFriction = ${h.sharedMaterial?.staticFriction}`),l.closeBlock("}")}l.closeBlock("}")}}),a&&(t.addEventListener("serialize",(l,c)=>{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 h=a.isTrigger?"Trigger":"Default";if(l.appendLine(`token type = "${h}"`),l.beginBlock('def RealityKitStruct "Shape"',"{",!0),a instanceof pl){const d=a;l.appendLine('token shapeType = "Sphere"'),l.appendLine(`float radius = ${d.radius}`)}else if(a instanceof Gu){const d=a;l.appendLine('token shapeType = "Box"'),l.appendLine(`float3 extent = (${d.size.x}, ${d.size.y}, ${d.size.z})`)}else if(a instanceof Wo){const d=a;l.appendLine('token shapeType = "Capsule"'),l.appendLine(`float radius = ${d.radius}`),l.appendLine(`float height = ${d.height}`)}else if(a instanceof js&&a.sharedMesh?.geometry){const d=a.sharedMesh.geometry;d.boundingBox||d.computeBoundingBox();const p=a.sharedMesh.geometry.boundingBox;p&&(l.appendLine('token shapeType = "Box"'),l.appendLine(`float3 extent = (${p.max.x-p.min.x}, ${p.max.y-p.min.y}, ${p.max.z-p.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("}")}),s.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 PA=w("debugshadowcomponents");Hb.prototype.interactable={get(){return this.interactive},set(o){this.interactable=o}};class un 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(){ai.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,yh)),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,un),!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[Ai]=this,this.setShadowComponentOwner(e);let n=!1;if(this.Root?.gameObject===this.gameObject)this.gameObject.add(e);else{const s=this._parentComponent.shadowComponent;s&&(s?.add(e),n=!0)}this.shadowComponent=e,t&&t.shadowComponent&&this.shadowComponent&&t.shadowComponent.add(this.shadowComponent),Dc&&e.add(new Ci(.5)),this.onAfterAddedToScene(),n&&zP(),PA&&console.warn("Added shadow component",this.shadowComponent)}setShadowComponentOwner(e){if(e&&(e[Ai]===void 0||e[Ai]===this)&&(e[Ai]=this,e.children))for(const t of e.children)this.setShadowComponentOwner(t)}traverseOwnedShadowComponents(e,t,i){if(e&&e[Ai]===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 yh extends un{awake(){super.awake()}}var OA=Object.defineProperty,kA=Object.getOwnPropertyDescriptor,bh=(o,e,t,i)=>{for(var n=i>1?void 0:i?kA(e,t):e,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&OA(e,t,n),n};const Gy=w("debugui"),qy=w("debuguilayout");class w1{width;height}class x1{x;y;width;height}const In=new b,_h=new J,Pp=new N,Tl=class US extends un{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 K),this._anchoredPosition}set anchoredPosition(e){this._anchoredPosition=e}sizeDelta=new K(100,100);pivot=new K(.5,.5);anchorMin=new K(0,0);anchorMax=new K(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 M,this.rectBlock.name=this.name,this.lastMatrix=new J,this._lastAnchoring=null,this._initialPosition=this.gameObject.position.clone(),this._initialPosition.z=0,this._anchoredPosition||(this._anchoredPosition=new K),hl(this,"_anchoredPosition",()=>{this.markDirty()}),hl(this,"sizeDelta",()=>{this.markDirty()}),hl(this,"pivot",()=>{this.markDirty()}),hl(this,"anchorMin",()=>{this.markDirty()}),hl(this,"anchorMax",()=>{this.markDirty()})}onEnable(){super.onEnable(),this.rectBlock||(this.rectBlock=new M),this.lastMatrix||(this.lastMatrix=new J),this._lastAnchoring||(this._lastAnchoring=new K),this._initialPosition||(this._initialPosition=new b),this._anchoredPosition||(this._anchoredPosition=new K),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(qy?`${e.name} changed`:void 0)}get isDirty(){return this._transformNeedsUpdate||(this._transformNeedsUpdate=!this.lastMatrix.equals(this.gameObject.matrix)),this._transformNeedsUpdate}markDirty(){this._transformNeedsUpdate||(qy&&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,US):this._parentRectTransform=void 0,this._transformNeedsUpdate=!1,qy&&console.warn("RectTransform \u2192 ApplyTransform",this.name+" because "+e),this.isRoot()?this.Root.screenspace||(t.rotation.y=Math.PI):(t.matrix.identity(),t.matrixAutoUpdate=!1,In.set(0,0,0),this.applyPivot(In),t.matrix.setPosition(In.x,In.y,0),(this.gameObject.quaternion.x||this.gameObject.quaternion.y||this.gameObject.quaternion.z)&&(Pp.copy(this.gameObject.quaternion),Pp.x*=-1,Pp.z*=-1,_h.makeRotationFromQuaternion(Pp),t.matrix.premultiply(_h)),In.set(0,0,0),this.applyAnchoring(In),this.canvas?.screenspace?In.z+=.1:In.z+=.01,_h.identity(),_h.setPosition(In.x,In.y,In.z),t.matrix.premultiply(_h),t.matrix.scale(this.gameObject.scale)),this.lastMatrix.copy(this.gameObject.matrix);const i=!0;for(const n of vu(this.gameObject,un,i,1)){if(n===this||!n.activeAndEnabled)continue;const s=n;s.onParentRectTransformChanged&&s.onParentRectTransformChanged(this)}}_lastAnchoring;applyAnchoring(e){this._lastAnchoring||(this._lastAnchoring=new K);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 s=1-this.anchorMax.y-this.anchorMin.y;n-=i.height*.5*s,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},Gy&&console.log(this.name,e);const t=new Hb(e);return this._createdBlocks.push(t),t}createNewText(e){Gy&&console.log(e),e={...this.getBasicOptions(),...e},Gy&&console.log(this.name,e);const t=new $b(e);return this._createdTextBlocks.push(t),t}};bh([u(K)],Tl.prototype,"anchoredPosition",1),bh([u(K)],Tl.prototype,"sizeDelta",2),bh([u(K)],Tl.prototype,"pivot",2),bh([u(K)],Tl.prototype,"anchorMin",2),bh([u(K)],Tl.prototype,"anchorMax",2);let Ln=Tl;var MA=Object.defineProperty,S1=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&MA(e,t,n),n};class Al extends E{effectColor;effectDistance}S1([u(se)],Al.prototype,"effectColor"),S1([u(K)],Al.prototype,"effectDistance");var EA=Object.defineProperty,RA=Object.getOwnPropertyDescriptor,C1=(o,e,t,i)=>{for(var n=i>1?void 0:i?RA(e,t):e,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&EA(e,t,n),n};const ta={backgroundColor:new oe(1,1,1),backgroundOpacity:1,borderColor:new oe(1,1,1),borderOpacity:1},Xy=class fd extends un{get isGraphic(){return!0}get color(){return this._color||(this._color=new se(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 se(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 oe(1,0,1);onColorChanged(){if(this.uiObject){this.sRGBColor.copy(this._color),this.sRGBColor.convertLinearToSRGB(),ta.backgroundColor=this.sRGBColor,ta.backgroundOpacity=this._color.alpha;const e=this.uiObject._simpleState__activeStates?.[0];if(e){const t=this.uiObject._simpleState__states?.[e];t&&("backgroundColor"in t&&(ta.backgroundColor=t.backgroundColor),"backgroundOpacity"in t&&(ta.backgroundOpacity=t.backgroundOpacity))}ta.backgroundOpacity*=this._alphaFactor,this.applyEffects(ta,this._alphaFactor),this.uiObject.set(ta),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,Ln)),!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 NP(this.uiObject)),this.uiObject.setupState(e.state,e.attributes))}setOptions(e){this.makePanel(),this.uiObject&&this.uiObject.set(e)}awake(){super.awake(),this.makePanel(),hl(this,"_color",()=>uR(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 e={backgroundColor:this.color,backgroundOpacity:this.color.alpha,offset:.015};this.onBeforeCreate(e),this.applyEffects(e),this.onCreate(e),this.controlsChildLayout=!1,this._currentlyCreatingPanel=!1,this.onAfterCreated(),this.onColorChanged()}onBeforeCreate(e){}onCreate(e){this.uiObject=this.rectTransform.createNewBlock(e),this.uiObject.name=this.name}onAfterCreated(){}applyEffects(e,t=1){const i=this.gameObject?.getComponent(Al);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(fd.textureCache.has(e))e=fd.textureCache.get(e);else if(!e.isRenderTargetTexture){const t=e.clone();t.colorSpace=Po,fd.textureCache.set(e,t),e=t}this.setOptions({backgroundImage:e,borderRadius:0,backgroundOpacity:this.color.alpha,backgroundSize:"stretch"}),Ve.assignTextureLOD(e,0).then(t=>{t instanceof Se&&(e&&fd.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)}};C1([u(se)],Xy.prototype,"color",1),C1([u()],Xy.prototype,"raycastTarget",2);let vh=Xy;class wh extends vh{_flippedObject=!1;onAfterCreated(){this.uiObject&&!this._flippedObject&&(this._flippedObject=!0,this.uiObject.scale.y*=-1)}}var TA=Object.defineProperty,AA=Object.getOwnPropertyDescriptor,Ko=(o,e,t,i)=>{for(var n=i>1?void 0:i?AA(e,t):e,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&TA(e,t,n),n};const ia=w("debugtext");var ht=(o=>(o[o.UpperLeft=0]="UpperLeft",o[o.UpperCenter=1]="UpperCenter",o[o.UpperRight=2]="UpperRight",o[o.MiddleLeft=3]="MiddleLeft",o[o.MiddleCenter=4]="MiddleCenter",o[o.MiddleRight=5]="MiddleRight",o[o.LowerLeft=6]="LowerLeft",o[o.LowerCenter=7]="LowerCenter",o[o.LowerRight=8]="LowerRight",o))(ht||{}),P1=(o=>(o[o.Normal=0]="Normal",o[o.Bold=1]="Bold",o[o.Italic=2]="Italic",o[o.BoldAndItalic=3]="BoldAndItalic",o))(P1||{});class Ht extends vh{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 oe(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){ia&&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,ia&&(e.backgroundColor=16750848,e.backgroundOpacity=.5);const t=this.rectTransform;e={...e,...this.getTextOpts()},this.getAlignment(e),ia&&(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(ia&&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 s=new Wm({textContent:e.substring(0,i.startIndex),color:"inherit"});this.uiObject.add(s)}}else{this.uiObject.textContent="",this.setOptions({textContent:e});return}const n=[];for(;i;){const s=this.getNextTag(e,i.endIndex),r={fontFamily:this.uiObject?.get("fontFamily"),color:"inherit",textContent:""};if(s){r.textContent=this.getText(e,i,s),this.handleTag(i,r,n);const a=new Wm(r);this.uiObject?.add(a)}else{r.textContent=e.substring(i.endIndex),this.handleTag(i,r,n);const a=new Wm(r);this.uiObject?.add(a)}i=s}}}_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 s=0;s<this._textMeshUi.length;s++){if(e[s]===!0)continue;n=!0;const r=this._textMeshUi[s];r.textContent&&(Wu(r,i),e[s]=!0)}if(!n)break;yield}}handleTag(e,t,i){if(!e.isEndTag){if(e.type.includes("color")){const n=new Qy(e,{color:t.color});if(i.push(n),e.type.length>6){const s=parseInt("0x"+e.type.substring(7));t.color=s}else t.color=new oe(1,1,1)}else if(e.type=="b"){this.setFont(t,1);const n=new Qy(e,{fontWeight:700});i.push(n)}else if(e.type=="i"){this.setFont(t,2);const n=new Qy(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 s=e.substring(i+1,n);return{type:s,startIndex:i,endIndex:n+1,isEndTag:s.startsWith("/")}}return null}setFont(e,t){if(!this.font)return;const i=this.font,n=this.getFamilyNameWithCorrectSuffix(i,t);ia&&console.log("Selected font family:"+n);let s=Gb.getFontFamily(n);switch(s||(s=Gb.addFontFamily(n)),e.fontFamily=s,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=s.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=s.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(IA.includes(n))return ia&&console.warn("Unsupported font style: "+n),e;const s=e.lastIndexOf("/");let r=e;s>=0&&(r=r.substring(s+1));const a=r[0]===r[0].toUpperCase(),l=e.substring(0,i>s?i:e.length);switch(ia&&console.log("Select font: ",e,P1[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}}}Ko([u()],Ht.prototype,"alignment",2),Ko([u()],Ht.prototype,"verticalOverflow",2),Ko([u()],Ht.prototype,"horizontalOverflow",2),Ko([u()],Ht.prototype,"lineSpacing",2),Ko([u()],Ht.prototype,"supportRichText",2),Ko([u(URL)],Ht.prototype,"font",2),Ko([u()],Ht.prototype,"fontStyle",2),Ko([u()],Ht.prototype,"text",1),Ko([u()],Ht.prototype,"fontSize",1);class Qy{tag;previousValues;constructor(e,t){this.tag=e,this.previousValues=t}}const IA=["medium","mediumitalic","black","blackitalic","thin","thinitalic","extrabold","light","lightitalic","semibold"];class Il{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/${mp(this.material)}>`),t.closeBlock()}}class Yy{static singleLine(e,t,i){const n=new Il("text_"+Il.getId());return n.content=e,t&&(n.pointSize=t),i&&(n.depth=i),n}static multiLine(e,t,i,n,s,r){const a=new Il("text_"+Il.getId());return a.content=e,a.width=t,a.height=i,a.horizontalAlignment=n,a.verticalAlignment=s,r!==void 0&&(a.wrapMode=r),a}}const LA=new J().makeRotationY(Math.PI),DA=new J().makeScale(-1,1,-1);class Op{get extensionName(){return"text"}exportText(e,t,i){const n=S.getComponent(e,Ht);if(!n)return;const s=S.getComponent(e,Ln);let r=100,a=100;s&&(r=s.width,a=s.height);const l=LA.clone();s&&l.premultiply(DA),t.setMatrix(l);const c=n.color.clone();t.material=new gt({color:c,emissive:c}),t.addEventListener("serialize",(h,d)=>{let p=n.text;p=p.replace(/\r/g,""),p=p.replace(/\n/g,"\\n");const m=Yy.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,h)})}convertToTextSize(e){return 1/.0502*144*e}setOverflow(e,t){t.horizontalOverflow?e.wrapMode="singleLine":e.wrapMode="flowing"}setTextAlignment(e,t){switch(t){case ht.LowerLeft:case ht.MiddleLeft:case ht.UpperLeft:e.horizontalAlignment="left";break;case ht.LowerCenter:case ht.MiddleCenter:case ht.UpperCenter:e.horizontalAlignment="center";break;case ht.LowerRight:case ht.MiddleRight:case ht.UpperRight:e.horizontalAlignment="right";break}switch(t){case ht.LowerLeft:case ht.LowerCenter:case ht.LowerRight:e.verticalAlignment="bottom";break;case ht.MiddleLeft:case ht.MiddleCenter:case ht.MiddleRight:e.verticalAlignment="middle";break;case ht.UpperLeft:case ht.UpperCenter:case ht.UpperRight:e.verticalAlignment="top";break}}}var jA=Object.defineProperty,et=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&jA(e,t,n),n};const O1=w("debuguilayout");class na{left=0;right=0;top=0;bottom=0;get vertical(){return this.top+this.bottom}get horizontal(){return this.left+this.right}}et([u()],na.prototype,"left"),et([u()],na.prototype,"right"),et([u()],na.prototype,"top"),et([u()],na.prototype,"bottom");class Fi 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&&(O1&&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(){O1&&console.log(this.name,this),this._rectTransform=this.gameObject.getComponent(Ln);const e=this.gameObject.getComponentInParent(Ll);e&&e.registerLayoutGroup(this),this._needsUpdate=!0}onDisable(){const e=this.gameObject.getComponentInParent(Ll);e&&e.unregisterLayoutGroup(this)}set m_Spacing(e){e!==this.spacing&&(this._needsUpdate=!0,this.spacing=e)}get m_Spacing(){return this.spacing}}et([u()],Fi.prototype,"childAlignment"),et([u()],Fi.prototype,"reverseArrangement"),et([u()],Fi.prototype,"spacing"),et([u(na)],Fi.prototype,"padding"),et([u()],Fi.prototype,"minWidth"),et([u()],Fi.prototype,"minHeight"),et([u()],Fi.prototype,"flexibleHeight"),et([u()],Fi.prototype,"flexibleWidth"),et([u()],Fi.prototype,"preferredHeight"),et([u()],Fi.prototype,"preferredWidth");class Gs extends Fi{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 s=e.height;let r=s;n-=this.padding.horizontal,r-=this.padding.vertical,t==="x"?this.padding.horizontal:this.padding.vertical;const a=t==="x",l=a?"y":"x",c=a?this.childControlWidth:this.childControlHeight,h=a?this.childControlHeight:this.childControlWidth,d=a?this.childForceExpandWidth:this.childForceExpandHeight,p=a?this.childForceExpandHeight:this.childForceExpandWidth,m=a?r:n,g=a?i:s,f=.5*(a?this.childAlignment%3:Math.floor(this.childAlignment/3));let y=0;a?y+=this.padding.left:y+=this.padding.top;let _=0,v=0;for(let L=0;L<this.gameObject.children.length;L++){const V=this.gameObject.children[L],W=S.getComponent(V,Ln);W?.activeAndEnabled&&(v+=1,a?_+=W.width:_+=W.height)}let P=0;const k=this.spacing*(v-1);if(d||c){let L=0;a?L=n-=k:L=r-=k,v>0&&(P=L/v)}let O=0;O+=this.padding.left,O-=this.padding.right,f!==0&&(y=g-_,y*=f,y-=k*f,a?(y-=this.padding.right*f,y+=this.padding.left*(1-f),y<this.padding.left&&(y=this.padding.left)):(y-=this.padding.bottom*f,y+=this.padding.top*(1-f),y<this.padding.top&&(y=this.padding.top)));let D=1;for(let L=0;L<this.gameObject.children.length;L++){const V=this.gameObject.children[L],W=S.getComponent(V,Ln);if(W?.activeAndEnabled){W.pivot?.set(.5,.5),W.anchorMin.set(0,1),W.anchorMax.set(0,1);const G=i*.5+O*.5;W.anchoredPosition.x!==G&&(W.anchoredPosition.x=G);const X=s*-.5;W.anchoredPosition.y!==X&&(W.anchoredPosition.y=X),p&&h&&W.sizeDelta[l]!==m&&(W.sizeDelta[l]=m),d&&c&&W.sizeDelta[t]!==P&&(W.sizeDelta[t]=P);const R=a?W.width:W.height,$=R*.5;if(y+=$,d){const he=P*D-P*.5;he>y&&(y=he-P*.5+R+this.padding.left,y-=$)}let q=y;t==="y"&&(q=-q),W.anchoredPosition[t]!==q&&(W.anchoredPosition[t]=q),y+=$,y+=this.spacing,D+=1}}}}et([u()],Gs.prototype,"childControlHeight"),et([u()],Gs.prototype,"childControlWidth"),et([u()],Gs.prototype,"childForceExpandHeight"),et([u()],Gs.prototype,"childForceExpandWidth"),et([u()],Gs.prototype,"childScaleHeight"),et([u()],Gs.prototype,"childScaleWidth");class Zy extends Gs{get primaryAxis(){return"y"}}class Ky extends Gs{get primaryAxis(){return"x"}}class Jy extends Fi{onCalculateLayout(){}}var BA=Object.defineProperty,FA=Object.getOwnPropertyDescriptor,co=(o,e,t,i)=>{for(var n=i>1?void 0:i?FA(e,t):e,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&BA(e,t,n),n},k1=(o=>(o[o.ScreenSpaceOverlay=0]="ScreenSpaceOverlay",o[o.ScreenSpaceCamera=1]="ScreenSpaceCamera",o[o.WorldSpace=2]="WorldSpace",o[o.Undefined=-1]="Undefined",o))(k1||{});const e0=w("debuguilayout"),rn=class zS extends yh{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 zS||(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,e0&&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 J,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 mc(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(),ai.ensureUpdateMeshUI(qb,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(),ai.ensureUpdateMeshUI(qb,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 J);const e=!this._lastMatrixWorld.equals(this.gameObject.matrixWorld);e0&&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(Fi)),(t.isDirty||i?.isDirty)&&(e0&&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(),xe.OnBeforeRender))}*_updateRenderSettingsDelayed(){if(yield,this._updateRenderSettingsRoutine=void 0,this.shadowComponent){this.onUpdateRenderMode(),Wu(this.shadowComponent,this);for(const e of S.getComponentsInChildren(this.gameObject,un))Wu(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=j.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 s=this.gameObject.getComponent(Ln);let r=!1;s.sizeDelta.x!==this.context.domWidth&&(r=!0),s.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&&(s.sizeDelta.x=this.context.domWidth,s.sizeDelta.y=this.context.domHeight,s?.markDirty());break;case 2:this._lastWidth=-1,this._lastHeight=-1;break}}};co([u()],rn.prototype,"renderOnTop",1),co([u()],rn.prototype,"depthWrite",1),co([u()],rn.prototype,"doubleSided",1),co([u()],rn.prototype,"castShadows",1),co([u()],rn.prototype,"receiveShadows",1),co([u()],rn.prototype,"renderMode",1),co([u(rn)],rn.prototype,"rootCanvas",1),co([u()],rn.prototype,"scaleFactor",1),co([u(gi)],rn.prototype,"worldCamera",2),co([u()],rn.prototype,"planeDistance",2);let Ll=rn;var UA=Object.defineProperty,zA=Object.getOwnPropertyDescriptor,t0=(o,e,t,i)=>{for(var n=i>1?void 0:i?zA(e,t):e,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&UA(e,t,n),n};class qs 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(),xe.OnBeforeRender))}*applyChangesDelayed(){this._isDirty=!1,this.applyChangesNow()}_buffer=[];applyChangesNow(){this._buffer.length=0;for(const e of S.getComponentsInChildren(this.gameObject,un,this._buffer)){const t=e;t.setAlphaFactor&&t.setAlphaFactor(this._alpha)}}}t0([u()],qs.prototype,"alpha",1),t0([u()],qs.prototype,"interactable",2),t0([u()],qs.prototype,"blocksRaycasts",2);class i0{get extensionName(){return"tmui"}onExportObject(e,t,i){const n=S.getComponent(e,Ll);if(n&&n.enabled&&n.renderMode===k1.WorldSpace){const s=new Op,r=S.getComponent(e,Ln),a=S.getComponent(e,qs),l=new Array;if(r){if(!S.isActiveSelf(e)){const d=S.isActiveSelf(e);S.setActive(e,!0),r.onEnable(),r.updateTransform(),l.push(()=>{r.onDisable(),S.setActive(e,d)})}e.traverse(d=>{if(!S.isActiveInHierarchy(d)){const p=S.isActiveSelf(d);S.setActive(d,!0);const m=S.getComponent(d,un);m&&(m.onEnable(),l.push(()=>{m.onDisable()}));const g=S.getComponent(d,Ln);g&&(g.onEnable(),g.updateTransform(),g.onApplyTransform(),l.push(()=>{g.onDisable()}));const f=S.getComponent(d,Ht);f&&(f.onEnable(),l.push(()=>{f.onDisable()})),l.push(()=>{S.setActive(d,p)})}}),r.width,r.height;const c=rt.createEmpty(),h=r.shadowComponent;if(t.add(c),h){const d=h.matrix;c.setMatrix(d);const p=new Map,m=new Map;p.set(h,c),m.set(h,a?a.alpha:1),h.traverse(g=>{if(g===h)return;const f=rt.createEmpty();f.setMatrix(g.matrix);const y=g.parent,_=!!y&&typeof y.textContent=="string"&&y.textContent.length>0;let v=m.get(y)||1;const P=S.getComponent(g,qs);if(P&&(v*=P.alpha),g instanceof H&&_){const O=g[Ai];O?s.exportText(O.gameObject,f,i):console.error("Error when exporting UI: shadow component owner not found. This is likely a bug.",g)}if(g instanceof H&&!_){const O=g.geometry.clone();O.scale(1,1,-1),this.flipWindingOrder(O),f.geometry=O;const D=new oe,L=g.material.opacity;D.copy(g.material.color),f.material=new Ce({color:D,opacity:L*v,map:g.material.map,transparent:!0})}p.set(g,f),m.set(g,v);const k=p.get(y);if(!k){console.error("Error when exporting UI: shadow component parent not found!",g,g.parent);return}k.add(f)})}}for(const c of l)c()}}flipWindingOrder(e){const t=e.index.array;for(let i=0,n=t.length/3;i<n;i++){const s=t[i*3];t[i*3]=t[i*3+2],t[i*3+2]=s}e.index.needsUpdate=!0}}const xh=w("debugusdz");function NA(o,e){const t=[],i=S.getComponentsInChildren(o,_t),n=S.getComponentsInChildren(o,Ut),s=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||s.includes(a))continue;const c=new hh;c.animator=a,c.stateName=l.name,c.trigger="start",c.name="PlayAnimationOnClick_implicitAtStart_"+c.stateName;const h=new M;S.addComponent(h,c),r.push(h),s.push(a),o.add(h)}else for(const a of i){if(!a||!a.runtimeAnimatorController||!a.enabled)continue;xh&&console.log(a);const l=[];for(const c of a.runtimeAnimatorController.enumerateActions()){xh&&console.log(c);const h=c.getClip();l.includes(h)||l.push(h)}t.push({root:a.gameObject,clips:l})}if(e.injectImplicitBehaviours)for(const a of n){if(!a||!a.clip||!a.enabled||!a.playAutomatically||s.includes(a))continue;const l=new hh;l.animation=a,l.stateName=a.clip.name,l.trigger="start",l.name="PlayAnimationOnClick_implicitAtStart_"+l.stateName;const c=new M;S.addComponent(c,l),r.push(c),s.push(a),o.add(c)}else for(const a of n){xh&&console.log(a);const l=[];for(const c of a.animations)l.includes(c)||l.push(c);t.push({root:a.gameObject,clips:l})}xh&&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 WA(o,e){const t=S.getComponentsInChildren(o,Di),i=S.getComponentsInChildren(o,zs),n=new Array,s=new Array;xh&&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 zs;a.target=r,a.name="PlayAudioOnClick_implicitAtStart_",a.trigger="start";const l=new M;S.addComponent(l,a),console.log("implicit PlayAudioOnStart",l,a),s.push(l),n.push(r),o.add(l)}return s}function VA(o){return new jt("DisableAtStart",$t.sceneStartTrigger(),fe.fadeAction(o,0,!1))}function M1(o,e){const t=o.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 s=document.createElement("a");s.id="needle-usdz-link",s.style.display="none",s.rel="ar",s.href="",s.target="_blank",i.appendChild(s);const r=document.createElement("img");return r.id="button",s.appendChild(r),o.domElement.shadowRoot.appendChild(i),s}var $A=Object.defineProperty,Rt=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&$A(e,t,n),n};const Tt=w("debugusdz"),HA=w("debugusdzpruning");class oa{callToAction;checkoutTitle;checkoutSubtitle;callToActionURL}Rt([u()],oa.prototype,"callToAction"),Rt([u()],oa.prototype,"checkoutTitle"),Rt([u()],oa.prototype,"checkoutSubtitle"),Rt([u()],oa.prototype,"callToActionURL");const bi=class Sa extends E{static beforeExport=new ae;static afterExport=new ae;static beforeLODExport=new ae;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(){Tt&&(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=I.supportsQuickLookAR(),t=I.isiOS()||I.isiPad();!this.button&&(Tt||e||t)&&(this.allowCreateQuicklookButton&&(this.button=this.createQuicklookButton()),this.lastCallback=this.quicklookCallback.bind(this),this.link=M1(this.context,e),this.link.addEventListener("message",this.lastCallback)),Tt&&Oe("USDZ Exporter enabled: "+this.name),document.getElementById("open-in-ar")?.addEventListener("click",this.onClickedOpenInARElement),kc.registerExporter(this)}onDisable(){this.button?.remove(),this.link?.removeEventListener("message",this.lastCallback),Tt&&Oe("USDZ Exporter disabled: "+this.name),document.getElementById("open-in-ar")?.removeEventListener("click",this.onClickedOpenInARElement),kc.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+="-"+Xx(),Yn()||(e!==""&&(e+="-"),e+="MadeWithNeedle"),this.link||(this.link=M1(this.context,I.supportsQuickLookAR())),this.customUsdzFile)return Tt&&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;Sa.beforeExport.invoke({exporter:this});const t=await this.export(this.objectToExport).finally(()=>{Sa.afterExport.invoke({exporter:this})});return t?(Tt&&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 \u2013 please report a bug!",n),null))):i}_currentExportTasks=new Map;_previousTimeScale=1;async internalExport(e){le.start("export-usdz",{onProgress:k=>{this.dispatchEvent(new CustomEvent("export-progress",{detail:{progress:k}}))}}),le.report("export-usdz",{message:"Starting export",totalSteps:40,currentStep:0}),le.report("export-usdz",{message:"Load progressive textures",autoStep:5}),le.start("export-usdz-textures","export-usdz");const t=S.getComponentsInChildren(e,yi);for(const k of t)k&&k.enabled&&k.updateSprite(!0);const i=S.getComponentsInChildren(e,ei),n=new Array;let s=0;for(const k of i){for(const O of k.sharedMeshes)if(O){let D=0;const L={exporter:this,type:"mesh",object:k.gameObject,mesh:O};if(Sa.beforeLODExport.invoke(L),L.overrideLevel!==void 0)if(L.overrideLevel===-1){Tt&&console.warn("Skipping LOD export for mesh due to overrideLevel -1",k.gameObject,O);continue}else L.overrideLevel>=0&&(D=L.overrideLevel,Tt&&console.log("Overriding LOD level for mesh export to level "+D+" "+O.name));const V=Ve.assignMeshLOD(O,D);V instanceof Promise&&n.push(new Promise((W,G)=>{V.then(()=>{s++,le.report("export-usdz-textures",{message:"Loaded progressive mesh",currentStep:s,totalSteps:n.length}),W()}).catch(X=>G(X))}))}for(const O of k.sharedMaterials)if(O){let D=0;const L={exporter:this,type:"texture",object:k.gameObject,material:O};if(Sa.beforeLODExport.invoke(L),L.overrideLevel!==void 0)if(L.overrideLevel===-1){Tt&&console.warn("Skipping LOD assignment due to overrideLevel -1",k.gameObject,O);continue}else L.overrideLevel>=0&&(D=L.overrideLevel,Tt&&console.log("Overriding LOD level for texture export to level "+D+" "+O.name));const V=Ve.assignTextureLOD(O,D);V instanceof Promise&&n.push(new Promise((W,G)=>{V.then(()=>{s++,le.report("export-usdz-textures",{message:"Loaded progressive texture",currentStep:s,totalSteps:n.length}),W()}).catch(X=>G(X))}))}}Tt&&Oe("Progressive Loading: "+n.length),await Promise.all(n),Tt&&Oe("Progressive Loading: done"),le.end("export-usdz-textures");const r=ri.Global.Mask;ri.Global.Set(io.AR);const a=new e1,l=new yp(this.quickLookCompatible);let c;const h=[];this.interactive&&(h.push(new $y),h.push(new Pa),globalThis.NEEDLE_USE_RAPIER&&S.getComponentsInChildren(e,Ke).length>0&&(this.physics?(c=new Hy,h.push(c)):A()&&console.warn("USDZExporter: Physics export is disabled, but there are active Rigidbody components in the scene. They will not be exported.")),h.push(new Op),h.push(new i0));const d=[l,...h,...this.extensions],p={self:this,exporter:a,extensions:d,object:e};le.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,le.report("export-usdz","auto export animations and audio sources");const m=new Array;this.autoExportAnimations&&m.push(...NA(e,l)),d.find(k=>k.extensionName==="Audio")&&this.autoExportAudioSources&&m.push(...WA(e)),a.debug=Tt,a.pruneUnusedNodes=!HA;const g=Oa.instance.objs.map(k=>k.batchedMesh);a.keepObject=k=>{let O=!0;const D=S.getComponent(k,ei);return D&&!D.enabled&&(O=!1),O&&g.includes(k)&&(O=!1),O&&S.getComponentInParent(k,nh)&&(O=!1),O&&S.getComponentInParent(k,Kn)&&(O=!1),Tt&&!O&&console.log("USDZExporter: Discarding object",k),O},a.beforeWritingDocument=()=>{if(A()&&l&&c){const k=l.animatedRoots;for(const O of k){const D=S.getComponentsInChildren(O,Ke).filter(V=>V.enabled),L=S.getComponents(O,nn).filter(V=>V.enabled&&!V.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.",O)}}};const f=new Array;this.objectToExport&&this.quickLookCompatible&&this.interactive&&this.objectToExport.traverse(k=>{k.visible||f.push(k)});const y=d.find(k=>k.extensionName==="Behaviour");this.interactive&&y&&f.length>0&&y.addBehavior(VA(f));let _=!0;this.quickLookCompatible&&!this.interactive&&(_=!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"),le.report("export-usdz","Invoking exporter.parse");const v=await a.parse(this.objectToExport,{ar:{anchoring:{type:this.anchoringType},planeAnchoring:{alignment:this.planeAnchoringAlignment}},extensions:d,quickLookCompatible:this.quickLookCompatible,maxTextureSize:this.maxTextureSize,exportInvisible:_}),P=new Blob([v],{type:"model/vnd.usdz+zip"});this.revertWebARSessionRoot(),this.context.time.timeScale=this._previousTimeScale,le.report("export-usdz","Invoking after-export"),this.dispatchEvent(new CustomEvent("after-export",{detail:p}));for(const k of m)S.destroy(k);return ri.Global.Set(r),le.end("export-usdz"),P}openInQuickLook(e,t){const i=e instanceof Blob?URL.createObjectURL(e):e,n=this.buildQuicklookOverlay();Tt&&console.log("QuickLook Overlay",n);const s=n.callToAction?encodeURIComponent(n.callToAction):"",r=n.checkoutTitle?encodeURIComponent(n.checkoutTitle):"",a=n.checkoutSubtitle?encodeURIComponent(n.checkoutSubtitle):"";this.link.href=i+`#callToAction=${s}&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){Sa.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"){Tt&&be("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");Tt&&Oe("Quicklook url: "+n),n&&(Yn()?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),Yn()||(console.log("Custom Quicklook banner text requires pro license: https://needle.tools/pricing"),e.callToAction="Close",e.checkoutTitle="\u{1F335} 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 J().makeRotationY(Math.PI);static invertForwardQuaternion=new N().setFromEuler(new at(0,Math.PI,0));_rootSessionRootWasAppliedTo=null;_rootPositionBeforeExport=new b;_rootRotationBeforeExport=new N;_rootScaleBeforeExport=new b;getARScaleAndTarget(){if(!this.objectToExport)return{scale:1,_invertForward:!1,target:this.gameObject,sessionRoot:null};const e=S.findObjectOfType(Sp);let t=S.getComponentInParent(this.objectToExport,yn);t||(t=S.getComponentInChildren(this.objectToExport,yn));let i=1,n=!1;const s=this.objectToExport;return e?i=e.arScale:t&&(i=t.arScale,n=t.invertForward),{scale:1/i,_invertForward:n,target:s,sessionRoot:t?.gameObject??null}}applyWebARSessionRoot(){if(!this.objectToExport)return;const{scale:e,_invertForward:t,target:i,sessionRoot:n}=this.getARScaleAndTarget(),s=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(Sa.invertForwardQuaternion),i.updateMatrix(),i.updateMatrixWorld(!0),n&&s&&i.matrix.premultiply(s)}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 e=ur.getOrCreate().createQuicklookButton();return e.parentNode||this.context.menu.appendChild(e),e}};Rt([u(M)],bi.prototype,"objectToExport"),Rt([u()],bi.prototype,"autoExportAnimations"),Rt([u()],bi.prototype,"autoExportAudioSources"),Rt([u()],bi.prototype,"exportFileName"),Rt([u(URL)],bi.prototype,"customUsdzFile"),Rt([u(oa)],bi.prototype,"customBranding"),Rt([u()],bi.prototype,"anchoringType"),Rt([u()],bi.prototype,"maxTextureSize"),Rt([u()],bi.prototype,"planeAnchoringAlignment"),Rt([u()],bi.prototype,"interactive"),Rt([u()],bi.prototype,"physics"),Rt([u()],bi.prototype,"allowCreateQuicklookButton"),Rt([u()],bi.prototype,"quickLookCompatible");let ho=bi;var GA=Object.defineProperty,qA=Object.getOwnPropertyDescriptor,n0=(o,e,t,i)=>{for(var n=qA(e,t),s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&GA(e,t,n),n};class Dl extends E{get fog(){return this._fog||(this._fog=new bb(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)}}n0([u()],Dl.prototype,"near"),n0([u()],Dl.prototype,"far"),n0([u(oe)],Dl.prototype,"color");var XA=Object.defineProperty,o0=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&XA(e,t,n),n};class sa extends E{objectBounds=!1;color;isGizmo=!0;_gizmoObject=null;_boxHelper=null;onEnable(){this.isGizmo&&!Dc||(this._gizmoObject||(this.objectBounds?this._gizmoObject=new VC(this.gameObject,this.color??16776960):(this.objectBounds=!1,this._gizmoObject=Fg(this.color??16776960))),this.objectBounds?(this.scene.add(this._gizmoObject),this._boxHelper=this._gizmoObject,this.startCoroutine(this.syncObjectBounds(),xe.OnBeforeRender)):this.gameObject.add(this._gizmoObject))}onDisable(){this._gizmoObject&&this.gameObject.remove(this._gizmoObject)}*syncObjectBounds(){for(;this._boxHelper;)this._boxHelper?.update(),yield}}o0([u()],sa.prototype,"objectBounds"),o0([u(oe)],sa.prototype,"color"),o0([u()],sa.prototype,"isGizmo");var QA=Object.defineProperty,s0=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&QA(e,t,n),n};class jl extends E{isGizmo=!1;color0;color1;gridHelper;size;divisions;offset;onEnable(){if(this.isGizmo&&!Dc)return;const e=this.size,t=this.divisions;this.gridHelper||(this.gridHelper=new gb(e,t,this.color0??new oe(.4,.4,.4),this.color1??new oe(.6,.6,.6)),this.offset!==void 0&&(this.gridHelper.position.y+=this.offset)),this.gridHelper&&this.gameObject.add(this.gridHelper)}onDisable(){this.gridHelper&&(this.gameObject.remove(this.gridHelper),this.gridHelper=null)}}s0([u()],jl.prototype,"isGizmo"),s0([u(oe)],jl.prototype,"color0"),s0([u(oe)],jl.prototype,"color1");var YA=Object.defineProperty,r0=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&YA(e,t,n),n};class a0 extends E{connectedBody;get rigidBody(){return this._rigidBody}_rigidBody=null;onEnable(){this._rigidBody||(this._rigidBody=this.gameObject.getComponent(Ke)),this.rigidBody&&this.connectedBody&&this.startCoroutine(this.create())}*create(){yield,this.rigidBody&&this.connectedBody&&this.activeAndEnabled&&this.createJoint(this.rigidBody,this.connectedBody)}}r0([u(Ke)],a0.prototype,"connectedBody");class l0 extends a0{createJoint(e,t){this.context.physics.engine?.addFixedJoint(e,t)}}class Sh extends a0{anchor;axis;createJoint(e,t){this.axis&&this.anchor&&this.context.physics.engine?.addHingeJoint(e,t,this.anchor,this.axis)}}r0([u(b)],Sh.prototype,"anchor"),r0([u(b)],Sh.prototype,"axis");var ZA=Object.defineProperty,KA=Object.getOwnPropertyDescriptor,Ui=(o,e,t,i)=>{for(var n=i>1?void 0:i?KA(e,t):e,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&ZA(e,t,n),n};function Bl(o){return o*Math.PI/180}const E1=300,Xs=w("debuglights");class At 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=Bl(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,i=1-Bl(e/2)/Bl(t/2);this.light.penumbra=i}}_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 oe(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),Xs&&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 oe(this.color??16777215),Xs&&console.log(this.name,this)}onEnable(){Xs&&console.log("ENABLE LIGHT",this.name),this.createLight(),!this.isBaked&&(this.light&&(this.light.visible=!0,this.light.intensity=this._intensity,Xs&&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(),xe.LateUpdate))}onDisable(){Xs&&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 Pm(this.color,this.intensity*Math.PI);if(t.position.set(0,0,-E1*.5).applyQuaternion(this.gameObject.quaternion),this.gameObject.add(t.target),Sr(t.target,0,0,0),this.light=t,this.gameObject.position.set(0,0,0),this.gameObject.rotation.set(0,0,0),Xs){const r=new HC(this.light,.2,this.color);this.context.scene.add(r)}break;case 0:const i=new $C(this.color,this.intensity*Math.PI,this.range,Bl(this.spotAngle/2),1-Bl(this.innerSpotAngle/2)/Bl(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 s=new Om(this.color,this.intensity*Math.PI,this.range);this.light=s;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),Xs&&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=E1*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,Xs&&this.context.scene.add(new GC(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)}}Ui([u()],At.prototype,"type",2),Ui([u()],At.prototype,"range",1),Ui([u()],At.prototype,"spotAngle",1),Ui([u()],At.prototype,"innerSpotAngle",1),Ui([u(oe)],At.prototype,"color",1),Ui([u()],At.prototype,"shadowNearPlane",1),Ui([u()],At.prototype,"shadowBias",1),Ui([u()],At.prototype,"shadowNormalBias",1),Ui([u()],At.prototype,"shadows",1),Ui([u()],At.prototype,"lightmapBakeType",2),Ui([u()],At.prototype,"intensity",1),Ui([u()],At.prototype,"shadowDistance",1),Ui([u()],At.prototype,"shadowResolution",1),new b(0,0,0);var JA=Object.defineProperty,kp=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&JA(e,t,n),n};const c0=w("debuglods"),e2=w("nolods");class Fl{screenRelativeTransitionHeight;distance;renderers}kp([u()],Fl.prototype,"screenRelativeTransitionHeight"),kp([u()],Fl.prototype,"distance"),kp([u(ei)],Fl.prototype,"renderers");class t2{model;get renderers(){return this.model.renderers}constructor(e){this.model=e}}class Mp extends E{lodModels=[];_lods=[];_settings=[];_lodsHandler;start(){if(c0&&console.log("LODGROUP",this.name,this.lodModels,this),!e2&&!this._lodsHandler&&this.gameObject&&this.lodModels&&Array.isArray(this.lodModels)){const e=[];for(const i of this.lodModels){const n=new t2(i);this._lods.push(n);for(const s of n.renderers)e.includes(s)||e.push(s)}this._lodsHandler=new Array;for(let i=0;i<e.length;i++){const n=new qC;this._lodsHandler.push(n),this.gameObject.add(n)}const t=new M;t.name="Cull "+this.name;for(let i=0;i<e.length;i++){const n=e[i],s=this._lodsHandler[i],r=n.gameObject;c0&&console.log(i,r.name);for(const a of this._lods){const l=a.model.distance;let c=null;if(a.renderers.includes(n)?c=r:c=t,c.type==="Group"){console.warn(`LODGroup ${this.name}: Group or MultiMaterial object's are not supported as LOD object: ${c.name}`);continue}c0&&console.log("LEVEL",c.name,l),s.autoUpdate=!1,this.onAddLodLevel(s,c,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}}}}kp([u(Fl)],Mp.prototype,"lodModels");var i2=Object.defineProperty,h0=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&i2(e,t,n),n};const Ep=w("debugnestedgltf");class Ul extends E{filePath;loaded=new ae;loadAssetInParent=!0;_isLoadingOrDoneLoading=!1;listenToProgress(e){this.filePath?.beginListenDownload(e)}preload(){return this.filePath?.preload()||null}async start(){if(this._isLoadingOrDoneLoading)return;Ep&&console.log(this,this.guid);const e=this.gameObject.parent;if(e&&this.filePath){this._isLoadingOrDoneLoading=!0;const t=new Nn;t.idProvider=new Bt(this.hash(this.guid)),t.parent=this.loadAssetInParent!==!1?e:this.gameObject,this.gameObject.updateMatrix();const i=this.gameObject.matrix;Ep&&console.log("Load nested:",this.filePath?.url??this.filePath,this.gameObject.position);const n=await this.filePath?.instantiate?.call(this.filePath,t);Ep&&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})),Ep&&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}}h0([u(ne)],Ul.prototype,"filePath"),h0([u(ae)],Ul.prototype,"loaded"),h0([u()],Ul.prototype,"loadAssetInParent");var n2=Object.defineProperty,d0=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&n2(e,t,n),n};const o2=w("debugnet"),Rp=class db extends E{url=null;urlParameterName=null;localhost=null;awake(){o2&&console.log(this),this.context.connection.registerProvider(this)}getWebsocketUrl(){let e=this.url?db.GetUrl(this.url,this.localhost):null;if(this.urlParameterName){const i=w(this.urlParameterName);i&&typeof i=="string"&&(e=i)}if(!e)return null;const t=new RegExp("(((https?)|(?<socket_prefix>wss?))://)?(www.)?(?<url>.+)","gm").exec(e);return t?.groups?t?.groups.socket_prefix?e:"wss://"+t?.groups.url:null}static GetUrl(e,t){let i=e;const n=db.IsLocalNetwork()&&t;if(n&&(i=t),e?.startsWith("/")){const s=n?i:window.location.origin;s?.endsWith("/")&&e.startsWith("/")&&(e=e.substring(1)),i=s+e}return i}static IsLocalNetwork(e=window.location.hostname){return ki(e)}};d0([u()],Rp.prototype,"url"),d0([u()],Rp.prototype,"urlParameterName"),d0([u()],Rp.prototype,"localhost");let u0=Rp;var s2=Object.defineProperty,Tp=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&s2(e,t,n),n};class ra extends E{referenceSpace;from;affectPosition=!1;affectRotation=!1;alignLookDirection=!1;levelLookDirection=!1;levelPosition=!1;positionOffset=new b(0,0,0);rotationOffset=new b(0,0,0);offset=new b(0,0,0);update(){if(!this.from)return;var e=ee(this.from),t=_e(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 _r(this.gameObject.up,0),l=ee(this.referenceSpace);a.setFromNormalAndCoplanarPoint(this.gameObject.up,l);const c=new b(0,0,0);a.projectPoint(e,c),e.copy(c)}this.affectPosition&&yt(this.gameObject,e);const n=new at(this.rotationOffset.x,this.rotationOffset.y,this.rotationOffset.z),s=new N().setFromEuler(n);this.affectRotation&&Sn(this.gameObject,t.multiply(s));const r=new b;this.from.getWorldDirection(r).multiplyScalar(50),this.levelLookDirection&&(r.y=0),this.alignLookDirection&&this.gameObject.lookAt(r)}}Tp([u(S)],ra.prototype,"referenceSpace"),Tp([u(S)],ra.prototype,"from"),Tp([u(b)],ra.prototype,"positionOffset"),Tp([u(b)],ra.prototype,"rotationOffset");var r2=Object.defineProperty,Qs=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&r2(e,t,n),n};class _i{time=0;value=0;inTangent=1/0;inWeight;outTangent=1/0;outWeight;weightedMode;constructor(e=0,t=0){this.time=e,this.value=t}}Qs([u()],_i.prototype,"time"),Qs([u()],_i.prototype,"value"),Qs([u()],_i.prototype,"inTangent"),Qs([u()],_i.prototype,"inWeight"),Qs([u()],_i.prototype,"outTangent"),Qs([u()],_i.prototype,"outWeight"),Qs([u()],_i.prototype,"weightedMode");const R1=class yd{static linearFromTo(e,t,i){const n=new yd,s=new _i;s.time=0,s.value=e;const r=new _i;return r.time=i,r.value=t,n.keys.push(s,r),n}static constant(e){const t=new yd,i=new _i;return i.time=0,i.value=e,t.keys.push(i),t}keys=[];clone(){const e=new yd;return e.keys=this.keys?.map(t=>{const i=new _i;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 n=this.keys[t+1];if(n.time<e)continue;return!isFinite(i.outTangent)||!isFinite(n.inTangent)?i.value:yd.interpolateValue(e,i,n)}else return i.value}return this.keys[this.keys.length-1].value}static interpolateValue(e,t,i){const n=t.time,s=t.value,r=t.outTangent,a=i.time,l=i.value,c=i.inTangent,h=a-n,d=h*h,p=d*h,m=((r+c)*h-2*(l-s))/p,g=(3*(l-s)-(c+2*r)*h)/d,f=r,y=s,_=e-n,v=_*_,P=v*_;return m*P+g*v+f*_+y}};Qs([u(_i)],R1.prototype,"keys");let Ch=R1;var a2=Object.defineProperty,x=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&a2(e,t,n),n};const Ap=w("debugparticles");var Jo=(o=>(o[o.Billboard=0]="Billboard",o[o.Stretch=1]="Stretch",o[o.HorizontalBillboard=2]="HorizontalBillboard",o[o.VerticalBillboard=3]="VerticalBillboard",o[o.Mesh=4]="Mesh",o))(Jo||{});class aa{alphaKeys=[];colorKeys=[];get duration(){return 1}evaluate(e,t){let i,n=0,s=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||!s)&&(s=l,r=a)}if(s)if(r+1<this.colorKeys.length){const a=this.colorKeys[r+1],l=j.remap(e,s.time,a.time,0,1);t.r=j.lerp(s.color.r,a.color.r,l),t.g=j.lerp(s.color.g,a.color.g,l),t.b=j.lerp(s.color.b,a.color.b,l)}else t.r=s.color.r,t.g=s.color.g,t.b=s.color.b;if(i)if(n+1<this.alphaKeys.length){const a=this.alphaKeys[n+1],l=j.remap(e,i.time,a.time,0,1);t.alpha=j.lerp(i.alpha,a.alpha,l)}else t.alpha=i.alpha;return t}}x([u()],aa.prototype,"alphaKeys"),x([u()],aa.prototype,"colorKeys");var Ph=(o=>(o[o.Local=0]="Local",o[o.World=1]="World",o[o.Custom=2]="Custom",o))(Ph||{}),Ip=(o=>(o[o.Sphere=0]="Sphere",o[o.SphereShell=1]="SphereShell",o[o.Hemisphere=2]="Hemisphere",o[o.HemisphereShell=3]="HemisphereShell",o[o.Cone=4]="Cone",o[o.Box=5]="Box",o[o.Mesh=6]="Mesh",o[o.ConeShell=7]="ConeShell",o[o.ConeVolume=8]="ConeVolume",o[o.ConeVolumeShell=9]="ConeVolumeShell",o[o.Circle=10]="Circle",o[o.CircleEdge=11]="CircleEdge",o[o.SingleSidedEdge=12]="SingleSidedEdge",o[o.MeshRenderer=13]="MeshRenderer",o[o.SkinnedMeshRenderer=14]="SkinnedMeshRenderer",o[o.BoxShell=15]="BoxShell",o[o.BoxEdge=16]="BoxEdge",o[o.Donut=17]="Donut",o[o.Rectangle=18]="Rectangle",o[o.Sprite=19]="Sprite",o[o.SpriteRenderer=20]="SpriteRenderer",o))(Ip||{});const es=class bd{static constant(e){const t=new bd;return t.setConstant(e),t}static betweenTwoConstants(e,t){const i=new bd;return i.setMinMaxConstant(e,t),i}static curve(e,t=1){const i=new bd;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 bd;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=j.clamp01(e),this.curve.evaluate(e)*this.curveMultiplier;case 2:case"TwoCurves":const n=e*this.curveMin.duration,s=e*this.curveMax.duration;return j.lerp(this.curveMin.evaluate(n),this.curveMax.evaluate(s),i%1)*this.curveMultiplier;case 3:case"TwoConstants":return j.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}};x([u()],es.prototype,"mode"),x([u()],es.prototype,"constant"),x([u()],es.prototype,"constantMin"),x([u()],es.prototype,"constantMax"),x([u(Ch)],es.prototype,"curve"),x([u(Ch)],es.prototype,"curveMin"),x([u(Ch)],es.prototype,"curveMax"),x([u()],es.prototype,"curveMultiplier");let Y=es;const Ys=class Dt{static constant(e){const t=new Dt;return t.constant(e),t}static betweenTwoColors(e,t){const i=new Dt;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 se(0,0,0,1);static _temp2=new se(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,Dt._temp),Dt._temp;case 2:case"TwoColors":return Dt._temp.lerpColors(this.colorMin,this.colorMax,i);case 3:case"TwoGradients":return this.gradientMin.evaluate(e,Dt._temp),this.gradientMax.evaluate(e,Dt._temp2),Dt._temp.lerp(Dt._temp2,i);case 4:case"RandomColor":const n=Math.random();return this.gradientMin.evaluate(e,Dt._temp),this.gradientMax.evaluate(e,Dt._temp2),Dt._temp.lerp(Dt._temp2,n)}return Dt._temp.set(16777215),Dt._temp.alpha=1,Dt._temp}};x([u()],Ys.prototype,"mode"),x([u(se)],Ys.prototype,"color"),x([u(se)],Ys.prototype,"colorMin"),x([u(se)],Ys.prototype,"colorMax"),x([u(aa)],Ys.prototype,"gradient"),x([u(aa)],Ys.prototype,"gradientMin"),x([u(aa)],Ys.prototype,"gradientMax");let la=Ys;var p0=(o=>(o[o.Hierarchy=0]="Hierarchy",o[o.Local=1]="Local",o[o.Shape=2]="Shape",o))(p0||{});class Gt{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}x([u(Y)],Gt.prototype,"gravityModifier"),x([u(la)],Gt.prototype,"startColor"),x([u(Y)],Gt.prototype,"startDelay"),x([u(Y)],Gt.prototype,"startLifetime"),x([u(Y)],Gt.prototype,"startRotation"),x([u(Y)],Gt.prototype,"startRotationX"),x([u(Y)],Gt.prototype,"startRotationY"),x([u(Y)],Gt.prototype,"startRotationZ"),x([u(Y)],Gt.prototype,"startSize"),x([u(Y)],Gt.prototype,"startSizeX"),x([u(Y)],Gt.prototype,"startSizeY"),x([u(Y)],Gt.prototype,"startSizeZ"),x([u(Y)],Gt.prototype,"startSpeed");class Lp{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=j.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=j.lerp(this.count.curveMin.evaluate(n),this.count.curveMax.evaluate(n),Math.random());break}}return t}}class ts{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}}x([u()],ts.prototype,"enabled"),x([u()],ts.prototype,"bursts"),x([u(Y)],ts.prototype,"rateOverTime"),x([u()],ts.prototype,"rateOverTimeMultiplier"),x([u(Y)],ts.prototype,"rateOverDistance"),x([u()],ts.prototype,"rateOverDistanceMultiplier");class Dp{enabled;color}x([u(la)],Dp.prototype,"color");class ca{enabled;separateAxes;size;sizeMultiplier;x;xMultiplier;y;yMultiplier;z;zMultiplier;_time=0;_temp=new b;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}}x([u(Y)],ca.prototype,"size"),x([u(Y)],ca.prototype,"x"),x([u(Y)],ca.prototype,"y"),x([u(Y)],ca.prototype,"z");const tt=class _d{get type(){return Ip[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 _d}shapeType=5;enabled=!0;alignToDirection=!1;angle=0;arc=360;arcSpread;arcSpeedMultiplier;arcMode;boxThickness;position;rotation;_rotation=new at;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 J;_worldSpaceMatrixInverse=new J;constructor(){Ap&&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=j.toRadians(this.rotation.x),this._rotation.y=j.toRadians(this.rotation.y),this._rotation.z=j.toRadians(this.rotation.z),this._rotation.order="ZYX",e.applyEuler(this._rotation)),t}_vector=new b(0,0,0);_temp=new b(0,0,0);_triangle=new XC;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:Ap&&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 s=this.meshRenderer;s?.destroyed==!1&&this.setMesh(s);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"),c=Math.floor(Math.random()*l.count);this._vector.fromBufferAttribute(l,c),this._vector.applyMatrix4(r.matrixWorld),e.mesh_normal=c}break;case 1:break;case 2:{const l=a.index;if(l){let c=Math.random(),h=Math.random();c+h>1&&(c=1-c,h=1-h);const d=Math.floor(Math.random()*(l.count/3));let p=d*3,m=d*3+1,g=d*3+2;p=l.getX(p),m=l.getX(m),g=l.getX(g);const f=a.getAttribute("position");this._triangle.a.fromBufferAttribute(f,p),this._triangle.b.fromBufferAttribute(f,m),this._triangle.c.fromBufferAttribute(f,g),this._vector.set(0,0,0).addScaledVector(this._triangle.a,c).addScaledVector(this._triangle.b,h).addScaledVector(this._triangle.c,1-(c+h)),this._vector.applyMatrix4(r.matrixWorld),e.mesh_normal=d}}break}break;default:this._vector.set(0,0,0),A()&&!globalThis.__particlesystem_shapetype_unsupported&&(console.warn("ParticleSystem ShapeType is not supported:",Ip[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)),Ap&&B.DrawSphere(this._vector,.03,16711680,.5,!0)}_dir=new b;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,s=t.z;this._dir.set(i,n,s),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"),c=e.mesh_normal;this._dir.fromBufferAttribute(l,c)}break;case 1:break;case 2:{const l=a.index;if(l){const c=e.mesh_normal,h=l.getX(c*3),d=l.getX(c*3+1),p=l.getX(c*3+2),m=a.getAttribute("position"),g=F(),f=F(),y=F();g.fromBufferAttribute(m,h),f.fromBufferAttribute(m,d),y.fromBufferAttribute(m,p),g.sub(f),y.sub(f),g.cross(y),this._dir.copy(g).multiplyScalar(-1);const _=_e(r);this._dir.applyQuaternion(_)}}break}break;default:this._dir.set(0,0,1);break}return this._space===1&&this._dir.applyQuaternion(this.system.worldQuaternion),this.applyRotation(this._dir),this._dir.normalize(),this.spherizeDirection(this._dir,this.sphericalDirectionAmount),this.randomizeDirection(this._dir,this.randomDirectionAmount),Ap&&(B.DrawSphere(t,.01,8925952,.5,!0),B.DrawDirection(t,this._dir,8925952,.5,!0)),this._dir}static _randomQuat=new N;static _tempVec=new b;randomizePosition(e,t){if(t<=0)return;const i=_d._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=_d._randomQuat,n=_d._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),s=Math.sin(n)*Math.cos(i),r=Math.sin(n)*Math.sin(i),a=Math.cos(n),l=new b(s,r,a);e.lerp(l,t)}randomSpherePoint(e,t,i,n,s){const r=Math.random(),a=Math.random(),l=2*Math.PI*r*(n/360),c=Math.acos(2*a-1),h=j.lerp(1,1-Math.pow(1-Math.random(),Math.PI),i)*t,d=e.x+this.scale.x*(-h*Math.sin(c)*Math.cos(l)),p=e.y+this.scale.y*(h*Math.sin(c)*Math.sin(l)),m=e.z+this.scale.z*(h*Math.cos(c));s.x=d,s.y=p,s.z=m}randomCirclePoint(e,t,i,n,s){const r=Math.random(),a=2*Math.PI*r*(n/360),l=j.lerp(1,1-Math.pow(1-Math.random(),Math.PI),i)*t,c=e.x+this.scale.x*l*Math.cos(a),h=e.y+this.scale.y*l*Math.sin(a),d=e.z;s.x=c,s.y=h,s.z=d}_loopTime=0;_loopDirection=1;randomConePoint(e,t,i,n,s,r,a){let l=0,c=0;switch(r){case 0:l=Math.random(),c=Math.random();break;case 2:this._loopTime>1&&(this._loopDirection=-1),this._loopTime<0&&(this._loopDirection=1);case 1:l=.5,c=Math.random(),this._loopTime+=this.system.deltaTime*this._loopDirection;break}let h=2*Math.PI*l*(s/360);switch(r){case 2:case 1:h+=Math.PI+.5,h+=this._loopTime*Math.PI*2,h%=j.toRadians(s);break}const d=Math.acos(2*c-1),p=j.lerp(1,1-Math.pow(1-Math.random(),Math.PI),n)*i,m=e.x+-p*Math.sin(d)*Math.cos(h),g=e.y+p*Math.sin(d)*Math.sin(h),f=e.z;a.x=m*this.scale.x,a.y=g*this.scale.y,a.z=f*this.scale.z}};x([u()],tt.prototype,"shapeType"),x([u()],tt.prototype,"enabled"),x([u()],tt.prototype,"alignToDirection"),x([u()],tt.prototype,"angle"),x([u()],tt.prototype,"arc"),x([u()],tt.prototype,"arcSpread"),x([u()],tt.prototype,"arcSpeedMultiplier"),x([u()],tt.prototype,"arcMode"),x([u(b)],tt.prototype,"boxThickness"),x([u(b)],tt.prototype,"position"),x([u(b)],tt.prototype,"rotation"),x([u(b)],tt.prototype,"scale"),x([u()],tt.prototype,"radius"),x([u()],tt.prototype,"radiusThickness"),x([u()],tt.prototype,"sphericalDirectionAmount"),x([u()],tt.prototype,"randomDirectionAmount"),x([u()],tt.prototype,"randomPositionAmount"),x([u()],tt.prototype,"meshShapeType"),x([u(ah)],tt.prototype,"meshRenderer");let m0=tt;class ve{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 b;apply(e,t,i,n,s,r){if(!this.enabled)return;this._noise||(this._noise=AP(()=>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),c=this._noise(a.x,a.y,a.z,this._time+1e3*this.frequency),h=this._noise(a.x,a.y,a.z,this._time+2e3*this.frequency);this._temp.set(l,c,h).normalize();const d=s/r;let p=this.positionAmount.evaluate(d);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(d)*1.5),this._temp.multiplyScalar(p)),i.x+=this._temp.x,i.y+=this._temp.y,i.z+=this._temp.z}}x([u()],ve.prototype,"damping"),x([u()],ve.prototype,"enabled"),x([u()],ve.prototype,"frequency"),x([u()],ve.prototype,"octaveCount"),x([u()],ve.prototype,"octaveMultiplier"),x([u()],ve.prototype,"octaveScale"),x([u(Y)],ve.prototype,"positionAmount"),x([u()],ve.prototype,"quality"),x([u(Y)],ve.prototype,"remap"),x([u()],ve.prototype,"remapEnabled"),x([u()],ve.prototype,"remapMultiplier"),x([u(Y)],ve.prototype,"remapX"),x([u()],ve.prototype,"remapXMultiplier"),x([u(Y)],ve.prototype,"remapY"),x([u()],ve.prototype,"remapYMultiplier"),x([u(Y)],ve.prototype,"remapZ"),x([u()],ve.prototype,"remapZMultiplier"),x([u()],ve.prototype,"scrollSpeedMultiplier"),x([u()],ve.prototype,"separateAxes"),x([u()],ve.prototype,"strengthMultiplier"),x([u(Y)],ve.prototype,"strengthX"),x([u()],ve.prototype,"strengthXMultiplier"),x([u(Y)],ve.prototype,"strengthY"),x([u()],ve.prototype,"strengthYMultiplier"),x([u(Y)],ve.prototype,"strengthZ"),x([u()],ve.prototype,"strengthZMultiplier");class Fe{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 s=this.widthOverTrail.evaluate(i,n);return e*=s,e}getColor(e,t,i){const n=this.colorOverTrail.evaluate(i),s=this.colorOverLifetime.evaluate(t);e.x*=n.r*s.r,e.y*=n.g*s.g,e.z*=n.b*s.b,"alpha"in n&&"alpha"in s&&(e.w*=n.alpha*s.alpha)}}x([u()],Fe.prototype,"enabled"),x([u()],Fe.prototype,"attachRibbonToTransform"),x([u(la)],Fe.prototype,"colorOverLifetime"),x([u(la)],Fe.prototype,"colorOverTrail"),x([u()],Fe.prototype,"dieWithParticles"),x([u()],Fe.prototype,"inheritParticleColor"),x([u(Y)],Fe.prototype,"lifetime"),x([u()],Fe.prototype,"lifetimeMultiplier"),x([u()],Fe.prototype,"minVertexDistance"),x([u()],Fe.prototype,"mode"),x([u()],Fe.prototype,"ratio"),x([u()],Fe.prototype,"ribbonCount"),x([u()],Fe.prototype,"shadowBias"),x([u()],Fe.prototype,"sizeAffectsLifetime"),x([u()],Fe.prototype,"sizeAffectsWidth"),x([u()],Fe.prototype,"splitSubEmitterRibbons"),x([u()],Fe.prototype,"textureMode"),x([u(Y)],Fe.prototype,"widthOverTrail"),x([u()],Fe.prototype,"widthOverTrailMultiplier"),x([u()],Fe.prototype,"worldSpace");class He{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 b;_temp2=new b;_temp3=new b;_hasOrbital=!1;_index=0;_orbitalMatrix=new J;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,s,r,a){if(!this.enabled)return;const l=r/a,c=this.speedModifier.evaluate(l)*this.speedModifierMultiplier,h=this.x.evaluate(l),d=this.y.evaluate(l),p=this.z.evaluate(l);if(this._temp.set(-h,d,p),this._system&&this._system.main.simulationSpace===1&&this._temp.applyQuaternion(this._system.worldQuaternion),this._hasOrbital&&this._system?.worldPos){const m=this._temp2.set(i.x,i.y,i.z),g=this.orbitalXMultiplier,f=this.orbitalYMultiplier,y=this.orbitalZMultiplier,_=c*Math.PI*2*10,v=Math.cos(_*g),P=Math.sin(_*g),k=Math.cos(_*f),O=Math.sin(_*f),D=Math.cos(_*y),L=Math.sin(_*y),V=m.x*(k*D)+m.y*(k*L)+m.z*-O,W=m.x*(P*O*D-v*L)+m.y*(P*O*L+v*D)+m.z*(P*k),G=m.x*(v*O*D+P*L)+m.y*(v*O*L-P*D)+m.z*(v*k),X=this._temp3.set(m.x-V,m.y-W,m.z-G);X.normalize(),X.multiplyScalar(.2/s*Math.max(this.orbitalXMultiplier,this.orbitalYMultiplier,this.orbitalZMultiplier)),n.x+=X.x,n.y+=X.y,n.z+=X.z}n.x+=this._temp.x,n.y+=this._temp.y,n.z+=this._temp.z,n.x*=c,n.y*=c,n.z*=c}}x([u()],He.prototype,"enabled"),x([u()],He.prototype,"space"),x([u(Y)],He.prototype,"orbitalX"),x([u(Y)],He.prototype,"orbitalY"),x([u(Y)],He.prototype,"orbitalZ"),x([u()],He.prototype,"orbitalXMultiplier"),x([u()],He.prototype,"orbitalYMultiplier"),x([u()],He.prototype,"orbitalZMultiplier"),x([u()],He.prototype,"orbitalOffsetX"),x([u()],He.prototype,"orbitalOffsetY"),x([u()],He.prototype,"orbitalOffsetZ"),x([u(Y)],He.prototype,"speedModifier"),x([u()],He.prototype,"speedModifierMultiplier"),x([u(Y)],He.prototype,"x"),x([u()],He.prototype,"xMultiplier"),x([u(Y)],He.prototype,"y"),x([u()],He.prototype,"yMultiplier"),x([u(Y)],He.prototype,"z"),x([u()],He.prototype,"zMultiplier");class qt{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}}x([u()],qt.prototype,"animation"),x([u()],qt.prototype,"enabled"),x([u()],qt.prototype,"cycleCount"),x([u(Y)],qt.prototype,"frameOverTime"),x([u()],qt.prototype,"frameOverTimeMultiplier"),x([u()],qt.prototype,"numTilesX"),x([u()],qt.prototype,"numTilesY"),x([u(Y)],qt.prototype,"startFrame"),x([u()],qt.prototype,"startFrameMultiplier"),x([u()],qt.prototype,"rowMode"),x([u()],qt.prototype,"rowIndex"),x([u()],qt.prototype,"spriteCount"),x([u()],qt.prototype,"timeMode");class Dn{enabled;separateAxes;x;xMultiplier;y;yMultiplier;z;zMultiplier;evaluate(e,t){return this.enabled?this.separateAxes?0:this.z.evaluate(e,t)*-1:0}}x([u()],Dn.prototype,"enabled"),x([u()],Dn.prototype,"separateAxes"),x([u(Y)],Dn.prototype,"x"),x([u()],Dn.prototype,"xMultiplier"),x([u(Y)],Dn.prototype,"y"),x([u()],Dn.prototype,"yMultiplier"),x([u(Y)],Dn.prototype,"z"),x([u()],Dn.prototype,"zMultiplier");class an{enabled;range;separateAxes;x;xMultiplier;y;yMultiplier;z;zMultiplier;evaluate(e,t){if(!this.enabled)return 0;if(!this.separateAxes){const i=j.lerp(this.range.x,this.range.y,t);return this.z.evaluate(i)*-1}return 0}}x([u()],an.prototype,"enabled"),x([u()],an.prototype,"range"),x([u()],an.prototype,"separateAxes"),x([u(Y)],an.prototype,"x"),x([u()],an.prototype,"xMultiplier"),x([u(Y)],an.prototype,"y"),x([u()],an.prototype,"yMultiplier"),x([u(Y)],an.prototype,"z"),x([u()],an.prototype,"zMultiplier");class dt{enabled;dampen;drag;dragMultiplier;limit;limitMultiplier;separateAxes;limitX;limitXMultiplier;limitY;limitYMultiplier;limitZ;limitZMultiplier;multiplyDragByParticleSize=!1;multiplyDragByParticleVelocity=!1;space;_temp=new b;_temp2=new b;apply(e,t,i,n,s,r,a){if(this.enabled){const l=this.limit.evaluate(s)*this.limitMultiplier;if(t.length()>l){this._temp.copy(t).normalize().multiplyScalar(l);const c=this.dampen*.5;t.x=j.lerp(t.x,this._temp.x,c),t.y=j.lerp(t.y,this._temp.y,c),t.z=j.lerp(t.z,this._temp.z,c),i.x=j.lerp(i.x,this._temp.x,c),i.y=j.lerp(i.y,this._temp.y,c),i.z=j.lerp(i.z,this._temp.z,c)}}}}x([u()],dt.prototype,"enabled"),x([u()],dt.prototype,"dampen"),x([u(Y)],dt.prototype,"drag"),x([u()],dt.prototype,"dragMultiplier"),x([u(Y)],dt.prototype,"limit"),x([u()],dt.prototype,"limitMultiplier"),x([u()],dt.prototype,"separateAxes"),x([u(Y)],dt.prototype,"limitX"),x([u()],dt.prototype,"limitXMultiplier"),x([u(Y)],dt.prototype,"limitY"),x([u()],dt.prototype,"limitYMultiplier"),x([u(Y)],dt.prototype,"limitZ"),x([u()],dt.prototype,"limitZMultiplier"),x([u()],dt.prototype,"multiplyDragByParticleSize"),x([u()],dt.prototype,"multiplyDragByParticleVelocity"),x([u()],dt.prototype,"space");const Oh=class NS{enabled;curve;curveMultiplier;mode;clone(){const e=new NS;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 b),this.system._iv_lastWorldPosition}get _velocity(){return this.system._iv_velocity||(this.system._iv_velocity=new b),this.system._iv_velocity}_temp=new b;_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}}};x([u()],Oh.prototype,"enabled"),x([u(Y)],Oh.prototype,"curve"),x([u()],Oh.prototype,"curveMultiplier"),x([u()],Oh.prototype,"mode");let g0=Oh;class vi{enabled;range;separateAxes;size;sizeMultiplier;x;xMultiplier;y;yMultiplier;z;zMultiplier;evaluate(e,t,i,n){const s=e.length(),r=j.remap(s,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}}x([u()],vi.prototype,"enabled"),x([u(K)],vi.prototype,"range"),x([u()],vi.prototype,"separateAxes"),x([u(Y)],vi.prototype,"size"),x([u()],vi.prototype,"sizeMultiplier"),x([u(Y)],vi.prototype,"x"),x([u()],vi.prototype,"xMultiplier"),x([u(Y)],vi.prototype,"y"),x([u()],vi.prototype,"yMultiplier"),x([u(Y)],vi.prototype,"z"),x([u()],vi.prototype,"zMultiplier");class zl{enabled;range;color;evaluate(e,t,i){const n=e.length(),s=j.remap(n,this.range.x,this.range.y,0,1),r=this.color.evaluate(s,t);i.x*=r.r,i.y*=r.g,i.z*=r.b,"alpha"in r&&(i.w*=r.alpha)}}x([u()],zl.prototype,"enabled"),x([u(K)],zl.prototype,"range"),x([u(la)],zl.prototype,"color"),new b(1,1,1),new b(0,0,1);class f0{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 s=1e3;this._circularBuffer=new Mi(()=>new Nm,s)}type="NeedleParticleSubEmitter";emitterType;emitterProbability;q_=new N;v_=new b;v2_=new b;_emitterMatrix=new Nm;_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===y0.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===y0.Death){let n=e.life;if(e[Nl]!==void 0&&(n=e[Nl]),!(e.age+t*1.2>=n))return;const s=this.subSystem.main.maxParticles-this.subSystem.currentParticles;e.emissionState.waitEmiting=s}const i=new Nm;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 l2=Object.defineProperty,Ue=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&l2(e,t,n),n};const Zs=w("debugparticles"),c2=w("noprogressive"),h2=w("debugprogressive");var y0=(o=>(o[o.Birth=0]="Birth",o[o.Collision=1]="Collision",o[o.Death=2]="Death",o[o.Trigger=3]="Trigger",o[o.Manual=4]="Manual",o))(y0||{});class ln 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"){Zs&&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=Po,t.map.premultiplyAlpha=!1);const i=new Ce;i.copy(t),e?this.trailMaterial=i:this.particleMaterial=i}t.map&&(t.map.colorSpace=Po,t.map.premultiplyAlpha=!1),e&&t.side===vs&&(t=t.clone(),t.side=Id,e?this.trailMaterial=t:this.particleMaterial=t)}return t&&!c2&&t._didRequestTextureLOD===void 0&&(t._didRequestTextureLOD=0,h2&&console.log("Load material LOD",t.name),Ve.assignTextureLOD(t,0)),t}getMesh(e){let t=null;if(!t&&(this.particleMesh instanceof H&&(t=this.particleMesh.geometry),t===null)){t=new vn(1,1);const i=t.attributes.uv;for(let n=0;n<i.count;n++)i.setX(n,1-i.getX(n))}return new H(t,this.getMaterial())}}Ue([u()],ln.prototype,"renderMode"),Ue([u(we)],ln.prototype,"particleMaterial"),Ue([u(we)],ln.prototype,"trailMaterial"),Ue([u()],ln.prototype,"maxParticleSize"),Ue([u()],ln.prototype,"minParticleSize"),Ue([u()],ln.prototype,"velocityScale"),Ue([u()],ln.prototype,"cameraVelocityScale"),Ue([u()],ln.prototype,"lengthScale");class jp{_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 b0{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 d2 extends b0{genValue(){return this.system.textureSheetAnimation.getStartIndex()}}class u2 extends b0{_lastPosition=new b;_lastDistance=0;update(){const e=ee(this.system.gameObject);this._lastDistance=this._lastPosition.distanceTo(e),this._lastPosition.copy(e)}genValue(){if(!this.system.isPlaying||!this.system.emission.enabled||this.system.currentParticles>=this.system.maxParticles)return 0;let e=this.system.emission.rateOverTime.evaluate(this.system.time/this.system.duration,Math.random());if(this.system.deltaTime>0){const n=this.system.emission.rateOverDistance.evaluate(this.system.time/this.system.duration,Math.random());let s=this._lastDistance/this.system.deltaTime*n;Number.isFinite(s)||(s=0),e+=s}const t=this.system.emission.getBurst();t>0&&(e+=t/this.system.deltaTime);const i=this.system.maxParticles-this.system.currentParticles;return j.clamp(e,0,i/this.system.deltaTime)}}class p2 extends b0{genValue(){return this.system.isPlaying,0}}class Ks{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 m2 extends Ks{type="NeedleTextureSheet";update(e,t){const i=this.system.textureSheetAnimation;if(i.enabled){const n=e.age/e.life,s=i.evaluate(n);s!==void 0&&(e.uvTile=s)}}}const T1=Symbol("particleRotation");class g2 extends Ks{type="NeedleRotation";initialize(e){e[T1]=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[T1])*t:this.system.renderer.renderMode===Jo.Billboard&&(e.rotation=Math.PI),this.system.rotationBySpeed.enabled)){const n=e.velocity.length();e.rotation+=this.system.rotationBySpeed.evaluate(i,n)*t}}}const A1=Symbol("sizeLerpFactor"),f2=new b;class y2 extends Ks{type="NeedleSize";_minSize=0;_maxSize=1;initialize(e){e[A1]=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[A1]).x);let s=1;this.system.renderer.renderMode!==Jo.Mesh&&(s=this.system.worldScale.x/this.system.cameraScale);const r=F(e.startSize).multiplyScalar(n*s);if(e.size.set(r.x,r.y,r.z),this.system.localspace){const a=B1(this.system,f2);e.size.x*=a.x,e.size.y*=a.y,e.size.z*=a.z}}}const Nl=Symbol("particleLife"),_0=Symbol("trailLifetime"),I1=Symbol("trailStartLength"),v0=Symbol("trailWidthRandom");class b2 extends Ks{type="NeedleTrail";initialize(e){e instanceof Vb&&(e[Nl]=e.life,this.system.trails.enabled&&this.system.trails.dieWithParticles===!1&&(e[_0]=this.system.trails.lifetime.evaluate(Math.random(),Math.random()),e.life+=e[_0]),e[I1]=e.length,e[v0]=Math.random())}update(e){if(this.system.trails?.enabled&&e instanceof Vb){const t=e,i=e.age/e[Nl],n=e.previous.values(),s=e.previous.length;for(let r=0;r<s;r++){const a=n.next().value,l=1-r/(s-1),c=e.size;if(c.x<=0&&!this.system.trails.sizeAffectsWidth){const h=20*this.system.trails.widthOverTrail.evaluate(.5,t[v0]);c.x=h,c.y=h,c.z=h}a.size=this.system.trails.getWidth(c.x,i,l,t[v0]),a.color.copy(e.color),this.system.trails.getColor(a.color,i,l)}if(e.age>e[Nl]){e.velocity.set(0,0,0);const r=(e.age-e[Nl])/e[_0];t.length=j.lerp(e[I1],0,r)}}}}const Bp=Symbol("startVelocity"),L1=Symbol("gravityModifier"),w0=Symbol("gravitySpeed"),Fp=Symbol("velocity lerp factor"),x0=new b;class _2 extends Ks{type="NeedleVelocity";_gravityDirection=new b;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[Bp]?e[Bp].copy(e.velocity):e[Bp]=e.velocity.clone();const n=this.system.main.gravityModifier.evaluate(Math.random(),Math.random());e[L1]=n*t,e[w0]=n*t*.5,e[Fp]=Math.random(),this.system.velocityOverLifetime?.init(e),this._gravityDirection.set(0,-1,0),this.system.main.simulationSpace===Ph.Local&&this._gravityDirection.applyQuaternion(this.system.worldQuaternionInverted).normalize()}update(e,t){const i=e[Bp],n=e[L1];if(n!==0){const d=n*e[w0];x0.copy(this._gravityDirection).multiplyScalar(d),e[w0]+=t*.05,i.add(x0)}e.velocity.copy(i);const s=e.age/e.life;this.system.inheritVelocity?.enabled&&this.system.inheritVelocity.applyCurrent(e.velocity,s,e[Fp]);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,s,e[Fp],e.size));const l=this.system.colorBySpeed;l?.enabled&&l.evaluate(e.velocity,e[Fp],e.color);const c=this.system.velocityOverLifetime;c.enabled&&c.apply(e,0,e.position,e.velocity,t,e.age,e.life);const h=this.system.limitVelocityOverLifetime;if(h.enabled&&h.apply(e.position,i,e.velocity,e.size,s,t,1),this.system.worldspace){const d=this.system.worldScale;e.velocity.x*=d.x,e.velocity.y*=d.y,e.velocity.z*=d.z}}}const D1=Symbol("colorLerpFactor"),j1=new se(1,1,1,1),ha=new se(1,1,1,1);class v2 extends Ks{type="NeedleColor";initialize(e){}_init(e){const t=this.system.renderer.particleMaterial;ha.copy(this.system.main.startColor.evaluate(Math.random())),t?.color&&(j1.copy(t.color),ha.multiply(j1)),ha.convertLinearToSRGB(),e.startColor.set(ha.r,ha.g,ha.b,ha.alpha),e.color.copy(e.startColor),e[D1]=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[D1]);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 w2{system;emission;get anim(){return this.system.textureSheetAnimation}constructor(e){this.system=e,this.emission=new u2(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 jp(this.system.main.startLifetime)}get startSpeed(){return new jp(this.system.main.startSpeed)}get startRotation(){return new jp(this.system.main.startRotation)}get startSize(){return new jp(this.system.main.startSize)}startLength;get startColor(){return new DP(new jP(1,1,1,1))}get emissionOverTime(){return this.emission}get emissionOverDistance(){return new p2(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 Eo.Trail;switch(this.system.renderer.renderMode){case Jo.Billboard:return Eo.BillBoard;case Jo.Stretch:return Eo.StretchedBillBoard;case Jo.HorizontalBillboard:return Eo.HorizontalBillBoard;case Jo.VerticalBillboard:return Eo.VerticalBillBoard;case Jo.Mesh:return Eo.Mesh}return Eo.BillBoard}rendererEmitterSettings={startLength:new BP(220),followLocalOrigin:!1};get speedFactor(){let e=this.system.main.simulationSpeed;return this.system.renderer?.renderMode===Jo.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=Po,this.clonedTexture.original=t,this.clonedTexture.clone=i}return this.clonedTexture.clone}return this.flatWhiteTexture||(this.flatWhiteTexture=gf(new se(1,1,1,1),1)),this.flatWhiteTexture}get startTileIndex(){return new d2(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??QC}get transparent(){return this.system.renderer.transparent}get worldSpace(){return this.system.main.simulationSpace===Ph.World}}class x2{burstParticleIndex=0;burstParticleCount=0;isBursting=!1;travelDistance=0;previousWorldPos;burstIndex=0;burstWaveIndex=0;time=0;waitEmiting=0}const Xt=class bm extends E{play(e=!1){e&&S.foreachComponent(this.gameObject,t=>{t instanceof bm&&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 bm&&t!==this&&t.pause(!1)},!0),this._isPlaying=!1}stop(e=!0,t=!1){e&&S.foreachComponent(this.gameObject,i=>{i instanceof bm&&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 x2),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===Ph.World}get localspace(){return this.main.simulationSpace===Ph.Local}__worldQuaternion=new N;get worldQuaternion(){return this.__worldQuaternion}_worldQuaternionInverted=new N;get worldQuaternionInverted(){return this._worldQuaternionInverted}_worldScale=new b;get worldScale(){return this._worldScale}_worldPositionFrame=-1;_worldPos=new b;get worldPos(){return this._worldPositionFrame!==this.context.time.frame&&(this._worldPositionFrame=this.context.time.frame,ee(this.gameObject,this._worldPos)),this._worldPos}get matrixWorld(){return this._container.matrixWorld}get isSubsystem(){return this._isUsedAsSubsystem}addBehaviour(e){return this._particleSystem?(e instanceof Ks&&(e.system=this),Zs&&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()||Zs)&&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 Lp)){const n=new Lp;Ja(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 Up)){const n=new Up;Ja(n,i),e[t]=n}}Zs&&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(ln),!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 M,this._container.matrixAutoUpdate=!1,this.context.scene.add(this._container),this._batchSystem=new IP,this._batchSystem.name=this.gameObject.name,this._container.add(this._batchSystem),this._interface=new w2(this),this._particleSystem=new LP(this._interface),this._particleSystem.addBehavior(new y2(this)),this._particleSystem.addBehavior(new v2(this)),this._particleSystem.addBehavior(new m2(this)),this._particleSystem.addBehavior(new g2(this)),this._particleSystem.addBehavior(new _2(this)),this._particleSystem.addBehavior(new b2(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),Zs&&(console.log(this),this.gameObject.add(new Ci(1)))}start(){this.addSubParticleSystems(),this.updateLayers(),this.renderer.particleMesh instanceof H&&this._interface.renderMode==Eo.Mesh&&Ve.assignMeshLOD(this.renderer.particleMesh,0).then(e=>{e&&this.particleSystem&&this._interface.renderMode==Eo.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 e=1/60,t=this.main.duration,i=this.main.startLifetime.getMax(),n=Math.min(Math.max(t,i)/Math.max(.01,this.main.simulationSpeed),1e3),s=Math.ceil(n/e),r=Date.now();Zs&&console.log(`Particles ${this.name} - Prewarm for ${s} frames (${n} sec). Duration: ${t}, Lifetime: ${i}`);for(let a=0;a<s&&!(this.currentParticles>=this.maxParticles);a++){const l=Date.now()-r;if(l>2e3){console.warn(`Particles ${this.name} - Prewarm took too long. Aborting: ${l}`);break}this.onUpdate(),this.onSimulate(e)}}_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=$e(e);this._cameraScale=n.x}const t=!this.worldspace,i=this.gameObject;if(_e(i,this.__worldQuaternion),this._worldQuaternionInverted.copy(this.__worldQuaternion).invert(),$e(this.gameObject,this._worldScale),t&&this._container&&this.gameObject?.parent){const n=B1(this,x0);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 f0(this,this._particleSystem,e.particleSystem,t);i.emitterType=e.type,i.emitterProbability=e.emitProbability,this._particleSystem.addBehavior(i)}else Zs&&console.warn("Could not add SubParticleSystem",e,this)}}};Ue([u(Dp)],Xt.prototype,"colorOverLifetime"),Ue([u(Gt)],Xt.prototype,"main"),Ue([u(ts)],Xt.prototype,"emission"),Ue([u(ca)],Xt.prototype,"sizeOverLifetime"),Ue([u(m0)],Xt.prototype,"shape"),Ue([u(ve)],Xt.prototype,"noise"),Ue([u(Fe)],Xt.prototype,"trails"),Ue([u(He)],Xt.prototype,"velocityOverLifetime"),Ue([u(dt)],Xt.prototype,"limitVelocityOverLifetime"),Ue([u(g0)],Xt.prototype,"inheritVelocity"),Ue([u(zl)],Xt.prototype,"colorBySpeed"),Ue([u(qt)],Xt.prototype,"textureSheetAnimation"),Ue([u(Dn)],Xt.prototype,"rotationOverLifetime"),Ue([u(an)],Xt.prototype,"rotationBySpeed"),Ue([u(vi)],Xt.prototype,"sizeBySpeed");let kh=Xt;class Up{particleSystem;emitProbability=1;properties;type;_deserialize(e,t){const i=this.particleSystem;if(i instanceof kh)return;let n="";i&&typeof i.guid=="string"&&(n=i.guid,this.particleSystem=S.findByGuid(n,t)),Zs&&!(this.particleSystem instanceof kh)&&console.warn("Could not find particle system for sub emitter",n,t,this)}}function B1(o,e){if(e.set(1,1,1),o.gameObject.parent&&o.localspace)switch(o.main.scalingMode){case p0.Local:e=$e(o.gameObject.parent,e),e.x=1/e.x,e.y=1/e.y,e.z=1/e.z;break;default:if(!o.unsupported_scaling_mode){o.unsupported_scaling_mode=!0;const t="ParticleSystem scale mode "+p0[o.main.scalingMode]+" is not supported";A()&&be(t),console.warn(t,o.name,o)}e=$e(o.gameObject,e);break}return e}var S2=Object.defineProperty,S0=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&S2(e,t,n),n};class Wl 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),s=n.length();if(s>this.radius)return;let r=t;s>1?r/=s*s:r/=Math.max(.05,s),i.applyImpulse(n.multiplyScalar(r))})}}S0([u()],Wl.prototype,"strength"),S0([u()],Wl.prototype,"radius"),S0([u(Ke)],Wl.prototype,"targets");class rc extends E{_didAssignPlayerColor=!1;onEnable(){this.context.connection.beginListen(ie.JoinedRoom,this.tryAssignColor),this._didAssignPlayerColor||this.startCoroutine(this.waitForConnection())}onDisable(){this.context.connection.stopListen(ie.JoinedRoom,this.tryAssignColor)}*waitForConnection(){for(;!this.destroyed&&this.activeAndEnabled&&(yield pf(.2),!this.tryAssignColor()););}tryAssignColor=()=>{const e=S.getComponentInParent(this.gameObject,sn);if(e&&e.owner)return this._didAssignPlayerColor=!0,this.assignUserColor(e.owner),!0;const t=S.getComponentInParent(this.gameObject,Le);return t?.connectionId?(this._didAssignPlayerColor=!0,this.assignUserColor(t.connectionId),!0):!1};assignUserColor(e){const t=rc.hashCode(e),i=rc.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 s=n;s.material&&s.material.color&&this.assignColor(i,e,s)}}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 oe(t/255,i/255,n/255)}}const Mh=w("debugpost");let C0=null;function C2(o){C0=o}function F1(o){let e=o.gameObject;for(;e;){for(const t of vu(e))if(t.isPostProcessingManager===!0)return t;e=e.parent}return null}function P2(o){let e=F1(o);if(!e)if(C0){Mh&&console.warn("Adding postprocessing manager to the scene.");const t=o.scene;e=Mn(t,C0)}else A()&&console.warn("No post processing manager found");return e}const ut={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 it=null;function O2(o){Mh==="verbose"&&console.debug("Before ordering effects",[...o]),it||(it=new Map,it.set(T.POSTPROCESSING.MODULE.NormalPass,ut.NormalPass),it.set(T.POSTPROCESSING.MODULE.DepthDownsamplingPass,ut.DepthDownsamplingPass),it.set(T.POSTPROCESSING.MODULE.SMAAEffect,ut.SMAA),it.set(T.POSTPROCESSING.MODULE.SSAOEffect,ut.SSAO),it.set(T.POSTPROCESSING_AO.MODULE.N8AOPostPass,ut.SSAO),it.set(T.POSTPROCESSING_AO.MODULE.N8AOPass,ut.SSAO),it.set(T.POSTPROCESSING.MODULE.TiltShiftEffect,ut.TiltShift),it.set(T.POSTPROCESSING.MODULE.DepthOfFieldEffect,ut.DepthOfField),it.set(T.POSTPROCESSING.MODULE.ChromaticAberrationEffect,ut.ChromaticAberration),it.set(T.POSTPROCESSING.MODULE.BloomEffect,ut.Bloom),it.set(T.POSTPROCESSING.MODULE.SelectiveBloomEffect,ut.Bloom),it.set(T.POSTPROCESSING.MODULE.VignetteEffect,ut.Vignette),it.set(T.POSTPROCESSING.MODULE.PixelationEffect,ut.Pixelation),it.set(T.POSTPROCESSING.MODULE.ToneMappingEffect,ut.ToneMapping),it.set(T.POSTPROCESSING.MODULE.HueSaturationEffect,ut.HueSaturation),it.set(T.POSTPROCESSING.MODULE.BrightnessContrastEffect,ut.BrightnessContrast)),o.sort((e,t)=>{const i=typeof e.priority=="number"?e.priority:it.get(e.effect.constructor)??Number.NEGATIVE_INFINITY,n=typeof t.priority=="number"?t.priority:it.get(t.effect.constructor)??Number.NEGATIVE_INFINITY;return i===Number.NEGATIVE_INFINITY?(Mh&&console.warn("Unknown effect found: ",e.constructor.name,e),1):n===Number.NEGATIVE_INFINITY?(Mh&&console.warn("Unknown effect found: ",t.constructor.name,t),-1):i-n}),Mh==="verbose"&&console.debug("After ordering effects",[...o])}var k2=Object.defineProperty,M2=Object.getOwnPropertyDescriptor,U1=(o,e,t,i)=>{for(var n=M2(e,t),s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&k2(e,t,n),n};const E2=w("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;E2&&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}}U1([u()],z.prototype,"overrideState"),U1([u()],z.prototype,"value");class R2 extends Zi{constructor(){super([z])}onSerialize(e,t){}onDeserialize(e,t){const i=t.target,n=t.path;let s;if(i&&n&&(s=i[n]),(typeof s!="object"||typeof s=="object"&&s.isVolumeParameter!==!0)&&(s=new z),typeof e=="object"&&"value"in e){const r=e.value;s.initialize(r),s.overrideState=e.overrideState}else s.value=e;return s}}new R2;var T2=Object.defineProperty,A2=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&T2(e,t,n),n};const P0=w("debugpost");class nt 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(),P0&&console.warn("Enable",this.constructor.name+(this.__internalDidAwakeAndStart?"":" (awake)")),this.__internalDidAwakeAndStart&&(this.active=!0),this.onEffectEnabled()}onDisable(){super.onDisable(),P0&&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=P2(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(){P0&&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}}}A2([u()],nt.prototype,"active");var I2=Object.defineProperty,L2=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&I2(e,t,n),n};const D2=w("debugpost"),O0={};function cn(o,e){O0[o]=e}function j2(o){return o.__type in O0?O0[o.__type]:(D2&&o.__type&&console.warn("Unknown postprocessing type",o.__type,o),nt)}class zp{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)}}L2([Ye([o=>j2(o),nt])],zp.prototype,"components");var B2=Object.defineProperty,F2=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&B2(e,t,n),n};const U2=w("debugpost");class Eh extends nt{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=>{U2&&console.log("Antialiasing preset changed to",t),e.applyPreset(t)},e}}F2([u(z)],Eh.prototype,"preset"),cn("Antialiasing",Eh);var z2=Object.defineProperty,k0=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&z2(e,t,n),n};const Np=class WS extends nt{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=WS.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=So.lerp(.1,.9,t))},e}};k0([u(z)],Np.prototype,"threshold"),k0([u(z)],Np.prototype,"intensity"),k0([u(z)],Np.prototype,"scatter");let Wp=Np;cn("Bloom",Wp);var N2=Object.defineProperty,W2=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&N2(e,t,n),n};class Rh extends nt{get typeName(){return"ChromaticAberration"}intensity=new z(0);onCreateEffect(){const e=new T.POSTPROCESSING.MODULE.ChromaticAberrationEffect;return e.offset=new K(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}}W2([u(z)],Rh.prototype,"intensity"),cn("ChromaticAberration",Rh);var Th=(o=>(o[o.None=0]="None",o[o.Neutral=1]="Neutral",o[o.ACES=2]="ACES",o[o.AgX=3]="AgX",o[o.KhronosNeutral=4]="KhronosNeutral",o))(Th||{});const z1=new Map;function M0(o){switch(o){case 0:return Dm;case 1:return Lm;case 2:return Rd;case 3:return Ed;case 4:return Da;default:return z1.has(o)||(z1.set(o,!0),console.warn("[Postprocessing] Unknown tone mapping mode",o)),Da}}function V2(o){switch(o){case Dm:return 0;case Rd:return 2;case Ed:return 3;case Da:return 1;case Lm:return 1;default:return 0}}function Vp(o){switch(o){case Dm:return T.POSTPROCESSING.MODULE.ToneMappingMode.LINEAR;case Rd:return T.POSTPROCESSING.MODULE.ToneMappingMode.ACES_FILMIC;case Ed:return T.POSTPROCESSING.MODULE.ToneMappingMode.AGX;case Da:return T.POSTPROCESSING.MODULE.ToneMappingMode.NEUTRAL;case Lm:return T.POSTPROCESSING.MODULE.ToneMappingMode.REINHARD;default:return T.POSTPROCESSING.MODULE.ToneMappingMode.LINEAR}}var $2=Object.defineProperty,N1=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&$2(e,t,n),n};const E0=w("debugpost");class Js extends nt{get typeName(){return"ToneMapping"}mode=new z(void 0);exposure=new z(1);setMode(e){const t=Th[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=F1(this);e&&super.onEffectEnabled(e)}_tonemappingEffect=null;onCreateEffect(){if(this.mode.isInitialized==!1){const i=V2(this.context.renderer.toneMapping);E0&&console.log("[PostProcessing] Initializing ToneMapping mode to renderer.toneMapping",this.context.renderer.toneMapping+" \u2192 "+i),this.mode.initialize(i)}this._tonemappingEffect?.dispose();const e=M0(this.mode.value),t=this._tonemappingEffect=new T.POSTPROCESSING.MODULE.ToneMappingEffect({mode:Vp(e)});return this.mode.onValueChanged=i=>{if(typeof i=="string")i=jw(i),t.mode=Vp(i);else{const n=M0(i);t.mode=Vp(n)}t.name="ToneMapping ("+Th[i]+")",E0&&console.log("[PostProcessing] ToneMapping mode changed to",Th[i],e,t.mode)},E0&&console.log("[PostProcessing] Use ToneMapping",Th[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=M0(this.mode.value)),this.exposure.overrideState&&this.exposure.value!==void 0)){const e=Math.max(0,this.exposure.value);this.context.renderer.toneMappingExposure=e}}}N1([u(z)],Js.prototype,"mode"),N1([u(z)],Js.prototype,"exposure"),cn("Tonemapping",Js);var H2=Object.defineProperty,$p=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&H2(e,t,n),n};class er extends nt{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(s=>s instanceof Js);t||(t=new Js,this.postprocessingContext?.components.push(t)),this.postExposure.onValueChanged=s=>{this.postExposure.overrideState&&t?t.exposure.value=s: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=s=>i.contrast=s;const n=new T.POSTPROCESSING.MODULE.HueSaturationEffect;return this.hueShift.onValueChanged=s=>n.hue=s,this.saturation.onValueChanged=s=>n.saturation=s,e.push(i),e.push(n),e}}$p([u(z)],er.prototype,"postExposure"),$p([u(z)],er.prototype,"contrast"),$p([u(z)],er.prototype,"hueShift"),$p([u(z)],er.prototype,"saturation"),cn("ColorAdjustments",er);var G2=Object.defineProperty,da=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&G2(e,t,n),n};const q2=w("debugpost");class jn extends nt{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 j.lerp(2,.01,i)};const e=20;this.aperture.valueProcessor=t=>{const i=1-t/32;return j.lerp(1,e,i)}}onCreateEffect(){if(this.mode===0){q2&&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(){}}da([u()],jn.prototype,"mode"),da([u(z)],jn.prototype,"focusDistance"),da([u(z)],jn.prototype,"focalLength"),da([u(z)],jn.prototype,"aperture"),da([u(z)],jn.prototype,"gaussianMaxRadius"),da([u(z)],jn.prototype,"resolutionScale"),da([u(z)],jn.prototype,"bokehScale"),cn("DepthOfField",jn);class Ah extends nt{effect;constructor(e){super(),this.effect=e}get typeName(){return this.effect.constructor.name}onCreateEffect(){return this.effect}}var X2=Object.defineProperty,Q2=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&X2(e,t,n),n};class Ih extends nt{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}}Q2([u(z)],Ih.prototype,"granularity"),cn("PixelationEffect",Ih);var Y2=Object.defineProperty,Lh=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&Y2(e,t,n),n};class is extends nt{get typeName(){return"ScreenSpaceAmbientOcclusion"}intensity=new z(2);falloff=new z(1);samples=new z(9);color=new z(new oe(0,0,0));luminanceInfluence=new z(.7);onBeforeRender(){if(this._ssao&&this.context.mainCamera instanceof de){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 oe),n.color.copy(r)},this.luminanceInfluence.onValueChanged=r=>{n.luminanceInfluence=r};const s=new Array;return s.push(t),s.push(i),s.push(n),s}}Lh([u(z)],is.prototype,"intensity"),Lh([u(z)],is.prototype,"falloff"),Lh([u(z)],is.prototype,"samples"),Lh([u(z)],is.prototype,"color"),Lh([u(z)],is.prototype,"luminanceInfluence"),cn("ScreenSpaceAmbientOcclusion",is);var Z2=Object.defineProperty,ua=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&Z2(e,t,n),n};const K2=w("debugN8AO");var R0=(o=>(o[o.Performance=0]="Performance",o[o.Low=1]="Low",o[o.Medium=2]="Medium",o[o.High=3]="High",o[o.Ultra=4]="Ultra",o))(R0||{});class Bn extends nt{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 oe(0,0,0));screenspaceRadius=!1;quality=2;_ssao;onValidate(){this._ssao&&(this._ssao.setQualityMode(R0[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 s=R0[this.quality];n.setQualityMode(s),n.configuration.transparencyAware=!1;const r=new Vn(t,i);return n.configuration.beautyRenderTarget=r,n.configuration.autoRenderBeauty=!1,n.configuration.gammaCorrection=this.gammaCorrection,n.configuration.screenSpaceRadius=this.screenspaceRadius,K2&&(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 oe),n.configuration.color.copy(a)},n}}ua([Mt(),u()],Bn.prototype,"gammaCorrection"),ua([u(z)],Bn.prototype,"aoRadius"),ua([u(z)],Bn.prototype,"falloff"),ua([u(z)],Bn.prototype,"intensity"),ua([u(z)],Bn.prototype,"color"),ua([Mt(),u()],Bn.prototype,"screenspaceRadius"),ua([Mt(),u()],Bn.prototype,"quality"),cn("ScreenSpaceAmbientOcclusionN8",Bn);var J2=Object.defineProperty,eI=Object.getOwnPropertyDescriptor,W1=(o,e,t,i)=>{for(var n=eI(e,t),s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&J2(e,t,n),n};class Dh extends nt{get typeName(){return"Sharpening"}order=ut.Sharpening;_effect;onCreateEffect(){return this._effect??=new(tI()),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}W1([u()],Dh.prototype,"amount"),W1([u()],Dh.prototype,"radius");function tI(){const o=`
1312
1312
  void mainSupport() {
1313
1313
  vUv = uv;
1314
1314
  gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
@@ -1359,7 +1359,7 @@ axisFormat %s
1359
1359
  \u2022 `)+`
1360
1360
  `),ns&&this._onCreateEffectsDebug(this._composer,s)}createPassForMergeableEffects(e,t,i,n){if(e.length>0){const s=new T.POSTPROCESSING.MODULE.EffectPass(i,...e);s.name=e.map(r=>r.name).join(", "),s.mainScene=n,s.enabled=!0,s.renderToScreen=!1,t.addPass(s),e.length=0}}handleDevicePixelRatio(){typeof this.context.devicePixelRatio=="number"&&this.context.requestSizeUpdate()}_menuEntry=null;_passIndices=null;_onCreateEffectsDebug(e,t){if(ns==="passes"){const i=new T.POSTPROCESSING.MODULE.DepthEffect({blendFunction:T.POSTPROCESSING.MODULE.BlendFunction.NORMAL,inverted:!0});i.name="Depth Effect";const n=new T.POSTPROCESSING.MODULE.EffectPass(t,i);if(n.name="Depth Effect Pass",n.enabled=!1,e.passes.push(n),this._passIndices!==null){const r=[e.passes[0]];this._passIndices.length>0&&r.push(...this._passIndices.filter(a=>a!==0).map(a=>e.passes[a]).filter(a=>a)),r.length>0&&console.log("[PostProcessing] Passes (selected) \u2192",r),e.passes.length=0;for(const a of r)a.enabled=!0,a.renderToScreen=!1,e.addPass(a)}const s=this.context.menu;if(s&&this._passIndices===null){this._menuEntry&&this._menuEntry.remove();const r=document.createElement("select");r.multiple=!0;const a=document.createElement("option");a.innerText="Final Output",a.value="-1",r.appendChild(a);for(const l of e.passes){const c=document.createElement("option");c.innerText=l.name,c.value=`${e.passes.indexOf(l)}`,c.title=l.name,r.appendChild(c)}s.appendChild(r),this._menuEntry=r,r.addEventListener("change",()=>{const l=Array.from(r.selectedOptions).map(c=>parseInt(c.value));l.length===1&&l[0]===-1?this._passIndices=null:this._passIndices=l,this.applyEffects(this.context)})}}}}var oI=Object.defineProperty,V1=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&oI(e,t,n),n};const ma=w("debugpost");class $l extends E{get isPostProcessingManager(){return!0}get effects(){return this._activeEffects}get dirty(){return this._isDirty}set dirty(e){this._isDirty=e}sharedProfile;multisampling="auto";addEffect(e){let t=e;return t instanceof nt||(t=new Ah(t),typeof e.order=="number"&&(t.order=e.order)),t.gameObject===void 0&&this.gameObject.addComponent(t),this._effects.includes(t)||(this._effects.push(t),this._isDirty=!0),e}removeEffect(e){let t=-1;if(e instanceof nt?t=this._effects.indexOf(e):t=this._effects.findIndex(i=>i instanceof Ah&&i.effect===e),t!==-1)return this._effects.splice(t,1),this._isDirty=!0,e;if(e instanceof nt){const i=this.sharedProfile?.components?.indexOf(e);i!==void 0&&i!==-1&&(this._isDirty=!0,this.sharedProfile?.components?.splice(i,1))}return e}_postprocessing;_activeEffects=[];_effects=[];markDirty(){this._isDirty=!0}awake(){ma&&(console.log("PostprocessingManager Awake",this),console.log("Press P to toggle post processing"),window.addEventListener("keydown",e=>{e.key==="p"&&(this.enabled=!this.enabled,Oe("Toggle PostProcessing "+this.name+": Enabled="+this.enabled),this.markDirty())})),this.sharedProfile?.__init(this)}_componentEnabledTime=-1;_multisampleAutoChangeTime=0;_multisampleAutoDecreaseTime=0;onEnable(){this._componentEnabledTime=this.context.time.realtimeSinceStartup,this._isDirty=!0}onDisable(){this._postprocessing?.unapply(),this._isDirty=!1}onBeforeRender(){if(!this.context.isInXR&&(this.context.mainCamera&&this._isDirty&&this.apply(),this.context.composer&&this._postprocessing&&this._postprocessing.composer===this.context.composer)){if(this.context.renderer.getContext().isContextLost()&&this.context.renderer.forceContextRestore(),this.context.composer.getRenderer()!==this.context.renderer&&this.context.composer.setRenderer(this.context.renderer),this.context.composer.setMainScene(this.context.scene),this.multisampling==="auto")if(this._postprocessing&&this._postprocessing.hasSmaaEffect)this._postprocessing.multisampling!==0&&(this._postprocessing.multisampling=0,(ma||A())&&console.log(`[PostProcessing] multisampling is disabled because it's set to 'auto' on your PostprocessingManager/Volume component that also has an SMAA effect.
1361
1361
 
1362
- If you need multisampling consider changing 'auto' to a fixed value (e.g. 4).`));else{const e=this.context.time.realtimeSinceStartup-this._multisampleAutoChangeTime;if(this.context.time.realtimeSinceStartup-this._componentEnabledTime>2&&e>.5){const t=this._postprocessing.multisampling;if(this._postprocessing.multisampling>0&&this.context.time.smoothedFps<=50){this._multisampleAutoChangeTime=this.context.time.realtimeSinceStartup,this._multisampleAutoDecreaseTime=this.context.time.realtimeSinceStartup;let i=this._postprocessing.multisampling*.5;i=Math.floor(i),i!=this._postprocessing.multisampling&&(this._postprocessing.multisampling=i),ma&&console.debug(`[PostProcessing] Reduced multisampling from ${t} to ${this._postprocessing.multisampling}`)}else if(e>1&&this.context.time.smoothedFps>=59&&this._postprocessing.multisampling<this.context.renderer.capabilities.maxSamples&&this.context.time.realtimeSinceStartup-this._multisampleAutoDecreaseTime>10){this._multisampleAutoChangeTime=this.context.time.realtimeSinceStartup;let i=this._postprocessing.multisampling<=0?1:this._postprocessing.multisampling*2;i=Math.floor(i),i!==this._postprocessing.multisampling&&(this._postprocessing.multisampling=i),ma&&console.debug(`[PostProcessing] Increased multisampling from ${t} to ${this._postprocessing.multisampling}`)}}}else{const e=Math.max(0,Math.min(this.multisampling,this.context.renderer.capabilities.maxSamples));e!==this._postprocessing.multisampling&&(this._postprocessing.multisampling=e)}if(this.context.mainCamera){const e=this.context.composer.passes;for(const t of e)if(t.mainCamera&&t.mainCamera!==this.context.mainCamera){this.context.composer.setMainCamera(this.context.mainCamera);break}}}}onDestroy(){this._postprocessing?.dispose()}_lastApplyTime;_rapidApplyCount=0;_isDirty=!1;apply(){if(ma&&console.log(`Apply PostProcessing "${this.name||"unnamed"}"`),A()&&(this._lastApplyTime!==void 0&&Date.now()-this._lastApplyTime<100&&(this._rapidApplyCount++,this._rapidApplyCount===5&&console.warn("Detected rapid post processing modifications - this might be a bug",this)),this._lastApplyTime=Date.now()),this._isDirty=!1,this._activeEffects.length=0,this.sharedProfile?.components){const e=this.sharedProfile.components;for(const t of e)t.active&&t.enabled&&!this._activeEffects.includes(t)&&this._activeEffects.push(t)}for(const e of this._effects)e.active&&e.enabled&&!this._activeEffects.includes(e)&&this._activeEffects.push(e);this._activeEffects.length>0?(this._postprocessing||(this._postprocessing=new I0(this.context)),this._postprocessing.apply(this._activeEffects)?.then(()=>{this.activeAndEnabled&&(this._applyPostQueue(),this._postprocessing?(this.multisampling==="auto"?this._postprocessing.multisampling=I.isMobileDevice()?2:4:this._postprocessing.multisampling=Math.max(0,Math.min(this.multisampling,this.context.renderer.capabilities.maxSamples)),ma&&console.debug(`[PostProcessing] Set multisampling to ${this._postprocessing.multisampling} (Is Mobile: ${I.isMobileDevice()})`)):ma&&console.warn("[PostProcessing] No composer found"))})):this._postprocessing?.unapply(!1)}_applyPostQueue(){if(this._modificationQueue){for(const e of this._modificationQueue.values())this.onEditorModification(e);this._modificationQueue.clear()}}onEditorModification(e){if(e.propertyName.startsWith("postprocessing.")){if(!this._postprocessing)return this._modificationQueue||(this._modificationQueue=new Map),this._modificationQueue.set(e.propertyName,e),!0;if(!this._activeEffects?.length)return;const t=e.propertyName.split(".");if(t.length===3||t.length===4){const i=t[1],n=t[2];for(const s of this._activeEffects)if(s.typeName?.toLowerCase()===i.toLowerCase()){if(n==="active"){s.active=e.value,this.scheduleRecreate();return}if(!Hp.has(i)){const r=new Array;Hp.set(i,r);const a=Object.keys(s);for(const l of a)s[l]instanceof z&&r.push(l)}if(Hp.has(i)){const r=n.toLowerCase(),a=Hp.get(i);for(const l of a)if(l.toLowerCase()===r){const c=s[l];c instanceof z&&(t.length===4&&t[3]==="active"?(c.overrideState=e.value,this.scheduleRecreate()):c&&c.value!==void 0&&(c.value=e.value));return}}console.warn("Unknown modification",n);return}}return!0}return!1}_modificationQueue;_recreateId=-1;scheduleRecreate(){const e=++this._recreateId;setTimeout(()=>{e===this._recreateId&&(this.onDisable(),this.onEnable())},200)}}V1([Qe(zp)],$l.prototype,"sharedProfile"),V1([Qe()],$l.prototype,"multisampling");const Hp=new Map;C2($l);async function L0(o){const{NeedleEngineWebComponent:e}=await Promise.resolve().then(()=>YL);e.observedAttributes.includes(o)||e.observedAttributes.push(o)}var sI=Object.defineProperty,St=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&sI(e,t,n),n};const Ct=w("debugsceneswitcher"),rI=w("sceneswitcher:clearscene"),Gp="scene";L0(Gp);const tr=Promise.resolve(!1);class Ke extends E{autoLoadFirstScene=!0;scenes=[];loadingScene;queryParameterName="scene";useSceneName=!0;clamp=!0;useHistory=!0;useKeyboard=!0;useSwipe=!0;useSceneLighting=!0;useSceneBackground=!0;preloadNext=1;preloadPrevious=1;preloadConcurrent=2;createMenuButtons=!1;get currentIndex(){return this._currentIndex}get currentLoadingProgress(){return this._currentLoadingProgress}get currentlyLoadingScene(){return this._currentlyLoadingScene}get currentlyLoadedScene(){return this._currentScene}sceneLoadingStart=new ae;sceneLoadingProgress=new ae;sceneLoaded=new ae;_currentIndex=-1;_currentScene=void 0;_currentSceneAsset=void 0;_engineElementOverserver=void 0;_preloadScheduler;_menuButtons;__lastSwitchScene;__lastSwitchScenePromise;awake(){this._currentScene=void 0,this._lastLoadingScene=void 0,this.__lastSwitchScenePromise=void 0,this.scenes===void 0&&(this.scenes=[]);for(const e of this.scenes)e&&!e.hasUrl&&e.asset instanceof M?S.remove(e.asset):e instanceof M&&S.remove(e);Ct&&console.log("SceneSwitcher",this)}async onEnable(){if(globalThis.addEventListener("popstate",this.onPopState),this.context.input.addEventListener(Ae.KeyDown,this.onInputKeyDown),this.context.input.addEventListener(Ae.PointerMove,this.onInputPointerMove),this.context.input.addEventListener(Ae.PointerUp,this.onInputPointerUp),this._engineElementOverserver||(this._engineElementOverserver=new MutationObserver(e=>{for(const t of e)if(t.type==="attributes"&&t.attributeName===Gp){const i=this.context.domElement.getAttribute(Gp);i!==null&&this.trySelectSceneFromValue(i)}})),this._engineElementOverserver.observe(this.context.domElement,{attributes:!0}),this._preloadScheduler||(this._preloadScheduler=new aI(this)),this._preloadScheduler.maxLoadAhead=this.preloadNext,this._preloadScheduler.maxLoadBehind=this.preloadPrevious,this._preloadScheduler.maxConcurrent=this.preloadConcurrent,this._preloadScheduler.begin(2e3),this.autoLoadFirstScene&&this._currentIndex===-1&&!await this.tryLoadFromQueryParam()){const e=this.context.domElement.getAttribute(Gp);(e===null||!await this.trySelectSceneFromValue(e))&&this._currentIndex===-1&&this.select(0)}this.createMenuButtons&&(this._menuButtons??=[],this._menuButtons.push(this.context.menu.appendChild({label:"Previous",icon:"arrow_back_ios",onClick:()=>this.selectPrev(),priority:-1005,class:"row2"})),this._menuButtons.push(this.context.menu.appendChild({label:"Next",icon:"arrow_forward_ios",iconSide:"right",onClick:()=>this.selectNext(),priority:-1e3,class:"row2"})))}onDisable(){if(globalThis.removeEventListener("popstate",this.onPopState),this.context.input.removeEventListener(Ae.KeyDown,this.onInputKeyDown),this.context.input.removeEventListener(Ae.PointerMove,this.onInputPointerMove),this.context.input.removeEventListener(Ae.PointerUp,this.onInputPointerUp),this._preloadScheduler?.stop(),this._menuButtons){for(const e of this._menuButtons)e.remove();this._menuButtons=void 0}}onPopState=async e=>{if(!this.useHistory)return;const t=this.useHistory;try{this.useHistory=!1;let i=!1;if(this.queryParameterName&&(i=await this.tryLoadFromQueryParam()),!i){const n=e?.state;if(n&&n.startsWith(this.guid)){const s=n.substr(this.guid.length+2);Ct&&console.log("PopState",s),await this.trySelectSceneFromValue(s)}}}finally{this.useHistory=t}};normalizedSwipeThresholdX=.1;_didSwipe=!1;onInputPointerMove=e=>{if(this.useSwipe&&!this._didSwipe&&e.button===0&&e.pointerType==="touch"&&this.context.input.getPointerPressedCount()===1){const t=this.context.input.getPointerPositionDelta(e.button);if(t){const i=t.x/this.context.domWidth;i>=this.normalizedSwipeThresholdX?(this._didSwipe=!0,this.selectPrev()):i<=-this.normalizedSwipeThresholdX&&(this._didSwipe=!0,this.selectNext())}}};onInputPointerUp=e=>{e.button===0&&(this._didSwipe=!1)};onInputKeyDown=e=>{if(!this.useKeyboard||!this.scenes)return;const t=e.key.toLowerCase();if(!t)return;const i=parseInt(t)-1;if(i>=0){this.trySelectSceneFromValue(i);return}switch(t){case"arrowright":case"d":this.selectNext();break;case"arrowleft":case"a":this.selectPrev();break}};addScene(e){if(typeof e=="string"){let t=this.context.addressables.findAssetReference(e);return t||(t=new ne(e),this.context.addressables.registerAssetReference(t)),this.scenes.push(t),t}return this.scenes.push(e),e}selectNext(){return this.select(this._currentIndex+1)}selectPrev(){return this.select(this._currentIndex-1)}select(e){if(Ct&&console.log("[SceneSwitcher] select",e),typeof e=="object"&&console.warn('[SceneSwitcher] Switching to "'+e+'" might not work. Please either use an index or a AssetReference (not a scene reference)'),typeof e=="string"){const i=this.scenes?.find(n=>n.url===e);if(!i){const n=ne.getOrCreate(this.sourceId??"",e,this.context);return this.switchScene(n)}if(i)e=this.scenes?.indexOf(i);else return tr}if(!this.scenes?.length)return tr;if(e<0){if(this.clamp)return tr;e=this.scenes.length-1}else if(e>=this.scenes.length){if(this.clamp)return tr;e=0}const t=this.scenes[e];return this.switchScene(t)}unload(){return this.__lastSwitchScene=void 0,this.__lastSwitchScenePromise=void 0,this.__unloadCurrentScene()}async reload(){if(this.__lastSwitchScene){const e=this.__lastSwitchScene;return this.__lastSwitchScene=void 0,this.switchScene(e)}return!1}async switchScene(e){if(!(e instanceof ne)){const t=typeof e;if(t==="string")return this.select(e);if(t==="number")return this.select(e);if(e&&e instanceof M){const i=this.scenes?.indexOf(e);e=new ne(e.name,void 0,e),i>=0&&(this.scenes[i]=e)}else return console.warn(`[SceneSwitcher] Can't switch to scene of type ${t}`),!1}return e.url===this.sourceId?(console.warn("[SceneSwitcher] Can't load own scene - prevent recursive loading",this.sourceId),!1):this.__lastSwitchScene===e&&this.__lastSwitchScenePromise?this.__lastSwitchScenePromise:(this.__lastSwitchScene=e,this.__lastSwitchScenePromise=this.__internalSwitchScene(e),await this.__lastSwitchScenePromise)}async __unloadCurrentScene(){const e=this._currentScene;if(this._currentScene=void 0,e){Ct&&console.log("[SceneSwitcher] UNLOAD",e.url,"HasURL?: "+e.hasUrl);const t=this.tryGetSceneEventListener(e.asset);if(t?.sceneClosing){const i=t.sceneClosing();i instanceof Promise&&await i}e.hasUrl?(e.unload(),this._currentSceneAsset&&Ii(this._currentSceneAsset,!0,!1)):S.remove(this._currentSceneAsset)}}_currentlyLoadingScene;async __internalSwitchScene(e){await this.__unloadCurrentScene();const t=this._currentIndex=this.scenes?.indexOf(e)??-1;try{Ct&&console.debug(`${Date.now()} [SceneSwitcher] Loading scene start: ${e.url} (index: ${t})`),this._currentlyLoadingScene=e,this._currentLoadingProgress=new ProgressEvent("progress",{loaded:0,total:1});const i=new CustomEvent("loadscene-start",{detail:{scene:e,switcher:this,index:t}});this.dispatchEvent(i),this.sceneLoadingStart?.invoke(i.detail),await this.onStartLoading(),await e.loadAssetAsync((s,r)=>{if(Ct){const a=r.loaded/r.total,l="["+"=".repeat(Math.floor(a*20))+"-".repeat(20-Math.floor(a*20))+"]";console.debug(`${Date.now()} [SceneSwitcher] Loading scene progress: ${(a*100).toFixed(1)} % ${l}`,e.url)}this._currentLoadingProgress=r,this.dispatchEvent(r),this.sceneLoadingProgress?.invoke(r)}).catch(console.error),await this.onEndLoading();const n=new CustomEvent("loadscene-finished",{detail:{scene:e,switcher:this,index:t}});if(this.dispatchEvent(n),this._currentLoadingProgress=void 0,this._currentlyLoadingScene=void 0,n.defaultPrevented)return Ct&&console.warn("[SceneSwitcher] Adding loaded scene prevented:",e,n),!1;if(!e.asset)return Ct&&console.warn("[SceneSwitcher] Failed loading scene:",e),!1;if(this._currentIndex===t){if(Ct&&console.log("[SceneSwitcher] ADD",e.url),this._currentScene=e,rI){const a=this.context.mainCameraComponent?.gameObject||this.context.mainCamera;a?.removeFromParent();const l=this.gameObject.removeFromParent();Ii(this.context.scene,!0,!0),this.context.scene=new Hi,this.context.scene.add(l),a&&this.context.scene.add(a)}if(e.asset.parent?this._currentSceneAsset=Ur(e.asset,{parent:this.gameObject}):(this._currentSceneAsset=e.asset,S.add(e.asset,this.gameObject)),this.useSceneLighting&&this.context.sceneLighting.enable(e),this.useSceneBackground){const a=this.context.lightmaps.tryGetSkybox(e.url);a?(a.mapping=Oo,this.context.scene.background=a):Ct&&console.warn("[SceneSwitcher] Can't find skybox for scene "+e.url)}if(this.useHistory&&t>=0){let a=t.toString();if(this.useSceneName&&(e instanceof M?a=e.name:e.url&&(a=$1(e.url))),this.queryParameterName?.length)uc(this.queryParameterName,a,this.useHistory);else{const l=history.state,c=this.guid+"::"+t;l!==c&&history.pushState(c,"unused",location.href)}}const s=this.tryGetSceneEventListener(e.asset);if(s?.sceneOpened){const a=s.sceneOpened(this);a instanceof Promise&&await a}Ct&&console.debug(`${Date.now()} [SceneSwitcher] Loading scene finished: ${e.url} (index: ${t})`);const r=new CustomEvent("scene-opened",{detail:{scene:e,switcher:this,index:t}});return this.dispatchEvent(r),this.sceneLoaded?.invoke(this),!0}}catch(i){console.error(i)}return!1}preload(e){if(e>=0&&e<this.scenes.length){const t=this.scenes[e];if(t instanceof ne)return t.preload()}return tr}tryLoadFromQueryParam(){if(!this.queryParameterName?.length)return tr;const e=w(this.queryParameterName);return typeof e=="boolean"?tr:this.trySelectSceneFromValue(e)}trySelectSceneFromValue(e){if(typeof e=="string"){const t=parseInt(e);if(t>=0&&t<this.scenes.length)return this.select(t);{const i=e.toLowerCase();for(let n=0;n<this.scenes.length;n++){const s=this.scenes[n];if(!!s&&(s instanceof M?s.name:$1(s.url)).toLowerCase().includes(i))return this.select(n)}}}else if(typeof e=="number"&&e>=0&&e<this.scenes.length)return this.select(e);return ki()&&console.warn('[SceneSwitcher] Can not find scene: "'+e+'"',this),tr}_lastLoadingScene=void 0;_loadingScenePromise=void 0;_isCurrentlyLoading=!1;_currentLoadingProgress=void 0;async onStartLoading(){if(this._isCurrentlyLoading=!0,this.loadingScene&&(this._lastLoadingScene!==this.loadingScene&&(this._loadingScenePromise=void 0),this._lastLoadingScene=this.loadingScene,this._loadingScenePromise||(this._loadingScenePromise=this.loadingScene?.loadAssetAsync().then(e=>e!=null)),await this._loadingScenePromise,this._isCurrentlyLoading&&this.loadingScene?.asset)){Ct&&console.log("Add loading scene",this.loadingScene.url,this.loadingScene.asset);const e=this.loadingScene.asset;S.add(e,this.gameObject);const t=this.tryGetSceneEventListener(e);if(t?.sceneOpened){const i=t.sceneOpened(this);i instanceof Promise&&await i}}if(this._isCurrentlyLoading){const e=this.tryGetSceneEventListener(this.gameObject);if(e&&e.sceneOpened){const t=e.sceneOpened(this);t instanceof Promise&&await t}}}async onEndLoading(){if(this._isCurrentlyLoading=!1,this.loadingScene?.asset){Ct&&console.log("Remove loading scene",this.loadingScene.url);const e=this.loadingScene.asset,t=this.tryGetSceneEventListener(e);if(typeof t?.sceneClosing=="function"){const i=t.sceneClosing();i instanceof Promise&&await i}S.remove(e)}if(!this._isCurrentlyLoading){const e=this.tryGetSceneEventListener(this.gameObject);if(e&&e.sceneClosing){const t=e.sceneClosing();t instanceof Promise&&await t}}}tryGetSceneEventListener(e,t=0){if(!e)return null;const i=S.foreachComponent(e,n=>{const s=n;if(s.sceneClosing||s.sceneOpened)return s});if(t===0&&!i&&e.children.length)for(const n of e.children){const s=this.tryGetSceneEventListener(n,t+1);if(s)return s}return i||null}}St([u()],Ke.prototype,"autoLoadFirstScene"),St([u(ne)],Ke.prototype,"scenes"),St([u(ne)],Ke.prototype,"loadingScene"),St([u()],Ke.prototype,"queryParameterName"),St([u()],Ke.prototype,"useSceneName"),St([u()],Ke.prototype,"clamp"),St([u()],Ke.prototype,"useHistory"),St([u()],Ke.prototype,"useKeyboard"),St([u()],Ke.prototype,"useSwipe"),St([u()],Ke.prototype,"useSceneLighting"),St([u()],Ke.prototype,"useSceneBackground"),St([u()],Ke.prototype,"preloadNext"),St([u()],Ke.prototype,"preloadPrevious"),St([u()],Ke.prototype,"preloadConcurrent"),St([u()],Ke.prototype,"createMenuButtons"),St([u(ae)],Ke.prototype,"sceneLoadingStart"),St([u(ae)],Ke.prototype,"sceneLoadingProgress"),St([u(ae)],Ke.prototype,"sceneLoaded");function $1(o){const e=o.split("/").pop()?.split(".").shift();return e?.length?e:o}class aI{maxLoadAhead;maxLoadBehind;maxConcurrent;_isRunning=!1;_switcher;_loadTasks=[];_maxConcurrentLoads=1;constructor(e,t=1,i=1,n=2){this._switcher=e,this.maxLoadAhead=t,this.maxLoadBehind=i,this.maxConcurrent=n}begin(e){if(this._isRunning)return;Ct&&console.log("[SceneSwitcher] Preload scheduled",{delay:e}),this._isRunning=!0;let t=-10,i,n;const s=this._switcher.scenes,r=Date.now()+e,a=setInterval(()=>{if(this.allLoaded()&&(Ct&&console.log("[SceneSwitcher] All scenes (pre-)loaded"),this.stop()),!this._isRunning){clearInterval(a);return}if(Date.now()<r||this.canLoadNewScene()===!1)return;(t===-10||t!==this._switcher.currentIndex)&&(t=this._switcher.currentIndex,n=0,i=0);const l=n%2===0;l&&(i+=1),n+=1;const c=l?this.maxLoadAhead:this.maxLoadBehind;if(i>c)return;const h=l?t+i:t-i;if(!(h<0)&&!(h<0||h>=s.length)&&!this._loadTasks.some(d=>d.index===h)){const d=s[h];Ct&&console.log("[SceneSwitcher] Schedule preload scene",{roomIndex:h,searchForward:l,lastRoom:t,currentIndex:this._switcher.currentIndex,tasks:this._loadTasks.length},d?.url),new lI(h,d,this._loadTasks)}},200)}stop(){this._isRunning=!1}canLoadNewScene(){return this._loadTasks.length<this._maxConcurrentLoads}allLoaded(){if(this._switcher.scenes){for(const e of this._switcher.scenes)if(e?.isLoaded&&e.isLoaded()===!1)return!1}return!0}}class lI{index;asset;tasks;constructor(e,t,i){this.index=e,this.asset=t,this.tasks=i,i.push(this),this.awaitLoading()}async awaitLoading(){this.asset&&!this.asset.isLoaded()&&(Ct&&console.log("[SceneSwitcher] Preload start: "+this.asset.url,this.index),await this.asset.preload(),Ct&&console.log("[SceneSwitcher] Preload finished: "+this.asset.url,this.index));const e=this.tasks.indexOf(this);e>=0&&this.tasks.splice(e,1)}}function cI(){return new Promise((o,e)=>{const t=()=>{t!=null&&(document.removeEventListener("pointerdown",t),document.removeEventListener("click",t),document.removeEventListener("dragstart",t),document.removeEventListener("touchstart",t),o())};document.addEventListener("pointerdown",t),document.addEventListener("click",t),document.addEventListener("dragstart",t),document.addEventListener("touchstart",t)})}async function hI(o){await cI(),o()}var dI=Object.defineProperty,uI=Object.getOwnPropertyDescriptor,zi=(o,e,t,i)=>{for(var n=i>1?void 0:i?uI(e,t):e,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&dI(e,t,n),n};const ot=w("debugvideo");var H1=(o=>(o[o.None=0]="None",o[o.AdjustHeight=1]="AdjustHeight",o[o.AdjustWidth=2]="AdjustWidth",o))(H1||{}),G1=(o=>(o[o.VideoClip=0]="VideoClip",o[o.Url=1]="Url",o))(G1||{}),q1=(o=>(o[o.CameraFarPlane=0]="CameraFarPlane",o[o.CameraNearPlane=1]="CameraNearPlane",o[o.RenderTexture=2]="RenderTexture",o[o.MaterialOverride=3]="MaterialOverride",o))(q1||{});class pt extends E{playOnAwake=!0;aspectMode=0;clip=null;source=1;get url(){return this._url}set url(e){const t=this._url!==e;this.__didAwake?t&&this.setClipURL(e??""):this._url=e}_url=null;renderMode;targetMaterialProperty;targetMaterialRenderer;targetTexture;time=0;_playbackSpeed=1;get playbackSpeed(){return this._videoElement?.playbackRate??this._playbackSpeed}set playbackSpeed(e){this._playbackSpeed=e,this._videoElement&&(this._videoElement.playbackRate=e)}_isLooping=!1;get isLooping(){return this._videoElement?.loop??this._isLooping}set isLooping(e){this._isLooping=e,this._videoElement&&(this._videoElement.loop=e)}get currentTime(){return this._videoElement?.currentTime??this.time}set currentTime(e){this._videoElement?this._videoElement.currentTime=e:this.time=e}get isPlaying(){const e=this._videoElement;return!!(e&&(e.currentTime>0&&!e.paused&&!e.ended&&e.readyState>e.HAVE_CURRENT_DATA||e.srcObject&&e.srcObject.active))}get crossOrigin(){return this._videoElement?.crossOrigin??this._crossOrigin}set crossOrigin(e){this._crossOrigin=e,this._videoElement&&(e!==null?this._videoElement.setAttribute("crossorigin",e):this._videoElement.removeAttribute("crossorigin"))}get videoMaterial(){return!this._videoMaterial&&!this.create(!1)?null:this._videoMaterial}get videoTexture(){return!this._videoTexture&&!this.create(!1)?null:this._videoTexture}get videoElement(){return!this._videoElement&&!this.create(!1)?null:this._videoElement}requestPictureInPicture(){return this._videoElement?this._videoElement.requestPictureInPicture():null}get muted(){return this._videoElement?.muted??this._muted}set muted(e){this._muted=e,this._videoElement&&(this._videoElement.muted=e)}_muted=!1;get currentVideo(){return this.clip}set audioOutputMode(e){e!==this._audioOutputMode&&(e===1&&A()&&console.warn("VideoAudioOutputMode.AudioSource is not yet implemented"),this._audioOutputMode=e,this.updateVideoElementSettings())}get audioOutputMode(){return this._audioOutputMode}_audioOutputMode=2;playInBackground=!0;_crossOrigin="anonymous";_videoElement=null;_videoTexture=null;_videoMaterial=null;_isPlaying=!1;wasPlaying=!1;preloadVideo(){ot&&console.log("Video Preload: "+this.name,this.clip),this.create(!1)}preload(){this.preloadVideo()}setVideo(e){this.clip=e,this.source=0,this._videoElement?(this._videoElement.srcObject=e,this._isPlaying&&this.play(),this.updateAspect()):this.create(this.playOnAwake)}setClipURL(e){this._url!==e&&(this._url=e,this.source=1,ot&&console.log("set url",e),this._videoElement?e.endsWith(".m3u8")||e.includes(".m3u")?this.ensureM3UCanBePlayed():(this._videoElement.src=e,this._isPlaying&&(this.stop(),this.play())):this.create(this.playOnAwake))}onEnable(){ot&&console.log("VideoPlayer.onEnable",G1[this.source],this.clip,this.url,this),window.addEventListener("visibilitychange",this.visibilityChanged),this.playOnAwake===!0?this.create(!0):this.preloadVideo(),this.screenspace?this._overlay?.start():this._overlay?.stop()}onDisable(){window.removeEventListener("visibilitychange",this.visibilityChanged),this._overlay?.stop(),this.pause()}visibilityChanged=e=>{switch(document.visibilityState){case"hidden":this.playInBackground||(this.wasPlaying=this._isPlaying,this.pause());break;case"visible":this.wasPlaying&&!this._isPlaying&&this.play();break}};onDestroy(){this._videoElement&&(this.videoElement?.remove(),this._videoElement=null),this._videoTexture&&(this._videoTexture.dispose(),this._videoTexture=null)}_receivedInput=!1;constructor(){super(),hI(()=>{this._receivedInput=!0,this.updateVideoElementSettings()}),this._targetObjects=[],w("videoscreenspace")&&window.addEventListener("keydown",e=>{e.key==="f"&&(this.screenspace=!this.screenspace)})}play(){if(this._videoElement||this.create(!1),!this._videoElement){ot&&console.warn("Can not play: no video element found",this);return}if(!(this._isPlaying&&!this._videoElement?.ended&&!this._videoElement?.paused)){if(this._isPlaying=!0,this._receivedInput||(this._videoElement.muted=!0),this.handleBeginPlaying(!1),this.shouldUseM3U){this.ensureM3UCanBePlayed();return}ot&&console.log("Video Play()",this.clip,this._videoElement,this.time),this._videoElement.currentTime=this.time,this._videoElement.play().catch(e=>{console.log(e),ot&&console.error("Error playing video",e,"CODE="+e.code,this.videoElement?.src,this),setTimeout(()=>{this._isPlaying&&!this.destroyed&&this.activeAndEnabled&&this.play()},1e3)}),ot&&console.log("play",this._videoElement,this.time)}}stop(){this._isPlaying=!1,this.time=0,this._videoElement&&(this._videoElement.currentTime=0,this._videoElement.pause(),ot&&console.log("STOP",this))}pause(){this.time=this._videoElement?.currentTime??0,this._isPlaying=!1,this._videoElement?.pause(),ot&&console.log("PAUSE",this,this.currentTime)}create(e){let t;switch(this.source){case 0:t=this.clip;break;case 1:t=this.url,!t?.length&&typeof this.clip=="string"&&(t=this.clip);break}return t?(this._videoElement||(ot&&console.warn("Create VideoElement",this),this._videoElement=this.createVideoElement(),this.context.domElement.shadowRoot.prepend(this._videoElement),this.updateVideoElementStyles()),typeof t=="string"?(ot&&console.log("Set Video src",t),this._videoElement.src=t):(ot&&console.log("Set Video srcObject",t),this._videoElement.srcObject=t),this._videoTexture||(this._videoTexture=new YC(this._videoElement)),this._videoTexture.flipY=!1,this._videoTexture.colorSpace=ko,e&&this.handleBeginPlaying(e),ot&&console.log("Video: handle playing done...",t,e),!0):(ot&&console.warn("No video source set",this),!1)}updateAspect(){this.aspectMode!==0&&this.startCoroutine(this.updateAspectImpl())}_overlay=null;get screenspace(){return this._overlay?.enabled??!1}set screenspace(e){if(e){if(!this._videoTexture)return;this._overlay||(this._overlay=new pI(this.context)),this._overlay.add(this._videoTexture)}else this._overlay?.remove(this._videoTexture);this._overlay&&(this._overlay.enabled=e)}_targetObjects;createVideoElement(){const e=document.createElement("video");return this._crossOrigin&&e.setAttribute("crossorigin",this._crossOrigin),ot&&console.log("created video element",e),e}handleBeginPlaying(e){if(!this.activeAndEnabled||!this._videoElement)return;this._targetObjects.length=0;let t=this.gameObject;switch(this.renderMode){case 3:t=this.targetMaterialRenderer?.gameObject,t||(t=S.getComponent(this.gameObject,ei)?.gameObject);break;case 2:console.error("VideoPlayer renderTexture not implemented yet. Please use material override instead");return}if(!t){console.error("Missing target for video material renderer",this.name,q1[this.renderMode],this);return}const i=t.material;if(i){this._targetObjects.push(t),i!==this._videoMaterial&&(this._videoMaterial=i.clone(),t.material=this._videoMaterial);const n="map",s=this._videoMaterial;if(!this.targetMaterialProperty)ot&&s[n]===void 0&&console.warn(`The target material does not have a '${n}' property, video might not render correctly.`),s[n]=this._videoTexture;else switch(this.targetMaterialProperty){default:ot&&s[this.targetMaterialProperty]===void 0&&console.warn(`The target material does not have a '${this.targetMaterialProperty}' property, video might not render correctly.`),s[n]=this._videoTexture;break}}else{console.warn("Can not play video, no material found, this might be a multimaterial case which is not supported yet");return}this.updateVideoElementSettings(),this.updateVideoElementStyles(),e&&(this.shouldUseM3U&&this.ensureM3UCanBePlayed(),this.play())}updateVideoElementSettings(){if(!this._videoElement)return;this._videoElement.loop=this._isLooping,this._videoElement.currentTime=this.currentTime,this._videoElement.playbackRate=this._playbackSpeed,this._videoElement.playsInline=!0;let e=!this._receivedInput||this.audioOutputMode===0;!e&&this._muted&&(e=!0),this._videoElement.muted=e,this.playOnAwake&&(this._videoElement.autoplay=!0)}updateVideoElementStyles(){this._videoElement&&(this._videoElement.style.userSelect="none",this._videoElement.style.visibility="hidden",this._videoElement.style.display="none",this.updateAspect())}_updateAspectRoutineId=-1;*updateAspectImpl(){const e=++this._updateAspectRoutineId,t=void 0,i=this.clip;for(;e===this._updateAspectRoutineId&&this.aspectMode!==0&&this.clip&&i===this.clip&&this._isPlaying;){if(!i||typeof i=="string")return;let n;for(const s of i.getVideoTracks()){const r=s.getSettings();if(r&&r.width&&r.height){n=r.width/r.height;break}else n=this.context.renderer.domElement.clientWidth/this.context.renderer.domElement.clientHeight}if(n===void 0){for(let s=0;s<10;s++)yield;if(!this.isPlaying)break;continue}if(t===n){yield;continue}for(const s of this._targetObjects){let r=1;if(s.parent){const a=$e(s.parent);r=a.x/a.y}switch(this.aspectMode){case 1:s.scale.y=1/n*s.scale.x*r;break;case 2:s.scale.x=n*s.scale.y*r;break}}for(let s=0;s<3;s++)yield}}get shouldUseM3U(){return this.url!=null&&(this.url.endsWith(".m3u8")||this.url.endsWith(".m3u"))&&this.source===1}ensureM3UCanBePlayed(){if(!this.shouldUseM3U)return;let e=document.head.querySelector("script[data-hls_library]");e?globalThis.Hls?this.onHlsAvailable():e.addEventListener("load",this.onHlsAvailable):(ot&&console.log("HLS: load script"),e=document.createElement("script"),e.dataset.hls_library="hls.js",e.src="https://cdn.jsdelivr.net/npm/hls.js@1",e.addEventListener("load",this.onHlsAvailable),document.head.append(e))}_hls;onHlsAvailable=()=>{ot&&console.log("HLS: available",this.clip),!(!this.shouldUseM3U||!this.url)&&(this._hls||(this._hls=new Hls),this.videoElement.autoplay=!0,this._hls.loadSource(this.url),this._hls.attachMedia(this.videoElement),this._videoElement?.play(),ot&&console.log("HLS: loaded",this.clip))}}zi([u()],pt.prototype,"playOnAwake",2),zi([u()],pt.prototype,"aspectMode",2),zi([u(URL)],pt.prototype,"clip",2),zi([u()],pt.prototype,"source",2),zi([u(URL)],pt.prototype,"url",1),zi([u()],pt.prototype,"renderMode",2),zi([u()],pt.prototype,"targetMaterialProperty",2),zi([u(ei)],pt.prototype,"targetMaterialRenderer",2),zi([u(Se)],pt.prototype,"targetTexture",2),zi([u()],pt.prototype,"time",2),zi([u()],pt.prototype,"playbackSpeed",1),zi([u()],pt.prototype,"isLooping",1),zi([u()],pt.prototype,"audioOutputMode",1);class pI{context;constructor(e){this.context=e,this._input=new mI(this)}get enabled(){return this._isInScreenspaceMode}set enabled(e){e?this.start():this.stop()}add(e){this._videos.indexOf(e)===-1&&this._videos.push(e)}remove(e){if(!e)return;const t=this._videos.indexOf(e);t>=0&&this._videos.splice(t,1)}start(){if(this._isInScreenspaceMode||this._videos.length<0)return;const e=this._videos[this._videos.length-1];if(!e)return;if(this._isInScreenspaceMode=!0,!this._screenspaceModeQuad){if(this._screenspaceModeQuad=Ps.createPrimitive(Qa.Quad,{material:new gI(e)}),!this._screenspaceModeQuad)return;this._screenspaceModeQuad.geometry.scale(2,2,2)}const t=this._screenspaceModeQuad;this.context.scene.add(t),this.updateScreenspaceMaterialUniforms();const i=t.material;i?.reset(),this._input?.enable(i)}stop(){this._isInScreenspaceMode=!1,this._screenspaceModeQuad&&(this._input?.disable(),this._screenspaceModeQuad.removeFromParent())}updateScreenspaceMaterialUniforms(){const e=this._screenspaceModeQuad?.material;e&&(e.screenAspect=this.context.domElement.clientWidth/this.context.domElement.clientHeight)}_videos=[];_screenspaceModeQuad;_isInScreenspaceMode=!1;_input}class mI{_onResizeScreenFn;_onKeyUpFn;_onMouseWheelFn;context;overlay;constructor(e){this.overlay=e,this.context=e.context}_material;enable(e){this._material=e,window.addEventListener("resize",this._onResizeScreenFn=()=>{this.overlay.updateScreenspaceMaterialUniforms()}),window.addEventListener("keyup",this._onKeyUpFn=n=>{n.key==="Escape"&&this.overlay.stop()}),window.addEventListener("wheel",this._onMouseWheelFn=n=>{this.overlay.enabled&&(e.zoom+=n.deltaY*5e-4,n.preventDefault())},{passive:!1});const t=new K;window.addEventListener("mousemove",n=>{if(this.overlay.enabled&&this.context.input.getPointerPressed(0)){const s=new K(n.movementX,n.movementY);s.x/=this.context.domElement.clientWidth,s.y/=this.context.domElement.clientHeight,t.set(s.x,s.y),t.multiplyScalar(e.zoom/-this.context.time.deltaTime*.01),e.offset=e.offset.add(t)}}),window.addEventListener("pointermove",n=>{this.overlay.enabled&&this.context.input.getPointerPressed(0)&&this.context.input.getTouchesPressedCount()===1&&(t.set(n.movementX,n.movementY),t.multiplyScalar(e.zoom*-this.context.time.deltaTime*.05),e.offset=e.offset.add(t))});let i=0;window.addEventListener("touchstart",n=>{if(n.touches.length<2){this.context.time.time-i<.3&&this.overlay.stop(),i=this.context.time.time;return}this._isPinching=!0,this._lastPinch=0}),window.addEventListener("touchmove",n=>{if(!this._isPinching||!this._material)return;const s=n.touches[0],r=n.touches[1],a=s.clientX-r.clientX,l=s.clientY-r.clientY,c=Math.sqrt(a*a+l*l);if(this._lastPinch!==0){const h=c-this._lastPinch;this._material.zoom-=h*.004}this._lastPinch=c}),window.addEventListener("touchend",()=>{this._isPinching=!1})}_isPinching=!1;_lastPinch=0;disable(){this._onResizeScreenFn&&(window.removeEventListener("resize",this._onResizeScreenFn),this._onResizeScreenFn=void 0),this._onKeyUpFn&&(window.removeEventListener("keyup",this._onKeyUpFn),this._onKeyUpFn=void 0),this._onMouseWheelFn&&(window.removeEventListener("wheel",this._onMouseWheelFn),this._onMouseWheelFn=void 0)}}class gI extends Wn{set screenAspect(e){this.uniforms.screenAspect.value=e,this.needsUpdate=!0}set offset(e){const t=this.uniforms.offsetScale.value;t.x=e.x,t.y=e.y,this.uniforms.offsetScale.value=t,this.needsUpdate=!0}_offset=new K;get offset(){const e=this.uniforms.offsetScale.value;return this._offset.set(e.x,e.y),this._offset}set zoom(e){const t=this.uniforms.offsetScale.value;e<.001&&(e=.001),t.z=e,this.needsUpdate=!0}get zoom(){return this.uniforms.offsetScale.value.z}reset(){this.offset=this.offset.set(0,0),this.zoom=1,this.needsUpdate=!0}constructor(e){super(),this.uniforms={map:{value:e},screenAspect:{value:1},offsetScale:{value:new ye(0,0,1,1)}},this.vertexShader=`
1362
+ If you need multisampling consider changing 'auto' to a fixed value (e.g. 4).`));else{const e=this.context.time.realtimeSinceStartup-this._multisampleAutoChangeTime;if(this.context.time.realtimeSinceStartup-this._componentEnabledTime>2&&e>.5){const t=this._postprocessing.multisampling;if(this._postprocessing.multisampling>0&&this.context.time.smoothedFps<=50){this._multisampleAutoChangeTime=this.context.time.realtimeSinceStartup,this._multisampleAutoDecreaseTime=this.context.time.realtimeSinceStartup;let i=this._postprocessing.multisampling*.5;i=Math.floor(i),i!=this._postprocessing.multisampling&&(this._postprocessing.multisampling=i),ma&&console.debug(`[PostProcessing] Reduced multisampling from ${t} to ${this._postprocessing.multisampling}`)}else if(e>1&&this.context.time.smoothedFps>=59&&this._postprocessing.multisampling<this.context.renderer.capabilities.maxSamples&&this.context.time.realtimeSinceStartup-this._multisampleAutoDecreaseTime>10){this._multisampleAutoChangeTime=this.context.time.realtimeSinceStartup;let i=this._postprocessing.multisampling<=0?1:this._postprocessing.multisampling*2;i=Math.floor(i),i!==this._postprocessing.multisampling&&(this._postprocessing.multisampling=i),ma&&console.debug(`[PostProcessing] Increased multisampling from ${t} to ${this._postprocessing.multisampling}`)}}}else{const e=Math.max(0,Math.min(this.multisampling,this.context.renderer.capabilities.maxSamples));e!==this._postprocessing.multisampling&&(this._postprocessing.multisampling=e)}if(this.context.mainCamera){const e=this.context.composer.passes;for(const t of e)if(t.mainCamera&&t.mainCamera!==this.context.mainCamera){this.context.composer.setMainCamera(this.context.mainCamera);break}}}}onDestroy(){this._postprocessing?.dispose()}_lastApplyTime;_rapidApplyCount=0;_isDirty=!1;apply(){if(ma&&console.log(`Apply PostProcessing "${this.name||"unnamed"}"`),A()&&(this._lastApplyTime!==void 0&&Date.now()-this._lastApplyTime<100&&(this._rapidApplyCount++,this._rapidApplyCount===5&&console.warn("Detected rapid post processing modifications - this might be a bug",this)),this._lastApplyTime=Date.now()),this._isDirty=!1,this._activeEffects.length=0,this.sharedProfile?.components){const e=this.sharedProfile.components;for(const t of e)t.active&&t.enabled&&!this._activeEffects.includes(t)&&this._activeEffects.push(t)}for(const e of this._effects)e.active&&e.enabled&&!this._activeEffects.includes(e)&&this._activeEffects.push(e);this._activeEffects.length>0?(this._postprocessing||(this._postprocessing=new I0(this.context)),this._postprocessing.apply(this._activeEffects)?.then(()=>{this.activeAndEnabled&&(this._applyPostQueue(),this._postprocessing?(this.multisampling==="auto"?this._postprocessing.multisampling=I.isMobileDevice()?2:4:this._postprocessing.multisampling=Math.max(0,Math.min(this.multisampling,this.context.renderer.capabilities.maxSamples)),ma&&console.debug(`[PostProcessing] Set multisampling to ${this._postprocessing.multisampling} (Is Mobile: ${I.isMobileDevice()})`)):ma&&console.warn("[PostProcessing] No composer found"))})):this._postprocessing?.unapply(!1)}_applyPostQueue(){if(this._modificationQueue){for(const e of this._modificationQueue.values())this.onEditorModification(e);this._modificationQueue.clear()}}onEditorModification(e){if(e.propertyName.startsWith("postprocessing.")){if(!this._postprocessing)return this._modificationQueue||(this._modificationQueue=new Map),this._modificationQueue.set(e.propertyName,e),!0;if(!this._activeEffects?.length)return;const t=e.propertyName.split(".");if(t.length===3||t.length===4){const i=t[1],n=t[2];for(const s of this._activeEffects)if(s.typeName?.toLowerCase()===i.toLowerCase()){if(n==="active"){s.active=e.value,this.scheduleRecreate();return}if(!Hp.has(i)){const r=new Array;Hp.set(i,r);const a=Object.keys(s);for(const l of a)s[l]instanceof z&&r.push(l)}if(Hp.has(i)){const r=n.toLowerCase(),a=Hp.get(i);for(const l of a)if(l.toLowerCase()===r){const c=s[l];c instanceof z&&(t.length===4&&t[3]==="active"?(c.overrideState=e.value,this.scheduleRecreate()):c&&c.value!==void 0&&(c.value=e.value));return}}console.warn("Unknown modification",n);return}}return!0}return!1}_modificationQueue;_recreateId=-1;scheduleRecreate(){const e=++this._recreateId;setTimeout(()=>{e===this._recreateId&&(this.onDisable(),this.onEnable())},200)}}V1([Ye(zp)],$l.prototype,"sharedProfile"),V1([Ye()],$l.prototype,"multisampling");const Hp=new Map;C2($l);async function L0(o){const{NeedleEngineWebComponent:e}=await Promise.resolve().then(()=>YL);e.observedAttributes.includes(o)||e.observedAttributes.push(o)}var sI=Object.defineProperty,St=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&sI(e,t,n),n};const Ct=w("debugsceneswitcher"),rI=w("sceneswitcher:clearscene"),Gp="scene";L0(Gp);const tr=Promise.resolve(!1);class Je extends E{autoLoadFirstScene=!0;scenes=[];loadingScene;queryParameterName="scene";useSceneName=!0;clamp=!0;useHistory=!0;useKeyboard=!0;useSwipe=!0;useSceneLighting=!0;useSceneBackground=!0;preloadNext=1;preloadPrevious=1;preloadConcurrent=2;createMenuButtons=!1;get currentIndex(){return this._currentIndex}get currentLoadingProgress(){return this._currentLoadingProgress}get currentlyLoadingScene(){return this._currentlyLoadingScene}get currentlyLoadedScene(){return this._currentScene}sceneLoadingStart=new ae;sceneLoadingProgress=new ae;sceneLoaded=new ae;_currentIndex=-1;_currentScene=void 0;_currentSceneAsset=void 0;_engineElementOverserver=void 0;_preloadScheduler;_menuButtons;__lastSwitchScene;__lastSwitchScenePromise;awake(){this._currentScene=void 0,this._lastLoadingScene=void 0,this.__lastSwitchScenePromise=void 0,this.scenes===void 0&&(this.scenes=[]);for(const e of this.scenes)e&&!e.hasUrl&&e.asset instanceof M?S.remove(e.asset):e instanceof M&&S.remove(e);Ct&&console.log("SceneSwitcher",this)}async onEnable(){if(globalThis.addEventListener("popstate",this.onPopState),this.context.input.addEventListener(Ae.KeyDown,this.onInputKeyDown),this.context.input.addEventListener(Ae.PointerMove,this.onInputPointerMove),this.context.input.addEventListener(Ae.PointerUp,this.onInputPointerUp),this._engineElementOverserver||(this._engineElementOverserver=new MutationObserver(e=>{for(const t of e)if(t.type==="attributes"&&t.attributeName===Gp){const i=this.context.domElement.getAttribute(Gp);i!==null&&this.trySelectSceneFromValue(i)}})),this._engineElementOverserver.observe(this.context.domElement,{attributes:!0}),this._preloadScheduler||(this._preloadScheduler=new aI(this)),this._preloadScheduler.maxLoadAhead=this.preloadNext,this._preloadScheduler.maxLoadBehind=this.preloadPrevious,this._preloadScheduler.maxConcurrent=this.preloadConcurrent,this._preloadScheduler.begin(2e3),this.autoLoadFirstScene&&this._currentIndex===-1&&!await this.tryLoadFromQueryParam()){const e=this.context.domElement.getAttribute(Gp);(e===null||!await this.trySelectSceneFromValue(e))&&this._currentIndex===-1&&this.select(0)}this.createMenuButtons&&(this._menuButtons??=[],this._menuButtons.push(this.context.menu.appendChild({label:"Previous",icon:"arrow_back_ios",onClick:()=>this.selectPrev(),priority:-1005,class:"row2"})),this._menuButtons.push(this.context.menu.appendChild({label:"Next",icon:"arrow_forward_ios",iconSide:"right",onClick:()=>this.selectNext(),priority:-1e3,class:"row2"})))}onDisable(){if(globalThis.removeEventListener("popstate",this.onPopState),this.context.input.removeEventListener(Ae.KeyDown,this.onInputKeyDown),this.context.input.removeEventListener(Ae.PointerMove,this.onInputPointerMove),this.context.input.removeEventListener(Ae.PointerUp,this.onInputPointerUp),this._preloadScheduler?.stop(),this._menuButtons){for(const e of this._menuButtons)e.remove();this._menuButtons=void 0}}onPopState=async e=>{if(!this.useHistory)return;const t=this.useHistory;try{this.useHistory=!1;let i=!1;if(this.queryParameterName&&(i=await this.tryLoadFromQueryParam()),!i){const n=e?.state;if(n&&n.startsWith(this.guid)){const s=n.substr(this.guid.length+2);Ct&&console.log("PopState",s),await this.trySelectSceneFromValue(s)}}}finally{this.useHistory=t}};normalizedSwipeThresholdX=.1;_didSwipe=!1;onInputPointerMove=e=>{if(this.useSwipe&&!this._didSwipe&&e.button===0&&e.pointerType==="touch"&&this.context.input.getPointerPressedCount()===1){const t=this.context.input.getPointerPositionDelta(e.button);if(t){const i=t.x/this.context.domWidth;i>=this.normalizedSwipeThresholdX?(this._didSwipe=!0,this.selectPrev()):i<=-this.normalizedSwipeThresholdX&&(this._didSwipe=!0,this.selectNext())}}};onInputPointerUp=e=>{e.button===0&&(this._didSwipe=!1)};onInputKeyDown=e=>{if(!this.useKeyboard||!this.scenes)return;const t=e.key.toLowerCase();if(!t)return;const i=parseInt(t)-1;if(i>=0){this.trySelectSceneFromValue(i);return}switch(t){case"arrowright":case"d":this.selectNext();break;case"arrowleft":case"a":this.selectPrev();break}};addScene(e){if(typeof e=="string"){let t=this.context.addressables.findAssetReference(e);return t||(t=new ne(e),this.context.addressables.registerAssetReference(t)),this.scenes.push(t),t}return this.scenes.push(e),e}selectNext(){return this.select(this._currentIndex+1)}selectPrev(){return this.select(this._currentIndex-1)}select(e){if(Ct&&console.log("[SceneSwitcher] select",e),typeof e=="object"&&console.warn('[SceneSwitcher] Switching to "'+e+'" might not work. Please either use an index or a AssetReference (not a scene reference)'),typeof e=="string"){const i=this.scenes?.find(n=>n.url===e);if(!i){const n=ne.getOrCreate(this.sourceId??"",e,this.context);return this.switchScene(n)}if(i)e=this.scenes?.indexOf(i);else return tr}if(!this.scenes?.length)return tr;if(e<0){if(this.clamp)return tr;e=this.scenes.length-1}else if(e>=this.scenes.length){if(this.clamp)return tr;e=0}const t=this.scenes[e];return this.switchScene(t)}unload(){return this.__lastSwitchScene=void 0,this.__lastSwitchScenePromise=void 0,this.__unloadCurrentScene()}async reload(){if(this.__lastSwitchScene){const e=this.__lastSwitchScene;return this.__lastSwitchScene=void 0,this.switchScene(e)}return!1}async switchScene(e){if(!(e instanceof ne)){const t=typeof e;if(t==="string")return this.select(e);if(t==="number")return this.select(e);if(e&&e instanceof M){const i=this.scenes?.indexOf(e);e=new ne(e.name,void 0,e),i>=0&&(this.scenes[i]=e)}else return console.warn(`[SceneSwitcher] Can't switch to scene of type ${t}`),!1}return e.url===this.sourceId?(console.warn("[SceneSwitcher] Can't load own scene - prevent recursive loading",this.sourceId),!1):this.__lastSwitchScene===e&&this.__lastSwitchScenePromise?this.__lastSwitchScenePromise:(this.__lastSwitchScene=e,this.__lastSwitchScenePromise=this.__internalSwitchScene(e),await this.__lastSwitchScenePromise)}async __unloadCurrentScene(){const e=this._currentScene;if(this._currentScene=void 0,e){Ct&&console.log("[SceneSwitcher] UNLOAD",e.url,"HasURL?: "+e.hasUrl);const t=this.tryGetSceneEventListener(e.asset);if(t?.sceneClosing){const i=t.sceneClosing();i instanceof Promise&&await i}e.hasUrl?(e.unload(),this._currentSceneAsset&&Ii(this._currentSceneAsset,!0,!1)):S.remove(this._currentSceneAsset)}}_currentlyLoadingScene;async __internalSwitchScene(e){await this.__unloadCurrentScene();const t=this._currentIndex=this.scenes?.indexOf(e)??-1;try{Ct&&console.debug(`${Date.now()} [SceneSwitcher] Loading scene start: ${e.url} (index: ${t})`),this._currentlyLoadingScene=e,this._currentLoadingProgress=new ProgressEvent("progress",{loaded:0,total:1});const i=new CustomEvent("loadscene-start",{detail:{scene:e,switcher:this,index:t}});this.dispatchEvent(i),this.sceneLoadingStart?.invoke(i.detail),await this.onStartLoading(),await e.loadAssetAsync((s,r)=>{if(Ct){const a=r.loaded/r.total,l="["+"=".repeat(Math.floor(a*20))+"-".repeat(20-Math.floor(a*20))+"]";console.debug(`${Date.now()} [SceneSwitcher] Loading scene progress: ${(a*100).toFixed(1)} % ${l}`,e.url)}this._currentLoadingProgress=r,this.dispatchEvent(r),this.sceneLoadingProgress?.invoke(r)}).catch(console.error),await this.onEndLoading();const n=new CustomEvent("loadscene-finished",{detail:{scene:e,switcher:this,index:t}});if(this.dispatchEvent(n),this._currentLoadingProgress=void 0,this._currentlyLoadingScene=void 0,n.defaultPrevented)return Ct&&console.warn("[SceneSwitcher] Adding loaded scene prevented:",e,n),!1;if(!e.asset)return Ct&&console.warn("[SceneSwitcher] Failed loading scene:",e),!1;if(this._currentIndex===t){if(Ct&&console.log("[SceneSwitcher] ADD",e.url),this._currentScene=e,rI){const a=this.context.mainCameraComponent?.gameObject||this.context.mainCamera;a?.removeFromParent();const l=this.gameObject.removeFromParent();Ii(this.context.scene,!0,!0),this.context.scene=new Hi,this.context.scene.add(l),a&&this.context.scene.add(a)}if(e.asset.parent?this._currentSceneAsset=Ur(e.asset,{parent:this.gameObject}):(this._currentSceneAsset=e.asset,S.add(e.asset,this.gameObject)),this.useSceneLighting&&this.context.sceneLighting.enable(e),this.useSceneBackground){const a=this.context.lightmaps.tryGetSkybox(e.url);a?(a.mapping=Oo,this.context.scene.background=a):Ct&&console.warn("[SceneSwitcher] Can't find skybox for scene "+e.url)}if(this.useHistory&&t>=0){let a=t.toString();if(this.useSceneName&&(e instanceof M?a=e.name:e.url&&(a=$1(e.url))),this.queryParameterName?.length)uc(this.queryParameterName,a,this.useHistory);else{const l=history.state,c=this.guid+"::"+t;l!==c&&history.pushState(c,"unused",location.href)}}const s=this.tryGetSceneEventListener(e.asset);if(s?.sceneOpened){const a=s.sceneOpened(this);a instanceof Promise&&await a}Ct&&console.debug(`${Date.now()} [SceneSwitcher] Loading scene finished: ${e.url} (index: ${t})`);const r=new CustomEvent("scene-opened",{detail:{scene:e,switcher:this,index:t}});return this.dispatchEvent(r),this.sceneLoaded?.invoke(this),!0}}catch(i){console.error(i)}return!1}preload(e){if(e>=0&&e<this.scenes.length){const t=this.scenes[e];if(t instanceof ne)return t.preload()}return tr}tryLoadFromQueryParam(){if(!this.queryParameterName?.length)return tr;const e=w(this.queryParameterName);return typeof e=="boolean"?tr:this.trySelectSceneFromValue(e)}trySelectSceneFromValue(e){if(typeof e=="string"){const t=parseInt(e);if(t>=0&&t<this.scenes.length)return this.select(t);{const i=e.toLowerCase();for(let n=0;n<this.scenes.length;n++){const s=this.scenes[n];if(!!s&&(s instanceof M?s.name:$1(s.url)).toLowerCase().includes(i))return this.select(n)}}}else if(typeof e=="number"&&e>=0&&e<this.scenes.length)return this.select(e);return ki()&&console.warn('[SceneSwitcher] Can not find scene: "'+e+'"',this),tr}_lastLoadingScene=void 0;_loadingScenePromise=void 0;_isCurrentlyLoading=!1;_currentLoadingProgress=void 0;async onStartLoading(){if(this._isCurrentlyLoading=!0,this.loadingScene&&(this._lastLoadingScene!==this.loadingScene&&(this._loadingScenePromise=void 0),this._lastLoadingScene=this.loadingScene,this._loadingScenePromise||(this._loadingScenePromise=this.loadingScene?.loadAssetAsync().then(e=>e!=null)),await this._loadingScenePromise,this._isCurrentlyLoading&&this.loadingScene?.asset)){Ct&&console.log("Add loading scene",this.loadingScene.url,this.loadingScene.asset);const e=this.loadingScene.asset;S.add(e,this.gameObject);const t=this.tryGetSceneEventListener(e);if(t?.sceneOpened){const i=t.sceneOpened(this);i instanceof Promise&&await i}}if(this._isCurrentlyLoading){const e=this.tryGetSceneEventListener(this.gameObject);if(e&&e.sceneOpened){const t=e.sceneOpened(this);t instanceof Promise&&await t}}}async onEndLoading(){if(this._isCurrentlyLoading=!1,this.loadingScene?.asset){Ct&&console.log("Remove loading scene",this.loadingScene.url);const e=this.loadingScene.asset,t=this.tryGetSceneEventListener(e);if(typeof t?.sceneClosing=="function"){const i=t.sceneClosing();i instanceof Promise&&await i}S.remove(e)}if(!this._isCurrentlyLoading){const e=this.tryGetSceneEventListener(this.gameObject);if(e&&e.sceneClosing){const t=e.sceneClosing();t instanceof Promise&&await t}}}tryGetSceneEventListener(e,t=0){if(!e)return null;const i=S.foreachComponent(e,n=>{const s=n;if(s.sceneClosing||s.sceneOpened)return s});if(t===0&&!i&&e.children.length)for(const n of e.children){const s=this.tryGetSceneEventListener(n,t+1);if(s)return s}return i||null}}St([u()],Je.prototype,"autoLoadFirstScene"),St([u(ne)],Je.prototype,"scenes"),St([u(ne)],Je.prototype,"loadingScene"),St([u()],Je.prototype,"queryParameterName"),St([u()],Je.prototype,"useSceneName"),St([u()],Je.prototype,"clamp"),St([u()],Je.prototype,"useHistory"),St([u()],Je.prototype,"useKeyboard"),St([u()],Je.prototype,"useSwipe"),St([u()],Je.prototype,"useSceneLighting"),St([u()],Je.prototype,"useSceneBackground"),St([u()],Je.prototype,"preloadNext"),St([u()],Je.prototype,"preloadPrevious"),St([u()],Je.prototype,"preloadConcurrent"),St([u()],Je.prototype,"createMenuButtons"),St([u(ae)],Je.prototype,"sceneLoadingStart"),St([u(ae)],Je.prototype,"sceneLoadingProgress"),St([u(ae)],Je.prototype,"sceneLoaded");function $1(o){const e=o.split("/").pop()?.split(".").shift();return e?.length?e:o}class aI{maxLoadAhead;maxLoadBehind;maxConcurrent;_isRunning=!1;_switcher;_loadTasks=[];_maxConcurrentLoads=1;constructor(e,t=1,i=1,n=2){this._switcher=e,this.maxLoadAhead=t,this.maxLoadBehind=i,this.maxConcurrent=n}begin(e){if(this._isRunning)return;Ct&&console.log("[SceneSwitcher] Preload scheduled",{delay:e}),this._isRunning=!0;let t=-10,i,n;const s=this._switcher.scenes,r=Date.now()+e,a=setInterval(()=>{if(this.allLoaded()&&(Ct&&console.log("[SceneSwitcher] All scenes (pre-)loaded"),this.stop()),!this._isRunning){clearInterval(a);return}if(Date.now()<r||this.canLoadNewScene()===!1)return;(t===-10||t!==this._switcher.currentIndex)&&(t=this._switcher.currentIndex,n=0,i=0);const l=n%2===0;l&&(i+=1),n+=1;const c=l?this.maxLoadAhead:this.maxLoadBehind;if(i>c)return;const h=l?t+i:t-i;if(!(h<0)&&!(h<0||h>=s.length)&&!this._loadTasks.some(d=>d.index===h)){const d=s[h];Ct&&console.log("[SceneSwitcher] Schedule preload scene",{roomIndex:h,searchForward:l,lastRoom:t,currentIndex:this._switcher.currentIndex,tasks:this._loadTasks.length},d?.url),new lI(h,d,this._loadTasks)}},200)}stop(){this._isRunning=!1}canLoadNewScene(){return this._loadTasks.length<this._maxConcurrentLoads}allLoaded(){if(this._switcher.scenes){for(const e of this._switcher.scenes)if(e?.isLoaded&&e.isLoaded()===!1)return!1}return!0}}class lI{index;asset;tasks;constructor(e,t,i){this.index=e,this.asset=t,this.tasks=i,i.push(this),this.awaitLoading()}async awaitLoading(){this.asset&&!this.asset.isLoaded()&&(Ct&&console.log("[SceneSwitcher] Preload start: "+this.asset.url,this.index),await this.asset.preload(),Ct&&console.log("[SceneSwitcher] Preload finished: "+this.asset.url,this.index));const e=this.tasks.indexOf(this);e>=0&&this.tasks.splice(e,1)}}function cI(){return new Promise((o,e)=>{const t=()=>{t!=null&&(document.removeEventListener("pointerdown",t),document.removeEventListener("click",t),document.removeEventListener("dragstart",t),document.removeEventListener("touchstart",t),o())};document.addEventListener("pointerdown",t),document.addEventListener("click",t),document.addEventListener("dragstart",t),document.addEventListener("touchstart",t)})}async function hI(o){await cI(),o()}var dI=Object.defineProperty,uI=Object.getOwnPropertyDescriptor,zi=(o,e,t,i)=>{for(var n=i>1?void 0:i?uI(e,t):e,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&dI(e,t,n),n};const ot=w("debugvideo");var H1=(o=>(o[o.None=0]="None",o[o.AdjustHeight=1]="AdjustHeight",o[o.AdjustWidth=2]="AdjustWidth",o))(H1||{}),G1=(o=>(o[o.VideoClip=0]="VideoClip",o[o.Url=1]="Url",o))(G1||{}),q1=(o=>(o[o.CameraFarPlane=0]="CameraFarPlane",o[o.CameraNearPlane=1]="CameraNearPlane",o[o.RenderTexture=2]="RenderTexture",o[o.MaterialOverride=3]="MaterialOverride",o))(q1||{});class pt extends E{playOnAwake=!0;aspectMode=0;clip=null;source=1;get url(){return this._url}set url(e){const t=this._url!==e;this.__didAwake?t&&this.setClipURL(e??""):this._url=e}_url=null;renderMode;targetMaterialProperty;targetMaterialRenderer;targetTexture;time=0;_playbackSpeed=1;get playbackSpeed(){return this._videoElement?.playbackRate??this._playbackSpeed}set playbackSpeed(e){this._playbackSpeed=e,this._videoElement&&(this._videoElement.playbackRate=e)}_isLooping=!1;get isLooping(){return this._videoElement?.loop??this._isLooping}set isLooping(e){this._isLooping=e,this._videoElement&&(this._videoElement.loop=e)}get currentTime(){return this._videoElement?.currentTime??this.time}set currentTime(e){this._videoElement?this._videoElement.currentTime=e:this.time=e}get isPlaying(){const e=this._videoElement;return!!(e&&(e.currentTime>0&&!e.paused&&!e.ended&&e.readyState>e.HAVE_CURRENT_DATA||e.srcObject&&e.srcObject.active))}get crossOrigin(){return this._videoElement?.crossOrigin??this._crossOrigin}set crossOrigin(e){this._crossOrigin=e,this._videoElement&&(e!==null?this._videoElement.setAttribute("crossorigin",e):this._videoElement.removeAttribute("crossorigin"))}get videoMaterial(){return!this._videoMaterial&&!this.create(!1)?null:this._videoMaterial}get videoTexture(){return!this._videoTexture&&!this.create(!1)?null:this._videoTexture}get videoElement(){return!this._videoElement&&!this.create(!1)?null:this._videoElement}requestPictureInPicture(){return this._videoElement?this._videoElement.requestPictureInPicture():null}get muted(){return this._videoElement?.muted??this._muted}set muted(e){this._muted=e,this._videoElement&&(this._videoElement.muted=e)}_muted=!1;get currentVideo(){return this.clip}set audioOutputMode(e){e!==this._audioOutputMode&&(e===1&&A()&&console.warn("VideoAudioOutputMode.AudioSource is not yet implemented"),this._audioOutputMode=e,this.updateVideoElementSettings())}get audioOutputMode(){return this._audioOutputMode}_audioOutputMode=2;playInBackground=!0;_crossOrigin="anonymous";_videoElement=null;_videoTexture=null;_videoMaterial=null;_isPlaying=!1;wasPlaying=!1;preloadVideo(){ot&&console.log("Video Preload: "+this.name,this.clip),this.create(!1)}preload(){this.preloadVideo()}setVideo(e){this.clip=e,this.source=0,this._videoElement?(this._videoElement.srcObject=e,this._isPlaying&&this.play(),this.updateAspect()):this.create(this.playOnAwake)}setClipURL(e){this._url!==e&&(this._url=e,this.source=1,ot&&console.log("set url",e),this._videoElement?e.endsWith(".m3u8")||e.includes(".m3u")?this.ensureM3UCanBePlayed():(this._videoElement.src=e,this._isPlaying&&(this.stop(),this.play())):this.create(this.playOnAwake))}onEnable(){ot&&console.log("VideoPlayer.onEnable",G1[this.source],this.clip,this.url,this),window.addEventListener("visibilitychange",this.visibilityChanged),this.playOnAwake===!0?this.create(!0):this.preloadVideo(),this.screenspace?this._overlay?.start():this._overlay?.stop()}onDisable(){window.removeEventListener("visibilitychange",this.visibilityChanged),this._overlay?.stop(),this.pause()}visibilityChanged=e=>{switch(document.visibilityState){case"hidden":this.playInBackground||(this.wasPlaying=this._isPlaying,this.pause());break;case"visible":this.wasPlaying&&!this._isPlaying&&this.play();break}};onDestroy(){this._videoElement&&(this.videoElement?.remove(),this._videoElement=null),this._videoTexture&&(this._videoTexture.dispose(),this._videoTexture=null)}_receivedInput=!1;constructor(){super(),hI(()=>{this._receivedInput=!0,this.updateVideoElementSettings()}),this._targetObjects=[],w("videoscreenspace")&&window.addEventListener("keydown",e=>{e.key==="f"&&(this.screenspace=!this.screenspace)})}play(){if(this._videoElement||this.create(!1),!this._videoElement){ot&&console.warn("Can not play: no video element found",this);return}if(!(this._isPlaying&&!this._videoElement?.ended&&!this._videoElement?.paused)){if(this._isPlaying=!0,this._receivedInput||(this._videoElement.muted=!0),this.handleBeginPlaying(!1),this.shouldUseM3U){this.ensureM3UCanBePlayed();return}ot&&console.log("Video Play()",this.clip,this._videoElement,this.time),this._videoElement.currentTime=this.time,this._videoElement.play().catch(e=>{console.log(e),ot&&console.error("Error playing video",e,"CODE="+e.code,this.videoElement?.src,this),setTimeout(()=>{this._isPlaying&&!this.destroyed&&this.activeAndEnabled&&this.play()},1e3)}),ot&&console.log("play",this._videoElement,this.time)}}stop(){this._isPlaying=!1,this.time=0,this._videoElement&&(this._videoElement.currentTime=0,this._videoElement.pause(),ot&&console.log("STOP",this))}pause(){this.time=this._videoElement?.currentTime??0,this._isPlaying=!1,this._videoElement?.pause(),ot&&console.log("PAUSE",this,this.currentTime)}create(e){let t;switch(this.source){case 0:t=this.clip;break;case 1:t=this.url,!t?.length&&typeof this.clip=="string"&&(t=this.clip);break}return t?(this._videoElement||(ot&&console.warn("Create VideoElement",this),this._videoElement=this.createVideoElement(),this.context.domElement.shadowRoot.prepend(this._videoElement),this.updateVideoElementStyles()),typeof t=="string"?(ot&&console.log("Set Video src",t),this._videoElement.src=t):(ot&&console.log("Set Video srcObject",t),this._videoElement.srcObject=t),this._videoTexture||(this._videoTexture=new YC(this._videoElement)),this._videoTexture.flipY=!1,this._videoTexture.colorSpace=ko,e&&this.handleBeginPlaying(e),ot&&console.log("Video: handle playing done...",t,e),!0):(ot&&console.warn("No video source set",this),!1)}updateAspect(){this.aspectMode!==0&&this.startCoroutine(this.updateAspectImpl())}_overlay=null;get screenspace(){return this._overlay?.enabled??!1}set screenspace(e){if(e){if(!this._videoTexture)return;this._overlay||(this._overlay=new pI(this.context)),this._overlay.add(this._videoTexture)}else this._overlay?.remove(this._videoTexture);this._overlay&&(this._overlay.enabled=e)}_targetObjects;createVideoElement(){const e=document.createElement("video");return this._crossOrigin&&e.setAttribute("crossorigin",this._crossOrigin),ot&&console.log("created video element",e),e}handleBeginPlaying(e){if(!this.activeAndEnabled||!this._videoElement)return;this._targetObjects.length=0;let t=this.gameObject;switch(this.renderMode){case 3:t=this.targetMaterialRenderer?.gameObject,t||(t=S.getComponent(this.gameObject,ei)?.gameObject);break;case 2:console.error("VideoPlayer renderTexture not implemented yet. Please use material override instead");return}if(!t){console.error("Missing target for video material renderer",this.name,q1[this.renderMode],this);return}const i=t.material;if(i){this._targetObjects.push(t),i!==this._videoMaterial&&(this._videoMaterial=i.clone(),t.material=this._videoMaterial);const n="map",s=this._videoMaterial;if(!this.targetMaterialProperty)ot&&s[n]===void 0&&console.warn(`The target material does not have a '${n}' property, video might not render correctly.`),s[n]=this._videoTexture;else switch(this.targetMaterialProperty){default:ot&&s[this.targetMaterialProperty]===void 0&&console.warn(`The target material does not have a '${this.targetMaterialProperty}' property, video might not render correctly.`),s[n]=this._videoTexture;break}}else{console.warn("Can not play video, no material found, this might be a multimaterial case which is not supported yet");return}this.updateVideoElementSettings(),this.updateVideoElementStyles(),e&&(this.shouldUseM3U&&this.ensureM3UCanBePlayed(),this.play())}updateVideoElementSettings(){if(!this._videoElement)return;this._videoElement.loop=this._isLooping,this._videoElement.currentTime=this.currentTime,this._videoElement.playbackRate=this._playbackSpeed,this._videoElement.playsInline=!0;let e=!this._receivedInput||this.audioOutputMode===0;!e&&this._muted&&(e=!0),this._videoElement.muted=e,this.playOnAwake&&(this._videoElement.autoplay=!0)}updateVideoElementStyles(){this._videoElement&&(this._videoElement.style.userSelect="none",this._videoElement.style.visibility="hidden",this._videoElement.style.display="none",this.updateAspect())}_updateAspectRoutineId=-1;*updateAspectImpl(){const e=++this._updateAspectRoutineId,t=void 0,i=this.clip;for(;e===this._updateAspectRoutineId&&this.aspectMode!==0&&this.clip&&i===this.clip&&this._isPlaying;){if(!i||typeof i=="string")return;let n;for(const s of i.getVideoTracks()){const r=s.getSettings();if(r&&r.width&&r.height){n=r.width/r.height;break}else n=this.context.renderer.domElement.clientWidth/this.context.renderer.domElement.clientHeight}if(n===void 0){for(let s=0;s<10;s++)yield;if(!this.isPlaying)break;continue}if(t===n){yield;continue}for(const s of this._targetObjects){let r=1;if(s.parent){const a=$e(s.parent);r=a.x/a.y}switch(this.aspectMode){case 1:s.scale.y=1/n*s.scale.x*r;break;case 2:s.scale.x=n*s.scale.y*r;break}}for(let s=0;s<3;s++)yield}}get shouldUseM3U(){return this.url!=null&&(this.url.endsWith(".m3u8")||this.url.endsWith(".m3u"))&&this.source===1}ensureM3UCanBePlayed(){if(!this.shouldUseM3U)return;let e=document.head.querySelector("script[data-hls_library]");e?globalThis.Hls?this.onHlsAvailable():e.addEventListener("load",this.onHlsAvailable):(ot&&console.log("HLS: load script"),e=document.createElement("script"),e.dataset.hls_library="hls.js",e.src="https://cdn.jsdelivr.net/npm/hls.js@1",e.addEventListener("load",this.onHlsAvailable),document.head.append(e))}_hls;onHlsAvailable=()=>{ot&&console.log("HLS: available",this.clip),!(!this.shouldUseM3U||!this.url)&&(this._hls||(this._hls=new Hls),this.videoElement.autoplay=!0,this._hls.loadSource(this.url),this._hls.attachMedia(this.videoElement),this._videoElement?.play(),ot&&console.log("HLS: loaded",this.clip))}}zi([u()],pt.prototype,"playOnAwake",2),zi([u()],pt.prototype,"aspectMode",2),zi([u(URL)],pt.prototype,"clip",2),zi([u()],pt.prototype,"source",2),zi([u(URL)],pt.prototype,"url",1),zi([u()],pt.prototype,"renderMode",2),zi([u()],pt.prototype,"targetMaterialProperty",2),zi([u(ei)],pt.prototype,"targetMaterialRenderer",2),zi([u(Se)],pt.prototype,"targetTexture",2),zi([u()],pt.prototype,"time",2),zi([u()],pt.prototype,"playbackSpeed",1),zi([u()],pt.prototype,"isLooping",1),zi([u()],pt.prototype,"audioOutputMode",1);class pI{context;constructor(e){this.context=e,this._input=new mI(this)}get enabled(){return this._isInScreenspaceMode}set enabled(e){e?this.start():this.stop()}add(e){this._videos.indexOf(e)===-1&&this._videos.push(e)}remove(e){if(!e)return;const t=this._videos.indexOf(e);t>=0&&this._videos.splice(t,1)}start(){if(this._isInScreenspaceMode||this._videos.length<0)return;const e=this._videos[this._videos.length-1];if(!e)return;if(this._isInScreenspaceMode=!0,!this._screenspaceModeQuad){if(this._screenspaceModeQuad=Ps.createPrimitive(Qa.Quad,{material:new gI(e)}),!this._screenspaceModeQuad)return;this._screenspaceModeQuad.geometry.scale(2,2,2)}const t=this._screenspaceModeQuad;this.context.scene.add(t),this.updateScreenspaceMaterialUniforms();const i=t.material;i?.reset(),this._input?.enable(i)}stop(){this._isInScreenspaceMode=!1,this._screenspaceModeQuad&&(this._input?.disable(),this._screenspaceModeQuad.removeFromParent())}updateScreenspaceMaterialUniforms(){const e=this._screenspaceModeQuad?.material;e&&(e.screenAspect=this.context.domElement.clientWidth/this.context.domElement.clientHeight)}_videos=[];_screenspaceModeQuad;_isInScreenspaceMode=!1;_input}class mI{_onResizeScreenFn;_onKeyUpFn;_onMouseWheelFn;context;overlay;constructor(e){this.overlay=e,this.context=e.context}_material;enable(e){this._material=e,window.addEventListener("resize",this._onResizeScreenFn=()=>{this.overlay.updateScreenspaceMaterialUniforms()}),window.addEventListener("keyup",this._onKeyUpFn=n=>{n.key==="Escape"&&this.overlay.stop()}),window.addEventListener("wheel",this._onMouseWheelFn=n=>{this.overlay.enabled&&(e.zoom+=n.deltaY*5e-4,n.preventDefault())},{passive:!1});const t=new K;window.addEventListener("mousemove",n=>{if(this.overlay.enabled&&this.context.input.getPointerPressed(0)){const s=new K(n.movementX,n.movementY);s.x/=this.context.domElement.clientWidth,s.y/=this.context.domElement.clientHeight,t.set(s.x,s.y),t.multiplyScalar(e.zoom/-this.context.time.deltaTime*.01),e.offset=e.offset.add(t)}}),window.addEventListener("pointermove",n=>{this.overlay.enabled&&this.context.input.getPointerPressed(0)&&this.context.input.getTouchesPressedCount()===1&&(t.set(n.movementX,n.movementY),t.multiplyScalar(e.zoom*-this.context.time.deltaTime*.05),e.offset=e.offset.add(t))});let i=0;window.addEventListener("touchstart",n=>{if(n.touches.length<2){this.context.time.time-i<.3&&this.overlay.stop(),i=this.context.time.time;return}this._isPinching=!0,this._lastPinch=0}),window.addEventListener("touchmove",n=>{if(!this._isPinching||!this._material)return;const s=n.touches[0],r=n.touches[1],a=s.clientX-r.clientX,l=s.clientY-r.clientY,c=Math.sqrt(a*a+l*l);if(this._lastPinch!==0){const h=c-this._lastPinch;this._material.zoom-=h*.004}this._lastPinch=c}),window.addEventListener("touchend",()=>{this._isPinching=!1})}_isPinching=!1;_lastPinch=0;disable(){this._onResizeScreenFn&&(window.removeEventListener("resize",this._onResizeScreenFn),this._onResizeScreenFn=void 0),this._onKeyUpFn&&(window.removeEventListener("keyup",this._onKeyUpFn),this._onKeyUpFn=void 0),this._onMouseWheelFn&&(window.removeEventListener("wheel",this._onMouseWheelFn),this._onMouseWheelFn=void 0)}}class gI extends Wn{set screenAspect(e){this.uniforms.screenAspect.value=e,this.needsUpdate=!0}set offset(e){const t=this.uniforms.offsetScale.value;t.x=e.x,t.y=e.y,this.uniforms.offsetScale.value=t,this.needsUpdate=!0}_offset=new K;get offset(){const e=this.uniforms.offsetScale.value;return this._offset.set(e.x,e.y),this._offset}set zoom(e){const t=this.uniforms.offsetScale.value;e<.001&&(e=.001),t.z=e,this.needsUpdate=!0}get zoom(){return this.uniforms.offsetScale.value.z}reset(){this.offset=this.offset.set(0,0),this.zoom=1,this.needsUpdate=!0}constructor(e){super(),this.uniforms={map:{value:e},screenAspect:{value:1},offsetScale:{value:new ye(0,0,1,1)}},this.vertexShader=`
1363
1363
  uniform sampler2D map;
1364
1364
  uniform float screenAspect;
1365
1365
  uniform vec4 offsetScale;
@@ -1423,7 +1423,7 @@ If you need multisampling consider changing 'auto' to a fixed value (e.g. 4).`))
1423
1423
  // be blended onto the scene.
1424
1424
  gl_FragColor = vec4(direct, max);
1425
1425
  return;
1426
- `)},e.userData.isLightBlendMaterial=!0}applyShadowMaterial(){if(this.targetMesh)if(this.targetMesh.material.type!=="ShadowMaterial"){const e=new mb;e.color=this.shadowColor,e.opacity=this.shadowColor.alpha,this.applyMaterialOptions(e),this.targetMesh.material=e,e.userData.isShadowCatcherMaterial=!0}else{const e=this.targetMesh.material;e.color=this.shadowColor,e.opacity=this.shadowColor.alpha,this.applyMaterialOptions(e),e.userData.isShadowCatcherMaterial=!0}}applyOccluderMaterial(){if(this.targetMesh){let e=this.targetMesh.material;if(!e){const t=new Ce;this.targetMesh.material=t,e=t}e.depthWrite=!0,e.stencilWrite=!0,e.colorWrite=!1,this.gameObject.renderOrder=-100}}applyMaterialOptions(e){e&&(e.depthWrite=!1,e.stencilWrite=!1)}}Q1([u()],Uh.prototype,"mode"),Q1([u(se)],Uh.prototype,"shadowColor");var xI=Object.defineProperty,zh=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&xI(e,t,n),n};const oi=w("debugskybox");L0("background-image"),L0("environment-image");const Y1={studio:{url:"https://cdn.needle.tools/static/skybox/modelviewer-Neutral.pmrem4x4.ktx2?pmrem",url_low:"https://cdn.needle.tools/static/skybox/modelviewer-Neutral-small.pmrem4x4.ktx2?pmrem"},"blurred-skybox":{url:"https://cdn.needle.tools/static/skybox/blurred-skybox.pmrem4x4.ktx2?pmrem",url_low:"https://cdn.needle.tools/static/skybox/blurred-skybox-small.pmrem4x4.ktx2?pmrem"},"quicklook-ar":{url:"https://cdn.needle.tools/static/skybox/QuickLook-ARMode.pmrem4x4.ktx2?pmrem",url_low:"https://cdn.needle.tools/static/skybox/QuickLook-ARMode-small.pmrem4x4.ktx2?pmrem"},quicklook:{url:"https://cdn.needle.tools/static/skybox/QuickLook-ObjectMode.pmrem4x4.ktx2?pmrem",url_low:"https://cdn.needle.tools/static/skybox/QuickLook-ObjectMode-small.pmrem4x4.ktx2?pmrem"}};function Z1(o,e,t,i,n){if(e==="transparent"||e?.startsWith("rgb")||e?.startsWith("#"))return console.warn(`Needle Engine: Invalid ${n} value (${e}). Did you mean to set background-color instead?`),null;const s=new Xp;s.sourceId=n_(e),s.allowDrop=!1,s.allowNetworking=!1,s.background=t,s.environment=i,S.addComponent(o.scene,s);const r=a=>{if(oi&&console.log(n,"CHANGED TO",a),a){if(typeof a!="string"){console.warn("Invalid attribute value for "+n);return}s.setSkybox(a)}else if(s.sourceId&&(i&&(o.sceneLighting.internalEnableReflection(s.sourceId)||(o.scene.environment=null)),t)){const l=o.lightmaps.tryGetSkybox(s.sourceId);o.scene.background=l}};return Xm(o.domElement,n,r),s.addEventListener("destroy",()=>{oi&&console.log("Destroyed attribute remote skybox",n),Qm(o.domElement,n,r)}),s.setSkybox(e)}const qp=new Array;pe.registerCallback(ue.ContextCreationStart,o=>{const e=o.context,t=e.domElement.getAttribute("background-image"),i=e.domElement.getAttribute("environment-image");if(t){oi&&console.log("Creating RemoteSkybox to load background "+t);const n=Z1(e,t,!0,!1,"background-image");n&&qp.push(n)}if(i){oi&&console.log("Creating RemoteSkybox to load environment "+i);const n=Z1(e,i,!1,!0,"environment-image");n&&qp.push(n)}}),pe.registerCallback(ue.ContextCreationStart,()=>Promise.all(qp).finally(()=>{qp.length=0}));const ga=class extends E{url="studio";allowDrop=!0;background=!0;environment=!0;allowNetworking=!0;_prevUrl;_prevLoadedEnvironment;_prevEnvironment=null;_prevBackground=null;onEnable(){this.setSkybox(this.url),this.registerDropEvents()}onDisable(){this.context.scene.environment===this._prevLoadedEnvironment&&(this.context.scene.environment=this._prevEnvironment,gi.backgroundShouldBeTransparent(this.context)||(this.context.scene.background=this._prevBackground),this._prevLoadedEnvironment=void 0),this.unregisterDropEvents(),this.context.mainCameraComponent?.applyClearFlags()}urlChangedSyncField(){this.allowNetworking&&this.url&&(this.isRemoteTexture(this.url)?this.setSkybox(this.url):oi&&console.warn(`RemoteSkybox: Not setting skybox: ${this.url} is not a remote texture. If you want to set a local texture, set allowNetworking to false.`))}async setSkybox(o,e){if(!this.activeAndEnabled||(o=SI(o,this.environment,this.background),!o))return!1;if(e??=o,this.isValidTextureType(e)||console.warn('Potentially invalid skybox URL: "'+e+'" on '+(this.name||this.gameObject?.name||"context")),oi&&console.log("Set RemoteSkybox url: "+o),this._prevUrl===o&&this._prevLoadedEnvironment)return this.apply(),!0;this._prevLoadedEnvironment?.dispose(),this._prevLoadedEnvironment=void 0,this._prevUrl=o;const t=await ay(o,this.context.renderer);return t?!this.enabled||this.destroyed?(oi&&console.warn("RemoteSkybox: Component is disabled or destroyed"),!1):this._prevUrl!==o?(oi&&console.warn("RemoteSkybox: URL changed while loading texture, aborting setSkybox"),!1):(this.url=o,this._prevLoadedEnvironment=t,this.apply(),!0):(oi&&console.warn("RemoteSkybox: Failed to load texture from url",o),!1)}apply(){const o=this._prevLoadedEnvironment;if(o&&(o instanceof Pb||o instanceof ZC||o.mapping==Cb||(o.mapping=KC,o.needsUpdate=!0),!this.destroyed)){if(!this.context){console.warn("RemoteSkybox: Context is not available - can not apply skybox.");return}this.context.scene.background!==o&&(this._prevBackground=this.context.scene.background),this.context.scene.environment!==o&&(this._prevEnvironment=this.context.scene.environment),oi&&console.log("Set RemoteSkybox ("+(this.environment&&this.background?"environment and background":this.environment?"environment":this.background?"background":"none")+")",this.url,!gi.backgroundShouldBeTransparent(this.context)),this.environment&&(this.context.scene.environment=o),this.background&&!gi.backgroundShouldBeTransparent(this.context)&&(this.context.scene.background=o),this.context.mainCameraComponent?.backgroundBlurriness!==void 0&&(this.context.scene.backgroundBlurriness=this.context.mainCameraComponent.backgroundBlurriness)}}validProtocols=["file:","blob:","data:"];validTextureTypes=[".ktx2",".hdr",".exr",".jpg",".jpeg",".png"];isRemoteTexture(o){return o.startsWith("http://")||o.startsWith("https://")}isValidTextureType(o){for(const e of this.validTextureTypes)if(o.includes(e))return!0;for(const e of this.validProtocols)if(o.startsWith(e))return!0;return!1}registerDropEvents(){this.unregisterDropEvents(),this.context.domElement.addEventListener("dragover",this.onDragOverEvent),this.context.domElement.addEventListener("drop",this.onDrop)}unregisterDropEvents(){this.context.domElement.removeEventListener("dragover",this.onDragOverEvent),this.context.domElement.removeEventListener("drop",this.onDrop)}onDragOverEvent=o=>{if(this.allowDrop&&o.dataTransfer)for(const e of o.dataTransfer.types)(e==="text/uri-list"||e==="Files")&&o.preventDefault()};onDrop=o=>{if(this.allowDrop&&o.dataTransfer){for(const e of o.dataTransfer.types)if(oi&&console.log(e),e==="text/uri-list"){const t=o.dataTransfer.getData(e);oi&&console.log(e,t);let i=new RegExp(/polyhaven.com\/asset_img\/.+?\/(?<name>.+)\.png/).exec(t)?.groups?.name;if(i||(i=new RegExp(/polyhaven\.com\/a\/(?<name>.+)/).exec(t)?.groups?.name),oi&&console.log(i),i){const n="https://dl.polyhaven.org/file/ph-assets/HDRIs/exr/1k/"+i+"_1k.exr";console.log(`[Remote Skybox] Setting skybox from url: ${n}`),o.preventDefault(),this.setSkybox(n);break}else if(this.isValidTextureType(t)){console.log("[Remote Skybox] Setting skybox from url: "+t),o.preventDefault(),this.setSkybox(t);break}else{console.warn(`[RemoteSkybox] Unknown url ${t}. If you want to load a skybox from a url, make sure it is a valid image url. Url must end with${this.validTextureTypes.join(", ")}.`);const n=new CustomEvent("dropped-unknown-url",{detail:{sender:this,event:o,url:t,apply:s=>{o.preventDefault(),this.setSkybox(s)}}});this.dispatchEvent(n)}}else if(e=="Files"){const t=o.dataTransfer.files.item(0);if(oi&&console.log(e,t),!t)continue;if(!this.isValidTextureType(t.name)){console.warn(`[RemoteSkybox]: File "${t.name}" is not supported. Supported files are ${this.validTextureTypes.join(", ")}`);return}o.preventDefault(),this.setSkybox(t.name);break}}}};zh([Uy(ga.prototype.urlChangedSyncField),u(URL)],ga.prototype,"url"),zh([u()],ga.prototype,"allowDrop"),zh([u()],ga.prototype,"background"),zh([u()],ga.prototype,"environment"),zh([u()],ga.prototype,"allowNetworking");let Xp=ga;function SI(o,e,t){if(o==null)return null;const i=e&&!t,n=Y1[o.toLowerCase()];return n?i?n.url_low:n.url:(typeof o=="string"&&o?.length&&(A()||oi)&&(o.includes("/")||o.includes(".")||console.warn(`RemoteSkybox: Unknown magic skybox name "${o}". Valid names are: ${Object.keys(Y1).map(s=>`"${s}"`).join(", ")}`)),o)}var CI=Object.defineProperty,Qp=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&CI(e,t,n),n};const Nh=class VS extends E{target=null;followFactor=.1;rotateFactor=.1;positionAxes=cl.All;flipForward=!1;static _invertForward=new N().setFromAxisAngle(new b(0,1,0),Math.PI);_firstUpdate=!0;onBeforeRender(){this.updateNow(!1)}updateNow(e){if(!(!this.target||this.target===this.gameObject)){if(this.followFactor>0){const t=ee(this.target),i=this._firstUpdate||e?1:j.clamp01(this.context.time.deltaTime*this.followFactor),n=this.worldPosition;this.positionAxes&cl.X&&(n.x=j.lerp(n.x,t.x,i)),this.positionAxes&cl.Y&&(n.y=j.lerp(n.y,t.y,i)),this.positionAxes&cl.Z&&(n.z=j.lerp(n.z,t.z,i)),this.worldPosition=n}if(this.rotateFactor>0){const t=_e(this.target);this.flipForward&&t.premultiply(VS._invertForward);const i=this._firstUpdate||e?1:j.clamp01(this.context.time.deltaTime*this.rotateFactor);this.worldQuaternion=this.worldQuaternion.slerp(t,i)}this._firstUpdate=!1}}};Qp([u(M)],Nh.prototype,"target"),Qp([u()],Nh.prototype,"followFactor"),Qp([u()],Nh.prototype,"rotateFactor"),Qp([u()],Nh.prototype,"positionAxes");let Yp=Nh;var PI=Object.defineProperty,Wh=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&PI(e,t,n),n};const Vh=w("debugspatialtrigger"),K1=new bs,J1=new bs;function OI(o,e){return K1.mask=o,J1.mask=e,K1.test(J1)}class po extends E{triggerMask=0;onEnter;onStay;onExit;start(){Vh&&console.log(this.name,this.triggerMask,this)}update(){this.currentIntersected.length=0;for(const e of Zp.triggers)OI(e.triggerMask,this.triggerMask)&&e.test(this.gameObject)&&this.currentIntersected.push(e);for(let e=this.lastIntersected.length-1;e>=0;e--){const t=this.lastIntersected[e];this.currentIntersected.indexOf(t)<0&&(this.onExitTrigger(t),this.lastIntersected.splice(e,1))}for(const e of this.currentIntersected)this.lastIntersected.indexOf(e)<0&&this.onEnterTrigger(e),this.onStayTrigger(e);this.lastIntersected.length=0,this.lastIntersected.push(...this.currentIntersected)}currentIntersected=[];lastIntersected=[];onEnterTrigger(e){Vh&&console.log("ENTER TRIGGER",this.name,e.name,this,e),e.raiseOnEnterEvent(this),this.onEnter?.invoke()}onExitTrigger(e){Vh&&console.log("EXIT TRIGGER",this.name,e.name),e.raiseOnExitEvent(this),this.onExit?.invoke()}onStayTrigger(e){e.raiseOnStayEvent(this),this.onStay?.invoke()}}Wh([u()],po.prototype,"triggerMask"),Wh([u(ae)],po.prototype,"onEnter"),Wh([u(ae)],po.prototype,"onStay"),Wh([u(ae)],po.prototype,"onExit");const eS=class _m extends E{static triggers=[];triggerMask;boxHelper;start(){Vh&&console.log(this.name,this.triggerMask,this)}onEnable(){_m.triggers.push(this),this.boxHelper||(this.boxHelper=S.addComponent(this.gameObject,Pt),this.boxHelper?.showHelper(null,Vh))}onDisable(){_m.triggers.splice(_m.triggers.indexOf(this),1)}test(e){return this.boxHelper?this.boxHelper.isInBox(e)??!1:!1}raiseOnEnterEvent(e){S.foreachComponent(this.gameObject,t=>{t!==e&&t instanceof po&&t.onEnterTrigger(this)},!1)}raiseOnStayEvent(e){S.foreachComponent(this.gameObject,t=>{t!==e&&t instanceof po&&t.onStayTrigger(this)},!1)}raiseOnExitEvent(e){S.foreachComponent(this.gameObject,t=>{t!==e&&t instanceof po&&t.onExitTrigger(this)},!1)}};Wh([u()],eS.prototype,"triggerMask");let Zp=eS;var kI=Object.defineProperty,MI=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&kI(e,t,n),n};const Ni=w("debugspectator");class Kp extends E{cam=null;useKeys=!0;_mode=0;get mode(){return this._mode}set mode(e){this._mode=e}get isSpectating(){return this._handler?.currentTarget!==void 0}isSpectatingUser(e){return this.target?.userId===e}isFollowedBy(e){return this.followers?.includes(e)}get followers(){return this._networking.followers}stopSpectating(){if(this.context.isInXR){this.followSelf();return}this.target=void 0}get localId(){return this.context.connection.connectionId??"local"}set target(e){if(this._handler){const t=this._handler.currentTarget?.userId,i=this.context.players.getPlayerView(this.localId);e===void 0||this.context.isInXR===!1&&i?.currentObject===e.currentObject?this._handler.currentTarget!==void 0&&(this._handler.disable(),S.setActive(this.gameObject,!1),this.orbit&&(this.orbit.enabled=!0),this._networking.onSpectatedObjectChanged(e,t)):this._handler.currentTarget!==e&&(this._handler.set(e),S.setActive(this.gameObject,!0),this.orbit&&(this.orbit.enabled=!1),this._networking.onSpectatedObjectChanged(e,t))}}get target(){return this._handler?.currentTarget}requestAllFollowMe(){this._networking.onRequestFollowMe()}get isSpectatingSelf(){return this.isSpectating&&this.target?.currentObject===this.context.players.getPlayerView(this.localId)?.currentObject}orbit=null;_handler;eventSub_WebXRRequestStartEvent=null;eventSub_WebXRStartEvent=null;eventSub_WebXREndEvent=null;_debug;_networking;awake(){if(this._debug=new TI(this.context,this),this._networking=new LI(this.context,this),this._networking.awake(),S.setActive(this.gameObject,!1),this.cam=S.getComponent(this.gameObject,gi),!this.cam){console.warn("SpectatorCamera: Spectator camera needs camera component on the same object.",this);return}!this._handler&&this.cam&&(this._handler=new EI(this.context,this.cam,this)),this.orbit=S.getComponent(this.context.mainCamera,ge)}onDestroy(){this.stopSpectating(),this._handler?.destroy(),this._networking?.destroy()}isSupportedPlatform(){const e=window.navigator.userAgent,t=/Windows NT/.test(e)&&/Edg/.test(e)&&!/Win64/.test(e);return I.isDesktop()&&!I.isMobileDevice()&&!t}onBeforeXR(e){this.isSupportedPlatform()&&S.setActive(this.gameObject,!0)}onEnterXR(e){this.isSupportedPlatform()&&(Ni&&console.log(this.context.mainCamera),this.context.mainCamera&&this.followSelf())}onLeaveXR(e){this.context.removeCamera(this.cam),S.setActive(this.gameObject,!1),this._handler?.set(void 0),this._handler?.disable(),this.isSpectatingSelf&&this.stopSpectating(),this.orbit&&(this.orbit.enabled=!0)}followSelf(){this.target=this.context.players.getPlayerView(this.context.connection.connectionId),this.target||(this.context.players.setPlayerView(this.localId,this.context.mainCamera,Fo.Headset),this.target=this.context.players.getPlayerView(this.localId)),Ni&&console.log("Follow self",this.target)}onAfterRender(){if(!this.cam)return;const e=this.context.renderer,t=e.xr.enabled;if(!e.xr.isPresenting&&!this._handler?.currentTarget)return;this._handler?.update(this._mode);const i=e.getRenderTarget();let n=null;const s=e.state;if(!i||i.isXRRenderTarget===!0){if(!e.state.bindFramebuffer||!s.bindXRFramebuffer)return;n=e._framebuffer,s.bindXRFramebuffer(null)}this.setAvatarFlagsBeforeRender();const r=this.context.mainCameraComponent;if(r){const c=r.backgroundColor;c&&e.setClearColor(c,c.alpha),this.cam.backgroundColor=c,this.cam.clearFlags=r.clearFlags,this.cam.nearClipPlane=r.nearClipPlane,this.cam.farClipPlane=r.farClipPlane}else e.setClearColor(new oe(1,1,1));e.setRenderTarget(null),e.xr.enabled=!1;const a=this.cam?.threeCamera;this.context.updateAspect(a);const l=e.xr.isPresenting;e.xr.isPresenting=!1,e.setSize(this.context.domWidth,this.context.domHeight),e.render(this.context.scene,a),e.xr.isPresenting=l,e.xr.enabled=t,i?e.setRenderTarget(i):s.bindXRFramebuffer&&s.bindXRFramebuffer(n),this.resetAvatarFlags()}setAvatarFlagsBeforeRender(){const e=this._mode===0;for(const t of Le.instances)if(t.avatar&&"isLocalAvatar"in t.avatar&&"flags"in t.avatar){let i=io.All;this.isSpectatingSelf&&(i=e&&t.avatar.isLocalAvatar?io.FirstPerson:io.ThirdPerson);const n=t.avatar.flags;if(!n)continue;for(const s of n)s.UpdateVisible(i)}}resetAvatarFlags(){for(const e of Le.instances)if(e.avatar&&"flags"in e.avatar){const t=e.avatar.flags;if(!t)continue;for(const i of t)"isLocalAvatar"in e.avatar&&e.avatar?.isLocalAvatar?i.UpdateVisible(io.FirstPerson):i.UpdateVisible(io.ThirdPerson)}}}MI([u()],Kp.prototype,"useKeys");class EI{context;cam;spectator;follow;target;view;currentObject;get currentTarget(){return this.view}constructor(e,t,i){this.context=e,this.cam=t,this.spectator=i}set(e){const t=e?.currentObject;if(!t){this.spectator.stopSpectating();return}t!==this.currentObject&&(this.currentObject=t,this.view=e,this.follow||(this.follow=S.addComponent(this.cam.gameObject,Yp)),this.target||(this.target=new M),t.add(this.target),this.follow.enabled=!0,this.follow.target=this.target,Ni&&console.log("FOLLOW",t),this.context.isInXR?this.context.removeCamera(this.cam):this.context.setCurrentCamera(this.cam))}disable(){Ni&&console.log("STOP FOLLOW",this.currentObject),this.view=void 0,this.currentObject=void 0,this.context.removeCamera(this.cam),this.follow&&(this.follow.enabled=!1)}destroy(){this.target?.removeFromParent(),this.follow&&S.destroy(this.follow)}update(e){if(this.currentTarget?.isConnected===!1||this.currentTarget?.removed===!0){Ni&&console.log("Target disconnected or timeout",this.currentTarget),this.spectator.stopSpectating();return}this.currentTarget&&this.currentTarget?.currentObject!==this.currentObject&&(Ni&&console.log("Target changed",this.currentObject,"to",this.currentTarget.currentObject),this.set(this.currentTarget));const t=this.context.mainCamera;if(t){const n=this.cam.threeCamera;(n.near!==t.near||n.far!==t.far)&&(n.near=t.near,n.far=t.far,n.updateProjectionMatrix())}const i=this.follow?.target;if(!(!i||!this.follow)){switch(e){case 0:this.view?.viewDevice!==Fo.Browser?(this.follow.followFactor=5,this.follow.rotateFactor=5):(this.follow.followFactor=50,this.follow.rotateFactor=50),i.position.set(0,0,0);break;case 1:this.follow.followFactor=3,this.follow.rotateFactor=2,i.position.set(0,.5,1.5);break}this.follow.flipForward=!1,this.view?.viewDevice!==Fo.Browser?i.quaternion.copy(RI):i.quaternion.identity()}}}const RI=new N().setFromAxisAngle(new b(0,1,0),Math.PI);class TI{context;spectator;constructor(e,t){this.context=e,this.spectator=t,console.log("[Spectator Camera] Click other avatars or cameras to follow them. Press ESC to exit spectator mode."),this.context.domElement.addEventListener("keydown",n=>{!this.spectator.useKeys||n.key==="Escape"&&this.spectator.stopSpectating()});let i=0;this.context.input.addEventListener(Ae.PointerDown,n=>{i=this.context.time.time}),this.context.input.addEventListener(Ae.PointerUp,n=>{const s=this.context.time.time-i;s>1?this.spectator.stopSpectating():this.context.input.getPointerClicked(0)&&s<.3&&this.trySelectObject()})}trySelectObject(){const e=new Os;e.setMask(16777215);const t=this.context.physics.raycast(e);if(Ni&&console.log(...t),t?.length)for(const i of t){if(i.distance<.2)continue;const n=i.object,s=sn.getFor(n);let r=s?.owner;if(r||(r=S.getComponentInParent(n,Le)?.connectionId),r){const a=this.context.players.getPlayerView(r);this.spectator.target=a,Ni&&console.log("spectate",r,s);break}}}}class AI{guid;dontSave=!0;targetUserId;stoppedFollowing;constructor(e,t,i){this.guid=e,this.targetUserId=t,this.stoppedFollowing=i}}class II{guid;userId;constructor(e,t){this.guid=e.guid,this.userId=t}}class LI{followers=[];context;spectator;_followerEventMethod;_requestFollowMethod;_joinedRoomMethod;constructor(e,t){this.context=e,this.spectator=t,this._followerEventMethod=this.onFollowerEvent.bind(this),this._requestFollowMethod=this.onRequestFollowEvent.bind(this),this._joinedRoomMethod=this.onUserJoinedRoom.bind(this)}awake(){this.context.connection.beginListen("spectator-follower-changed",this._followerEventMethod),this.context.connection.beginListen("spectator-request-follow",this._requestFollowMethod),this.context.connection.beginListen(ie.JoinedRoom,this._joinedRoomMethod),this.context.domElement.addEventListener("keydown",e=>{this.spectator.useKeys&&(e.key==="f"?this.onRequestFollowMe():e.key==="Escape"&&this.onRequestFollowMe(!0))})}destroy(){this.context.connection.stopListen("spectator-follower-changed",this._followerEventMethod),this.context.connection.stopListen("spectator-request-follow",this._requestFollowMethod),this.context.connection.stopListen(ie.JoinedRoom,this._joinedRoomMethod)}onSpectatedObjectChanged(e,t){if(Ni&&console.log(this.context.connection.connectionId,"onSpectatedObjectChanged",e,t),this.context.connection.connectionId){const i=e?.userId===void 0,n=i?t:e?.userId,s=new AI(this.context.connection.connectionId,n,i);this.context.connection.send("spectator-follower-changed",s)}}onRequestFollowMe(e=!1){if(Ni&&console.log("Request follow",this.context.connection.connectionId),this.context.connection.connectionId){this.spectator.stopSpectating();const t=e?void 0:this.context.connection.connectionId,i=new II(this.spectator,t);this.context.connection.send("spectator-request-follow",i)}}onUserJoinedRoom(){w("followme")&&this.onRequestFollowMe()}onFollowerEvent(e){const t=e.targetUserId,i=e.guid;if(Ni&&console.log(e),t===this.context.connection.connectionId)if(e.stoppedFollowing){const n=this.followers.indexOf(i);n!==-1&&(this.followers.splice(n,1),this.removeDisconnectedFollowers(),console.log(i,"unfollows you",this.followers.length))}else this.followers.includes(i)||(this.followers.push(i),this.removeDisconnectedFollowers(),console.log(i,"follows you",this.followers.length))}removeDisconnectedFollowers(){for(let e=this.followers.length-1;e>=0;e--){const t=this.followers[e];this.context.connection.userIsInRoom(t)===!1&&this.followers.splice(e,1)}}_lastRequestFollowUser;onRequestFollowEvent(e){if(this._lastRequestFollowUser=e,e.userId===this.context.connection.connectionId)this.spectator.stopSpectating();else if(e.userId===void 0)this.spectator.stopSpectating();else{const t=this.context.players.getPlayerView(e.userId);if(t)this.spectator.target=t;else return Ni&&console.warn("Could not find view",e.userId),this.enforceFollow(),!1}return!0}_enforceFollowInterval;enforceFollow(){this._enforceFollowInterval||(this._enforceFollowInterval=setInterval(()=>{this._lastRequestFollowUser===void 0||this._lastRequestFollowUser.userId&&this.spectator.isFollowedBy(this._lastRequestFollowUser.userId)?(clearInterval(this._enforceFollowInterval),this._enforceFollowInterval=void 0):(Ni&&console.log("REQUEST FOLLOW AGAIN",this._lastRequestFollowUser.userId),this.onRequestFollowEvent(this._lastRequestFollowUser))},1e3))}}var DI=Object.defineProperty,jI=Object.getOwnPropertyDescriptor,Gl=(o,e,t,i)=>{for(var n=i>1?void 0:i?jI(e,t):e,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&DI(e,t,n),n};const tS=w("debugsplines");class mo{position=new b;rotation=new N;tangentIn=new b;tangentOut=new b}Gl([Qe(b)],mo.prototype,"position",2),Gl([Qe(N)],mo.prototype,"rotation",2),Gl([Qe(b)],mo.prototype,"tangentIn",2),Gl([Qe(b)],mo.prototype,"tangentOut",2);class fa extends E{addKnot(e){if(e instanceof mo)this.spline.push(e),this._isDirty=!0;else{const t=new mo;t.position.copy(e.position),this.spline.push(t),this._isDirty=!0}return this}removeKnot(e){if(typeof e=="number")this.spline.splice(e,1),this._isDirty=!0;else{const t=this.spline.indexOf(e);t!==-1&&(this.spline.splice(t,1),this._isDirty=!0)}return this}getPointAt(e,t){if(!this.curve)return new b;const i=this.curve.getPointAt(j.clamp01(e),t),n=this.gameObject.matrixWorld??void 0;return n&&i.applyMatrix4(n),i}markDirty(){this._isDirty=!0}getTangentAt(e,t){if(!this.curve)return t??new b;const i=this.gameObject.worldQuaternion;return this.curve.getTangentAt(j.clamp01(e),t).applyQuaternion(i)}set closed(e){this._closed=e,this._isDirty=!0}get closed(){return this._closed}_closed=!1;spline=[];set debug(e){e&&!this._builtCurve&&this.buildCurve(),this._debugLine&&(this._debugLine.visible=e)}get curve(){return this._curve}get isDirty(){return this._isDirty}_isDirty=!1;_curve=null;_builtCurve=!1;_debugLine=null;awake(){tS&&(console.log(`[Spline] ${this.name}`,this),this.buildCurve())}update(){this._isDirty&&this.buildCurve(!0),this._debugLine&&this._debugLine.parent!==this.gameObject&&this.gameObject.add(this._debugLine)}buildCurve(e=!1){if(!(this._builtCurve&&!e)){if(this._builtCurve=!0,!this.spline){console.error("[Spline] Can not build curve, no spline data",this.name);return}this._isDirty=!1,this._curve=BI(this.spline,this.closed),this.buildDebugCurve()}}buildDebugCurve(){if(tS&&this.spline&&this._curve){this._debugLine?.removeFromParent(),this._debugLine=null;const e=new km({color:6684927}),t=this.spline.length*10,i=this._curve.getPoints(t),n=new wn().setFromPoints(i);this._debugLine=new Ia(n,e),this.gameObject?.add(this._debugLine)}}}Gl([Qe()],fa.prototype,"closed",1),Gl([Qe(mo)],fa.prototype,"spline",2);function BI(o,e){const t=o.map(s=>new b(-s.position.x,s.position.y,s.position.z));t.length===1&&t.push(t[0]);const i=o.reduce((s,r)=>s+Math.abs(r.tangentOut.x)+Math.abs(r.tangentOut.y)+Math.abs(r.tangentOut.z),0)/o.length,n=j.remap(i,0,.3,0,.5);return new JC(t,e,"catmullrom",n)}var FI=Object.defineProperty,UI=Object.getOwnPropertyDescriptor,nr=(o,e,t,i)=>{for(var n=i>1?void 0:i?UI(e,t):e,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&FI(e,t,n),n};class hn extends E{spline=null;object=void 0;useLookAt=!0;lookAt=null;clamp=!1;get position01(){return this._position01}set position01(e){this._position01=e,this._needsUpdate=!0}reset(){this._position01=0}autoRun=!0;duration=10;pullStrength=1;_position01=0;_needsUpdate=!1;start(){this.object===void 0&&(this.object=this.gameObject),this.updateFromPosition()}onEnable(){window.addEventListener("pointerdown",this.onUserInput,{passive:!0}),this.context.domElement.addEventListener("wheel",this.onUserInput,{passive:!0})}onDisable(){window.removeEventListener("pointerdown",this.onUserInput),this.context.domElement.removeEventListener("wheel",this.onUserInput)}onUserInput=()=>{this.object?.contains(this.context.mainCamera)&&(this._needsUpdate=!1,this._performedUpdates+=999)};update(){this.autoRun&&(this._needsUpdate=!0,this._position01+=this.context.time.deltaTime/this.duration),this._needsUpdate&&(this._needsUpdate=!1,this.updateFromPosition())}updateFromPosition(){if(!this.spline||!this.spline.curve||!this.object)return;this.clamp?this._position01=j.clamp01(this._position01):this._position01=this._position01%1;const e=this._position01>=1?1:this._position01%1,t=this.spline.getPointAt(e);if(this.pullStrength>=1)this.object.worldPosition=t;else if(this._position01!==this._lastPosition01&&(this._performedUpdates=0),this._requiredUpdates=Math.round(100/this.pullStrength),this._performedUpdates<this._requiredUpdates){const i=this.object.worldPosition;this._performedUpdates++;const n=j.clamp01(this.pullStrength),s=this.object.worldPosition=i.lerp(t,n*(this.context.time.deltaTime/.3));this._lastPositionVector.copy(s),this._needsUpdate=!0}if(this.useLookAt)if(this.lookAt)this.object.lookAt(this.lookAt.worldPosition);else{const i=this.spline.getTangentAt(e);this.object.lookAt(t.add(i))}this._lastPosition01=this._position01}_lastPosition01=0;_requiredUpdates=0;_performedUpdates=0;_lastPositionVector=new b}nr([Qe(fa)],hn.prototype,"spline",2),nr([Qe(M)],hn.prototype,"object",2),nr([Qe()],hn.prototype,"useLookAt",2),nr([Qe(M)],hn.prototype,"lookAt",2),nr([Qe()],hn.prototype,"clamp",2),nr([Qe()],hn.prototype,"position01",1),nr([Qe()],hn.prototype,"autoRun",2),nr([Qe()],hn.prototype,"duration",2);class vo{bb=null;bb_pos=0;__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsSyncedCameraModel(e,t){return(t||new vo).__init(e.readInt32(e.position())+e.position(),e)}static getSizePrefixedRootAsSyncedCameraModel(e,t){return e.setPosition(e.position()+Wb),(t||new vo).__init(e.readInt32(e.position())+e.position(),e)}userId(e){const t=this.bb.__offset(this.bb_pos,4);return t?this.bb.__string(this.bb_pos+t,e):null}guid(e){const t=this.bb.__offset(this.bb_pos,6);return t?this.bb.__string(this.bb_pos+t,e):null}dontSave(){const e=this.bb.__offset(this.bb_pos,8);return e?!!this.bb.readInt8(this.bb_pos+e):!1}pos(e){const t=this.bb.__offset(this.bb_pos,10);return t?(e||new Vr).__init(this.bb_pos+t,this.bb):null}rot(e){const t=this.bb.__offset(this.bb_pos,12);return t?(e||new Vr).__init(this.bb_pos+t,this.bb):null}static startSyncedCameraModel(e){e.startObject(5)}static addUserId(e,t){e.addFieldOffset(0,t,0)}static addGuid(e,t){e.addFieldOffset(1,t,0)}static addDontSave(e,t){e.addFieldInt8(2,+t,0)}static addPos(e,t){e.addFieldStruct(3,t,0)}static addRot(e,t){e.addFieldStruct(4,t,0)}static endSyncedCameraModel(e){return e.endObject()}static finishSyncedCameraModelBuffer(e,t){e.finish(t)}static finishSizePrefixedSyncedCameraModelBuffer(e,t){e.finish(t,void 0,!0)}}var zI=Object.defineProperty,NI=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&zI(e,t,n),n};const Jp="SCAM";kg(Jp,vo.getRootAsSyncedCameraModel);const Wi=new zm;class WI{userId;guid;constructor(e,t){this.guid=t,this.userId=e}send(e,t){if(e){Wi.clear();const i=Wi.createString(this.guid),n=Wi.createString(this.userId);vo.startSyncedCameraModel(Wi),vo.addGuid(Wi,i),vo.addUserId(Wi,n);const s=ee(e),r=Vd(e);vo.addPos(Wi,Vr.createVec3(Wi,s.x,s.y,s.z)),vo.addRot(Wi,Vr.createVec3(Wi,r.x,r.y,r.z));const a=vo.endSyncedCameraModel(Wi);Wi.finish(a,Jp),t.sendBinary(Wi.asUint8Array())}}}const iS=class ub extends E{static instances=[];getCameraObject(e){const t=this.userToCamMap[e];return t?this.remoteCams[t].obj:null}cameraPrefab=null;_lastWorldPosition;_lastWorldQuaternion;_model=null;_needsUpdate=!0;_lastUpdateTime=0;remoteCams={};userToCamMap={};_camTimeoutInSeconds=10;_receiveCallback=null;async awake(){this._lastWorldPosition=this.worldPosition.clone(),this._lastWorldQuaternion=this.worldQuaternion.clone(),this.cameraPrefab&&("uri"in this.cameraPrefab&&(this.cameraPrefab=await this.cameraPrefab.instantiate(this.gameObject)),this.cameraPrefab&&"isObject3D"in this.cameraPrefab&&(this.cameraPrefab.visible=!1))}onEnable(){this._receiveCallback=this.context.connection.beginListenBinary(Jp,this.onReceivedRemoteCameraInfoBin.bind(this))}onDisable(){this.context.connection.stopListenBinary(Jp,this._receiveCallback)}update(){for(const n in this.remoteCams){const s=this.remoteCams[n],r=this.context.time.realtimeSinceStartup-s.lastUpdate;if(!s||r>this._camTimeoutInSeconds){A()&&console.log("Remote cam timeout",n),s?.obj&&S.destroy(s.obj),delete this.remoteCams[n],s&&delete this.userToCamMap[s.userId],ub.instances.push(s),this.context.players.removePlayerView(s.userId,Fo.Browser);continue}}if(this.context.isInXR)return;const e=this.context.mainCamera;if(e===null){this.enabled=!1;return}if(!this.context.connection.isConnected||this.context.connection.connectionId===null)return;this._model===null&&(this._model=new WI(this.context.connection.connectionId,this.context.connection.connectionId+"_camera"));const t=ee(e),i=_e(e);(t.distanceTo(this._lastWorldPosition)>.001||i.angleTo(this._lastWorldQuaternion)>.01)&&(this._needsUpdate=!0),this._lastWorldPosition.copy(t),this._lastWorldQuaternion.copy(i),!((!this._needsUpdate||this.context.time.frameCount%2!==0)&&!(this.context.time.realtimeSinceStartup-this._lastUpdateTime>this._camTimeoutInSeconds*.5))&&(this._lastUpdateTime=this.context.time.realtimeSinceStartup,this._needsUpdate=!1,this._model.send(e,this.context.connection),this.context.isInXR||this.context.players.setPlayerView(this.context.connection.connectionId,e,Fo.Browser))}onReceivedRemoteCameraInfoBin(e){const t=e.guid();if(!t)return;const i=e.userId();if(!i||!this.context.connection.userIsInRoom(i)||!this.cameraPrefab)return;let n=this.remoteCams[t];if(!n)if("isObject3D"in this.cameraPrefab){const l=new Nn;l.context=this.context;const c=S.instantiate(this.cameraPrefab,l);n=this.remoteCams[t]={obj:c,lastUpdate:this.context.time.realtimeSinceStartup,userId:i},n.obj.visible=!0,this.gameObject.add(c),this.userToCamMap[i]=t,ub.instances.push(n);const h=S.getOrAddComponent(c,Le);h.connectionId=i,h.avatar=c}else return;const s=n.obj;this.context.players.setPlayerView(i,s,Fo.Browser),n.lastUpdate=this.context.time.realtimeSinceStartup,pn.markDirty(s);const r=e.pos();r&&Sr(s,r.x(),r.y(),r.z());const a=e.rot();a&&fc(s,a.x(),a.y(),a.z())}};NI([u([M,ne])],iS.prototype,"cameraPrefab");let D0=iS;var VI=Object.defineProperty,$I=Object.getOwnPropertyDescriptor,or=(o,e,t,i)=>{for(var n=i>1?void 0:i?$I(e,t):e,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&VI(e,t,n),n};const j0="view",B0=w("debugsyncedroom");class Fn extends E{roomName="";urlParameterName="room";joinRandomRoom;requireRoomParameter=!1;autoRejoin=!0;createJoinButton=!0;createViewOnlyButton=!1;get currentRoomName(){return w(j0)||w(this.urlParameterName)}_lastJoinedRoom;set roomPrefix(e){this._roomPrefix=e}get roomPrefix(){return this._roomPrefix}_roomPrefix="";awake(){this.joinRandomRoom===void 0&&this.roomName?.length<=0&&(this.joinRandomRoom=!0),B0&&console.log(`SyncedRoom roomName:${this.roomName}, urlParamName:${this.urlParameterName}, joinRandomRoom:${this.joinRandomRoom}`)}onEnable(){const e=w(j0);if(e&&typeof e=="string"&&e.length>0){console.log("Join as viewer"),this.context.connection.joinRoom(e,!0);return}if(this.tryJoinRoom(),this.createJoinButton){const t=this.createRoomButton();this.context.menu.appendChild(t)}this.createViewOnlyButton&&this.onEnableViewOnlyButton()}onDisable(){this._roomButton?.remove(),this.onDisableViewOnlyButton(),this.roomName&&this.roomName.length>0&&this.context.connection.leaveRoom(this.roomName)}onDestroy(){this.destroyRoomButton()}tryJoinRandomRoom(){this.setRandomRoomUrlParameter(),this.tryJoinRoom()}tryJoinRoom(e=0){e===void 0&&(e=0);let t=!1;if(this.urlParameterName?.length>0){const i=w(this.urlParameterName);if(i&&(typeof i=="string"||typeof i=="number")){t=!0;const n=t_(i.toString());this.roomName=n}else if(this.joinRandomRoom&&(console.debug("No room name found in url, generating random one"),this.setRandomRoomUrlParameter(),e<1))return this.tryJoinRoom(e+1)}else this.joinRandomRoom&&(this.roomName===null||this.roomName===void 0||this.roomName.length<=0)&&(this.roomName=this.generateRoomName());return this.requireRoomParameter&&!t?((B0||A())&&console.warn('[SyncedRoom] Missing required room parameter "'+this.urlParameterName+`" in url - will not connect.
1426
+ `)},e.userData.isLightBlendMaterial=!0}applyShadowMaterial(){if(this.targetMesh)if(this.targetMesh.material.type!=="ShadowMaterial"){const e=new mb;e.color=this.shadowColor,e.opacity=this.shadowColor.alpha,this.applyMaterialOptions(e),this.targetMesh.material=e,e.userData.isShadowCatcherMaterial=!0}else{const e=this.targetMesh.material;e.color=this.shadowColor,e.opacity=this.shadowColor.alpha,this.applyMaterialOptions(e),e.userData.isShadowCatcherMaterial=!0}}applyOccluderMaterial(){if(this.targetMesh){let e=this.targetMesh.material;if(!e){const t=new Ce;this.targetMesh.material=t,e=t}e.depthWrite=!0,e.stencilWrite=!0,e.colorWrite=!1,this.gameObject.renderOrder=-100}}applyMaterialOptions(e){e&&(e.depthWrite=!1,e.stencilWrite=!1)}}Q1([u()],Uh.prototype,"mode"),Q1([u(se)],Uh.prototype,"shadowColor");var xI=Object.defineProperty,zh=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&xI(e,t,n),n};const oi=w("debugskybox");L0("background-image"),L0("environment-image");const Y1={studio:{url:"https://cdn.needle.tools/static/skybox/modelviewer-Neutral.pmrem4x4.ktx2?pmrem",url_low:"https://cdn.needle.tools/static/skybox/modelviewer-Neutral-small.pmrem4x4.ktx2?pmrem"},"blurred-skybox":{url:"https://cdn.needle.tools/static/skybox/blurred-skybox.pmrem4x4.ktx2?pmrem",url_low:"https://cdn.needle.tools/static/skybox/blurred-skybox-small.pmrem4x4.ktx2?pmrem"},"quicklook-ar":{url:"https://cdn.needle.tools/static/skybox/QuickLook-ARMode.pmrem4x4.ktx2?pmrem",url_low:"https://cdn.needle.tools/static/skybox/QuickLook-ARMode-small.pmrem4x4.ktx2?pmrem"},quicklook:{url:"https://cdn.needle.tools/static/skybox/QuickLook-ObjectMode.pmrem4x4.ktx2?pmrem",url_low:"https://cdn.needle.tools/static/skybox/QuickLook-ObjectMode-small.pmrem4x4.ktx2?pmrem"}};function Z1(o,e,t,i,n){if(e==="transparent"||e?.startsWith("rgb")||e?.startsWith("#"))return console.warn(`Needle Engine: Invalid ${n} value (${e}). Did you mean to set background-color instead?`),null;const s=new Xp;s.sourceId=n_(e),s.allowDrop=!1,s.allowNetworking=!1,s.background=t,s.environment=i,S.addComponent(o.scene,s);const r=a=>{if(oi&&console.log(n,"CHANGED TO",a),a){if(typeof a!="string"){console.warn("Invalid attribute value for "+n);return}s.setSkybox(a)}else if(s.sourceId&&(i&&(o.sceneLighting.internalEnableReflection(s.sourceId)||(o.scene.environment=null)),t)){const l=o.lightmaps.tryGetSkybox(s.sourceId);o.scene.background=l}};return Xm(o.domElement,n,r),s.addEventListener("destroy",()=>{oi&&console.log("Destroyed attribute remote skybox",n),Qm(o.domElement,n,r)}),s.setSkybox(e)}const qp=new Array;pe.registerCallback(ue.ContextCreationStart,o=>{const e=o.context,t=e.domElement.getAttribute("background-image"),i=e.domElement.getAttribute("environment-image");if(t){oi&&console.log("Creating RemoteSkybox to load background "+t);const n=Z1(e,t,!0,!1,"background-image");n&&qp.push(n)}if(i){oi&&console.log("Creating RemoteSkybox to load environment "+i);const n=Z1(e,i,!1,!0,"environment-image");n&&qp.push(n)}}),pe.registerCallback(ue.ContextCreationStart,()=>Promise.all(qp).finally(()=>{qp.length=0}));const ga=class extends E{url="studio";allowDrop=!0;background=!0;environment=!0;allowNetworking=!0;_prevUrl;_prevLoadedEnvironment;_prevEnvironment=null;_prevBackground=null;onEnable(){this.setSkybox(this.url),this.registerDropEvents()}onDisable(){this.context.scene.environment===this._prevLoadedEnvironment&&(this.context.scene.environment=this._prevEnvironment,gi.backgroundShouldBeTransparent(this.context)||(this.context.scene.background=this._prevBackground),this._prevLoadedEnvironment=void 0),this.unregisterDropEvents(),this.context.mainCameraComponent?.applyClearFlags()}urlChangedSyncField(){this.allowNetworking&&this.url&&(this.isRemoteTexture(this.url)?this.setSkybox(this.url):oi&&console.warn(`RemoteSkybox: Not setting skybox: ${this.url} is not a remote texture. If you want to set a local texture, set allowNetworking to false.`))}async setSkybox(o,e){if(!this.activeAndEnabled||(o=SI(o,this.environment,this.background),!o))return!1;if(e??=o,this.isValidTextureType(e)||console.warn('Potentially invalid skybox URL: "'+e+'" on '+(this.name||this.gameObject?.name||"context")),oi&&console.log("Set RemoteSkybox url: "+o),this._prevUrl===o&&this._prevLoadedEnvironment)return this.apply(),!0;this._prevLoadedEnvironment?.dispose(),this._prevLoadedEnvironment=void 0,this._prevUrl=o;const t=await ay(o,this.context.renderer);return t?!this.enabled||this.destroyed?(oi&&console.warn("RemoteSkybox: Component is disabled or destroyed"),!1):this._prevUrl!==o?(oi&&console.warn("RemoteSkybox: URL changed while loading texture, aborting setSkybox"),!1):(this.url=o,this._prevLoadedEnvironment=t,this.apply(),!0):(oi&&console.warn("RemoteSkybox: Failed to load texture from url",o),!1)}apply(){const o=this._prevLoadedEnvironment;if(o&&(o instanceof Pb||o instanceof ZC||o.mapping==Cb||(o.mapping=KC,o.needsUpdate=!0),!this.destroyed)){if(!this.context){console.warn("RemoteSkybox: Context is not available - can not apply skybox.");return}this.context.scene.background!==o&&(this._prevBackground=this.context.scene.background),this.context.scene.environment!==o&&(this._prevEnvironment=this.context.scene.environment),oi&&console.log("Set RemoteSkybox ("+(this.environment&&this.background?"environment and background":this.environment?"environment":this.background?"background":"none")+")",this.url,!gi.backgroundShouldBeTransparent(this.context)),this.environment&&(this.context.scene.environment=o),this.background&&!gi.backgroundShouldBeTransparent(this.context)&&(this.context.scene.background=o),this.context.mainCameraComponent?.backgroundBlurriness!==void 0&&(this.context.scene.backgroundBlurriness=this.context.mainCameraComponent.backgroundBlurriness)}}validProtocols=["file:","blob:","data:"];validTextureTypes=[".ktx2",".hdr",".exr",".jpg",".jpeg",".png"];isRemoteTexture(o){return o.startsWith("http://")||o.startsWith("https://")}isValidTextureType(o){for(const e of this.validTextureTypes)if(o.includes(e))return!0;for(const e of this.validProtocols)if(o.startsWith(e))return!0;return!1}registerDropEvents(){this.unregisterDropEvents(),this.context.domElement.addEventListener("dragover",this.onDragOverEvent),this.context.domElement.addEventListener("drop",this.onDrop)}unregisterDropEvents(){this.context.domElement.removeEventListener("dragover",this.onDragOverEvent),this.context.domElement.removeEventListener("drop",this.onDrop)}onDragOverEvent=o=>{if(this.allowDrop&&o.dataTransfer)for(const e of o.dataTransfer.types)(e==="text/uri-list"||e==="Files")&&o.preventDefault()};onDrop=o=>{if(this.allowDrop&&o.dataTransfer){for(const e of o.dataTransfer.types)if(oi&&console.log(e),e==="text/uri-list"){const t=o.dataTransfer.getData(e);oi&&console.log(e,t);let i=new RegExp(/polyhaven.com\/asset_img\/.+?\/(?<name>.+)\.png/).exec(t)?.groups?.name;if(i||(i=new RegExp(/polyhaven\.com\/a\/(?<name>.+)/).exec(t)?.groups?.name),oi&&console.log(i),i){const n="https://dl.polyhaven.org/file/ph-assets/HDRIs/exr/1k/"+i+"_1k.exr";console.log(`[Remote Skybox] Setting skybox from url: ${n}`),o.preventDefault(),this.setSkybox(n);break}else if(this.isValidTextureType(t)){console.log("[Remote Skybox] Setting skybox from url: "+t),o.preventDefault(),this.setSkybox(t);break}else{console.warn(`[RemoteSkybox] Unknown url ${t}. If you want to load a skybox from a url, make sure it is a valid image url. Url must end with${this.validTextureTypes.join(", ")}.`);const n=new CustomEvent("dropped-unknown-url",{detail:{sender:this,event:o,url:t,apply:s=>{o.preventDefault(),this.setSkybox(s)}}});this.dispatchEvent(n)}}else if(e=="Files"){const t=o.dataTransfer.files.item(0);if(oi&&console.log(e,t),!t)continue;if(!this.isValidTextureType(t.name)){console.warn(`[RemoteSkybox]: File "${t.name}" is not supported. Supported files are ${this.validTextureTypes.join(", ")}`);return}o.preventDefault(),this.setSkybox(t.name);break}}}};zh([Uy(ga.prototype.urlChangedSyncField),u(URL)],ga.prototype,"url"),zh([u()],ga.prototype,"allowDrop"),zh([u()],ga.prototype,"background"),zh([u()],ga.prototype,"environment"),zh([u()],ga.prototype,"allowNetworking");let Xp=ga;function SI(o,e,t){if(o==null)return null;const i=e&&!t,n=Y1[o.toLowerCase()];return n?i?n.url_low:n.url:(typeof o=="string"&&o?.length&&(A()||oi)&&(o.includes("/")||o.includes(".")||console.warn(`RemoteSkybox: Unknown magic skybox name "${o}". Valid names are: ${Object.keys(Y1).map(s=>`"${s}"`).join(", ")}`)),o)}var CI=Object.defineProperty,Qp=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&CI(e,t,n),n};const Nh=class VS extends E{target=null;followFactor=.1;rotateFactor=.1;positionAxes=cl.All;flipForward=!1;static _invertForward=new N().setFromAxisAngle(new b(0,1,0),Math.PI);_firstUpdate=!0;onBeforeRender(){this.updateNow(!1)}updateNow(e){if(!(!this.target||this.target===this.gameObject)){if(this.followFactor>0){const t=ee(this.target),i=this._firstUpdate||e?1:j.clamp01(this.context.time.deltaTime*this.followFactor),n=this.worldPosition;this.positionAxes&cl.X&&(n.x=j.lerp(n.x,t.x,i)),this.positionAxes&cl.Y&&(n.y=j.lerp(n.y,t.y,i)),this.positionAxes&cl.Z&&(n.z=j.lerp(n.z,t.z,i)),this.worldPosition=n}if(this.rotateFactor>0){const t=_e(this.target);this.flipForward&&t.premultiply(VS._invertForward);const i=this._firstUpdate||e?1:j.clamp01(this.context.time.deltaTime*this.rotateFactor);this.worldQuaternion=this.worldQuaternion.slerp(t,i)}this._firstUpdate=!1}}};Qp([u(M)],Nh.prototype,"target"),Qp([u()],Nh.prototype,"followFactor"),Qp([u()],Nh.prototype,"rotateFactor"),Qp([u()],Nh.prototype,"positionAxes");let Yp=Nh;var PI=Object.defineProperty,Wh=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&PI(e,t,n),n};const Vh=w("debugspatialtrigger"),K1=new bs,J1=new bs;function OI(o,e){return K1.mask=o,J1.mask=e,K1.test(J1)}class po extends E{triggerMask=0;onEnter;onStay;onExit;start(){Vh&&console.log(this.name,this.triggerMask,this)}update(){this.currentIntersected.length=0;for(const e of Zp.triggers)OI(e.triggerMask,this.triggerMask)&&e.test(this.gameObject)&&this.currentIntersected.push(e);for(let e=this.lastIntersected.length-1;e>=0;e--){const t=this.lastIntersected[e];this.currentIntersected.indexOf(t)<0&&(this.onExitTrigger(t),this.lastIntersected.splice(e,1))}for(const e of this.currentIntersected)this.lastIntersected.indexOf(e)<0&&this.onEnterTrigger(e),this.onStayTrigger(e);this.lastIntersected.length=0,this.lastIntersected.push(...this.currentIntersected)}currentIntersected=[];lastIntersected=[];onEnterTrigger(e){Vh&&console.log("ENTER TRIGGER",this.name,e.name,this,e),e.raiseOnEnterEvent(this),this.onEnter?.invoke()}onExitTrigger(e){Vh&&console.log("EXIT TRIGGER",this.name,e.name),e.raiseOnExitEvent(this),this.onExit?.invoke()}onStayTrigger(e){e.raiseOnStayEvent(this),this.onStay?.invoke()}}Wh([u()],po.prototype,"triggerMask"),Wh([u(ae)],po.prototype,"onEnter"),Wh([u(ae)],po.prototype,"onStay"),Wh([u(ae)],po.prototype,"onExit");const eS=class _m extends E{static triggers=[];triggerMask;boxHelper;start(){Vh&&console.log(this.name,this.triggerMask,this)}onEnable(){_m.triggers.push(this),this.boxHelper||(this.boxHelper=S.addComponent(this.gameObject,Pt),this.boxHelper?.showHelper(null,Vh))}onDisable(){_m.triggers.splice(_m.triggers.indexOf(this),1)}test(e){return this.boxHelper?this.boxHelper.isInBox(e)??!1:!1}raiseOnEnterEvent(e){S.foreachComponent(this.gameObject,t=>{t!==e&&t instanceof po&&t.onEnterTrigger(this)},!1)}raiseOnStayEvent(e){S.foreachComponent(this.gameObject,t=>{t!==e&&t instanceof po&&t.onStayTrigger(this)},!1)}raiseOnExitEvent(e){S.foreachComponent(this.gameObject,t=>{t!==e&&t instanceof po&&t.onExitTrigger(this)},!1)}};Wh([u()],eS.prototype,"triggerMask");let Zp=eS;var kI=Object.defineProperty,MI=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&kI(e,t,n),n};const Ni=w("debugspectator");class Kp extends E{cam=null;useKeys=!0;_mode=0;get mode(){return this._mode}set mode(e){this._mode=e}get isSpectating(){return this._handler?.currentTarget!==void 0}isSpectatingUser(e){return this.target?.userId===e}isFollowedBy(e){return this.followers?.includes(e)}get followers(){return this._networking.followers}stopSpectating(){if(this.context.isInXR){this.followSelf();return}this.target=void 0}get localId(){return this.context.connection.connectionId??"local"}set target(e){if(this._handler){const t=this._handler.currentTarget?.userId,i=this.context.players.getPlayerView(this.localId);e===void 0||this.context.isInXR===!1&&i?.currentObject===e.currentObject?this._handler.currentTarget!==void 0&&(this._handler.disable(),S.setActive(this.gameObject,!1),this.orbit&&(this.orbit.enabled=!0),this._networking.onSpectatedObjectChanged(e,t)):this._handler.currentTarget!==e&&(this._handler.set(e),S.setActive(this.gameObject,!0),this.orbit&&(this.orbit.enabled=!1),this._networking.onSpectatedObjectChanged(e,t))}}get target(){return this._handler?.currentTarget}requestAllFollowMe(){this._networking.onRequestFollowMe()}get isSpectatingSelf(){return this.isSpectating&&this.target?.currentObject===this.context.players.getPlayerView(this.localId)?.currentObject}orbit=null;_handler;eventSub_WebXRRequestStartEvent=null;eventSub_WebXRStartEvent=null;eventSub_WebXREndEvent=null;_debug;_networking;awake(){if(this._debug=new TI(this.context,this),this._networking=new LI(this.context,this),this._networking.awake(),S.setActive(this.gameObject,!1),this.cam=S.getComponent(this.gameObject,gi),!this.cam){console.warn("SpectatorCamera: Spectator camera needs camera component on the same object.",this);return}!this._handler&&this.cam&&(this._handler=new EI(this.context,this.cam,this)),this.orbit=S.getComponent(this.context.mainCamera,ge)}onDestroy(){this.stopSpectating(),this._handler?.destroy(),this._networking?.destroy()}isSupportedPlatform(){const e=window.navigator.userAgent,t=/Windows NT/.test(e)&&/Edg/.test(e)&&!/Win64/.test(e);return I.isDesktop()&&!I.isMobileDevice()&&!t}onBeforeXR(e){this.isSupportedPlatform()&&S.setActive(this.gameObject,!0)}onEnterXR(e){this.isSupportedPlatform()&&(Ni&&console.log(this.context.mainCamera),this.context.mainCamera&&this.followSelf())}onLeaveXR(e){this.context.removeCamera(this.cam),S.setActive(this.gameObject,!1),this._handler?.set(void 0),this._handler?.disable(),this.isSpectatingSelf&&this.stopSpectating(),this.orbit&&(this.orbit.enabled=!0)}followSelf(){this.target=this.context.players.getPlayerView(this.context.connection.connectionId),this.target||(this.context.players.setPlayerView(this.localId,this.context.mainCamera,Fo.Headset),this.target=this.context.players.getPlayerView(this.localId)),Ni&&console.log("Follow self",this.target)}onAfterRender(){if(!this.cam)return;const e=this.context.renderer,t=e.xr.enabled;if(!e.xr.isPresenting&&!this._handler?.currentTarget)return;this._handler?.update(this._mode);const i=e.getRenderTarget();let n=null;const s=e.state;if(!i||i.isXRRenderTarget===!0){if(!e.state.bindFramebuffer||!s.bindXRFramebuffer)return;n=e._framebuffer,s.bindXRFramebuffer(null)}this.setAvatarFlagsBeforeRender();const r=this.context.mainCameraComponent;if(r){const c=r.backgroundColor;c&&e.setClearColor(c,c.alpha),this.cam.backgroundColor=c,this.cam.clearFlags=r.clearFlags,this.cam.nearClipPlane=r.nearClipPlane,this.cam.farClipPlane=r.farClipPlane}else e.setClearColor(new oe(1,1,1));e.setRenderTarget(null),e.xr.enabled=!1;const a=this.cam?.threeCamera;this.context.updateAspect(a);const l=e.xr.isPresenting;e.xr.isPresenting=!1,e.setSize(this.context.domWidth,this.context.domHeight),e.render(this.context.scene,a),e.xr.isPresenting=l,e.xr.enabled=t,i?e.setRenderTarget(i):s.bindXRFramebuffer&&s.bindXRFramebuffer(n),this.resetAvatarFlags()}setAvatarFlagsBeforeRender(){const e=this._mode===0;for(const t of Le.instances)if(t.avatar&&"isLocalAvatar"in t.avatar&&"flags"in t.avatar){let i=io.All;this.isSpectatingSelf&&(i=e&&t.avatar.isLocalAvatar?io.FirstPerson:io.ThirdPerson);const n=t.avatar.flags;if(!n)continue;for(const s of n)s.UpdateVisible(i)}}resetAvatarFlags(){for(const e of Le.instances)if(e.avatar&&"flags"in e.avatar){const t=e.avatar.flags;if(!t)continue;for(const i of t)"isLocalAvatar"in e.avatar&&e.avatar?.isLocalAvatar?i.UpdateVisible(io.FirstPerson):i.UpdateVisible(io.ThirdPerson)}}}MI([u()],Kp.prototype,"useKeys");class EI{context;cam;spectator;follow;target;view;currentObject;get currentTarget(){return this.view}constructor(e,t,i){this.context=e,this.cam=t,this.spectator=i}set(e){const t=e?.currentObject;if(!t){this.spectator.stopSpectating();return}t!==this.currentObject&&(this.currentObject=t,this.view=e,this.follow||(this.follow=S.addComponent(this.cam.gameObject,Yp)),this.target||(this.target=new M),t.add(this.target),this.follow.enabled=!0,this.follow.target=this.target,Ni&&console.log("FOLLOW",t),this.context.isInXR?this.context.removeCamera(this.cam):this.context.setCurrentCamera(this.cam))}disable(){Ni&&console.log("STOP FOLLOW",this.currentObject),this.view=void 0,this.currentObject=void 0,this.context.removeCamera(this.cam),this.follow&&(this.follow.enabled=!1)}destroy(){this.target?.removeFromParent(),this.follow&&S.destroy(this.follow)}update(e){if(this.currentTarget?.isConnected===!1||this.currentTarget?.removed===!0){Ni&&console.log("Target disconnected or timeout",this.currentTarget),this.spectator.stopSpectating();return}this.currentTarget&&this.currentTarget?.currentObject!==this.currentObject&&(Ni&&console.log("Target changed",this.currentObject,"to",this.currentTarget.currentObject),this.set(this.currentTarget));const t=this.context.mainCamera;if(t){const n=this.cam.threeCamera;(n.near!==t.near||n.far!==t.far)&&(n.near=t.near,n.far=t.far,n.updateProjectionMatrix())}const i=this.follow?.target;if(!(!i||!this.follow)){switch(e){case 0:this.view?.viewDevice!==Fo.Browser?(this.follow.followFactor=5,this.follow.rotateFactor=5):(this.follow.followFactor=50,this.follow.rotateFactor=50),i.position.set(0,0,0);break;case 1:this.follow.followFactor=3,this.follow.rotateFactor=2,i.position.set(0,.5,1.5);break}this.follow.flipForward=!1,this.view?.viewDevice!==Fo.Browser?i.quaternion.copy(RI):i.quaternion.identity()}}}const RI=new N().setFromAxisAngle(new b(0,1,0),Math.PI);class TI{context;spectator;constructor(e,t){this.context=e,this.spectator=t,console.log("[Spectator Camera] Click other avatars or cameras to follow them. Press ESC to exit spectator mode."),this.context.domElement.addEventListener("keydown",n=>{!this.spectator.useKeys||n.key==="Escape"&&this.spectator.stopSpectating()});let i=0;this.context.input.addEventListener(Ae.PointerDown,n=>{i=this.context.time.time}),this.context.input.addEventListener(Ae.PointerUp,n=>{const s=this.context.time.time-i;s>1?this.spectator.stopSpectating():this.context.input.getPointerClicked(0)&&s<.3&&this.trySelectObject()})}trySelectObject(){const e=new Os;e.setMask(16777215);const t=this.context.physics.raycast(e);if(Ni&&console.log(...t),t?.length)for(const i of t){if(i.distance<.2)continue;const n=i.object,s=sn.getFor(n);let r=s?.owner;if(r||(r=S.getComponentInParent(n,Le)?.connectionId),r){const a=this.context.players.getPlayerView(r);this.spectator.target=a,Ni&&console.log("spectate",r,s);break}}}}class AI{guid;dontSave=!0;targetUserId;stoppedFollowing;constructor(e,t,i){this.guid=e,this.targetUserId=t,this.stoppedFollowing=i}}class II{guid;userId;constructor(e,t){this.guid=e.guid,this.userId=t}}class LI{followers=[];context;spectator;_followerEventMethod;_requestFollowMethod;_joinedRoomMethod;constructor(e,t){this.context=e,this.spectator=t,this._followerEventMethod=this.onFollowerEvent.bind(this),this._requestFollowMethod=this.onRequestFollowEvent.bind(this),this._joinedRoomMethod=this.onUserJoinedRoom.bind(this)}awake(){this.context.connection.beginListen("spectator-follower-changed",this._followerEventMethod),this.context.connection.beginListen("spectator-request-follow",this._requestFollowMethod),this.context.connection.beginListen(ie.JoinedRoom,this._joinedRoomMethod),this.context.domElement.addEventListener("keydown",e=>{this.spectator.useKeys&&(e.key==="f"?this.onRequestFollowMe():e.key==="Escape"&&this.onRequestFollowMe(!0))})}destroy(){this.context.connection.stopListen("spectator-follower-changed",this._followerEventMethod),this.context.connection.stopListen("spectator-request-follow",this._requestFollowMethod),this.context.connection.stopListen(ie.JoinedRoom,this._joinedRoomMethod)}onSpectatedObjectChanged(e,t){if(Ni&&console.log(this.context.connection.connectionId,"onSpectatedObjectChanged",e,t),this.context.connection.connectionId){const i=e?.userId===void 0,n=i?t:e?.userId,s=new AI(this.context.connection.connectionId,n,i);this.context.connection.send("spectator-follower-changed",s)}}onRequestFollowMe(e=!1){if(Ni&&console.log("Request follow",this.context.connection.connectionId),this.context.connection.connectionId){this.spectator.stopSpectating();const t=e?void 0:this.context.connection.connectionId,i=new II(this.spectator,t);this.context.connection.send("spectator-request-follow",i)}}onUserJoinedRoom(){w("followme")&&this.onRequestFollowMe()}onFollowerEvent(e){const t=e.targetUserId,i=e.guid;if(Ni&&console.log(e),t===this.context.connection.connectionId)if(e.stoppedFollowing){const n=this.followers.indexOf(i);n!==-1&&(this.followers.splice(n,1),this.removeDisconnectedFollowers(),console.log(i,"unfollows you",this.followers.length))}else this.followers.includes(i)||(this.followers.push(i),this.removeDisconnectedFollowers(),console.log(i,"follows you",this.followers.length))}removeDisconnectedFollowers(){for(let e=this.followers.length-1;e>=0;e--){const t=this.followers[e];this.context.connection.userIsInRoom(t)===!1&&this.followers.splice(e,1)}}_lastRequestFollowUser;onRequestFollowEvent(e){if(this._lastRequestFollowUser=e,e.userId===this.context.connection.connectionId)this.spectator.stopSpectating();else if(e.userId===void 0)this.spectator.stopSpectating();else{const t=this.context.players.getPlayerView(e.userId);if(t)this.spectator.target=t;else return Ni&&console.warn("Could not find view",e.userId),this.enforceFollow(),!1}return!0}_enforceFollowInterval;enforceFollow(){this._enforceFollowInterval||(this._enforceFollowInterval=setInterval(()=>{this._lastRequestFollowUser===void 0||this._lastRequestFollowUser.userId&&this.spectator.isFollowedBy(this._lastRequestFollowUser.userId)?(clearInterval(this._enforceFollowInterval),this._enforceFollowInterval=void 0):(Ni&&console.log("REQUEST FOLLOW AGAIN",this._lastRequestFollowUser.userId),this.onRequestFollowEvent(this._lastRequestFollowUser))},1e3))}}var DI=Object.defineProperty,jI=Object.getOwnPropertyDescriptor,Gl=(o,e,t,i)=>{for(var n=i>1?void 0:i?jI(e,t):e,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&DI(e,t,n),n};const tS=w("debugsplines");class mo{position=new b;rotation=new N;tangentIn=new b;tangentOut=new b}Gl([Ye(b)],mo.prototype,"position",2),Gl([Ye(N)],mo.prototype,"rotation",2),Gl([Ye(b)],mo.prototype,"tangentIn",2),Gl([Ye(b)],mo.prototype,"tangentOut",2);class fa extends E{addKnot(e){if(e instanceof mo)this.spline.push(e),this._isDirty=!0;else{const t=new mo;t.position.copy(e.position),this.spline.push(t),this._isDirty=!0}return this}removeKnot(e){if(typeof e=="number")this.spline.splice(e,1),this._isDirty=!0;else{const t=this.spline.indexOf(e);t!==-1&&(this.spline.splice(t,1),this._isDirty=!0)}return this}getPointAt(e,t){if(!this.curve)return new b;const i=this.curve.getPointAt(j.clamp01(e),t),n=this.gameObject.matrixWorld??void 0;return n&&i.applyMatrix4(n),i}markDirty(){this._isDirty=!0}getTangentAt(e,t){if(!this.curve)return t??new b;const i=this.gameObject.worldQuaternion;return this.curve.getTangentAt(j.clamp01(e),t).applyQuaternion(i)}set closed(e){this._closed=e,this._isDirty=!0}get closed(){return this._closed}_closed=!1;spline=[];set debug(e){e&&!this._builtCurve&&this.buildCurve(),this._debugLine&&(this._debugLine.visible=e)}get curve(){return this._curve}get isDirty(){return this._isDirty}_isDirty=!1;_curve=null;_builtCurve=!1;_debugLine=null;awake(){tS&&(console.log(`[Spline] ${this.name}`,this),this.buildCurve())}update(){this._isDirty&&this.buildCurve(!0),this._debugLine&&this._debugLine.parent!==this.gameObject&&this.gameObject.add(this._debugLine)}buildCurve(e=!1){if(!(this._builtCurve&&!e)){if(this._builtCurve=!0,!this.spline){console.error("[Spline] Can not build curve, no spline data",this.name);return}this._isDirty=!1,this._curve=BI(this.spline,this.closed),this.buildDebugCurve()}}buildDebugCurve(){if(tS&&this.spline&&this._curve){this._debugLine?.removeFromParent(),this._debugLine=null;const e=new km({color:6684927}),t=this.spline.length*10,i=this._curve.getPoints(t),n=new wn().setFromPoints(i);this._debugLine=new Ia(n,e),this.gameObject?.add(this._debugLine)}}}Gl([Ye()],fa.prototype,"closed",1),Gl([Ye(mo)],fa.prototype,"spline",2);function BI(o,e){const t=o.map(s=>new b(-s.position.x,s.position.y,s.position.z));t.length===1&&t.push(t[0]);const i=o.reduce((s,r)=>s+Math.abs(r.tangentOut.x)+Math.abs(r.tangentOut.y)+Math.abs(r.tangentOut.z),0)/o.length,n=j.remap(i,0,.3,0,.5);return new JC(t,e,"catmullrom",n)}var FI=Object.defineProperty,UI=Object.getOwnPropertyDescriptor,nr=(o,e,t,i)=>{for(var n=i>1?void 0:i?UI(e,t):e,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&FI(e,t,n),n};class hn extends E{spline=null;object=void 0;useLookAt=!0;lookAt=null;clamp=!1;get position01(){return this._position01}set position01(e){this._position01=e,this._needsUpdate=!0}reset(){this._position01=0}autoRun=!0;duration=10;pullStrength=1;_position01=0;_needsUpdate=!1;start(){this.object===void 0&&(this.object=this.gameObject),this.updateFromPosition()}onEnable(){window.addEventListener("pointerdown",this.onUserInput,{passive:!0}),this.context.domElement.addEventListener("wheel",this.onUserInput,{passive:!0})}onDisable(){window.removeEventListener("pointerdown",this.onUserInput),this.context.domElement.removeEventListener("wheel",this.onUserInput)}onUserInput=()=>{this.object?.contains(this.context.mainCamera)&&(this._needsUpdate=!1,this._performedUpdates+=999)};update(){this.autoRun&&(this._needsUpdate=!0,this._position01+=this.context.time.deltaTime/this.duration),this._needsUpdate&&(this._needsUpdate=!1,this.updateFromPosition())}updateFromPosition(){if(!this.spline||!this.spline.curve||!this.object)return;this.clamp?this._position01=j.clamp01(this._position01):this._position01=this._position01%1;const e=this._position01>=1?1:this._position01%1,t=this.spline.getPointAt(e);if(this.pullStrength>=1)this.object.worldPosition=t;else if(this._position01!==this._lastPosition01&&(this._performedUpdates=0),this._requiredUpdates=Math.round(100/this.pullStrength),this._performedUpdates<this._requiredUpdates){const i=this.object.worldPosition;this._performedUpdates++;const n=j.clamp01(this.pullStrength),s=this.object.worldPosition=i.lerp(t,n*(this.context.time.deltaTime/.3));this._lastPositionVector.copy(s),this._needsUpdate=!0}if(this.useLookAt)if(this.lookAt)this.object.lookAt(this.lookAt.worldPosition);else{const i=this.spline.getTangentAt(e);this.object.lookAt(t.add(i))}this._lastPosition01=this._position01}_lastPosition01=0;_requiredUpdates=0;_performedUpdates=0;_lastPositionVector=new b}nr([Ye(fa)],hn.prototype,"spline",2),nr([Ye(M)],hn.prototype,"object",2),nr([Ye()],hn.prototype,"useLookAt",2),nr([Ye(M)],hn.prototype,"lookAt",2),nr([Ye()],hn.prototype,"clamp",2),nr([Ye()],hn.prototype,"position01",1),nr([Ye()],hn.prototype,"autoRun",2),nr([Ye()],hn.prototype,"duration",2);class vo{bb=null;bb_pos=0;__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsSyncedCameraModel(e,t){return(t||new vo).__init(e.readInt32(e.position())+e.position(),e)}static getSizePrefixedRootAsSyncedCameraModel(e,t){return e.setPosition(e.position()+Wb),(t||new vo).__init(e.readInt32(e.position())+e.position(),e)}userId(e){const t=this.bb.__offset(this.bb_pos,4);return t?this.bb.__string(this.bb_pos+t,e):null}guid(e){const t=this.bb.__offset(this.bb_pos,6);return t?this.bb.__string(this.bb_pos+t,e):null}dontSave(){const e=this.bb.__offset(this.bb_pos,8);return e?!!this.bb.readInt8(this.bb_pos+e):!1}pos(e){const t=this.bb.__offset(this.bb_pos,10);return t?(e||new Vr).__init(this.bb_pos+t,this.bb):null}rot(e){const t=this.bb.__offset(this.bb_pos,12);return t?(e||new Vr).__init(this.bb_pos+t,this.bb):null}static startSyncedCameraModel(e){e.startObject(5)}static addUserId(e,t){e.addFieldOffset(0,t,0)}static addGuid(e,t){e.addFieldOffset(1,t,0)}static addDontSave(e,t){e.addFieldInt8(2,+t,0)}static addPos(e,t){e.addFieldStruct(3,t,0)}static addRot(e,t){e.addFieldStruct(4,t,0)}static endSyncedCameraModel(e){return e.endObject()}static finishSyncedCameraModelBuffer(e,t){e.finish(t)}static finishSizePrefixedSyncedCameraModelBuffer(e,t){e.finish(t,void 0,!0)}}var zI=Object.defineProperty,NI=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&zI(e,t,n),n};const Jp="SCAM";kg(Jp,vo.getRootAsSyncedCameraModel);const Wi=new zm;class WI{userId;guid;constructor(e,t){this.guid=t,this.userId=e}send(e,t){if(e){Wi.clear();const i=Wi.createString(this.guid),n=Wi.createString(this.userId);vo.startSyncedCameraModel(Wi),vo.addGuid(Wi,i),vo.addUserId(Wi,n);const s=ee(e),r=Vd(e);vo.addPos(Wi,Vr.createVec3(Wi,s.x,s.y,s.z)),vo.addRot(Wi,Vr.createVec3(Wi,r.x,r.y,r.z));const a=vo.endSyncedCameraModel(Wi);Wi.finish(a,Jp),t.sendBinary(Wi.asUint8Array())}}}const iS=class ub extends E{static instances=[];getCameraObject(e){const t=this.userToCamMap[e];return t?this.remoteCams[t].obj:null}cameraPrefab=null;_lastWorldPosition;_lastWorldQuaternion;_model=null;_needsUpdate=!0;_lastUpdateTime=0;remoteCams={};userToCamMap={};_camTimeoutInSeconds=10;_receiveCallback=null;async awake(){this._lastWorldPosition=this.worldPosition.clone(),this._lastWorldQuaternion=this.worldQuaternion.clone(),this.cameraPrefab&&("uri"in this.cameraPrefab&&(this.cameraPrefab=await this.cameraPrefab.instantiate(this.gameObject)),this.cameraPrefab&&"isObject3D"in this.cameraPrefab&&(this.cameraPrefab.visible=!1))}onEnable(){this._receiveCallback=this.context.connection.beginListenBinary(Jp,this.onReceivedRemoteCameraInfoBin.bind(this))}onDisable(){this.context.connection.stopListenBinary(Jp,this._receiveCallback)}update(){for(const n in this.remoteCams){const s=this.remoteCams[n],r=this.context.time.realtimeSinceStartup-s.lastUpdate;if(!s||r>this._camTimeoutInSeconds){A()&&console.log("Remote cam timeout",n),s?.obj&&S.destroy(s.obj),delete this.remoteCams[n],s&&delete this.userToCamMap[s.userId],ub.instances.push(s),this.context.players.removePlayerView(s.userId,Fo.Browser);continue}}if(this.context.isInXR)return;const e=this.context.mainCamera;if(e===null){this.enabled=!1;return}if(!this.context.connection.isConnected||this.context.connection.connectionId===null)return;this._model===null&&(this._model=new WI(this.context.connection.connectionId,this.context.connection.connectionId+"_camera"));const t=ee(e),i=_e(e);(t.distanceTo(this._lastWorldPosition)>.001||i.angleTo(this._lastWorldQuaternion)>.01)&&(this._needsUpdate=!0),this._lastWorldPosition.copy(t),this._lastWorldQuaternion.copy(i),!((!this._needsUpdate||this.context.time.frameCount%2!==0)&&!(this.context.time.realtimeSinceStartup-this._lastUpdateTime>this._camTimeoutInSeconds*.5))&&(this._lastUpdateTime=this.context.time.realtimeSinceStartup,this._needsUpdate=!1,this._model.send(e,this.context.connection),this.context.isInXR||this.context.players.setPlayerView(this.context.connection.connectionId,e,Fo.Browser))}onReceivedRemoteCameraInfoBin(e){const t=e.guid();if(!t)return;const i=e.userId();if(!i||!this.context.connection.userIsInRoom(i)||!this.cameraPrefab)return;let n=this.remoteCams[t];if(!n)if("isObject3D"in this.cameraPrefab){const l=new Nn;l.context=this.context;const c=S.instantiate(this.cameraPrefab,l);n=this.remoteCams[t]={obj:c,lastUpdate:this.context.time.realtimeSinceStartup,userId:i},n.obj.visible=!0,this.gameObject.add(c),this.userToCamMap[i]=t,ub.instances.push(n);const h=S.getOrAddComponent(c,Le);h.connectionId=i,h.avatar=c}else return;const s=n.obj;this.context.players.setPlayerView(i,s,Fo.Browser),n.lastUpdate=this.context.time.realtimeSinceStartup,pn.markDirty(s);const r=e.pos();r&&Sr(s,r.x(),r.y(),r.z());const a=e.rot();a&&fc(s,a.x(),a.y(),a.z())}};NI([u([M,ne])],iS.prototype,"cameraPrefab");let D0=iS;var VI=Object.defineProperty,$I=Object.getOwnPropertyDescriptor,or=(o,e,t,i)=>{for(var n=i>1?void 0:i?$I(e,t):e,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&VI(e,t,n),n};const j0="view",B0=w("debugsyncedroom");class Fn extends E{roomName="";urlParameterName="room";joinRandomRoom;requireRoomParameter=!1;autoRejoin=!0;createJoinButton=!0;createViewOnlyButton=!1;get currentRoomName(){return w(j0)||w(this.urlParameterName)}_lastJoinedRoom;set roomPrefix(e){this._roomPrefix=e}get roomPrefix(){return this._roomPrefix}_roomPrefix="";awake(){this.joinRandomRoom===void 0&&this.roomName?.length<=0&&(this.joinRandomRoom=!0),B0&&console.log(`SyncedRoom roomName:${this.roomName}, urlParamName:${this.urlParameterName}, joinRandomRoom:${this.joinRandomRoom}`)}onEnable(){const e=w(j0);if(e&&typeof e=="string"&&e.length>0){console.log("Join as viewer"),this.context.connection.joinRoom(e,!0);return}if(this.tryJoinRoom(),this.createJoinButton){const t=this.createRoomButton();this.context.menu.appendChild(t)}this.createViewOnlyButton&&this.onEnableViewOnlyButton()}onDisable(){this._roomButton?.remove(),this.onDisableViewOnlyButton(),this.roomName&&this.roomName.length>0&&this.context.connection.leaveRoom(this.roomName)}onDestroy(){this.destroyRoomButton()}tryJoinRandomRoom(){this.setRandomRoomUrlParameter(),this.tryJoinRoom()}tryJoinRoom(e=0){e===void 0&&(e=0);let t=!1;if(this.urlParameterName?.length>0){const i=w(this.urlParameterName);if(i&&(typeof i=="string"||typeof i=="number")){t=!0;const n=t_(i.toString());this.roomName=n}else if(this.joinRandomRoom&&(console.debug("No room name found in url, generating random one"),this.setRandomRoomUrlParameter(),e<1))return this.tryJoinRoom(e+1)}else this.joinRandomRoom&&(this.roomName===null||this.roomName===void 0||this.roomName.length<=0)&&(this.roomName=this.generateRoomName());return this.requireRoomParameter&&!t?((B0||A())&&console.warn('[SyncedRoom] Missing required room parameter "'+this.urlParameterName+`" in url - will not connect.
1427
1427
  To allow joining a room without a query parameter you can set "requireRoomParameter" to false.`),!1):(this.context.connection.isConnected||this.context.connection.connect(),this._lastJoinedRoom=this.roomName,this._roomPrefix&&(this.roomName=this._roomPrefix+this.roomName),this.roomName.length<=0?(console.warn(`[SyncedRoom] Room name is not set so we can not join a networked room.
1428
1428
  Please choose one of the following options to fix this:
1429
1429
  A) Set a room name in the SyncedRoom component
@@ -1475,7 +1475,7 @@ void main() {
1475
1475
  #include <colorspace_fragment>
1476
1476
  }
1477
1477
  `;var kL=Object.defineProperty,lr=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&kL(e,t,n),n};const td=w("debugimagetracking");class ac{get url(){return this._trackedImage.image??""}get widthInMeters(){return this._trackedImage.widthInMeters??void 0}get bitmap(){return this._bitmap}get model(){return this._trackedImage}measuredSize;state;getPosition(e){return this.ensureTransformData(),e.copy(this._position),e}getQuaternion(e){return this.ensureTransformData(),e.copy(this._rotation),e}applyToObject(e,t=void 0){this.ensureTransformData();const i=e.position.distanceToSquared(this._position)/.05+e.quaternion.angleTo(this._rotation)/.05;t&&(t*=Math.max(1,i)),t===void 0||t>=1?(e.position.copy(this._position),e.quaternion.copy(this._rotation)):(t=Math.max(0,Math.min(1,t)),e.position.lerp(this._position,t),e.quaternion.slerp(this._rotation,t))}static _positionBuffer=new Mi(()=>new b,20);static _rotationBuffer=new Mi(()=>new N,20);_position;_rotation;ensureTransformData(){if(!this._position){this._position=ac._positionBuffer.get(),this._rotation=ac._rotationBuffer.get();const e=this._pose.transform,t=Z.active.convertSpace(e);this._position.copy(t?.position),this._rotation.copy(t?.quaternion)}}_trackingComponent;_trackedImage;_bitmap;_pose;constructor(e,t,i,n,s,r){this._trackingComponent=e,this._trackedImage=t,this._bitmap=i,this.measuredSize=n,this.state=s,this._pose=r}}class ls{constructor(e){this.image=e.url,this.widthInMeters=e.widthInMeters,e.object instanceof M?this.object=new ne({asset:e.object}):this.object=e.object,e.createObjectInstance!==void 0&&(this.createObjectInstance=e.createObjectInstance),e.imageDoesNotMove!==void 0&&(this.imageDoesNotMove=e.imageDoesNotMove),e.hideWhenTrackingIsLost!==void 0&&(this.hideWhenTrackingIsLost=e.hideWhenTrackingIsLost)}image;widthInMeters=.25;object;createObjectInstance=!1;imageDoesNotMove=!1;hideWhenTrackingIsLost=!0;getNameFromUrl(){if(this.image){const e=this.image.split("/");return e[e.length-1]}return null}}lr([u(URL)],ls.prototype,"image"),lr([u()],ls.prototype,"widthInMeters"),lr([u(ne)],ls.prototype,"object"),lr([u()],ls.prototype,"createObjectInstance"),lr([u()],ls.prototype,"imageDoesNotMove"),lr([u()],ls.prototype,"hideWhenTrackingIsLost");class ML{constructor(e,t){this.exporter=e,this.component=t,td&&console.log(this),this.exporter.anchoringType="image"}isImageTrackingExtension=!0;get extensionName(){return"image-tracking"}shouldExport=!0;filename=null;imageModel=null;onBeforeBuildDocument(e){const t=this.exporter.extensions.filter(i=>{const n=i;return n.isImageTrackingExtension&&n.component.activeAndEnabled&&n.component.trackedImages?.length>0}).indexOf(this);this.shouldExport=t===0,this.shouldExport&&this.component.trackedImages?.length>1&&(td||A())&&(be("USDZ: Only one tracked image is supported."),console.warn("USDZ: Only one tracked image is supported. Will choose the first one in the trackedImages list"))}onAfterHierarchy(e,t){if(!this.shouldExport)return;const i=I.getiOSVersion(),n=(i?parseInt(i.split(".")[0]):18)>=18?1:100;t.beginBlock('def Preliminary_ReferenceImage "AnchoringReferenceImage"'),t.appendLine("uniform asset image = @image_tracking/"+this.filename+"@"),t.appendLine("uniform double physicalWidth = "+(this.imageModel.widthInMeters*n).toFixed(8)),t.closeBlock()}async onAfterSerialize(e){if(!this.shouldExport)return;const t=this.imageModel,i=nd.get(t.image),n=await(await(await r1(i)).convertToBlob({type:"image/png"})).arrayBuffer();e.files["image_tracking/"+this.filename]=new Uint8Array(n)}onExportObject(e,t,i){if(!this.shouldExport)return;const n=this.component;if(!n||!n.trackedImages?.length||!n.activeAndEnabled)return;const s=n.trackedImages[0];if(s.object?.asset===e){this.imageModel=s,this.filename=s.getNameFromUrl()||"marker.png";const{scale:r,target:a}=this.exporter.getARScaleAndTarget();let l=e;const c=new J;if(e!==a)for(;l&&l.parent&&l.parent!==a;)l=l.parent,c.premultiply(l.matrix);const h=c.clone().invert();t.setMatrix(h.scale(new b(r,r,r)))}}}class id extends E{setPrimaryImage(e){const t=this.trackedImages.indexOf(e);if(t>=0){const i=this.trackedImages[0];i!==e&&(this.trackedImages[0]=e,this.trackedImages[t]=i)}else console.warn(`[WebXRImageTracking] Can not set primary: image not found in 'trackedImages' array ${e.image}`)}addImage(e,t=!1){this.trackedImages.includes(e)||(this.trackedImages.push(e),pS(e.image)),t&&this.setPrimaryImage(e)}trackedImages=[];smooth=!0;trackedImageIndexMap=new Map;get supported(){return this._supported}_supported=!0;awake(){if(td&&console.log(this),!!this.trackedImages)for(const e of this.trackedImages)e.image&&pS(e.image)}onEnable(){ho.beforeExport.addEventListener(this.onBeforeUSDZExport)}onDisable(){ho.beforeExport.removeEventListener(this.onBeforeUSDZExport)}onBeforeUSDZExport=e=>{this.activeAndEnabled&&this.trackedImages?.length&&e.exporter.extensions.push(new ML(e.exporter,this))};onBeforeXR(e,t){if(this.trackedImages){t.optionalFeatures=t.optionalFeatures||[],t.optionalFeatures.includes("image-tracking")||t.optionalFeatures.push("image-tracking"),t.trackedImages||(t.trackedImages=[]);for(const i of this.trackedImages)if(i.image?.length&&i.widthInMeters>0){const n=nd.get(i.image);n&&(this.trackedImageIndexMap.set(t.trackedImages.length,i),t.trackedImages.push({image:n,widthInMeters:i.widthInMeters}))}}}onEnterXR(e){if(this.trackedImages){for(const t of this.trackedImages)if(t.object?.asset){const i=t.object.asset;i.userData||(i.userData={});const n={visible:i.visible,parent:i.parent,matrix:i.matrix.clone()};i.userData["image-tracking"]=n}}for(const t of this.imageToObjectMap.values())t.frames=0}onLeaveXR(e){if(!this.supported&&I.isAndroidDevice()&&be(this.webXRIncubationsWarning),this.trackedImages){for(const t of this.trackedImages)if(t.object?.asset){const i=t.object.asset;if(i.userData){const n=i.userData["image-tracking"];n&&(i.visible=n.visible,n.parent?.add(i),i.matrix.copy(n.matrix),i.matrix.decompose(i.position,i.quaternion,i.scale)),delete i.userData["image-tracking"]}}}}imageToObjectMap=new Map;currentImages=[];webXRIncubationsWarning=`Image tracking is currently not supported on this device. On Chrome for Android, you can enable the <a target="_blank" href="#" onclick="() => console.log('I')">chrome://flags/#webxr-incubations</a> flag.`;onUpdateXR(e){this.currentImages.length=0;const t=e.xr.frame;if(!t)return;if("getImageTrackingResults"in t){if(e.xr.session.enabledFeatures?.includes("image-tracking")===!1)return;if(t.session&&typeof t.getImageTrackingResults=="function"){const n=t.getImageTrackingResults();if(n.length>0){const s=this.context.renderer.xr.getReferenceSpace();if(s){for(const r of n){const a=r.trackingState,l=r.index,c=this.trackedImageIndexMap.get(l);if(c){const h=t.getPose(r.imageSpace,s),d=new ac(this,c,r.image,r.measuredSize,a,h);this.currentImages.push(d)}else td&&console.warn("No tracked image for index",l)}if(this.currentImages.length>0)try{this.dispatchEvent(new CustomEvent("image-tracking",{detail:this.currentImages})),this.onImageTrackingUpdate(this.currentImages)}catch(r){console.error(r)}}}}}else{this.didPrintWarning||(this.didPrintWarning=!0,console.log(this.webXRIncubationsWarning)),this._supported=!1,be(this.webXRIncubationsWarning);return}const i=1e3;for(const[n,s]of this.imageToObjectMap){if(!s.object||!n||n.hideWhenTrackingIsLost===!1)continue;let r=!1;for(const a of this.currentImages)if(a.model===n){const l=Date.now()-s.lastTrackingTime;if(td&&Oe(n.image+", State: "+a.state+(n.imageDoesNotMove?" (static)":"")+(l<=i?" (hysteresis)":"")),n.imageDoesNotMove||a.state==="tracked"||l<=i){r=!0;break}}r||S.setActive(s.object,!1)}}onImageTrackingUpdate=e=>{const t=Z.active;if(t)for(const i of e){const n=i.model,s=i.state==="tracked";if(!n.object)continue;let r=this.imageToObjectMap.get(n);if(r===void 0)r={object:null,frames:0,lastTrackingTime:Date.now()},this.imageToObjectMap.set(n,r),n.object.loadAssetAsync().then(a=>{if(n.createObjectInstance&&a&&(a=S.instantiate(a)),a){r.object=a;for(const l of a.getComponentsInChildren(ei))l.setInstancingEnabled(!1);t.rig?(t.rig.gameObject.add(a),i.applyToObject(a),a.activeSelf||S.setActive(a,!0)):console.warn("XRImageTracking: missing XRRig")}});else{if(r.frames++,s&&(r.lastTrackingTime=Date.now()),n.imageDoesNotMove&&r.frames>10||!r.object)continue;t.rig&&(t.rig.gameObject.add(r.object),i.applyToObject(r.object,this.smooth?this.context.time.deltaTimeUnscaled*3:void 0),r.object.activeSelf||S.setActive(r.object,!0))}}}}lr([u(ls)],id.prototype,"trackedImages"),lr([u()],id.prototype,"smooth");const nd=new Map,pm=new Map;async function pS(o){if(nd.has(o))return pm.has(o)?pm.get(o):Promise.resolve(!0);const e=new Promise(t=>{nd.set(o,null);const i=document.createElement("img");i.src=o,i.addEventListener("load",async()=>{const n=await createImageBitmap(i);nd.set(o,n),t(!0)})});return pm.set(o,e),e.finally(()=>{pm.delete(o)}),e}var EL=Object.defineProperty,Jl=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&EL(e,t,n),n};const wa=w("debugplanetracking");class cs extends E{dataTemplate;occluder=!0;initiateRoomCaptureIfNoData=!0;usePlaneData=!0;useMeshData=!0;runInVR=!0;get trackedPlanes(){return this._allPlanes.values()}get trackedMeshes(){return this._allMeshes.values()}onBeforeXR(e,t){e==="immersive-vr"&&!this.runInVR||(t.optionalFeatures=t.optionalFeatures||[],this.usePlaneData&&!t.optionalFeatures.includes("plane-detection")&&t.optionalFeatures.push("plane-detection"),this.useMeshData&&!t.optionalFeatures.includes("mesh-detection")&&t.optionalFeatures.push("mesh-detection"))}onEnterXR(e){for(const t of this._allPlanes.keys())this.removeData(t,this._allPlanes);for(const t of this._allMeshes.keys())this.removeData(t,this._allMeshes)}onLeaveXR(e){for(const t of this._allPlanes.keys())this.removeData(t,this._allPlanes);for(const t of this._allMeshes.keys())this.removeData(t,this._allMeshes)}onUpdateXR(e){if(!this.runInVR&&e.xr.isVR)return;const t=e.xr.rig;if(!t){console.warn("No XR rig found, cannot parent tracked planes to it");return}const i=e.xr.frame;if(!this.context.renderer.xr.getReferenceSpace())return;const n=i.detectedPlanes,s=i.detectedMeshes,r=n!==void 0&&n.size>0,a=s!==void 0&&s.size>0;if(this.initiateRoomCaptureIfNoData&&(!r&&!a&&this.firstTimeNoPlanesDetected<-10&&(this.firstTimeNoPlanesDetected=Date.now()),(r||a)&&(this.firstTimeNoPlanesDetected=-1),this.firstTimeNoPlanesDetected>0&&Date.now()-this.firstTimeNoPlanesDetected>2500&&"initiateRoomCapture"in i.session&&(i.session.initiateRoomCapture(),this.firstTimeNoPlanesDetected=-1)),n!==void 0&&this.processFrameData(e.xr,t.gameObject,i,n,this._allPlanes),s!==void 0&&this.processFrameData(e.xr,t.gameObject,i,s,this._allMeshes),wa){const l=this.context.mainCameraComponent.gameObject.worldPosition;for(const c of this._allPlanes.values())!c.mesh||!c.mesh.visible||(this.bounds.makeEmpty(),c.mesh.traverse(h=>{h instanceof H&&this.bounds.expandByObject(h)}),this.bounds.getCenter(this.center),this.labelOffset.copy(l).sub(this.center).normalize().multiplyScalar(.1),B.DrawLabel(this.center.add(this.labelOffset),(c.xrData.semanticLabel||"plane").toUpperCase()+`
1478
- `+c.xrData.lastChangedTime.toFixed(2),.02))}}bounds=new Si;center=new b;labelOffset=new b;removeData(e,t){const i=t.get(e);if(!i)return;t.delete(e),wa&&console.log("Plane no longer tracked, id="+i.id),i.mesh&&(i.mesh.removeFromParent(),i.mesh.traverse(s=>{const r=s.userData.normalsHelper;r?(r.dispose(),r.removeFromParent()):wa&&console.warn("No normals helper found for mesh",i.mesh)}),Ii(i.mesh,!0,!0));const n=new CustomEvent("plane-tracking",{detail:{type:"plane-removed",context:i}});this.dispatchEvent(n)}_dataId=1;_allPlanes=new Map;_allMeshes=new Map;firstTimeNoPlanesDetected=-100;makeOccluder=(e,t,i=!1)=>{if(t){if(t instanceof Array){for(const n of t)this.makeOccluder(e,n,i);return}!i&&!t.name.toLowerCase().includes("occlu")||(t.colorWrite=!1,t.depthTest=!0,t.depthWrite=!0,t.transparent=!1,t.polygonOffset=!0,t.polygonOffsetFactor=1,t.polygonOffsetUnits=.1,e.renderOrder=-1e3)}};processFrameData(e,t,i,n,s){const r=this.context.renderer.xr.getReferenceSpace();if(r){for(const a of s.keys())n.has(a)||this.removeData(a,s);for(const a of n){const l="planeSpace"in a?a.planeSpace:"meshSpace"in a?a.meshSpace:void 0;if(!l)continue;const c=i.getPose(l,r);let h;if(s.has(a)){const d=s.get(a);if(h=d.mesh,d.timestamp<a.lastChangedTime){if(d.timestamp=a.lastChangedTime,d.mesh){const m=this.createGeometry(a);if(d.mesh instanceof H)d.mesh.geometry.dispose(),d.mesh.geometry=m,this.makeOccluder(d.mesh,d.mesh.material);else if(d.mesh instanceof Co)for(const g of d.mesh.children)g instanceof H&&(g.geometry.dispose(),g.geometry=m,this.makeOccluder(g,g.material));if(d.collider){const g=d.mesh;d.collider.sharedMesh=g,d.collider.convex=this.checkIfContextShouldBeConvex(g,d.xrData),d.collider.onDisable(),d.collider.onEnable()}wa&&(console.log("Plane updated, id="+d.id,d),d.mesh.traverse(g=>{if(!(g instanceof H))return;const f=g.userData.normalsHelper;f&&f.update()}))}const p=new CustomEvent("plane-tracking",{detail:{type:"plane-updated",context:d}});this.dispatchEvent(p)}}else{if(!this.dataTemplate){const d=new H;wa?d.material=new nP:this.occluder?(d.material=new Ce,this.makeOccluder(d,d.material,!0)):d.material=new Ce({wireframe:!0,opacity:.5,transparent:!0,color:3355443}),this.dataTemplate=new ne("","",d)}if(!this.dataTemplate.asset)this.dataTemplate.loadAssetAsync();else{const d=S.instantiate(this.dataTemplate.asset);if(d.name="xr-tracked-plane",h=d,dg(d,!1),d instanceof H)ke(d.geometry),d.geometry=this.createGeometry(a),this.makeOccluder(d,d.material,this.occluder&&!this.dataTemplate);else if(d instanceof Co)for(const g of d.children)g instanceof H&&(ke(g.geometry),g.geometry=this.createGeometry(a),this.makeOccluder(g,g.material,this.occluder&&!this.dataTemplate));const p=d.getComponent(js);if(p){const g=d;p.sharedMesh=g,p.convex=this.checkIfContextShouldBeConvex(g,a),p.onDisable(),p.onEnable()}d.matrixAutoUpdate=!1,d.matrixWorldNeedsUpdate=!0,t.add(d);const m={id:this._dataId++,xrData:a,timestamp:a.lastChangedTime,mesh:d,collider:p};s.set(a,m),wa&&console.log("New plane detected, id="+m.id,m,{hasCollider:!!p,isGroup:d instanceof Co});try{const g=new CustomEvent("plane-tracking",{detail:{type:"plane-added",context:m}});this.dispatchEvent(g)}catch(g){console.error(g)}}}h&&(c?(h.visible=!0,h.matrix.fromArray(c.transform.matrix),h.matrix.premultiply(this._flipForwardMatrix)):h.visible=!1,wa&&h.traverse(d=>{if(d instanceof H)if(d.userData.normalsHelper)d.userData.normalsHelper.update();else{const p=new kP(d,.05,255);p.layers.disableAll(),p.layers.set(2),this.context.scene.add(p),d.userData.normalsHelper=p}}))}}}_flipForwardMatrix=new J().makeRotationY(Math.PI);checkIfContextShouldBeConvex(e,t){if(!e)return!0;if(e){const i=new Si;i.expandByObject(e);const n=new b;i.getSize(n);let s=!0;return n.x>2&&n.y>2&&n.z>1.5&&(s=!1),s&&"semanticLabel"in t&&t.semanticLabel==="wall"&&(s=!0),s}return!0}createGeometry(e){return"polygon"in e?this.createPlaneGeometry(e.polygon):"vertices"in e&&"indices"in e?this.createMeshGeometry(e.vertices,e.indices):new wn}_verticesCache=new Map;createMeshGeometry(e,t){const i=e.toString()+"_"+t.toString();if(this._verticesCache.has(i))return this._verticesCache.get(i);const n=new wn;n.setIndex(new ft(t,1)),n.setAttribute("position",new ft(e,3));const s=Array();for(let r=0;r<e.length;r+=3)s.push(e[r],e[r+2]);return n.setAttribute("uv",new ft(e,3)),n.computeVertexNormals(),this._verticesCache.set(i,n),n}createPlaneGeometry(e){const t=new wn,i=[],n=[];e.forEach(p=>{i.push(p.x,p.y,p.z),n.push(p.x,p.z)});const s=new b(i[0],i[1],i[2]),r=new b(i[3],i[4],i[5]),a=new b(i[6],i[7],i[8]),l=new b,c=new b;l.subVectors(r,s),c.subVectors(a,s),l.cross(c),l.normalize();const h=[];for(let p=0;p<i.length/3;p++)h.push(l.x,l.y,l.z);const d=[];for(let p=2;p<e.length;++p)d.push(0,p-1,p);return t.setAttribute("position",new ft(new Float32Array(i),3)),t.setAttribute("uv",new ft(new Float32Array(n),2)),t.setAttribute("normal",new ft(new Float32Array(h),3)),t.setIndex(d),t.computeBoundingBox(),t.computeBoundingSphere(),t}}Jl([u(ne)],cs.prototype,"dataTemplate"),Jl([u()],cs.prototype,"occluder"),Jl([u()],cs.prototype,"initiateRoomCaptureIfNoData"),Jl([u()],cs.prototype,"usePlaneData"),Jl([u()],cs.prototype,"useMeshData"),Jl([u()],cs.prototype,"runInVR");var RL=Object.defineProperty,TL=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&RL(e,t,n),n};const mS=w("debugwebxr");class mm extends E{priority=0;get isActive(){return this.activeAndEnabled&&this.gameObject.visible}setAsActiveXRRig(){Z.active?.setRigActive(this)}setPriority(e){this.priority=e}awake(){if(mS){const e=new M;e.position.y+=.5,this.gameObject.add(e);const t=e.addNewComponent(sa);t&&(t.isGizmo=!1);const i=new Ci(.5);this.gameObject.add(i)}}isXRRig(){return!0}supportsXR(e){return!0}_startScale;onEnterXR(e){this._startScale=this.gameObject.scale.clone(),e.xr.addRig(this),mS&&console.log("WebXR: add Rig",this.name,this.priority)}onLeaveXR(e){e.xr.removeRig(this),this._startScale&&this.gameObject&&this.gameObject.scale.copy(this._startScale)}}TL([u()],mm.prototype,"priority");class AL extends E{toggleKey="KeyP";update(){this.context.input.isKeyDown(this.toggleKey)&&this.context.domElement.classList.toggle("presentation-mode")}}C.add("AlignmentConstraint",Gc),C.add("Animation",Ut),C.add("Animator",_t),C.add("AudioListener",No),C.add("AudioSource",Di),C.add("Avatar_Brain_LookAt",eh),C.add("Avatar_MouthShapes",th),C.add("Avatar_MustacheShake",Vf),C.add("AvatarBlink_Simple",Gr),C.add("AvatarEyeLook_Rotation",Hf),C.add("AxesHelper",ul),C.add("BasicIKConstraint",qf),C.add("BoxHelperComponent",Pt),C.add("Camera",gi),C.add("CharacterController",qr),C.add("CharacterControllerInput",$o),C.add("SphereCollider",pl),C.add("BoxCollider",Gu),C.add("MeshCollider",js),C.add("CapsuleCollider",Wo),C.add("ContactShadows",nh),C.add("LogStats",Yf),C.add("DeleteBox",gr),C.add("Deletable",Kf),C.add("DeviceFlag",qu),C.add("DragControls",Yr),C.add("DropListener",Xo),C.add("Duplicatable",my),C.add("EventListEvent",Fu),C.add("EventTrigger",ap),C.add("GltfExportBox",by),C.add("GltfExport",vy),C.add("VariantAction",Ey),C.add("ChangeTransformOnClick",ea),C.add("ChangeMaterialOnClick",Ty),C.add("SetActiveOnClick",Ay),C.add("HideOnStart",fn),C.add("EmphasizeOnClick",Ol),C.add("PlayAudioOnClick",zs),C.add("PlayAnimationOnClick",hh),C.add("PreliminaryAction",kl),C.add("PreliminaryTrigger",dh),C.add("VisibilityAction",uh),C.add("TapGestureTrigger",Ly),C.add("USDZExporter",ho),C.add("Fog",Dl),C.add("BoxGizmo",sa),C.add("GridHelper",jl),C.add("GroundProjectedEnv",Kn),C.add("UsageMarker",oh),C.add("Interactable",Zf),C.add("FixedJoint",l0),C.add("HingeJoint",Sh),C.add("Light",At),C.add("LODGroup",Mp),C.add("LookAtConstraint",Wr),C.add("NeedleMenu",lo),C.add("NestedGltf",Ul),C.add("Networking",u0),C.add("OffsetConstraint",ra),C.add("CameraTargetReachedEvent",Jc),C.add("OrbitControls",ge),C.add("ParticleSystemRenderer",ln),C.add("ParticleSystem",kh),C.add("Attractor",Wl),C.add("PlayerColor",rc),C.add("Antialiasing",Eh),C.add("BloomEffect",Wp),C.add("ChromaticAberration",Rh),C.add("ColorAdjustments",er),C.add("DepthOfField",jn),C.add("EffectWrapper",Ah),C.add("PixelationEffect",Ih),C.add("ScreenSpaceAmbientOcclusion",is),C.add("ScreenSpaceAmbientOcclusionN8",Bn),C.add("SharpeningEffect",Dh),C.add("TiltShiftEffect",uo),C.add("ToneMappingEffect",Js),C.add("Vignette",pa),C.add("Volume",$l),C.add("ReflectionProbe",Go),C.add("Renderer",ei),C.add("MeshRenderer",ah),C.add("SkinnedMeshRenderer",uy),C.add("Rigidbody",Ze),C.add("SceneSwitcher",Ke),C.add("ScreenCapture",ir),C.add("SeeThrough",os),C.add("ShadowCatcher",Uh),C.add("RemoteSkybox",Xp),C.add("SmoothFollow",Yp),C.add("SpatialTriggerReceiver",po),C.add("SpatialTrigger",Zp),C.add("SpectatorCamera",Kp),C.add("SplineContainer",fa),C.add("SplineWalker",hn),C.add("SpriteRenderer",yi),C.add("SyncedCamera",D0),C.add("SyncedRoom",Fn),C.add("SyncedTransform",Tn),C.add("TestRunner",F0),C.add("TestSimulateUserData",U0),C.add("PlayableDirector",ya),C.add("SignalReceiver",Hh),C.add("AnimationTrackHandler",Gh),C.add("AudioTrackHandler",fs),C.add("MarkerTrackHandler",im),C.add("SignalTrackHandler",qh),C.add("ControlTrackHandler",nm),C.add("TransformGizmo",ba),C.add("BaseUIComponent",un),C.add("UIRootComponent",yh),C.add("Button",ss),C.add("Canvas",Ll),C.add("CanvasGroup",qs),C.add("EventSystem",ai),C.add("Graphic",vh),C.add("MaskableGraphic",wh),C.add("Image",Xl),C.add("RawImage",rm),C.add("InputField",V0),C.add("VerticalLayoutGroup",Zy),C.add("HorizontalLayoutGroup",Ky),C.add("GridLayoutGroup",Jy),C.add("Outline",Al),C.add("ObjectRaycaster",Ji),C.add("GraphicRaycaster",Nu),C.add("SpatialGrabRaycaster",Ca),C.add("RectTransform",Ln),C.add("SpatialHtml",Qh),C.add("Text",Ht),C.add("EnvironmentScene",lm),C.add("LookAt",$0),C.add("OpenURL",Ql),C.add("VideoPlayer",pt),C.add("Voip",Ds),C.add("ClickThrough",hm),C.add("CursorFollow",va),C.add("HoverAnimation",yo),C.add("ScrollFollow",rs),C.add("ViewBox",st),C.add("Avatar",Ws),C.add("XRControllerFollow",as),C.add("XRControllerModel",Zo),C.add("XRControllerMovement",Bi),C.add("TeleportTarget",xp),C.add("WebARCameraBackground",ed),C.add("WebARSessionRoot",yn),C.add("WebXR",Sp),C.add("AvatarMarker",Le),C.add("WebXRImageTracking",id),C.add("WebXRPlaneTracking",cs),C.add("XRRig",mm),C.add("XRFlag",tn),C.add("PlayerSync",zy),C.add("PlayerState",sn),C.add("PresentationMode",AL);const od=bt,IL=w("debugtypestore");IL&&console.log(C);function LL(o,e){const t=ew(o,e);return t!==void 0?t:null}const DL=new EM,Z0=Symbol("deserialize-queue");async function jL(o,e,t,i=null,n){if(!t){console.debug("Can not create component instances: gltf is null");return}const s=[];let r=i;typeof r=="number"&&(r=new Bt(i));const a=e.indexOf("?");e=a===-1?e:e.substring(0,a);const l=new sf(t.scene);l.gltfId=e,l.context=o,l.gltf=t,l.nodeToObject=n?.nodeToObjectMap,l.implementationInformation=DL;let c=o[Z0];if(c||(c=o[Z0]=[]),t.scenes)for(const h of t.scenes)await eb(l,h,c,s,0);if(t.children)for(const h of t.children)await eb(l,h,c,s,0);o.new_scripts_pre_setup_callbacks.push(()=>{const h=o[Z0];if(h){for(const d of h)BL(d,l);h.length=0}if(r){const d={},p=[];J0(t,r,d,p);for(const m of t.scenes)J0(m,r,d,p);for(const m of p)m.resolveGuids(d)}})}const K0=Symbol("original-component-name"),ec=new Map;function J0(o,e,t,i){if(e===null||!o)return;const n=o.guid,s=o.guid;s?.length&&(ec.has(s)||(od&&console.log('Creating InstanceIdProvider with key "'+s+'" for object '+o.name),ec.set(s,new Bt(s))));const r=s&&ec.get(s)||e;if(o.guid=r.generateUUID(),n&&n!=="invalid"&&(t[n]=o.guid),o&&o.userData&&o.userData.components)for(const a of o.userData.components){if(a===null)continue;const l=a.guid;l?ec.has(l)||(od&&console.log('Creating InstanceIdProvider with key "'+l+'" for component '+a[K0]),ec.set(l,new Bt(l))):od&&console.warn("Can not create IdProvider: component "+a[K0]+" has no guid",a.guid);const c=ec.get(l)||e,h=a.guid;a.guid=c.generateUUID(),h&&h!=="invalid"&&(t[h]=a.guid),a.resolveGuids&&i.push(a)}if(o.children)for(const a of o.children)J0(a,e,t,i)}const sd=[];async function eb(o,e,t,i,n){if(!e)return;const s=e.userData;if(s){const r=s.builtin_components;if(r&&r.length>0)for(const a of r)try{if(a===null)continue;const l=C.get(a.name);if(l!=null){const c=new l;c.sourceId=o.gltfId,Ja(c,a,o.implementationInformation),c.context=o.context,"guid"in a&&(c[xc]=a.guid),c[K0]=a.name,Lr(e,c,!1),t.push({instance:c,compData:a,obj:e}),c.isCamera&&o.context&&o.context.mainCamera===null&&c.tag==="MainCamera"&&o.context.setCurrentCamera(c),o.context?.physics?.engine?.isInitialized===!1&&(c.isCollider||c.isRigidbody)&&o.context?.physics.engine?.initialize()}else od&&console.debug("unknown component: "+a.name),sd.includes(a.name)||sd.push(a.name)}catch(l){console.error(a.name+" - "+l.message,l)}}if(e.children)for(const r of e.children)await eb(o,r,t,i,n+1);if(sd.length>0&&n===0){const r=sd.join(", ");console.warn(`Unknown components in scene: ${r}`),sd.length=0,ki()&&Oe(`<strong>Unknown components in scene</strong>:
1478
+ `+c.xrData.lastChangedTime.toFixed(2),.02))}}bounds=new Si;center=new b;labelOffset=new b;removeData(e,t){const i=t.get(e);if(!i)return;t.delete(e),wa&&console.log("Plane no longer tracked, id="+i.id),i.mesh&&(i.mesh.removeFromParent(),i.mesh.traverse(s=>{const r=s.userData.normalsHelper;r?(r.dispose(),r.removeFromParent()):wa&&console.warn("No normals helper found for mesh",i.mesh)}),Ii(i.mesh,!0,!0));const n=new CustomEvent("plane-tracking",{detail:{type:"plane-removed",context:i}});this.dispatchEvent(n)}_dataId=1;_allPlanes=new Map;_allMeshes=new Map;firstTimeNoPlanesDetected=-100;makeOccluder=(e,t,i=!1)=>{if(t){if(t instanceof Array){for(const n of t)this.makeOccluder(e,n,i);return}!i&&!t.name.toLowerCase().includes("occlu")||(t.colorWrite=!1,t.depthTest=!0,t.depthWrite=!0,t.transparent=!1,t.polygonOffset=!0,t.polygonOffsetFactor=1,t.polygonOffsetUnits=.1,e.renderOrder=-1e3)}};processFrameData(e,t,i,n,s){const r=this.context.renderer.xr.getReferenceSpace();if(r){for(const a of s.keys())n.has(a)||this.removeData(a,s);for(const a of n){const l="planeSpace"in a?a.planeSpace:"meshSpace"in a?a.meshSpace:void 0;if(!l)continue;const c=i.getPose(l,r);let h;if(s.has(a)){const d=s.get(a);if(h=d.mesh,d.timestamp<a.lastChangedTime){if(d.timestamp=a.lastChangedTime,d.mesh){const m=this.createGeometry(a);if(d.mesh instanceof H)d.mesh.geometry.dispose(),d.mesh.geometry=m,this.makeOccluder(d.mesh,d.mesh.material);else if(d.mesh instanceof Co)for(const g of d.mesh.children)g instanceof H&&(g.geometry.dispose(),g.geometry=m,this.makeOccluder(g,g.material));if(d.collider){const g=d.mesh;d.collider.sharedMesh=g,d.collider.convex=this.checkIfContextShouldBeConvex(g,d.xrData),d.collider.onDisable(),d.collider.onEnable()}wa&&(console.log("Plane updated, id="+d.id,d),d.mesh.traverse(g=>{if(!(g instanceof H))return;const f=g.userData.normalsHelper;f&&f.update()}))}const p=new CustomEvent("plane-tracking",{detail:{type:"plane-updated",context:d}});this.dispatchEvent(p)}}else{if(!this.dataTemplate){const d=new H;wa?d.material=new nP:this.occluder?(d.material=new Ce,this.makeOccluder(d,d.material,!0)):d.material=new Ce({wireframe:!0,opacity:.5,transparent:!0,color:3355443}),this.dataTemplate=new ne("","",d)}if(!this.dataTemplate.asset)this.dataTemplate.loadAssetAsync();else{const d=S.instantiate(this.dataTemplate.asset);if(d.name="xr-tracked-plane",h=d,dg(d,!1),d instanceof H)ke(d.geometry),d.geometry=this.createGeometry(a),this.makeOccluder(d,d.material,this.occluder&&!this.dataTemplate);else if(d instanceof Co)for(const g of d.children)g instanceof H&&(ke(g.geometry),g.geometry=this.createGeometry(a),this.makeOccluder(g,g.material,this.occluder&&!this.dataTemplate));const p=d.getComponent(js);if(p){const g=d;p.sharedMesh=g,p.convex=this.checkIfContextShouldBeConvex(g,a),p.onDisable(),p.onEnable()}d.matrixAutoUpdate=!1,d.matrixWorldNeedsUpdate=!0,t.add(d);const m={id:this._dataId++,xrData:a,timestamp:a.lastChangedTime,mesh:d,collider:p};s.set(a,m),wa&&console.log("New plane detected, id="+m.id,m,{hasCollider:!!p,isGroup:d instanceof Co});try{const g=new CustomEvent("plane-tracking",{detail:{type:"plane-added",context:m}});this.dispatchEvent(g)}catch(g){console.error(g)}}}h&&(c?(h.visible=!0,h.matrix.fromArray(c.transform.matrix),h.matrix.premultiply(this._flipForwardMatrix)):h.visible=!1,wa&&h.traverse(d=>{if(d instanceof H)if(d.userData.normalsHelper)d.userData.normalsHelper.update();else{const p=new kP(d,.05,255);p.layers.disableAll(),p.layers.set(2),this.context.scene.add(p),d.userData.normalsHelper=p}}))}}}_flipForwardMatrix=new J().makeRotationY(Math.PI);checkIfContextShouldBeConvex(e,t){if(!e)return!0;if(e){const i=new Si;i.expandByObject(e);const n=new b;i.getSize(n);let s=!0;return n.x>2&&n.y>2&&n.z>1.5&&(s=!1),s&&"semanticLabel"in t&&t.semanticLabel==="wall"&&(s=!0),s}return!0}createGeometry(e){return"polygon"in e?this.createPlaneGeometry(e.polygon):"vertices"in e&&"indices"in e?this.createMeshGeometry(e.vertices,e.indices):new wn}_verticesCache=new Map;createMeshGeometry(e,t){const i=e.toString()+"_"+t.toString();if(this._verticesCache.has(i))return this._verticesCache.get(i);const n=new wn;n.setIndex(new ft(t,1)),n.setAttribute("position",new ft(e,3));const s=Array();for(let r=0;r<e.length;r+=3)s.push(e[r],e[r+2]);return n.setAttribute("uv",new ft(e,3)),n.computeVertexNormals(),this._verticesCache.set(i,n),n}createPlaneGeometry(e){const t=new wn,i=[],n=[];e.forEach(p=>{i.push(p.x,p.y,p.z),n.push(p.x,p.z)});const s=new b(i[0],i[1],i[2]),r=new b(i[3],i[4],i[5]),a=new b(i[6],i[7],i[8]),l=new b,c=new b;l.subVectors(r,s),c.subVectors(a,s),l.cross(c),l.normalize();const h=[];for(let p=0;p<i.length/3;p++)h.push(l.x,l.y,l.z);const d=[];for(let p=2;p<e.length;++p)d.push(0,p-1,p);return t.setAttribute("position",new ft(new Float32Array(i),3)),t.setAttribute("uv",new ft(new Float32Array(n),2)),t.setAttribute("normal",new ft(new Float32Array(h),3)),t.setIndex(d),t.computeBoundingBox(),t.computeBoundingSphere(),t}}Jl([u(ne)],cs.prototype,"dataTemplate"),Jl([u()],cs.prototype,"occluder"),Jl([u()],cs.prototype,"initiateRoomCaptureIfNoData"),Jl([u()],cs.prototype,"usePlaneData"),Jl([u()],cs.prototype,"useMeshData"),Jl([u()],cs.prototype,"runInVR");var RL=Object.defineProperty,TL=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&RL(e,t,n),n};const mS=w("debugwebxr");class mm extends E{priority=0;get isActive(){return this.activeAndEnabled&&this.gameObject.visible}setAsActiveXRRig(){Z.active?.setRigActive(this)}setPriority(e){this.priority=e}awake(){if(mS){const e=new M;e.position.y+=.5,this.gameObject.add(e);const t=e.addNewComponent(sa);t&&(t.isGizmo=!1);const i=new Ci(.5);this.gameObject.add(i)}}isXRRig(){return!0}supportsXR(e){return!0}_startScale;onEnterXR(e){this._startScale=this.gameObject.scale.clone(),e.xr.addRig(this),mS&&console.log("WebXR: add Rig",this.name,this.priority)}onLeaveXR(e){e.xr.removeRig(this),this._startScale&&this.gameObject&&this.gameObject.scale.copy(this._startScale)}}TL([u()],mm.prototype,"priority");class AL extends E{toggleKey="KeyP";update(){this.context.input.isKeyDown(this.toggleKey)&&this.context.domElement.classList.toggle("presentation-mode")}}C.add("AlignmentConstraint",Gc),C.add("Animation",Ut),C.add("Animator",_t),C.add("AudioListener",No),C.add("AudioSource",Di),C.add("Avatar_Brain_LookAt",eh),C.add("Avatar_MouthShapes",th),C.add("Avatar_MustacheShake",Vf),C.add("AvatarBlink_Simple",Gr),C.add("AvatarEyeLook_Rotation",Hf),C.add("AxesHelper",ul),C.add("BasicIKConstraint",qf),C.add("BoxHelperComponent",Pt),C.add("Camera",gi),C.add("CharacterController",qr),C.add("CharacterControllerInput",$o),C.add("SphereCollider",pl),C.add("BoxCollider",Gu),C.add("MeshCollider",js),C.add("CapsuleCollider",Wo),C.add("ContactShadows",nh),C.add("LogStats",Yf),C.add("DeleteBox",gr),C.add("Deletable",Kf),C.add("DeviceFlag",qu),C.add("DragControls",Yr),C.add("DropListener",Xo),C.add("Duplicatable",my),C.add("EventListEvent",Fu),C.add("EventTrigger",ap),C.add("GltfExportBox",by),C.add("GltfExport",vy),C.add("VariantAction",Ey),C.add("ChangeTransformOnClick",ea),C.add("ChangeMaterialOnClick",Ty),C.add("SetActiveOnClick",Ay),C.add("HideOnStart",fn),C.add("EmphasizeOnClick",Ol),C.add("PlayAudioOnClick",zs),C.add("PlayAnimationOnClick",hh),C.add("PreliminaryAction",kl),C.add("PreliminaryTrigger",dh),C.add("VisibilityAction",uh),C.add("TapGestureTrigger",Ly),C.add("USDZExporter",ho),C.add("Fog",Dl),C.add("BoxGizmo",sa),C.add("GridHelper",jl),C.add("GroundProjectedEnv",Kn),C.add("UsageMarker",oh),C.add("Interactable",Zf),C.add("FixedJoint",l0),C.add("HingeJoint",Sh),C.add("Light",At),C.add("LODGroup",Mp),C.add("LookAtConstraint",Wr),C.add("NeedleMenu",lo),C.add("NestedGltf",Ul),C.add("Networking",u0),C.add("OffsetConstraint",ra),C.add("CameraTargetReachedEvent",Jc),C.add("OrbitControls",ge),C.add("ParticleSystemRenderer",ln),C.add("ParticleSystem",kh),C.add("Attractor",Wl),C.add("PlayerColor",rc),C.add("Antialiasing",Eh),C.add("BloomEffect",Wp),C.add("ChromaticAberration",Rh),C.add("ColorAdjustments",er),C.add("DepthOfField",jn),C.add("EffectWrapper",Ah),C.add("PixelationEffect",Ih),C.add("ScreenSpaceAmbientOcclusion",is),C.add("ScreenSpaceAmbientOcclusionN8",Bn),C.add("SharpeningEffect",Dh),C.add("TiltShiftEffect",uo),C.add("ToneMappingEffect",Js),C.add("Vignette",pa),C.add("Volume",$l),C.add("ReflectionProbe",Go),C.add("Renderer",ei),C.add("MeshRenderer",ah),C.add("SkinnedMeshRenderer",uy),C.add("Rigidbody",Ke),C.add("SceneSwitcher",Je),C.add("ScreenCapture",ir),C.add("SeeThrough",os),C.add("ShadowCatcher",Uh),C.add("RemoteSkybox",Xp),C.add("SmoothFollow",Yp),C.add("SpatialTriggerReceiver",po),C.add("SpatialTrigger",Zp),C.add("SpectatorCamera",Kp),C.add("SplineContainer",fa),C.add("SplineWalker",hn),C.add("SpriteRenderer",yi),C.add("SyncedCamera",D0),C.add("SyncedRoom",Fn),C.add("SyncedTransform",Tn),C.add("TestRunner",F0),C.add("TestSimulateUserData",U0),C.add("PlayableDirector",ya),C.add("SignalReceiver",Hh),C.add("AnimationTrackHandler",Gh),C.add("AudioTrackHandler",fs),C.add("MarkerTrackHandler",im),C.add("SignalTrackHandler",qh),C.add("ControlTrackHandler",nm),C.add("TransformGizmo",ba),C.add("BaseUIComponent",un),C.add("UIRootComponent",yh),C.add("Button",ss),C.add("Canvas",Ll),C.add("CanvasGroup",qs),C.add("EventSystem",ai),C.add("Graphic",vh),C.add("MaskableGraphic",wh),C.add("Image",Xl),C.add("RawImage",rm),C.add("InputField",V0),C.add("VerticalLayoutGroup",Zy),C.add("HorizontalLayoutGroup",Ky),C.add("GridLayoutGroup",Jy),C.add("Outline",Al),C.add("ObjectRaycaster",Ji),C.add("GraphicRaycaster",Nu),C.add("SpatialGrabRaycaster",Ca),C.add("RectTransform",Ln),C.add("SpatialHtml",Qh),C.add("Text",Ht),C.add("EnvironmentScene",lm),C.add("LookAt",$0),C.add("OpenURL",Ql),C.add("VideoPlayer",pt),C.add("Voip",Ds),C.add("ClickThrough",hm),C.add("CursorFollow",va),C.add("HoverAnimation",yo),C.add("ScrollFollow",rs),C.add("ViewBox",st),C.add("Avatar",Ws),C.add("XRControllerFollow",as),C.add("XRControllerModel",Zo),C.add("XRControllerMovement",Bi),C.add("TeleportTarget",xp),C.add("WebARCameraBackground",ed),C.add("WebARSessionRoot",yn),C.add("WebXR",Sp),C.add("AvatarMarker",Le),C.add("WebXRImageTracking",id),C.add("WebXRPlaneTracking",cs),C.add("XRRig",mm),C.add("XRFlag",tn),C.add("PlayerSync",zy),C.add("PlayerState",sn),C.add("PresentationMode",AL);const od=bt,IL=w("debugtypestore");IL&&console.log(C);function LL(o,e){const t=ew(o,e);return t!==void 0?t:null}const DL=new EM,Z0=Symbol("deserialize-queue");async function jL(o,e,t,i=null,n){if(!t){console.debug("Can not create component instances: gltf is null");return}const s=[];let r=i;typeof r=="number"&&(r=new Bt(i));const a=e.indexOf("?");e=a===-1?e:e.substring(0,a);const l=new sf(t.scene);l.gltfId=e,l.context=o,l.gltf=t,l.nodeToObject=n?.nodeToObjectMap,l.implementationInformation=DL;let c=o[Z0];if(c||(c=o[Z0]=[]),t.scenes)for(const h of t.scenes)await eb(l,h,c,s,0);if(t.children)for(const h of t.children)await eb(l,h,c,s,0);o.new_scripts_pre_setup_callbacks.push(()=>{const h=o[Z0];if(h){for(const d of h)BL(d,l);h.length=0}if(r){const d={},p=[];J0(t,r,d,p);for(const m of t.scenes)J0(m,r,d,p);for(const m of p)m.resolveGuids(d)}})}const K0=Symbol("original-component-name"),ec=new Map;function J0(o,e,t,i){if(e===null||!o)return;const n=o.guid,s=o.guid;s?.length&&(ec.has(s)||(od&&console.log('Creating InstanceIdProvider with key "'+s+'" for object '+o.name),ec.set(s,new Bt(s))));const r=s&&ec.get(s)||e;if(o.guid=r.generateUUID(),n&&n!=="invalid"&&(t[n]=o.guid),o&&o.userData&&o.userData.components)for(const a of o.userData.components){if(a===null)continue;const l=a.guid;l?ec.has(l)||(od&&console.log('Creating InstanceIdProvider with key "'+l+'" for component '+a[K0]),ec.set(l,new Bt(l))):od&&console.warn("Can not create IdProvider: component "+a[K0]+" has no guid",a.guid);const c=ec.get(l)||e,h=a.guid;a.guid=c.generateUUID(),h&&h!=="invalid"&&(t[h]=a.guid),a.resolveGuids&&i.push(a)}if(o.children)for(const a of o.children)J0(a,e,t,i)}const sd=[];async function eb(o,e,t,i,n){if(!e)return;const s=e.userData;if(s){const r=s.builtin_components;if(r&&r.length>0)for(const a of r)try{if(a===null)continue;const l=C.get(a.name);if(l!=null){const c=new l;c.sourceId=o.gltfId,Ja(c,a,o.implementationInformation),c.context=o.context,"guid"in a&&(c[xc]=a.guid),c[K0]=a.name,Lr(e,c,!1),t.push({instance:c,compData:a,obj:e}),c.isCamera&&o.context&&o.context.mainCamera===null&&c.tag==="MainCamera"&&o.context.setCurrentCamera(c),o.context?.physics?.engine?.isInitialized===!1&&(c.isCollider||c.isRigidbody)&&o.context?.physics.engine?.initialize()}else od&&console.debug("unknown component: "+a.name),sd.includes(a.name)||sd.push(a.name)}catch(l){console.error(a.name+" - "+l.message,l)}}if(e.children)for(const r of e.children)await eb(o,r,t,i,n+1);if(sd.length>0&&n===0){const r=sd.join(", ");console.warn(`Unknown components in scene: ${r}`),sd.length=0,ki()&&Oe(`<strong>Unknown components in scene</strong>:
1479
1479
 
1480
1480
  ${r}
1481
1481
 
@@ -1534,7 +1534,7 @@ Please refer to the documentation on <a href="https://fwd.needle.tools/needle-en
1534
1534
  width: 100%;
1535
1535
  opacity: 0;
1536
1536
  transition: opacity 1s ease-in-out 4s;
1537
- `,setTimeout(()=>{d.style.opacity="1"},1),this._loadingElement.appendChild(d);const p=document.createElement("div"),m=100;return p.style.display="flex",p.style.width=m+"%",p.style.height="5px",p.style.position="absolute",p.style.left="0",p.style.top="0px",p.style.opacity="0",p.style.transition="opacity 1s ease-in-out",p.style.backgroundColor="rgba(240,240,240,.5)",setTimeout(()=>{p.style.opacity="1"},1),this._loadingElement.appendChild(p),this._loadingBar=document.createElement("div"),p.appendChild(this._loadingBar),this._loadingBar.style.backgroundAttachment="fixed",this._loadingBar.style.background="#c4c4c4ab",this._loadingBarFinishedColor="#ddddddab",this._loadingBar.style.width="0%",this._loadingBar.style.height="100%",this._loadingElement}}yg(gS);const Re=w("debugwebcomponent"),xS="needle-engine",SS="vr",CS="desktop",GL=[vS,SS,CS],hd="ar-session-active",dd="desktop-session-active",qL=["src","hash","camera-controls","dracoDecoderPath","dracoDecoderType","ktx2DecoderPath","public-key","version","tone-mapping","tone-mapping-exposure","background-blurriness","background-color","environment-intensity","focus-rect","loadstart","progress","loadfinished"];class nb extends HTMLElement{static get observedAttributes(){return qL}get loadingProgress01(){return this._loadingProgress01}get loadingFinished(){return this.loadingProgress01>.999}get cameraControls(){const e=this.getAttribute("camera-controls");return e==null?null:!(e===null||e==="False"||e==="false"||e==="0"||e==="none")}set cameraControls(e){e===null?this.removeAttribute("camera-controls"):this.setAttribute("camera-controls",e?"true":"false")}getContext(){return new Promise((e,t)=>{if(this._context&&this.loadingFinished)e(this._context);else{const i=()=>{this.removeEventListener("loadfinished",i),this._context&&this.loadingFinished&&e(this._context)};this.addEventListener("loadfinished",i)}})}get context(){return this._context}_context;_overlay_ar;_loadingProgress01=0;_loadingView;_previousSrc=null;_didFullyLoad=!1;_didInitialize=!1;constructor(){super(),this.addEventListener("ready",this.onReady),this._overlay_ar=new $L,this._context=new U({domElement:this})}ensureInitialized(){this._didInitialize||(this._didInitialize=!0,this.initializeDom())}initializeDom(){Uw();const e=this.attachShadow({mode:"open",delegatesFocus:!0});this.setAttribute("role","application"),this.setAttribute("aria-label","Needle Engine 3D scene");const t=document.createElement("template");t.innerHTML=`<style>
1537
+ `,setTimeout(()=>{d.style.opacity="1"},1),this._loadingElement.appendChild(d);const p=document.createElement("div"),m=100;return p.style.display="flex",p.style.width=m+"%",p.style.height="5px",p.style.position="absolute",p.style.left="0",p.style.top="0px",p.style.opacity="0",p.style.transition="opacity 1s ease-in-out",p.style.backgroundColor="rgba(240,240,240,.5)",setTimeout(()=>{p.style.opacity="1"},1),this._loadingElement.appendChild(p),this._loadingBar=document.createElement("div"),p.appendChild(this._loadingBar),this._loadingBar.style.backgroundAttachment="fixed",this._loadingBar.style.background="#c4c4c4ab",this._loadingBarFinishedColor="#ddddddab",this._loadingBar.style.width="0%",this._loadingBar.style.height="100%",this._loadingElement}}yg(gS);const Re=w("debugwebcomponent"),xS="needle-engine",SS="vr",CS="desktop",GL=[vS,SS,CS],hd="ar-session-active",dd="desktop-session-active",qL=["src","hash","camera-controls","dracoDecoderPath","dracoDecoderType","ktx2DecoderPath","public-key","version","tone-mapping","tone-mapping-exposure","background-blurriness","background-color","environment-intensity","focus-rect","loadstart","progress","loadfinished"];class nb extends HTMLElement{static get observedAttributes(){return qL}get loadingProgress01(){return this._loadingProgress01}get loadingFinished(){return this.loadingProgress01>.999}get cameraControls(){const e=this.getAttribute("camera-controls");return e==null?null:!(e===null||e==="False"||e==="false"||e==="0"||e==="none")}set cameraControls(e){e===null?this.removeAttribute("camera-controls"):this.setAttribute("camera-controls",e?"true":"false")}getContext(){return new Promise((e,t)=>{if(this._context&&this.loadingFinished)e(this._context);else{const i=()=>{this.removeEventListener("loadfinished",i),this._context&&this.loadingFinished&&e(this._context)};this.addEventListener("loadfinished",i)}})}get context(){return this._context}_context;_overlay_ar;_loadingProgress01=0;_loadingView;_previousSrc=null;_didFullyLoad=!1;_didInitialize=!1;constructor(){super(),this.attachShadow({mode:"open",delegatesFocus:!0});const e=document.createElement("template");e.innerHTML=`<style>
1538
1538
  @import url('https://fonts.googleapis.com/css2?family=Roboto+Flex:opsz,wght@8..144,100..1000&display=swap');
1539
1539
 
1540
1540
  :host {
@@ -1599,7 +1599,7 @@ Please refer to the documentation on <a href="https://fwd.needle.tools/needle-en
1599
1599
  }
1600
1600
  :host .quit-ar-button {
1601
1601
  position: absolute;
1602
- // top: env(titlebar-area-y); /** this doesnt work **/
1602
+ /** top: env(titlebar-area-y); this doesnt work **/
1603
1603
  top: 60px; /** camera access needs a bit more space **/
1604
1604
  right: 20px;
1605
1605
  z-index: 9999;
@@ -1611,7 +1611,7 @@ Please refer to the documentation on <a href="https://fwd.needle.tools/needle-en
1611
1611
  <div class="content">
1612
1612
  <slot class="overlay-content" style="display: contents;"></slot>
1613
1613
  </div>
1614
- `,e.appendChild(t.content.cloneNode(!0)),this.addEventListener("error",this.onError)}async connectedCallback(){if(Re&&console.log("<needle-engine> connected"),this.ensureInitialized(),this.setPublicKey(),this.setVersion(),(this.getAttribute("tabindex")===null||this.getAttribute("tabindex")===void 0)&&this.setAttribute("tabindex","0"),this.addEventListener("xr-session-started",this.onXRSessionStarted),this.onSetupDesktop(),!this.getAttribute("src")){const t=globalThis["needle:codegen_files"];Re&&console.log('src is null, trying to load from globalThis["needle:codegen_files"]',t),t&&(Re&&console.log('globalThis["needle:codegen_files"]',t),this.setAttribute("src",t))}Re&&console.log("src",this.getAttribute("src"));const e=this._loadId;setTimeout(()=>{this.isConnected!==!1&&e===this._loadId&&this.onLoad()},1)}disconnectedCallback(){this.removeEventListener("xr-session-started",this.onXRSessionStarted),this._didFullyLoad=!1;const e=this.getAttribute("keep-alive"),t=e==null||e?.length>0&&e!=="true"&&e!=="1";Re&&console.warn('<needle-engine> disconnected, keep-alive: "'+e+'"',typeof e,"Dispose=",t),t?(Re&&console.warn("<needle-engine> dispose"),this._context?.dispose(),this._context=null,this._lastSourceFiles=null,this._loadId+=1):Re&&console.warn("<needle-engine> is not disposed because keep-alive is set")}connectedMoveCallback(){}attributeChangedCallback(e,t,i){switch(Re&&console.log("attributeChangedCallback",e,t,i),e){case"src":Re&&console.warn(`<needle-engine src>
1614
+ `,this.shadowRoot.appendChild(e.content.cloneNode(!0)),this.addEventListener("ready",this.onReady),this.addEventListener("error",this.onError)}ensureInitialized(){this._didInitialize||(this._didInitialize=!0,this.initializeDom())}initializeDom(){Uw(),this.setAttribute("role","application"),this.setAttribute("aria-label","Needle Engine 3D scene")}connectedCallback(){if(Re&&console.log("<needle-engine> connected"),this.ensureInitialized(),this.setPublicKey(),this.setVersion(),(this.getAttribute("tabindex")===null||this.getAttribute("tabindex")===void 0)&&this.setAttribute("tabindex","0"),this._overlay_ar=new $L,this._context??=new U({domElement:this}),this.addEventListener("xr-session-started",this.onXRSessionStarted),this.onSetupDesktop(),!this.getAttribute("src")){const t=globalThis["needle:codegen_files"];Re&&console.log('src is null, trying to load from globalThis["needle:codegen_files"]',t),t&&(Re&&console.log('globalThis["needle:codegen_files"]',t),this.setAttribute("src",t))}Re&&console.log("src",this.getAttribute("src"));const e=this._loadId;setTimeout(()=>{this.isConnected!==!1&&e===this._loadId&&this.onLoad()},1)}disconnectedCallback(){this.removeEventListener("xr-session-started",this.onXRSessionStarted),this._didFullyLoad=!1;const e=this.getAttribute("keep-alive"),t=e==null||e?.length>0&&e!=="true"&&e!=="1";Re&&console.warn('<needle-engine> disconnected, keep-alive: "'+e+'"',typeof e,"Dispose=",t),t?(Re&&console.warn("<needle-engine> dispose"),this._context?.dispose(),this._context=null,this._lastSourceFiles=null,this._loadId+=1):Re&&console.warn("<needle-engine> is not disposed because keep-alive is set")}connectedMoveCallback(){}attributeChangedCallback(e,t,i){switch(Re&&console.log("attributeChangedCallback",e,t,i),e){case"src":Re&&console.warn(`<needle-engine src>
1615
1615
  changed from "`,t,'" to "',i,'"'),this.onLoad();break;case"hash":this._context&&(this._context.hash=i);break;case"loadstart":case"progress":case"loadfinished":typeof i=="string"&&i.length>0&&(Re&&console.log(e+" attribute changed",i),this.registerEventFromAttribute(e,i));break;case"dracoDecoderPath":Re&&console.log("dracoDecoderPath",i),Xw(i);break;case"dracoDecoderType":i==="wasm"||i==="js"?(Re&&console.log("dracoDecoderType",i),Qw(i)):console.error("Invalid dracoDecoderType",i,"expected js or wasm");break;case"ktx2DecoderPath":Re&&console.log("ktx2DecoderPath",i),Yw(i);break;case"tonemapping":case"tone-mapping":case"tone-mapping-exposure":case"background-blurriness":case"background-color":case"environment-intensity":{this.applyAttributes();break}case"public-key":{i!=xs&&this.setPublicKey();break}case"version":{i!=Ti&&this.setVersion();break}case"focus-rect":{const n=this.getAttribute("focus-rect");if(n&&this._context)if(n===null)this._context.setCameraFocusRect(null);else if(typeof n=="string"&&n.length>0){const s=document.querySelector(n);this._context.setCameraFocusRect(s instanceof HTMLElement?s:null)}else n instanceof HTMLElement&&this._context.setCameraFocusRect(n)}break}}get toneMapping(){return this.getAttribute("tonemapping")||this.getAttribute("tone-mapping")}_loadId=0;_abortController=null;_lastSourceFiles=null;_createContextPromise=null;async onLoad(){if(!this.isConnected)return;if(this._context||(Re&&console.warn("Create new context"),this._context=new U({domElement:this})),!this._context){console.error("Needle Engine: Context not initialized");return}const e=this.getSourceFiles();if(!this.checkIfSourceHasChanged(e,this._lastSourceFiles))return;this._abortController&&(Re&&console.warn("Abort previous loading process"),this._abortController.abort(),this._abortController=null),this._lastSourceFiles=e;const t=++this._loadId;if((e==null||e.length<=0)&&(Re&&console.warn("Clear scene",e),this._context.clear(),t!==this._loadId))return;const i=this.getAttribute("alias");this.classList.add("loading");const n=Zn();this.ensureLoadStartIsRegistered();let s=this.dispatchEvent(new CustomEvent("loadstart",{detail:{context:this._context,alias:i},cancelable:!0}));if(n){const g=this.getAttribute("hide-loading-overlay");g!=null&&g!=="0"&&(s=!1)}s===!1&&!n&&(A()||(s=!0),console.warn("Needle Engine: You need a commercial license to override the default loading view. Visit https://needle.tools/pricing"),A()&&be('You need a <a target="_blank" href="https://needle.tools/pricing">commercial license</a> to override the default loading view. This will not work in production.')),!this._loadingView&&s&&(this._loadingView=new xd(this)),s&&(this._didFullyLoad!==!0?this._loadingView?.onLoadingBegin("begin load"):setTimeout(()=>{this._loadingView&&this._loadingProgress01<.3&&this._loadId===t&&this._loadingView.onLoadingBegin("begin load")},300)),Re&&console.warn(`--------------
1616
1616
  Needle Engine: Begin loading `+t+`
1617
1617
  `,e),this.onBeforeBeginLoading();const r=[],a={context:this._context,name:"",progress:{},index:0,count:e.length,totalProgress01:this._loadingProgress01},l=new CustomEvent("progress",{detail:a}),c=new Array,h=new AbortController;this._abortController=h;const d={files:e,abortSignal:h.signal,onLoadingProgress:g=>{if(Re&&console.debug("Loading progress: ",g),h.signal.aborted)return;const f=g.index;!c[f]&&g.name&&(c[f]=XL(g.name)),g.name=c[f],s&&this._loadingView?.onLoadingUpdate(g),a.name=g.name,a.progress=g.progress,this._loadingProgress01=ib(g),a.totalProgress01=this._loadingProgress01,this.dispatchEvent(l)},onLoadingFinished:(g,f,y)=>{Re&&console.debug(`Finished loading "${f}" (aborted? ${h.signal.aborted})`),!h.signal.aborted&&y&&r.push({src:f,file:y})}};QL(this);const p=this.getAttribute("hash");p!=null&&(this._context.hash=p),this._context.alias=i,this._createContextPromise=this._context.create(d);const m=await this._createContextPromise;if(this.applyAttributes(),Re&&console.warn(`--------------
@@ -1651,4 +1651,4 @@ Error:`,r),null}}updateColliderCollisionGroups(e){const t=e[Qt],i=e.membership;l
1651
1651
  justify-content: center;
1652
1652
  gap: .5rem;
1653
1653
  }
1654
- `),this.#n.innerHTML=this.#e.innerHTML,this.#n.style.cssText="display: flex; align-items: center; justify-content: center;",this.#e.innerHTML=this.#n.outerHTML,this.#t.innerHTML=this.#e.outerHTML,this.#t.prepend(this.#o),Ou(xf,{element:this.#t}),this.#s?.disconnect(),this.#s??=new MutationObserver(()=>this.#c()),this.#s.observe(this.#e,{attributes:!0}),ab&&console.log("Needle Button updated",this)}#c(){this.#e&&(this.#e.style.display==="none"?this.style.display="none":this.style.display==="none"&&(this.style.display=""))}#a=e=>{ab&&console.log("Needle Button clicked",{defaultPrevented:e.defaultPrevented,hasButton:!!this.#e}),!e.defaultPrevented&&this.#e&&this.#e.click()}}typeof window<"u"&&!window.customElements.get(MS)&&window.customElements.define(MS,ES);const ud=w("debugavatar");class lb{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(s=>s.layers.set(2))}}class RS{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 s=new Nn;i=S.instantiate(Ba(t,e.scene),s)}}else i=t;if(!i)return null;const n=this.findAvatar(i);return n.isValid?(ud&&console.log("[Custom Avatar] valid config",t,ud?n:""),n):(console.warn("[Custom Avatar] config isn't valid",t,ud?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(ud&&console.log("[Custom Avatar] "+t+", loading..."),t.endsWith(".glb")||(t+=".glb"),this.avatarRegistryUrl===null){const n=await fetch("./"+t);let s=null;if(n.ok){const r=await n.blob();r&&(s=await r.arrayBuffer())}return s?(await Cn().parseSync(e,s,null,0))?.scene??null:null}const i=new Mo;return Tf(i,e),new Promise((n,s)=>{const r=this.avatarRegistryUrl+"/"+t;i.load(r,async a=>{await Cn().createBuiltinComponents(e,r,a,null,void 0),n(a.scene)},a=>{ud&&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 s=this.findAvatarPart(i,["left","hand"]),r=this.findAvatarPart(i,["right","hand"]);if(!n){n=t;const a=new b;new Si().setFromObject(n).getSize(a);const l=Math.max(a.x,a.y,a.z);console.warn("[Custom Avatar] Normalizing head scale, it's too big: "+l+" meters! Should be < 0.3m"),l>.3&&n.scale.multiplyScalar(1/l*.3)}return new lb(t,n,s,r)}findAvatarPart(e,t){const i=e.name.toLowerCase();let n=!0;for(const s of t){if(!n)break;i.indexOf(s)===-1&&(n=!1)}if(n)return e;if(e.children)for(const s of e.children){const r=this.findAvatarPart(s,t);if(r)return r}return null}handleCustomAvatarErrors(e){if(!e.ok)throw Error(e.statusText);return e}}class TS{get extensionName(){return"DocumentExtension"}onAfterBuildDocument(e){}}class AS{}const sD=Object.freeze(Object.defineProperty({__proto__:null,ActionBuilder:fe,ActionCollection:g1,ActionModel:xi,AlignmentConstraint:Gc,Animation:Ut,AnimationCurve:Ch,AnimationExtension:yp,AnimationTrackHandler:Gh,Animator:_t,AnimatorController:gn,Antialiasing:Eh,Attractor:Wl,AudioExtension:Pa,AudioListener:No,AudioSource:Di,AudioTrackHandler:fs,Avatar:Ws,AvatarBlink_Simple:Gr,AvatarEyeLook_Rotation:Hf,AvatarLoader:RS,AvatarMarker:Le,AvatarModel:lb,Avatar_Brain_LookAt:eh,Avatar_MouthShapes:th,Avatar_MustacheShake:Vf,Avatar_POI:Hr,AxesHelper:ul,BaseUIComponent:un,BasicIKConstraint:qf,BehaviorExtension:$y,BehaviorModel:jt,BloomEffect:Wp,BoxCollider:Gu,BoxGizmo:sa,BoxHelperComponent:Pt,Button:ss,CallInfo:zo,Camera:gi,CameraTargetReachedEvent:Jc,Canvas:Ll,CanvasGroup:qs,CapsuleCollider:Wo,ChangeMaterialOnClick:Ty,ChangeTransformOnClick:ea,CharacterController:qr,CharacterControllerInput:$o,ChromaticAberration:Rh,ClickThrough:hm,ColorAdjustments:er,ColorBySpeedModule:zl,ColorOverLifetimeModule:Dp,ContactShadows:nh,ControlTrackHandler:nm,CursorFollow:va,CustomBranding:oa,Deletable:Kf,DeleteBox:gr,DepthOfField:jn,DeviceFlag:qu,DocumentExtension:TS,DragControls:Yr,DropListener:Xo,Duplicatable:my,EffectWrapper:Ah,EmissionModule:ts,EmphasizeOnClick:Ol,EnvironmentScene:lm,EventList:ae,EventListEvent:Fu,EventSystem:ai,EventTrigger:ap,FieldWithDefault:Vx,FixedJoint:l0,Fog:Dl,GltfExport:vy,GltfExportBox:by,Gradient:aa,Graphic:vh,GraphicRaycaster:Nu,GridHelper:jl,GridLayoutGroup:Jy,GroundProjectedEnv:Kn,GroupActionModel:Jr,HideOnStart:fn,HingeJoint:Sh,HorizontalLayoutGroup:Ky,get HoverAnimation(){return yo},Image:Xl,InheritVelocityModule:g0,InputField:V0,InstanceHandle:Ra,InstancingHandler:Oa,Interactable:Zf,Keyframe:_i,LODGroup:Mp,LODModel:Fl,Light:At,LimitVelocityOverLifetimeModule:dt,LogStats:Yf,LookAt:$0,LookAtConstraint:Wr,MainModule:Gt,MarkerTrackHandler:im,MaskableGraphic:wh,MeshCollider:js,MeshRenderer:ah,MinMaxCurve:Y,MinMaxGradient:la,NeedleMenu:lo,NestedGltf:Ul,Networking:u0,NoiseModule:ve,ObjectRaycaster:Ji,OffsetConstraint:ra,OpenURL:Ql,OrbitControls:ge,Outline:Al,Padding:na,ParticleBurst:Lp,ParticleSubEmitter:f0,ParticleSystem:kh,ParticleSystemRenderer:ln,PhysicsExtension:Hy,PixelationEffect:Ih,PlayAnimationOnClick:hh,PlayAudioOnClick:zs,PlayableDirector:ya,PlayerColor:rc,PointerEventData:vd,PostProcessingHandler:I0,PreliminaryAction:kl,PreliminaryTrigger:dh,RawImage:rm,Rect:x1,RectTransform:Ln,ReflectionProbe:Go,RegisteredAnimationInfo:fr,RemoteSkybox:Xp,Renderer:ei,RendererLightmap:dy,Rigidbody:Ze,RotationBySpeedModule:an,RotationOverLifetimeModule:Dn,SceneSwitcher:Ke,ScreenCapture:ir,ScreenSpaceAmbientOcclusion:is,ScreenSpaceAmbientOcclusionN8:Bn,ScrollFollow:rs,SeeThrough:os,SetActiveOnClick:Ay,ShadowCatcher:Uh,ShapeModule:m0,SharpeningEffect:Dh,SignalAsset:tm,SignalReceiver:Hh,SignalReceiverEvent:$h,SignalTrackHandler:qh,Size:w1,SizeBySpeedModule:vi,SizeOverLifetimeModule:ca,SkinnedMeshRenderer:uy,SmoothFollow:Yp,SpatialGrabRaycaster:Ca,SpatialHtml:Qh,SpatialTrigger:Zp,SpatialTriggerReceiver:po,SpectatorCamera:Kp,SphereCollider:pl,SplineContainer:fa,SplineData:mo,SplineWalker:hn,Sprite:Yo,SpriteData:El,SpriteRenderer:yi,SpriteSheet:Ml,SubEmitterSystem:Up,SyncedCamera:D0,SyncedRoom:Fn,SyncedTransform:Tn,TapGestureTrigger:Ly,TeleportTarget:xp,TestRunner:F0,TestSimulateUserData:U0,Text:Ht,TextBuilder:Yy,TextExtension:Op,TextureSheetAnimationModule:qt,TiltShiftEffect:uo,ToneMappingEffect:Js,TrailModule:Fe,TransformData:Ne,TransformGizmo:ba,TriggerBuilder:$t,TriggerModel:dr,UIRaycastUtils:jf,UIRootComponent:yh,USDZExporter:ho,USDZText:Il,USDZUIExtension:i0,UsageMarker:oh,VariantAction:Ey,VelocityOverLifetimeModule:He,VerticalLayoutGroup:Zy,VideoPlayer:pt,get ViewBox(){return st},Vignette:pa,VisibilityAction:uh,Voip:Ds,Volume:$l,VolumeParameter:z,VolumeProfile:zp,WebARCameraBackground:ed,WebARSessionRoot:yn,WebXR:Sp,WebXRImageTracking:id,WebXRImageTrackingModel:ls,WebXRPlaneTracking:cs,WebXRTrackedImage:ac,XRControllerFollow:as,XRControllerModel:Zo,XRControllerMovement:Bi,XRFlag:tn,XRRig:mm,XRState:ri,__Ignore:AS},Symbol.toStringTag,{value:"Module"})),pd=w("debugmissingcamera");pe.registerCallback(ue.MissingCamera,o=>{pd&&console.warn("Creating missing camera");const e=o.context.scene,t=new de;t.name="Default Fallback Camera",e.add(t);const i=new gi;if(i.sourceId=o.files?.[0]?.src??"unknown",i.fieldOfView=35,o.context.domElement.getAttribute("transparent")!=null)i.clearFlags=$r.Uninitialized;else if(o.context.domElement.getAttribute("background-image")?.length||o.context.lightmaps.tryGetSkybox(i.sourceId))i.clearFlags=$r.Skybox;else{if(i.clearFlags=$r.SolidColor,!o.context.domElement.getAttribute("background-color")){let s="#efefef";typeof window!==void 0&&window.matchMedia("(prefers-color-scheme: dark)").matches&&(s="#1f1f1f"),e.background=new oe(s)}if(!e.environment){const s=new sP(o.context.renderer),r=new lm("neutral");e.environment=s.fromScene(r,.025).texture}}const n=Lr(t,i,!0);return t.position.x=0,t.position.y=1,t.position.z=2,o.context.domElement?.cameraControls!=!1&&IS(o.context,n),n}),pe.registerCallback(ue.ContextCreated,o=>{if(!o.context.mainCamera){pd&&console.log("Will not auto-fit because a default camera exists");return}if(o.context.domElement?.cameraControls==!0){if(p_(o.context.mainCamera)?.isCameraController==!0){pd&&console.log("Will not auto-fit because a camera controller exists");return}IS(o.context)}});function IS(o,e){e=e??o.mainCameraComponent;const t=e?.gameObject;if(pd&&console.log("Creating default camera controls",e?.name),t){const i=jc(t,ge);i.sourceId=e?.sourceId??"unknown";const n=o.domElement.getAttribute("auto-rotate");i.autoRotate=n!="0"&&n?.toLowerCase()!="false";const s=Number.parseFloat(n||".5");i.autoRotateSpeed=isNaN(s)?.5:s,pd&&console.log("Auto-rotate",i.autoRotate,"speed:",i.autoRotateSpeed);const r=o.domElement.getAttribute("auto-fit");i.autoFit=r!=="0"&&r?.toLowerCase()!="false",i.autoTarget=!0}else console.warn("Missing camera object, can not add orbit controls")}pe.registerCallback(ue.ContextCreated,o=>{const e=o.context.domElement.getAttribute("autoplay");if(e!==void 0&&(e===""||e==="true"||e==="1")&&o.files)for(const t of o.files)S.foreachComponent(t.file.scene,i=>{if(i.enabled!==!1){if(i instanceof Ut&&i.playAutomatically||i instanceof _t||i instanceof ya&&i.playOnAwake===!0)return!0;if(i instanceof Ut)return i.playAutomatically=!0,!0;if(i instanceof ya)return i.playOnAwake=!0,!0}},!0)!==!0&&Xn.autoplayAnimations(t.file)});var cb;(o=>{function e(t,i=!1,n=.75){const s=new fa,r=1-j.clamp(n,0,1);return t.forEach((a,l)=>{const c=new b;l<t.length-1?c.subVectors(t[l+1],a).normalize().multiplyScalar(r):i&&t.length>1&&c.subVectors(t[0],a).normalize().multiplyScalar(r);const h=new mo;h.position.copy(a),h.tangentIn.copy(c),h.tangentOut.copy(c),s.addKnot(h)}),s.closed=i,s}o.createFromPoints=e})(cb||(cb={}));class rD extends FP{constructor(){super(new Worker(URL.createObjectURL(new Blob([`import '${new URL("./generateMeshBVH.worker-DiCnZlf3.js",import.meta.url).toString()}';`],{type:"text/javascript"})),{type:"module"})),this.name="GenerateMeshBVHWorker"}runTask(e,t,i={}){return new Promise((n,s)=>{if(t.getAttribute("position").isInterleavedBufferAttribute||t.index&&t.index.isInterleavedBufferAttribute)throw new Error("GenerateMeshBVHWorker: InterleavedBufferAttribute are not supported for the geometry attributes.");e.onerror=c=>{s(new Error(`[GenerateMeshBVHWorker] ${c.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=c=>{const{data:h}=c;if(h.error)s(new Error(h.error)),e.onmessage=null;else if(h.serialized){const{serialized:d,position:p}=h,m=UP.deserialize(d,t,{setIndex:!1}),g=Object.assign({setBoundingBox:!0},i);if(t.attributes.position.array=p,d.index)if(t.index)t.index.array=d.index;else{const f=new ft(d.index,1,!1);t.setIndex(f)}g.setBoundingBox&&(t.boundingBox=m.getBoundingBox(new Si)),i.onProgress&&i.onProgress(h.progress),n(m),e.onmessage=null}else i.onProgress&&i.onProgress(h.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(c=>c.buffer).filter(c=>typeof SharedArrayBuffer>"u"||!(c instanceof SharedArrayBuffer)))})}}const aD=Object.freeze(Object.defineProperty({__proto__:null,GenerateMeshBVHWorker:rD},Symbol.toStringTag,{value:"Module"}));export{W_ as $componentName,yk as $physicsKey,fe as ActionBuilder,g1 as ActionCollection,xi as ActionModel,ww as Addressables,Gc as AlignmentConstraint,rl as AmbientMode,Ut as Animation,Ch as AnimationCurve,yp as AnimationExtension,Gh as AnimationTrackHandler,Xn as AnimationUtils,_t as Animator,Ts as AnimatorConditionMode,gn as AnimatorController,If as AnimatorControllerParameterType,qc as AnimatorStateInfo,Eh as Antialiasing,zn as Application,kv as AssetDatabase,ne as AssetReference,Wl as Attractor,Pa as AudioExtension,No as AudioListener,Di as AudioSource,fs as AudioTrackHandler,Ws as Avatar,Gr as AvatarBlink_Simple,Hf as AvatarEyeLook_Rotation,RS as AvatarLoader,Le as AvatarMarker,lb as AvatarModel,eh as Avatar_Brain_LookAt,th as Avatar_MouthShapes,Vf as Avatar_MustacheShake,Hr as Avatar_POI,cl as Axes,ul as AxesHelper,wc as BUILD_TIME,un as BaseUIComponent,qf as BasicIKConstraint,$y as BehaviorExtension,jt as BehaviorModel,zr as BlobStorage,Wp as BloomEffect,Gu as BoxCollider,sa as BoxGizmo,Pt as BoxHelperComponent,ss as Button,mn as ButtonsFactory,fx as CallDirection,zo as CallInfo,gi as Camera,Jc as CameraTargetReachedEvent,Ll as Canvas,qs as CanvasGroup,Wo as CapsuleCollider,Ty as ChangeMaterialOnClick,ea as ChangeTransformOnClick,qr as CharacterController,$o as CharacterControllerInput,Rh as ChromaticAberration,Mi as CircularBuffer,$r as ClearFlags,hm as ClickThrough,go as ClipExtrapolation,nn as Collider,$_ as Collision,ju as CollisionDetectionMode,er as ColorAdjustments,zl as ColorBySpeedModule,Dp as ColorOverLifetimeModule,AE as Component,E as Component$1,ru as ComponentLifecycleEvents,sD as Components,dv as ConnectionEvents,V_ as ContactPoint,nh as ContactShadows,U as Context,yE as ContextArgs,ue as ContextEvent,pe as ContextRegistry,nm as ControlTrackHandler,va as CursorFollow,oa as CustomBranding,Te as CustomShader,Cu as DefaultReflectionMode,Kf as Deletable,gr as DeleteBox,jn as DepthOfField,qu as DeviceFlag,I as DeviceUtilities,TS as DocumentExtension,Yr as DragControls,ey as DragMode,Xo as DropListener,my as Duplicatable,Ah as EffectWrapper,ts as EmissionModule,Ol as EmphasizeOnClick,xd as EngineLoadingView,lm as EnvironmentScene,ae as EventList,Fu as EventListEvent,ai as EventSystem,ap as EventTrigger,Vx as FieldWithDefault,Ea as FileReference,Sw as FileReferenceSerializer,qR as FileSpawnModel,Cx as File_Event,l0 as FixedJoint,Dl as Fog,xe as FrameEvent,Wa as GENERATOR,S as GameObject,B as Gizmos,vy as GltfExport,by as GltfExportBox,aa as Gradient,vh as Graphic,Nu as GraphicRaycaster,pr as Graphics,jl as GridHelper,Jy as GridLayoutGroup,Kn as GroundProjectedEnv,Jr as GroupActionModel,Gd as HideFlags,fn as HideOnStart,Sh as HingeJoint,Ky as HorizontalLayoutGroup,bM as HostData,yo as HoverAnimation,Xl as Image,Ma as ImageReference,xw as ImageReferenceSerializer,g0 as InheritVelocityModule,K_ as Input,di as InputEventQueue,Ae as InputEvents,V0 as InputField,Ra as InstanceHandle,Oa as InstancingHandler,pn as InstancingUtil,Wv as InstantiateEvent,Bt as InstantiateIdProvider,Nn as InstantiateOptions,Zf as Interactable,Jh as InternalScreenshotUtils,Lk as JoinedRoomResponse,Sk as KeyEventArgs,_i as Keyframe,Mp as LODGroup,Fl as LODModel,Dk as LeftRoomResponse,At as Light,Tw as LightData,dt as LimitVelocityOverLifetimeModule,HL as LoadingElementOptions,Yf as LogStats,Ei as LogType,$0 as LookAt,Wr as LookAtConstraint,T as MODULES,Gt as MainModule,im as MarkerTrackHandler,z0 as MarkerType,wh as MaskableGraphic,ps as MaterialPropertyBlock,tp as MaterialX,j as Mathf,js as MeshCollider,ah as MeshRenderer,Y as MinMaxCurve,la as MinMaxGradient,Ac as NEEDLE_ENGINE_FEATURE_FLAGS,Sc as NEKeyboardEvent,Io as NEPointerEvent,ES as NeedleButtonElement,iy as NeedleEngineModelLoader,nb as NeedleEngineWebComponent,lo as NeedleMenu,Xd as NeedlePatchesKey,Sg as NeedleXRController,Z as NeedleXRSession,mv as NeedleXRSync,wv as NeedleXRUtils,Ul as NestedGltf,pv as NetworkConnection,eo as NetworkedStreamEvents,wd as NetworkedStreams,u0 as Networking,$v as NewInstanceModel,ve as NoiseModule,Ji as ObjectRaycaster,Ps as ObjectUtils,ra as OffsetConstraint,Ud as OneEuroFilter,ig as OneEuroFilterXYZ,Ql as OpenURL,ge as OrbitControls,Al as Outline,uv as OwnershipEvent,Eg as OwnershipModel,xs as PUBLIC_KEY,na as Padding,Lp as ParticleBurst,f0 as ParticleSubEmitter,kh as ParticleSystem,Ks as ParticleSystemBaseBehaviour,ln as ParticleSystemRenderer,Ip as ParticleSystemShapeType,gs as PeerHandle,cv as PeerNetworking,oc as Physics,Hy as PhysicsExtension,vt as PhysicsMaterialCombine,Ih as PixelationEffect,hh as PlayAnimationOnClick,zs as PlayAudioOnClick,ya as PlayableDirector,rc as PlayerColor,sn as PlayerState,_1 as PlayerStateEvent,zy as PlayerSync,Ow as PlayerView,kw as PlayerViewManager,vd as PointerEventData,Yd as PointerType,nt as PostProcessingEffect,ut as PostProcessingEffectOrder,I0 as PostProcessingHandler,kl as PreliminaryAction,dh as PreliminaryTrigger,Fs as PreviewHelper,Qa as PrimitiveType,le as Progress,Zm as PromiseAllWithErrors,Ym as PromiseErrorResult,se as RGBAColor,lc as RapierPhysics,rm as RawImage,Os as RaycastOptions,x1 as Rect,Ln as RectTransform,Go as ReflectionProbe,fr as RegisteredAnimationInfo,Xp as RemoteSkybox,wo as RenderTexture,dx as RenderTextureSerializer,ei as Renderer,Rw as RendererData,dy as RendererLightmap,Ze as Rigidbody,Ye as RigidbodyConstraints,ie as RoomEvents,an as RotationBySpeedModule,Dn as RotationOverLifetimeModule,ep as SceneLightSettings,Ke as SceneSwitcher,ir as ScreenCapture,is as ScreenSpaceAmbientOcclusion,Bn as ScreenSpaceAmbientOcclusionN8,rs as ScrollFollow,os as SeeThrough,Pn as SendQueue,sf as SerializationContext,Ay as SetActiveOnClick,Uh as ShadowCatcher,m0 as ShapeModule,H_ as ShapeOverlapResult,Dh as SharpeningEffect,tm as SignalAsset,Hh as SignalReceiver,$h as SignalReceiverEvent,qh as SignalTrackHandler,w1 as Size,vi as SizeBySpeedModule,ca as SizeOverLifetimeModule,uy as SkinnedMeshRenderer,Yp as SmoothFollow,Ca as SpatialGrabRaycaster,Qh as SpatialHtml,Zp as SpatialTrigger,po as SpatialTriggerReceiver,Kp as SpectatorCamera,pl as SphereCollider,zg as SphereIntersection,fa as SplineContainer,mo as SplineData,cb as SplineUtils,hn as SplineWalker,Yo as Sprite,El as SpriteData,yi as SpriteRenderer,Ml as SpriteSheet,FE as StateMachineBehaviour,Nf as StreamEndedEvent,gx as StreamReceivedEvent,Up as SubEmitterSystem,D0 as SyncedCamera,Fn as SyncedRoom,Tn as SyncedTransform,Ly as TapGestureTrigger,xp as TeleportTarget,F0 as TestRunner,U0 as TestSimulateUserData,Ht as Text,Yy as TextBuilder,Op as TextExtension,qt as TextureSheetAnimationModule,uo as TiltShiftEffect,Iw as Time,Js as ToneMappingEffect,ql as TrackHandler,Vi as TrackType,Fe as TrailModule,Ne as TransformData,ba as TransformGizmo,$t as TriggerBuilder,dr as TriggerModel,C as TypeStore,jf as UIRaycastUtils,yh as UIRootComponent,wy as USDDocument,rt as USDObject,Kx as USDWriter,e1 as USDZExporter,ho as USDZExporter$1,Il as USDZText,i0 as USDZUIExtension,ux as UriSerializer,oh as UsageMarker,jk as UserJoinedOrLeftRoomModel,Ti as VERSION,Ey as VariantAction,He as VelocityOverLifetimeModule,Zy as VerticalLayoutGroup,pt as VideoPlayer,st as ViewBox,Fo as ViewDevice,pa as Vignette,uh as VisibilityAction,Ds as Voip,$l as Volume,z as VolumeParameter,zp as VolumeProfile,YM as WaitForFrames,Cw as WaitForPromise,pf as WaitForSeconds,us as Watch,ed as WebARCameraBackground,yn as WebARSessionRoot,Sp as WebXR,ur as WebXRButtonFactory,id as WebXRImageTracking,ls as WebXRImageTrackingModel,cs as WebXRPlaneTracking,ac as WebXRTrackedImage,as as XRControllerFollow,Zo as XRControllerModel,Bi as XRControllerMovement,tn as XRFlag,mm as XRRig,ri as XRState,io as XRStateFlag,AS as __Ignore,aM as __internalNotifyObjectDestroyed,Ao as activeInHierarchyFieldName,Xm as addAttributeChangeCallback,Mn as addComponent,bT as addCustomExtensionPlugin,Lr as addNewComponent,qd as addPatch,gu as apply,TE as applyHMRChanges,rw as applyPrototypeExtensions,Vv as beginListenDestroy,Gv as beginListenInstantiate,Og as binaryIdentifierCasts,fE as build_scene_functions,Mr as builtinComponentKeyName,ib as calculateProgress01,fO as clearMessages,tR as colorSerializer,Yv as compareAssociation,Uu as componentSerializer,P_ as copyTexture,ox as createMotion,ui as debugNet,Pc as debugOwner,s1 as decompressGpuTexture,pc as deepClone,Ro as delay,mc as delayForFrames,pu as deserializeObject,Ii as destroy,hw as destroyComponentInstance,Px as determineMimeTypeFromExtension,ke as disposeObjectResources,to as disposeStream,xc as editorGuidKeyName,Na as enableSpatialConsole,nR as euler,aR as eventListSerializer,iD as exportAsGLTF,cf as findByGuid,tl as findObjectOfType,pw as findObjectsOfType,Ng as findResourceUsers,ax as fitCamera,k_ as fitObjectIntoVolume,Fr as foreachComponent,vu as foreachComponentEnumerator,LO as forward,Bw as generateQRCode,Hv as generateSeed,Ri as getBoundingBox,p_ as getCameraController,Dr as getComponent,Fc as getComponentInChildren,Uc as getComponentInParent,Bc as getComponents,el as getComponentsInChildren,mu as getComponentsInParent,Xx as getFormattedDate,Ot as getIconElement,_f as getIconTexture,Cn as getLoader,jc as getOrAddComponent,w as getParam,BO as getParentHierarchyPath,XP as getPath,Rk as getPeerOptions,av as getPeerjsInstance,cM as getResourceUserCount,f_ as getTempColor,ci as getTempQuaternion,F as getTempVector,dc as getUrlParams,O_ as getVisibleInCustomShadowRendering,v_ as getWorldDirection,cg as getWorldEuler,ee as getWorldPosition,_e as getWorldQuaternion,Vd as getWorldRotation,$e as getWorldScale,Zn as hasCommercialLicense,Vc as hasIndieLicense,Bu as hasPointerEventComponent,Yn as hasProLicense,A_ as hideDebugConsole,r1 as imageToCanvas,Ur as instantiate,Fx as invokeLoadedImportPluginHooks,Z_ as invokeXRSessionEnd,Y_ as invokeXRSessionStart,mw as isActiveInHierarchy,il as isActiveSelf,eO as isAndroidDevice,C_ as isAnimationAction,bg as isComponent,$P as isDebugMode,YP as isDesktop,Br as isDestroyed,A as isDevEnvironment,rM as isDisposed,eD as isExporting,N_ as isGLTFModel,Xb as isHostedOnGlitch,Af as isHotReloadEnabled,EE as isHotReloading,KP as isIPad,Fw as isIconElement,ki as isLocalNetwork,iO as isMacOS,ZP as isMobileDevice,tO as isMozillaXR,sO as isQuest,Ev as isResourceTrackingEnabled,oO as isSafari,yu as isUsingInstancing,nO as isiOS,JP as isiPad,UL as loadAsset,ay as loadPMREM,tb as loadSync,$d as logHierarchy,OO as lookAtInverse,gc as lookAtObject,kO as lookAtScreenPoint,GP as makeId,e_ as makeIdFromRandomWords,ji as makeNameSafe,gw as markAsInstancedRendered,rO as microphonePermissionsGranted,VP as nameof,Yb as nameofFactory,hx as objectSerializer,xk as offXRSessionEnd,wk as offXRSessionStart,wE as onAfterRender,vE as onBeforeRender,bE as onClear,_E as onDestroy,Cf as onInitialized,Eu as onStart,Vw as onUpdate,xg as onXRSessionEnd,Qd as onXRSessionStart,bS as parseSync,M_ as placeOnSurface,ug as postprocessFBXMaterials,QE as prefix,Zb as pushState,qP as randomNumber,kg as registerBinaryType,Mu as registerComponent,cy as registerComponentExtension,cn as registerCustomEffectType,hy as registerExportExtensions,np as registerExtensions,Kw as registerHotReloadType,yg as registerLoader,Xv as registerPrefabProvider,aw as registerPrototypeExtensions,Jg as registerType,i_ as relativePathPrefix,Qm as removeAttributeChangeCallback,lf as removeComponent,_T as removeCustomImportExtensionType,_k as removePatch,To as resolveUrl,t_ as sanitizeString,dS as saveImage,xL as screenshot,Y0 as screenshot2,Yg as sendDestroyed,u as serializable,ew as serializeObject,Qe as serializeable,zc as setActive,r_ as setAllowBalloonMessages,uO as setAllowOverlayMessages,Nd as setAutoFitEnabled,ng as setCameraController,yw as setDestroyed,HO as setDevEnvironment,Tv as setDisposable,nl as setDontDestroy,Hm as setOrAddParamsToUrl,HP as setParam,uc as setParamWithoutReload,Tk as setPeerOptions,sM as setResourceTrackingEnabled,Gm as setState,dg as setVisibleInCustomShadowRendering,hg as setWorldEuler,yt as setWorldPosition,Sr as setWorldPositionXYZ,Sn as setWorldQuaternion,lg as setWorldQuaternionXYZW,S_ as setWorldRotation,fc as setWorldRotationXYZ,za as setWorldScale,_c as showBalloonError,Oe as showBalloonMessage,be as showBalloonWarning,gg as showDebugConsole,PO as slerp,Lc as syncDestroy,Uy as syncField,Zg as syncInstantiate,FO as textureToCanvas,n_ as toSourceId,sv as tryCastBinary,kx as tryDetermineMimetypeFromBinary,Ox as tryDetermineMimetypeFromURL,Ba as tryFindObject,rv as tryGetGuid,Jw as unregisterHotReloadType,qm as unwatchWrite,m_ as useForAutoFit,Mt as validate,Bd as watchWrite};
1654
+ `),this.#n.innerHTML=this.#e.innerHTML,this.#n.style.cssText="display: flex; align-items: center; justify-content: center;",this.#e.innerHTML=this.#n.outerHTML,this.#t.innerHTML=this.#e.outerHTML,this.#t.prepend(this.#o),Ou(xf,{element:this.#t}),this.#s?.disconnect(),this.#s??=new MutationObserver(()=>this.#c()),this.#s.observe(this.#e,{attributes:!0}),ab&&console.log("Needle Button updated",this)}#c(){this.#e&&(this.#e.style.display==="none"?this.style.display="none":this.style.display==="none"&&(this.style.display=""))}#a=e=>{ab&&console.log("Needle Button clicked",{defaultPrevented:e.defaultPrevented,hasButton:!!this.#e}),!e.defaultPrevented&&this.#e&&this.#e.click()}}typeof window<"u"&&!window.customElements.get(MS)&&window.customElements.define(MS,ES);const ud=w("debugavatar");class lb{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(s=>s.layers.set(2))}}class RS{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 s=new Nn;i=S.instantiate(Ba(t,e.scene),s)}}else i=t;if(!i)return null;const n=this.findAvatar(i);return n.isValid?(ud&&console.log("[Custom Avatar] valid config",t,ud?n:""),n):(console.warn("[Custom Avatar] config isn't valid",t,ud?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(ud&&console.log("[Custom Avatar] "+t+", loading..."),t.endsWith(".glb")||(t+=".glb"),this.avatarRegistryUrl===null){const n=await fetch("./"+t);let s=null;if(n.ok){const r=await n.blob();r&&(s=await r.arrayBuffer())}return s?(await Cn().parseSync(e,s,null,0))?.scene??null:null}const i=new Mo;return Tf(i,e),new Promise((n,s)=>{const r=this.avatarRegistryUrl+"/"+t;i.load(r,async a=>{await Cn().createBuiltinComponents(e,r,a,null,void 0),n(a.scene)},a=>{ud&&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 s=this.findAvatarPart(i,["left","hand"]),r=this.findAvatarPart(i,["right","hand"]);if(!n){n=t;const a=new b;new Si().setFromObject(n).getSize(a);const l=Math.max(a.x,a.y,a.z);console.warn("[Custom Avatar] Normalizing head scale, it's too big: "+l+" meters! Should be < 0.3m"),l>.3&&n.scale.multiplyScalar(1/l*.3)}return new lb(t,n,s,r)}findAvatarPart(e,t){const i=e.name.toLowerCase();let n=!0;for(const s of t){if(!n)break;i.indexOf(s)===-1&&(n=!1)}if(n)return e;if(e.children)for(const s of e.children){const r=this.findAvatarPart(s,t);if(r)return r}return null}handleCustomAvatarErrors(e){if(!e.ok)throw Error(e.statusText);return e}}class TS{get extensionName(){return"DocumentExtension"}onAfterBuildDocument(e){}}class AS{}const sD=Object.freeze(Object.defineProperty({__proto__:null,ActionBuilder:fe,ActionCollection:g1,ActionModel:xi,AlignmentConstraint:Gc,Animation:Ut,AnimationCurve:Ch,AnimationExtension:yp,AnimationTrackHandler:Gh,Animator:_t,AnimatorController:gn,Antialiasing:Eh,Attractor:Wl,AudioExtension:Pa,AudioListener:No,AudioSource:Di,AudioTrackHandler:fs,Avatar:Ws,AvatarBlink_Simple:Gr,AvatarEyeLook_Rotation:Hf,AvatarLoader:RS,AvatarMarker:Le,AvatarModel:lb,Avatar_Brain_LookAt:eh,Avatar_MouthShapes:th,Avatar_MustacheShake:Vf,Avatar_POI:Hr,AxesHelper:ul,BaseUIComponent:un,BasicIKConstraint:qf,BehaviorExtension:$y,BehaviorModel:jt,BloomEffect:Wp,BoxCollider:Gu,BoxGizmo:sa,BoxHelperComponent:Pt,Button:ss,CallInfo:zo,Camera:gi,CameraTargetReachedEvent:Jc,Canvas:Ll,CanvasGroup:qs,CapsuleCollider:Wo,ChangeMaterialOnClick:Ty,ChangeTransformOnClick:ea,CharacterController:qr,CharacterControllerInput:$o,ChromaticAberration:Rh,ClickThrough:hm,ColorAdjustments:er,ColorBySpeedModule:zl,ColorOverLifetimeModule:Dp,ContactShadows:nh,ControlTrackHandler:nm,CursorFollow:va,CustomBranding:oa,Deletable:Kf,DeleteBox:gr,DepthOfField:jn,DeviceFlag:qu,DocumentExtension:TS,DragControls:Yr,DropListener:Xo,Duplicatable:my,EffectWrapper:Ah,EmissionModule:ts,EmphasizeOnClick:Ol,EnvironmentScene:lm,EventList:ae,EventListEvent:Fu,EventSystem:ai,EventTrigger:ap,FieldWithDefault:Vx,FixedJoint:l0,Fog:Dl,GltfExport:vy,GltfExportBox:by,Gradient:aa,Graphic:vh,GraphicRaycaster:Nu,GridHelper:jl,GridLayoutGroup:Jy,GroundProjectedEnv:Kn,GroupActionModel:Jr,HideOnStart:fn,HingeJoint:Sh,HorizontalLayoutGroup:Ky,get HoverAnimation(){return yo},Image:Xl,InheritVelocityModule:g0,InputField:V0,InstanceHandle:Ra,InstancingHandler:Oa,Interactable:Zf,Keyframe:_i,LODGroup:Mp,LODModel:Fl,Light:At,LimitVelocityOverLifetimeModule:dt,LogStats:Yf,LookAt:$0,LookAtConstraint:Wr,MainModule:Gt,MarkerTrackHandler:im,MaskableGraphic:wh,MeshCollider:js,MeshRenderer:ah,MinMaxCurve:Y,MinMaxGradient:la,NeedleMenu:lo,NestedGltf:Ul,Networking:u0,NoiseModule:ve,ObjectRaycaster:Ji,OffsetConstraint:ra,OpenURL:Ql,OrbitControls:ge,Outline:Al,Padding:na,ParticleBurst:Lp,ParticleSubEmitter:f0,ParticleSystem:kh,ParticleSystemRenderer:ln,PhysicsExtension:Hy,PixelationEffect:Ih,PlayAnimationOnClick:hh,PlayAudioOnClick:zs,PlayableDirector:ya,PlayerColor:rc,PointerEventData:vd,PostProcessingHandler:I0,PreliminaryAction:kl,PreliminaryTrigger:dh,RawImage:rm,Rect:x1,RectTransform:Ln,ReflectionProbe:Go,RegisteredAnimationInfo:fr,RemoteSkybox:Xp,Renderer:ei,RendererLightmap:dy,Rigidbody:Ke,RotationBySpeedModule:an,RotationOverLifetimeModule:Dn,SceneSwitcher:Je,ScreenCapture:ir,ScreenSpaceAmbientOcclusion:is,ScreenSpaceAmbientOcclusionN8:Bn,ScrollFollow:rs,SeeThrough:os,SetActiveOnClick:Ay,ShadowCatcher:Uh,ShapeModule:m0,SharpeningEffect:Dh,SignalAsset:tm,SignalReceiver:Hh,SignalReceiverEvent:$h,SignalTrackHandler:qh,Size:w1,SizeBySpeedModule:vi,SizeOverLifetimeModule:ca,SkinnedMeshRenderer:uy,SmoothFollow:Yp,SpatialGrabRaycaster:Ca,SpatialHtml:Qh,SpatialTrigger:Zp,SpatialTriggerReceiver:po,SpectatorCamera:Kp,SphereCollider:pl,SplineContainer:fa,SplineData:mo,SplineWalker:hn,Sprite:Yo,SpriteData:El,SpriteRenderer:yi,SpriteSheet:Ml,SubEmitterSystem:Up,SyncedCamera:D0,SyncedRoom:Fn,SyncedTransform:Tn,TapGestureTrigger:Ly,TeleportTarget:xp,TestRunner:F0,TestSimulateUserData:U0,Text:Ht,TextBuilder:Yy,TextExtension:Op,TextureSheetAnimationModule:qt,TiltShiftEffect:uo,ToneMappingEffect:Js,TrailModule:Fe,TransformData:Ne,TransformGizmo:ba,TriggerBuilder:$t,TriggerModel:dr,UIRaycastUtils:jf,UIRootComponent:yh,USDZExporter:ho,USDZText:Il,USDZUIExtension:i0,UsageMarker:oh,VariantAction:Ey,VelocityOverLifetimeModule:He,VerticalLayoutGroup:Zy,VideoPlayer:pt,get ViewBox(){return st},Vignette:pa,VisibilityAction:uh,Voip:Ds,Volume:$l,VolumeParameter:z,VolumeProfile:zp,WebARCameraBackground:ed,WebARSessionRoot:yn,WebXR:Sp,WebXRImageTracking:id,WebXRImageTrackingModel:ls,WebXRPlaneTracking:cs,WebXRTrackedImage:ac,XRControllerFollow:as,XRControllerModel:Zo,XRControllerMovement:Bi,XRFlag:tn,XRRig:mm,XRState:ri,__Ignore:AS},Symbol.toStringTag,{value:"Module"})),pd=w("debugmissingcamera");pe.registerCallback(ue.MissingCamera,o=>{pd&&console.warn("Creating missing camera");const e=o.context.scene,t=new de;t.name="Default Fallback Camera",e.add(t);const i=new gi;if(i.sourceId=o.files?.[0]?.src??"unknown",i.fieldOfView=35,o.context.domElement.getAttribute("transparent")!=null)i.clearFlags=$r.Uninitialized;else if(o.context.domElement.getAttribute("background-image")?.length||o.context.lightmaps.tryGetSkybox(i.sourceId))i.clearFlags=$r.Skybox;else{if(i.clearFlags=$r.SolidColor,!o.context.domElement.getAttribute("background-color")){let s="#efefef";typeof window!==void 0&&window.matchMedia("(prefers-color-scheme: dark)").matches&&(s="#1f1f1f"),e.background=new oe(s)}if(!e.environment){const s=new sP(o.context.renderer),r=new lm("neutral");e.environment=s.fromScene(r,.025).texture}}const n=Lr(t,i,!0);return t.position.x=0,t.position.y=1,t.position.z=2,o.context.domElement?.cameraControls!=!1&&IS(o.context,n),n}),pe.registerCallback(ue.ContextCreated,o=>{if(!o.context.mainCamera){pd&&console.log("Will not auto-fit because a default camera exists");return}if(o.context.domElement?.cameraControls==!0){if(p_(o.context.mainCamera)?.isCameraController==!0){pd&&console.log("Will not auto-fit because a camera controller exists");return}IS(o.context)}});function IS(o,e){e=e??o.mainCameraComponent;const t=e?.gameObject;if(pd&&console.log("Creating default camera controls",e?.name),t){const i=jc(t,ge);i.sourceId=e?.sourceId??"unknown";const n=o.domElement.getAttribute("auto-rotate");i.autoRotate=n!="0"&&n?.toLowerCase()!="false";const s=Number.parseFloat(n||".5");i.autoRotateSpeed=isNaN(s)?.5:s,pd&&console.log("Auto-rotate",i.autoRotate,"speed:",i.autoRotateSpeed);const r=o.domElement.getAttribute("auto-fit");i.autoFit=r!=="0"&&r?.toLowerCase()!="false",i.autoTarget=!0}else console.warn("Missing camera object, can not add orbit controls")}pe.registerCallback(ue.ContextCreated,o=>{const e=o.context.domElement.getAttribute("autoplay");if(e!==void 0&&(e===""||e==="true"||e==="1")&&o.files)for(const t of o.files)S.foreachComponent(t.file.scene,i=>{if(i.enabled!==!1){if(i instanceof Ut&&i.playAutomatically||i instanceof _t||i instanceof ya&&i.playOnAwake===!0)return!0;if(i instanceof Ut)return i.playAutomatically=!0,!0;if(i instanceof ya)return i.playOnAwake=!0,!0}},!0)!==!0&&Xn.autoplayAnimations(t.file)});var cb;(o=>{function e(t,i=!1,n=.75){const s=new fa,r=1-j.clamp(n,0,1);return t.forEach((a,l)=>{const c=new b;l<t.length-1?c.subVectors(t[l+1],a).normalize().multiplyScalar(r):i&&t.length>1&&c.subVectors(t[0],a).normalize().multiplyScalar(r);const h=new mo;h.position.copy(a),h.tangentIn.copy(c),h.tangentOut.copy(c),s.addKnot(h)}),s.closed=i,s}o.createFromPoints=e})(cb||(cb={}));class rD extends FP{constructor(){super(new Worker(URL.createObjectURL(new Blob([`import '${new URL("./generateMeshBVH.worker-DiCnZlf3.js",import.meta.url).toString()}';`],{type:"text/javascript"})),{type:"module"})),this.name="GenerateMeshBVHWorker"}runTask(e,t,i={}){return new Promise((n,s)=>{if(t.getAttribute("position").isInterleavedBufferAttribute||t.index&&t.index.isInterleavedBufferAttribute)throw new Error("GenerateMeshBVHWorker: InterleavedBufferAttribute are not supported for the geometry attributes.");e.onerror=c=>{s(new Error(`[GenerateMeshBVHWorker] ${c.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=c=>{const{data:h}=c;if(h.error)s(new Error(h.error)),e.onmessage=null;else if(h.serialized){const{serialized:d,position:p}=h,m=UP.deserialize(d,t,{setIndex:!1}),g=Object.assign({setBoundingBox:!0},i);if(t.attributes.position.array=p,d.index)if(t.index)t.index.array=d.index;else{const f=new ft(d.index,1,!1);t.setIndex(f)}g.setBoundingBox&&(t.boundingBox=m.getBoundingBox(new Si)),i.onProgress&&i.onProgress(h.progress),n(m),e.onmessage=null}else i.onProgress&&i.onProgress(h.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(c=>c.buffer).filter(c=>typeof SharedArrayBuffer>"u"||!(c instanceof SharedArrayBuffer)))})}}const aD=Object.freeze(Object.defineProperty({__proto__:null,GenerateMeshBVHWorker:rD},Symbol.toStringTag,{value:"Module"}));export{W_ as $componentName,yk as $physicsKey,fe as ActionBuilder,g1 as ActionCollection,xi as ActionModel,ww as Addressables,Gc as AlignmentConstraint,rl as AmbientMode,Ut as Animation,Ch as AnimationCurve,yp as AnimationExtension,Gh as AnimationTrackHandler,Xn as AnimationUtils,_t as Animator,Ts as AnimatorConditionMode,gn as AnimatorController,If as AnimatorControllerParameterType,qc as AnimatorStateInfo,Eh as Antialiasing,zn as Application,kv as AssetDatabase,ne as AssetReference,Wl as Attractor,Pa as AudioExtension,No as AudioListener,Di as AudioSource,fs as AudioTrackHandler,Ws as Avatar,Gr as AvatarBlink_Simple,Hf as AvatarEyeLook_Rotation,RS as AvatarLoader,Le as AvatarMarker,lb as AvatarModel,eh as Avatar_Brain_LookAt,th as Avatar_MouthShapes,Vf as Avatar_MustacheShake,Hr as Avatar_POI,cl as Axes,ul as AxesHelper,wc as BUILD_TIME,un as BaseUIComponent,qf as BasicIKConstraint,$y as BehaviorExtension,jt as BehaviorModel,zr as BlobStorage,Wp as BloomEffect,Gu as BoxCollider,sa as BoxGizmo,Pt as BoxHelperComponent,ss as Button,mn as ButtonsFactory,fx as CallDirection,zo as CallInfo,gi as Camera,Jc as CameraTargetReachedEvent,Ll as Canvas,qs as CanvasGroup,Wo as CapsuleCollider,Ty as ChangeMaterialOnClick,ea as ChangeTransformOnClick,qr as CharacterController,$o as CharacterControllerInput,Rh as ChromaticAberration,Mi as CircularBuffer,$r as ClearFlags,hm as ClickThrough,go as ClipExtrapolation,nn as Collider,$_ as Collision,ju as CollisionDetectionMode,er as ColorAdjustments,zl as ColorBySpeedModule,Dp as ColorOverLifetimeModule,AE as Component,E as Component$1,ru as ComponentLifecycleEvents,sD as Components,dv as ConnectionEvents,V_ as ContactPoint,nh as ContactShadows,U as Context,yE as ContextArgs,ue as ContextEvent,pe as ContextRegistry,nm as ControlTrackHandler,va as CursorFollow,oa as CustomBranding,Te as CustomShader,Cu as DefaultReflectionMode,Kf as Deletable,gr as DeleteBox,jn as DepthOfField,qu as DeviceFlag,I as DeviceUtilities,TS as DocumentExtension,Yr as DragControls,ey as DragMode,Xo as DropListener,my as Duplicatable,Ah as EffectWrapper,ts as EmissionModule,Ol as EmphasizeOnClick,xd as EngineLoadingView,lm as EnvironmentScene,ae as EventList,Fu as EventListEvent,ai as EventSystem,ap as EventTrigger,Vx as FieldWithDefault,Ea as FileReference,Sw as FileReferenceSerializer,qR as FileSpawnModel,Cx as File_Event,l0 as FixedJoint,Dl as Fog,xe as FrameEvent,Wa as GENERATOR,S as GameObject,B as Gizmos,vy as GltfExport,by as GltfExportBox,aa as Gradient,vh as Graphic,Nu as GraphicRaycaster,pr as Graphics,jl as GridHelper,Jy as GridLayoutGroup,Kn as GroundProjectedEnv,Jr as GroupActionModel,Gd as HideFlags,fn as HideOnStart,Sh as HingeJoint,Ky as HorizontalLayoutGroup,bM as HostData,yo as HoverAnimation,Xl as Image,Ma as ImageReference,xw as ImageReferenceSerializer,g0 as InheritVelocityModule,K_ as Input,di as InputEventQueue,Ae as InputEvents,V0 as InputField,Ra as InstanceHandle,Oa as InstancingHandler,pn as InstancingUtil,Wv as InstantiateEvent,Bt as InstantiateIdProvider,Nn as InstantiateOptions,Zf as Interactable,Jh as InternalScreenshotUtils,Lk as JoinedRoomResponse,Sk as KeyEventArgs,_i as Keyframe,Mp as LODGroup,Fl as LODModel,Dk as LeftRoomResponse,At as Light,Tw as LightData,dt as LimitVelocityOverLifetimeModule,HL as LoadingElementOptions,Yf as LogStats,Ei as LogType,$0 as LookAt,Wr as LookAtConstraint,T as MODULES,Gt as MainModule,im as MarkerTrackHandler,z0 as MarkerType,wh as MaskableGraphic,ps as MaterialPropertyBlock,tp as MaterialX,j as Mathf,js as MeshCollider,ah as MeshRenderer,Y as MinMaxCurve,la as MinMaxGradient,Ac as NEEDLE_ENGINE_FEATURE_FLAGS,Sc as NEKeyboardEvent,Io as NEPointerEvent,ES as NeedleButtonElement,iy as NeedleEngineModelLoader,nb as NeedleEngineWebComponent,lo as NeedleMenu,Xd as NeedlePatchesKey,Sg as NeedleXRController,Z as NeedleXRSession,mv as NeedleXRSync,wv as NeedleXRUtils,Ul as NestedGltf,pv as NetworkConnection,eo as NetworkedStreamEvents,wd as NetworkedStreams,u0 as Networking,$v as NewInstanceModel,ve as NoiseModule,Ji as ObjectRaycaster,Ps as ObjectUtils,ra as OffsetConstraint,Ud as OneEuroFilter,ig as OneEuroFilterXYZ,Ql as OpenURL,ge as OrbitControls,Al as Outline,uv as OwnershipEvent,Eg as OwnershipModel,xs as PUBLIC_KEY,na as Padding,Lp as ParticleBurst,f0 as ParticleSubEmitter,kh as ParticleSystem,Ks as ParticleSystemBaseBehaviour,ln as ParticleSystemRenderer,Ip as ParticleSystemShapeType,gs as PeerHandle,cv as PeerNetworking,oc as Physics,Hy as PhysicsExtension,vt as PhysicsMaterialCombine,Ih as PixelationEffect,hh as PlayAnimationOnClick,zs as PlayAudioOnClick,ya as PlayableDirector,rc as PlayerColor,sn as PlayerState,_1 as PlayerStateEvent,zy as PlayerSync,Ow as PlayerView,kw as PlayerViewManager,vd as PointerEventData,Yd as PointerType,nt as PostProcessingEffect,ut as PostProcessingEffectOrder,I0 as PostProcessingHandler,kl as PreliminaryAction,dh as PreliminaryTrigger,Fs as PreviewHelper,Qa as PrimitiveType,le as Progress,Zm as PromiseAllWithErrors,Ym as PromiseErrorResult,se as RGBAColor,lc as RapierPhysics,rm as RawImage,Os as RaycastOptions,x1 as Rect,Ln as RectTransform,Go as ReflectionProbe,fr as RegisteredAnimationInfo,Xp as RemoteSkybox,wo as RenderTexture,dx as RenderTextureSerializer,ei as Renderer,Rw as RendererData,dy as RendererLightmap,Ke as Rigidbody,Ze as RigidbodyConstraints,ie as RoomEvents,an as RotationBySpeedModule,Dn as RotationOverLifetimeModule,ep as SceneLightSettings,Je as SceneSwitcher,ir as ScreenCapture,is as ScreenSpaceAmbientOcclusion,Bn as ScreenSpaceAmbientOcclusionN8,rs as ScrollFollow,os as SeeThrough,Pn as SendQueue,sf as SerializationContext,Ay as SetActiveOnClick,Uh as ShadowCatcher,m0 as ShapeModule,H_ as ShapeOverlapResult,Dh as SharpeningEffect,tm as SignalAsset,Hh as SignalReceiver,$h as SignalReceiverEvent,qh as SignalTrackHandler,w1 as Size,vi as SizeBySpeedModule,ca as SizeOverLifetimeModule,uy as SkinnedMeshRenderer,Yp as SmoothFollow,Ca as SpatialGrabRaycaster,Qh as SpatialHtml,Zp as SpatialTrigger,po as SpatialTriggerReceiver,Kp as SpectatorCamera,pl as SphereCollider,zg as SphereIntersection,fa as SplineContainer,mo as SplineData,cb as SplineUtils,hn as SplineWalker,Yo as Sprite,El as SpriteData,yi as SpriteRenderer,Ml as SpriteSheet,FE as StateMachineBehaviour,Nf as StreamEndedEvent,gx as StreamReceivedEvent,Up as SubEmitterSystem,D0 as SyncedCamera,Fn as SyncedRoom,Tn as SyncedTransform,Ly as TapGestureTrigger,xp as TeleportTarget,F0 as TestRunner,U0 as TestSimulateUserData,Ht as Text,Yy as TextBuilder,Op as TextExtension,qt as TextureSheetAnimationModule,uo as TiltShiftEffect,Iw as Time,Js as ToneMappingEffect,ql as TrackHandler,Vi as TrackType,Fe as TrailModule,Ne as TransformData,ba as TransformGizmo,$t as TriggerBuilder,dr as TriggerModel,C as TypeStore,jf as UIRaycastUtils,yh as UIRootComponent,wy as USDDocument,rt as USDObject,Kx as USDWriter,e1 as USDZExporter,ho as USDZExporter$1,Il as USDZText,i0 as USDZUIExtension,ux as UriSerializer,oh as UsageMarker,jk as UserJoinedOrLeftRoomModel,Ti as VERSION,Ey as VariantAction,He as VelocityOverLifetimeModule,Zy as VerticalLayoutGroup,pt as VideoPlayer,st as ViewBox,Fo as ViewDevice,pa as Vignette,uh as VisibilityAction,Ds as Voip,$l as Volume,z as VolumeParameter,zp as VolumeProfile,YM as WaitForFrames,Cw as WaitForPromise,pf as WaitForSeconds,us as Watch,ed as WebARCameraBackground,yn as WebARSessionRoot,Sp as WebXR,ur as WebXRButtonFactory,id as WebXRImageTracking,ls as WebXRImageTrackingModel,cs as WebXRPlaneTracking,ac as WebXRTrackedImage,as as XRControllerFollow,Zo as XRControllerModel,Bi as XRControllerMovement,tn as XRFlag,mm as XRRig,ri as XRState,io as XRStateFlag,AS as __Ignore,aM as __internalNotifyObjectDestroyed,Ao as activeInHierarchyFieldName,Xm as addAttributeChangeCallback,Mn as addComponent,bT as addCustomExtensionPlugin,Lr as addNewComponent,qd as addPatch,gu as apply,TE as applyHMRChanges,rw as applyPrototypeExtensions,Vv as beginListenDestroy,Gv as beginListenInstantiate,Og as binaryIdentifierCasts,fE as build_scene_functions,Mr as builtinComponentKeyName,ib as calculateProgress01,fO as clearMessages,tR as colorSerializer,Yv as compareAssociation,Uu as componentSerializer,P_ as copyTexture,ox as createMotion,ui as debugNet,Pc as debugOwner,s1 as decompressGpuTexture,pc as deepClone,Ro as delay,mc as delayForFrames,pu as deserializeObject,Ii as destroy,hw as destroyComponentInstance,Px as determineMimeTypeFromExtension,ke as disposeObjectResources,to as disposeStream,xc as editorGuidKeyName,Na as enableSpatialConsole,nR as euler,aR as eventListSerializer,iD as exportAsGLTF,cf as findByGuid,tl as findObjectOfType,pw as findObjectsOfType,Ng as findResourceUsers,ax as fitCamera,k_ as fitObjectIntoVolume,Fr as foreachComponent,vu as foreachComponentEnumerator,LO as forward,Bw as generateQRCode,Hv as generateSeed,Ri as getBoundingBox,p_ as getCameraController,Dr as getComponent,Fc as getComponentInChildren,Uc as getComponentInParent,Bc as getComponents,el as getComponentsInChildren,mu as getComponentsInParent,Xx as getFormattedDate,Ot as getIconElement,_f as getIconTexture,Cn as getLoader,jc as getOrAddComponent,w as getParam,BO as getParentHierarchyPath,XP as getPath,Rk as getPeerOptions,av as getPeerjsInstance,cM as getResourceUserCount,f_ as getTempColor,ci as getTempQuaternion,F as getTempVector,dc as getUrlParams,O_ as getVisibleInCustomShadowRendering,v_ as getWorldDirection,cg as getWorldEuler,ee as getWorldPosition,_e as getWorldQuaternion,Vd as getWorldRotation,$e as getWorldScale,Zn as hasCommercialLicense,Vc as hasIndieLicense,Bu as hasPointerEventComponent,Yn as hasProLicense,A_ as hideDebugConsole,r1 as imageToCanvas,Ur as instantiate,Fx as invokeLoadedImportPluginHooks,Z_ as invokeXRSessionEnd,Y_ as invokeXRSessionStart,mw as isActiveInHierarchy,il as isActiveSelf,eO as isAndroidDevice,C_ as isAnimationAction,bg as isComponent,$P as isDebugMode,YP as isDesktop,Br as isDestroyed,A as isDevEnvironment,rM as isDisposed,eD as isExporting,N_ as isGLTFModel,Xb as isHostedOnGlitch,Af as isHotReloadEnabled,EE as isHotReloading,KP as isIPad,Fw as isIconElement,ki as isLocalNetwork,iO as isMacOS,ZP as isMobileDevice,tO as isMozillaXR,sO as isQuest,Ev as isResourceTrackingEnabled,oO as isSafari,yu as isUsingInstancing,nO as isiOS,JP as isiPad,UL as loadAsset,ay as loadPMREM,tb as loadSync,$d as logHierarchy,OO as lookAtInverse,gc as lookAtObject,kO as lookAtScreenPoint,GP as makeId,e_ as makeIdFromRandomWords,ji as makeNameSafe,gw as markAsInstancedRendered,rO as microphonePermissionsGranted,VP as nameof,Yb as nameofFactory,hx as objectSerializer,xk as offXRSessionEnd,wk as offXRSessionStart,wE as onAfterRender,vE as onBeforeRender,bE as onClear,_E as onDestroy,Cf as onInitialized,Eu as onStart,Vw as onUpdate,xg as onXRSessionEnd,Qd as onXRSessionStart,bS as parseSync,M_ as placeOnSurface,ug as postprocessFBXMaterials,QE as prefix,Zb as pushState,qP as randomNumber,kg as registerBinaryType,Mu as registerComponent,cy as registerComponentExtension,cn as registerCustomEffectType,hy as registerExportExtensions,np as registerExtensions,Kw as registerHotReloadType,yg as registerLoader,Xv as registerPrefabProvider,aw as registerPrototypeExtensions,Jg as registerType,i_ as relativePathPrefix,Qm as removeAttributeChangeCallback,lf as removeComponent,_T as removeCustomImportExtensionType,_k as removePatch,To as resolveUrl,t_ as sanitizeString,dS as saveImage,xL as screenshot,Y0 as screenshot2,Yg as sendDestroyed,u as serializable,ew as serializeObject,Ye as serializeable,zc as setActive,r_ as setAllowBalloonMessages,uO as setAllowOverlayMessages,Nd as setAutoFitEnabled,ng as setCameraController,yw as setDestroyed,HO as setDevEnvironment,Tv as setDisposable,nl as setDontDestroy,Hm as setOrAddParamsToUrl,HP as setParam,uc as setParamWithoutReload,Tk as setPeerOptions,sM as setResourceTrackingEnabled,Gm as setState,dg as setVisibleInCustomShadowRendering,hg as setWorldEuler,yt as setWorldPosition,Sr as setWorldPositionXYZ,Sn as setWorldQuaternion,lg as setWorldQuaternionXYZW,S_ as setWorldRotation,fc as setWorldRotationXYZ,za as setWorldScale,_c as showBalloonError,Oe as showBalloonMessage,be as showBalloonWarning,gg as showDebugConsole,PO as slerp,Lc as syncDestroy,Uy as syncField,Zg as syncInstantiate,FO as textureToCanvas,n_ as toSourceId,sv as tryCastBinary,kx as tryDetermineMimetypeFromBinary,Ox as tryDetermineMimetypeFromURL,Ba as tryFindObject,rv as tryGetGuid,Jw as unregisterHotReloadType,qm as unwatchWrite,m_ as useForAutoFit,Mt as validate,Bd as watchWrite};