@needle-tools/engine 5.1.0-experimental.0 → 5.1.0-experimental.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.
@@ -1,4 +1,4 @@
1
- "use strict";const c=require("./three.umd.cjs"),re=require("./gltf-progressive-ByD1UX0A.umd.cjs"),X=require("./three-examples.umd.cjs"),le=require("./vendor-BI4TX0aC.umd.cjs"),ie=require("./three-mesh-ui-Chib781Y.umd.cjs"),Jx=require("./postprocessing-Dwy7Hz_T.umd.cjs");var ya=typeof document<"u"?document.currentScript:null;const Ky=typeof window!==void 0?window.location.search.includes("debugcontext"):!1;var ae=(s=>(s.ContextRegistered="ContextRegistered",s.ContextCreationStart="ContextCreationStart",s.ContextCreated="ContextCreated",s.ContextFirstFrameRendered="ContextFirstFrameRendered",s.ContextDestroying="ContextDestroying",s.ContextDestroyed="ContextDestroyed",s.MissingCamera="MissingCamera",s.ContextClearing="ContextClearing",s.ContextCleared="ContextCleared",s))(ae||{});class ce{static get Current(){return globalThis["NeedleEngine.Context.Current"]}static set Current(e){globalThis["NeedleEngine.Context.Current"]=e}static get All(){return this.Registered}static Registered=[];static register(e){this.Registered.indexOf(e)===-1&&(Ky&&console.warn("Registering context"),this.Registered.push(e),this.dispatchCallback("ContextRegistered",e))}static unregister(e){const t=this.Registered.indexOf(e);t!==-1&&(Ky&&console.warn("Unregistering context"),this.Registered.splice(t,1))}static _callbacks={};static registerCallback(e,t){this._callbacks[e]||(this._callbacks[e]=[]),this._callbacks[e].push(t)}static unregisterCallback(e,t){if(!this._callbacks[e])return;const i=this._callbacks[e].indexOf(t);i!==-1&&this._callbacks[e].splice(i,1)}static dispatchCallback(e,t,i){if(!this._callbacks[e])return!0;const n={event:e,context:t};if(i)for(const r in i)n[r]=i[r];const o=new Array;return this._callbacks[e].forEach(r=>{const a=r(n);a instanceof Promise&&o.push(a)}),Promise.all(o)}static addContextCreatedCallback(e){this.registerCallback("ContextCreated",e)}static addContextDestroyedCallback(e){this.registerCallback("ContextDestroyed",e)}}const Of=new Map;function yi(s=globalThis.location?.hostname){if(Of.has(s))return Of.get(s);const e=/(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})|localhost/.test(s);return Of.set(s,e),e===!0}function uv(){return window.location.hostname.includes("glitch.me")}const fv=()=>s=>s;function eS(s){return fv()(s)}function tS(){return!!x("debug")}class _i{_factory;_cache=[];_maxSize;_index=0;constructor(e,t){this._factory=e,this._maxSize=t}get(){const e=this._index%this._maxSize;return this._index++,this._cache.length<=e&&(this._cache[e]=this._factory()),this._cache[e]}}let Wo=!1;const Ap=new Array;typeof window<"u"&&setTimeout(()=>{if(Wo){const s={},e=new URL(window.location.href),t=new URL(e);t.searchParams.append("console","");const i=t.toString().replace(/=$|=(?=&)/g,"");for(const o of Ap){const r=new URL(e);r.searchParams.append(o,""),s[o]=r.toString().replace(/=$|=(?=&)/g,"")}console.log(`🌵 ?help: Debug Options for Needle Engine.
1
+ "use strict";const c=require("./three.umd.cjs"),re=require("./gltf-progressive-ByD1UX0A.umd.cjs"),X=require("./three-examples.umd.cjs"),le=require("./vendor-BlyEaMTL.umd.cjs"),ie=require("./three-mesh-ui-Chib781Y.umd.cjs"),Jx=require("./postprocessing-Dwy7Hz_T.umd.cjs");var ya=typeof document<"u"?document.currentScript:null;const Ky=typeof window!==void 0?window.location.search.includes("debugcontext"):!1;var ae=(s=>(s.ContextRegistered="ContextRegistered",s.ContextCreationStart="ContextCreationStart",s.ContextCreated="ContextCreated",s.ContextFirstFrameRendered="ContextFirstFrameRendered",s.ContextDestroying="ContextDestroying",s.ContextDestroyed="ContextDestroyed",s.MissingCamera="MissingCamera",s.ContextClearing="ContextClearing",s.ContextCleared="ContextCleared",s))(ae||{});class ce{static get Current(){return globalThis["NeedleEngine.Context.Current"]}static set Current(e){globalThis["NeedleEngine.Context.Current"]=e}static get All(){return this.Registered}static Registered=[];static register(e){this.Registered.indexOf(e)===-1&&(Ky&&console.warn("Registering context"),this.Registered.push(e),this.dispatchCallback("ContextRegistered",e))}static unregister(e){const t=this.Registered.indexOf(e);t!==-1&&(Ky&&console.warn("Unregistering context"),this.Registered.splice(t,1))}static _callbacks={};static registerCallback(e,t){this._callbacks[e]||(this._callbacks[e]=[]),this._callbacks[e].push(t)}static unregisterCallback(e,t){if(!this._callbacks[e])return;const i=this._callbacks[e].indexOf(t);i!==-1&&this._callbacks[e].splice(i,1)}static dispatchCallback(e,t,i){if(!this._callbacks[e])return!0;const n={event:e,context:t};if(i)for(const r in i)n[r]=i[r];const o=new Array;return this._callbacks[e].forEach(r=>{const a=r(n);a instanceof Promise&&o.push(a)}),Promise.all(o)}static addContextCreatedCallback(e){this.registerCallback("ContextCreated",e)}static addContextDestroyedCallback(e){this.registerCallback("ContextDestroyed",e)}}const Of=new Map;function yi(s=globalThis.location?.hostname){if(Of.has(s))return Of.get(s);const e=/(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})|localhost/.test(s);return Of.set(s,e),e===!0}function uv(){return window.location.hostname.includes("glitch.me")}const fv=()=>s=>s;function eS(s){return fv()(s)}function tS(){return!!x("debug")}class _i{_factory;_cache=[];_maxSize;_index=0;constructor(e,t){this._factory=e,this._maxSize=t}get(){const e=this._index%this._maxSize;return this._index++,this._cache.length<=e&&(this._cache[e]=this._factory()),this._cache[e]}}let Wo=!1;const Ap=new Array;typeof window<"u"&&setTimeout(()=>{if(Wo){const s={},e=new URL(window.location.href),t=new URL(e);t.searchParams.append("console","");const i=t.toString().replace(/=$|=(?=&)/g,"");for(const o of Ap){const r=new URL(e);r.searchParams.append(o,""),s[o]=r.toString().replace(/=$|=(?=&)/g,"")}console.log(`🌵 ?help: Debug Options for Needle Engine.
2
2
  Append any of these parameters to the URL to enable specific debug options.
3
3
  Example: ${i} will show an onscreen console window.`);const n=Wo===!0?"":` (containing "${Wo}")`;console.group("Available URL parameters:"+n);for(const o of Object.keys(s).sort())typeof Wo=="string"&&!o.toLowerCase().includes(Wo.toLowerCase())||(console.groupCollapsed(o),console.log("Reload with this flag enabled:"),console.log(s[o]),console.groupEnd());console.groupEnd()}},100);function Fc(){return new URLSearchParams(globalThis.location?.search)}function x(s){Wo&&!Ap.includes(s)&&Ap.push(s);const e=Fc();if(e.has(s)){const t=e.get(s);if(t){const i=Number(t);return isNaN(i)?t:i}else return!0}return!1}Wo=x("help");function iS(s,e){const t=Fc();t.has(s)?t.set(s,e):t.append(s,e),document.location.search=t.toString()}function yc(s,e,t=!0){const i=Fc();i.has(s)?e===null?i.delete(s):i.set(s,e):e!==null&&i.append(s,e),t?pv(s,i):Lm(s,i)}function Lp(s,e,t){s.has(e)?s.set(e,t.toString()):s.append(e,t.toString())}function pv(s,e,t){window.history.pushState(t,s,"?"+e.toString())}function Lm(s,e,t){window.history.replaceState(t,s,"?"+e.toString())}function nS(s){for(var e="",t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",i=t.length,n=0;n<s;n++)e+=t.charAt(Math.floor(Math.random()*i));return e}function sS(s,e){return Math.floor(Math.random()*(e-s+1))+s}const Zy=["smol","tiny","giant","interesting","smart","bright","dull","extreme","beautiful","pretty","dark","epic","salty","silly","funny","lame","lazy","loud","lucky","mad","mean","mighty","mysterious","nasty","odd","old","powerful","quiet","rapid","scary","shiny","shy","silly","smooth","sour","spicy","stupid","sweet","tasty","terrible","ugly","unusual","vast","wet","wild","witty","wrong","zany","zealous","zippy","zombie","zorro"],Jy=["cat","dog","mouse","pig","cow","horse","sheep","chicken","duck","goat","panda","tiger","lion","elephant","monkey","bird","fish","snake","frog","turtle","hamster","penguin","kangaroo","whale","dolphin","crocodile","snail","ant","bee","beetle","butterfly","dragon","eagle","fish","giraffe","lizard","panda","penguin","rabbit","snake","spider","tiger","zebra"];function mv(){const s=Zy[Math.floor(Math.random()*Zy.length)],e=Jy[Math.floor(Math.random()*Jy.length)];return s+"_"+e}function gv(s){return s=s.replace(/[^a-z0-9áéíóúñü \.,_-]/gim,""),s.trim()}function ka(s,e,t=!0,i=!1){if(e==null)return null;if(e.userData&&e.userData.guid===s)return e;if(e.guid==s)return e;if(i&&e.userData?.components){for(const n of e.userData.components)if(n.guid===s)return n}if(t){if(e.scenes)for(const n in e.scenes){const o=e.scenes[n],r=ka(s,o,t,i);if(r)return r}if(e.children)for(const n in e.children){const o=e.children[n],r=ka(s,o,t,i);if(r)return r}}}function Uc(s,e){if(s!=null&&typeof s=="object"){let t;Array.isArray(s)?t=[]:(t=Object.create(s),Object.assign(t,s));for(const i of Object.keys(s)){const n=s[i];e&&!e(s,i,n)?t[i]=n:n?.clone!==void 0&&typeof n.clone=="function"?t[i]=n.clone():t[i]=Uc(n,e)}return t}return s}function _s(s){return new Promise((e,t)=>{setTimeout(e,s)})}function zc(s,e){if(s<=0)return Promise.resolve();if(e||(e=ce.Current),!e)return Promise.reject("No context");const t=e.time.frameCount+s;return new Promise((i,n)=>{if(!e)return n("No context");const o=()=>{e.time.frameCount>=t&&(e.pre_update_callbacks.splice(e.pre_update_callbacks.indexOf(o),1),i())};e.pre_update_callbacks.push(o)})}const Dh=x("debugresolveurl"),yv="rel:";function oS(s,e){return ws(s,e)}function ws(s,e){if(e===void 0)return Dh&&console.warn("getPath: uri is undefined, returning uri",e),e;if(e.startsWith("./"))return e;if(e.startsWith("http"))return Dh&&console.warn("getPath: uri is absolute, returning uri",e),e;if(s===void 0)return Dh&&console.warn("getPath: source is undefined, returning uri",e),e;e.startsWith(yv)&&(e=e.substring(4));const t=s.lastIndexOf("/");if(t>=0){const i=s.substring(0,t+1);for(;i.endsWith("/")&&e.startsWith("/");)e=e.substring(1);const n=i+e;return Dh&&console.log("source:",s,`changed uri
4
4
  from`,e,`
@@ -140,7 +140,7 @@ void main(){
140
140
  #__vconsole .vc-mask {
141
141
  overflow: hidden;
142
142
  }
143
- `,Do?.prepend(i),s===!0&&bv()<=0&&Fv(),console.log("🌵 Debug console has loaded")}},e.onerror=()=>{console.warn("🌵 Debug console failed to load."+(window.crossOriginIsolated?"This page is using cross-origin isolation, so external scripts can't be loaded.":"")),vl=!1,Zt=null},e.src="https://cdn.jsdelivr.net/npm/vconsole@3.15.1/dist/vconsole.min.js",document.body.appendChild(e)}function cC(){if(!globalThis.VConsole)return;const s=new VConsole.VConsolePlugin("needle-console","🌵 Inspect glTF"),e=()=>document.querySelector("#__vc_plug_"+s._id+" iframe");return s.on("renderTab",function(t){const i=globalThis["needle:codegen_files"];if(!i||i.length===0)return;let n=globalThis["needle:codegen_files"][0];const o=n.indexOf("?");o>-1&&(n=n.substring(0,o));const a=location.protocol+"//"+location.host+location.pathname+"/"+n,l=encodeURIComponent(a);s.fullUrl="https://viewer.needle.tools?inspect&file="+l;var h='<iframe src="" style="width: 100%; height: 99%; border: none;"></iframe>';t(h)}),s.on("show",function(){const t=e();t&&t.src!==s.fullUrl&&(t.src=s.fullUrl)}),s.on("hide",function(){const t=e();t&&(t.src="")}),s.on("addTopBar",function(t){var i=new Array;i.push({name:"Open in new window ↗",onClick:function(n){window.open(s.fullUrl,"_blank"),Zt?.hide()}}),i.push({name:"Reload",onClick:function(n){const o=e();o&&(o.src=s.fullUrl)}}),i.push({name:"Fullscreen",onClick:function(n){const o=e();o.requestFullscreen?o.requestFullscreen():o.webkitRequestFullscreen instanceof Function&&o.webkitRequestFullscreen()}}),t(i)}),s}const Up="padding: 10px; font-family: monospace;",d_="margin-bottom: 10px;",Io="margin-bottom: 10px; margin-top: 15px;",hC="width: 100%; border-collapse: collapse; border: 1px solid rgba(0,0,0,0.1); table-layout: fixed;",Uv="border: 1px solid rgba(0,0,0,0.1); padding: 5px;",dC=Uv,uC=Uv+" word-break: break-all;";function En(s,e=!1){e&&s.sort((i,n)=>(n.value?1:0)-(i.value?1:0));let t=`<table style='${hC}'>`;t+="<tbody>";for(const i of s){const n=typeof i.value=="boolean"?i.value?"✅":"❌":i.value;t+=`<tr><td style='${dC}'>${i.label}</td><td style='${uC}'>${n}</td></tr>`}return t+="</tbody></table>",t}function zv(){try{if(document.createElement("canvas").getContext("webgl2"))return"✅"}catch{}return"❌"}function fC(){if(!globalThis.VConsole)return;const s=new VConsole.VConsolePlugin("device-utilities","📱 Device Info");return s.on("renderTab",function(e){let t=`<div style='${Up}'>`;const i=SC();t+=`<h3 style='${d_}'>Device: ${i}</h3>`,t+=En([{label:"💻 Desktop",value:exports.DeviceUtilities.isDesktop()},{label:"📱 Mobile Device",value:exports.DeviceUtilities.isMobileDevice()},{label:"🍎 iOS",value:exports.DeviceUtilities.isiOS()},{label:"📱 iPad",value:exports.DeviceUtilities.isiPad()},{label:"🤖 Android",value:exports.DeviceUtilities.isAndroidDevice()},{label:"🦊 Mozilla XR",value:exports.DeviceUtilities.isMozillaXR()},{label:"🌵 Needle App Clip",value:exports.DeviceUtilities.isNeedleAppClip()},{label:"🍏 macOS",value:exports.DeviceUtilities.isMacOS()},{label:"👓 VisionOS",value:exports.DeviceUtilities.isVisionOS()},{label:"🧭 Safari",value:exports.DeviceUtilities.isSafari()},{label:"🕶️ Meta Quest",value:exports.DeviceUtilities.isQuest()},{label:"🔗 QuickLook AR Support",value:exports.DeviceUtilities.supportsQuickLookAR()}],!0);const n=[],o=exports.DeviceUtilities.getiOSVersion();o&&n.push({label:"🍎 iOS Version",value:o});const r=exports.DeviceUtilities.getChromeVersion();r&&n.push({label:"🌐 Chrome Version",value:r});const a=exports.DeviceUtilities.getSafariVersion();a&&n.push({label:"🧭 Safari Version",value:a}),n.length>0&&(t+=En(n,!1)),t+="</div>",t+=`<div style='${Up} margin-top: 20px;'>`,t+=`<h3 style='${d_}'>User Agent Info</h3>`;const l=[{label:"User Agent",value:navigator.userAgent},{label:"Platform",value:navigator.platform},{label:"App Version",value:navigator.appVersion},{label:"User Agent Data",value:navigator.userAgentData?`Platform: ${navigator.userAgentData.platform}, Mobile: ${navigator.userAgentData.mobile}`:"Not supported"},{label:"WebXR",value:"xr"in navigator?"✅":"❌"},{label:"WebGPU",value:"gpu"in navigator?"✅":"❌"},{label:"WebGL 2",value:zv()}];t+=En(l,!1),t+="</div>",e(t)}),s}function pC(){if(!globalThis.VConsole)return;const s=new VConsole.VConsolePlugin("graphics-info","🎨 Graphics Info");return s.on("renderTab",async function(e){let t=`<div style='${Up}'>`;const i=mC();i.length>0&&(t+=`<h3 style='${Io}'>General GPU Info</h3>`,t+=En(i,!1));const n=yC();n.length>0&&(t+=`<h3 style='${Io}'>WebGL</h3>`,t+=En(n,!1));const o=_C();o.length>0&&(t+=`<h3 style='${Io}'>WebGL 2 Features</h3>`,t+=En(o,!1));const r=bC();r.length>0&&(t+=`<h3 style='${Io}'>WebGL Limits</h3>`,t+=En(r,!1));const a=vC();a.length>0&&(t+=`<h3 style='${Io}'>Texture Formats</h3>`,t+=En(a,!1));const l=await wC();if(l.length>0&&(t+=`<h3 style='${Io}'>WebGPU</h3>`,t+=En(l,!1)),exports.DeviceUtilities.isSafari()){const h=xC();h.length>0&&(t+=`<h3 style='${Io}'>Safari GPU Info</h3>`,t+=En(h,!1))}t+="</div>",e(t)}),s}function mC(){const s=[],e=window.devicePixelRatio;s.push({label:"Device Pixel Ratio",value:e.toString()}),s.push({label:"Width (px)",value:(window.innerWidth*e).toString()}),s.push({label:"Height (px)",value:(window.innerHeight*e).toString()});const i=exports.DeviceUtilities.isMobileDevice()?150:96,n=screen.width/i,o=screen.height/i,r=n*2.54,a=o*2.54;s.push({label:"Estimated Width (cm)",value:r.toFixed(1)}),s.push({label:"Estimated Height (cm)",value:a.toFixed(1)});const l=Nv();if(l){s.push({label:"GPU",value:l.renderer}),s.push({label:"Driver",value:l.vendor}),s.push({label:"ANGLE",value:l.angle||"Not detected"});const h=gC(l.renderer);h&&(h.manufacturer&&s.push({label:"Manufacturer",value:h.manufacturer}),h.cardVersion&&s.push({label:"Card Version",value:h.cardVersion}),h.brand&&s.push({label:"Brand",value:h.brand}),s.push({label:"Integrated",value:h.integrated?"Yes":"No"}),h.layer&&s.push({label:"WebGL Layer",value:h.layer}))}return s}function gC(s){if(!s)return null;const e=(h,d)=>{const u=d.match(h);return u&&u[0]},t=e(/(ANGLE)/g,s)||void 0,i=e(/((NVIDIA|AMD|Intel)[^\d]*[^\s]+)/,s)||s,n=i.split(" ");n.shift();const o=e(/(NVIDIA|AMD|Intel)/g,i)||void 0,r=n.length>0?n.pop():void 0,a=n.length>0?n.join(" "):void 0;return{manufacturer:o,cardVersion:r,brand:a,integrated:o==="Intel",layer:t,card:i}}function yC(){const s=[],e=Nv();return e&&(s.push({label:"📊 WebGL Version",value:e.version}),s.push({label:"🎮 WebGL 2 Available",value:zv()})),s}function _C(){const s=[];try{const t=document.createElement("canvas").getContext("webgl2");if(!t)return s;s.push({label:"Float Color Buffer",value:t.getExtension("EXT_color_buffer_float")?"✅":"❌"}),s.push({label:"Anisotropic Filtering",value:t.getExtension("EXT_texture_filter_anisotropic")?"✅":"❌"}),s.push({label:"Float Texture Linear",value:t.getExtension("OES_texture_float_linear")?"✅":"❌"}),s.push({label:"S3TC Compression",value:t.getExtension("WEBGL_compressed_texture_s3tc")?"✅":"❌"}),s.push({label:"ETC Compression",value:t.getExtension("WEBGL_compressed_texture_etc")?"✅":"❌"}),s.push({label:"PVRTC Compression",value:t.getExtension("WEBGL_compressed_texture_pvrtc")?"✅":"❌"}),s.push({label:"ASTC Compression",value:t.getExtension("WEBGL_compressed_texture_astc")?"✅":"❌"})}catch{}return s}function bC(){const s=[];try{const e=document.createElement("canvas"),t=e.getContext("webgl2")||e.getContext("webgl");if(!t)return s;const i=t instanceof WebGL2RenderingContext;s.push({label:"📏 Max Texture Size",value:t.getParameter(t.MAX_TEXTURE_SIZE).toString()}),s.push({label:"🎨 Max Renderbuffer Size",value:t.getParameter(t.MAX_RENDERBUFFER_SIZE).toString()}),s.push({label:"🔗 Max Vertex Attribs",value:t.getParameter(t.MAX_VERTEX_ATTRIBS).toString()}),s.push({label:"🎯 Max Texture Units",value:t.getParameter(t.MAX_TEXTURE_IMAGE_UNITS).toString()}),i&&(s.push({label:"⚡ Max Samples",value:t.getParameter(t.MAX_SAMPLES).toString()}),s.push({label:"🔄 Max Uniform Buffer Bindings",value:t.getParameter(t.MAX_UNIFORM_BUFFER_BINDINGS).toString()}),s.push({label:"📐 Max 3D Texture Size",value:t.getParameter(t.MAX_3D_TEXTURE_SIZE).toString()}))}catch{}return s}function vC(){const s=[];try{document.createElement("canvas").getContext("webgl")&&(s.push({label:"WebGL 1 RGBA",value:"✅"}),s.push({label:"WebGL 1 RGB",value:"✅"}));const n=document.createElement("canvas").getContext("webgl2");n&&(s.push({label:"WebGL 2 RGBA32F",value:n.getExtension("EXT_color_buffer_float")?"✅":"❌"}),s.push({label:"WebGL 2 RGB32F",value:n.getExtension("EXT_color_buffer_float")?"✅":"❌"}),s.push({label:"WebGL 2 R11F_G11F_B10F",value:"✅"}),s.push({label:"WebGL 2 RGB565",value:"✅"}),s.push({label:"WebGL 2 RGB5_A1",value:"✅"}),s.push({label:"WebGL 2 RGBA4444",value:"✅"}))}catch{}return s}async function wC(){const s=[];if(!("gpu"in navigator))return s.push({label:"🚀 WebGPU Support",value:"❌ Not supported"}),s;s.push({label:"🚀 WebGPU Support",value:"✅ Supported"});try{const e=await navigator.gpu.requestAdapter();if(!e)return s.push({label:"🎯 Adapter",value:"No adapter available"}),s;s.push({label:"🎯 Adapter",value:e.name||"Unknown Adapter"});const t=await e.requestDevice();s.push({label:"🔧 Device",value:t.label||"WebGPU Device"}),s.push({label:"📏 Max Texture 2D",value:t.limits.maxTextureDimension2D.toString()}),s.push({label:"📐 Max Texture 3D",value:t.limits.maxTextureDimension3D.toString()}),s.push({label:"📊 Max Texture Array Layers",value:t.limits.maxTextureArrayLayers.toString()}),s.push({label:"💾 Max Buffer Size",value:`${(t.limits.maxBufferSize/1024/1024).toFixed(1)}MB`}),s.push({label:"🔗 Max Bind Groups",value:t.limits.maxBindGroups.toString()})}catch(e){s.push({label:"❌ Error",value:e.message})}return s}function Nv(){try{const s=document.createElement("canvas"),e=s.getContext("webgl2")||s.getContext("webgl");if(!e)return null;const t=e.getExtension("WEBGL_debug_renderer_info"),i=t?e.getParameter(t.UNMASKED_RENDERER_WEBGL):e.getParameter(e.RENDERER),n=t?e.getParameter(t.UNMASKED_VENDOR_WEBGL):e.getParameter(e.VENDOR),o=e.getParameter(e.VERSION);let r;if(i&&i.includes("ANGLE")){const a=i.match(/ANGLE \(([^)]+)\)/);a&&(r=a[1])}return{renderer:i,vendor:n,version:o,angle:r}}catch{return null}}function xC(){const s=[];try{const t=document.createElement("canvas").getContext("webgl");if(t){const i=t.getExtension("WEBGL_debug_renderer_info");if(i){const n=t.getParameter(i.UNMASKED_RENDERER_WEBGL);n&&n.includes("Apple")&&s.push({label:"🍎 Apple GPU",value:n})}}}catch{}try{const t=document.createElement("canvas").getContext("webgl");t&&(t.getSupportedExtensions()||[]).includes("WEBGL_compressed_texture_pvrtc")&&s.push({label:"🗜️ PVRTC Support",value:"✅"})}catch{}return s}function SC(){return exports.DeviceUtilities.isQuest()?"Meta Quest":exports.DeviceUtilities.isVisionOS()?"Vision Pro":exports.DeviceUtilities.isiOS()?exports.DeviceUtilities.isiPad()?"iPad":"iPhone/iPod":exports.DeviceUtilities.isAndroidDevice()?"Android Device":exports.DeviceUtilities.isMozillaXR()?"Mozilla XR Browser":exports.DeviceUtilities.isNeedleAppClip()?"Needle App Clip":exports.DeviceUtilities.isMacOS()?"Mac":exports.DeviceUtilities.isDesktop()?"Desktop PC":"Unknown Device"}function CC(){const s=document.querySelector("#__vconsole .vc-switch");return s||null}function PC(){const s=document.querySelector("#__vconsole");return s||null}const jh=x("debugtypes");class OC{_types=new Map;_reverseTypes=new Map;_lazyLoaders=new Map;constructor(){jh&&console.warn("TypeStore: Created",this)}add(e,t){jh&&console.warn("ADD TYPE",e);const i=this._types.get(e);i?jh&&i!==t&&console.warn("Type name exists multiple times in your project and may lead to runtime errors:",e):(this._types.set(e,t),this._reverseTypes.set(t,e))}addLazy(e,t){this._types.has(e)||this._lazyLoaders.set(e,t)}get(e){return this._types.get(e)||null}async getAsync(e){const t=this._types.get(e);if(t)return t;const i=this._lazyLoaders.get(e);if(i){jh&&console.warn("LAZY LOAD TYPE",e);const n=await i();return this.add(e,n),this._lazyLoaders.delete(e),n}return null}getKey(e){return this._reverseTypes.get(e)||null}}const kC=Symbol("BuiltInType"),P=new OC,qm=function(s){P.get(s.name)||P.add(s.name,s)};class MC{context;mixers=[];constructor(e){this.context=e}onDestroy(){this.mixers.forEach(e=>e.stopAllAction()),this.mixers.length=0}registerAnimationMixer(e){if(!e){console.warn("AnimationsRegistry.registerAnimationMixer called with null or undefined mixer");return}this.mixers.includes(e)||this.mixers.push(e)}unregisterAnimationMixer(e){if(!e){console.warn("AnimationsRegistry.unregisterAnimationMixer called with null or undefined mixer");return}const t=this.mixers.indexOf(e);t!==-1&&this.mixers.splice(t,1)}}class Hn{static testIfRootCanAnimate(e,t){const i=e.getRoot();return i&&(i.userData.static||i.matrixAutoUpdate===!1||i.matrixWorldAutoUpdate===!1)?((t===!0||t===void 0&&A())&&console.warn(`AnimationUtils: The root object (${i.name||i.type}) of this AnimationAction has matrixAutoUpdate or matrixWorldAutoUpdate set to false. This may prevent the animation from working correctly. If the object is marked as static, try to change it to dynamic.`,{static:i.userData.static,name:i.userData.name,tag:i.userData.tag,matrixAutoUpdate:i.matrixAutoUpdate,matrixWorldAutoUpdate:i.matrixWorldAutoUpdate}),!1):!0}static tryGetActionsFromMixer(e){const t=e._actions;return t||null}static tryGetAnimationClipsFromObjectHierarchy(e,t){if(t||(t=new Array),e)e.animations&&t.push(...e.animations);else return t;if(e.children)for(const i of e.children)this.tryGetAnimationClipsFromObjectHierarchy(i,t);return t}static autoplayAnimations(e){if(!e||!e.animations)return console.debug("No animations found in file"),null;const t="scene"in e?e.scene:e,i=new Array;for(let o=0;o<e.animations.length;o++){const r=e.animations[o];if(!r.tracks||r.tracks.length<=0){console.warn("Animation has no tracks");continue}for(const a in r.tracks){const l=r.tracks[a],h=c.PropertyBinding.parseTrackName(l.name);let d=c.PropertyBinding.findNode(t,h.nodeName);if(!d){const p=l.__objectName??l.name.substring(0,l.name.indexOf("."));if(d=t.getObjectByProperty("uuid",p)??null,!d)continue}let u=n(d)||n(t);if(!u){const p=P.get("Animation");if(u=t.addComponent(p),!u){console.error("Failed creating Animation component: No 'Animation' component found in TypeStore");break}}i.push(u),u.addClip&&u.addClip(r)}}return i;function n(o){if(!o)return null;const r=o.userData?.components;if(r&&r.length>0)for(let a=0;a<r.length;a++){const l=r[a];if(l.isAnimationComponent===!0)return l}return n(o.parent)}}static emptyClip(){return new c.AnimationClip("empty",0,[])}static createScaleClip(e){const t=e?.duration??.3;let i={x:1,y:1,z:1};e?.scale!==void 0&&(typeof e.scale=="number"?i={x:e.scale,y:e.scale,z:e.scale}:i=e.scale);const n=e?.type??"linear",o=e?.scaleFactor??1.2,r=new Array,a=new Array;switch(n){case"linear":r.push(0,t),a.push(i.x,i.y,i.z,i.x*o,i.y*o,i.z*o);break;case"spring":r.push(0,t*.3,t*.5,t*.7,t*.9,t),a.push(i.x,i.y,i.z,i.x*o,i.y*o,i.z*o,i.x*.9,i.y*.9,i.z*.9,i.x*1.05,i.y*1.05,i.z*1.05,i.x*.98,i.y*.98,i.z*.98,i.x,i.y,i.z);break}const l=new c.KeyframeTrack(".scale",r,a);return new c.AnimationClip("scale",r[r.length-1],[l])}}const Be=function(s){return f(s)},f=function(s){if(s===void 0&&(s=null),!Array.isArray(s))s=u_(s);else for(let e=0;e<s.length;e++){const t=s[e];s[e]=u_(t)}return function(e,t){if(!e){const n=typeof t=="string"?t:t.name;console.warn(`@serializable without a target at '${n}'.`);return}typeof t!="string"&&(t=t.name),Object.getOwnPropertyDescriptor(e,"$serializedTypes")||(e.$serializedTypes={});const i=e.$serializedTypes=e.$serializedTypes||{};i[t]=s}};function u_(s){switch(s?.prototype?.constructor?.name){case"Number":case"String":case"Boolean":return null}return s}const f_=x("debugcomponentevents");class gu{static eventListeners=new Map;static addComponentLifecylceEventListener(e,t){this.eventListeners.has(e)&&this.eventListeners.set(e,[]);let i=this.eventListeners.get(e);i||(i=[]),i.push(t),this.eventListeners.set(e,i),f_&&console.log("Added event listener for "+e,this.eventListeners)}static removeComponentLifecylceEventListener(e,t){const i=this.eventListeners.get(e);if(!i)return;const n=i.indexOf(t);n<0||i.splice(n,1)}static dispatchComponentLifecycleEvent(e,t){const i=this.eventListeners.get(e);if(f_&&console.log("Dispatching event "+e,i),!!i)for(const n of i)n(t)}}const Vv=x("debugdefines");go('if(!globalThis["NEEDLE_ENGINE_VERSION"]) globalThis["NEEDLE_ENGINE_VERSION"] = "0.0.0";');go('if(!globalThis["NEEDLE_ENGINE_GENERATOR"]) globalThis["NEEDLE_ENGINE_GENERATOR"] = "unknown";');go('if(!globalThis["NEEDLE_PROJECT_BUILD_TIME"]) globalThis["NEEDLE_PROJECT_BUILD_TIME"] = "unknown";');go('if(!globalThis["NEEDLE_PUBLIC_KEY"]) globalThis["NEEDLE_PUBLIC_KEY"] = "unknown";');go('globalThis["__NEEDLE_ENGINE_VERSION__"] = "5.1.0-experimental.0";');go('globalThis["__NEEDLE_ENGINE_GENERATOR__"] = "undefined";');go('globalThis["__NEEDLE_PROJECT_BUILD_TIME__"] = "Mon Mar 30 2026 12:54:09 GMT+0700 (Indochina Time)";');go('globalThis["__NEEDLE_PUBLIC_KEY__"] = "npk_ad8e492e31253a2800d563522e42a7311d0d7b766ac4ec1f64d3b425f06eacbd";');const ii="5.1.0-experimental.0",Ea="undefined",_c="Mon Mar 30 2026 12:54:09 GMT+0700 (Indochina Time)";Vv&&console.log(`Engine version: ${ii} (generator: ${Ea})
143
+ `,Do?.prepend(i),s===!0&&bv()<=0&&Fv(),console.log("🌵 Debug console has loaded")}},e.onerror=()=>{console.warn("🌵 Debug console failed to load."+(window.crossOriginIsolated?"This page is using cross-origin isolation, so external scripts can't be loaded.":"")),vl=!1,Zt=null},e.src="https://cdn.jsdelivr.net/npm/vconsole@3.15.1/dist/vconsole.min.js",document.body.appendChild(e)}function cC(){if(!globalThis.VConsole)return;const s=new VConsole.VConsolePlugin("needle-console","🌵 Inspect glTF"),e=()=>document.querySelector("#__vc_plug_"+s._id+" iframe");return s.on("renderTab",function(t){const i=globalThis["needle:codegen_files"];if(!i||i.length===0)return;let n=globalThis["needle:codegen_files"][0];const o=n.indexOf("?");o>-1&&(n=n.substring(0,o));const a=location.protocol+"//"+location.host+location.pathname+"/"+n,l=encodeURIComponent(a);s.fullUrl="https://viewer.needle.tools?inspect&file="+l;var h='<iframe src="" style="width: 100%; height: 99%; border: none;"></iframe>';t(h)}),s.on("show",function(){const t=e();t&&t.src!==s.fullUrl&&(t.src=s.fullUrl)}),s.on("hide",function(){const t=e();t&&(t.src="")}),s.on("addTopBar",function(t){var i=new Array;i.push({name:"Open in new window ↗",onClick:function(n){window.open(s.fullUrl,"_blank"),Zt?.hide()}}),i.push({name:"Reload",onClick:function(n){const o=e();o&&(o.src=s.fullUrl)}}),i.push({name:"Fullscreen",onClick:function(n){const o=e();o.requestFullscreen?o.requestFullscreen():o.webkitRequestFullscreen instanceof Function&&o.webkitRequestFullscreen()}}),t(i)}),s}const Up="padding: 10px; font-family: monospace;",d_="margin-bottom: 10px;",Io="margin-bottom: 10px; margin-top: 15px;",hC="width: 100%; border-collapse: collapse; border: 1px solid rgba(0,0,0,0.1); table-layout: fixed;",Uv="border: 1px solid rgba(0,0,0,0.1); padding: 5px;",dC=Uv,uC=Uv+" word-break: break-all;";function En(s,e=!1){e&&s.sort((i,n)=>(n.value?1:0)-(i.value?1:0));let t=`<table style='${hC}'>`;t+="<tbody>";for(const i of s){const n=typeof i.value=="boolean"?i.value?"✅":"❌":i.value;t+=`<tr><td style='${dC}'>${i.label}</td><td style='${uC}'>${n}</td></tr>`}return t+="</tbody></table>",t}function zv(){try{if(document.createElement("canvas").getContext("webgl2"))return"✅"}catch{}return"❌"}function fC(){if(!globalThis.VConsole)return;const s=new VConsole.VConsolePlugin("device-utilities","📱 Device Info");return s.on("renderTab",function(e){let t=`<div style='${Up}'>`;const i=SC();t+=`<h3 style='${d_}'>Device: ${i}</h3>`,t+=En([{label:"💻 Desktop",value:exports.DeviceUtilities.isDesktop()},{label:"📱 Mobile Device",value:exports.DeviceUtilities.isMobileDevice()},{label:"🍎 iOS",value:exports.DeviceUtilities.isiOS()},{label:"📱 iPad",value:exports.DeviceUtilities.isiPad()},{label:"🤖 Android",value:exports.DeviceUtilities.isAndroidDevice()},{label:"🦊 Mozilla XR",value:exports.DeviceUtilities.isMozillaXR()},{label:"🌵 Needle App Clip",value:exports.DeviceUtilities.isNeedleAppClip()},{label:"🍏 macOS",value:exports.DeviceUtilities.isMacOS()},{label:"👓 VisionOS",value:exports.DeviceUtilities.isVisionOS()},{label:"🧭 Safari",value:exports.DeviceUtilities.isSafari()},{label:"🕶️ Meta Quest",value:exports.DeviceUtilities.isQuest()},{label:"🔗 QuickLook AR Support",value:exports.DeviceUtilities.supportsQuickLookAR()}],!0);const n=[],o=exports.DeviceUtilities.getiOSVersion();o&&n.push({label:"🍎 iOS Version",value:o});const r=exports.DeviceUtilities.getChromeVersion();r&&n.push({label:"🌐 Chrome Version",value:r});const a=exports.DeviceUtilities.getSafariVersion();a&&n.push({label:"🧭 Safari Version",value:a}),n.length>0&&(t+=En(n,!1)),t+="</div>",t+=`<div style='${Up} margin-top: 20px;'>`,t+=`<h3 style='${d_}'>User Agent Info</h3>`;const l=[{label:"User Agent",value:navigator.userAgent},{label:"Platform",value:navigator.platform},{label:"App Version",value:navigator.appVersion},{label:"User Agent Data",value:navigator.userAgentData?`Platform: ${navigator.userAgentData.platform}, Mobile: ${navigator.userAgentData.mobile}`:"Not supported"},{label:"WebXR",value:"xr"in navigator?"✅":"❌"},{label:"WebGPU",value:"gpu"in navigator?"✅":"❌"},{label:"WebGL 2",value:zv()}];t+=En(l,!1),t+="</div>",e(t)}),s}function pC(){if(!globalThis.VConsole)return;const s=new VConsole.VConsolePlugin("graphics-info","🎨 Graphics Info");return s.on("renderTab",async function(e){let t=`<div style='${Up}'>`;const i=mC();i.length>0&&(t+=`<h3 style='${Io}'>General GPU Info</h3>`,t+=En(i,!1));const n=yC();n.length>0&&(t+=`<h3 style='${Io}'>WebGL</h3>`,t+=En(n,!1));const o=_C();o.length>0&&(t+=`<h3 style='${Io}'>WebGL 2 Features</h3>`,t+=En(o,!1));const r=bC();r.length>0&&(t+=`<h3 style='${Io}'>WebGL Limits</h3>`,t+=En(r,!1));const a=vC();a.length>0&&(t+=`<h3 style='${Io}'>Texture Formats</h3>`,t+=En(a,!1));const l=await wC();if(l.length>0&&(t+=`<h3 style='${Io}'>WebGPU</h3>`,t+=En(l,!1)),exports.DeviceUtilities.isSafari()){const h=xC();h.length>0&&(t+=`<h3 style='${Io}'>Safari GPU Info</h3>`,t+=En(h,!1))}t+="</div>",e(t)}),s}function mC(){const s=[],e=window.devicePixelRatio;s.push({label:"Device Pixel Ratio",value:e.toString()}),s.push({label:"Width (px)",value:(window.innerWidth*e).toString()}),s.push({label:"Height (px)",value:(window.innerHeight*e).toString()});const i=exports.DeviceUtilities.isMobileDevice()?150:96,n=screen.width/i,o=screen.height/i,r=n*2.54,a=o*2.54;s.push({label:"Estimated Width (cm)",value:r.toFixed(1)}),s.push({label:"Estimated Height (cm)",value:a.toFixed(1)});const l=Nv();if(l){s.push({label:"GPU",value:l.renderer}),s.push({label:"Driver",value:l.vendor}),s.push({label:"ANGLE",value:l.angle||"Not detected"});const h=gC(l.renderer);h&&(h.manufacturer&&s.push({label:"Manufacturer",value:h.manufacturer}),h.cardVersion&&s.push({label:"Card Version",value:h.cardVersion}),h.brand&&s.push({label:"Brand",value:h.brand}),s.push({label:"Integrated",value:h.integrated?"Yes":"No"}),h.layer&&s.push({label:"WebGL Layer",value:h.layer}))}return s}function gC(s){if(!s)return null;const e=(h,d)=>{const u=d.match(h);return u&&u[0]},t=e(/(ANGLE)/g,s)||void 0,i=e(/((NVIDIA|AMD|Intel)[^\d]*[^\s]+)/,s)||s,n=i.split(" ");n.shift();const o=e(/(NVIDIA|AMD|Intel)/g,i)||void 0,r=n.length>0?n.pop():void 0,a=n.length>0?n.join(" "):void 0;return{manufacturer:o,cardVersion:r,brand:a,integrated:o==="Intel",layer:t,card:i}}function yC(){const s=[],e=Nv();return e&&(s.push({label:"📊 WebGL Version",value:e.version}),s.push({label:"🎮 WebGL 2 Available",value:zv()})),s}function _C(){const s=[];try{const t=document.createElement("canvas").getContext("webgl2");if(!t)return s;s.push({label:"Float Color Buffer",value:t.getExtension("EXT_color_buffer_float")?"✅":"❌"}),s.push({label:"Anisotropic Filtering",value:t.getExtension("EXT_texture_filter_anisotropic")?"✅":"❌"}),s.push({label:"Float Texture Linear",value:t.getExtension("OES_texture_float_linear")?"✅":"❌"}),s.push({label:"S3TC Compression",value:t.getExtension("WEBGL_compressed_texture_s3tc")?"✅":"❌"}),s.push({label:"ETC Compression",value:t.getExtension("WEBGL_compressed_texture_etc")?"✅":"❌"}),s.push({label:"PVRTC Compression",value:t.getExtension("WEBGL_compressed_texture_pvrtc")?"✅":"❌"}),s.push({label:"ASTC Compression",value:t.getExtension("WEBGL_compressed_texture_astc")?"✅":"❌"})}catch{}return s}function bC(){const s=[];try{const e=document.createElement("canvas"),t=e.getContext("webgl2")||e.getContext("webgl");if(!t)return s;const i=t instanceof WebGL2RenderingContext;s.push({label:"📏 Max Texture Size",value:t.getParameter(t.MAX_TEXTURE_SIZE).toString()}),s.push({label:"🎨 Max Renderbuffer Size",value:t.getParameter(t.MAX_RENDERBUFFER_SIZE).toString()}),s.push({label:"🔗 Max Vertex Attribs",value:t.getParameter(t.MAX_VERTEX_ATTRIBS).toString()}),s.push({label:"🎯 Max Texture Units",value:t.getParameter(t.MAX_TEXTURE_IMAGE_UNITS).toString()}),i&&(s.push({label:"⚡ Max Samples",value:t.getParameter(t.MAX_SAMPLES).toString()}),s.push({label:"🔄 Max Uniform Buffer Bindings",value:t.getParameter(t.MAX_UNIFORM_BUFFER_BINDINGS).toString()}),s.push({label:"📐 Max 3D Texture Size",value:t.getParameter(t.MAX_3D_TEXTURE_SIZE).toString()}))}catch{}return s}function vC(){const s=[];try{document.createElement("canvas").getContext("webgl")&&(s.push({label:"WebGL 1 RGBA",value:"✅"}),s.push({label:"WebGL 1 RGB",value:"✅"}));const n=document.createElement("canvas").getContext("webgl2");n&&(s.push({label:"WebGL 2 RGBA32F",value:n.getExtension("EXT_color_buffer_float")?"✅":"❌"}),s.push({label:"WebGL 2 RGB32F",value:n.getExtension("EXT_color_buffer_float")?"✅":"❌"}),s.push({label:"WebGL 2 R11F_G11F_B10F",value:"✅"}),s.push({label:"WebGL 2 RGB565",value:"✅"}),s.push({label:"WebGL 2 RGB5_A1",value:"✅"}),s.push({label:"WebGL 2 RGBA4444",value:"✅"}))}catch{}return s}async function wC(){const s=[];if(!("gpu"in navigator))return s.push({label:"🚀 WebGPU Support",value:"❌ Not supported"}),s;s.push({label:"🚀 WebGPU Support",value:"✅ Supported"});try{const e=await navigator.gpu.requestAdapter();if(!e)return s.push({label:"🎯 Adapter",value:"No adapter available"}),s;s.push({label:"🎯 Adapter",value:e.name||"Unknown Adapter"});const t=await e.requestDevice();s.push({label:"🔧 Device",value:t.label||"WebGPU Device"}),s.push({label:"📏 Max Texture 2D",value:t.limits.maxTextureDimension2D.toString()}),s.push({label:"📐 Max Texture 3D",value:t.limits.maxTextureDimension3D.toString()}),s.push({label:"📊 Max Texture Array Layers",value:t.limits.maxTextureArrayLayers.toString()}),s.push({label:"💾 Max Buffer Size",value:`${(t.limits.maxBufferSize/1024/1024).toFixed(1)}MB`}),s.push({label:"🔗 Max Bind Groups",value:t.limits.maxBindGroups.toString()})}catch(e){s.push({label:"❌ Error",value:e.message})}return s}function Nv(){try{const s=document.createElement("canvas"),e=s.getContext("webgl2")||s.getContext("webgl");if(!e)return null;const t=e.getExtension("WEBGL_debug_renderer_info"),i=t?e.getParameter(t.UNMASKED_RENDERER_WEBGL):e.getParameter(e.RENDERER),n=t?e.getParameter(t.UNMASKED_VENDOR_WEBGL):e.getParameter(e.VENDOR),o=e.getParameter(e.VERSION);let r;if(i&&i.includes("ANGLE")){const a=i.match(/ANGLE \(([^)]+)\)/);a&&(r=a[1])}return{renderer:i,vendor:n,version:o,angle:r}}catch{return null}}function xC(){const s=[];try{const t=document.createElement("canvas").getContext("webgl");if(t){const i=t.getExtension("WEBGL_debug_renderer_info");if(i){const n=t.getParameter(i.UNMASKED_RENDERER_WEBGL);n&&n.includes("Apple")&&s.push({label:"🍎 Apple GPU",value:n})}}}catch{}try{const t=document.createElement("canvas").getContext("webgl");t&&(t.getSupportedExtensions()||[]).includes("WEBGL_compressed_texture_pvrtc")&&s.push({label:"🗜️ PVRTC Support",value:"✅"})}catch{}return s}function SC(){return exports.DeviceUtilities.isQuest()?"Meta Quest":exports.DeviceUtilities.isVisionOS()?"Vision Pro":exports.DeviceUtilities.isiOS()?exports.DeviceUtilities.isiPad()?"iPad":"iPhone/iPod":exports.DeviceUtilities.isAndroidDevice()?"Android Device":exports.DeviceUtilities.isMozillaXR()?"Mozilla XR Browser":exports.DeviceUtilities.isNeedleAppClip()?"Needle App Clip":exports.DeviceUtilities.isMacOS()?"Mac":exports.DeviceUtilities.isDesktop()?"Desktop PC":"Unknown Device"}function CC(){const s=document.querySelector("#__vconsole .vc-switch");return s||null}function PC(){const s=document.querySelector("#__vconsole");return s||null}const jh=x("debugtypes");class OC{_types=new Map;_reverseTypes=new Map;_lazyLoaders=new Map;constructor(){jh&&console.warn("TypeStore: Created",this)}add(e,t){jh&&console.warn("ADD TYPE",e);const i=this._types.get(e);i?jh&&i!==t&&console.warn("Type name exists multiple times in your project and may lead to runtime errors:",e):(this._types.set(e,t),this._reverseTypes.set(t,e))}addLazy(e,t){this._types.has(e)||this._lazyLoaders.set(e,t)}get(e){return this._types.get(e)||null}async getAsync(e){const t=this._types.get(e);if(t)return t;const i=this._lazyLoaders.get(e);if(i){jh&&console.warn("LAZY LOAD TYPE",e);const n=await i();return this.add(e,n),this._lazyLoaders.delete(e),n}return null}getKey(e){return this._reverseTypes.get(e)||null}}const kC=Symbol("BuiltInType"),P=new OC,qm=function(s){P.get(s.name)||P.add(s.name,s)};class MC{context;mixers=[];constructor(e){this.context=e}onDestroy(){this.mixers.forEach(e=>e.stopAllAction()),this.mixers.length=0}registerAnimationMixer(e){if(!e){console.warn("AnimationsRegistry.registerAnimationMixer called with null or undefined mixer");return}this.mixers.includes(e)||this.mixers.push(e)}unregisterAnimationMixer(e){if(!e){console.warn("AnimationsRegistry.unregisterAnimationMixer called with null or undefined mixer");return}const t=this.mixers.indexOf(e);t!==-1&&this.mixers.splice(t,1)}}class Hn{static testIfRootCanAnimate(e,t){const i=e.getRoot();return i&&(i.userData.static||i.matrixAutoUpdate===!1||i.matrixWorldAutoUpdate===!1)?((t===!0||t===void 0&&A())&&console.warn(`AnimationUtils: The root object (${i.name||i.type}) of this AnimationAction has matrixAutoUpdate or matrixWorldAutoUpdate set to false. This may prevent the animation from working correctly. If the object is marked as static, try to change it to dynamic.`,{static:i.userData.static,name:i.userData.name,tag:i.userData.tag,matrixAutoUpdate:i.matrixAutoUpdate,matrixWorldAutoUpdate:i.matrixWorldAutoUpdate}),!1):!0}static tryGetActionsFromMixer(e){const t=e._actions;return t||null}static tryGetAnimationClipsFromObjectHierarchy(e,t){if(t||(t=new Array),e)e.animations&&t.push(...e.animations);else return t;if(e.children)for(const i of e.children)this.tryGetAnimationClipsFromObjectHierarchy(i,t);return t}static autoplayAnimations(e){if(!e||!e.animations)return console.debug("No animations found in file"),null;const t="scene"in e?e.scene:e,i=new Array;for(let o=0;o<e.animations.length;o++){const r=e.animations[o];if(!r.tracks||r.tracks.length<=0){console.warn("Animation has no tracks");continue}for(const a in r.tracks){const l=r.tracks[a],h=c.PropertyBinding.parseTrackName(l.name);let d=c.PropertyBinding.findNode(t,h.nodeName);if(!d){const p=l.__objectName??l.name.substring(0,l.name.indexOf("."));if(d=t.getObjectByProperty("uuid",p)??null,!d)continue}let u=n(d)||n(t);if(!u){const p=P.get("Animation");if(u=t.addComponent(p),!u){console.error("Failed creating Animation component: No 'Animation' component found in TypeStore");break}}i.push(u),u.addClip&&u.addClip(r)}}return i;function n(o){if(!o)return null;const r=o.userData?.components;if(r&&r.length>0)for(let a=0;a<r.length;a++){const l=r[a];if(l.isAnimationComponent===!0)return l}return n(o.parent)}}static emptyClip(){return new c.AnimationClip("empty",0,[])}static createScaleClip(e){const t=e?.duration??.3;let i={x:1,y:1,z:1};e?.scale!==void 0&&(typeof e.scale=="number"?i={x:e.scale,y:e.scale,z:e.scale}:i=e.scale);const n=e?.type??"linear",o=e?.scaleFactor??1.2,r=new Array,a=new Array;switch(n){case"linear":r.push(0,t),a.push(i.x,i.y,i.z,i.x*o,i.y*o,i.z*o);break;case"spring":r.push(0,t*.3,t*.5,t*.7,t*.9,t),a.push(i.x,i.y,i.z,i.x*o,i.y*o,i.z*o,i.x*.9,i.y*.9,i.z*.9,i.x*1.05,i.y*1.05,i.z*1.05,i.x*.98,i.y*.98,i.z*.98,i.x,i.y,i.z);break}const l=new c.KeyframeTrack(".scale",r,a);return new c.AnimationClip("scale",r[r.length-1],[l])}}const Be=function(s){return f(s)},f=function(s){if(s===void 0&&(s=null),!Array.isArray(s))s=u_(s);else for(let e=0;e<s.length;e++){const t=s[e];s[e]=u_(t)}return function(e,t){if(!e){const n=typeof t=="string"?t:t.name;console.warn(`@serializable without a target at '${n}'.`);return}typeof t!="string"&&(t=t.name),Object.getOwnPropertyDescriptor(e,"$serializedTypes")||(e.$serializedTypes={});const i=e.$serializedTypes=e.$serializedTypes||{};i[t]=s}};function u_(s){switch(s?.prototype?.constructor?.name){case"Number":case"String":case"Boolean":return null}return s}const f_=x("debugcomponentevents");class gu{static eventListeners=new Map;static addComponentLifecylceEventListener(e,t){this.eventListeners.has(e)&&this.eventListeners.set(e,[]);let i=this.eventListeners.get(e);i||(i=[]),i.push(t),this.eventListeners.set(e,i),f_&&console.log("Added event listener for "+e,this.eventListeners)}static removeComponentLifecylceEventListener(e,t){const i=this.eventListeners.get(e);if(!i)return;const n=i.indexOf(t);n<0||i.splice(n,1)}static dispatchComponentLifecycleEvent(e,t){const i=this.eventListeners.get(e);if(f_&&console.log("Dispatching event "+e,i),!!i)for(const n of i)n(t)}}const Vv=x("debugdefines");go('if(!globalThis["NEEDLE_ENGINE_VERSION"]) globalThis["NEEDLE_ENGINE_VERSION"] = "0.0.0";');go('if(!globalThis["NEEDLE_ENGINE_GENERATOR"]) globalThis["NEEDLE_ENGINE_GENERATOR"] = "unknown";');go('if(!globalThis["NEEDLE_PROJECT_BUILD_TIME"]) globalThis["NEEDLE_PROJECT_BUILD_TIME"] = "unknown";');go('if(!globalThis["NEEDLE_PUBLIC_KEY"]) globalThis["NEEDLE_PUBLIC_KEY"] = "unknown";');go('globalThis["__NEEDLE_ENGINE_VERSION__"] = "5.1.0-experimental.0";');go('globalThis["__NEEDLE_ENGINE_GENERATOR__"] = "undefined";');go('globalThis["__NEEDLE_PROJECT_BUILD_TIME__"] = "Mon Mar 30 2026 13:05:42 GMT+0700 (Indochina Time)";');go('globalThis["__NEEDLE_PUBLIC_KEY__"] = "npk_ad8e492e31253a2800d563522e42a7311d0d7b766ac4ec1f64d3b425f06eacbd";');const ii="5.1.0-experimental.0",Ea="undefined",_c="Mon Mar 30 2026 13:05:42 GMT+0700 (Indochina Time)";Vv&&console.log(`Engine version: ${ii} (generator: ${Ea})
144
144
  Project built at ${_c}`);const er="npk_ad8e492e31253a2800d563522e42a7311d0d7b766ac4ec1f64d3b425f06eacbd",jn="needle_isActiveInHierarchy",Go="builtin_components",ec="needle_editor_guid";function go(s){try{(0,eval)(s)}catch(e){Vv&&console.error(e)}}const Xm={experimentalSmartHierarchyUpdate:!1},pi=Symbol("shadowDomOwner"),EC=x("debugpatch");function yu(s,e,t,i){const n=EC===e;if(!t&&!i)return;const o=e+"___needle";TC(s,e,t,i);const r=Object.getOwnPropertyDescriptor(s,e),a=s[e];n&&console.log("Patch",s.constructor.name,e,r,a),r?(n&&console.log("Apply patch with existing descriptor",s.constructor.name,e,r),typeof r.value=="function"&&(s[e]=m_(r.value,s,e))):(n&&console.log("Create patch with new property",s.constructor.name,e,r),Object.defineProperty(s,e,{set:function(l){if(typeof l=="function")this[o]=m_(l,s,e);else{const h=this[o];$v(s,e,this,h,l),this[o]=l,Wv(s,e,this,h,l)}},get:function(){const l=this[o];return typeof l=="function"&&l[o]?l[o]:l}}))}function RC(s,e,t){const i=Qm(s,e);if(i)for(let n=i.length-1;n>=0;n--){const o=i[n];o.prefix===t&&(o.prefix=null),o.postfix===t&&(o.postfix=null),!o.prefix&&!o.postfix&&i.splice(n,1)}}const p_=Symbol("Needle:Patches:WrappedFunction");function m_(s,e,t){if(s[p_])return s;const i=function(...n){$v(e,t,this,...n);const o=s.apply(this,n);return Wv(e,t,this,o,...n),o};return i[p_]=!0,i}const _d="Needle:Patches";function zp(){return globalThis[_d]||(globalThis[_d]=new WeakMap),globalThis[_d]}function Qm(s,e){const t=zp().get(s);return t?t.get(e):null}function TC(s,e,t,i){let n=zp().get(s);n||(n=new Map,zp().set(s,n));let o=n.get(e);o||(o=[],n.set(e,o)),o.push({prefix:t,postfix:i})}function $v(s,e,t,...i){if(!t)return;const n=Qm(s,e);if(n)for(const o of n)o.prefix?.call(t,...i)}function Wv(s,e,t,i,...n){if(!t)return;const o=Qm(s,e);if(o)for(const r of o)r.postfix?.call(t,i,...n)}function AC(s,e){if(typeof window!==void 0&&window.SPECTOR){console.log(window.SPECTOR);const t=new URLSearchParams(window.location.search);if(t.has("spector")){let i=function(){if(n>s.time.frame)return window.requestAnimationFrame(()=>i());const r=o.captureCanvas(e);r&&r instanceof Promise?r.then(()=>o.displayUI()):o.displayUI()};const n=Number.parseInt(t.get("spector")||"0")||0;console.log("Scheduled Spector capture at frame #"+n);const o=new window.SPECTOR.Spector;o.spyCanvases=!0,i();return}else A()&&console.debug("Spector available: Add '?spector=<frame>' to the URL to enable it and capture a frame.")}}function Gv(s){const e=s;return!!(e.parser&&e.parser.json)}var _u=(s=>(s[s.None=0]="None",s[s.DontExport=1]="DontExport",s))(_u||{});const Hv=Symbol("component-name");function Ym(s){return s&&s.isComponent}const LC=Symbol("object"),Af=new _i(()=>new c.Vector3,20);class qv{_point;_normal;_tangentVelocity;distance;impulse;friction;get point(){return Af.get().set(this._point.x,this._point.y,this._point.z)}get normal(){return Af.get().set(this._normal.x,this._normal.y,this._normal.z)}get tangentVelocity(){return Af.get().set(this._tangentVelocity.x,this._tangentVelocity.y,this._tangentVelocity.z)}constructor(e,t,i,n,o,r){this._point=e,this.distance=t,this._normal=i,this.impulse=n,this.friction=o,this._tangentVelocity=r}}class Xv{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 Qv{object;collider;constructor(e,t){this.object=e,this.collider=t}}class Gd{constructor(e){this.context=e,this.root.style.cssText=`
145
145
  position: absolute;
146
146
  width: 1px; height: 1px;
@@ -271,8 +271,8 @@ TEX `+i.texture_lod;if(Ff=="density"&&(_+=`
271
271
  `+(y/n.lastScreenCoverage).toFixed(0)+` dens
272
272
  `+(n.lastScreenCoverage*100).toFixed(1)+`% cov
273
273
  `+(n.lastCentrality*100).toFixed(1)+`% centr
274
- `+(zh.min.x.toFixed(2)+"-"+zh.max.x.toFixed(2)+"x"+zh.min.y.toFixed(2)+"-"+zh.max.y.toFixed(2))+" scr"),n.lastScreenCoverage>.1){const g=e,v=g.worldForward,b=g.worldPosition,R=F(v).multiplyScalar(h*.7).add(l),O=R.distanceTo(b),k=d[Math.min(d.length-1,Math.max(0,o))]+"88",L=this.context.domHeight>0?screen.height/this.context.domHeight:1,D=e.isPerspectiveCamera?Math.tan(e.fov*Math.PI/180/2):1;B.DrawLabel(R,_,O*.012*L*D,void 0,16777215,k)}}}}}const og={};function rg(s,e){og[s]=e}function b0(s){const e=s.getBufferIdentifier(),t=og[e];return t(s)}function v0(s){return typeof s.guid=="function"?s.guid():null}function wl(s){const e=[],t={MODULE:void 0,MAYBEMODULE:null,ready(){return t.MODULE?Promise.resolve(t.MODULE):new Promise(i=>{e.push(i)})},async load(){if(t.MODULE)return t.MODULE;const i=await s();t.MODULE=i,t.MAYBEMODULE=i;for(const n of e)n(i);return e.length=0,i}};return t}const T={MaterialX:wl(()=>Promise.resolve().then(()=>require("./materialx-hLP3E8AA.umd.cjs"))),RAPIER_PHYSICS:wl(()=>Promise.resolve().then(()=>require("./rapier-DQltNJbN.umd.cjs"))),POSTPROCESSING:wl(()=>Promise.resolve().then(()=>require("./postprocessing-Dwy7Hz_T.umd.cjs")).then(s=>s.index)),POSTPROCESSING_AO:wl(()=>Promise.resolve().then(()=>require("./postprocessing-Dwy7Hz_T.umd.cjs")).then(s=>s.N8AO)),PEERJS:wl(()=>Promise.resolve().then(()=>require("./vendor-BI4TX0aC.umd.cjs")).then(s=>s.bundler))};let ag;function y1(){return ag}function _1(s){ag=s}async function w0(s,e){const i=(await T.PEERJS.load()).default;return e||(e={}),e={...ag,...e},s?new i(s,e):new i(e)}async function R_(){const s=await T.PEERJS.load();return s.default===void 0?s:s.default}class x0{get isHost(){return this._host!==void 0}_host;_client;_clientData;constructor(){this.onEnable()}onEnable(){this.trySetupHost("HOST-5980e65c-8438-453e-8b35-f13c736dcd81")}async trySetupHost(e){const t=await R_(),i=new t(e);i.on("error",n=>{console.error(n),this._host=void 0,this.trySetupClient(e)}),i.on("open",n=>{this._host=new v1(i)})}async trySetupClient(e){const t=await R_();this._client=new t,this._client.on("error",i=>{console.error("Client error",i)}),this._client.on("open",i=>{console.log("client connected",i),this._clientData=this._client.connect(e,{metadata:{id:i}}),this._clientData.on("open",()=>{console.log("Connected to host")}),this._clientData.on("data",n=>{console.log("<<",n)})})}}class b1{_peer;constructor(e){this._peer=e}}class v1 extends b1{get isHost(){return!0}_connections=[];constructor(e){super(e),console.log("I AM THE HOST"),this._peer?.on("connection",this.onConnection.bind(this)),this._peer.on("close",()=>{this.broadcast("BYE")}),setInterval(()=>{this.broadcast("HELLO")},2e3)}onConnection(e){console.log("host connection",e),e.on("open",()=>{this._connections.push(e),this.broadcastConnection(e)})}broadcastConnection(e){const t=this._connections.map(i=>i.metadata?.id).filter(i=>i!==void 0);this.broadcast({type:"connection-list",connections:t})}broadcast(e){if(e!=null){console.log(">>",e);for(const t in this._peer.connections){const i=this._peer.connections[t];if(i)if(Array.isArray(i))for(const n of i)n&&n.send(e);else console.warn(i)}}}}const T_="https://urls.needle.tools/default-networking-backend/index";let Mi="wss://networking-2.needle.tools/socket";const Yt=!!x("debugnet"),Ul=!!(Yt||x("debugowner")),Vh=x("debugnetbin");var S0=(s=>(s.ConnectionInfo="connection-start-info",s))(S0||{}),K=(s=>(s.Join="join-room",s.Leave="leave-room",s.JoinedRoom="joined-room",s.LeftRoom="left-room",s.UserJoinedRoom="user-joined-room",s.UserLeftRoom="user-left-room",s.RoomStateSent="room-state-sent",s))(K||{});class w1{room;viewId;allowEditing;inRoom}class x1{room}class S1{userId}var C0=(s=>(s.RequestHasOwner="request-has-owner",s.ResponseHasOwner="response-has-owner",s.RequestIsOwner="request-is-owner",s.ResponseIsOwner="response-is-owner",s.RequestOwnership="request-ownership",s.GainedOwnership="gained-ownership",s.RemoveOwnership="remove-ownership",s.LostOwnership="lost-ownership",s.GainedOwnershipBroadcast="gained-ownership-broadcast",s.LostOwnershipBroadcast="lost-ownership-broadcast",s))(C0||{});class lg{guid;connection;get hasOwnership(){return this._hasOwnership}get isOwned(){return this._isOwned}get isConnected(){return this.connection.isConnected}_hasOwnership=!1;_isOwned=void 0;_gainSubscription;_lostSubscription;_hasOwnerResponse;constructor(e,t){this.connection=e,this.guid=t,this._gainSubscription=this.onGainedOwnership.bind(this),this._lostSubscription=this.onLostOwnership.bind(this),e.beginListen("lost-ownership",this._lostSubscription),e.beginListen("gained-ownership-broadcast",this._gainSubscription),this._hasOwnerResponse=this.onHasOwnerResponse.bind(this),e.beginListen("response-has-owner",this._hasOwnerResponse)}_isWaitingForOwnershipResponseCallback=null;updateIsOwned(){this.connection.send("request-has-owner",{guid:this.guid})}onHasOwnerResponse(e){e.guid===this.guid&&(this._isOwned=e.value)}requestOwnershipIfNotOwned(){return this._isWaitingForOwnershipResponseCallback!==null?this:(this._isWaitingForOwnershipResponseCallback=this.waitForHasOwnershipRequestResponse.bind(this),this.connection.beginListen("response-has-owner",this._isWaitingForOwnershipResponseCallback),this.connection.send("request-has-owner",{guid:this.guid}),this)}waitForHasOwnershipRequestResponse(e){e.guid===this.guid&&(this._isWaitingForOwnershipResponseCallback&&(this.connection.stopListen("response-has-owner",this._isWaitingForOwnershipResponseCallback),this._isWaitingForOwnershipResponseCallback=null),this._isOwned=e.value,e.value||(Ul&&console.log("request ownership",this.guid),this.requestOwnership()))}requestOwnershipAsync(){return new Promise((e,t)=>{this.requestOwnership();let i=0;const n=()=>{if(i++>10)return t("Timeout");setTimeout(()=>{this.hasOwnership?e(this):n()},100)};n()})}requestOwnership(){return Ul&&console.log("Request ownership",this.guid),this.connection.send("request-ownership",{guid:this.guid}),this}freeOwnership(){return this.connection.send("remove-ownership",{guid:this.guid}),this._isWaitingForOwnershipResponseCallback&&(this.connection.stopListen("response-has-owner",this._isWaitingForOwnershipResponseCallback),this._isWaitingForOwnershipResponseCallback=null),this}destroy(){this.connection.stopListen("gained-ownership",this._gainSubscription),this.connection.stopListen("lost-ownership",this._lostSubscription),this.connection.stopListen("response-has-owner",this._hasOwnerResponse),this._isWaitingForOwnershipResponseCallback&&(this.connection.stopListen("response-has-owner",this._isWaitingForOwnershipResponseCallback),this._isWaitingForOwnershipResponseCallback=null)}onGainedOwnership(e){e.guid===this.guid&&(this._isOwned=!0,this.connection.connectionId===e.owner?(Ul&&console.log("GAINED OWNERSHIP",this.guid),this._hasOwnership=!0):this._hasOwnership=!1)}onLostOwnership(e){e===this.guid&&(Ul&&console.log("LOST OWNERSHIP",this.guid),this._hasOwnership=!1,this._isOwned=!1)}}class P0{context;_peer=null;constructor(e){this.context=e}get peer(){return this._peer||(this._peer=new x0),this._peer}tryGetState(e){return e==="invalid"?null:this._state[e]}get connectionId(){return this._connectionId}get isDebugEnabled(){return Yt}get isConnected(){return this.connected}get currentRoomName(){return this._currentRoomName}get allowEditing(){return this._currentRoomAllowEditing}get currentRoomViewId(){return this._currentRoomViewId}getViewOnlyUrl(){if(this.currentRoomViewId===null)return null;const e=new URL(window.location.href);return e.searchParams.set("view",this.currentRoomViewId),e.href}get isInRoom(){return this._isInRoom}get currentLatency(){return this._currentDelay}get currentServerUrl(){return this._ws?.url??null}sendPing(){this.send("ping",{time:this.context.time.time})}userIsInRoom(e){return this._currentInRoom.indexOf(e)!==-1}_usersInRoomCopy=[];usersInRoom(e=null){e||(e=this._usersInRoomCopy),e.length=0;for(const t of this._currentInRoom)e.push(t);return e}joinRoom(e,t=!1){return e?e.length>1024?(console.error('Room name too long, can not join: "'+e+'". Max length is 1024 characters.'),!1):(this.isInRoom&&this.currentRoomName!==e&&console.warn("Needle Engine is already connected to a networking room. Connecting to multiple rooms is not supported"),this.connect(),Yt&&console.log("join: "+e),this.send("join-room",{room:e,viewOnly:t},ln.OnConnection),!0):(console.error('Missing room name, can not join: "'+e+'"'),!1)}leaveRoom(e=null){return e||(e=this.currentRoomName),e?(this.send("leave-room",{room:e}),!0):(console.error('Missing room name, can not join: "'+e+'"'),!1)}send(e,t=null,i=ln.Queued){if(t===null&&(t={}),i===ln.Queued){this._defaultMessagesBuffer.push({key:e,value:t});return}return this.sendWithWebsocket(e,t,i)}sendDeleteRemoteState(e){this.send("delete-state",{guid:e,dontSave:!0}),delete this._state[e]}sendDeleteRemoteStateAll(){this.send("delete-all-state"),this._state={}}sendBinary(e){Vh&&console.log("<< send binary",this.context.time.frame,e.length/1024+" KB"),this._ws?.send(e)}_defaultMessagesBuffer=[];_defaultMessagesBufferArray=[];sendBufferedMessagesNow(){if(!this._ws)return;this._defaultMessagesBufferArray.length=0;const e=Object.keys(this._defaultMessagesBuffer).length;for(const i in this._defaultMessagesBuffer){const n=this._defaultMessagesBuffer[i];if(e<=1){this.sendWithWebsocket(n.key,n.value,ln.Immediate);break}const o=this.toMessage(n.key,n.value);this._defaultMessagesBufferArray.push(o)}if(this._defaultMessagesBuffer.length=0,this._defaultMessagesBufferArray.length>0&&Yt&&console.log("SEND BUFFERED",this._defaultMessagesBufferArray.length),this._defaultMessagesBufferArray.length<=0)return;const t=JSON.stringify(this._defaultMessagesBufferArray);this._ws?.send(t)}beginListen(e,t){return this._listeners[e]||(this._listeners[e]=[]),this._listeners[e].push(t),t}stopListening(e,t){return this.stopListen(e,t)}stopListen(e,t){if(!t||!this._listeners[e])return;const i=this._listeners[e].indexOf(t);i>=0&&this._listeners[e].splice(i,1)}beginListenBinary(e,t){return this._listenersBinary[e]||(this._listenersBinary[e]=[]),this._listenersBinary[e].push(t),t}stopListenBinary(e,t){if(!this._listenersBinary[e])return;const i=this._listenersBinary[e].indexOf(t);i>=0&&this._listenersBinary[e].splice(i,1)}netWebSocketUrlProvider;registerProvider(e){this.netWebSocketUrlProvider=e}async connect(e){if(this.connected&&e&&e!==Mi)return Promise.reject("Can not connect to different server url. Please disconnect first.");if(this.connected)return Promise.resolve(!0);e&&console.debug("Connecting to user provided url "+e);const t=e||this.netWebSocketUrlProvider?.getWebsocketUrl();return t?Mi=t:uv()&&(Mi="wss://"+window.location.host+"/socket"),this.connectWebsocket()}disconnect(){this._ws?.close(),this._ws=void 0,Mi=void 0,this._currentRoomAllowEditing=!0,this._currentRoomName=null,this._currentRoomViewId=null,this._isInRoom=!1,this._currentInRoom.length=0,this._state={},this._currentDelay=-1}_listeners={};_listenersBinary={};connected=!1;channelId;_connectionId=null;_ws;_waitingForSocket={};_isInRoom=!1;_currentRoomName=null;_currentRoomViewId=null;_currentRoomAllowEditing=!0;_currentInRoom=[];_state={};_currentDelay=-1;_connectingToWebsocketPromise=null;connectWebsocket(){return this._connectingToWebsocketPromise?this._connectingToWebsocketPromise:this._connectingToWebsocketPromise=new Promise(async(e,t)=>{let i=!1;const n=h=>{i||(i=!0,e(h))};if(Mi===void 0&&(console.log("Fetch default backend url: "+T_),Mi=await(await fetch(T_)).text()),Mi===void 0){n(!1);return}console.debug(`Connecting to networking backend on
275
- `+Mi);const o=await Promise.resolve().then(()=>require("./vendor-BI4TX0aC.umd.cjs")).then(h=>h.index),r=o.default?.WebsocketBuilder??o.WebsocketBuilder,a=o.default?.ExponentialBackoff??o.ExponentialBackoff,l=new r(Mi).withMaxRetries(10).withBackoff(new a(2e3,4)).onOpen(()=>{this._connectingToWebsocketPromise=null,this._ws=l,this.connected=!0,A()||Yt?console.log(`Connected to networking backend
274
+ `+(zh.min.x.toFixed(2)+"-"+zh.max.x.toFixed(2)+"x"+zh.min.y.toFixed(2)+"-"+zh.max.y.toFixed(2))+" scr"),n.lastScreenCoverage>.1){const g=e,v=g.worldForward,b=g.worldPosition,R=F(v).multiplyScalar(h*.7).add(l),O=R.distanceTo(b),k=d[Math.min(d.length-1,Math.max(0,o))]+"88",L=this.context.domHeight>0?screen.height/this.context.domHeight:1,D=e.isPerspectiveCamera?Math.tan(e.fov*Math.PI/180/2):1;B.DrawLabel(R,_,O*.012*L*D,void 0,16777215,k)}}}}}const og={};function rg(s,e){og[s]=e}function b0(s){const e=s.getBufferIdentifier(),t=og[e];return t(s)}function v0(s){return typeof s.guid=="function"?s.guid():null}function wl(s){const e=[],t={MODULE:void 0,MAYBEMODULE:null,ready(){return t.MODULE?Promise.resolve(t.MODULE):new Promise(i=>{e.push(i)})},async load(){if(t.MODULE)return t.MODULE;const i=await s();t.MODULE=i,t.MAYBEMODULE=i;for(const n of e)n(i);return e.length=0,i}};return t}const T={MaterialX:wl(()=>Promise.resolve().then(()=>require("./materialx-hLP3E8AA.umd.cjs"))),RAPIER_PHYSICS:wl(()=>Promise.resolve().then(()=>require("./rapier-DQltNJbN.umd.cjs"))),POSTPROCESSING:wl(()=>Promise.resolve().then(()=>require("./postprocessing-Dwy7Hz_T.umd.cjs")).then(s=>s.index)),POSTPROCESSING_AO:wl(()=>Promise.resolve().then(()=>require("./postprocessing-Dwy7Hz_T.umd.cjs")).then(s=>s.N8AO)),PEERJS:wl(()=>Promise.resolve().then(()=>require("./vendor-BlyEaMTL.umd.cjs")).then(s=>s.bundler))};let ag;function y1(){return ag}function _1(s){ag=s}async function w0(s,e){const i=(await T.PEERJS.load()).default;return e||(e={}),e={...ag,...e},s?new i(s,e):new i(e)}async function R_(){const s=await T.PEERJS.load();return s.default===void 0?s:s.default}class x0{get isHost(){return this._host!==void 0}_host;_client;_clientData;constructor(){this.onEnable()}onEnable(){this.trySetupHost("HOST-5980e65c-8438-453e-8b35-f13c736dcd81")}async trySetupHost(e){const t=await R_(),i=new t(e);i.on("error",n=>{console.error(n),this._host=void 0,this.trySetupClient(e)}),i.on("open",n=>{this._host=new v1(i)})}async trySetupClient(e){const t=await R_();this._client=new t,this._client.on("error",i=>{console.error("Client error",i)}),this._client.on("open",i=>{console.log("client connected",i),this._clientData=this._client.connect(e,{metadata:{id:i}}),this._clientData.on("open",()=>{console.log("Connected to host")}),this._clientData.on("data",n=>{console.log("<<",n)})})}}class b1{_peer;constructor(e){this._peer=e}}class v1 extends b1{get isHost(){return!0}_connections=[];constructor(e){super(e),console.log("I AM THE HOST"),this._peer?.on("connection",this.onConnection.bind(this)),this._peer.on("close",()=>{this.broadcast("BYE")}),setInterval(()=>{this.broadcast("HELLO")},2e3)}onConnection(e){console.log("host connection",e),e.on("open",()=>{this._connections.push(e),this.broadcastConnection(e)})}broadcastConnection(e){const t=this._connections.map(i=>i.metadata?.id).filter(i=>i!==void 0);this.broadcast({type:"connection-list",connections:t})}broadcast(e){if(e!=null){console.log(">>",e);for(const t in this._peer.connections){const i=this._peer.connections[t];if(i)if(Array.isArray(i))for(const n of i)n&&n.send(e);else console.warn(i)}}}}const T_="https://urls.needle.tools/default-networking-backend/index";let Mi="wss://networking-2.needle.tools/socket";const Yt=!!x("debugnet"),Ul=!!(Yt||x("debugowner")),Vh=x("debugnetbin");var S0=(s=>(s.ConnectionInfo="connection-start-info",s))(S0||{}),K=(s=>(s.Join="join-room",s.Leave="leave-room",s.JoinedRoom="joined-room",s.LeftRoom="left-room",s.UserJoinedRoom="user-joined-room",s.UserLeftRoom="user-left-room",s.RoomStateSent="room-state-sent",s))(K||{});class w1{room;viewId;allowEditing;inRoom}class x1{room}class S1{userId}var C0=(s=>(s.RequestHasOwner="request-has-owner",s.ResponseHasOwner="response-has-owner",s.RequestIsOwner="request-is-owner",s.ResponseIsOwner="response-is-owner",s.RequestOwnership="request-ownership",s.GainedOwnership="gained-ownership",s.RemoveOwnership="remove-ownership",s.LostOwnership="lost-ownership",s.GainedOwnershipBroadcast="gained-ownership-broadcast",s.LostOwnershipBroadcast="lost-ownership-broadcast",s))(C0||{});class lg{guid;connection;get hasOwnership(){return this._hasOwnership}get isOwned(){return this._isOwned}get isConnected(){return this.connection.isConnected}_hasOwnership=!1;_isOwned=void 0;_gainSubscription;_lostSubscription;_hasOwnerResponse;constructor(e,t){this.connection=e,this.guid=t,this._gainSubscription=this.onGainedOwnership.bind(this),this._lostSubscription=this.onLostOwnership.bind(this),e.beginListen("lost-ownership",this._lostSubscription),e.beginListen("gained-ownership-broadcast",this._gainSubscription),this._hasOwnerResponse=this.onHasOwnerResponse.bind(this),e.beginListen("response-has-owner",this._hasOwnerResponse)}_isWaitingForOwnershipResponseCallback=null;updateIsOwned(){this.connection.send("request-has-owner",{guid:this.guid})}onHasOwnerResponse(e){e.guid===this.guid&&(this._isOwned=e.value)}requestOwnershipIfNotOwned(){return this._isWaitingForOwnershipResponseCallback!==null?this:(this._isWaitingForOwnershipResponseCallback=this.waitForHasOwnershipRequestResponse.bind(this),this.connection.beginListen("response-has-owner",this._isWaitingForOwnershipResponseCallback),this.connection.send("request-has-owner",{guid:this.guid}),this)}waitForHasOwnershipRequestResponse(e){e.guid===this.guid&&(this._isWaitingForOwnershipResponseCallback&&(this.connection.stopListen("response-has-owner",this._isWaitingForOwnershipResponseCallback),this._isWaitingForOwnershipResponseCallback=null),this._isOwned=e.value,e.value||(Ul&&console.log("request ownership",this.guid),this.requestOwnership()))}requestOwnershipAsync(){return new Promise((e,t)=>{this.requestOwnership();let i=0;const n=()=>{if(i++>10)return t("Timeout");setTimeout(()=>{this.hasOwnership?e(this):n()},100)};n()})}requestOwnership(){return Ul&&console.log("Request ownership",this.guid),this.connection.send("request-ownership",{guid:this.guid}),this}freeOwnership(){return this.connection.send("remove-ownership",{guid:this.guid}),this._isWaitingForOwnershipResponseCallback&&(this.connection.stopListen("response-has-owner",this._isWaitingForOwnershipResponseCallback),this._isWaitingForOwnershipResponseCallback=null),this}destroy(){this.connection.stopListen("gained-ownership",this._gainSubscription),this.connection.stopListen("lost-ownership",this._lostSubscription),this.connection.stopListen("response-has-owner",this._hasOwnerResponse),this._isWaitingForOwnershipResponseCallback&&(this.connection.stopListen("response-has-owner",this._isWaitingForOwnershipResponseCallback),this._isWaitingForOwnershipResponseCallback=null)}onGainedOwnership(e){e.guid===this.guid&&(this._isOwned=!0,this.connection.connectionId===e.owner?(Ul&&console.log("GAINED OWNERSHIP",this.guid),this._hasOwnership=!0):this._hasOwnership=!1)}onLostOwnership(e){e===this.guid&&(Ul&&console.log("LOST OWNERSHIP",this.guid),this._hasOwnership=!1,this._isOwned=!1)}}class P0{context;_peer=null;constructor(e){this.context=e}get peer(){return this._peer||(this._peer=new x0),this._peer}tryGetState(e){return e==="invalid"?null:this._state[e]}get connectionId(){return this._connectionId}get isDebugEnabled(){return Yt}get isConnected(){return this.connected}get currentRoomName(){return this._currentRoomName}get allowEditing(){return this._currentRoomAllowEditing}get currentRoomViewId(){return this._currentRoomViewId}getViewOnlyUrl(){if(this.currentRoomViewId===null)return null;const e=new URL(window.location.href);return e.searchParams.set("view",this.currentRoomViewId),e.href}get isInRoom(){return this._isInRoom}get currentLatency(){return this._currentDelay}get currentServerUrl(){return this._ws?.url??null}sendPing(){this.send("ping",{time:this.context.time.time})}userIsInRoom(e){return this._currentInRoom.indexOf(e)!==-1}_usersInRoomCopy=[];usersInRoom(e=null){e||(e=this._usersInRoomCopy),e.length=0;for(const t of this._currentInRoom)e.push(t);return e}joinRoom(e,t=!1){return e?e.length>1024?(console.error('Room name too long, can not join: "'+e+'". Max length is 1024 characters.'),!1):(this.isInRoom&&this.currentRoomName!==e&&console.warn("Needle Engine is already connected to a networking room. Connecting to multiple rooms is not supported"),this.connect(),Yt&&console.log("join: "+e),this.send("join-room",{room:e,viewOnly:t},ln.OnConnection),!0):(console.error('Missing room name, can not join: "'+e+'"'),!1)}leaveRoom(e=null){return e||(e=this.currentRoomName),e?(this.send("leave-room",{room:e}),!0):(console.error('Missing room name, can not join: "'+e+'"'),!1)}send(e,t=null,i=ln.Queued){if(t===null&&(t={}),i===ln.Queued){this._defaultMessagesBuffer.push({key:e,value:t});return}return this.sendWithWebsocket(e,t,i)}sendDeleteRemoteState(e){this.send("delete-state",{guid:e,dontSave:!0}),delete this._state[e]}sendDeleteRemoteStateAll(){this.send("delete-all-state"),this._state={}}sendBinary(e){Vh&&console.log("<< send binary",this.context.time.frame,e.length/1024+" KB"),this._ws?.send(e)}_defaultMessagesBuffer=[];_defaultMessagesBufferArray=[];sendBufferedMessagesNow(){if(!this._ws)return;this._defaultMessagesBufferArray.length=0;const e=Object.keys(this._defaultMessagesBuffer).length;for(const i in this._defaultMessagesBuffer){const n=this._defaultMessagesBuffer[i];if(e<=1){this.sendWithWebsocket(n.key,n.value,ln.Immediate);break}const o=this.toMessage(n.key,n.value);this._defaultMessagesBufferArray.push(o)}if(this._defaultMessagesBuffer.length=0,this._defaultMessagesBufferArray.length>0&&Yt&&console.log("SEND BUFFERED",this._defaultMessagesBufferArray.length),this._defaultMessagesBufferArray.length<=0)return;const t=JSON.stringify(this._defaultMessagesBufferArray);this._ws?.send(t)}beginListen(e,t){return this._listeners[e]||(this._listeners[e]=[]),this._listeners[e].push(t),t}stopListening(e,t){return this.stopListen(e,t)}stopListen(e,t){if(!t||!this._listeners[e])return;const i=this._listeners[e].indexOf(t);i>=0&&this._listeners[e].splice(i,1)}beginListenBinary(e,t){return this._listenersBinary[e]||(this._listenersBinary[e]=[]),this._listenersBinary[e].push(t),t}stopListenBinary(e,t){if(!this._listenersBinary[e])return;const i=this._listenersBinary[e].indexOf(t);i>=0&&this._listenersBinary[e].splice(i,1)}netWebSocketUrlProvider;registerProvider(e){this.netWebSocketUrlProvider=e}async connect(e){if(this.connected&&e&&e!==Mi)return Promise.reject("Can not connect to different server url. Please disconnect first.");if(this.connected)return Promise.resolve(!0);e&&console.debug("Connecting to user provided url "+e);const t=e||this.netWebSocketUrlProvider?.getWebsocketUrl();return t?Mi=t:uv()&&(Mi="wss://"+window.location.host+"/socket"),this.connectWebsocket()}disconnect(){this._ws?.close(),this._ws=void 0,Mi=void 0,this._currentRoomAllowEditing=!0,this._currentRoomName=null,this._currentRoomViewId=null,this._isInRoom=!1,this._currentInRoom.length=0,this._state={},this._currentDelay=-1}_listeners={};_listenersBinary={};connected=!1;channelId;_connectionId=null;_ws;_waitingForSocket={};_isInRoom=!1;_currentRoomName=null;_currentRoomViewId=null;_currentRoomAllowEditing=!0;_currentInRoom=[];_state={};_currentDelay=-1;_connectingToWebsocketPromise=null;connectWebsocket(){return this._connectingToWebsocketPromise?this._connectingToWebsocketPromise:this._connectingToWebsocketPromise=new Promise(async(e,t)=>{let i=!1;const n=h=>{i||(i=!0,e(h))};if(Mi===void 0&&(console.log("Fetch default backend url: "+T_),Mi=await(await fetch(T_)).text()),Mi===void 0){n(!1);return}console.debug(`Connecting to networking backend on
275
+ `+Mi);const o=await Promise.resolve().then(()=>require("./vendor-BlyEaMTL.umd.cjs")).then(h=>h.index),r=o.default?.WebsocketBuilder??o.WebsocketBuilder,a=o.default?.ExponentialBackoff??o.ExponentialBackoff,l=new r(Mi).withMaxRetries(10).withBackoff(new a(2e3,4)).onOpen(()=>{this._connectingToWebsocketPromise=null,this._ws=l,this.connected=!0,A()||Yt?console.log(`Connected to networking backend
276
276
  `+Mi):console.debug("Connected to networking backend",Mi),n(!0),this.onSendQueued(ln.OnConnection)}).onClose(h=>{this._connectingToWebsocketPromise=null,this.connected=!1,this._isInRoom=!1,n(!1);let d="Websocket connection closed...";Mi?.includes("/socket")||(d+=' Do you perhaps mean to connect to "/socket"?'),console.error(d)}).onError(h=>{console.error("Websocket connection failed..."),n(!1),ni.sendEvent(this.context,"networking",{event:"connection_error"})}).onRetry(()=>{console.log("Retry connecting to networking websocket")}).build();l.addEventListener(o.WebsocketEvent.message,(h,d)=>{this.onMessage(h,d)})})}onMessage(e,t){const i=t.data;try{if(typeof i!="string"){i.size&&this.handleIncomingBinaryMessage(i);return}const n=JSON.parse(i);if(Array.isArray(n))for(const o of n)this.handleIncomingStringMessage(o);else this.handleIncomingStringMessage(n);return}catch(n){Yt&&i==="pong"?console.log("<<",i):A()&&console.error("Failed to parse message",n)}}async handleIncomingBinaryMessage(e){Vh&&console.log("<< bin",this.context.time.frame);const t=await e.arrayBuffer();var i=new Uint8Array(t);const n=new le.ByteBuffer(i),o=n.getBufferIdentifier(),r=this._listenersBinary[o],a=b0(n),l=v0(a);if(l&&typeof l=="string"&&(this._state[l]=a),!r)return;const h=a??n;for(const d of r)d(h)}handleIncomingStringMessage(e){if(Yt&&console.log("<<",e.key??e),e.key)switch(e.key){case"connection-start-info":if(e.data){const r=e.data;r&&(console.assert(r.id!==void 0&&r.id!==null&&r.id.length>0,"server did not send connection id",r.id),console.debug("Your id is: "+r.id,this.context.alias??""),this._connectionId=r.id,ni.sendEvent(this.context,"networking",{event:"connected"}))}else console.warn("Expected connection id in "+e.key);break;case"joined-room":if(Yt&&console.log(e),e){this._isInRoom=!0;const r=e;this._currentRoomName=r.room,this._currentRoomViewId=r.viewId,this._currentRoomAllowEditing=r.allowEditing??!0,this._currentInRoom.length=0,this._currentInRoom.push(...r.inRoom),(Vh||A())&&console.debug("Joined Needle Engine Room: "+r.room);const a=new URL(window.location.href);a.searchParams.has("room")&&a.searchParams.delete("room"),a.searchParams.set("view",this._currentRoomViewId),console.debug(`Room view id: ${this._currentRoomViewId}
277
277
  ${a.href}`)}this.onSendQueued(ln.OnRoomJoin),ni.sendEvent(this.context,"networking",{event:"joined_room",room:this._currentRoomName});break;case"left-room":const n=e;n.room===this.currentRoomName&&(this._isInRoom=!1,this._currentRoomName=null,this._currentRoomAllowEditing=!0,this._currentInRoom.length=0,(Vh||A())&&console.debug("Left Needle Engine Room: "+n.room)),ni.sendEvent(this.context,"networking",{event:"left_room",room:n.room});break;case"user-joined-room":if(e.data){const r=e.data;this._currentInRoom.push(r.userId),Yt&&console.log(r.userId+" joined","now in room:",this._currentInRoom)}break;case"user-left-room":if(e.data){const r=e.data,a=this._currentInRoom.indexOf(r.userId);a>=0&&(Yt&&console.log(r.userId+" left","now in room:",this._currentInRoom),this._currentInRoom.splice(a,1)),r.userId===this.connectionId&&console.log("you left the room")}break;case"all-room-state-deleted":Yt&&console.log("RECEIVED all-room-state-deleted"),this._state={};break;case"ping":case"pong":const o=e.data?.time;o&&(this._currentDelay=this.context.time.time-o),Yt&&console.log(`Current latency: ${(this._currentDelay*1e3).toFixed()} ms`,"Clients in room: "+this._currentInRoom?.length);break}const t=e.data;t&&(this._state[t.guid]=t);let i=this._listeners[e.key];if(i){i=[...i];for(const n of i)try{n(e.data)}catch(o){console.error('Error invoking callback for "'+e.key+'"',o)}}}toMessage(e,t){return{key:e,data:t}}sendWithWebsocket(e,t,i=ln.OnRoomJoin){if(!this._ws){const o=this._waitingForSocket[i]||[];o.push(()=>this.sendWithWebsocket(e,t,i)),this._waitingForSocket[i]=o;return}const n=JSON.stringify(this.toMessage(e,t));Yt&&console.log(">>",e),this._ws.send(n)}onSendQueued(e){const t=this._waitingForSocket[e];if(t){for(const i of t)i();t.length=0}}}const C1=x("debugplayerview");var gs=(s=>(s.Browser="browser",s.Headset="headset",s.Handheld="handheld",s))(gs||{});class O0{userId;context;viewDevice="browser";get currentObject(){return this._object}set currentObject(e){this._object=e}get isConnected(){return this.context.connection.userIsInRoom(this.userId)}removed=!1;_object;constructor(e,t){this.userId=e,this.context=t}}class k0{context;playerViews=new Map;constructor(e){this.context=e}setPlayerView(e,t,i){let n=this.playerViews.get(e);n||(n=new O0(e,this.context),this.playerViews.set(e,n)),n.viewDevice=i,n.currentObject=t,n.removed=!1}getPlayerView(e){if(!e)return;if(!this.context.connection.userIsInRoom(e)){this.playerViews.delete(e);return}return this.playerViews.get(e)}removePlayerView(e,t){const i=this.playerViews.get(e);i?.viewDevice===t&&(C1&&console.log("REMOVE",e),i.removed=!0,this.playerViews.delete(e))}}const qc=new Uint8Array(4);qc[0]=255;qc[1]=255;qc[2]=255;qc[3]=255;const P1=new c.DataTexture(qc,1,1,c.RGBAFormat);function cg(s,e=1){const t="alpha"in s,i=e*e,n=new Uint8Array(4*i),o=Math.floor(s.r*255),r=Math.floor(s.g*255),a=Math.floor(s.b*255);for(let h=0;h<i;h++){const d=h*4;n[d+0]=o,n[d+1]=r,n[d+2]=a,t?n[d+3]=Math.floor(s.alpha*255):n[d+3]=255}const l=new c.DataTexture(n,e,e);return l.needsUpdate=!0,l}function O1(s,e,t,i=1,n=3){const r=i*n,a=[s,e,t],l=a.length,h=new Uint8Array(4*l*r),d=new c.Color;for(let p=0;p<n;p++){const m=Math.floor(p/n*l),y=I.clamp(m+1,0,l-1),_=a[m],g=a[y],v=p/n*l%1;d.lerpColors(_,g,v);const b=Math.floor(d.r*255),w=Math.floor(d.g*255),R=Math.floor(d.b*255);for(let O=0;O<i;O++){const k=(p*i+O)*4;h[k+0]=b,h[k+1]=w,h[k+2]=R,h[k+3]=255}}const u=new c.DataTexture(h,i,n);return u.needsUpdate=!0,u}function Yd(s,e){const t=s.elements;e||(e=[]),e.length=0;for(let i=0;i<16;i+=4){const n=t[i],o=t[i+1],r=t[i+2],a=t[i+3],l=new c.Vector4(n,o,r,a);e.push(l)}return e}const Uf=[],A_=[];function k1(s,e){if(Uf.length===0)for(let t=0;t<27;t++)Uf.push(0);e||(e=Uf);for(let t=0;t<27;t++)A_[t]=e[t];e=A_,s.unity_SHAr={value:new c.Vector4(e[9],e[3],e[6],e[0])},s.unity_SHBr={value:new c.Vector4(e[12],e[15],e[18],e[21])},s.unity_SHAg={value:new c.Vector4(e[10],e[4],e[7],e[1])},s.unity_SHBg={value:new c.Vector4(e[13],e[16],e[19],e[22])},s.unity_SHAb={value:new c.Vector4(e[11],e[5],e[8],e[2])},s.unity_SHBb={value:new c.Vector4(e[14],e[17],e[20],e[23])},s.unity_SHC={value:new c.Vector4(e[24],e[25],e[26],1)}}class M1{vertexShader;fragmentShader;technique;constructor(e,t,i){this.vertexShader=e,this.fragmentShader=t,this.technique=i}}async function E1(s,e){if(!s)return console.error("Can not find technique: no shader data"),null;const t=s.programs[e],i=t.vertexShader,n=t.fragmentShader;if(i!==void 0&&n!==void 0){const o=s.shaders[i],r=s.shaders[n];if(o.uri&&r.uri||o.code&&r.code){if(!o.code&&o.uri&&await L_(o),!r.code&&r.uri&&await L_(r),!o.code||!r.code)return null;const a=s.techniques[e];return new M1(o.code,r.code,a)}}return console.error("Shader technique not found",e),null}async function L_(s){const e=s.uri;if(e)if(e.endsWith(".glsl")){const i=await new c.FileLoader().loadAsync(e);s.code=i.toString()}else s.code=R1(s.uri)}function R1(s){return decodeURIComponent(Array.prototype.map.call(atob(s),function(e){return"%"+("00"+e.charCodeAt(0).toString(16)).slice(-2)}).join(""))}const tn=x("debugenvlight");var va=(s=>(s[s.Skybox=0]="Skybox",s[s.Trilight=1]="Trilight",s[s.Flat=3]="Flat",s[s.Custom=4]="Custom",s))(va||{}),Kd=(s=>(s[s.Skybox=0]="Skybox",s[s.Custom=1]="Custom",s))(Kd||{});class M0{context;constructor(e){this.context=e,this.context.pre_update_callbacks.push(this.preUpdate.bind(this))}_currentLightSettingsId;_sceneLightSettings;get currentLightSettingsId(){return this._currentLightSettingsId}preUpdate(){const e=this.context.time;this._timevec4.x=e.time,this._timevec4.y=Math.sin(e.time),this._timevec4.z=Math.cos(e.time),this._timevec4.w=e.deltaTime}_timevec4=new c.Vector4;get timeVec4(){return this._timevec4}get environmentIntensity(){if(!this._sceneLightSettings||!this._currentLightSettingsId)return 1;const e=this._sceneLightSettings.get(this._currentLightSettingsId);return e?e.ambientIntensity:1}get sceneLightSettings(){return this._sceneLightSettings?.values()}enable(e){e instanceof Z&&(e=e.url);const t=this._sceneLightSettings?.get(e);return t?(tn&&console.log("Enable scene light settings",e,t),e!==this._currentLightSettingsId&&this._currentLightSettingsId&&this.disable(this._currentLightSettingsId),this._currentLightSettingsId=e,t.enabled=!0,!0):(tn&&console.warn("No light settings found for",e),!1)}disable(e){if(e instanceof Z&&(e=e.url),e==null)return!1;const t=this._sceneLightSettings?.get(e);return t?(tn&&console.log("Disable scene light settings",e,t),t.enabled=!1,!0):!1}enableCurrent(){return this._currentLightSettingsId?(this.enable(this._currentLightSettingsId),this._currentLightSettingsId??null):null}disableCurrent(){if(this._currentLightSettingsId){const e=this._currentLightSettingsId;return this.disable(this._currentLightSettingsId),e}return null}internalRegisterSceneLightSettings(e){const t=e.sourceId;if(!t){console.error("Missing source id for scene light settings, can not register:",e);return}tn&&console.log("Register "+e?.sourceId+" lighting",e),this._sceneLightSettings||(this._sceneLightSettings=new Map),this._sceneLightSettings.set(t,e)}internalUnregisterSceneLightSettings(e){const t=e.sourceId;if(!t){console.error("Missing source id for scene light settings, can not unregister:",e);return}tn&&console.log("Unregister "+e?.sourceId+" lighting",e),this._sceneLightSettings&&this._sceneLightSettings.delete(t)}internalRegisterReflection(e,t){tn&&console.log("Register reflection",e,t);const i=new E0(this.context,t,1);this._lighting[e]=i}internalGetReflection(e){return this._lighting[e]}__currentReflectionId=null;internalEnableReflection(e){this.__currentReflectionId=e;const t=this._sceneLightSettings?.get(e);switch(tn&&console.log("Enable reflection",e,t?va[t.ambientMode]:"Unknown ambient mode",t),t?.ambientMode){case 0:case 4:const i=this.internalGetReflection(e);if(i&&i.Source){tn&&console.log("Setting environment reflection",i);const n=this.context.scene,o=i.Source;return o.mapping!==c.CubeUVReflectionMapping&&(o.mapping=c.EquirectangularReflectionMapping),n.environment=o,n.environmentIntensity=this.environmentIntensity||1,o}else tn&&console.warn("Could not find reflection for source",e);break}if(t?.environmentReflectionSource===1)switch(t?.ambientMode){case 1:if(t.ambientTrilight){const i=t.ambientTrilight,n=O1(i[0],i[1],i[2],64,64);return n.colorSpace=c.SRGBColorSpace,n.mapping=c.EquirectangularReflectionMapping,this.context.scene.environment=n,n}else console.error("Missing ambient trilight",t.sourceId);case 3:if(t.ambientLight){const i=cg(t.ambientLight,64);return i.colorSpace=c.SRGBColorSpace,i.mapping=c.EquirectangularReflectionMapping,this.context.scene.environment=i,i}else console.error("Missing ambientlight",t.sourceId)}return null}internalDisableReflection(e){if(e&&e!==this.__currentReflectionId){tn&&console.log("Not disabling reflection for",e,"because it is not the current light settings id",this.__currentReflectionId);return}tn&&console.log("Disable reflection",e);const t=this.context.scene;t.environment=null}_lighting={}}class E0{get Source(){return this._source}_source;constructor(e,t,i=1){this._source=t,t.mapping!==c.CubeUVReflectionMapping&&(t.mapping=c.EquirectangularReflectionMapping)}}const D_=x("timescale");let Qp=1;typeof D_=="number"&&(Qp=D_);class R0{get time(){return this._time}set time(e){this._time=e}_time=0;get deltaTime(){return this._deltaTime}set deltaTime(e){this._deltaTime=e}_deltaTime=0;get deltaTimeUnscaled(){return this._deltaTimeUnscaled}_deltaTimeUnscaled=0;timeScale=1;get frame(){return this._frame}set frame(e){this._frame=e}_frame=0;get frameCount(){return this.frame}get realtimeSinceStartup(){return this.clock.getElapsed()}get fps(){return 1/this.deltaTime}get smoothedFps(){return this._smoothedFps}get smoothedDeltaTime(){return 1/this._smoothedFps}clock=new c.Timer;_smoothedFps=0;_smoothedDeltaTime=0;_fpsSamples=[];_fpsSampleIndex=0;constructor(){typeof Qp=="number"&&(this.timeScale=Qp)}update(){this.clock.update(),this.deltaTime=this.clock.getDelta(),this.deltaTime=Math.min(.1,this.deltaTime),this._deltaTimeUnscaled=this.deltaTime,this.deltaTime<=0&&(this.deltaTime=1e-12),this.deltaTime*=this.timeScale,this.frame+=1,this.time+=this.deltaTime,this._fpsSamples.length<60?this._fpsSamples.push(this.deltaTime):this._fpsSamples[this._fpsSampleIndex++%60]=this.deltaTime;let e=0;for(let t=0;t<this._fpsSamples.length;t++)e+=this._fpsSamples[t];this._smoothedDeltaTime=e/this._fpsSamples.length,this._smoothedFps=1/this._smoothedDeltaTime}}let I_=!1;function T0(s){I_||(I_=!0,T1(),A1())}function T1(){const s=`
278
278
  float startCompression = 0.8;
@@ -876,7 +876,7 @@ Pinch: ${this.getGesture("pinch")?.value.toFixed(3)}`),n+=`
876
876
  Layout: `;for(const o of Object.keys(this._layout.components||{})){const r=this.getStick(o),a=this._layout.components[o]?.gamepadIndices,l=a?Object.entries(a).map(h=>h[0][0].toUpperCase()+h[0].slice(1)+"="+h[1]).join(","):"";n+=`
877
877
  ${o}: ${this._layout.components[o]?.type} [${l}] (${r.x.toPrecision(2)},${r.y.toPrecision(2)})`}}B.DrawLabel(t,n,.006)}onUpdateFrame(e){if(this._handJointPoses.clear(),this._hand_wristDotUp=void 0,!this.xr.referenceSpace||!this.inputSource.gamepad?.connected){this._isTracking=!1;return}const t=e.getPose(this.inputSource.targetRaySpace,this.xr.referenceSpace);this._isTracking=t!=null;let i=null,n=null,o=null,r=null;if(t){const d=t.transform;this._rayMatrix.fromArray(d.matrix).premultiply(wa),this._rayMatrix.decompose(this._rayPosition,this._rayQuaternion,F(1,1,1)),o=F(d.position),r=ei(d.orientation),this._rayPositionRaw.copy(o),this._rayRotationRaw.copy(r)}if(this.inputSource.gripSpace){const d=e.getPose(this.inputSource.gripSpace,this.xr.referenceSpace);if(d){const u=d.transform;if(i=F(u.position),n=ei(u.orientation),this._gripMatrix.fromArray(u.matrix).premultiply(wa),this._gripMatrix.decompose(this._gripPosition,this._gripQuaternion,F(1,1,1)),"linearVelocity"in d&&d.linearVelocity){const p=d.linearVelocity;this._linearVelocity.set(p.x,p.y,p.z)}}}this.xr.context.mainCamera?.parent&&(this._object.parent!==this.xr.context.mainCamera?.parent&&this.xr.context.mainCamera.parent.add(this._object),this._gripSpaceObject!==void 0&&this._gripSpaceObject?.parent!==this.xr.context.mainCamera?.parent&&this.xr.context.mainCamera.parent.add(this._gripSpaceObject),this._raySpaceObject!==void 0&&this._raySpaceObject?.parent!==this.xr.context.mainCamera?.parent&&this.xr.context.mainCamera.parent.add(this._raySpaceObject));const a=this.hand;if(a){let d=!1;const u=a.get("wrist"),p=u&&this.getHandJointPose(u,e);if(p){d=!0;const _=p.transform.position,g=p.transform.orientation;this._object.position.set(_.x,_.y,_.z),this._object.quaternion.set(g.x,g.y,g.z,g.w).multiply(Di)}d||(this._object.position.copy(this._rayPosition),this._object.quaternion.copy(this._rayQuaternion).multiply(Di));const m=a.get("middle-finger-metacarpal"),y=m&&this.getHandJointPose(m,e);y&&(this._gripMatrix.fromArray(y.transform.matrix).premultiply(wa),this._gripMatrix.decompose(this._gripPosition,this._gripQuaternion,F(1,1,1)),i=F().copy(y.transform.position),n=ei().copy(y.transform.orientation),n.multiply(iP),i.add(F(nP).applyQuaternion(n)))}else this.inputSource.gripSpace&&this.targetRayMode==="transient-pointer"&&i&&n?(this._object.position.copy(i),this._object.quaternion.copy(n).multiply(Di)):o&&r&&(this._object.position.copy(o),this._object.quaternion.copy(r).multiply(Di));Jn&&(o&&r&&(this._raySpaceObject?.position.copy(o),this._raySpaceObject?.quaternion.copy(r).multiply(Di)),i&&n&&(this._gripSpaceObject?.position.copy(i),this._gripSpaceObject?.quaternion.copy(n).multiply(Di)));const l=this.xr.context.mainCamera?.parent,h=l?pe(l):void 0;i&&n&&(this._gripWorldPosition.copy(i),l&&this._gripWorldPosition.applyMatrix4(l.matrixWorld),this._gripWorldQuaternion.copy(n),this._gripWorldQuaternion.multiply(Di),h&&this._gripWorldQuaternion.premultiply(h)),this.updateRayWorldPosition(),this.updateRayWorldQuaternion()}onDisconnected(){this._connected=!1,Jn&&console.warn("Controller disconnected",this.index);for(const e of this._object.children)this.xr.context.scene.attach(e);this._object?.removeFromParent(),this._debugAxesHelper?.removeFromParent(),this._debugGripAxesHelper?.removeFromParent(),this._debugRayAxesHelper?.removeFromParent(),this._gripSpaceObject?.removeFromParent(),this._raySpaceObject?.removeFromParent(),this.unsubscribeEvents(),this._hitTestSource&&(this._hitTestSource.cancel(),this._hitTestSource=void 0)}getButton(e){if(!this._layout)return;switch(e){case"primary-button":if(this.isLeft)e="x-button";else if(this.isRight)e="a-button";else return;break;case"primary":return this.hand?this.getGesture("pinch"):this.toNeedleGamepadButton(0,e);case"xr-standard-trigger":if(this.inputSource.gamepad)return this.toNeedleGamepadButton(0,e);break;case"xr-standard-squeeze":if(this.inputSource.gamepad)return this.toNeedleGamepadButton(1,e);break;case"xr-standard-thumbstick":if(this.inputSource.gamepad)return this.toNeedleGamepadButton(3,e);break}if(this._buttonMap.has(e))return this.toNeedleGamepadButton(this._buttonMap.get(e),e);const t=this._layout?.components[e];if(t?.gamepadIndices)switch(t.type){case"button":case"squeeze":if(this.inputSource.gamepad){const i=t.gamepadIndices.button;return this._buttonMap.set(e,i),this.toNeedleGamepadButton(i,e)}break;default:console.warn("Unsupported component type",t.type);break}this._buttonMap.set(e,void 0)}getGesture(e){const t=this.states[e];if(!t)return null;this.states[e]=t;const i=this._needleGamepadButtons[e]||new z_(void 0,e);return i.pressed=t.pressed,i.value=t.value,i.isDown=t.isDown,i.isUp=t.isUp,this._needleGamepadButtons[e]=i,i}getPointerId(e){if((e==="primary"||e==="pinch")&&(e=0),typeof e!="number"){const t=this._buttonMap.get(e);if(t===void 0)return;e=t}return this.index*10+e}_needleGamepadButtons={};toNeedleGamepadButton(e,t){if(!this.inputSource.gamepad?.buttons)return;const i=this.inputSource.gamepad?.buttons[e],n=this.states[e],o=this._needleGamepadButtons[e]||new z_(e,t);return i&&(o.pressed=i.pressed,o.value=i.value,o.touched=i.touched),n&&(o.isDown=n.isDown,o.isUp=n.isUp),this._needleGamepadButtons[e]=o,o}getStick(e){if(!this._layout)return{x:0,y:0,z:0};if(this.isHand)return{x:0,y:0,z:0};e==="primary"&&this._layout.components["xr-standard-thumbstick"]&&(e="xr-standard-thumbstick");const t=this._layout?.components[e];if(t?.gamepadIndices)switch(t.type){case"thumbstick":case"touchpad":if(this.inputSource.gamepad){const i=t.gamepadIndices.xAxis,n=t.gamepadIndices.yAxis;let o=this.inputSource.gamepad.axes[i]||0,r=this.inputSource.gamepad.axes[n]||0;o*=-1,r*=-1;const a=t.gamepadIndices.button,l=this.inputSource.gamepad?.buttons[a]?.value||0;return{x:o,y:r,z:l}}}return{x:0,y:0,z:0}}_buttonMap=new Map;_motioncontroller;_layout;getMotionController;initialize(){if(this._hasSelectEvent=this.profiles.includes("generic-hand-select")||this.profiles.some(e=>e.startsWith("generic-trigger")),this._isMetaQuestTouchController=this.profiles.includes("meta-quest-touch-plus")||this.profiles.includes("oculus-touch-v3"),this._isMxInk=this.profiles.includes("logitech-mx-ink"),!this._layout){if(this.inputSource.targetRayMode==="transient-pointer")return;const e=le.fetchProfile(this.inputSource,eP,tP);this.getMotionController=e.then(t=>{if(!this.connected)return null;this._motioncontroller=new le.MotionController(this.inputSource,t.profile,t.assetPath||"");const n=t.profile.layouts[this.inputSource.handedness];if(this._layout=n,this._layout){if(!this._layout.gamepad?.length){this._layout.gamepad=[];for(const o in this._layout.components){const r=this._layout.components[o];this._layout.gamepad[r.gamepadIndices.button]=o}}this.profiles.length>=1&&this.profiles[0]==="htc-vive-focus-plus"&&this.inputSource.gamepad&&this.inputSource.gamepad.axes.length===4&&!this._layout.components["xr-standard-thumbstick"]&&(this._layout.components["xr-standard-thumbstick"]={type:"thumbstick",gamepadIndices:{xAxis:2,yAxis:3}})}return this._motioncontroller}).catch(t=>(this.inputSource&&console.warn("Couldn't initialize motion controller profile for ",this.inputSource,t),null))}}emitPointerDownEvent=!0;emitPointerUpEvent=!0;emitPointerMoveEvent=!0;pointerMoveDistanceThreshold=.03;pointerMoveAngleThreshold=.05;subscribeEvents(){this.xr.session.addEventListener("selectstart",this.onSelectStart),this.xr.session.addEventListener("selectend",this.onSelectEnd),this.xr.session.addEventListener("squeezestart",this.onSequeezeStart),this.xr.session.addEventListener("squeezeend",this.onSequeezeEnd)}unsubscribeEvents(){this.xr.session.removeEventListener("selectstart",this.onSelectStart),this.xr.session.removeEventListener("selectend",this.onSelectEnd),this.xr.session.removeEventListener("squeezestart",this.onSequeezeStart),this.xr.session.removeEventListener("squeezeend",this.onSequeezeEnd)}_selectButtonIndex=void 0;_squeezeButtonIndex=void 0;onSelectStart=e=>{if(!this.emitPointerDownEvent||this.inputSource!==e.inputSource)return;this.onUpdateFrame(e.frame),this._hasSelectEvent=!0;const t=this._layout?.selectComponentId,i=this._layout?.components[t]?.gamepadIndices?.button;i!==void 0&&(this._selectButtonIndex=i),!Gh&&(Jn&&B.DrawDirection(this.rayWorldPosition,F(0,.01,1).applyQuaternion(this.rayWorldQuaternion),16711680,10),this.emitPointerEvent(Pe.PointerDown,this._selectButtonIndex||0,"xr-standard-trigger",!0,e))};onSelectEnd=e=>{this.emitPointerUpEvent&&(Gh||this.inputSource===e.inputSource&&this.emitPointerEvent(Pe.PointerUp,this._selectButtonIndex||0,"xr-standard-trigger",!0,e))};onSequeezeStart=e=>{this.emitPointerDownEvent&&this.inputSource===e.inputSource&&(this._squeezeButtonIndex=this._layout?.components["xr-standard-squeeze"]?.gamepadIndices?.button,this._squeezeButtonIndex!==void 0&&(Jn&&B.DrawDirection(this.rayWorldPosition,F(0,.01,1).applyQuaternion(this.rayWorldQuaternion),255,10),this.emitPointerEvent(Pe.PointerDown,this._squeezeButtonIndex||0,"xr-standard-squeeze",!0,e)))};onSequeezeEnd=e=>{this.emitPointerUpEvent&&this.inputSource===e.inputSource&&this._squeezeButtonIndex!==void 0&&this.emitPointerEvent(Pe.PointerUp,this._squeezeButtonIndex||0,"xr-standard-squeeze",!0,e)};states={};updateInputEvents(){if(this.gamepad?.buttons){for(let e=0;e<this.gamepad.buttons.length;e++){const t=this.gamepad.buttons[e],i=this.states[e]||new U_;let n=null;this._isMxInk&&(e===4||e===5)?(t.value>0&&!i.pressed?(n="pointerdown",i.isDown=!0,i.isUp=!1):t.value===0&&i.pressed?(n="pointerup",i.isDown=!1,i.isUp=!0):i.pressed&&(n="pointermove",i.isDown=!1,i.isUp=!1),i.pressed=t.value>0,i.value=t.value):(t.pressed&&!i.pressed?(n="pointerdown",i.isDown=!0,i.isUp=!1):!t.pressed&&i.pressed?(n="pointerup",i.isDown=!1,i.isUp=!0):(i.isDown=!1,i.isUp=!1),i.pressed=t.pressed,i.value=t.value),this.states[e]=i;const o=e!==this._selectButtonIndex&&e!==this._squeezeButtonIndex;if(n!=null&&o){let r=this._layout?.gamepad[e];this._isMxInk&&e===4&&(r="stylus-touch"),this._isMxInk&&e===5&&(r="stylus-tip"),(Jn||Gh)&&console.log("Emitting pointer event",n,e,r,t.value,this.gamepad,this._layout),this.emitPointerEvent(n,e,r??"none",!1,null,t.value)}}if(this._isMetaQuestTouchController){const e=this.gamepad.buttons.length-1,t=this.states[e];if(t&&t.isDown){const i=this.context.menu;i.spatialMenuIsVisible?i.setSpatialMenuVisible(!1):this.context.menu.setSpatialMenuVisible(!0)}}}if(this.hand){const e=this.handObject;if(e){const t=e.joints["index-finger-tip"],i=e.joints["thumb-tip"];if(t&&i){const n=t.position.distanceTo(i.position);this._pinchPosition.lerpVectors(t.position,i.position,.5);const o=this.xr.context.mainCamera?.parent;if(o&&this._pinchPosition.applyMatrix4(o.matrixWorld),n!==0){const l=this.states.pinch||new U_,h=(.02+.01)*1.5;l.value=1-(n-.02)/h;const d=n<.02-.01,u=n>.02+.01;d&&!l.pressed?(Gh&&console.log("pinch start",n),l.isDown=!0,l.isUp=!1,l.pressed=!0):u&&l.pressed?(l.isDown=!1,l.isUp=!0,l.pressed=!1):(l.isDown=!1,l.isUp=!1),this.states.pinch=l}}}}}_didMoveLastFrame=!1;_lastPointerMovePosition=new c.Vector3;_lastPointerMoveQuaternion=new c.Quaternion;onUpdateMove(){if(!this.emitPointerMoveEvent)return;let e=!1;if(this._lastPointerMovePosition.distanceTo(this.gripWorldPosition)>this.pointerMoveDistanceThreshold*this.xr.rigScale&&(e=!0),e||this._lastPointerMoveQuaternion.angleTo(this.gripWorldQuaternion)>this.pointerMoveAngleThreshold&&(e=!0),e){this._didMoveLastFrame=!0,this._lastPointerMovePosition.copy(this.gripWorldPosition),this._lastPointerMoveQuaternion.copy(this.gripWorldQuaternion),Jn&&B.DrawLabel(this.rayWorldPosition.add(this.object.worldForward.multiplyScalar(.1)),"move",.01);let i=this.xr.context.input.getFirstPressedButtonForPointer(this.index);i===void 0&&(i=0);const n=this.gamepad?.buttons[i]?.value;this.emitPointerEvent("pointermove",i,"none",!1,null,n)}else this._didMoveLastFrame=!1}pointerInit;emitPointerEvent(e,t,i,n,o=null,r){if(!this.emitEvents){Jn&&e!==Pe.PointerMove&&console.warn("Pointer events are disabled for this controller",this.index,e,t);return}if(this.xr.mode==="immersive-vr"||this.xr.isPassThrough){this.pointerInit.origin=this,this.pointerInit.pointerId=this.getPointerId(t),this.pointerInit.pointerType=this.hand?"hand":"controller",this.pointerInit.button=t,this.pointerInit.buttonName=i,this.pointerInit.isPrimary=n,this.pointerInit.mode=this.inputSource.targetRayMode,this.pointerInit.ray=this.ray,this.pointerInit.device=this.object,this.pointerInit.pressure=r,this.pointerInit.clientX=this._rayPosition.x/this.xr.rigScale,this.pointerInit.clientY=this._rayPosition.y/this.xr.rigScale,this.pointerInit.clientZ=this._rayPosition.z/this.xr.rigScale;const a=U.Current;U.Current=this.xr.context,Jn&&e!=="pointermove"&&console.warn("Pointer event",e,t,i,{...this.pointerInit}),this.xr.context.input.createInputEvent(new ss(e,o,this.pointerInit)),U.Current=a}}}class U_{isDown=!1;isUp=!1;pressed=!1;value=0}class z_{index;name;touched=!1;pressed=!1;value=0;isDown=!1;isUp=!1;constructor(e,t){this.index=e,this.name=t}}const nc=x("debugwebxr");class Vf{controllerStates=[];userId;context;userStateEvtName;constructor(e,t){this.userId=e,this.context=t,this.userStateEvtName="xr-sync-user-state-"+e,this.context.connection.beginListen(this.userStateEvtName,this.onReceivedControllerState)}dispose(){this.context.connection.stopListen(this.userStateEvtName,this.onReceivedControllerState)}onReceivedControllerState=e=>{nc&&console.log(`XRSync: Received change for ${this.userId}: ${e.type} ${e.handedness}; tracked=${e.isTracking}`);let t=!1;for(let i=0;i<this.controllerStates.length;i++)if(this.controllerStates[i].index===e.index){this.controllerStates[i]=e,t=!0;break}t||this.controllerStates.push(e)};update(e){if(this.context.connection.isConnected!=!1){for(let t=this.controllerStates.length-1;t>=0;t--){const i=this.controllerStates[t];let n=!1;for(let o=0;o<e.controllers.length;o++)e.controllers[o].index===i.index&&(n=!0);n||(nc&&console.log(`XRSync: ${i.type} ${i.handedness} removed`,i.index),this.controllerStates.splice(t,1),this.sendControllerRemoved(i))}for(const t of e.controllers)this.updateControllerStates(t)}}onExitXR(e){for(const t of this.controllerStates)this.sendControllerRemoved(t);this.controllerStates.length=0}sendControllerRemoved(e){e.isTracking=!1,e.guid="",this.context.connection.send(this.userStateEvtName,e),this.context.connection.sendDeleteRemoteState(e.guid)}updateControllerStates(e){const t=this.controllerStates.find(i=>i.index===e.index);if(t){let i=!1;i||=t.isTracking!=e.isTracking,i&&(t.isTracking=e.isTracking,this.context.connection.send(this.userStateEvtName,t))}else{const i={guid:this.userId+"-"+e.index,isTracking:e.isTracking,handedness:e.side,index:e.index,type:e.hand?"hand":"controller"};this.controllerStates.push(i),this.context.connection.send(this.userStateEvtName,i),nc&&console.log(`XRSync: ${i.type} ${i.handedness} added`,i.index)}}}class U0{hasState(e){return e?this._states.has(e):!1}isTracking(e,t){if(!e)return;const i=this._states.get(e);return i?i.controllerStates.find(o=>o.handedness===t)?.isTracking||!1:void 0}getDeviceType(e,t){if(!e)return;const i=this._states.get(e);return i?i.controllerStates.find(o=>o.handedness===t)?.type||"unknown":void 0}context;constructor(e){this.context=e,this.context.connection.beginListen(K.JoinedRoom,this.onJoinedRoom),this.context.connection.beginListen(K.LeftRoom,this.onLeftRoom),this.context.connection.beginListen(K.UserJoinedRoom,this.onOtherUserJoinedRoom),this.context.connection.beginListen(K.UserLeftRoom,this.onOtherUserLeftRoom)}destroy(){this.context.connection.stopListen(K.JoinedRoom,this.onJoinedRoom),this.context.connection.stopListen(K.LeftRoom,this.onLeftRoom),this.context.connection.stopListen(K.UserJoinedRoom,this.onOtherUserJoinedRoom),this.context.connection.stopListen(K.UserLeftRoom,this.onOtherUserLeftRoom)}onJoinedRoom=()=>{if(this.context.connection.connectionId){this._states.has(this.context.connection.connectionId)||(nc&&console.log("XRSync: Local user joined room",this.context.connection.connectionId),this._states.set(this.context.connection.connectionId,new Vf(this.context.connection.connectionId,this.context)));for(const e of this.context.connection.usersInRoom())this._states.has(e)||this._states.set(e,new Vf(e,this.context))}};onLeftRoom=()=>{this.context.connection.connectionId&&(this._states.has(this.context.connection.connectionId)||(this._states.get(this.context.connection.connectionId)?.dispose(),this._states.delete(this.context.connection.connectionId)))};onOtherUserJoinedRoom=e=>{const t=e.userId;this._states.has(t)||(nc&&console.log("XRSync: Remote user joined room",t),this._states.set(t,new Vf(t,this.context)))};onOtherUserLeftRoom=e=>{const t=e.userId;this._states.has(t)||(this._states.get(t)?.dispose(),this._states.delete(t))};_states=new Map;onUpdate(e){this.context.connection.isConnected&&this.context.connection.connectionId&&this._states.get(this.context.connection.connectionId)?.update(e)}onExitXR(e){this.context.connection.isConnected&&this.context.connection.connectionId&&this._states.get(this.context.connection.connectionId)?.onExitXR(e)}}class N_{_fadeToColorQuad;_fadeToColorMaterial;constructor(){this._fadeToColorMaterial=new c.MeshBasicMaterial({color:0,transparent:!0,depthTest:!1,fog:!1,side:c.DoubleSide}),this._fadeToColorQuad=new c.Mesh(new c.PlaneGeometry(10,10),this._fadeToColorMaterial)}dispose(){this._fadeToColorQuad.geometry.dispose(),this._fadeToColorMaterial.dispose()}update(e,t){const i=this._fadeToColorQuad,n=this._fadeToColorMaterial;i.parent!==e&&n.opacity>0?e.add(i):n.opacity===0&&i.removeFromParent(),i.layers.set(2),i.material=this._fadeToColorMaterial,i.position.z=-1,i.renderOrder=1/0;const o=this._requestedFadeValue;n.opacity=I.lerp(n.opacity,o,t/.03),Math.abs(n.opacity-o)<=.01&&this._transitionResolve&&(this._transitionResolve(),this._transitionResolve=null,this._transitionPromise=null,this._requestedFadeValue=0)}remove(){this._fadeToColorQuad.removeFromParent()}fadeTransition(){if(this._transitionPromise)return this._transitionPromise;this._requestedFadeValue=1;const e=new Promise(t=>{this._transitionResolve=t});return this._transitionPromise=e,e}_requestedFadeValue=0;_transitionPromise=null;_transitionResolve=null}class Da{static _active=null;static get active(){return this._active}static _requestInFlight=!1;static async start(e,t){if(this._active)return console.error("Cannot start a new XR session while one is already active"),null;if(this._requestInFlight)return console.error("Cannot start a new XR session while a request is already in flight"),null;if("xr"in navigator&&navigator.xr){if(!t)return console.error("XRSessionInit must be provided"),null;this._requestInFlight=!0;const i=await navigator.xr.requestSession(e,t).catch(n=>{console.error("Failed to start temporary XR session:",n)});return i?(i.addEventListener("end",()=>{this._active=null}),this._requestInFlight?(this._requestInFlight=!1,this._active=new Da(e,t,i),this._active):(i.end(),null)):(this._requestInFlight=!1,null)}return null}static async handoff(){return this._active?this._active.handoff():null}static async stop(){this._requestInFlight=!1,this._active&&(await this._active.end(),await _s(100)),this._active=null}_session;_mode;_init;get isAR(){return this._mode==="immersive-ar"}get isVR(){return this._mode==="immersive-vr"}_renderer;_camera;_scene;constructor(e,t,i){this._mode=e,this._init=t,this._session=i,this._session.addEventListener("end",this.onEnd),this._renderer=new c.WebGLRenderer({alpha:!0,antialias:!0}),this._renderer.outputColorSpace="srgb",this._renderer.setPixelRatio(Math.min(2,window.devicePixelRatio)),this._renderer.setSize(window.innerWidth,window.innerHeight,!0),exports.DeviceUtilities.isNeedleAppClip()&&window.requestAnimationFrame(()=>{const n=Math.min(2,window.devicePixelRatio),o=Math.floor(window.innerWidth*n),r=Math.floor(window.innerHeight*n);this._renderer.domElement.width=o,this._renderer.domElement.height=r}),this._renderer.setAnimationLoop(this.onFrame),this._renderer.xr.setSession(i),this._renderer.xr.enabled=!0,this._camera=new c.PerspectiveCamera,this._scene=new c.Scene,this._scene.fog=new c.Fog(4473924,10,250),this._scene.add(this._camera),this.setupScene()}end(){return this._session?this._session.end():Promise.resolve()}async handoff(){if(!this._session)throw new Error("Cannot handoff a session that has already ended");const e={session:this._session,mode:this._mode,init:this._init};return await this.onBeforeHandoff(),this.onEnd(),this._session=null,e}onEnd=()=>{this._session?.removeEventListener("end",this.onEnd),this._renderer.setAnimationLoop(null),this._renderer.dispose(),this._scene.clear()};_lastTime=0;_frames=0;onFrame=(e,t)=>{const i=e-this._lastTime;this.update(e,i),this._camera.parent!==this._scene&&this._scene.add(this._camera),this._renderer.render(this._scene,this._camera),this._lastTime=e,this._frames++};_roomFlyObjects=[];_logoObject=null;get _logoDistance(){return this.isAR?.3:5}get _logoScale(){return this.isAR?.04:1}update(e,t){const i=e*4e-4;for(let r=0;r<this._roomFlyObjects.length;r++){const a=this._roomFlyObjects[r];a.position.y+=Math.sin(i+r*.5)*.005,a.rotateY(.002)}const n=this._logoObject,o=this._renderer.xr.getCamera();if(n){const r=new c.Vector3;o.getWorldDirection(r);const a=o.position.clone().addScaledVector(r,this._logoDistance),l=this.isAR?.005:1e-5;n.position.lerp(a,this._frames<=2?1:t*l),n.lookAt(this._camera.position)}}async onBeforeHandoff(){await _s(1e3),this._scene.clear()}setupScene(){this._scene.background=new c.Color(0);let e=La;if($n()){const d=document.querySelector("needle-engine");if(d){const u=d.getAttribute("logo-src");u?.length&&(e=u,A()&&console.debug("[XR] Using custom loading logo from license:",e))}}const t=this._logoObject=new c.Mesh(new c.PlaneGeometry(1,1,1,1),new c.MeshBasicMaterial({transparent:!0,side:2}));t.scale.multiplyScalar(this._logoScale*window.devicePixelRatio),t.renderOrder=1e3,t.material.opacity=0,this._scene.add(t);const i=document.createElement("canvas"),n=i.getContext("2d"),o=new Image,r=d=>{if(!n)return;t.material.opacity=1;const u=1024;i.width=u,i.height=u,n.imageSmoothingQuality="high";const p=u*.19,m=o.width/o.height;{const w=i.height-p*1.5,R=w*m,O=(i.width-R)/2;n.drawImage(o,O,0,R,w)}const y=u*.12,_="Loading...";n.shadowBlur=0,n.fillStyle=this.isAR?"white":"rgba(255,255,255,0.4)",n.font=`${y}px Arial`,n.shadowBlur=u*.02,n.shadowColor="rgba(0,0,0,0.5)",n.shadowOffsetX=0,n.shadowOffsetY=0;const g=n.measureText(_);n.fillText(_,i.width/2-g.width/2,i.height-p/4),n.font=`${y}px Arial`,n.fillText(_,i.width/2-g.width/2,i.height-p/4);const v=new c.TextureLoader().load(i.toDataURL());v.generateMipmaps=!0,v.colorSpace="srgb",v.anisotropy=4;const b=i.width/i.height;t.scale.x=this._logoScale*b*window.devicePixelRatio,t.scale.y=this._logoScale*window.devicePixelRatio,t.material.map=v,t.material.needsUpdate=!0};o.onload=()=>r(),o.onerror=d=>{console.error("Failed to load temporary XR logo:",e,d),o.src=La},o.crossOrigin="anonymous",o.src=e;const a=new c.DirectionalLight(16777215,1);a.position.set(0,20,0),a.castShadow=!1,this._scene.add(a);const l=new c.DirectionalLight(16777215,1);l.position.set(0,-1,0),l.castShadow=!1,this._scene.add(l);const h=new c.PointLight(16777215,1,100,1);if(h.position.set(0,2,0),h.castShadow=!1,h.distance=200,this._scene.add(h),this.isAR===!1)for(let u=0;u<100;u++){const p=new c.MeshStandardMaterial({color:2236962,metalness:1,roughness:.8}),m=Va.Sphere,y=_o.createPrimitive(m,{material:p});y.position.x=I.random(-50,50),y.position.y=I.random(-2,50),y.position.z=I.random(-50,50),y.rotation.x=I.random(0,Math.PI*2),y.rotation.y=I.random(0,Math.PI*2),y.rotation.z=I.random(0,Math.PI*2),y.scale.multiplyScalar(.5+Math.random()*10);const _=y.position.distanceTo(this._camera.position)-y.scale.x;_<10&&(y.position.z+=5,y.position.multiplyScalar(1+1/_)),this._roomFlyObjects.push(y),this._scene.add(y)}}}var xc;(s=>{const e=[];function t(){e?.length||A()&&console.warn("No USDZ exporters found – cannot export USDZ for QuickLook.");for(const o of e)o.exportAndOpen();return!0}s.exportAndOpen=t;function i(o){e.push(o)}s.registerExporter=i;function n(o){if(!e)return;const r=e.indexOf(o);r>=0&&e.splice(r,1)}s.unregisterExporter=n})(xc||(xc={}));const Ue=x("debugwebxr"),V_=x("stats");let $f=0;function sP(s){let e=null;const t=s;return t.getAROverlayContainer?e=t.getAROverlayContainer():e=s,e}oP();async function oP(){let s="immersive-vr";try{if(exports.DeviceUtilities.isNeedleAppClip()?s="immersive-ar":await navigator.xr?.isSessionSupported("immersive-vr")||(s="immersive-ar"),!await navigator.xr?.isSessionSupported("immersive-ar")&&s==="immersive-ar")return}catch(e){console.debug("[NeedleXRSession:granted] Error while checking XR support:",e);return}if(x("debugasap")){let e=globalThis["needle:XRSession"];if(e instanceof Promise){delete globalThis["needle:XRSession"],ce.addContextCreatedCallback(async t=>{if(!e)return;_a(!0);const i=await e;if(i){const n=q.getDefaultSessionInit(s);q.setSession(s,i,n,t.context)}else console.error("[NeedleXRSession:granted] ASAP session was rejected");e=void 0});return}}if("xr"in navigator){if(/WebXRViewer\//i.test(navigator.userAgent)){console.warn("WebXRViewer does not support addEventListener");return}navigator.xr?.addEventListener("sessiongranted",async()=>{const e=sessionStorage.getItem("needle_xr_session_mode"),t=sessionStorage.getItem("needle_xr_session_init")??null,i=t?JSON.parse(t):null;let n=null;if(z0()&&(await Da.start(e||s,i||q.getDefaultSessionInit(s)).catch(o=>console.warn("[NeedleXRSession:granted] TemporaryXRContext start failed:",o)),await lP(),n=await Da.handoff()),n)q.setSession(n.mode,n.session,n.init,U.Current);else if(e&&t){console.log("[NeedleXRSession:granted] Restore last session");const o=JSON.parse(t);q.start(e,o).catch(r=>console.warn(r))}else q.start(s).catch(o=>console.warn("[NeedleXRSession:granted] failed:",o))},{once:!0})}}function rP(s,e){sessionStorage.setItem("needle_xr_session_mode",s),sessionStorage.setItem("needle_xr_session_init",JSON.stringify(e))}function aP(){sessionStorage.removeItem("needle_xr_session_mode"),sessionStorage.removeItem("needle_xr_session_init")}const fg=new Set;ce.registerCallback(ae.ContextCreationStart,async s=>{fg.add(s.context)});ce.registerCallback(ae.ContextCreated,async s=>{fg.delete(s.context);const e=s.context?.domElement.getAttribute("autostart")||null;cP(e)});function z0(){return fg.size>0}function lP(){return new Promise(s=>{const e=Date.now(),t=setInterval(()=>{(!z0()||Date.now()-e>6e4)&&(clearInterval(t),s())},100)})}exports.DeviceUtilities.isDesktop()&&A()&&window.addEventListener("keydown",s=>{(s.key==="x"||s.key==="Escape")&&q.active&&q.stop()});function cP(s){s&&s?.toLowerCase()==="ar"&&fn.registerWaitForInteraction(()=>{q.start("ar")})}const Hh=Symbol("initial-fov"),Wf=Symbol("initial-near");class q{static _sync=null;static getXRSync(e){return this._sync||(this._sync=new U0(e)),this._sync}static get currentSessionRequest(){return this._currentSessionRequestMode}static _currentSessionRequestMode=null;static get active(){return this._activeSession}static get activeMode(){return this._activeSession?.mode??null}static get xrSystem(){return"xr"in navigator?navigator.xr:void 0}static isXRSupported(){return Promise.all([this.isVRSupported(),this.isARSupported()]).then(e=>e.some(t=>t)).catch(()=>!1)}static isVRSupported(){return this.isSessionSupported("immersive-vr")}static isARSupported(){return this.isSessionSupported("immersive-ar")}static isSessionSupported(e){return this.xrSystem?.isSessionSupported(e).catch(t=>(Ue&&console.error(t),!1))??Promise.resolve(!1)}static _currentSessionRequest;static _activeSession;static onSessionRequestStart(e){this._sessionRequestStartListeners.push(e)}static offSessionRequestStart(e){const t=this._sessionRequestStartListeners.indexOf(e);t>=0&&this._sessionRequestStartListeners.splice(t,1)}static _sessionRequestStartListeners=[];static onSessionRequestEnd(e){this._sessionRequestEndListeners.push(e)}static offSessionRequestEnd(e){const t=this._sessionRequestEndListeners.indexOf(e);t>=0&&this._sessionRequestEndListeners.splice(t,1)}static _sessionRequestEndListeners=[];static onXRSessionStart(e){this._xrStartListeners.push(e)}static offXRSessionStart(e){const t=this._xrStartListeners.indexOf(e);t>=0&&this._xrStartListeners.splice(t,1)}static _xrStartListeners=[];static onXRSessionEnd(e){this._xrEndListeners.push(e)}static offXRSessionEnd(e){const t=this._xrEndListeners.indexOf(e);t>=0&&this._xrEndListeners.splice(t,1)}static _xrEndListeners=[];static onControllerAdded(e){this._controllerAddedListeners.push(e)}static offControllerAdded(e){const t=this._controllerAddedListeners.indexOf(e);t>=0&&this._controllerAddedListeners.splice(t,1)}static _controllerAddedListeners=[];static onControllerRemoved(e){this._controllerRemovedListeners.push(e)}static offControllerRemoved(e){const t=this._controllerRemovedListeners.indexOf(e);t>=0&&this._controllerRemovedListeners.splice(t,1)}static _controllerRemovedListeners=[];static offerSession(e,t,i){return"xr"in navigator&&navigator.xr&&"offerSession"in navigator.xr?(typeof navigator.xr.offerSession=="function"&&(console.log("WebXR offerSession is available - requesting mode: "+e),t=="default"&&(t=this.getDefaultSessionInit(e)),navigator.xr.offerSession(e,{...t}).then(n=>q.setSession(e,n,t,i)).catch(n=>{console.log("XRSession offer rejected (perhaps because another call to offerSession was made or a call to requestSession was made)")})),!0):!1}static getDefaultSessionInit(e){switch(e){case"immersive-ar":const t=["anchors","local-floor","layers","dom-overlay","hit-test","unbounded"];return exports.DeviceUtilities.isVisionOS()||t.push("hand-tracking"),{optionalFeatures:t};case"immersive-vr":const i=["local-floor","bounded-floor","high-fixed-foveation-level","layers"];return exports.DeviceUtilities.isVisionOS()||i.push("hand-tracking"),{optionalFeatures:i};default:return console.warn("No default session init for mode",e),{}}}static async start(e,t,i){if(t||(t={}),exports.DeviceUtilities.isiOS()){const a=await this.isARSupported().catch(()=>!1);if(exports.DeviceUtilities.isVisionOS()&&!a&&(e==="ar"||e==="immersive-ar")&&(e="quicklook"),e==="quicklook")return ni.sendEvent(U.Current,"xr",{action:"quicklook_export",source:"NeedleXRSession.start"}),xc.exportAndOpen(),null;if(!a&&(e==="immersive-ar"||e==="ar")){this.invokeSessionRequestStart("immersive-ar",t);const l=new URL("https://appclip.apple.com/id?p=tools.needle.launch-app.Clip");l.searchParams.set("url",location.href);const h=l.toString();ni.sendEvent(U.Current,"xr",{action:"app_clip_launch",source:"NeedleXRSession.start",url:h});const d=window.top||window;try{console.debug("iOS device detected - opening Needle App Clip for AR experience",{mode:e,init:t,url:l}),d.location.href=h}catch(u){console.warn("Error navigating to AppClip "+h+`
878
878
  `,u),window!==window.top?window.open(h,"_blank"):window.location.href=h}return setTimeout(()=>{this.invokeSessionRequestEnd("immersive-ar",t||{},null)},3e3),null}}if(e==="quicklook")return console.warn("QuickLook mode is only supported on iOS devices"),null;if(e=="ar"&&(e="immersive-ar"),A()&&x("debugxrpreroom"))return console.warn("Debug: Starting temporary XR session"),await Da.start(e,t||q.getDefaultSessionInit(e)),null;if(this._currentSessionRequest)return console.warn("A XRSession is already being requested"),(Ue||A())&&fe("A XRSession is already being requested"),this._currentSessionRequest.then(()=>this._activeSession);if(this._activeSession)return console.error("A XRSession is already running"),this._activeSession;if(i||(i=U.Current),i||(i=ce.All[0]),!i)throw new Error("No Needle Engine Context found");switch(e){case"immersive-ar":{if(await this.xrSystem?.isSessionSupported("immersive-ar")!==!0)return console.error(e+" is not supported by this browser."),null;const l=this.getDefaultSessionInit(e),h=sP(i.domElement);h&&!exports.DeviceUtilities.isQuest()&&(l.domOverlay={root:h},l.optionalFeatures.push("dom-overlay")),t={...l,...t}}break;case"immersive-vr":{if(await this.xrSystem?.isSessionSupported("immersive-vr")!==!0)return console.error(e+" is not supported by this browser."),null;t={...this.getDefaultSessionInit(e),...t}}break;default:console.warn("No default session init for mode",e);break}t.optionalFeatures??=[],t.requiredFeatures??=[],await Da.stop();const n=e=="immersive-ar"?i.scripts_immersive_ar:i.scripts_immersive_vr;Ue?console.log(`%cRequesting ${e} session`,"font-weight:bold;",t,n):console.log(`%cRequesting ${e} session`,"font-weight:bold;");for(const a of n)a.onBeforeXR&&a.activeAndEnabled&&!a.destroyed&&a.onBeforeXR(e,t);this.invokeSessionRequestStart(e,t),Ue&&Se("Requesting "+e+" session ("+Date.now()+")"),ni.sendEvent(U.Current,"xr",{action:"session_request",mode:e,features:(t.requiredFeatures??[]).concat(t.optionalFeatures??[]).join(","),source:"NeedleXRSession.start"}),this._currentSessionRequest=navigator?.xr?.requestSession(e,t),this._currentSessionRequestMode=e;const o=await this._currentSessionRequest?.catch(a=>{console.error(a,"Code: "+a?.code),a?.code===9&&fe("Couldn't start XR session. Make sure you allow the required permissions."),console.log("If the specified XR configuration is not supported (e.g. entering AR doesnt work) - make sure you access the website on a secure connection (HTTPS) and your device has the required permissions (e.g. camera access)"),location.protocol==="http:"&&fe("XR requires a secure connection (HTTPS)")});return this._currentSessionRequest=void 0,this._currentSessionRequestMode=null,this.invokeSessionRequestEnd(e,t,o),o?this.setSession(e,o,t,i):(console.warn("XR Session request was rejected"),null)}static invokeSessionRequestStart(e,t){for(const i of this._sessionRequestStartListeners)i({mode:e,init:t})}static invokeSessionRequestEnd(e,t,i){for(const n of this._sessionRequestEndListeners)n({mode:e,init:t,newSession:i||null})}static setSession(e,t,i,n){if(this._activeSession)return console.error("A XRSession is already running"),this._activeSession;const o=e=="immersive-ar"?n.scripts_immersive_ar:n.scripts_immersive_vr;return this._activeSession=new q(e,t,n,{scripts:o,controller_added:this._controllerAddedListeners,controller_removed:this._controllerRemovedListeners,init:i}),t.addEventListener("end",this.onEnd),Ue?console.log(`%cStarted ${e} session`,"font-weight:bold;",o):console.log(`%cStarted ${e} session`,"font-weight:bold;"),this._activeSession}static $_stop_request=Symbol();static stop(){const e=this._activeSession;e&&(e[this.$_stop_request]===void 0?(Ue&&console.log("[NeedleXRSession] Stopping XR Session... (new)"),e[this.$_stop_request]=setTimeout(()=>{e.end()})):Ue&&console.warn("[NeedleXRSession] XR Session stop already requested"))}static onEnd=()=>{Ue&&console.log("XR Session ended"),this._activeSession=null};context;get sync(){return q._sync}get running(){return!this._ended&&this.session!=null}session;mode;get interactionMode(){return this.session.interactionMode}get visibilityState(){return this.session.visibilityState}get isVisibleBlurred(){return this.session.visibilityState==="visible-blurred"}get isSystemKeyboardSupported(){return this.session.isSystemKeyboardSupported}get environmentBlendMode(){return this.session.environmentBlendMode}get frame(){return this.context.xrFrame}controllers=[];get leftController(){return this.controllers.find(e=>e.side==="left")}get rightController(){return this.controllers.find(e=>e.side==="right")}getController(e){return typeof e=="number"?this.controllers[e]||null:this.controllers.find(t=>t.side===e)||null}get isPassThrough(){return!!(this.environmentBlendMode!=="opaque"&&this.interactionMode==="world-space"||this.mode==="immersive-ar"&&this.environmentBlendMode!=="opaque"&&this.controllers.some(e=>e.inputSource.targetRayMode==="tracked-pointer")||A()&&exports.DeviceUtilities.isDesktop()&&this.mode==="immersive-ar")}get isAR(){return this.mode==="immersive-ar"}get isVR(){return this.mode==="immersive-vr"}get isScreenBasedAR(){return this.isAR&&!this.isPassThrough}get posePosition(){return this._transformPosition}get poseOrientation(){return this._transformOrientation}get referenceSpace(){return this.context.renderer.xr.getReferenceSpace()}get viewerPose(){return this._viewerPose}get isTrackingImages(){if(this.frame&&"getImageTrackingResults"in this.frame&&typeof this.frame.getImageTrackingResults=="function")try{const e=this.frame.getImageTrackingResults();for(const t of e)if(t.trackingState==="tracked")return!0}catch{return!1}return!1}get rig(){const e=this._rigs[0]??null;return e?.gameObject&&dr(e.gameObject)||e?.isActive===!1?(this.updateActiveXRRig(),this._rigs[0]??null):e}_rigScale=1;_lastRigScaleUpdate=-1;get rigScale(){return this._rigs[0]?(this._lastRigScaleUpdate!==this.context.time.frame&&(this._lastRigScaleUpdate=this.context.time.frame,this._rigScale=this._rigs[0].gameObject.worldScale.x),this._rigScale):1}addRig(e){this._rigs.indexOf(e)>=0||(e.priority===void 0&&(e.priority=0),this._rigs.push(e),this.updateActiveXRRig())}removeRig(e){const t=this._rigs.indexOf(e);t!==-1&&(this._rigs.splice(t,1),this.updateActiveXRRig())}setRigActive(e){const t=this._rigs.indexOf(e),i=this._rigs[0];this._rigs.splice(t,1),this._rigs.unshift(e),e.priority=i?.priority??0,this.updateActiveXRRig()}getUserOffsetInRig(){const e=this.context.mainCamera?.position;if(!e||!this.rig)return F(0,0,0);const t=F(e);return t.x*=-1,t.z*=-1,t.applyQuaternion(ei(this.rig.gameObject.quaternion)),t}updateActiveXRRig(){const e=this._rigs[0]??null;this._defaultRig.gameObject.parent!==this.context.scene&&this.context.scene.add(this._defaultRig.gameObject),this._defaultRig.gameObject.visible=!0,this._rigs.includes(this._defaultRig)||this._rigs.push(this._defaultRig);let t=this._rigs[0];t&&t.priority===void 0&&(t.priority=0);for(let i=1;i<this._rigs.length;i++){const n=this._rigs[i];if(n.isActive){if(dr(n.gameObject)){this._rigs.splice(i,1),i--;continue}(!t||t.isActive===!1||n.priority!==void 0&&n.priority>t.priority)&&(t=n)}}if(e!==t){const i=this._rigs.indexOf(t);i>=0&&this._rigs.splice(i,1),this._rigs.unshift(t)}Ue&&(e===t?console.log("Updated Active XR Rig:",t,"prev:",e):console.log("Updated Active XRRig:",t," (the same as before)"))}_rigs=[];_viewerHitTestSource=null;getHitTest(e){if(e)return this.getControllerHitTest(e);if(!this._viewerHitTestSource)return null;const t=this._viewerHitTestSource,i=this.frame.getHitTestResults(t);if(i.length>0){const n=i[0];return this.convertHitTestResult(n)}return null}getControllerHitTest(e){const t=e.getHitTestSource();if(!t)return null;const i=this.frame.getHitTestResultsForTransientInput(t);for(const n of i)if(n.inputSource===e.inputSource)for(const o of n.results)return this.convertHitTestResult(o);return null}convertHitTestResult(e){const t=this.context.renderer.xr.getReferenceSpace(),i=t&&e.getPose(t);if(i){const n=F(i.transform.position),o=ei(i.transform.orientation),r=this.context.mainCamera;if(r?.parent!==this._cameraRenderParent&&n.applyMatrix4(wa),r?.parent){n.applyMatrix4(r.parent.matrixWorld),o.multiply(Di);const a=pe(r.parent);a.premultiply(Di),o.premultiply(a)}return{hit:e,position:n,quaternion:o}}return null}convertSpace(e){const t=F(e.position);t.applyMatrix4(wa);const i=ei(e.orientation);return i.premultiply(Di),{position:t,quaternion:i}}_defaultRig;_xr_scripts;_xr_update_scripts=[];_inactive_scripts=[];_controllerAdded;_controllerRemoved;_originalCameraWorldPosition;_originalCameraWorldRotation;_originalCameraWorldScale;_originalCameraParent;_mainCamera=null;constructor(e,t,i,n){rP(e,n.init),this.session=t,this.mode=e,this.context=i,(Ue||x("console"))&&_a(!0),this._xr_scripts=[...n.scripts],this._xr_update_scripts=this._xr_scripts.filter(o=>typeof o.onUpdateXR=="function"),this._controllerAdded=n.controller_added,this._controllerRemoved=n.controller_removed,xs(this.onBefore,ge.LateUpdate),this.context.pre_render_callbacks.push(this.onBeforeRender),this.context.post_render_callbacks.push(this.onAfterRender),(n.init.optionalFeatures?.includes("hit-test")||n.init.requiredFeatures?.includes("hit-test"))&&t.requestReferenceSpace("viewer").then(o=>t.requestHitTestSource?.call(t,{space:o})?.then(r=>this._viewerHitTestSource=r).catch(r=>console.error(r))).catch(o=>console.error(o)),this.context.mainCamera&&(this._originalCameraWorldPosition=Y(this.context.mainCamera,new c.Vector3),this._originalCameraWorldRotation=pe(this.context.mainCamera,new c.Quaternion),this._originalCameraWorldScale=je(this.context.mainCamera,new c.Vector3),this._originalCameraParent=this.context.mainCamera.parent,this.context.mainCamera instanceof c.PerspectiveCamera&&(this.context.mainCamera[Hh]=this.context.mainCamera.fov)),this._defaultRig=new J1,this.context.scene.add(this._defaultRig.gameObject),this.addRig(this._defaultRig);for(let o=0;o<t.inputSources.length;o++){const r=t.inputSources[o];if(!r.handedness){console.warn("Input source in xr session has no handedness - ignoring",o);continue}this.onInputSourceAdded(r)}this.session.addEventListener("end",this.onEnd),this.session.addEventListener("inputsourceschange",o=>{for(const r of o.removed)this.disconnectInputSource(r);for(const r of o.added)this.onInputSourceAdded(r)}),this.context.xr=this,this.context.renderer.xr.setSession(this.session).then(this.onRendererSessionSet),"controllerAutoUpdate"in this.context.renderer.xr?(console.debug("Disabling three.js controllerAutoUpdate"),this.context.renderer.xr.controllerAutoUpdate=!1):Ue&&console.warn("controllerAutoUpdate is not available in three.js - cannot disable it"),exports.DeviceUtilities.isNeedleAppClip()&&window.requestAnimationFrame(()=>{const o=this.context.renderer.domElement,r=window.devicePixelRatio||1,a=o.width,l=o.height,h=Math.floor(window.innerWidth*r),d=Math.floor(window.innerHeight*r);(Math.abs(a-h)>2||Math.abs(l-d)>2)&&(o.width=h,o.height=d,console.debug("Applied DPR scaling for Needle AppClip XR session",r,o.width,o.height))})}onRendererSessionSet=()=>{this.running&&(this.context.renderer.xr.enabled=!0,this.context.renderer.xr.updateCamera(this.context.mainCamera),this.context.mainCameraComponent?.applyClearFlags())};onInputSourceAdded=e=>{if(e.targetRayMode==="screen")return;let t=0;for(let n=0;n<this.session.inputSources.length;n++)if(this.session.inputSources[n]===e){t=n;break}if(this.controllers.find(n=>n.inputSource===e)){console.debug("Controller already exists for input source",t);return}else if(this._newControllers.find(n=>n.inputSource===e)){console.debug("Controller already registered for input source",t);return}const i=new ug(this,e,t);this._newControllers.push(i)};disconnectInputSource(e){const t=(o,r)=>{if(o.inputSource===e){Ue&&console.log("Disconnecting controller",o.index);const a=r.indexOf(o);a>=0&&r.splice(a,1),this.invokeControllerEvent(o,this._controllerRemoved,"removed");const l={xr:this,controller:o,change:"removed"};for(const h of this._xr_scripts)h.onXRControllerRemoved&&h.onXRControllerRemoved(l);o.onDisconnected()}},i=[...this.controllers];for(let o=i.length-1;o>=0;o--){const r=i[o];t(r,this.controllers)}const n=[...this._newControllers];for(let o=n.length-1;o>=0;o--){const r=n[o];t(r,this._newControllers)}}end(){this._ended||this.session.end().catch(e=>console.warn(e))}_ended=!1;_newControllers=[];onEnd=e=>{if(this._ended)return;this._ended=!0,console.debug("XR Session ended"),ni.sendEvent(U.Current,"xr",{action:"session_end",mode:this.mode,source:"NeedleXRSession.onEnd"}),aP(),this.onAfterRender(),this.revertCustomForward(),this._didStart=!1,this._previousCameraParent=null,this.requestedCameraNearPlane=null,yo(this.onBefore,ge.LateUpdate);const t=this.context.pre_render_callbacks.indexOf(this.onBeforeRender);t>=0&&this.context.pre_render_callbacks.splice(t,1);const i=this.context.post_render_callbacks.indexOf(this.onAfterRender);i>=0&&this.context.post_render_callbacks.splice(i,1),this.context.xr=null,this.context.renderer.xr.enabled=!1,this.context.pre_update_oneshot_callbacks.push(()=>{this.context.mainCameraComponent?.applyClearFlags(),this.context.mainCameraComponent?.applyClippingPlane()}),D0({session:this});for(const o of q._xrEndListeners)o({xr:this});const n=[...this.controllers];for(let o=0;o<n.length;o++)this.disconnectInputSource(n[o].inputSource);this.controllers.length=0,this._newControllers.length=0;for(const o of this._xr_scripts)o?.onLeaveXR?.({xr:this});this.sync?.onExitXR(this),this.context.mainCamera&&(this._originalCameraParent?.add(this.context.mainCamera),this._originalCameraWorldPosition&&at(this.context.mainCamera,this._originalCameraWorldPosition),this._originalCameraWorldRotation&&dn(this.context.mainCamera,this._originalCameraWorldRotation),this._originalCameraWorldScale&&Ma(this.context.mainCamera,this._originalCameraWorldScale),this.context.mainCamera instanceof c.PerspectiveCamera&&(this.context.mainCamera[Hh]&&(this.context.mainCamera.fov=this.context.mainCamera[Hh],this.context.mainCamera[Hh]=0),this.context.mainCamera[Wf]&&(this.context.mainCamera.near=this.context.mainCamera[Wf],this.context.mainCamera[Wf]=0))),this.context.requestSizeUpdate(),this._defaultRig.gameObject.removeFromParent(),_a(!1)};_didStart=!1;onBefore=e=>{const t=e.xrFrame;if(!t)return;this.context.xr=this,this.context.mainCameraComponent&&this.context.mainCameraComponent!==this._mainCamera&&(this._mainCamera=this.context.mainCameraComponent),this.rig?.isActive==!1&&(Ue&&console.warn("Latest rig is not active - trying to activate a different rig",this.rig),this.updateActiveXRRig()),this.rig&&this._mainCamera?.gameObject&&this._mainCamera?.gameObject?.parent!==this.rig.gameObject&&this.rig.gameObject.add(this._mainCamera?.gameObject),this.internalUpdateState(),this.applyCustomForward();const i={xr:this};if(this._didStart){if(this.context.new_scripts_xr.length>0){const n=[...this.context.new_scripts_xr];for(let o=0;o<n.length;o++){const r=this.context.new_scripts_xr[o];if(!r||r.destroyed||r.supportsXR?.(this.mode)==!1){this.context.new_scripts_xr.splice(o,1);continue}if(!r.activeAndEnabled){this.context.new_scripts_xr.splice(o,1),this.markInactive(r);continue}if(this.addScript(r)){this.invokeCallback_EnterXR(r);for(const a of this.controllers)this.invokeCallback_ControllerAdded(r,a)}}}}else{if(this._didStart=!0,this.mode==="immersive-vr"){const o=ri(this.context.scene.children);if(o){const r=o.getSize(F());if(r.length()>0){const a=this._defaultRig.gameObject;a.position.set(o.min.x+r.x*.5,o.min.y,o.max.z+r.z*.5+1.5);const l=o.getCenter(F());l.y=a.position.y,a.lookAt(l)}}}L0({session:this}),_r();for(const o of q._xrStartListeners)o(i);const n=[...this._xr_scripts];Ue&&console.log("NeedleXRSession start, handle scripts:",n);for(const o of n){if(o.destroyed){this._script_to_remove.push(o);continue}if(!o.activeAndEnabled){this.markInactive(o);continue}this.invokeCallback_EnterXR(o);for(const r of this.controllers)this.invokeCallback_ControllerAdded(o,r)}}this.syncCameraCullingMask();for(const n of this.controllers)n.onUpdate(t);if(this._newControllers.length>0){const n=[...this._newControllers];this._newControllers.length=0;for(const o of n){if(!o.connected){console.warn("New controller is not connected",o);continue}this.controllers.push(o);for(const r of this._xr_scripts){if(r.destroyed){this._script_to_remove.push(r);continue}r.activeAndEnabled!==!1&&this.invokeCallback_ControllerAdded(r,o)}}this.controllers.sort((o,r)=>o.index-r.index)}Ue&&this.context.time.frame%30===0&&this.controllers.length<=0&&this.session.inputSources.length>0&&(_a(!0),console.error("XRControllers are not added but inputSources are present"));for(const n of this._xr_update_scripts){if(n.destroyed===!0){this._script_to_remove.push(n);continue}if(n.activeAndEnabled===!1){this.markInactive(n);continue}n.onUpdateXR&&n.onUpdateXR(i)}if(this.handleInactiveScripts(),this._script_to_remove.length>0){const n=[...new Set(this._script_to_remove)];this._script_to_remove.length=0;for(const o of n)!o.destroyed&&this.running&&o.onLeaveXR?.(i),this.removeScript(o)}this.sync?.onUpdate(this),this.onRenderDebug()};onRenderDebug(){if(Ue)for(const e of this.controllers)e.onRenderDebug();if((Ue||V_)&&this.rig&&($f++,$f>=20)){const e=this.rig.gameObject.worldPosition,t=this.rig.gameObject.worldForward;e.add(t.multiplyScalar(1.5));const i=this.rig.gameObject.worldUp;e.add(i.multiplyScalar(2.5));let n="";if(n+=`${this.context.time.smoothedFps.toFixed(0)} FPS`,n+=`, calls: ${this.context.renderer.info.render.calls}, tris: ${this.context.renderer.info.render.triangles.toLocaleString()}`,Ue||V_)for(const o of this.controllers)n+=`
879
- ${o.hand?"hand":"ctrl"} ${o.inputSource.handedness}[${o.index}] con:${o.connected} tr:${o.isTracking} hts:${o.hasHitTestSource?"yes":"no"}`;$f=0,B.DrawLabel(e,n,void 0,1/60*20)}}onBeforeRender=()=>{this.context.mainCamera&&(this.updateFade(this.context.mainCamera),this.requestedCameraNearPlane!==null&&this.context.mainCamera instanceof c.PerspectiveCamera&&(this.context.mainCamera.near=this.requestedCameraNearPlane,this.requestedCameraNearPlane=null))};onAfterRender=()=>{if(this.onUpdateFade_PostRender(),exports.DeviceUtilities.isDesktop()||!this._renderOnceOnDevice){const e=this.context.renderer;if(e.xr.isPresenting&&this.context.mainCamera){this._renderOnceOnDevice=!0;const t=e.xr.enabled,i=e.getRenderTarget(),n=this.context.scene.background;e.xr.enabled=!1,e.setRenderTarget(null),this.isPassThrough&&(this.context.scene.background=null),this.context.composer?this.context.composer.render(this.context.time.deltaTime):e.render(this.context.scene,this.context.mainCamera),e.xr.enabled=t,e.setRenderTarget(i),this.context.scene.background=n}}};addScript(e){return this._xr_scripts.includes(e)?!1:(Ue&&console.log("Register new XRScript",e),this._xr_scripts.push(e),typeof e.onUpdateXR=="function"&&this._xr_update_scripts.push(e),!0)}markInactive(e){if(!(this._inactive_scripts.indexOf(e)>=0)){this.removeScript(e,!1),this._inactive_scripts.push(e);for(const t of this.controllers)this.invokeCallback_ControllerRemoved(e,t);this.invokeCallback_LeaveXR(e)}}handleInactiveScripts(){if(this._inactive_scripts.length>0)for(let e=this._inactive_scripts.length-1;e>=0;e--){const t=this._inactive_scripts[e];if(t.activeAndEnabled){this._inactive_scripts.splice(e,1),this.addScript(t),this.invokeCallback_EnterXR(t);for(const i of this.controllers)this.invokeCallback_ControllerAdded(t,i)}}}_script_to_remove=[];removeScript(e,t=!0){Ue&&console.log("Remove XRScript",e);const i=this._xr_scripts.indexOf(e);i>=0&&this._xr_scripts.splice(i,1);const n=this._xr_update_scripts.indexOf(e);if(n>=0&&this._xr_update_scripts.splice(n,1),t){const o=this._inactive_scripts.indexOf(e);o>=0&&this._inactive_scripts.splice(o,1)}}invokeCallback_EnterXR(e){e.onEnterXR&&e.onEnterXR({xr:this})}invokeCallback_ControllerAdded(e,t){e.onXRControllerAdded&&e.onXRControllerAdded({xr:this,controller:t,change:"added"})}invokeCallback_ControllerRemoved(e,t){e.onXRControllerRemoved&&e.onXRControllerRemoved({xr:this,controller:t,change:"removed"})}invokeCallback_LeaveXR(e){e.onLeaveXR&&!e.destroyed&&e.onLeaveXR({xr:this})}syncCameraCullingMask(){const e=this.context.xrCamera,t=this.context.mainCameraComponent?.cullingMask;if(e&&t!==void 0){for(const i of e.cameras)i.layers.mask=t;e.layers.mask=t}else if(e){for(const i of e.cameras)i.layers.enableAll();e.layers.enableAll()}}invokeControllerEvent(e,t,i){for(let n=t.length-1;n>=0;n--){const o=t[n];if(o)try{o({xr:this,controller:e,change:i})}catch(r){console.error(r)}}}_camera;_cameraRenderParent=new c.Object3D().rotateY(Math.PI);_previousCameraParent;_customforward=!0;originalCameraNearPlane;requestedCameraNearPlane=null;applyCustomForward(){if(this.context.mainCamera&&this._customforward){this._camera=this.context.mainCamera,this._camera.parent!==this._cameraRenderParent&&(this._previousCameraParent=this._camera.parent,this._previousCameraParent?.add(this._cameraRenderParent)),this._cameraRenderParent.name="XR Camera Render Parent",this._cameraRenderParent.add(this._camera);{let e=.02;const t=.001;if(this.rig){const i=je(this.rig.gameObject);e*=i.x}this._camera instanceof c.PerspectiveCamera&&Math.abs(this._camera.near-e)>t&&(this.isAR?this.originalCameraNearPlane=this._camera.near:this._camera.near=e,Ue&&console.debug(`Setting camera near plane to ${e} (was ${this.originalCameraNearPlane}) to account for XR rendering scale`))}}}revertCustomForward(){this._camera&&this._previousCameraParent&&this._previousCameraParent.add(this._camera),this._previousCameraParent=null,this._camera instanceof c.PerspectiveCamera&&this.originalCameraNearPlane!=null&&(this._camera.near=this.originalCameraNearPlane,this.originalCameraNearPlane=void 0)}_viewerPose;_transformOrientation=new c.Quaternion;_transformPosition=new c.Vector3;internalUpdateState(){const e=this.context.renderer.xr.getReferenceSpace();if(!e){this._viewerPose=void 0;return}if(this._viewerPose=this.frame.getViewerPose(e),this._viewerPose){const t=this._viewerPose.transform;this._transformPosition.set(t.position.x,t.position.y,t.position.z),this._transformOrientation.set(t.orientation.x,t.orientation.y,t.orientation.z,t.orientation.w)}}_transition;get transition(){return this._transition||(this._transition=new N_),this._transition}fadeTransition(){return this._transition||(this._transition=new N_),this._transition.fadeTransition()}updateFade(e){this._transition&&e instanceof c.PerspectiveCamera&&this._transition.update(e,this.context.time.deltaTime)}onUpdateFade_PostRender(){this._transition?.remove()}}const Gf=x("debugwebxr");class N0{static tryFindAvatarObjects(e,t,i){if(i.head&&i.leftHand&&i.rightHand)return;const n=e.name.toLocaleLowerCase();!i.head&&n.includes("head")&&(Gf&&console.log("FOUND AVATAR HEAD",e.name),i.head=new Z("",t,e)),n.includes("hand")&&(!i.leftHand&&n.includes("left")&&(Gf&&console.log("FOUND AVATAR LEFT HAND",e.name),i.leftHand=new Z("",t,e)),!i.rightHand&&n.includes("right")&&(Gf&&console.log("FOUND AVATAR RIGHT HAND",e.name),i.rightHand=new Z("",t,e)));for(let o=0;o<e.children.length;o++){if(i.head&&i.leftHand&&i.rightHand)return;const r=e.children[o];this.tryFindAvatarObjects(r,t,i)}}}class te extends c.Color{alpha=1;get isRGBAColor(){return!0}set a(e){this.alpha=e}get a(){return this.alpha}constructor(e,t,i,n){super(),typeof e=="number"&&typeof t=="number"&&typeof i=="number"?(this.set(e,t,i),this.alpha=typeof n=="number"?n:1):e!==void 0&&(this.set(e),this.alpha=1)}clone(){const e=super.clone();return e.alpha=this.alpha,e}copy(e){return this.r=e.r,this.g=e.g,this.b=e.b,"alpha"in e&&typeof e.alpha=="number"?this.alpha=e.alpha:typeof e.a=="number"&&(this.alpha=e.a),this}lerp(e,t){const i=e;return i.alpha!=null&&(this.alpha=I.lerp(this.alpha,i.alpha,t)),super.lerp(e,t)}lerpColors(e,t,i){const n=e,o=t;return n.alpha!=null&&o.alpha!=null&&(this.alpha=I.lerp(n.alpha,o.alpha,i)),super.lerpColors(e,t,i)}multiply(e){const t=e;return t.alpha!=null&&(this.alpha=this.alpha*t.alpha),super.multiply(e)}fromArray(e,t=0){return this.alpha=e[t+3],super.fromArray(e,t)}static fromColorRepresentation(e){if(typeof e=="string"){if(e.trim()==="transparent")return new te(0,0,0,0);if(e.startsWith("#")&&e.length===9){const t=parseInt(e.slice(1,9),16),i=t>>24&255,n=t>>16&255,o=t>>8&255,r=t>>0&255;return new te(i/255,n/255,o/255,r/255)}else if(e.startsWith("#")){const t=parseInt(e.slice(1),16),i=t>>16&255,n=t>>8&255,o=t>>0&255;return new te(i/255,n/255,o/255,1)}else if(e.startsWith("rgba")){const t=e.slice(5,-1).split(",").map(Number);return new te(t[0]/255,t[1]/255,t[2]/255,t[3])}else if(e.startsWith("rgb")){const t=e.slice(4,-1).split(",").map(Number);return new te(t[0]/255,t[1]/255,t[2]/255,1)}}else if(Array.isArray(e)){if(e.length===4)return new te(e[0],e[1],e[2],e[3]);if(e.length===3)return new te(e[0],e[1],e[2],1);console.error("Invalid color array length. Expected 3 or 4, got "+e.length)}return new te(e)}}const kt=new c.Vector3,$_=new c.Vector3,W_=new c.Quaternion,hP=x("debuggizmos"),nn=8947848,Hf=32;class B{constructor(){}static enabled=!0;static isGizmo(e){return e[Jp]!==void 0}static setVisible(e){for(const t of Ei.timedObjectsBuffer)t.visible=e}static DrawLabel(e,t,i=.05,n=0,o,r,a){if(!B.enabled)return null;o||(o=nn);const l=q.active?.rigScale??1,h=Ei.getTextLabel(n,t,i*l,o,r);return a instanceof c.Object3D&&a.add(h),h.position.x=e.x,h.position.y=e.y,h.position.z=e.z,h}static DrawRay(e,t,i=nn,n=0,o=!0){if(!B.enabled)return;const r=Ei.getLine(n),a=r.geometry.getAttribute("position");a.setXYZ(0,e.x,e.y,e.z),kt.set(t.x,t.y,t.z).multiplyScalar(999999999),a.setXYZ(1,e.x+kt.x,e.y+kt.y,e.z+kt.z),a.needsUpdate=!0,r.material.depthTest=o,r.material.depthWrite=!1,r.material.fog=!1,rn(r.material,i)}static DrawDirection(e,t,i=nn,n=0,o=!0,r=1){if(!B.enabled)return;const a=Ei.getLine(n),l=a.geometry.getAttribute("position");l.setXYZ(0,e.x,e.y,e.z),t.w!==void 0?(kt.set(0,0,-r),W_.set(t.x,t.y,t.z,t.w),kt.applyQuaternion(W_)):(kt.set(t.x,t.y,t.z),kt.multiplyScalar(r)),l.setXYZ(1,e.x+kt.x,e.y+kt.y,e.z+kt.z),l.needsUpdate=!0,a.material.depthTest=o,a.material.depthWrite=!1,rn(a.material,i)}static DrawLine(e,t,i=nn,n=0,o=!0){if(!B.enabled)return;const r=Ei.getLine(n),a=r.geometry.getAttribute("position");a.setXYZ(0,e.x,e.y,e.z),a.setXYZ(1,t.x,t.y,t.z),a.needsUpdate=!0,r.material.depthTest=o,r.material.depthWrite=!1,r.material.fog=!1,rn(r.material,i)}static DrawCircle(e,t,i,n=nn,o=0,r=!0){if(!B.enabled)return;const a=Ei.getCircle(o);a.position.set(e.x,e.y,e.z),a.scale.set(i,i,i),a.quaternion.setFromUnitVectors(this._up,kt.set(t.x,t.y,t.z).normalize()),a.material.depthTest=r,a.material.depthWrite=!1,a.material.fog=!1,rn(a.material,n)}static DrawWireSphere(e,t,i=nn,n=0,o=!0){if(!B.enabled)return;const r=Ei.getSphere(t,n,!0);hr(r,e.x,e.y,e.z),r.material.depthTest=o,r.material.depthWrite=!1,r.material.fog=!1,rn(r.material,i)}static DrawSphere(e,t,i=nn,n=0,o=!0){if(!B.enabled)return;const r=Ei.getSphere(t,n,!1);hr(r,e.x,e.y,e.z),r.material.depthTest=o,r.material.depthWrite=!1,rn(r.material,i)}static DrawWireBox(e,t,i=nn,n=0,o=!0,r=void 0){if(!B.enabled)return;const a=Ei.getBox(n);a.position.set(e.x,e.y,e.z),a.scale.set(t.x,t.y,t.z),r?a.quaternion.copy(r):a.quaternion.identity(),a.material.depthTest=o,a.material.wireframe=!0,a.material.depthWrite=!1,a.material.fog=!1,rn(a.material,i)}static DrawWireBox3(e,t=nn,i=0,n=!0){if(!B.enabled)return;const o=Ei.getBox(i);o.position.copy(e.getCenter(kt)),o.scale.copy(e.getSize(kt)),o.material.depthTest=n,o.material.wireframe=!0,o.material.depthWrite=!1,o.material.fog=!1,rn(o.material,t)}static _up=new c.Vector3(0,1,0);static DrawArrow(e,t,i=nn,n=0,o=!0,r=!1){if(!B.enabled)return;const a=Ei.getArrowHead(n);a.position.set(t.x,t.y,t.z),a.quaternion.setFromUnitVectors(this._up.set(0,1,0),kt.set(t.x,t.y,t.z).sub($_.set(e.x,e.y,e.z)).normalize());const h=kt.set(t.x,t.y,t.z).sub($_.set(e.x,e.y,e.z)).length()*.1;a.scale.set(h,h,h),a.material.depthTest=o,a.material.wireframe=r,rn(a.material,i),this.DrawLine(e,t,i,n,o)}static DrawWireMesh(e){const t=Ei.getMesh(e.duration??0);"mesh"in e?(t.geometry=e.mesh.geometry,t.matrixWorld.copy(e.mesh.matrixWorld)):(t.geometry=e.geometry,t.matrixWorld.copy(e.matrix)),t.matrixAutoUpdate=!1,t.matrixWorldAutoUpdate=!1,t.material.depthTest=e.depthTest??!0,t.material.wireframe=!0,rn(t.material,e.color??nn)}}const dP=new c.BoxGeometry(1,1,1);function pg(s=null){const e=new c.Color(s??14540253),t=new c.EdgesGeometry(dP);return new c.LineSegments(t,new c.LineBasicMaterial({color:e}))}function rn(s,e){if(Array.isArray(s)){for(const i of s)rn(i,e);return}const t=e instanceof te?e.a:1;s.color.set(e),s.opacity=t,s.transparent=t<1}const Jp=Symbol("GizmoCache");class Ei{static familyName="needle-gizmos";static ensureFont(){let e=ie.__webpack_exports__default.FontLibrary.getFontFamily(this.familyName);e||(e=ie.__webpack_exports__default.FontLibrary.addFontFamily(this.familyName),e.addVariant("normal","normal","https://cdn.needle.tools/static/fonts/msdf/arial/arial-msdf.json","https://cdn.needle.tools/static/fonts/msdf/arial/arial.png")?.addEventListener("ready",()=>{ie.__webpack_exports__default.update()}))}static getTextLabel(e,t,i,n,o){this.ensureFont();let r=this.textLabelCache.pop(),a=1;o&&typeof o=="string"&&o?.length>=8&&o.startsWith("#")?(a=parseInt(o.substring(7),16)/255,o=o.substring(0,7),hP&&console.log(o,a)):typeof o=="object"&&o.a!==void 0&&(a=o.a);const l={boxSizing:"border-box",fontFamily:this.familyName,width:"auto",fontSize:i,color:n,lineHeight:1,backgroundColor:o??void 0,backgroundOpacity:a,textContent:t,borderRadius:.5*i,padding:.8*i,whiteSpace:"pre",offset:.05*i};if(r)r.set(l);else{r=new ie.__webpack_exports__Text(l);const h=this,d=r;d.setText=function(u){this.set({textContent:u}),h.tmuiNeedsUpdate=!0}}return this.tmuiNeedsUpdate=!0,this.registerTimedObject(U.Current,r,e,this.textLabelCache),r}static getBox(e){let t=this.boxesCache.pop();if(!t){const i=new c.BoxGeometry(1,1,1);t=new c.Mesh(i)}return this.registerTimedObject(U.Current,t,e,this.boxesCache),t}static getLine(e){let t=this.linesCache.pop();if(!t){t=new c.Line;let i=t.geometry.getAttribute("position");i||(i=new c.BufferAttribute(new Float32Array(6),3),t.geometry.setAttribute("position",i))}return t.frustumCulled=!1,this.registerTimedObject(U.Current,t,e,this.linesCache),t}static getCircle(e){let t=this.circlesCache.pop();if(!t){t=new c.Line;let i=t.geometry.getAttribute("position");if(!i){i=new c.BufferAttribute(new Float32Array(Hf*3),3),t.geometry.setAttribute("position",i);const n=F(0,1,0),o=F(0,0,1),r=F(o);r.cross(n).normalize();const a=F(r),l=Math.PI*2/(Hf-1);for(let h=0;h<Hf+1;h++){const d=l*h;n.copy(a).multiplyScalar(Math.cos(d)*1),r.copy(o).multiplyScalar(Math.sin(d)*1);const u=n.add(r);i.setXYZ(h,u.x,u.y,u.z)}}}return t.frustumCulled=!1,this.registerTimedObject(U.Current,t,e,this.circlesCache),t}static getSphere(e,t,i){let n=this.spheresCache.pop();return n||(n=new c.Mesh(new c.SphereGeometry(1,8,8))),n.scale.set(e,e,e),n.material.wireframe=i,this.registerTimedObject(U.Current,n,t,this.spheresCache),n}static getArrowHead(e){let t=this.arrowHeadsCache.pop();return t||(t=new c.Mesh(new c.CylinderGeometry(0,.5,1,8))),this.registerTimedObject(U.Current,t,e,this.arrowHeadsCache),t}static getMesh(e){let t=this.mesh.pop();return t||(t=new c.Mesh,t.material=new c.MeshBasicMaterial),this.registerTimedObject(U.Current,t,e,this.mesh),t}static linesCache=[];static circlesCache=[];static spheresCache=[];static boxesCache=[];static arrowHeadsCache=[];static mesh=[];static textLabelCache=[];static registerTimedObject(e,t,i,n){if(!e){console.error("No Needle Engine context available. Did you call a Gizmos function in global scope?");return}const o=this.contextBeforeRenderCallbacks.get(e),r=this.contextPostRenderCallbacks.get(e);if(o){if(e.pre_render_callbacks[e.pre_render_callbacks.length-1]!==o){const a=e.pre_render_callbacks.indexOf(o);a>=0&&e.pre_render_callbacks.splice(a,1),e.pre_render_callbacks.push(o)}}else{const a=()=>{this.onBeforeRender(e,this.timedObjectsBuffer)};this.contextBeforeRenderCallbacks.set(e,a),e.pre_render_callbacks.push(a)}if(r){if(e.post_render_callbacks[e.post_render_callbacks.length-1]!==r){const a=e.post_render_callbacks.indexOf(r);a>=0&&e.post_render_callbacks.splice(a,1),e.post_render_callbacks.push(r)}}else{const a=()=>{this.onPostRender(e,this.timedObjectsBuffer,this.timesBuffer)};this.contextPostRenderCallbacks.set(e,a),e.post_render_callbacks.push(a)}t.traverse(a=>{a.layers.disableAll(),a.layers.enable(2)}),t.renderOrder=999999,t[Jp]=n,t.castShadow=!1,t.receiveShadow=!1,t.isGizmo=!0,this.timedObjectsBuffer.push(t),this.timesBuffer.push(U.Current.time.realtimeSinceStartup+i),e.scene.add(t)}static timedObjectsBuffer=new Array;static timesBuffer=new Array;static contextPostRenderCallbacks=new Map;static contextBeforeRenderCallbacks=new Map;static tmuiNeedsUpdate=!1;static onBeforeRender(e,t){this.tmuiNeedsUpdate&&(this.tmuiNeedsUpdate=!1,ie.__webpack_exports__default.update());for(let i=0;i<t.length;i++){const n=t[i];if(e.mainCamera&&n instanceof ie.__webpack_exports__default.MeshUIBaseElement){if(dr(n))continue;const o=e.isInVR,r=!1,a=!o;Nc(n,e.mainCamera,r,a)}}}static onPostRender(e,t,i){const n=e.time.realtimeSinceStartup;for(let o=t.length-1;o>=0;o--){const r=t[o];n>=i[o]-1e-6&&(t.splice(o,1),i.splice(o,1),r.removeFromParent(),dr(r)!=!0&&r[Jp].push(r))}}}const Vt=x("debugphysics"),uP=x("debugworker"),G_=new c.Layers;class bo{static AllLayers=4294967295;ray;cam;screenPoint;raycaster;results;targets;recursive=!0;minDistance;maxDistance;lineThreshold;layerMask;ignore;testObject;useAcceleratedRaycast;allowSlowRaycastFallback=!0;screenPointFromOffset(e,t){this.screenPoint===void 0&&(this.screenPoint=new c.Vector2),this.screenPoint.x=e/window.innerWidth*2-1,this.screenPoint.y=-(t/window.innerHeight)*2+1}setLayer(e){G_.set(e),this.layerMask=G_}setMask(e){this.layerMask||(this.layerMask=new c.Layers);const t=this.layerMask;t?t.mask=e:this.layerMask=e}}class mg{distance;point;object;constructor(e,t,i){this.object=e,this.distance=t,this.point=i}}class Ia{static _raycasting=0;static get raycasting(){return this._raycasting>0}raycastPhysicsFast(e,t=void 0,i=1/0,n=!0){return this.context.physics.engine?.raycast(e,t,{maxDistance:i,solid:n})??null}raycastPhysicsFastAndGetNormal(e,t=void 0,i=1/0,n=!0){return this.context.physics.engine?.raycastAndGetNormal(e,t,{maxDistance:i,solid:n})??null}sphereOverlapPhysics(e,t){return this.context.physics.engine?.sphereOverlap(e,t)??null}context;engine;constructor(e){this.context=e}raycaster=new c.Raycaster;defaultRaycastOptions=new bo;targetBuffer=new Array(1);defaultThresholds={Mesh:{},Line:{threshold:-1},LOD:{},Points:{threshold:0},Sprite:{}};sphereResults=new Array;sphereMask=new c.Layers;sphere=new c.Sphere;sphereOverlap(e,t,i=!0,n=!1,o=null){if(this.sphereResults.length=0,!this.context.scene)return this.sphereResults;const r=this.sphereMask;r.enableAll(),r.disable(2);for(const a of this.context.scene.children)this.intersectSphere(a,e,t,r,this.sphereResults,i,n,o);return this.sphereResults.sort((a,l)=>a.distance-l.distance)}raycastFromRay(e,t=null){const i=t??this.defaultRaycastOptions;i.ray=e;const n=this.raycast(i);return i===this.defaultRaycastOptions&&(i.ray=void 0),n}raycast(e=null){Vt&&performance.mark("raycast.start"),e||(e=this.defaultRaycastOptions);const t=e.screenPoint??this.context.input.mousePositionRC,i=e.raycaster??this.raycaster;if(i.near=e.minDistance??0,i.far=e.maxDistance??1/0,i.params=this.defaultThresholds,e.lineThreshold===void 0&&(e.lineThreshold=-1),i.params.Line={threshold:e.lineThreshold},e.ray)i.ray.copy(e.ray);else{const a=e.cam??this.context.mainCamera;if(!a)return Vt&&console.error("Can not perform raycast - no main camera found"),this.defaultRaycastOptions.results&&(this.defaultRaycastOptions.results.length=0),this.defaultRaycastOptions.results??[];const l=this.context.xrCamera;this.context.isInXR&&l instanceof c.ArrayCamera&&l.cameras.length>0?i.setFromCamera(t,l.cameras[0]):i.setFromCamera(t,a)}let n=e.targets;n||(n=this.targetBuffer,n.length=1,n[0]=this.context.scene);let o=e.results;this.defaultRaycastOptions.results&&(this.defaultRaycastOptions.results.length=0),o||(this.defaultRaycastOptions.results||(this.defaultRaycastOptions.results=new Array),o=this.defaultRaycastOptions.results),e.layerMask!==void 0?e.layerMask instanceof c.Layers?i.layers.mask=e.layerMask.mask:i.layers.mask=e.layerMask:(i.layers.enableAll(),i.layers.disable(2)),Vt&&console.time("raycast"),o.length=0,Ia._raycasting++,this.intersect(this.raycaster,n,o,e),o.sort((a,l)=>a.distance-l.distance);const r=e.ignore;return r!==void 0&&r.length>0&&(o=o.filter(a=>!r.includes(a.object))),Ia._raycasting--,Vt&&(console.timeEnd("raycast"),console.warn("#"+this.context.time.frame+", hits:",o?.length?[...o]:"nothing"),performance.mark("raycast.end"),performance.measure("raycast","raycast.start","raycast.end")),o}intersect(e,t,i,n){for(const o of t){if(!o||o.visible===!1||B.isGizmo(o)||n.lineThreshold!==void 0&&n.lineThreshold<0&&o instanceof c.Line)continue;let r=!0;const a=o,l=a.geometry;if(o.raycastAllowed===!1&&(r=!1),r&&n.testObject){const h=n.testObject?.(o);if(h===!1)continue;h==="continue in children"&&(r=!1)}else r&&(l&&H_(l)||(r=!1));if(r){const h=i.length,d=o.raycastPreference||"lod";let u=d!=="bounds";if(n.precise===!1&&(u=!1),l&&(u||=l.getAttribute("position")?.array?.length<64),a instanceof X.GroundedSkybox&&(u=!1),d==="lod"){const p=re.getRaycastMesh(o);p&&(a.geometry=p)}if(!u&&pP(a,e,i)||(n.useAcceleratedRaycast!==!1?Zd.runMeshBVHRaycast(e,a,i,this.context,n):e.intersectObject(a,!1,i)),a.geometry=l,Vt&&i.length!=h){const p=i[i.length-1];B.DrawWireSphere(p.point,.1,7798784,1,!1),B.DrawWireMesh({mesh:o,depthTest:!1,duration:.2,color:7798784})}}n.recursive!==!1&&this.intersect(e,o.children,i,n)}return i}tempBoundingBox=new c.Box3;intersectSphere(e,t,i,n,o,r,a,l){let h=e&&e.isMesh&&e.layers.test(n)&&!B.isGizmo(e);h&&=e.visible,h&&=!(e instanceof c.Line),h&&=!(e instanceof X.GroundedSkybox);const d=e,u=d.geometry;if(h&&l){const p=l(e);if(p===!1)return;p==="continue in children"&&(h=!1)}if(u&&H_(u)||(h=!1),h){if(a){const p=this.sphere;p.center.copy(t),p.radius=i;const m=o.length;if(Zd.runMeshBVHRaycast(this.sphere,d,o,this.context,{}),m!=o.length&&!r)return}else if(u.boundingBox||u.computeBoundingBox(),u.boundingBox){d.matrixWorldNeedsUpdate&&d.updateWorldMatrix(!1,!1);const p=this.tempBoundingBox.copy(u.boundingBox).applyMatrix4(d.matrixWorld),m=this.sphere;if(m.center.copy(t),m.radius=i,m.intersectsBox(p)){const y=Y(e),_=y.distanceTo(m.center),g=new mg(e,_,y);if(o.push(g),!r)return}}}if(e.children)for(const p of e.children){const m=o.length;if(this.intersectSphere(p,t,i,n,o,r,a,l),m!=o.length&&!r)return}}}function H_(s){return!(s.index&&s.index.array.length<3)}const jo=new c.Sphere,qh=new c.Plane,fP=new c.Matrix3;function pP(s,e,t){const i=s._computeIntersections;if(!i)return!1;let n=s["_computeIntersections:Needle"];return n||(n=s["_computeIntersections:Needle"]=function(o,r,a){const l=this,h=l.geometry.boundingSphere;if(h){if(l instanceof X.GroundedSkybox){qh.setFromNormalAndCoplanarPoint(F(0,1,0),F(0,-l.position.y,0)),qh.applyMatrix4(l.matrixWorld,fP);const u=o.ray.intersectPlane(qh,F());if(u){jo.copy(h),jo.applyMatrix4(l.matrixWorld);const m=F(u).sub(o.ray.origin).length(),y=jo.radius*.5;m<y&&r.push({distance:m,point:u,object:l,normal:qh.normal.clone()})}return}jo.copy(h),jo.applyMatrix4(l.matrixWorld);const d=o.ray.intersectSphere(jo,F());if(d){const u=F(d).sub(o.ray.origin),p=u.length();if(p>jo.radius){const m=u.clone().normalize();r.push({distance:p,point:d,object:l,normal:m})}}}}),s._computeIntersections=n,e.intersectObject(s,!1,t),s._computeIntersections=i,!0}var Zd;(s=>{let e=0;function t(b,w,R,O,k){if(!w.geometry||!w.geometry.hasAttribute("position"))return!1;const L=w.geometry;if(w?.isSkinnedMesh){const D=w,j=D.bvhNeedsUpdate;if(!D.staticGenerator)l(),r&&(D.staticGenerator=new r(w),D.staticGenerator.applyWorldTransforms=!1,D.staticGeometry=D.staticGenerator.generate(),L.boundsTree=a?.call(D.staticGeometry),D.staticGeometryLastUpdate=performance.now()+Math.random()*200,D.bvhNeedsUpdate=!0);else if(L.boundsTree&&(D.autoUpdateMeshBvhInterval!==void 0&&D.autoUpdateMeshBvhInterval>=0||j===!0)){const V=performance.now(),W=V-D.staticGeometryLastUpdate,M=D.autoUpdateMeshBvhInterval??100;(j||W>M)&&(Vt&&console.warn(`Physics: updating skinned mesh bvh for ${w.name} after ${W.toFixed(2)}ms`),D.bvhNeedsUpdate=!1,D.staticGeometryLastUpdate=V,D.staticGenerator?.generate(D.staticGeometry),L.boundsTree.refit())}}else if(!L.boundsTree){d||v();let D=!0;if((O.xr||L[y]===!1||L.getAttribute("position")?.isInterleavedBufferAttribute||L.index&&L.index?.isInterleavedBufferAttribute||e>10)&&(D=!1),D&&p){if(L[m]===void 0){let j=null;if(g.length>0){const V=g.shift();V&&!V.running&&(j=V)}if(!j&&_.length<3)try{uP&&console.warn("[GenerateMeshBVHWorker] Creating worker with import.meta.url:",typeof document>"u"?require("url").pathToFileURL(__filename).href:ya&&ya.tagName.toUpperCase()==="SCRIPT"&&ya.src||new URL("needle-engine.bundle-BOAJ6UPK.umd.cjs",document.baseURI).href),j=new p,_.push(j)}catch(V){V instanceof DOMException&&V.name==="SecurityError"?(console.warn("Failed to create MeshBVH worker, falling back to main thread generation. This can happen when running from file://, if the browser does not support workers or if the browser is blocking workers for other reasons."),console.debug(V),e+=10):(console.error("Failed to create MeshBVH worker. Please see below for more details:"),console.log(V)),e++}if(j!=null&&!j.running){const V=w.name;Vt&&console.log("<<<< worker start",V,j),L[m]="queued",performance.mark("bvh.create.start");const W=L.clone();try{j.generate(W).then(M=>{L[m]="done",L.boundsTree=M}).catch(M=>{L[m]="failed - "+M?.message,L[y]=!1,Vt&&console.error("Failed to generate mesh bvh on worker",M)}).finally(()=>{Vt&&console.log(">>>>> worker done",V,{hasBoundsTre:L.boundsTree!=null}),g.push(j),W.dispose(),performance.mark("bvh.create.end"),performance.measure("bvh.create (worker)","bvh.create.start","bvh.create.end")})}catch(M){console.error("Failed to generate mesh bvh on worker",M)}}else Vt&&console.warn("No worker available")}}else(!u||!D)&&(l(),o&&(performance.mark("bvh.create.start"),L.boundsTree=new o(L),performance.mark("bvh.create.end"),performance.measure("bvh.create","bvh.create.start","bvh.create.end")))}if(b instanceof c.Raycaster){const D=b,j=w.raycast;if(L.boundsTree)l(),n&&(w.acceleratedRaycast||(w.acceleratedRaycast=n.bind(w),Vt&&console.debug(`Physics: bind acceleratedRaycast fn to "${w.name}"`)),w.raycast=w.acceleratedRaycast);else if(Vt&&console.warn("No bounds tree found for mesh",w.name,{workerTask:L[m],hasAcceleratedRaycast:n!=null}),k.allowSlowRaycastFallback===!1&&(L.getAttribute("position")?.array?.length??0)>2e3)return Vt&&console.warn("Skipping raycast because no bounds tree is available and allowSlowRaycastFallback is false"),!1;const V=D.firstHitOnly;return D.firstHitOnly=!1,D.intersectObject(w,!1,R),D.firstHitOnly=V,w.raycast=j,!0}else if(b instanceof c.Sphere){const D=L.boundsTree;if(D){const j=b;if(h.copy(w.matrixWorld).invert(),j.applyMatrix4(h),D.intersectsSphere(j)){const W=Y(w),M=W.distanceTo(j.center),N=new mg(w,M,W);R.push(N)}}return!0}return!1}s.runMeshBVHRaycast=t;let i=!1,n=null,o=null,r=null,a=null;function l(){i||(i=!0,Promise.resolve().then(()=>require("./vendor-BI4TX0aC.umd.cjs")).then(b=>b.index$1).then(b=>{n=b.acceleratedRaycast,o=b.MeshBVH,r=b.StaticGeometryGenerator,a=b.computeBoundsTree}).catch(b=>{(Vt||A())&&console.error("Failed to load BVH library...",b.message)}))}const h=new c.Matrix4;let d=!1,u=!1,p=null;const m=Symbol("Needle:MeshBVH-Worker"),y=Symbol("Needle:MeshBVH-CanUseWorker"),_=[],g=[];function v(){d=!0,u=!0,Promise.resolve().then(()=>RA).then(b=>{p=b.GenerateMeshBVHWorker}).catch(b=>{Vt||A()?console.warn("Failed to setup mesh bvh worker"):console.debug("Failed to setup mesh bvh worker",b)}).finally(()=>{u=!1})}})(Zd||(Zd={}));const q_=Symbol("gltf-loader-internal-usage-tracker"),mP=x("debugusers");class xa{get name(){return"NEEDLE_internal_usage_tracker"}static isLoading(e){return xa._loadingProcesses>0}static _loadingProcesses=0;parser;_getDependency;_loadingId;_loadedObjects=new Set;constructor(e){this.parser=e,this._getDependency=this.parser.getDependency,this._loadingId=Date.now().toString()}beforeRoot(){xa._loadingProcesses++;const e=this,t=this._getDependency;return this.parser.getDependency=function(i,n){const o=t.call(this,i,n);return o.then(r=>(r&&(e._loadedObjects.add(r),r[q_]=e._loadingId),r)),o},null}afterRoot(e){xa._loadingProcesses--,this.parser.getDependency=this._getDependency;for(const t of this._loadedObjects)delete t[q_],t instanceof c.Object3D&&(t.parent||t instanceof c.Mesh&&setTimeout(()=>{mP&&console.warn("> GLTF LOADER: Mesh not used in scene!",t),t.material=null,t.geometry=null},1e3));return null}}class V0{constructor(){window.addEventListener("unhandledrejection",e=>{if(e.defaultPrevented)return;const t=e?.reason?.path;if(t){const i=t[0];i&&i.tagName==="IMG"&&(console.warn(`Could not load image:
879
+ ${o.hand?"hand":"ctrl"} ${o.inputSource.handedness}[${o.index}] con:${o.connected} tr:${o.isTracking} hts:${o.hasHitTestSource?"yes":"no"}`;$f=0,B.DrawLabel(e,n,void 0,1/60*20)}}onBeforeRender=()=>{this.context.mainCamera&&(this.updateFade(this.context.mainCamera),this.requestedCameraNearPlane!==null&&this.context.mainCamera instanceof c.PerspectiveCamera&&(this.context.mainCamera.near=this.requestedCameraNearPlane,this.requestedCameraNearPlane=null))};onAfterRender=()=>{if(this.onUpdateFade_PostRender(),exports.DeviceUtilities.isDesktop()||!this._renderOnceOnDevice){const e=this.context.renderer;if(e.xr.isPresenting&&this.context.mainCamera){this._renderOnceOnDevice=!0;const t=e.xr.enabled,i=e.getRenderTarget(),n=this.context.scene.background;e.xr.enabled=!1,e.setRenderTarget(null),this.isPassThrough&&(this.context.scene.background=null),this.context.composer?this.context.composer.render(this.context.time.deltaTime):e.render(this.context.scene,this.context.mainCamera),e.xr.enabled=t,e.setRenderTarget(i),this.context.scene.background=n}}};addScript(e){return this._xr_scripts.includes(e)?!1:(Ue&&console.log("Register new XRScript",e),this._xr_scripts.push(e),typeof e.onUpdateXR=="function"&&this._xr_update_scripts.push(e),!0)}markInactive(e){if(!(this._inactive_scripts.indexOf(e)>=0)){this.removeScript(e,!1),this._inactive_scripts.push(e);for(const t of this.controllers)this.invokeCallback_ControllerRemoved(e,t);this.invokeCallback_LeaveXR(e)}}handleInactiveScripts(){if(this._inactive_scripts.length>0)for(let e=this._inactive_scripts.length-1;e>=0;e--){const t=this._inactive_scripts[e];if(t.activeAndEnabled){this._inactive_scripts.splice(e,1),this.addScript(t),this.invokeCallback_EnterXR(t);for(const i of this.controllers)this.invokeCallback_ControllerAdded(t,i)}}}_script_to_remove=[];removeScript(e,t=!0){Ue&&console.log("Remove XRScript",e);const i=this._xr_scripts.indexOf(e);i>=0&&this._xr_scripts.splice(i,1);const n=this._xr_update_scripts.indexOf(e);if(n>=0&&this._xr_update_scripts.splice(n,1),t){const o=this._inactive_scripts.indexOf(e);o>=0&&this._inactive_scripts.splice(o,1)}}invokeCallback_EnterXR(e){e.onEnterXR&&e.onEnterXR({xr:this})}invokeCallback_ControllerAdded(e,t){e.onXRControllerAdded&&e.onXRControllerAdded({xr:this,controller:t,change:"added"})}invokeCallback_ControllerRemoved(e,t){e.onXRControllerRemoved&&e.onXRControllerRemoved({xr:this,controller:t,change:"removed"})}invokeCallback_LeaveXR(e){e.onLeaveXR&&!e.destroyed&&e.onLeaveXR({xr:this})}syncCameraCullingMask(){const e=this.context.xrCamera,t=this.context.mainCameraComponent?.cullingMask;if(e&&t!==void 0){for(const i of e.cameras)i.layers.mask=t;e.layers.mask=t}else if(e){for(const i of e.cameras)i.layers.enableAll();e.layers.enableAll()}}invokeControllerEvent(e,t,i){for(let n=t.length-1;n>=0;n--){const o=t[n];if(o)try{o({xr:this,controller:e,change:i})}catch(r){console.error(r)}}}_camera;_cameraRenderParent=new c.Object3D().rotateY(Math.PI);_previousCameraParent;_customforward=!0;originalCameraNearPlane;requestedCameraNearPlane=null;applyCustomForward(){if(this.context.mainCamera&&this._customforward){this._camera=this.context.mainCamera,this._camera.parent!==this._cameraRenderParent&&(this._previousCameraParent=this._camera.parent,this._previousCameraParent?.add(this._cameraRenderParent)),this._cameraRenderParent.name="XR Camera Render Parent",this._cameraRenderParent.add(this._camera);{let e=.02;const t=.001;if(this.rig){const i=je(this.rig.gameObject);e*=i.x}this._camera instanceof c.PerspectiveCamera&&Math.abs(this._camera.near-e)>t&&(this.isAR?this.originalCameraNearPlane=this._camera.near:this._camera.near=e,Ue&&console.debug(`Setting camera near plane to ${e} (was ${this.originalCameraNearPlane}) to account for XR rendering scale`))}}}revertCustomForward(){this._camera&&this._previousCameraParent&&this._previousCameraParent.add(this._camera),this._previousCameraParent=null,this._camera instanceof c.PerspectiveCamera&&this.originalCameraNearPlane!=null&&(this._camera.near=this.originalCameraNearPlane,this.originalCameraNearPlane=void 0)}_viewerPose;_transformOrientation=new c.Quaternion;_transformPosition=new c.Vector3;internalUpdateState(){const e=this.context.renderer.xr.getReferenceSpace();if(!e){this._viewerPose=void 0;return}if(this._viewerPose=this.frame.getViewerPose(e),this._viewerPose){const t=this._viewerPose.transform;this._transformPosition.set(t.position.x,t.position.y,t.position.z),this._transformOrientation.set(t.orientation.x,t.orientation.y,t.orientation.z,t.orientation.w)}}_transition;get transition(){return this._transition||(this._transition=new N_),this._transition}fadeTransition(){return this._transition||(this._transition=new N_),this._transition.fadeTransition()}updateFade(e){this._transition&&e instanceof c.PerspectiveCamera&&this._transition.update(e,this.context.time.deltaTime)}onUpdateFade_PostRender(){this._transition?.remove()}}const Gf=x("debugwebxr");class N0{static tryFindAvatarObjects(e,t,i){if(i.head&&i.leftHand&&i.rightHand)return;const n=e.name.toLocaleLowerCase();!i.head&&n.includes("head")&&(Gf&&console.log("FOUND AVATAR HEAD",e.name),i.head=new Z("",t,e)),n.includes("hand")&&(!i.leftHand&&n.includes("left")&&(Gf&&console.log("FOUND AVATAR LEFT HAND",e.name),i.leftHand=new Z("",t,e)),!i.rightHand&&n.includes("right")&&(Gf&&console.log("FOUND AVATAR RIGHT HAND",e.name),i.rightHand=new Z("",t,e)));for(let o=0;o<e.children.length;o++){if(i.head&&i.leftHand&&i.rightHand)return;const r=e.children[o];this.tryFindAvatarObjects(r,t,i)}}}class te extends c.Color{alpha=1;get isRGBAColor(){return!0}set a(e){this.alpha=e}get a(){return this.alpha}constructor(e,t,i,n){super(),typeof e=="number"&&typeof t=="number"&&typeof i=="number"?(this.set(e,t,i),this.alpha=typeof n=="number"?n:1):e!==void 0&&(this.set(e),this.alpha=1)}clone(){const e=super.clone();return e.alpha=this.alpha,e}copy(e){return this.r=e.r,this.g=e.g,this.b=e.b,"alpha"in e&&typeof e.alpha=="number"?this.alpha=e.alpha:typeof e.a=="number"&&(this.alpha=e.a),this}lerp(e,t){const i=e;return i.alpha!=null&&(this.alpha=I.lerp(this.alpha,i.alpha,t)),super.lerp(e,t)}lerpColors(e,t,i){const n=e,o=t;return n.alpha!=null&&o.alpha!=null&&(this.alpha=I.lerp(n.alpha,o.alpha,i)),super.lerpColors(e,t,i)}multiply(e){const t=e;return t.alpha!=null&&(this.alpha=this.alpha*t.alpha),super.multiply(e)}fromArray(e,t=0){return this.alpha=e[t+3],super.fromArray(e,t)}static fromColorRepresentation(e){if(typeof e=="string"){if(e.trim()==="transparent")return new te(0,0,0,0);if(e.startsWith("#")&&e.length===9){const t=parseInt(e.slice(1,9),16),i=t>>24&255,n=t>>16&255,o=t>>8&255,r=t>>0&255;return new te(i/255,n/255,o/255,r/255)}else if(e.startsWith("#")){const t=parseInt(e.slice(1),16),i=t>>16&255,n=t>>8&255,o=t>>0&255;return new te(i/255,n/255,o/255,1)}else if(e.startsWith("rgba")){const t=e.slice(5,-1).split(",").map(Number);return new te(t[0]/255,t[1]/255,t[2]/255,t[3])}else if(e.startsWith("rgb")){const t=e.slice(4,-1).split(",").map(Number);return new te(t[0]/255,t[1]/255,t[2]/255,1)}}else if(Array.isArray(e)){if(e.length===4)return new te(e[0],e[1],e[2],e[3]);if(e.length===3)return new te(e[0],e[1],e[2],1);console.error("Invalid color array length. Expected 3 or 4, got "+e.length)}return new te(e)}}const kt=new c.Vector3,$_=new c.Vector3,W_=new c.Quaternion,hP=x("debuggizmos"),nn=8947848,Hf=32;class B{constructor(){}static enabled=!0;static isGizmo(e){return e[Jp]!==void 0}static setVisible(e){for(const t of Ei.timedObjectsBuffer)t.visible=e}static DrawLabel(e,t,i=.05,n=0,o,r,a){if(!B.enabled)return null;o||(o=nn);const l=q.active?.rigScale??1,h=Ei.getTextLabel(n,t,i*l,o,r);return a instanceof c.Object3D&&a.add(h),h.position.x=e.x,h.position.y=e.y,h.position.z=e.z,h}static DrawRay(e,t,i=nn,n=0,o=!0){if(!B.enabled)return;const r=Ei.getLine(n),a=r.geometry.getAttribute("position");a.setXYZ(0,e.x,e.y,e.z),kt.set(t.x,t.y,t.z).multiplyScalar(999999999),a.setXYZ(1,e.x+kt.x,e.y+kt.y,e.z+kt.z),a.needsUpdate=!0,r.material.depthTest=o,r.material.depthWrite=!1,r.material.fog=!1,rn(r.material,i)}static DrawDirection(e,t,i=nn,n=0,o=!0,r=1){if(!B.enabled)return;const a=Ei.getLine(n),l=a.geometry.getAttribute("position");l.setXYZ(0,e.x,e.y,e.z),t.w!==void 0?(kt.set(0,0,-r),W_.set(t.x,t.y,t.z,t.w),kt.applyQuaternion(W_)):(kt.set(t.x,t.y,t.z),kt.multiplyScalar(r)),l.setXYZ(1,e.x+kt.x,e.y+kt.y,e.z+kt.z),l.needsUpdate=!0,a.material.depthTest=o,a.material.depthWrite=!1,rn(a.material,i)}static DrawLine(e,t,i=nn,n=0,o=!0){if(!B.enabled)return;const r=Ei.getLine(n),a=r.geometry.getAttribute("position");a.setXYZ(0,e.x,e.y,e.z),a.setXYZ(1,t.x,t.y,t.z),a.needsUpdate=!0,r.material.depthTest=o,r.material.depthWrite=!1,r.material.fog=!1,rn(r.material,i)}static DrawCircle(e,t,i,n=nn,o=0,r=!0){if(!B.enabled)return;const a=Ei.getCircle(o);a.position.set(e.x,e.y,e.z),a.scale.set(i,i,i),a.quaternion.setFromUnitVectors(this._up,kt.set(t.x,t.y,t.z).normalize()),a.material.depthTest=r,a.material.depthWrite=!1,a.material.fog=!1,rn(a.material,n)}static DrawWireSphere(e,t,i=nn,n=0,o=!0){if(!B.enabled)return;const r=Ei.getSphere(t,n,!0);hr(r,e.x,e.y,e.z),r.material.depthTest=o,r.material.depthWrite=!1,r.material.fog=!1,rn(r.material,i)}static DrawSphere(e,t,i=nn,n=0,o=!0){if(!B.enabled)return;const r=Ei.getSphere(t,n,!1);hr(r,e.x,e.y,e.z),r.material.depthTest=o,r.material.depthWrite=!1,rn(r.material,i)}static DrawWireBox(e,t,i=nn,n=0,o=!0,r=void 0){if(!B.enabled)return;const a=Ei.getBox(n);a.position.set(e.x,e.y,e.z),a.scale.set(t.x,t.y,t.z),r?a.quaternion.copy(r):a.quaternion.identity(),a.material.depthTest=o,a.material.wireframe=!0,a.material.depthWrite=!1,a.material.fog=!1,rn(a.material,i)}static DrawWireBox3(e,t=nn,i=0,n=!0){if(!B.enabled)return;const o=Ei.getBox(i);o.position.copy(e.getCenter(kt)),o.scale.copy(e.getSize(kt)),o.material.depthTest=n,o.material.wireframe=!0,o.material.depthWrite=!1,o.material.fog=!1,rn(o.material,t)}static _up=new c.Vector3(0,1,0);static DrawArrow(e,t,i=nn,n=0,o=!0,r=!1){if(!B.enabled)return;const a=Ei.getArrowHead(n);a.position.set(t.x,t.y,t.z),a.quaternion.setFromUnitVectors(this._up.set(0,1,0),kt.set(t.x,t.y,t.z).sub($_.set(e.x,e.y,e.z)).normalize());const h=kt.set(t.x,t.y,t.z).sub($_.set(e.x,e.y,e.z)).length()*.1;a.scale.set(h,h,h),a.material.depthTest=o,a.material.wireframe=r,rn(a.material,i),this.DrawLine(e,t,i,n,o)}static DrawWireMesh(e){const t=Ei.getMesh(e.duration??0);"mesh"in e?(t.geometry=e.mesh.geometry,t.matrixWorld.copy(e.mesh.matrixWorld)):(t.geometry=e.geometry,t.matrixWorld.copy(e.matrix)),t.matrixAutoUpdate=!1,t.matrixWorldAutoUpdate=!1,t.material.depthTest=e.depthTest??!0,t.material.wireframe=!0,rn(t.material,e.color??nn)}}const dP=new c.BoxGeometry(1,1,1);function pg(s=null){const e=new c.Color(s??14540253),t=new c.EdgesGeometry(dP);return new c.LineSegments(t,new c.LineBasicMaterial({color:e}))}function rn(s,e){if(Array.isArray(s)){for(const i of s)rn(i,e);return}const t=e instanceof te?e.a:1;s.color.set(e),s.opacity=t,s.transparent=t<1}const Jp=Symbol("GizmoCache");class Ei{static familyName="needle-gizmos";static ensureFont(){let e=ie.__webpack_exports__default.FontLibrary.getFontFamily(this.familyName);e||(e=ie.__webpack_exports__default.FontLibrary.addFontFamily(this.familyName),e.addVariant("normal","normal","https://cdn.needle.tools/static/fonts/msdf/arial/arial-msdf.json","https://cdn.needle.tools/static/fonts/msdf/arial/arial.png")?.addEventListener("ready",()=>{ie.__webpack_exports__default.update()}))}static getTextLabel(e,t,i,n,o){this.ensureFont();let r=this.textLabelCache.pop(),a=1;o&&typeof o=="string"&&o?.length>=8&&o.startsWith("#")?(a=parseInt(o.substring(7),16)/255,o=o.substring(0,7),hP&&console.log(o,a)):typeof o=="object"&&o.a!==void 0&&(a=o.a);const l={boxSizing:"border-box",fontFamily:this.familyName,width:"auto",fontSize:i,color:n,lineHeight:1,backgroundColor:o??void 0,backgroundOpacity:a,textContent:t,borderRadius:.5*i,padding:.8*i,whiteSpace:"pre",offset:.05*i};if(r)r.set(l);else{r=new ie.__webpack_exports__Text(l);const h=this,d=r;d.setText=function(u){this.set({textContent:u}),h.tmuiNeedsUpdate=!0}}return this.tmuiNeedsUpdate=!0,this.registerTimedObject(U.Current,r,e,this.textLabelCache),r}static getBox(e){let t=this.boxesCache.pop();if(!t){const i=new c.BoxGeometry(1,1,1);t=new c.Mesh(i)}return this.registerTimedObject(U.Current,t,e,this.boxesCache),t}static getLine(e){let t=this.linesCache.pop();if(!t){t=new c.Line;let i=t.geometry.getAttribute("position");i||(i=new c.BufferAttribute(new Float32Array(6),3),t.geometry.setAttribute("position",i))}return t.frustumCulled=!1,this.registerTimedObject(U.Current,t,e,this.linesCache),t}static getCircle(e){let t=this.circlesCache.pop();if(!t){t=new c.Line;let i=t.geometry.getAttribute("position");if(!i){i=new c.BufferAttribute(new Float32Array(Hf*3),3),t.geometry.setAttribute("position",i);const n=F(0,1,0),o=F(0,0,1),r=F(o);r.cross(n).normalize();const a=F(r),l=Math.PI*2/(Hf-1);for(let h=0;h<Hf+1;h++){const d=l*h;n.copy(a).multiplyScalar(Math.cos(d)*1),r.copy(o).multiplyScalar(Math.sin(d)*1);const u=n.add(r);i.setXYZ(h,u.x,u.y,u.z)}}}return t.frustumCulled=!1,this.registerTimedObject(U.Current,t,e,this.circlesCache),t}static getSphere(e,t,i){let n=this.spheresCache.pop();return n||(n=new c.Mesh(new c.SphereGeometry(1,8,8))),n.scale.set(e,e,e),n.material.wireframe=i,this.registerTimedObject(U.Current,n,t,this.spheresCache),n}static getArrowHead(e){let t=this.arrowHeadsCache.pop();return t||(t=new c.Mesh(new c.CylinderGeometry(0,.5,1,8))),this.registerTimedObject(U.Current,t,e,this.arrowHeadsCache),t}static getMesh(e){let t=this.mesh.pop();return t||(t=new c.Mesh,t.material=new c.MeshBasicMaterial),this.registerTimedObject(U.Current,t,e,this.mesh),t}static linesCache=[];static circlesCache=[];static spheresCache=[];static boxesCache=[];static arrowHeadsCache=[];static mesh=[];static textLabelCache=[];static registerTimedObject(e,t,i,n){if(!e){console.error("No Needle Engine context available. Did you call a Gizmos function in global scope?");return}const o=this.contextBeforeRenderCallbacks.get(e),r=this.contextPostRenderCallbacks.get(e);if(o){if(e.pre_render_callbacks[e.pre_render_callbacks.length-1]!==o){const a=e.pre_render_callbacks.indexOf(o);a>=0&&e.pre_render_callbacks.splice(a,1),e.pre_render_callbacks.push(o)}}else{const a=()=>{this.onBeforeRender(e,this.timedObjectsBuffer)};this.contextBeforeRenderCallbacks.set(e,a),e.pre_render_callbacks.push(a)}if(r){if(e.post_render_callbacks[e.post_render_callbacks.length-1]!==r){const a=e.post_render_callbacks.indexOf(r);a>=0&&e.post_render_callbacks.splice(a,1),e.post_render_callbacks.push(r)}}else{const a=()=>{this.onPostRender(e,this.timedObjectsBuffer,this.timesBuffer)};this.contextPostRenderCallbacks.set(e,a),e.post_render_callbacks.push(a)}t.traverse(a=>{a.layers.disableAll(),a.layers.enable(2)}),t.renderOrder=999999,t[Jp]=n,t.castShadow=!1,t.receiveShadow=!1,t.isGizmo=!0,this.timedObjectsBuffer.push(t),this.timesBuffer.push(U.Current.time.realtimeSinceStartup+i),e.scene.add(t)}static timedObjectsBuffer=new Array;static timesBuffer=new Array;static contextPostRenderCallbacks=new Map;static contextBeforeRenderCallbacks=new Map;static tmuiNeedsUpdate=!1;static onBeforeRender(e,t){this.tmuiNeedsUpdate&&(this.tmuiNeedsUpdate=!1,ie.__webpack_exports__default.update());for(let i=0;i<t.length;i++){const n=t[i];if(e.mainCamera&&n instanceof ie.__webpack_exports__default.MeshUIBaseElement){if(dr(n))continue;const o=e.isInVR,r=!1,a=!o;Nc(n,e.mainCamera,r,a)}}}static onPostRender(e,t,i){const n=e.time.realtimeSinceStartup;for(let o=t.length-1;o>=0;o--){const r=t[o];n>=i[o]-1e-6&&(t.splice(o,1),i.splice(o,1),r.removeFromParent(),dr(r)!=!0&&r[Jp].push(r))}}}const Vt=x("debugphysics"),uP=x("debugworker"),G_=new c.Layers;class bo{static AllLayers=4294967295;ray;cam;screenPoint;raycaster;results;targets;recursive=!0;minDistance;maxDistance;lineThreshold;layerMask;ignore;testObject;useAcceleratedRaycast;allowSlowRaycastFallback=!0;screenPointFromOffset(e,t){this.screenPoint===void 0&&(this.screenPoint=new c.Vector2),this.screenPoint.x=e/window.innerWidth*2-1,this.screenPoint.y=-(t/window.innerHeight)*2+1}setLayer(e){G_.set(e),this.layerMask=G_}setMask(e){this.layerMask||(this.layerMask=new c.Layers);const t=this.layerMask;t?t.mask=e:this.layerMask=e}}class mg{distance;point;object;constructor(e,t,i){this.object=e,this.distance=t,this.point=i}}class Ia{static _raycasting=0;static get raycasting(){return this._raycasting>0}raycastPhysicsFast(e,t=void 0,i=1/0,n=!0){return this.context.physics.engine?.raycast(e,t,{maxDistance:i,solid:n})??null}raycastPhysicsFastAndGetNormal(e,t=void 0,i=1/0,n=!0){return this.context.physics.engine?.raycastAndGetNormal(e,t,{maxDistance:i,solid:n})??null}sphereOverlapPhysics(e,t){return this.context.physics.engine?.sphereOverlap(e,t)??null}context;engine;constructor(e){this.context=e}raycaster=new c.Raycaster;defaultRaycastOptions=new bo;targetBuffer=new Array(1);defaultThresholds={Mesh:{},Line:{threshold:-1},LOD:{},Points:{threshold:0},Sprite:{}};sphereResults=new Array;sphereMask=new c.Layers;sphere=new c.Sphere;sphereOverlap(e,t,i=!0,n=!1,o=null){if(this.sphereResults.length=0,!this.context.scene)return this.sphereResults;const r=this.sphereMask;r.enableAll(),r.disable(2);for(const a of this.context.scene.children)this.intersectSphere(a,e,t,r,this.sphereResults,i,n,o);return this.sphereResults.sort((a,l)=>a.distance-l.distance)}raycastFromRay(e,t=null){const i=t??this.defaultRaycastOptions;i.ray=e;const n=this.raycast(i);return i===this.defaultRaycastOptions&&(i.ray=void 0),n}raycast(e=null){Vt&&performance.mark("raycast.start"),e||(e=this.defaultRaycastOptions);const t=e.screenPoint??this.context.input.mousePositionRC,i=e.raycaster??this.raycaster;if(i.near=e.minDistance??0,i.far=e.maxDistance??1/0,i.params=this.defaultThresholds,e.lineThreshold===void 0&&(e.lineThreshold=-1),i.params.Line={threshold:e.lineThreshold},e.ray)i.ray.copy(e.ray);else{const a=e.cam??this.context.mainCamera;if(!a)return Vt&&console.error("Can not perform raycast - no main camera found"),this.defaultRaycastOptions.results&&(this.defaultRaycastOptions.results.length=0),this.defaultRaycastOptions.results??[];const l=this.context.xrCamera;this.context.isInXR&&l instanceof c.ArrayCamera&&l.cameras.length>0?i.setFromCamera(t,l.cameras[0]):i.setFromCamera(t,a)}let n=e.targets;n||(n=this.targetBuffer,n.length=1,n[0]=this.context.scene);let o=e.results;this.defaultRaycastOptions.results&&(this.defaultRaycastOptions.results.length=0),o||(this.defaultRaycastOptions.results||(this.defaultRaycastOptions.results=new Array),o=this.defaultRaycastOptions.results),e.layerMask!==void 0?e.layerMask instanceof c.Layers?i.layers.mask=e.layerMask.mask:i.layers.mask=e.layerMask:(i.layers.enableAll(),i.layers.disable(2)),Vt&&console.time("raycast"),o.length=0,Ia._raycasting++,this.intersect(this.raycaster,n,o,e),o.sort((a,l)=>a.distance-l.distance);const r=e.ignore;return r!==void 0&&r.length>0&&(o=o.filter(a=>!r.includes(a.object))),Ia._raycasting--,Vt&&(console.timeEnd("raycast"),console.warn("#"+this.context.time.frame+", hits:",o?.length?[...o]:"nothing"),performance.mark("raycast.end"),performance.measure("raycast","raycast.start","raycast.end")),o}intersect(e,t,i,n){for(const o of t){if(!o||o.visible===!1||B.isGizmo(o)||n.lineThreshold!==void 0&&n.lineThreshold<0&&o instanceof c.Line)continue;let r=!0;const a=o,l=a.geometry;if(o.raycastAllowed===!1&&(r=!1),r&&n.testObject){const h=n.testObject?.(o);if(h===!1)continue;h==="continue in children"&&(r=!1)}else r&&(l&&H_(l)||(r=!1));if(r){const h=i.length,d=o.raycastPreference||"lod";let u=d!=="bounds";if(n.precise===!1&&(u=!1),l&&(u||=l.getAttribute("position")?.array?.length<64),a instanceof X.GroundedSkybox&&(u=!1),d==="lod"){const p=re.getRaycastMesh(o);p&&(a.geometry=p)}if(!u&&pP(a,e,i)||(n.useAcceleratedRaycast!==!1?Zd.runMeshBVHRaycast(e,a,i,this.context,n):e.intersectObject(a,!1,i)),a.geometry=l,Vt&&i.length!=h){const p=i[i.length-1];B.DrawWireSphere(p.point,.1,7798784,1,!1),B.DrawWireMesh({mesh:o,depthTest:!1,duration:.2,color:7798784})}}n.recursive!==!1&&this.intersect(e,o.children,i,n)}return i}tempBoundingBox=new c.Box3;intersectSphere(e,t,i,n,o,r,a,l){let h=e&&e.isMesh&&e.layers.test(n)&&!B.isGizmo(e);h&&=e.visible,h&&=!(e instanceof c.Line),h&&=!(e instanceof X.GroundedSkybox);const d=e,u=d.geometry;if(h&&l){const p=l(e);if(p===!1)return;p==="continue in children"&&(h=!1)}if(u&&H_(u)||(h=!1),h){if(a){const p=this.sphere;p.center.copy(t),p.radius=i;const m=o.length;if(Zd.runMeshBVHRaycast(this.sphere,d,o,this.context,{}),m!=o.length&&!r)return}else if(u.boundingBox||u.computeBoundingBox(),u.boundingBox){d.matrixWorldNeedsUpdate&&d.updateWorldMatrix(!1,!1);const p=this.tempBoundingBox.copy(u.boundingBox).applyMatrix4(d.matrixWorld),m=this.sphere;if(m.center.copy(t),m.radius=i,m.intersectsBox(p)){const y=Y(e),_=y.distanceTo(m.center),g=new mg(e,_,y);if(o.push(g),!r)return}}}if(e.children)for(const p of e.children){const m=o.length;if(this.intersectSphere(p,t,i,n,o,r,a,l),m!=o.length&&!r)return}}}function H_(s){return!(s.index&&s.index.array.length<3)}const jo=new c.Sphere,qh=new c.Plane,fP=new c.Matrix3;function pP(s,e,t){const i=s._computeIntersections;if(!i)return!1;let n=s["_computeIntersections:Needle"];return n||(n=s["_computeIntersections:Needle"]=function(o,r,a){const l=this,h=l.geometry.boundingSphere;if(h){if(l instanceof X.GroundedSkybox){qh.setFromNormalAndCoplanarPoint(F(0,1,0),F(0,-l.position.y,0)),qh.applyMatrix4(l.matrixWorld,fP);const u=o.ray.intersectPlane(qh,F());if(u){jo.copy(h),jo.applyMatrix4(l.matrixWorld);const m=F(u).sub(o.ray.origin).length(),y=jo.radius*.5;m<y&&r.push({distance:m,point:u,object:l,normal:qh.normal.clone()})}return}jo.copy(h),jo.applyMatrix4(l.matrixWorld);const d=o.ray.intersectSphere(jo,F());if(d){const u=F(d).sub(o.ray.origin),p=u.length();if(p>jo.radius){const m=u.clone().normalize();r.push({distance:p,point:d,object:l,normal:m})}}}}),s._computeIntersections=n,e.intersectObject(s,!1,t),s._computeIntersections=i,!0}var Zd;(s=>{let e=0;function t(b,w,R,O,k){if(!w.geometry||!w.geometry.hasAttribute("position"))return!1;const L=w.geometry;if(w?.isSkinnedMesh){const D=w,j=D.bvhNeedsUpdate;if(!D.staticGenerator)l(),r&&(D.staticGenerator=new r(w),D.staticGenerator.applyWorldTransforms=!1,D.staticGeometry=D.staticGenerator.generate(),L.boundsTree=a?.call(D.staticGeometry),D.staticGeometryLastUpdate=performance.now()+Math.random()*200,D.bvhNeedsUpdate=!0);else if(L.boundsTree&&(D.autoUpdateMeshBvhInterval!==void 0&&D.autoUpdateMeshBvhInterval>=0||j===!0)){const V=performance.now(),W=V-D.staticGeometryLastUpdate,M=D.autoUpdateMeshBvhInterval??100;(j||W>M)&&(Vt&&console.warn(`Physics: updating skinned mesh bvh for ${w.name} after ${W.toFixed(2)}ms`),D.bvhNeedsUpdate=!1,D.staticGeometryLastUpdate=V,D.staticGenerator?.generate(D.staticGeometry),L.boundsTree.refit())}}else if(!L.boundsTree){d||v();let D=!0;if((O.xr||L[y]===!1||L.getAttribute("position")?.isInterleavedBufferAttribute||L.index&&L.index?.isInterleavedBufferAttribute||e>10)&&(D=!1),D&&p){if(L[m]===void 0){let j=null;if(g.length>0){const V=g.shift();V&&!V.running&&(j=V)}if(!j&&_.length<3)try{uP&&console.warn("[GenerateMeshBVHWorker] Creating worker with import.meta.url:",typeof document>"u"?require("url").pathToFileURL(__filename).href:ya&&ya.tagName.toUpperCase()==="SCRIPT"&&ya.src||new URL("needle-engine.bundle-CaHKqc30.umd.cjs",document.baseURI).href),j=new p,_.push(j)}catch(V){V instanceof DOMException&&V.name==="SecurityError"?(console.warn("Failed to create MeshBVH worker, falling back to main thread generation. This can happen when running from file://, if the browser does not support workers or if the browser is blocking workers for other reasons."),console.debug(V),e+=10):(console.error("Failed to create MeshBVH worker. Please see below for more details:"),console.log(V)),e++}if(j!=null&&!j.running){const V=w.name;Vt&&console.log("<<<< worker start",V,j),L[m]="queued",performance.mark("bvh.create.start");const W=L.clone();try{j.generate(W).then(M=>{L[m]="done",L.boundsTree=M}).catch(M=>{L[m]="failed - "+M?.message,L[y]=!1,Vt&&console.error("Failed to generate mesh bvh on worker",M)}).finally(()=>{Vt&&console.log(">>>>> worker done",V,{hasBoundsTre:L.boundsTree!=null}),g.push(j),W.dispose(),performance.mark("bvh.create.end"),performance.measure("bvh.create (worker)","bvh.create.start","bvh.create.end")})}catch(M){console.error("Failed to generate mesh bvh on worker",M)}}else Vt&&console.warn("No worker available")}}else(!u||!D)&&(l(),o&&(performance.mark("bvh.create.start"),L.boundsTree=new o(L),performance.mark("bvh.create.end"),performance.measure("bvh.create","bvh.create.start","bvh.create.end")))}if(b instanceof c.Raycaster){const D=b,j=w.raycast;if(L.boundsTree)l(),n&&(w.acceleratedRaycast||(w.acceleratedRaycast=n.bind(w),Vt&&console.debug(`Physics: bind acceleratedRaycast fn to "${w.name}"`)),w.raycast=w.acceleratedRaycast);else if(Vt&&console.warn("No bounds tree found for mesh",w.name,{workerTask:L[m],hasAcceleratedRaycast:n!=null}),k.allowSlowRaycastFallback===!1&&(L.getAttribute("position")?.array?.length??0)>2e3)return Vt&&console.warn("Skipping raycast because no bounds tree is available and allowSlowRaycastFallback is false"),!1;const V=D.firstHitOnly;return D.firstHitOnly=!1,D.intersectObject(w,!1,R),D.firstHitOnly=V,w.raycast=j,!0}else if(b instanceof c.Sphere){const D=L.boundsTree;if(D){const j=b;if(h.copy(w.matrixWorld).invert(),j.applyMatrix4(h),D.intersectsSphere(j)){const W=Y(w),M=W.distanceTo(j.center),N=new mg(w,M,W);R.push(N)}}return!0}return!1}s.runMeshBVHRaycast=t;let i=!1,n=null,o=null,r=null,a=null;function l(){i||(i=!0,Promise.resolve().then(()=>require("./vendor-BlyEaMTL.umd.cjs")).then(b=>b.index$1).then(b=>{n=b.acceleratedRaycast,o=b.MeshBVH,r=b.StaticGeometryGenerator,a=b.computeBoundsTree}).catch(b=>{(Vt||A())&&console.error("Failed to load BVH library...",b.message)}))}const h=new c.Matrix4;let d=!1,u=!1,p=null;const m=Symbol("Needle:MeshBVH-Worker"),y=Symbol("Needle:MeshBVH-CanUseWorker"),_=[],g=[];function v(){d=!0,u=!0,Promise.resolve().then(()=>RA).then(b=>{p=b.GenerateMeshBVHWorker}).catch(b=>{Vt||A()?console.warn("Failed to setup mesh bvh worker"):console.debug("Failed to setup mesh bvh worker",b)}).finally(()=>{u=!1})}})(Zd||(Zd={}));const q_=Symbol("gltf-loader-internal-usage-tracker"),mP=x("debugusers");class xa{get name(){return"NEEDLE_internal_usage_tracker"}static isLoading(e){return xa._loadingProcesses>0}static _loadingProcesses=0;parser;_getDependency;_loadingId;_loadedObjects=new Set;constructor(e){this.parser=e,this._getDependency=this.parser.getDependency,this._loadingId=Date.now().toString()}beforeRoot(){xa._loadingProcesses++;const e=this,t=this._getDependency;return this.parser.getDependency=function(i,n){const o=t.call(this,i,n);return o.then(r=>(r&&(e._loadedObjects.add(r),r[q_]=e._loadingId),r)),o},null}afterRoot(e){xa._loadingProcesses--,this.parser.getDependency=this._getDependency;for(const t of this._loadedObjects)delete t[q_],t instanceof c.Object3D&&(t.parent||t instanceof c.Mesh&&setTimeout(()=>{mP&&console.warn("> GLTF LOADER: Mesh not used in scene!",t),t.material=null,t.geometry=null},1e3));return null}}class V0{constructor(){window.addEventListener("unhandledrejection",e=>{if(e.defaultPrevented)return;const t=e?.reason?.path;if(t){const i=t[0];i&&i.tagName==="IMG"&&(console.warn(`Could not load image:
880
880
  `+i.src),e.preventDefault())}})}}const Pu=x("trackresources");function $0(){return Pu==="dispose"}let br=!0;Pu===0&&(br=!1);function gP(s){br=s}function W0(){return br}const G0=Symbol("disposable");function H0(s,e){s&&(s[G0]=e,nr&&console.warn("Set disposable",e,s))}const q0=Symbol("disposed");function yP(s){return s[q0]===!0}function we(s){if(s){if(s[G0]===!1){nr&&console.warn("Object is marked as not disposable",s);return}if(typeof s=="object"&&(s[q0]=!0),s instanceof c.Scene)we(s.environment),we(s.background),we(s.customDepthMaterial),we(s.customDistanceMaterial);else if(s instanceof c.SkinnedMesh)we(s.geometry),we(s.material),we(s.skeleton),we(s.bindMatrix),we(s.bindMatrixInverse),we(s.customDepthMaterial),we(s.customDistanceMaterial),s.visible=!1;else if(s instanceof c.Mesh)we(s.geometry),we(s.material),we(s.customDepthMaterial),we(s.customDistanceMaterial),s.visible=!1;else if(s instanceof c.Object3D)s.visible=!1;else if(s instanceof c.BufferGeometry){qr(s);for(const e of Object.keys(s.attributes)){const t=s.attributes[e];we(t)}}else if(s instanceof c.BufferAttribute||s instanceof c.InterleavedBufferAttribute)nr&&console.warn("BufferAttribute dispose not supported",s.count);else if(s instanceof Array)for(const e of s)e instanceof c.Material&&we(e);else if(s instanceof c.Material){qr(s);for(const t of Object.keys(s)){const i=s[t];i instanceof c.Texture&&we(i)}const e=s.uniforms;if(e)for(const t of Object.keys(e)){const i=e[t];i instanceof c.Texture?we(i):i instanceof c.Uniform&&we(i.value)}}else s instanceof c.Texture?(qr(s),qr(s.source),s.source?.data instanceof ImageBitmap&&qr(s.source.data)):s instanceof c.Skeleton?(qr(s.boneTexture),s.boneTexture=null):s instanceof c.Bone||!(s instanceof c.Object3D)&&nr&&console.warn("Unknown object type",s)}}function qr(s){s&&((nr||$0()||Pu)&&console.warn("🧨 FREE",s),s instanceof ImageBitmap||"dispose"in s&&typeof s.dispose=="function"&&s.dispose())}function _P(s){}const bP=new Set;function gg(s,e,t=null,i){if(i||(i=bP,i.clear()),!s)return i;const n=s[Sc];if(n)for(const o of n)i.has(o)||t?.call(null,o)!==!1&&(i.add(o),e&&gg(o,!0,t,i));return i}function vP(s){return s[zl]}const nr=x("debugresourceusers")||x("debugmemory"),Sc=Symbol("needle-resource-users"),zl=Symbol("needle-resource-users-count");function Bt(s,e){yu(s,e,function(t,i){br&&!Ia.raycasting&&(Jd(Sc,this,t,!1),Jd(Sc,this,i,!0))})}br&&(Bt(c.Mesh.prototype,"material"),Bt(c.Mesh.prototype,"geometry"),Bt(c.Material.prototype,"map"),Bt(c.Material.prototype,"bumpMap"),Bt(c.Material.prototype,"alphaMap"),Bt(c.Material.prototype,"normalMap"),Bt(c.Material.prototype,"displacementMap"),Bt(c.Material.prototype,"roughnessMap"),Bt(c.Material.prototype,"metalnessMap"),Bt(c.Material.prototype,"emissiveMap"),Bt(c.Material.prototype,"specularMap"),Bt(c.Material.prototype,"envMap"),Bt(c.Material.prototype,"lightMap"),Bt(c.Material.prototype,"aoMap"),Bt(c.Material.prototype,"gradientMap"));function wP(s){if(br===!1)return;const e=s[Sc];if(e)for(const t of e)Jd(Sc,t,s,!1)}br&&yu(c.Material.prototype,"dispose",function(){wP(this)});let em=0;function Jd(s,e,t,i){if(em>0)return;if(Array.isArray(t)){for(const o of t)Jd(s,e,o,i);return}if(!t)return;let n=t[s];if(n||(n=new Set),i){if(e&&!n.has(e)){n.add(e);let o=t[zl]||0;o+=1,t[zl]=o,nr&&console.warn(`🟢 Added user of "${t.type}"`,e,t,o,"users:",n)}}else if(e&&n.has(e)){n.delete(e);let o=t[zl]||0;o>0&&(o-=1,t[zl]=o),nr&&console.warn(`🔴 Removed user of "${t.type}"`,e,t,o,"users:",n),o<=0&&(xa.isLoading(t)||(Pu&&console.warn(`🔴 Removed all user of "${t.type}"`,t),$0()&&we(t)))}t[s]=n}try{yu(c.WebGLRenderer.prototype,"render",function(){em++},function(){em--})}catch(s){console.warn("Could not wrap WebGLRenderer.render",s)}const Cc=Symbol("NEEDLE_NEED_UPDATE_INSTANCE"),X0=Symbol("isUsingInstancing"),Q0=Symbol("instancingRenderer"),Nl=Symbol("instancingAutoUpdateBounds");class Ni{static isUsingInstancing(e){return e[X0]===!0}static getRenderer(e){return e[Q0]||null}setAutoUpdateBounds(e,t){const i=Ni.getRenderer(e);i&&(i[Nl]=t)}static markDirty(e,t=!0){if(e&&(this.isUsingInstancing(e)&&(e[Cc]=!0,e.matrixWorldNeedsUpdate=!0),t))for(const i of e.children)Ni.markDirty(i,!0)}}const Y0=new Map;function K0(s,e){if(!s)return;if(!e){console.warn("No prototype found",s,s.prototype,s.constructor);return}const t=Y0.get(e);t&&t.apply(s)}function yg(s){const e=xP(s.prototype);Y0.set(s,e)}function xP(s){return new SP(s)}class SP{$symbol;extensions;descriptors;constructor(e){this.$symbol=Symbol("prototype-extension"),this.extensions=Object.keys(e),this.descriptors=new Array;for(let t=0;t<this.extensions.length;t++){const i=this.extensions[t],n=Object.getOwnPropertyDescriptor(e,i);n&&this.descriptors.push(n)}}apply(e){if(!e[this.$symbol]){e[this.$symbol]=!0;for(let t=0;t<this.extensions.length;t++){const i=this.extensions[t],n=this.descriptors[t];n&&Object.defineProperty(e,i,n)}}}}function Ou(s){s&&s.isObject3D===!0&&K0(s,c.Object3D)}let X_=!1;function CP(){if(X_)return;if(X_=!0,Xm.experimentalSmartHierarchyUpdate){const i=c.Object3D.prototype.add;c.Object3D.prototype.add=function(...r){return Xf(),i.apply(this,r)};const n=c.Object3D.prototype.attach;c.Object3D.prototype.attach=function(...r){return Xf(),n.apply(this,r)};const o=c.Object3D.prototype.remove;c.Object3D.prototype.remove=function(...r){return Xf(),o.apply(this,r)}}c.Object3D.prototype.SetActive=function(i){this.visible=i},c.Object3D.prototype.setActive=function(i){this.visible=i},c.Object3D.prototype.destroy=function(){bi(this)},c.Object3D.prototype.addComponent=function(i,n){return hn(this,i,n)},c.Object3D.prototype.addNewComponent=function(i,n){return hn(this,i,n)},c.Object3D.prototype.removeComponent=function(i){return vg(this,i)},c.Object3D.prototype.getOrAddComponent=function(i,n){return Xc(this,i,n)},c.Object3D.prototype.getComponent=function(i){return vr(this,i)},c.Object3D.prototype.getComponents=function(i,n){return Qc(this,i,n)},c.Object3D.prototype.getComponentInChildren=function(i,n=!1){return Yc(this,i,n)},c.Object3D.prototype.getComponentsInChildren=function(i,n){return Wa(this,i,n)},c.Object3D.prototype.getComponentInParent=function(i,n=!1){return Pc(this,i,n)},c.Object3D.prototype.getComponentsInParent=function(i,n){return Eu(this,i,n)},Object.getOwnPropertyDescriptor(c.Object3D.prototype,"activeSelf")||Object.defineProperty(c.Object3D.prototype,"activeSelf",{get:function(){return $a(this)},set:function(i){sc(this,i)}}),Object.getOwnPropertyDescriptor(c.Object3D.prototype,"raycastAllowed")||Object.defineProperty(c.Object3D.prototype,"raycastAllowed",{get:function(){return this.userData&&this.userData.raycastAllowed!==!1},set:function(i){const n=this;n.userData||(n.userData={}),n.userData.raycastAllowed=i}}),Object.getOwnPropertyDescriptor(c.Object3D.prototype,"worldPosition")||Object.defineProperty(c.Object3D.prototype,"worldPosition",{get:function(){return this instanceof X.TransformControlsGizmo?Y(this.object):Y(this)},set:function(i){at(this,i)}}),Object.getOwnPropertyDescriptor(c.Object3D.prototype,"worldQuaternion")||Object.defineProperty(c.Object3D.prototype,"worldQuaternion",{get:function(){return this instanceof X.TransformControlsGizmo?pe(this.object):pe(this)},set:function(i){dn(this,i)}}),Object.getOwnPropertyDescriptor(c.Object3D.prototype,"worldRotation")||Object.defineProperty(c.Object3D.prototype,"worldRotation",{get:function(){return mu(this)},set:function(i){Rv(this,i)}}),Object.getOwnPropertyDescriptor(c.Object3D.prototype,"worldScale")||Object.defineProperty(c.Object3D.prototype,"worldScale",{get:function(){return je(this)},set:function(i){Ma(this,i)}});const s=new c.Matrix4,e=new c.Vector3(0,0,0),t=new c.Vector3(0,1,0);Object.getOwnPropertyDescriptor(c.Object3D.prototype,"worldForward")||Object.defineProperty(c.Object3D.prototype,"worldForward",{get:function(){return F().set(0,0,1).applyQuaternion(pe(this))},set:function(i){const n=ei().setFromRotationMatrix(s.lookAt(e.set(0,0,0),i,t.set(0,1,0)));this.worldQuaternion=n}}),Object.getOwnPropertyDescriptor(c.Object3D.prototype,"worldRight")||Object.defineProperty(c.Object3D.prototype,"worldRight",{get:function(){return F().set(1,0,0).applyQuaternion(pe(this))}}),Object.getOwnPropertyDescriptor(c.Object3D.prototype,"worldUp")||Object.defineProperty(c.Object3D.prototype,"worldUp",{get:function(){return F().set(0,1,0).applyQuaternion(pe(this))}}),Object.getOwnPropertyDescriptor(c.Object3D.prototype,"contains")||Object.defineProperty(c.Object3D.prototype,"contains",{value:function(i){if(!i)return!1;if(this===i)return!0;for(const n of this.children)if(n.contains(i))return!0;return!1}}),yg(c.Object3D)}const wd=x("debuggetcomponent"),sr=x("debuginstantiate");class gn{idProvider;parent;keepWorldPosition;position;rotation;scale;visible;context;components;clone(){const e=new gn;return e.idProvider=this.idProvider,e.parent=this.parent,e.keepWorldPosition=this.keepWorldPosition,e.position=Array.isArray(this.position)?[...this.position]:this.position?.clone(),e.rotation=Array.isArray(this.rotation)?[...this.rotation]:this.rotation?.clone(),e.scale=Array.isArray(this.scale)?[...this.scale]:this.scale?.clone(),e.visible=this.visible,e.context=this.context,e.components=this.components,e}cloneAssign(e){this.idProvider=e.idProvider,this.parent=e.parent,this.keepWorldPosition=e.keepWorldPosition,this.position=Array.isArray(e.position)?[...e.position]:e.position?.clone(),this.rotation=Array.isArray(e.rotation)?[...e.rotation]:e.rotation?.clone(),this.scale=Array.isArray(e.scale)?[...e.scale]:e.scale?.clone(),this.visible=e.visible,this.context=e.context,this.components=e.components}}function $a(s){return s.visible}function sc(s,e){return typeof e=="number"&&(e=e>.5),s.visible=e,s.visible}function Z0(s){return s[jn]||ku(s)}function J0(s,e){s[X0]=e}function ku(s){return Ni.isUsingInstancing(s)}function _g(s,e){return ka(s,e,!0,!0)}const ew=Symbol("isDestroyed");function dr(s){return s[ew]}function tw(s,e){s[ew]=e}const tm=Symbol("isDontDestroy");function na(s,e=!0){s[tm]=e}const xd=[],Sd=[];function bi(s,e=!0,t=!1){xd.length=0,Sd.length=0,im(s,e,!0);for(const i of xd)i.gameObject=null,i.context=null;for(const i of Sd)tw(i,!0),t&&we(i);Sd.length=0,xd.length=0}function im(s,e=!0,t=!0){if(s==null)return;const i=s;if(i.isComponent){if(i[tm])return;xd.push(i);const r=i.gameObject;i.__internalDisable(),i.__internalDestroy(),i.gameObject=r;return}if(s[tm])return;const n=s;wd&&console.log(n),Sd.push(n);const o=n.userData?.components;if(o!=null&&Array.isArray(o)){let r=o.length;for(let a=0;a<o.length;a++){const l=o[a];im(l,e,!1),o.length<r&&(r=o.length,a--)}}if(e&&n.children)for(const r of n.children)im(r,e,!1);t&&n.removeFromParent()}function ur(s,e,t=!0){return iw(s,e,t)}function*Mu(s,e,t=!1,i=999,n=0){if(s?.userData.components&&!(n>i)){for(const o of s.userData.components)e&&o?.isComponent===!0&&o instanceof e?yield o:yield o;if(t===!0)for(const o of s.children)yield*Mu(o,e,!0,i,n+1)}}function iw(s,e,t,i=0){if(s){if(s.isObject3D,i>1e3){console.warn("Failed to iterate components: too many levels");return}if(s.userData?.components)for(let n=0;n<s.userData.components.length;n++){const o=s.userData.components[n];if(o?.isComponent===!0){const r=e(o);if(r!==void 0)return r}}if(t&&s.children){const n=i+1;for(let o=0;o<s.children.length;o++){const r=s.children[o];if(!r)continue;const a=iw(r,e,t,n);if(a!==void 0)return a}}}}function ho(s,e){if("isAssetReference"in s)return s.instantiate(e??void 0);let t=null;e!=null&&(e.x!==void 0?(t=new gn,t.position=e):t=e);let i=U.Current;t?.context&&(i=t.context),wd&&i.alias&&console.log("context",i.alias),t&&!t.idProvider&&(t.idProvider=new xt(Date.now()));const n=[],o={},r={},a=nw(i,s,t,n,o,r);a&&(kP(a,o),OP(r,o)),wd&&($d(s,!0),$d(a,!0));const l={};if(t?.components!==!1){for(const h in n){const d=n[h],u=d.guid;t&&t.idProvider&&(d.guid=t.idProvider.generateUUID(),l[u]=d.guid,wd&&console.log(d.name,d.guid)),Cu(d,i),d.__internalNewInstanceCreated&&d.__internalNewInstanceCreated()}for(const h in n){const d=n[h];d.resolveGuids&&d.resolveGuids(l),d.enabled!==!1&&(d.enabled=!0)}eu(i)}return a}function nw(s,e,t,i,n,o){if(!e||e[pi])return null;const r=e.userData;e.userData={};const a=e.children;e.children=[];const l=e.clone(!1);if(Ou(l),e.userData=r,e.children=a,n[e.uuid]={original:e,clone:l},sr&&console.log("ADD",e,l),e.type==="SkinnedMesh"&&(o[e.uuid]={original:e,clone:l}),t?.visible!==void 0&&(l.visible=t.visible),t?.idProvider){l.uuid=t.idProvider.generateUUID();const d=l;d&&(d.guid=l.uuid)}e.animations&&e.animations.length>0&&(l.animations=[...e.animations]);const h=e.parent;if(h&&h.add(l),t?.position)if(Array.isArray(t.position)){const d=new c.Vector3;d.fromArray(t.position),l.worldPosition=d}else l.worldPosition=t.position;else l.position.copy(e.position);if(t?.rotation){if(t.rotation instanceof c.Quaternion)l.worldQuaternion=t.rotation;else if(t.rotation instanceof c.Euler)l.worldQuaternion=ei().setFromEuler(t.rotation);else if(Array.isArray(t.rotation)){const d=new c.Euler;d.fromArray(t.rotation),l.worldQuaternion=ei().setFromEuler(d)}}else l.quaternion.copy(e.quaternion);if(t?.scale)if(Array.isArray(t.scale)){const d=new c.Vector3;d.fromArray(t.scale),t.scale=d}else l.scale.copy(t.scale);else l.scale.copy(e.scale);if(t?.parent&&t.parent!=="scene"){let d=null;if(typeof t.parent=="string"?d=ka(t.parent,s.scene,!0):d=t.parent,d){const u=t.keepWorldPosition===!0?d.attach:d.add;u?u.call(d,l):console.error("Invalid parent object",d,"received when instantiating:",e)}else console.warn("could not find parent:",t.parent)}for(const[d,u]of Object.entries(e.userData))d!=="components"&&(l.userData[d]=u);if(e.userData?.components){const d=e.userData.components,u=[];l.userData.components=u;for(let p=0;p<d.length;p++){const m=d[p],y=new m.constructor;PP(m,y),m[ec]!==void 0&&(y[ec]=m[ec]),u.push(y),y.gameObject=l,i.push(y),n[m.guid]={original:m,clone:y},gu.dispatchComponentLifecycleEvent("component-added",y)}}t&&(t.position=void 0,t.rotation=void 0,t.scale=void 0,t.parent=void 0,t.visible=void 0);for(const d in e.children){const u=e.children[d],p=nw(s,u,t,i,n,o);p&&(n[p.uuid]={original:u,clone:p},l.add(p))}return l}function PP(s,e,t){Ra(e,s,void 0,{})}function OP(s,e){for(const t in s){const i=s[t],n=i.original,o=n.skeleton,r=i.clone;if(!o){console.warn("Skinned mesh has no skeleton?",i);continue}const a=o.bones,l=r.skeleton.clone();r.skeleton=l,r.bindMatrix.clone().copy(n.bindMatrix),r.bindMatrixInverse.copy(n.bindMatrixInverse);const h=[];l.bones=h;for(let d=0;d<a.length;d++){const u=a[d],m=e[u.uuid].clone;h.push(m)}}for(const t in s){const i=s[t].clone;i.skeleton.update(),i.bind(i.skeleton,i.bindMatrix),i.updateMatrixWorld(!0)}}function kP(s,e){for(const t in e){const n=e[t].clone;if(n?.isObject3D&&n?.userData?.components)for(let o=0;o<n.userData.components.length;o++){const r=n.userData.components[o],a=Object.entries(r);for(const[l,h]of a)if(Array.isArray(h)){const d=[];r[l]=d;for(let u=0;u<h.length;u++){const p=h[u];if(typeof p!="object"){d.push(p);continue}const m=Q_(r,l,p,e);m!==void 0?(sr&&console.log("Found new instance for",l,p,"->",m),d.push(m)):(sr&&console.warn("Could not find new instance for",l,p),d.push(p))}}else if(typeof h=="object"){const d=Q_(r,l,h,e);d!==void 0?r[l]=d:sr&&console.warn("Could not find new instance for",l,h)}}}}function Q_(s,e,t,i){if(t!=null)if(t.isComponent===!0){const n=t.gameObject;if(n){const o=n.uuid,r=i[o]?.clone;if(!r){sr&&console.log("reference did not change",e,s,t);return}const a=n.userData.components.indexOf(t);if(a>=0&&r.isObject3D)return sr&&console.log(e,o),r.userData.components[a];console.warn("could not find component",e,t)}}else if(t.isObject3D===!0){if(e==="gameObject")return;const n=t;if(n){const o=n.uuid,r=i[o]?.clone;if(r)return sr&&console.log(e,"old",t,"new",r),r}}else{if(t.isVector4||t.isVector3||t.isVector2||t.isQuaternion||t.isEuler)return t.clone();if(t.isColor===!0)return t.clone();if(t.isEventList===!0)return t.__internalOnInstantiate(i)}}function oc(s,e){try{e||s()}catch(t){return console.error(t),!1}return!0}const nm=x("debugnewscripts"),MP=x("debughierarchy"),Ce=[];function EP(){return Ce.length>0}function eu(s){if(nm&&console.log("Register new components",s.new_scripts.length,[...s.new_scripts],s.alias?"element: "+s.alias:s.hash,s),s.new_scripts_pre_setup_callbacks.length>0){for(const e of s.new_scripts_pre_setup_callbacks)e&&e();s.new_scripts_pre_setup_callbacks.length=0}if(!(s.new_scripts.length<=0)){Ce.length=0,s.new_scripts.length>0&&Ce.push(...s.new_scripts),s.new_scripts.length=0;for(let e=0;e<Ce.length;e++)try{const t=Ce[e];if(t.isComponent!==!0){(A()||nm)&&console.error(`Registered script is not a Needle Engine component.
881
881
  The script will be ignored. Please make sure your component extends "Behaviour" imported from "@needle-tools/engine"
882
882
  `,t),Ce.splice(e,1),e--;continue}if(t.destroyed)continue;if(!t.gameObject){console.warn(`Component can not be initialized: no GameObject assigned.
@@ -997,7 +997,7 @@ Consider registering a custom loader via the 'onCreateCustomModelLoader' callbac
997
997
  Content-Type: "${t.headers.get("content-type")}"
998
998
  "Text: "${o}"
999
999
  Binary:`,i)}else Me&&console.debug("Could not determine file type from binary data");return"unknown"}const tp=x("debugstencil");function Pk(s,e){return(s&1<<e.layer)!=0}const Ok=Symbol("stencils");class io{get name(){return"NEEDLE_render_objects"}static stencils={};static applyStencil(e){if(!e)return;const t=e.sourceId;if(tp&&console.log(t,io.stencils),!t)return;const i=io.stencils[t];if(i)for(let n=i.length-1;n>=0;n--){const o=i[n];if(Pk(o.layer,e)){tp&&console.log(o),setTimeout(()=>{yi()&&ku(e.gameObject)&&(fe("Stencil not supported on instanced objects"),console.warn("Stencil not supported on instanced objects",e))},500);for(let r=0;r<e.sharedMaterials.length;r++){let a=e.sharedMaterials[r];a&&(a=a.clone(),a[Ok]=!0,a.stencilWrite=!0,a.stencilWriteMask=255,a.stencilFuncMask=255,a.stencilRef=o.value,a.stencilFunc=o.compareFunc,a.stencilZPass=o.passOp,a.stencilFail=o.failOp,a.stencilZFail=o.zFailOp,e.sharedMaterials[r]=a)}e.gameObject.renderOrder=o.event*1e3+o.index*50;break}}}parser;source;constructor(e,t){this.parser=e,this.source=t}afterRoot(e){const t=this.parser.json.extensions;if(t){const i=t[Mk];if(i){tp&&console.log(i);const n=i.stencil;if(n&&Array.isArray(n))for(const o of n){const r={...o};r.compareFunc=kk(r.compareFunc),r.passOp=ip(r.passOp),r.failOp=ip(r.failOp),r.zFailOp=ip(r.zFailOp),io.stencils[this.source]||(io.stencils[this.source]=[]),io.stencils[this.source].push(r)}}}return null}}function ip(s){switch(s){case 0:return c.KeepStencilOp;case 1:return c.ZeroStencilOp;case 2:return c.ReplaceStencilOp;case 3:return c.IncrementStencilOp;case 4:return c.DecrementStencilOp;case 6:return c.IncrementWrapStencilOp;case 7:return c.DecrementWrapStencilOp;case 5:return c.InvertStencilOp}return 0}function kk(s){switch(s){case 1:return c.NeverStencilFunc;case 2:return c.LessStencilFunc;case 3:return c.EqualStencilFunc;case 4:return c.LessEqualStencilFunc;case 5:return c.GreaterStencilFunc;case 6:return c.NotEqualStencilFunc;case 7:return c.GreaterEqualStencilFunc;case 8:return c.AlwaysStencilFunc}return c.NeverStencilFunc}const Mk="NEEDLE_render_objects";class Ek{objectToBlock=new WeakMap;meshToOwners=new WeakMap;meshToOriginalCallbacks=new WeakMap;getBlock(e){return this.objectToBlock.get(e)}setBlock(e,t){this.objectToBlock.set(e,t)}deleteBlock(e){this.objectToBlock.delete(e)}isHooked(e,t){return this.meshToOwners.get(e)?.has(t)??!1}addHook(e,t){let i=this.meshToOwners.get(e);i||(i=new Set,this.meshToOwners.set(e,i)),i.add(t)}removeHook(e,t){const i=this.meshToOwners.get(e);i&&(i.delete(t),i.size===0&&this.meshToOwners.delete(e))}getOriginalCallbacks(e){return this.meshToOriginalCallbacks.get(e)}setOriginalCallbacks(e,t){this.meshToOriginalCallbacks.set(e,t)}}const ps=new Ek;class ys{_overrides=[];_defines={};_object=null;get object(){return this._object}constructor(e=null){this._object=e}static get(e){let t=ps.getBlock(e);return t||(t=new ys(e),ps.setBlock(e,t),Ak(e,t)),t}static hasOverrides(e){const t=ps.getBlock(e);return t?t.hasOverrides():!1}dispose(){this._object&&ps.deleteBlock(this._object),this._overrides=[],this._object=null}setOverride(e,t,i){const n=this._overrides.find(o=>o.name===e);n?(n.value=t,n.textureTransform=i):this._overrides.push({name:e,value:t,textureTransform:i})}getOverride(e){return this._overrides.find(t=>t.name===e)}removeOveride(e){const t=this._overrides.findIndex(i=>i.name===e);t>=0&&this._overrides.splice(t,1)}clearAllOverrides(){this._overrides=[]}get overrides(){return this._overrides}hasOverrides(){return this._overrides.length>0}setDefine(e,t){this._defines[e]=t}clearDefine(e){this._defines[e]=void 0}getDefines(){return this._defines}getCacheKey(){const e=[],t=Object.keys(this._defines).sort();for(const i of t){const n=this._defines[i];n!==void 0&&e.push(`d:${i}=${n}`)}for(const i of this._overrides){if(i.value===null)continue;let n="";if(i.value instanceof c.Texture){if(n=i.value.uuid||"texture",i.textureTransform){const o=i.textureTransform;o.offset&&(n+=`;to:${o.offset.x},${o.offset.y}`),o.repeat&&(n+=`;tr:${o.repeat.x},${o.repeat.y}`)}}else if(Array.isArray(i.value))n=i.value.join(",");else if(i.value&&typeof i.value=="object"&&"r"in i.value){const o=i.value;n=`${o.r},${o.g},${o.b},${o.a!==void 0?o.a:""}`}else if(i.value&&typeof i.value=="object"&&"x"in i.value){const o=i.value;n=`${o.x},${o.y}${o.z!==void 0?`,${o.z}`:""}${o.w!==void 0?`,${o.w}`:""}`}else n=String(i.value);e.push(`${i.name}=${n}`)}return e.join(";")}}const Td=Symbol("originalValues"),Ad=Symbol("savedTextureTransforms");function jw(s){let e=ps.getBlock(s);if(e)return{block:e,owner:s};if(s.parent&&s.parent.type==="Group"&&(e=ps.getBlock(s.parent),e))return{block:e,owner:s.parent}}const Sa=Symbol("beforeRenderingFlag"),fm=new WeakMap,pm=new WeakMap,Rk=function(s,e,t,i){const n=ps.getBlock(s);if(n&&n.hasOverrides()){const o=n.getOverride("transmission")?.value,r=n.getOverride("transparent")?.value;o!==void 0&&typeof o=="number"&&"transmission"in t&&o!==t.transmission&&(pm.set(this,t.transmission),t.transmission=o),r!==void 0&&typeof r=="boolean"&&r!==t.transparent&&(fm.set(this,t.transparent),t.transparent=r)}},Tk=function(s,e,t,i){const n=fm.get(s);n!==void 0&&(fm.delete(s),t.transparent=n);const o=pm.get(s);o!==void 0&&(pm.delete(s),t.transmission=o)},yb=function(s,e,t,i,n,o){const r=this.material;if(!r)return;if(Array.isArray(r)){if(!r.includes(n))return}else if(r!==n)return;this[Sa]===void 0&&(this[Sa]=new WeakSet),this[Sa].add(n);const a=jw(this);if(!a)return;const{block:l,owner:h}=a,d=l.overrides,u=n,p=l.getDefines(),m=Object.keys(p);if(m.length>0){u.defines||(u.defines={});for(const g of m){const v=p[g];v!==void 0&&(u.defines[g]=v)}}if(d.length===0&&m.length===0)return;let y=m.length>0;u[Td]||(u[Td]=[]);const _=u[Td];for(const g of d){if(g.value===null)continue;const v=u[g.name],b=_.find(w=>w.name===g.name);if(b?b.value=v:_.push({name:g.name,value:v}),!y&&!!v!=!!g.value&&(y=!0),u[g.name]=g.value,g.textureTransform&&g.value instanceof c.Texture){const w=g.value;u[Ad]||(u[Ad]=[]),u[Ad].push({name:g.name,offsetX:w.offset.x,offsetY:w.offset.y,repeatX:w.repeat.x,repeatY:w.repeat.y});const R=g.textureTransform;R.offset&&w.offset.copy(R.offset),R.repeat&&w.repeat.copy(R.repeat)}}y&&(u.needsUpdate=!0),u._forceRefresh=!0},_b=function(s,e,t,i,n,o){if(this[Sa]===void 0||!this[Sa].has(n))return;this[Sa].delete(n);const r=jw(this);if(!r)return;const{block:a,owner:l}=r,h=a.overrides,d=n,u=d[Td],p=a.getDefines(),m=Object.keys(p);let y=!1;if(m.length>0&&d.defines){for(const g of m)delete d.defines[g];y=!0}if(h.length===0){y&&(d.needsUpdate=!0,d._forceRefresh=!0);return}if(!u)return;const _=d[Ad];if(_&&_.length>0){for(const g of _){const v=h.find(b=>b.name===g.name);v?.value instanceof c.Texture&&(v.value.offset.set(g.offsetX,g.offsetY),v.value.repeat.set(g.repeatX,g.repeatY))}_.length=0}for(const g of h){const v=u.find(b=>b.name===g.name);v&&(!y&&!!g.value!=!!v.value&&(y=!0),d[g.name]=v.value)}y&&(d.needsUpdate=!0),d._forceRefresh=!0};function Ak(s,e){s.type==="Group"?s.children.forEach(t=>{(t.type==="Mesh"||t.type==="SkinnedMesh")&&bb(t,s,e)}):(s.type==="Mesh"||s.type==="SkinnedMesh")&&bb(s,s,e)}function bb(s,e,t){if(!ps.isHooked(s,e)){if(ps.addHook(s,e),s["needle:materialPropertyBlock"]=t,!s.onBeforeRender)s.onBeforeRender=yb;else{const i=s.onBeforeRender;s.onBeforeRender=function(n,o,r,a,l,h){i.call(this,n,o,r,a,l,h),yb.call(this,n,o,r,a,l,h)}}if(!s.onAfterRender)s.onAfterRender=_b;else{const i=s.onAfterRender;s.onAfterRender=function(n,o,r,a,l,h){_b.call(this,n,o,r,a,l,h),i.call(this,n,o,r,a,l,h)}}s.onBeforeRenderListPush=Rk,s.onAfterRenderListPush=Tk}}var Lk=Object.defineProperty,Dk=Object.getOwnPropertyDescriptor,Wu=(s,e,t,i)=>{for(var n=i>1?void 0:i?Dk(e,t):e,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&Lk(e,t,n),n};const Xr=x("debugreflectionprobe"),vb=x("noreflectionprobe");let Bo=null;const Ik=Symbol("reflectionProbeKey"),ah=class an extends E{static _probes=new Map;static testBox=new c.Box3;static isUsingReflectionProbe(e){return!!e[Ik]}static onEnabled=new ne;static onDisabled=new ne;static get(e,t,i,n){if(!e||e.isObject3D!==!0||vb)return null;const o=an._probes.get(t);if(o){for(const r of o)if(r.__didAwake||r.__internalAwake(),r.activeAndEnabled){if(n){if(r.gameObject===n)return r}else if(r.isInBox(e))return Xr&&console.log("Found reflection probe",e.name,r.name),r}}return Xr&&console.debug("Did not find reflection probe",e.name,i,e),null}_texture;_textureUrlInFlight;set texture(e){if(this._texture!==e){if(typeof e=="string"){Xr&&console.debug(`[ReflectionProbe] Loading reflection probe texture from URL: ${e}`),this._textureUrlInFlight=e;const t=ws(this.sourceId,e);Eg(t,this.context.renderer).then(i=>{this._textureUrlInFlight===e&&i&&(this._textureUrlInFlight=void 0,Xr&&console.debug(`[ReflectionProbe] Successfully loaded reflection probe texture: ${e}`),this.texture=i)});return}this.__didAwake&&(this._textureUrlInFlight=void 0),this._texture=e,Xr&&console.debug("[ReflectionProbe] Set reflection probe texture "+(e?.name||"(removed)")),e&&(e instanceof c.CubeTexture||e.mapping===c.CubeUVReflectionMapping||e.mapping!==c.EquirectangularReflectionMapping&&(e.mapping=c.EquirectangularReflectionMapping),e.colorSpace=c.LinearSRGBColorSpace,e.needsUpdate=!0)}}get texture(){return this._texture}intensity=1;center=new c.Vector3;size=new c.Vector3(1,1,1);__lightmapIntensityScale=!0;isInBox(e){return Bo??=new c.Box3,Bo.setFromCenterAndSize(this.gameObject.worldPosition.add(this.center),this.size),ri([e],void 0,void 0,an.testBox),an.testBox.isEmpty()?Bo.containsPoint(e.worldPosition):Bo?.intersectsBox(an.testBox)}constructor(){super(),an._probes.has(this.context)||an._probes.set(this.context,[]),an._probes.get(this.context)?.push(this)}awake(){this._texture&&(this._texture.mapping!==c.CubeUVReflectionMapping&&(this._texture.mapping=c.EquirectangularReflectionMapping),this._texture.colorSpace=c.LinearSRGBColorSpace,this._texture.needsUpdate=!0)}update(){Xr&&(Bo??=new c.Box3,Bo.setFromCenterAndSize(this.gameObject.worldPosition.add(this.center),this.size),B.DrawWireBox3(Bo,5592320))}onEnable(){an.onEnabled?.invoke(this)}onDisable(){an.onDisabled?.invoke(this)}start(){this._texture||console.warn(`[ReflectionProbe] Missing texture. Please assign a custom cubemap texture. To use reflection probes assign them to your renderer's "anchor" property.`)}onDestroy(){const e=an._probes.get(this.context);if(e){const t=e.indexOf(this);t>=0&&e.splice(t,1)}}apply(e){if(vb||!this.enabled||!this.texture)return;const t=ys.get(e);t.setOverride("envMap",this.texture),t.setOverride("envMapRotation",this.gameObject.rotation);let i=this.intensity;this.__lightmapIntensityScale&&t.getOverride("lightMap")&&(i/=Math.PI),t.setOverride("envMapIntensity",i)}unapply(e){const t=ys.get(e);t&&t.getOverride("envMap")?.value===this.texture&&t.removeOveride("envMap")}};Wu([f([c.Texture,String])],ah.prototype,"texture",1);Wu([f()],ah.prototype,"intensity",2);Wu([f(c.Vector3)],ah.prototype,"center",2);Wu([f(c.Vector3)],ah.prototype,"size",2);let os=ah;const np=x("debugexr");class jk{get name(){return"EXT_texture_exr"}parser;constructor(e){this.parser=e,np&&console.log(e)}loadTexture(e){const t=this.name,i=this.parser,o=i.json.textures[e];if(np&&console.log("EXT_texture_exr.loadTexture",e,o),!o.extensions||!o.extensions[t])return null;const r=o.extensions[t],a=new X.EXRLoader(i.options.manager);return np&&console.log("EXT_texture_exr.loadTexture",r),i.loadTextureImage(e,r.source,a)}}typeof window<"u"&&window.addEventListener("unhandledrejection",s=>{});const Cn=rt,Zh="$___Export_Components",Bk="NEEDLE_components";class Fk{[Go]}class Uk{node;nodeIndex;nodeDef;constructor(e,t,i){this.node=e,this.nodeIndex=t,this.nodeDef=i}}class Bw{get name(){return Bk}exportContext;objectToNodeMap={};context;writer;registerExport(e){e.register(t=>{if("serializeUserData"in t){const i=t.serializeUserData.bind(t);this.writer=t,t.serializeUserData=(n,o)=>{try{this.serializeUserData(n,o)&&(t.extensionsUsed[this.name]=!0),i(n,o)}finally{this.afterSerializeUserData(n,o)}}}return this})}beforeParse(){this.exportContext={},this.objectToNodeMap={}}serializeUserData(e,t){const i=e.userData?.components;return!i||i.length<=0?!1:(delete e.userData.components,e[Zh]=i,!0)}afterSerializeUserData(e,t){if(e.type==="Scene"&&Cn&&console.log("DONE",JSON.stringify(t)),e[Zh]===void 0)return;const i=e[Zh];delete e[Zh],i!==null&&(e.userData.components=i)}writeNode(e,t){const i=this.writer.json.nodes.length;Cn&&console.log(e.name,i,e.uuid);const n=new Uk(e,i,t);this.exportContext[i]=n,this.objectToNodeMap[e.uuid]=i}afterParse(e){Cn&&console.log("AFTER",e);for(const t in this.exportContext){const i=this.exportContext[t],n=i.node,o=i.nodeDef,r=i.nodeIndex,a=n.userData?.components;if(!a||a.length<=0)continue;const l=new Fk;o.extensions=o.extensions||{},o.extensions[this.name]=l,this.context.object=n,this.context.nodeId=r,this.context.objectToNode=this.objectToNodeMap;const h=[];for(const d of a){this.context.target=d;const u=un().writeBuiltinComponentData(d,this.context);u!==null&&h.push(u)}h.length>0&&(l[Go]=h,Cn&&console.log("DID WRITE",n,"nodeIndex",r,h))}}parser;nodeToObjectMap={};gltf=null;beforeRoot(){return Cn&&console.log("BEGIN LOAD"),this.nodeToObjectMap={},null}async afterRoot(e){this.gltf=e;const t=e.parser,i=t?.extensions;if(!i)return;const n=i[this.name];Cn&&console.log("After root",e,this.parser,i);const o=[];if(n===!0){const r=t.json.nodes;if(r){for(let a=0;a<r.length;a++){const l=await t.getDependency("node",a);this.nodeToObjectMap[a]=l}for(let a=0;a<r.length;a++){const l=r[a],h=a,d=l.extensions;if(!d)continue;const u=d[this.name];if(!u)continue;Cn&&console.log("NODE",l);const p=this.nodeToObjectMap[h];if(!p){console.error("Could not find object for node index: "+h,l,t);continue}Ou(p),o.push(this.createComponents(e,l,p,u))}}}await Promise.all(o);for(const r of t.associations.keys()){const a=t.associations.get(r);if(a?.materials!=null){const l="/materials/"+a.materials;YC(r,l)}}}async createComponents(e,t,i,n){if(!n)return;const o=n[Go];if(o){const r=new Array;Cn&&console.log(i.name,o);for(const a in o){const l=o[a];if(Cn&&console.log("Serialized data",JSON.parse(JSON.stringify(l))),(l?.name==="MeshRenderer"||l?.name==="SkinnedMeshRenderer")&&!l.sharedMaterials){let h=!1;if("mesh"in t){const d=t.mesh;if(typeof d=="number"&&e.parser){const u=e.parser.json.meshes?.[d];u?.primitives&&(l.sharedMaterials=u.primitives.map(p=>"/materials/"+(p.material??0)),h=!0)}}!h&&(Cn||A())&&console.warn(`[NEEDLE_components] Component '${l.name}' on object '${i.name}' is not added to a mesh or failed to retrieve materials from glTF.`)}l&&this.parser&&r.push(ig(this.parser,l).catch(h=>console.error(`Error while resolving references (see console for details)
1000
- `,h,i,l))),i.userData=i.userData||{},i.userData[Go]=i.userData[Go]||[],i.userData[Go].push(l)}await Promise.all(r).catch(a=>{console.error("Error while loading components",a)})}}}const wb="NEEDLE_gameobject_data";class zk{get name(){return wb}parser;constructor(e){this.parser=e}afterRoot(e){const t=[];for(let i=0;i<this.parser.json.nodes?.length;i++){const n=this.parser.json.nodes[i];if(n&&n.extensions){const o=n.extensions[wb];if(o){const r=this.findAndApplyExtensionData(i,o);t.push(r)}}}return Promise.all(t).then(()=>null)}async findAndApplyExtensionData(e,t){const i=await this.parser.getDependency("node",e);i&&this.applyExtensionData(i,t)}applyExtensionData(e,t){t.layers===void 0&&(t.layers=0),e.userData.layer=t.layers,e.layers.disableAll(),e.layers.set(t.layers),e.userData.tag=t.tag??"none",e.hideFlags=0,e.userData.static=t.static??!1,e.visible=t.activeSelf??!0,e.guid=t.guid}}const xb="NEEDLE_lighting_settings",ra=x("debugenvlight");class Nk{get name(){return xb}parser;sourceId;context;constructor(e,t,i){this.parser=e,this.sourceId=t,this.context=i}afterRoot(e){const t=this.parser.json.extensions;if(t){const i=t[xb];if(i){ra&&console.log('Loaded "'+this.name+'", src: "'+this.sourceId+'"',i);let n;if(e.scene.children.length===1){const o=e.scene.children[0];n=S.addComponent(o,ou,{},{callAwake:!1})}else{const o=new c.Object3D;o.name="LightSettings "+this.sourceId,e.scene.add(o),n=S.addComponent(o,ou,{},{callAwake:!1})}n.sourceId=this.sourceId,n.ambientIntensity=i.ambientIntensity,n.ambientLight=new c.Color().fromArray(i.ambientLight),Array.isArray(i.ambientTrilight)&&(n.ambientTrilight=i.ambientTrilight.map(o=>new c.Color().fromArray(o))),n.ambientMode=i.ambientMode,n.environmentReflectionSource=i.environmentReflectionSource}}return null}}ce.registerCallback(ae.ContextCreated,s=>{const e=s.context,t=S.findObjectOfType(ou,e);t?.sourceId&&(t.enabled=!0)});class ou extends E{ambientMode=va.Skybox;ambientLight;ambientTrilight;ambientIntensity=1;environmentReflectionSource=Kd.Skybox;_hasReflection=!1;_ambientLightObj;_hemisphereLightObj;awake(){if(this.sourceId){const t=this.environmentReflectionSource===Kd.Skybox?Tn.Skybox:Tn.Reflection,i=this.context.lightmaps.tryGet(this.sourceId,t,0);this._hasReflection=i!=null,i&&this.context.sceneLighting.internalRegisterReflection(this.sourceId,i)}this.enabled=!1,this.context.sceneLighting.internalRegisterSceneLightSettings(this),ra&&window.addEventListener("keydown",t=>{this.destroyed||t.key==="l"&&(this.enabled=!this.enabled)});const e=this.gameObject.userData?.components;if(e){const t=e.indexOf(this);e.splice(t,1),e.push(this)}}onDestroy(){this.context.sceneLighting.internalUnregisterSceneLightSettings(this)}calculateIntensityFactor(e){const t=Math.max(e.r,e.g,e.b);return 2.2*I.lerp(0,1.33,t)}onEnable(){if(ra&&console.warn("💡🟡 >>> Enable lighting",this.sourceId,this.enabled,this),this.ambientMode==va.Flat){if(this.ambientLight&&!this._ambientLightObj){const e=this.calculateIntensityFactor(this.ambientLight);this._ambientLightObj=new c.AmbientLight(this.ambientLight,this.ambientIntensity*e),ra&&console.log("Created ambient light",this.sourceId,this._ambientLightObj,this.ambientIntensity,e)}this._ambientLightObj&&this.gameObject.add(this._ambientLightObj)}else if(this.ambientMode===va.Trilight){if(this.ambientTrilight){const e=this.ambientTrilight[0],t=this.ambientTrilight[this.ambientTrilight.length-1],i=this.calculateIntensityFactor(t);this._hemisphereLightObj=new c.HemisphereLight(t,e,this.ambientIntensity*i),this.gameObject.add(this._hemisphereLightObj),ra&&console.log("Created hemisphere ambient light",this.sourceId,this._hemisphereLightObj,this.ambientIntensity,i)}}else this._ambientLightObj&&this._ambientLightObj.removeFromParent(),this._hemisphereLightObj&&this._hemisphereLightObj.removeFromParent();this.sourceId&&(this.context.domElement.getAttribute("environment-image")||this.context.sceneLighting.internalEnableReflection(this.sourceId))}onDisable(){ra&&console.warn("💡⚫ <<< Disable lighting:",this.sourceId,this),this._ambientLightObj&&this._ambientLightObj.removeFromParent(),this._hemisphereLightObj&&this._hemisphereLightObj.removeFromParent(),this.sourceId&&this.context.sceneLighting.internalDisableReflection(this.sourceId)}}exports.MaterialX=void 0;(s=>{async function e(t,i){if(!t)throw new Error("URL or XML string is required to load a MaterialX material");const n=await T.MaterialX.load(),o=t.trimStart().startsWith("<"),r=o?t:await fetch(t).then(h=>h.text()).catch(console.error);if(!r)return console.warn("Failed to load MaterialX file from url",t),null;let a;if(i?.url||!o){const h=(i?.url||t).split("/");h.pop(),a=h.join("/")}const l=new c.TextureLoader;return n.Experimental_API.createMaterialXMaterial(r,i?.materialNameOrIndex??0,{getTexture:async h=>(!h.startsWith("http")&&!h.startsWith("data:")&&!h.startsWith("blob:")&&!h.startsWith("file:")&&a&&(h=a+"/"+h),l.loadAsync(h).catch(d=>{console.warn(`Failed to load texture for MaterialX material ${h}`,d)}))},{cacheKey:t})}s.loadFromUrl=e})(exports.MaterialX||(exports.MaterialX={}));class Vk extends c.Loader{loadAsync(e,t){return new Promise((i,n)=>{this.load(e,i,t,n)})}load(e,t,i,n){i?.({type:"progress",loaded:0,total:0}),exports.MaterialX.loadFromUrl(e,{}).then(o=>{o?t(this.onLoaded(o)):n?.(new Error("Failed to load MaterialX material from url: "+e))})}onLoaded(e){return _o.createPrimitive("ShaderBall",{material:e})}}class $k{constructor(e,t,i,n){this.context=e,this.loader=t,this.url=i,this.parser=n}get name(){return"materialx-loading-helper"}mtlxLoader;async beforeRoot(){if(this.parser.json.extensions?.NEEDLE_materials_mtlx){const t=await T.MaterialX.load();try{this.mtlxLoader=new t.MaterialXLoader(this.parser,{cacheKey:`${this.url}:materialx`,parameters:{precision:this.context.renderer?.capabilities.precision}},{getFrame:()=>this.context.time.frame,getTime:()=>this.context.time.time})}catch(i){console.error(i)}}}loadMaterial(e){return this.mtlxLoader?this.mtlxLoader.loadMaterial(e):null}}var Fw=(s=>(s[s.INT=5124]="INT",s[s.FLOAT=5126]="FLOAT",s[s.FLOAT_VEC2=35664]="FLOAT_VEC2",s[s.FLOAT_VEC3=35665]="FLOAT_VEC3",s[s.FLOAT_VEC4=35666]="FLOAT_VEC4",s[s.INT_VEC2=35667]="INT_VEC2",s[s.INT_VEC3=35668]="INT_VEC3",s[s.INT_VEC4=35669]="INT_VEC4",s[s.BOOL=35670]="BOOL",s[s.BOOL_VEC2=35671]="BOOL_VEC2",s[s.BOOL_VEC3=35672]="BOOL_VEC3",s[s.BOOL_VEC4=35673]="BOOL_VEC4",s[s.FLOAT_MAT2=35674]="FLOAT_MAT2",s[s.FLOAT_MAT3=35675]="FLOAT_MAT3",s[s.FLOAT_MAT4=35676]="FLOAT_MAT4",s[s.SAMPLER_2D=35678]="SAMPLER_2D",s[s.SAMPLER_3D=35680]="SAMPLER_3D",s[s.SAMPLER_CUBE=35681]="SAMPLER_CUBE",s[s.UNKNOWN=0]="UNKNOWN",s))(Fw||{});const Mn=x("debugcustomshader"),Qr="NEEDLE_techniques_webgl";class Wk{objectToWorldMatrix=new c.Matrix4;worldToObjectMatrix=new c.Matrix4;objectToWorld=new Array;worldToObject=new Array;updateFrom(e){this.objectToWorldMatrix.copy(e.matrixWorld),Yd(this.objectToWorldMatrix,this.objectToWorld),this.worldToObjectMatrix.copy(e.matrixWorld).invert(),Yd(this.worldToObjectMatrix,this.worldToObject)}}class ve extends c.RawShaderMaterial{identifier;onBeforeRenderSceneCallback=this.onBeforeRenderScene.bind(this);clone(){const e=super.clone();return Uw(e),e}constructor(e,...t){super(...t),this.identifier=e,Mn&&console.log(this),this.type="NEEDLE_CUSTOM_SHADER",this.uniforms[this._objToWorldName]||(this.uniforms[this._objToWorldName]={value:[]}),this.uniforms[this._worldToObjectName]||(this.uniforms[this._worldToObjectName]={value:[]}),this.uniforms[this._viewProjectionName]||(this.uniforms[this._viewProjectionName]={value:[]}),this.uniforms[this._sphericalHarmonicsName],(this.depthTextureUniform||this.opaqueTextureUniform)&&U.Current.pre_render_callbacks.push(this.onBeforeRenderSceneCallback)}dispose(){super.dispose();const e=U.Current.pre_render_callbacks.indexOf(this.onBeforeRenderSceneCallback);e>=0&&U.Current.pre_render_callbacks.splice(e,1)}_sphericalHarmonicsName="unity_SpecCube0";_objToWorldName="hlslcc_mtx4x4unity_ObjectToWorld";_worldToObjectName="hlslcc_mtx4x4unity_WorldToObject";static viewProjection=new c.Matrix4;static _viewProjectionValues=[];_viewProjectionName="hlslcc_mtx4x4unity_MatrixVP";static viewMatrix=new c.Matrix4;static _viewMatrixValues=[];_viewMatrixName="hlslcc_mtx4x4unity_MatrixV";static _worldSpaceCameraPosName="_WorldSpaceCameraPos";static _worldSpaceCameraPos=new c.Vector3;static _mainLightColor=new c.Vector4;static _mainLightPosition=new c.Vector3;static _lightData=new c.Vector4;_rendererData=new Wk;get depthTextureUniform(){if(this.uniforms)return this.uniforms._CameraDepthTexture}get opaqueTextureUniform(){if(this.uniforms)return this.uniforms._CameraOpaqueTexture}onBeforeRenderScene(){this.opaqueTextureUniform&&U.Current.setRequireColor(!0),this.depthTextureUniform&&U.Current.setRequireDepth(!0)}onBeforeRender(e,t,i,n,o,r){n.attributes.tangent||n.computeTangents(),this.onUpdateUniforms(i,o)}onUpdateUniforms(e,t){const i=U.Current;if(e&&(ve.viewProjection&&this.uniforms[this._viewProjectionName]&&(ve.viewProjection.copy(e.projectionMatrix).multiply(e.matrixWorldInverse),Yd(ve.viewProjection,ve._viewProjectionValues)),ve.viewMatrix&&this.uniforms[this._viewMatrixName]&&(ve.viewMatrix.copy(e.matrixWorldInverse),Yd(ve.viewMatrix,ve._viewMatrixValues)),this.uniforms[ve._worldSpaceCameraPosName]&&ve._worldSpaceCameraPos.setFromMatrixPosition(e.matrixWorld)),this.uniforms._TimeParameters&&(this.uniforms._TimeParameters.value=i.sceneLighting.timeVec4),this.uniforms._Time){const a=this.uniforms._Time.value;a.x=i.sceneLighting.timeVec4.x/20,a.y=i.sceneLighting.timeVec4.x,a.z=i.sceneLighting.timeVec4.x*2,a.w=i.sceneLighting.timeVec4.x*3}if(this.uniforms._SinTime){const a=this.uniforms._SinTime.value;a.x=Math.sin(i.sceneLighting.timeVec4.x/8),a.y=Math.sin(i.sceneLighting.timeVec4.x/4),a.z=Math.sin(i.sceneLighting.timeVec4.x/2),a.w=Math.sin(i.sceneLighting.timeVec4.x)}if(this.uniforms._CosTime){const a=this.uniforms._CosTime.value;a.x=Math.cos(i.sceneLighting.timeVec4.x/8),a.y=Math.cos(i.sceneLighting.timeVec4.x/4),a.z=Math.cos(i.sceneLighting.timeVec4.x/2),a.w=Math.cos(i.sceneLighting.timeVec4.x)}if(this.uniforms.unity_DeltaTime){const a=this.uniforms.unity_DeltaTime.value;a.x=i.time.deltaTime,a.y=1/i.time.deltaTime,a.z=i.time.smoothedDeltaTime,a.w=1/i.time.smoothedDeltaTime}const n=i.mainLight;if(n){const a=Y(n.gameObject,ve._mainLightPosition);this.uniforms._MainLightPosition={value:a.normalize()},ve._mainLightColor.set(n.color.r,n.color.g,n.color.b,0),this.uniforms._MainLightColor={value:ve._mainLightColor};const l=n.intensity;ve._lightData.z=l,this.uniforms.unity_LightData={value:ve._lightData}}if(e&&(ve.viewProjection&&this.uniforms[this._viewProjectionName]&&(this.uniforms[this._viewProjectionName].value=ve._viewProjectionValues),ve.viewMatrix&&this.uniforms[this._viewMatrixName]&&(this.uniforms[this._viewMatrixName].value=ve._viewMatrixValues),this.uniforms[ve._worldSpaceCameraPosName]&&(this.uniforms[ve._worldSpaceCameraPosName]={value:ve._worldSpaceCameraPos}),i.mainCameraComponent)){if(this.uniforms._ProjectionParams){const a=this.uniforms._ProjectionParams.value;a.x=1,a.y=i.mainCameraComponent.nearClipPlane,a.z=i.mainCameraComponent.farClipPlane,a.w=1/a.z,this.uniforms._ProjectionParams.value=a}if(this.uniforms._ZBufferParams){const a=this.uniforms._ZBufferParams.value,l=i.mainCameraComponent;a.x=1-l.farClipPlane/l.nearClipPlane,a.y=l.farClipPlane/l.nearClipPlane,a.z=a.x/l.farClipPlane,a.w=a.y/l.farClipPlane,this.uniforms._ZBufferParams.value=a}if(this.uniforms._ScreenParams){const a=this.uniforms._ScreenParams.value;a.x=i.domWidth,a.y=i.domHeight,a.z=1+1/a.x,a.w=1+1/a.y,this.uniforms._ScreenParams.value=a}if(this.uniforms._ScaledScreenParams){const a=this.uniforms._ScaledScreenParams.value;a.x=i.domWidth,a.y=i.domHeight,a.z=1+1/a.x,a.w=1+1/a.y,this.uniforms._ScaledScreenParams.value=a}}const o=this.depthTextureUniform;o&&(o.value=i.depthTexture);const r=this.opaqueTextureUniform;if(r&&(r.value=i.opaqueColorTexture),t){const a=this._rendererData;a.updateFrom(t),this.uniforms[this._worldToObjectName].value=a.worldToObject,this.uniforms[this._objToWorldName].value=a.objectToWorld}this.uniformsNeedUpdate=!0}}class Gk{get name(){return Qr}parser;identifier;constructor(e,t){this.parser=e,this.identifier=t}loadMaterial(e){const t=this.parser.json.materials[e];if(!t)return Mn&&console.log(e,this.parser.json.materials),null;if(!t.extensions||!t.extensions[Qr])return Mn&&console.log(`Material ${e} does not use NEEDLE_techniques_webgl`),null;Mn&&console.log(`Material ${e} uses NEEDLE_techniques_webgl`,t);const i=t.extensions[Qr].technique;if(i<0)return console.debug(`Material ${e} does not have a valid technique index`),null;const n=this.parser.json.extensions[Qr];if(!n)return Mn?console.error("Missing shader data",this.parser.json.extensions):console.debug("Missing custom shader data in parser.json.extensions"),null;Mn&&console.log(n);const o=n.techniques[i];return o?new Promise(async(r,a)=>{const l=await E1(n,o.program),h=l?.fragmentShader,d=l?.vertexShader;if(!h||!d)return a();Mn&&console.log("loadMaterial",t,l);const u={},p=o.uniforms;(d.includes("_Time")||h.includes("_Time"))&&(u._Time={value:new c.Vector4(0,0,0,0)}),(d.includes("_SinTime")||h.includes("_SinTime"))&&(u._SinTime={value:new c.Vector4(0,0,0,0)}),(d.includes("_CosTime")||h.includes("_CosTime"))&&(u._CosTime={value:new c.Vector4(0,0,0,0)}),(d.includes("unity_DeltaTime")||h.includes("unity_DeltaTime"))&&(u.unity_DeltaTime={value:new c.Vector4(0,0,0,0)});for(const v in p){const b=v;switch(b){case"_TimeParameters":const w=new c.Vector4;u[b]={value:w};break;case"hlslcc_mtx4x4unity_MatrixV":case"hlslcc_mtx4x4unity_MatrixVP":u[b]={value:[]};break;case"_MainLightPosition":case"_MainLightColor":case"_WorldSpaceCameraPos":u[b]={value:[0,0,0,1]};break;case"unity_OrthoParams":break;case"unity_SpecCube0":u[b]={value:null};break;default:case"_ScreenParams":case"_ZBufferParams":case"_ProjectionParams":u[b]={value:[0,0,0,0]};break;case"_CameraOpaqueTexture":case"_CameraDepthTexture":u[b]={value:null};break}}let m=!1;if(t.extensions&&t.extensions[Qr]){const v=t.extensions[Qr];if(v.technique===i){Mn&&console.log(t.name,"Material Properties",v);for(const b in v.values){const w=v.values[b];if(typeof w=="string"){if(w.startsWith("/textures/")){const R=w.substring(10),O=Number.parseInt(R);if(O>=0){const k=await this.parser.getDependency("texture",O);k instanceof c.Texture&&(k.colorSpace=c.LinearSRGBColorSpace,k.needsUpdate=!0),u[b]={value:k};continue}}if(b==="alphaMode"){w==="BLEND"&&(m=!0);continue}}if(Array.isArray(w)&&w.length===4){u[b]={value:new c.Vector4(w[0],w[1],w[2],w[3])};continue}u[b]={value:w}}}}const y=new ve(this.identifier,{name:t.name??"",uniforms:u,vertexShader:d,fragmentShader:h,lights:!1});switch(y.glslVersion=c.GLSL3,y.vertexShader=y.vertexShader.replace("#version 300 es",""),y.fragmentShader=y.fragmentShader.replace("#version 300 es",""),u._Cull?.value){case 0:y.side=c.DoubleSide;break;case 1:y.side=c.BackSide;break;case 2:y.side=c.FrontSide;break;default:y.side=c.FrontSide;break}switch(u._ZTest?.value){case 3:y.depthTest=!0,y.depthFunc=c.EqualDepth;break;case 6:y.depthTest=!0,y.depthFunc=c.NotEqualDepth;break;case 2:y.depthTest=!0,y.depthFunc=c.LessDepth;break;case 4:y.depthTest=!0,y.depthFunc=c.LessEqualDepth;break;case 5:y.depthTest=!0,y.depthFunc=c.GreaterDepth;break;case 7:y.depthTest=!0,y.depthFunc=c.GreaterEqualDepth;break;case 8:y.depthTest=!1,y.depthFunc=c.AlwaysDepth;break}y.transparent=m,m&&(y.depthWrite=!1),k1(u),y.onUpdateUniforms();for(const v in p){const b=v,w=p[v].type;u[b]?.value===void 0&&(w===Fw.SAMPLER_2D?(u[b]={value:P1},console.warn("Missing/unassigned texture, fallback to white: "+b)):b==="unity_OrthoParams"||console.warn("TODO: EXPECTED UNIFORM / fallback NOT SET: "+b,p[v]))}Mn&&console.log(y.uuid,u),Uw(y),r(y)}):null}}function Uw(s){if(s.uniforms){Mn&&console.log("Uniforms:",s.uniforms);for(const t in s.uniforms)switch(e(t,t),t){case"_Color":e("color",t);break;case"_map":e("map",t);break}}function e(t,i){Object.getOwnPropertyDescriptor(s,t)||Object.defineProperty(s,t,{get:()=>s.uniforms[i].value,set:n=>{s.uniforms[i].value=n,s.needsUpdate=!0}})}}const Hk=x("debugextensions");let ru;const qk=Promise.resolve().then(()=>require("./vendor-BI4TX0aC.umd.cjs")).then(s=>s.index$2).then(async s=>(ru=s.GLTFAnimationPointerExtension,ru)).catch(s=>{console.warn("Failed to import GLTFLoaderAnimationPointer. Please use @needle-tools/three-animationpointer for full KHR_animation support",s)}),mr=new Array;function Xk(s){mr.includes(s)||mr.push(s)}function Qk(s){const e=mr.indexOf(s);e>=0&&mr.splice(e,1)}function Vg(s){if(s instanceof X.GLTFLoader){const e=new Bw;return s.register(t=>(e.parser=t,e)),e}return null}class Yk{resolvePath(e){return e.includes("/extensions/builtin_components/")?e.replace("/extensions/builtin_components/","/userData/components/"):e.includes("extensions/builtin_components/")?e.replace("extensions/builtin_components/","/userData/components/"):e}}async function au(s,e,t,i){const n=t.indexOf("?");n>=0&&(t=t.substring(0,n)),i||(i=t),(i.startsWith("blob:")||i.startsWith("data:"))&&console.debug("[GLTFLoader] Suspicious sourceId detected"),s.register(o=>new zk(o)),s.register(o=>new ZC(o)),s.register(o=>new p1(o,e.lightmaps,i)),s.register(o=>new Nk(o,i,e)),s.register(o=>new Gk(o,i)),s.register(o=>new io(o,i)),s.register(o=>new re.NEEDLE_progressive(o)),s.register(o=>new jk(o)),s.register(o=>new wu(o)),s.register(o=>new $k(e,s,t,o)),W0()&&s.register(o=>new xa(o)),await qk.catch(o=>{}),s.register(o=>{if(ru){const r=new ru(o);return r.setAnimationPointerResolver.bind(r)(new Yk),r}else return(Hk||A())&&console.error("Missing KHR_animation_pointer extension..."),{name:"KHR_animation_pointer_NOT_AVAILABLE"}});for(const o of mr)o.onImport&&o.onImport(s,t,e)}function $g(s,e){for(const t of mr)t.onExport&&t.onExport(s,e)}function zw(s,e,t){for(const i of mr)i.onLoaded&&i.onLoaded(s,e,t)}const Mt=x("debuginstancing");class gr{static instance=new gr;static getStartInstanceCount=e=>4;objs=[];setup(e,t,i,n,o,r=0){e.applySettings(t);const a=this.tryCreateOrAddInstance(t,i,o);if(a){n===null&&(n=[]),n.push(a);const l=a.object.material;Array.isArray(l)?l.forEach(u=>re.NEEDLE_progressive.assignTextureLOD(u,0)):re.NEEDLE_progressive.assignTextureLOD(l,0);const h=a.object,d=h.geometry;re.NEEDLE_progressive.assignMeshLOD(h,0).then(u=>{u&&d!=u&&a.setGeometry(u)})}else if(r<=0&&t.type!=="Mesh"){const l=r+1;for(const h of t.children)n=this.setup(e,h,i,n,o,l)}return r===0&&o.useMatrixWorldAutoUpdate&&n&&n.length>=0&&this.autoUpdateInstanceMatrix(t),n}tryCreateOrAddInstance(e,t,i){if(e.type==="Mesh"){const n=i.foundMeshes;if(i.foundMeshes+=1,!i.rend.enableInstancing)return null;if(i.rend.enableInstancing!==!0){if(n>=i.rend.enableInstancing.length)return Mt&&console.error("Something is wrong with instance setup",e,i.rend.enableInstancing,n),null;if(!i.rend.enableInstancing[n])return null}const o=e,r=o.material;for(const u of this.objs){if(!u.canAdd(o.geometry,r))continue;return u.addInstance(o)}let a=gr.getStartInstanceCount(e);(!a||a<0)&&(a=4);let l=e.name;l?.length||(l=mv());const h=new Kk(l,o.geometry,r,a,t);return this.objs.push(h),h.addInstance(o)}return null}autoUpdateInstanceMatrix(e){const t=e.matrixWorld.multiplyMatrices.bind(e.matrixWorld),i=e.matrixWorld.clone(),n=(o,r)=>{const a=t(o,r);return(e[Cc]||i.equals(a)===!1)&&(i.copy(a),e[Cc]=!0),a};e.matrixWorld.multiplyMatrices=n}}class cr{static all=[];get name(){return this.object.name}get isActive(){return this.__instanceIndex>=0}get vertexCount(){return this.object.geometry.attributes.position.count}get maxVertexCount(){return Math.max(this.meshInformation.vertexCount,this.vertexCount)}get reservedVertexCount(){return this.__reservedVertexRange}get indexCount(){return this.object.geometry.index?this.object.geometry.index.count:0}get maxIndexCount(){return Math.max(this.meshInformation.indexCount,this.indexCount)}get reservedIndexCount(){return this.__reservedIndexRange}object;renderer;__instanceIndex=-1;__reservedVertexRange=0;__reservedIndexRange=0;__geometryIndex=-1;meshInformation;constructor(e,t){this.__instanceIndex=-1,this.object=e,this.renderer=t,e[Q0]=t,this.meshInformation=Ho(e.geometry),cr.all.push(this)}updateMeshInformation(){const e=Ho(this.object.geometry),t=this.meshInformation.vertexCount,i=this.meshInformation.indexCount;return Object.assign(this.meshInformation,e),t!==this.meshInformation.vertexCount||i!==this.meshInformation.indexCount}updateInstanceMatrix(e=!1,t=!0){this.__instanceIndex<0||(t&&this.object.updateWorldMatrix(!0,e),this.renderer.updateInstance(this.object.matrixWorld,this.__instanceIndex))}setMatrix(e){this.__instanceIndex<0||this.renderer.updateInstance(e,this.__instanceIndex)}setGeometry(e){if(this.__geometryIndex<0)return!1;const t=this;if(this.vertexCount>this.__reservedVertexRange)return i(`Instancing: Can not update geometry (${this.name}), reserved vertex range is too small: ${this.__reservedVertexRange.toLocaleString()} < ${this.vertexCount.toLocaleString()} vertices for ${this.name}`);if(this.indexCount>this.__reservedIndexRange)return i(`Instancing: Can not update geometry (${this.name}), reserved index range is too small: ${this.__reservedIndexRange.toLocaleString()} < ${this.indexCount.toLocaleString()} indices for ${this.name}`);return this.renderer.updateGeometry(e,this.__geometryIndex);function i(n){return t.updateMeshInformation()&&(t.renderer.remove(t,!0),t.renderer.add(t))?!0:((A()||Mt)&&console.error(n),!1)}}add(){this.__instanceIndex>=0||(this.renderer.add(this),S.markAsInstancedRendered(this.object,!0))}remove(e){if(!(this.__instanceIndex<0)&&(this.renderer.remove(this,e),S.markAsInstancedRendered(this.object,!1),e)){const t=cr.all.indexOf(this);t>=0&&cr.all.splice(t,1)}}}class Kk{get batchedMesh(){return this._batchedMesh}get visible(){return this._batchedMesh.visible}set visible(e){this._batchedMesh.visible=e}get castShadow(){return this._batchedMesh.castShadow}set castShadow(e){this._batchedMesh.castShadow=e}set receiveShadow(e){this._batchedMesh.receiveShadow=e}allowResize=!0;name="";geometry;material;get count(){return this._currentInstanceCount}updateBounds(e=!0,t=!0){if(this._needUpdateBounds=!1,e&&this._batchedMesh.computeBoundingBox(),t&&this._batchedMesh.computeBoundingSphere(),Mt&&this._batchedMesh.boundingSphere){const i=this._batchedMesh.boundingSphere;B.DrawWireSphere(i.center,i.radius,65280)}}_context;_batchedMesh;_handles=[];_geometryIds=new WeakMap;_maxInstanceCount;_currentInstanceCount=0;_currentVertexCount=0;_currentIndexCount=0;_maxVertexCount;_maxIndexCount;static nullMatrix=new c.Matrix4;canAdd(e,t){return this._maxVertexCount>1e7||t!==this.material||!this.validateGeometry(e)?!1:!!(!this.mustGrow(e)||this.allowResize)}_needUpdateBounds=!1;_debugMaterial=null;getBatchedMeshName(){return this.name?`${this.name} (BatchedMesh)`:"BatchedMesh"}constructor(e,t,i,n,o){this.name=e,this.geometry=t,this.material=i,this._context=o,this._maxInstanceCount=Math.max(2,n),Mt&&(this._debugMaterial=Sb());const r=this.tryEstimateVertexCountSize(this._maxInstanceCount,[t],n);this._maxVertexCount=r.vertexCount,this._maxIndexCount=r.indexCount,this._batchedMesh=new c.BatchedMesh(this._maxInstanceCount,this._maxVertexCount,this._maxIndexCount,this._debugMaterial??this.material),this._batchedMesh.name=this.getBatchedMeshName(),this._batchedMesh[Nl]=!0,this._batchedMesh.visible=!0,this._context.scene.add(this._batchedMesh),i instanceof c.RawShaderMaterial&&(i.defines.USE_INSTANCING=!0,i.needsUpdate=!0),o.pre_render_callbacks.push(this.onBeforeRender),o.post_render_callbacks.push(this.onAfterRender),Mt&&console.log(`Instanced renderer (${this.name}) created with ${this._maxInstanceCount} instances, ${this._maxVertexCount} max vertices and ${this._maxIndexCount} max indices for "${e}"`)}dispose(){Mt&&console.warn("Dispose instanced renderer",this.name),this._context.scene.remove(this._batchedMesh),this._batchedMesh.dispose(),this._batchedMesh=null,this._handles=[]}addInstance(e){const t=new cr(e,this);e.castShadow===!0&&this._batchedMesh.castShadow===!1&&(this._batchedMesh.castShadow=!0),e.receiveShadow===!0&&this._batchedMesh.receiveShadow===!1&&(this._batchedMesh.receiveShadow=!0);try{this.add(t)}catch(i){if(console.error(`Failed adding mesh to instancing (object name: "${e.name}", instances: ${this._currentInstanceCount.toLocaleString()}/${this._maxInstanceCount.toLocaleString()}, vertices: ${this._currentVertexCount.toLocaleString()}/${this._maxVertexCount.toLocaleString()}, indices: ${this._currentIndexCount.toLocaleString()}/${this._maxIndexCount.toLocaleString()})
1000
+ `,h,i,l))),i.userData=i.userData||{},i.userData[Go]=i.userData[Go]||[],i.userData[Go].push(l)}await Promise.all(r).catch(a=>{console.error("Error while loading components",a)})}}}const wb="NEEDLE_gameobject_data";class zk{get name(){return wb}parser;constructor(e){this.parser=e}afterRoot(e){const t=[];for(let i=0;i<this.parser.json.nodes?.length;i++){const n=this.parser.json.nodes[i];if(n&&n.extensions){const o=n.extensions[wb];if(o){const r=this.findAndApplyExtensionData(i,o);t.push(r)}}}return Promise.all(t).then(()=>null)}async findAndApplyExtensionData(e,t){const i=await this.parser.getDependency("node",e);i&&this.applyExtensionData(i,t)}applyExtensionData(e,t){t.layers===void 0&&(t.layers=0),e.userData.layer=t.layers,e.layers.disableAll(),e.layers.set(t.layers),e.userData.tag=t.tag??"none",e.hideFlags=0,e.userData.static=t.static??!1,e.visible=t.activeSelf??!0,e.guid=t.guid}}const xb="NEEDLE_lighting_settings",ra=x("debugenvlight");class Nk{get name(){return xb}parser;sourceId;context;constructor(e,t,i){this.parser=e,this.sourceId=t,this.context=i}afterRoot(e){const t=this.parser.json.extensions;if(t){const i=t[xb];if(i){ra&&console.log('Loaded "'+this.name+'", src: "'+this.sourceId+'"',i);let n;if(e.scene.children.length===1){const o=e.scene.children[0];n=S.addComponent(o,ou,{},{callAwake:!1})}else{const o=new c.Object3D;o.name="LightSettings "+this.sourceId,e.scene.add(o),n=S.addComponent(o,ou,{},{callAwake:!1})}n.sourceId=this.sourceId,n.ambientIntensity=i.ambientIntensity,n.ambientLight=new c.Color().fromArray(i.ambientLight),Array.isArray(i.ambientTrilight)&&(n.ambientTrilight=i.ambientTrilight.map(o=>new c.Color().fromArray(o))),n.ambientMode=i.ambientMode,n.environmentReflectionSource=i.environmentReflectionSource}}return null}}ce.registerCallback(ae.ContextCreated,s=>{const e=s.context,t=S.findObjectOfType(ou,e);t?.sourceId&&(t.enabled=!0)});class ou extends E{ambientMode=va.Skybox;ambientLight;ambientTrilight;ambientIntensity=1;environmentReflectionSource=Kd.Skybox;_hasReflection=!1;_ambientLightObj;_hemisphereLightObj;awake(){if(this.sourceId){const t=this.environmentReflectionSource===Kd.Skybox?Tn.Skybox:Tn.Reflection,i=this.context.lightmaps.tryGet(this.sourceId,t,0);this._hasReflection=i!=null,i&&this.context.sceneLighting.internalRegisterReflection(this.sourceId,i)}this.enabled=!1,this.context.sceneLighting.internalRegisterSceneLightSettings(this),ra&&window.addEventListener("keydown",t=>{this.destroyed||t.key==="l"&&(this.enabled=!this.enabled)});const e=this.gameObject.userData?.components;if(e){const t=e.indexOf(this);e.splice(t,1),e.push(this)}}onDestroy(){this.context.sceneLighting.internalUnregisterSceneLightSettings(this)}calculateIntensityFactor(e){const t=Math.max(e.r,e.g,e.b);return 2.2*I.lerp(0,1.33,t)}onEnable(){if(ra&&console.warn("💡🟡 >>> Enable lighting",this.sourceId,this.enabled,this),this.ambientMode==va.Flat){if(this.ambientLight&&!this._ambientLightObj){const e=this.calculateIntensityFactor(this.ambientLight);this._ambientLightObj=new c.AmbientLight(this.ambientLight,this.ambientIntensity*e),ra&&console.log("Created ambient light",this.sourceId,this._ambientLightObj,this.ambientIntensity,e)}this._ambientLightObj&&this.gameObject.add(this._ambientLightObj)}else if(this.ambientMode===va.Trilight){if(this.ambientTrilight){const e=this.ambientTrilight[0],t=this.ambientTrilight[this.ambientTrilight.length-1],i=this.calculateIntensityFactor(t);this._hemisphereLightObj=new c.HemisphereLight(t,e,this.ambientIntensity*i),this.gameObject.add(this._hemisphereLightObj),ra&&console.log("Created hemisphere ambient light",this.sourceId,this._hemisphereLightObj,this.ambientIntensity,i)}}else this._ambientLightObj&&this._ambientLightObj.removeFromParent(),this._hemisphereLightObj&&this._hemisphereLightObj.removeFromParent();this.sourceId&&(this.context.domElement.getAttribute("environment-image")||this.context.sceneLighting.internalEnableReflection(this.sourceId))}onDisable(){ra&&console.warn("💡⚫ <<< Disable lighting:",this.sourceId,this),this._ambientLightObj&&this._ambientLightObj.removeFromParent(),this._hemisphereLightObj&&this._hemisphereLightObj.removeFromParent(),this.sourceId&&this.context.sceneLighting.internalDisableReflection(this.sourceId)}}exports.MaterialX=void 0;(s=>{async function e(t,i){if(!t)throw new Error("URL or XML string is required to load a MaterialX material");const n=await T.MaterialX.load(),o=t.trimStart().startsWith("<"),r=o?t:await fetch(t).then(h=>h.text()).catch(console.error);if(!r)return console.warn("Failed to load MaterialX file from url",t),null;let a;if(i?.url||!o){const h=(i?.url||t).split("/");h.pop(),a=h.join("/")}const l=new c.TextureLoader;return n.Experimental_API.createMaterialXMaterial(r,i?.materialNameOrIndex??0,{getTexture:async h=>(!h.startsWith("http")&&!h.startsWith("data:")&&!h.startsWith("blob:")&&!h.startsWith("file:")&&a&&(h=a+"/"+h),l.loadAsync(h).catch(d=>{console.warn(`Failed to load texture for MaterialX material ${h}`,d)}))},{cacheKey:t})}s.loadFromUrl=e})(exports.MaterialX||(exports.MaterialX={}));class Vk extends c.Loader{loadAsync(e,t){return new Promise((i,n)=>{this.load(e,i,t,n)})}load(e,t,i,n){i?.({type:"progress",loaded:0,total:0}),exports.MaterialX.loadFromUrl(e,{}).then(o=>{o?t(this.onLoaded(o)):n?.(new Error("Failed to load MaterialX material from url: "+e))})}onLoaded(e){return _o.createPrimitive("ShaderBall",{material:e})}}class $k{constructor(e,t,i,n){this.context=e,this.loader=t,this.url=i,this.parser=n}get name(){return"materialx-loading-helper"}mtlxLoader;async beforeRoot(){if(this.parser.json.extensions?.NEEDLE_materials_mtlx){const t=await T.MaterialX.load();try{this.mtlxLoader=new t.MaterialXLoader(this.parser,{cacheKey:`${this.url}:materialx`,parameters:{precision:this.context.renderer?.capabilities.precision}},{getFrame:()=>this.context.time.frame,getTime:()=>this.context.time.time})}catch(i){console.error(i)}}}loadMaterial(e){return this.mtlxLoader?this.mtlxLoader.loadMaterial(e):null}}var Fw=(s=>(s[s.INT=5124]="INT",s[s.FLOAT=5126]="FLOAT",s[s.FLOAT_VEC2=35664]="FLOAT_VEC2",s[s.FLOAT_VEC3=35665]="FLOAT_VEC3",s[s.FLOAT_VEC4=35666]="FLOAT_VEC4",s[s.INT_VEC2=35667]="INT_VEC2",s[s.INT_VEC3=35668]="INT_VEC3",s[s.INT_VEC4=35669]="INT_VEC4",s[s.BOOL=35670]="BOOL",s[s.BOOL_VEC2=35671]="BOOL_VEC2",s[s.BOOL_VEC3=35672]="BOOL_VEC3",s[s.BOOL_VEC4=35673]="BOOL_VEC4",s[s.FLOAT_MAT2=35674]="FLOAT_MAT2",s[s.FLOAT_MAT3=35675]="FLOAT_MAT3",s[s.FLOAT_MAT4=35676]="FLOAT_MAT4",s[s.SAMPLER_2D=35678]="SAMPLER_2D",s[s.SAMPLER_3D=35680]="SAMPLER_3D",s[s.SAMPLER_CUBE=35681]="SAMPLER_CUBE",s[s.UNKNOWN=0]="UNKNOWN",s))(Fw||{});const Mn=x("debugcustomshader"),Qr="NEEDLE_techniques_webgl";class Wk{objectToWorldMatrix=new c.Matrix4;worldToObjectMatrix=new c.Matrix4;objectToWorld=new Array;worldToObject=new Array;updateFrom(e){this.objectToWorldMatrix.copy(e.matrixWorld),Yd(this.objectToWorldMatrix,this.objectToWorld),this.worldToObjectMatrix.copy(e.matrixWorld).invert(),Yd(this.worldToObjectMatrix,this.worldToObject)}}class ve extends c.RawShaderMaterial{identifier;onBeforeRenderSceneCallback=this.onBeforeRenderScene.bind(this);clone(){const e=super.clone();return Uw(e),e}constructor(e,...t){super(...t),this.identifier=e,Mn&&console.log(this),this.type="NEEDLE_CUSTOM_SHADER",this.uniforms[this._objToWorldName]||(this.uniforms[this._objToWorldName]={value:[]}),this.uniforms[this._worldToObjectName]||(this.uniforms[this._worldToObjectName]={value:[]}),this.uniforms[this._viewProjectionName]||(this.uniforms[this._viewProjectionName]={value:[]}),this.uniforms[this._sphericalHarmonicsName],(this.depthTextureUniform||this.opaqueTextureUniform)&&U.Current.pre_render_callbacks.push(this.onBeforeRenderSceneCallback)}dispose(){super.dispose();const e=U.Current.pre_render_callbacks.indexOf(this.onBeforeRenderSceneCallback);e>=0&&U.Current.pre_render_callbacks.splice(e,1)}_sphericalHarmonicsName="unity_SpecCube0";_objToWorldName="hlslcc_mtx4x4unity_ObjectToWorld";_worldToObjectName="hlslcc_mtx4x4unity_WorldToObject";static viewProjection=new c.Matrix4;static _viewProjectionValues=[];_viewProjectionName="hlslcc_mtx4x4unity_MatrixVP";static viewMatrix=new c.Matrix4;static _viewMatrixValues=[];_viewMatrixName="hlslcc_mtx4x4unity_MatrixV";static _worldSpaceCameraPosName="_WorldSpaceCameraPos";static _worldSpaceCameraPos=new c.Vector3;static _mainLightColor=new c.Vector4;static _mainLightPosition=new c.Vector3;static _lightData=new c.Vector4;_rendererData=new Wk;get depthTextureUniform(){if(this.uniforms)return this.uniforms._CameraDepthTexture}get opaqueTextureUniform(){if(this.uniforms)return this.uniforms._CameraOpaqueTexture}onBeforeRenderScene(){this.opaqueTextureUniform&&U.Current.setRequireColor(!0),this.depthTextureUniform&&U.Current.setRequireDepth(!0)}onBeforeRender(e,t,i,n,o,r){n.attributes.tangent||n.computeTangents(),this.onUpdateUniforms(i,o)}onUpdateUniforms(e,t){const i=U.Current;if(e&&(ve.viewProjection&&this.uniforms[this._viewProjectionName]&&(ve.viewProjection.copy(e.projectionMatrix).multiply(e.matrixWorldInverse),Yd(ve.viewProjection,ve._viewProjectionValues)),ve.viewMatrix&&this.uniforms[this._viewMatrixName]&&(ve.viewMatrix.copy(e.matrixWorldInverse),Yd(ve.viewMatrix,ve._viewMatrixValues)),this.uniforms[ve._worldSpaceCameraPosName]&&ve._worldSpaceCameraPos.setFromMatrixPosition(e.matrixWorld)),this.uniforms._TimeParameters&&(this.uniforms._TimeParameters.value=i.sceneLighting.timeVec4),this.uniforms._Time){const a=this.uniforms._Time.value;a.x=i.sceneLighting.timeVec4.x/20,a.y=i.sceneLighting.timeVec4.x,a.z=i.sceneLighting.timeVec4.x*2,a.w=i.sceneLighting.timeVec4.x*3}if(this.uniforms._SinTime){const a=this.uniforms._SinTime.value;a.x=Math.sin(i.sceneLighting.timeVec4.x/8),a.y=Math.sin(i.sceneLighting.timeVec4.x/4),a.z=Math.sin(i.sceneLighting.timeVec4.x/2),a.w=Math.sin(i.sceneLighting.timeVec4.x)}if(this.uniforms._CosTime){const a=this.uniforms._CosTime.value;a.x=Math.cos(i.sceneLighting.timeVec4.x/8),a.y=Math.cos(i.sceneLighting.timeVec4.x/4),a.z=Math.cos(i.sceneLighting.timeVec4.x/2),a.w=Math.cos(i.sceneLighting.timeVec4.x)}if(this.uniforms.unity_DeltaTime){const a=this.uniforms.unity_DeltaTime.value;a.x=i.time.deltaTime,a.y=1/i.time.deltaTime,a.z=i.time.smoothedDeltaTime,a.w=1/i.time.smoothedDeltaTime}const n=i.mainLight;if(n){const a=Y(n.gameObject,ve._mainLightPosition);this.uniforms._MainLightPosition={value:a.normalize()},ve._mainLightColor.set(n.color.r,n.color.g,n.color.b,0),this.uniforms._MainLightColor={value:ve._mainLightColor};const l=n.intensity;ve._lightData.z=l,this.uniforms.unity_LightData={value:ve._lightData}}if(e&&(ve.viewProjection&&this.uniforms[this._viewProjectionName]&&(this.uniforms[this._viewProjectionName].value=ve._viewProjectionValues),ve.viewMatrix&&this.uniforms[this._viewMatrixName]&&(this.uniforms[this._viewMatrixName].value=ve._viewMatrixValues),this.uniforms[ve._worldSpaceCameraPosName]&&(this.uniforms[ve._worldSpaceCameraPosName]={value:ve._worldSpaceCameraPos}),i.mainCameraComponent)){if(this.uniforms._ProjectionParams){const a=this.uniforms._ProjectionParams.value;a.x=1,a.y=i.mainCameraComponent.nearClipPlane,a.z=i.mainCameraComponent.farClipPlane,a.w=1/a.z,this.uniforms._ProjectionParams.value=a}if(this.uniforms._ZBufferParams){const a=this.uniforms._ZBufferParams.value,l=i.mainCameraComponent;a.x=1-l.farClipPlane/l.nearClipPlane,a.y=l.farClipPlane/l.nearClipPlane,a.z=a.x/l.farClipPlane,a.w=a.y/l.farClipPlane,this.uniforms._ZBufferParams.value=a}if(this.uniforms._ScreenParams){const a=this.uniforms._ScreenParams.value;a.x=i.domWidth,a.y=i.domHeight,a.z=1+1/a.x,a.w=1+1/a.y,this.uniforms._ScreenParams.value=a}if(this.uniforms._ScaledScreenParams){const a=this.uniforms._ScaledScreenParams.value;a.x=i.domWidth,a.y=i.domHeight,a.z=1+1/a.x,a.w=1+1/a.y,this.uniforms._ScaledScreenParams.value=a}}const o=this.depthTextureUniform;o&&(o.value=i.depthTexture);const r=this.opaqueTextureUniform;if(r&&(r.value=i.opaqueColorTexture),t){const a=this._rendererData;a.updateFrom(t),this.uniforms[this._worldToObjectName].value=a.worldToObject,this.uniforms[this._objToWorldName].value=a.objectToWorld}this.uniformsNeedUpdate=!0}}class Gk{get name(){return Qr}parser;identifier;constructor(e,t){this.parser=e,this.identifier=t}loadMaterial(e){const t=this.parser.json.materials[e];if(!t)return Mn&&console.log(e,this.parser.json.materials),null;if(!t.extensions||!t.extensions[Qr])return Mn&&console.log(`Material ${e} does not use NEEDLE_techniques_webgl`),null;Mn&&console.log(`Material ${e} uses NEEDLE_techniques_webgl`,t);const i=t.extensions[Qr].technique;if(i<0)return console.debug(`Material ${e} does not have a valid technique index`),null;const n=this.parser.json.extensions[Qr];if(!n)return Mn?console.error("Missing shader data",this.parser.json.extensions):console.debug("Missing custom shader data in parser.json.extensions"),null;Mn&&console.log(n);const o=n.techniques[i];return o?new Promise(async(r,a)=>{const l=await E1(n,o.program),h=l?.fragmentShader,d=l?.vertexShader;if(!h||!d)return a();Mn&&console.log("loadMaterial",t,l);const u={},p=o.uniforms;(d.includes("_Time")||h.includes("_Time"))&&(u._Time={value:new c.Vector4(0,0,0,0)}),(d.includes("_SinTime")||h.includes("_SinTime"))&&(u._SinTime={value:new c.Vector4(0,0,0,0)}),(d.includes("_CosTime")||h.includes("_CosTime"))&&(u._CosTime={value:new c.Vector4(0,0,0,0)}),(d.includes("unity_DeltaTime")||h.includes("unity_DeltaTime"))&&(u.unity_DeltaTime={value:new c.Vector4(0,0,0,0)});for(const v in p){const b=v;switch(b){case"_TimeParameters":const w=new c.Vector4;u[b]={value:w};break;case"hlslcc_mtx4x4unity_MatrixV":case"hlslcc_mtx4x4unity_MatrixVP":u[b]={value:[]};break;case"_MainLightPosition":case"_MainLightColor":case"_WorldSpaceCameraPos":u[b]={value:[0,0,0,1]};break;case"unity_OrthoParams":break;case"unity_SpecCube0":u[b]={value:null};break;default:case"_ScreenParams":case"_ZBufferParams":case"_ProjectionParams":u[b]={value:[0,0,0,0]};break;case"_CameraOpaqueTexture":case"_CameraDepthTexture":u[b]={value:null};break}}let m=!1;if(t.extensions&&t.extensions[Qr]){const v=t.extensions[Qr];if(v.technique===i){Mn&&console.log(t.name,"Material Properties",v);for(const b in v.values){const w=v.values[b];if(typeof w=="string"){if(w.startsWith("/textures/")){const R=w.substring(10),O=Number.parseInt(R);if(O>=0){const k=await this.parser.getDependency("texture",O);k instanceof c.Texture&&(k.colorSpace=c.LinearSRGBColorSpace,k.needsUpdate=!0),u[b]={value:k};continue}}if(b==="alphaMode"){w==="BLEND"&&(m=!0);continue}}if(Array.isArray(w)&&w.length===4){u[b]={value:new c.Vector4(w[0],w[1],w[2],w[3])};continue}u[b]={value:w}}}}const y=new ve(this.identifier,{name:t.name??"",uniforms:u,vertexShader:d,fragmentShader:h,lights:!1});switch(y.glslVersion=c.GLSL3,y.vertexShader=y.vertexShader.replace("#version 300 es",""),y.fragmentShader=y.fragmentShader.replace("#version 300 es",""),u._Cull?.value){case 0:y.side=c.DoubleSide;break;case 1:y.side=c.BackSide;break;case 2:y.side=c.FrontSide;break;default:y.side=c.FrontSide;break}switch(u._ZTest?.value){case 3:y.depthTest=!0,y.depthFunc=c.EqualDepth;break;case 6:y.depthTest=!0,y.depthFunc=c.NotEqualDepth;break;case 2:y.depthTest=!0,y.depthFunc=c.LessDepth;break;case 4:y.depthTest=!0,y.depthFunc=c.LessEqualDepth;break;case 5:y.depthTest=!0,y.depthFunc=c.GreaterDepth;break;case 7:y.depthTest=!0,y.depthFunc=c.GreaterEqualDepth;break;case 8:y.depthTest=!1,y.depthFunc=c.AlwaysDepth;break}y.transparent=m,m&&(y.depthWrite=!1),k1(u),y.onUpdateUniforms();for(const v in p){const b=v,w=p[v].type;u[b]?.value===void 0&&(w===Fw.SAMPLER_2D?(u[b]={value:P1},console.warn("Missing/unassigned texture, fallback to white: "+b)):b==="unity_OrthoParams"||console.warn("TODO: EXPECTED UNIFORM / fallback NOT SET: "+b,p[v]))}Mn&&console.log(y.uuid,u),Uw(y),r(y)}):null}}function Uw(s){if(s.uniforms){Mn&&console.log("Uniforms:",s.uniforms);for(const t in s.uniforms)switch(e(t,t),t){case"_Color":e("color",t);break;case"_map":e("map",t);break}}function e(t,i){Object.getOwnPropertyDescriptor(s,t)||Object.defineProperty(s,t,{get:()=>s.uniforms[i].value,set:n=>{s.uniforms[i].value=n,s.needsUpdate=!0}})}}const Hk=x("debugextensions");let ru;const qk=Promise.resolve().then(()=>require("./vendor-BlyEaMTL.umd.cjs")).then(s=>s.index$2).then(async s=>(ru=s.GLTFAnimationPointerExtension,ru)).catch(s=>{console.warn("Failed to import GLTFLoaderAnimationPointer. Please use @needle-tools/three-animationpointer for full KHR_animation support",s)}),mr=new Array;function Xk(s){mr.includes(s)||mr.push(s)}function Qk(s){const e=mr.indexOf(s);e>=0&&mr.splice(e,1)}function Vg(s){if(s instanceof X.GLTFLoader){const e=new Bw;return s.register(t=>(e.parser=t,e)),e}return null}class Yk{resolvePath(e){return e.includes("/extensions/builtin_components/")?e.replace("/extensions/builtin_components/","/userData/components/"):e.includes("extensions/builtin_components/")?e.replace("extensions/builtin_components/","/userData/components/"):e}}async function au(s,e,t,i){const n=t.indexOf("?");n>=0&&(t=t.substring(0,n)),i||(i=t),(i.startsWith("blob:")||i.startsWith("data:"))&&console.debug("[GLTFLoader] Suspicious sourceId detected"),s.register(o=>new zk(o)),s.register(o=>new ZC(o)),s.register(o=>new p1(o,e.lightmaps,i)),s.register(o=>new Nk(o,i,e)),s.register(o=>new Gk(o,i)),s.register(o=>new io(o,i)),s.register(o=>new re.NEEDLE_progressive(o)),s.register(o=>new jk(o)),s.register(o=>new wu(o)),s.register(o=>new $k(e,s,t,o)),W0()&&s.register(o=>new xa(o)),await qk.catch(o=>{}),s.register(o=>{if(ru){const r=new ru(o);return r.setAnimationPointerResolver.bind(r)(new Yk),r}else return(Hk||A())&&console.error("Missing KHR_animation_pointer extension..."),{name:"KHR_animation_pointer_NOT_AVAILABLE"}});for(const o of mr)o.onImport&&o.onImport(s,t,e)}function $g(s,e){for(const t of mr)t.onExport&&t.onExport(s,e)}function zw(s,e,t){for(const i of mr)i.onLoaded&&i.onLoaded(s,e,t)}const Mt=x("debuginstancing");class gr{static instance=new gr;static getStartInstanceCount=e=>4;objs=[];setup(e,t,i,n,o,r=0){e.applySettings(t);const a=this.tryCreateOrAddInstance(t,i,o);if(a){n===null&&(n=[]),n.push(a);const l=a.object.material;Array.isArray(l)?l.forEach(u=>re.NEEDLE_progressive.assignTextureLOD(u,0)):re.NEEDLE_progressive.assignTextureLOD(l,0);const h=a.object,d=h.geometry;re.NEEDLE_progressive.assignMeshLOD(h,0).then(u=>{u&&d!=u&&a.setGeometry(u)})}else if(r<=0&&t.type!=="Mesh"){const l=r+1;for(const h of t.children)n=this.setup(e,h,i,n,o,l)}return r===0&&o.useMatrixWorldAutoUpdate&&n&&n.length>=0&&this.autoUpdateInstanceMatrix(t),n}tryCreateOrAddInstance(e,t,i){if(e.type==="Mesh"){const n=i.foundMeshes;if(i.foundMeshes+=1,!i.rend.enableInstancing)return null;if(i.rend.enableInstancing!==!0){if(n>=i.rend.enableInstancing.length)return Mt&&console.error("Something is wrong with instance setup",e,i.rend.enableInstancing,n),null;if(!i.rend.enableInstancing[n])return null}const o=e,r=o.material;for(const u of this.objs){if(!u.canAdd(o.geometry,r))continue;return u.addInstance(o)}let a=gr.getStartInstanceCount(e);(!a||a<0)&&(a=4);let l=e.name;l?.length||(l=mv());const h=new Kk(l,o.geometry,r,a,t);return this.objs.push(h),h.addInstance(o)}return null}autoUpdateInstanceMatrix(e){const t=e.matrixWorld.multiplyMatrices.bind(e.matrixWorld),i=e.matrixWorld.clone(),n=(o,r)=>{const a=t(o,r);return(e[Cc]||i.equals(a)===!1)&&(i.copy(a),e[Cc]=!0),a};e.matrixWorld.multiplyMatrices=n}}class cr{static all=[];get name(){return this.object.name}get isActive(){return this.__instanceIndex>=0}get vertexCount(){return this.object.geometry.attributes.position.count}get maxVertexCount(){return Math.max(this.meshInformation.vertexCount,this.vertexCount)}get reservedVertexCount(){return this.__reservedVertexRange}get indexCount(){return this.object.geometry.index?this.object.geometry.index.count:0}get maxIndexCount(){return Math.max(this.meshInformation.indexCount,this.indexCount)}get reservedIndexCount(){return this.__reservedIndexRange}object;renderer;__instanceIndex=-1;__reservedVertexRange=0;__reservedIndexRange=0;__geometryIndex=-1;meshInformation;constructor(e,t){this.__instanceIndex=-1,this.object=e,this.renderer=t,e[Q0]=t,this.meshInformation=Ho(e.geometry),cr.all.push(this)}updateMeshInformation(){const e=Ho(this.object.geometry),t=this.meshInformation.vertexCount,i=this.meshInformation.indexCount;return Object.assign(this.meshInformation,e),t!==this.meshInformation.vertexCount||i!==this.meshInformation.indexCount}updateInstanceMatrix(e=!1,t=!0){this.__instanceIndex<0||(t&&this.object.updateWorldMatrix(!0,e),this.renderer.updateInstance(this.object.matrixWorld,this.__instanceIndex))}setMatrix(e){this.__instanceIndex<0||this.renderer.updateInstance(e,this.__instanceIndex)}setGeometry(e){if(this.__geometryIndex<0)return!1;const t=this;if(this.vertexCount>this.__reservedVertexRange)return i(`Instancing: Can not update geometry (${this.name}), reserved vertex range is too small: ${this.__reservedVertexRange.toLocaleString()} < ${this.vertexCount.toLocaleString()} vertices for ${this.name}`);if(this.indexCount>this.__reservedIndexRange)return i(`Instancing: Can not update geometry (${this.name}), reserved index range is too small: ${this.__reservedIndexRange.toLocaleString()} < ${this.indexCount.toLocaleString()} indices for ${this.name}`);return this.renderer.updateGeometry(e,this.__geometryIndex);function i(n){return t.updateMeshInformation()&&(t.renderer.remove(t,!0),t.renderer.add(t))?!0:((A()||Mt)&&console.error(n),!1)}}add(){this.__instanceIndex>=0||(this.renderer.add(this),S.markAsInstancedRendered(this.object,!0))}remove(e){if(!(this.__instanceIndex<0)&&(this.renderer.remove(this,e),S.markAsInstancedRendered(this.object,!1),e)){const t=cr.all.indexOf(this);t>=0&&cr.all.splice(t,1)}}}class Kk{get batchedMesh(){return this._batchedMesh}get visible(){return this._batchedMesh.visible}set visible(e){this._batchedMesh.visible=e}get castShadow(){return this._batchedMesh.castShadow}set castShadow(e){this._batchedMesh.castShadow=e}set receiveShadow(e){this._batchedMesh.receiveShadow=e}allowResize=!0;name="";geometry;material;get count(){return this._currentInstanceCount}updateBounds(e=!0,t=!0){if(this._needUpdateBounds=!1,e&&this._batchedMesh.computeBoundingBox(),t&&this._batchedMesh.computeBoundingSphere(),Mt&&this._batchedMesh.boundingSphere){const i=this._batchedMesh.boundingSphere;B.DrawWireSphere(i.center,i.radius,65280)}}_context;_batchedMesh;_handles=[];_geometryIds=new WeakMap;_maxInstanceCount;_currentInstanceCount=0;_currentVertexCount=0;_currentIndexCount=0;_maxVertexCount;_maxIndexCount;static nullMatrix=new c.Matrix4;canAdd(e,t){return this._maxVertexCount>1e7||t!==this.material||!this.validateGeometry(e)?!1:!!(!this.mustGrow(e)||this.allowResize)}_needUpdateBounds=!1;_debugMaterial=null;getBatchedMeshName(){return this.name?`${this.name} (BatchedMesh)`:"BatchedMesh"}constructor(e,t,i,n,o){this.name=e,this.geometry=t,this.material=i,this._context=o,this._maxInstanceCount=Math.max(2,n),Mt&&(this._debugMaterial=Sb());const r=this.tryEstimateVertexCountSize(this._maxInstanceCount,[t],n);this._maxVertexCount=r.vertexCount,this._maxIndexCount=r.indexCount,this._batchedMesh=new c.BatchedMesh(this._maxInstanceCount,this._maxVertexCount,this._maxIndexCount,this._debugMaterial??this.material),this._batchedMesh.name=this.getBatchedMeshName(),this._batchedMesh[Nl]=!0,this._batchedMesh.visible=!0,this._context.scene.add(this._batchedMesh),i instanceof c.RawShaderMaterial&&(i.defines.USE_INSTANCING=!0,i.needsUpdate=!0),o.pre_render_callbacks.push(this.onBeforeRender),o.post_render_callbacks.push(this.onAfterRender),Mt&&console.log(`Instanced renderer (${this.name}) created with ${this._maxInstanceCount} instances, ${this._maxVertexCount} max vertices and ${this._maxIndexCount} max indices for "${e}"`)}dispose(){Mt&&console.warn("Dispose instanced renderer",this.name),this._context.scene.remove(this._batchedMesh),this._batchedMesh.dispose(),this._batchedMesh=null,this._handles=[]}addInstance(e){const t=new cr(e,this);e.castShadow===!0&&this._batchedMesh.castShadow===!1&&(this._batchedMesh.castShadow=!0),e.receiveShadow===!0&&this._batchedMesh.receiveShadow===!1&&(this._batchedMesh.receiveShadow=!0);try{this.add(t)}catch(i){if(console.error(`Failed adding mesh to instancing (object name: "${e.name}", instances: ${this._currentInstanceCount.toLocaleString()}/${this._maxInstanceCount.toLocaleString()}, vertices: ${this._currentVertexCount.toLocaleString()}/${this._maxVertexCount.toLocaleString()}, indices: ${this._currentIndexCount.toLocaleString()}/${this._maxIndexCount.toLocaleString()})
1001
1001
  `,i),A()){$c("Failed instancing mesh. See the browser console for details.");debugger}return null}return t}add(e){const t=e.object.geometry;if(!t||!t.attributes)return console.error("Cannot add object to instancing without geometry",e.name),!1;if(this._currentInstanceCount+1>this._maxInstanceCount||this.mustGrow(t))if(this.allowResize)this.grow(t);else return console.error("Cannot add instance, max count reached",this.name,this.count,this._maxInstanceCount),!1;return e.object.updateWorldMatrix(!0,!0),this.addGeometry(e),this._handles[e.__instanceIndex]=e,this._currentInstanceCount+=1,this.markNeedsUpdate(),this._currentInstanceCount>0&&(this._batchedMesh.visible=!0),!0}remove(e,t){e&&(e.__instanceIndex<0||this._handles[e.__instanceIndex]!=e||this._currentInstanceCount<=0||(this.removeGeometry(e,t),this._handles[e.__instanceIndex]=null,e.__instanceIndex=-1,this._currentInstanceCount>0&&(this._currentInstanceCount-=1),this._currentInstanceCount<=0&&(this._batchedMesh.visible=!1),this.markNeedsUpdate()))}updateInstance(e,t){this._batchedMesh.setMatrixAt(t,e),this.markNeedsUpdate()}updateGeometry(e,t){return this.validateGeometry(e)?(this.mustGrow()&&this.grow(e),Mt&&console.debug("[Instancing] UPDATE GEOMETRY at "+t,this._batchedMesh._geometryCount,e.name,Ho(e),e.attributes.position.count,e.index?e.index.count:0),this._batchedMesh.setGeometryAt(t,e),this._geometryIds.set(e,t),this.markNeedsUpdate(),!0):!1}onBeforeRender=()=>{this._batchedMesh.layers.enableAll(),this._needUpdateBounds&&this._batchedMesh[Nl]===!0&&(Mt==="verbose"&&console.log("Update instancing bounds",this.name,this._batchedMesh.matrixWorldNeedsUpdate),this.updateBounds())};onAfterRender=()=>{this._batchedMesh.layers.disableAll()};validateGeometry(e){const t=this.geometry;for(const i in t.attributes)if(i!=="batchId"&&!e.hasAttribute(i))return A()&&console.warn(`BatchedMesh: Added geometry missing "${i}". All geometries must have consistent attributes.`),!1;return!0}markNeedsUpdate(){Mt==="verbose"&&console.warn("Marking instanced mesh dirty",this.name),this._needUpdateBounds=!0}mustGrow(e){if(this.count>=this._maxInstanceCount)return!0;if(!e||!e.attributes||this._geometryIds.has(e))return!1;const i=Ho(e),n=i.vertexCount,o=i.indexCount;return this._currentVertexCount+n>this._maxVertexCount||this._currentIndexCount+o>this._maxIndexCount}_growId=0;grow(e){const t=++this._growId,o=this.count>=this._maxInstanceCount?Math.ceil(this._maxInstanceCount*2):this._maxInstanceCount,r=this.tryEstimateVertexCountSize(o,[e]),a=1.25,l=Math.max(this._maxVertexCount,Math.ceil(r.vertexCount*a)),h=Math.max(this._maxIndexCount,Math.ceil(r.indexCount*a));if(Mt){const p=Ho(e);console.warn(`[Instancing] Growing Buffer
1002
1002
  Mesh: "${this.name}${e.name?.length?"/"+e.name:""}" (${p.vertexCount.toLocaleString()} vertices, ${p.indexCount.toLocaleString()} indices)
1003
1003
  Max count ${this._maxInstanceCount.toLocaleString()} → ${o.toLocaleString()}
@@ -1651,4 +1651,4 @@ Needle Engine: Begin loading `+i+`
1651
1651
  Needle Engine: finished loading `+i+`
1652
1652
  `,t,`Aborted? ${u.signal.aborted}`),u.signal.aborted){console.log("Loading finished but aborted...");return}if(this._loadId!==i){console.log("Load id changed during loading process");return}this._loadingProgress01=1,r&&y&&this._loadingView?.onLoadingUpdate(1,"creating scene"),this._didFullyLoad=!0,this.classList.remove("loading"),this.classList.add("loading-finished"),this.dispatchEvent(new CustomEvent("loadfinished",{detail:{context:this._context,src:n,loadedFiles:a}}))}applyAttributes(){const e=this.getOrCreateContext();if(e.renderer){const o=A0(this.toneMapping);o!==void 0&&(e.renderer.toneMapping=o);const r=this.getAttribute("tone-mapping-exposure");if(r!=null){const a=parseFloat(r);isNaN(a)||(e.renderer.toneMappingExposure=a)}}const t=this.getAttribute("background-blurriness");if(t!=null){const o=parseFloat(t);isNaN(o)||(e.scene.backgroundBlurriness=o)}const i=this.getAttribute("environment-intensity");if(i!=null){const o=parseFloat(i);isNaN(o)||(e.scene.environmentIntensity=o)}const n=this.getAttribute("background-color");if(e.renderer)if(typeof n=="string"&&n.length>0){const o=te.fromColorRepresentation(n);be&&console.debug("<needle-engine> background-color changed, str:",n,"→",o),e.renderer.setClearColor(o,o.alpha),e.scene.background=null}else this.getAttribute("background-image")&&this.setAttribute("background-image",this.getAttribute("background-image"))}onXRSessionStarted=()=>{const e=this.getOrCreateContext(),t=e.xrSessionMode;t==="immersive-ar"?this.onEnterAR(e.xrSession):t==="immersive-vr"&&this.onEnterVR(e.xrSession),e.xrSession?.addEventListener("end",()=>{this.dispatchEvent(new CustomEvent("xr-session-ended",{detail:{session:e.xrSession,context:this._context,sessionMode:t}})),t==="immersive-ar"?this.onExitAR(e.xrSession):t==="immersive-vr"&&this.onExitVR(e.xrSession)})};onReady=()=>this._loadingView?.onLoadingFinished();onError=()=>this._loadingView?.setMessage("Loading failed!");getSourceFiles(){const e=this.getAttribute("src");if(!e)return[];let t;Array.isArray(e)?t=e:e.startsWith("[")&&e.endsWith("]")?t=JSON.parse(e):e.includes(",")?t=e.split(","):t=[e];for(let i=t.length-1;i>=0;i--){const n=t[i];(n==="null"||n==="undefined"||n?.length<=0)&&t.splice(i,1)}return t}checkIfSourceHasChanged(e,t){if(e?.length!==t?.length||e==null&&t!==null||e!==null&&t==null)return!0;if(e!==null&&t!==null){for(let i=0;i<e?.length;i++)if(e[i]!==t[i])return!0}return!1}_previouslyRegisteredMap=new Map;ensureLoadStartIsRegistered(){const e=this.getAttribute("loadstart");e&&this.registerEventFromAttribute("loadstart",e)}registerEventFromAttribute(e,t){const i=this._previouslyRegisteredMap.get(e);if(i&&(this._previouslyRegisteredMap.delete(e),this.removeEventListener(e,i)),typeof t=="string"&&t.length>0)try{const n=(0,eval)(t);typeof n=="function"&&(this._previouslyRegisteredMap.set(e,n),this.addEventListener(e,o=>n?.call(globalThis,this.getOrCreateContext(),o)))}catch(n){console.error("Error registering event "+e+'="'+t+`" failed with the following error:
1653
1653
  `,n)}}setPublicKey(){er.length>0&&this.setAttribute("public-key",er)}setVersion(){ii.length>0&&this.setAttribute("version",ii)}getAROverlayContainer(){return this._overlay_ar.createOverlayContainer(this)}getVROverlayContainer(){for(let e=0;e<this.children.length;e++){const t=this.children[e];if(t.classList.contains("vr"))return t}return null}onEnterAR(e){const t=this.getOrCreateContext();this.onSetupAR();const i=this.getAROverlayContainer();this._overlay_ar.onBegin(t,i,e),this.dispatchEvent(new CustomEvent("enter-ar",{detail:{session:e,context:t,htmlContainer:this._overlay_ar?.ARContainer}}))}onExitAR(e){const t=this.getOrCreateContext();this._overlay_ar.onEnd(t),this.onSetupDesktop(),this.dispatchEvent(new CustomEvent("exit-ar",{detail:{session:e,context:t,htmlContainer:this._overlay_ar?.ARContainer}}))}onEnterVR(e){const t=this.getOrCreateContext();this.onSetupVR(),this.dispatchEvent(new CustomEvent("enter-vr",{detail:{session:e,context:t}}))}onExitVR(e){const t=this.getOrCreateContext();this.onSetupDesktop(),this.dispatchEvent(new CustomEvent("exit-vr",{detail:{session:e,context:t}}))}onSetupAR(){this.classList.add(Il),this.classList.remove(jl);const e=this.getAROverlayContainer();be&&console.warn("onSetupAR:",e),e&&(e.classList.add(Il),e.classList.remove(jl)),this.foreachHtmlElement(t=>this.setupElementsForMode(t,qx))}onSetupVR(){this.classList.remove(Il),this.classList.remove(jl),this.foreachHtmlElement(e=>this.setupElementsForMode(e,Xx))}onSetupDesktop(){this.classList.remove(Il),this.classList.add(jl);const e=this.getAROverlayContainer();e&&(e.classList.remove(Il),e.classList.add(jl)),this.foreachHtmlElement(t=>this.setupElementsForMode(t,Qx))}setupElementsForMode(e,t,i=null){if(e===this._context?.renderer?.domElement||e.id==="VRButton"||e.id==="ARButton")return;if(e.classList.contains(t))e.style.visibility="visible",e.style.display==="none"&&(e.style.display="block");else for(const o of pA)e.classList.contains(o)&&(e.style.visibility="hidden",e.style.display="none")}foreachHtmlElement(e){for(let t=0;t<this.children.length;t++){const i=this.children[t];i.style&&e(i)}}onBeforeBeginLoading(){const e=this.getAttribute("dracoDecoderPath");e&&(be&&console.log("using custom draco decoder path",e),Fb(e));const t=this.getAttribute("dracoDecoderType");t&&(be&&console.log("using custom draco decoder type",t),Ub(t));const i=this.getAttribute("ktx2DecoderPath");i&&(be&&console.log("using custom ktx2 decoder path",i),zb(i))}setAttribute(e,t){super.setAttribute(e,typeof t=="string"?t:String(t))}getAttribute(e){return super.getAttribute(e)}addEventListener(e,t,i){return super.addEventListener(e,t,i)}}function gA(s){if(s.startsWith("blob:"))return"blob";const e=s.split("/");let t=e[e.length-1];const i=t.indexOf("?");i>0&&(t=t.substring(0,i));const n=t.indexOf("=");n>0&&(t=t.substring(n));const o=t.split(".").pop(),a=o?["glb","gltf","usdz","usd","fbx","obj","mtl"].indexOf(o.toLowerCase()):-1;if(o&&a>=0&&(t=t.substring(0,t.length-o.length-1)),t=decodeURIComponent(t),t.length>3){let l="",h=!1;const d=["(",")","[","]","{","}",":",";",",",".","!","?"];for(let u=0;u<t.length;u++){let p=t[u];(p==="_"||p==="-")&&(p=" "),!(p===" "&&l.length<=0||d.includes(p)||(l.length===0&&(p=p.toUpperCase()),h&&p===" "))&&(h&&(p=p.toUpperCase()),h=!1,l+=p,p===" "&&(h=!0))}return A()&&t!==l&&console.debug('Generated display name: "'+t+'" → "'+l+'"'),l.trim()}return t}function yA(s){bu(e=>{const t=s.getAttribute("loading-blur");if(t!==null&&t!=="0"&&e.domElement===s){const i=e.lodsManager.manager?.awaitLoading({frames:5,signal:AbortSignal.timeout(1e4),maxPromisesPerObject:1}).catch(r=>{});let n="20px";t.endsWith("px")&&(n=t);const o=170;if(e.scene.background===null){const r=s,a=e.renderer.domElement,l=a.style.filter,h=a.style.overflow;a.style.filter+=`blur(${n})`,r.style.overflow="hidden",i?.then(()=>{const d=a.animate([{filter:"blur(0px)"}],{duration:o,easing:"ease-in"});d.onfinish=()=>{a.style.filter=l,r.style.overflow=h}})}else{const r=document.createElement("div");e.domElement.prepend(r),r.style.cssText="position: absolute; top: 0; left: 0; width: 100%; height: 100%; z-index: 10; pointer-events: none",r.style.backdropFilter=`blur(${n})`,i?.then(()=>{const a=r.animate([{backdropFilter:"blur(0px)",opacity:0}],{duration:o,easing:"ease-in"});a.onfinish=()=>{r.remove()}})}}},{once:!0})}const _A=Object.freeze(Object.defineProperty({__proto__:null,NeedleEngineWebComponent:Xy},Symbol.toStringTag,{value:"Module"}));function bA(){typeof window>"u"||(window.customElements.get("needle-engine")||window.customElements.define("needle-engine",Xy),window.customElements.get("needle-button")||window.customElements.define("needle-button",Hx),window.customElements.get("needle-logo-element")||window.customElements.define("needle-logo-element",Su),window.customElements.get("needle-menu")||window.customElements.define("needle-menu",wc))}let lv=!1;function vA(){lv||(lv=!0,bA(),cM(),T0(),yk(),cA(),CP(),hA(),QT(),nA(),setTimeout(YT,1e3),BO(),DO(),YO(),zO())}const Ee=x("debugphysics"),Rp=x("debugcolliderplacement"),Tp=x("debugcollisions"),wA=x("showcolliders"),md=x("debugraycasts"),Kt=Symbol("needle component"),gt=Symbol("physics body"),cv=Symbol("rigidbody");globalThis.NEEDLE_USE_RAPIER=globalThis.NEEDLE_USE_RAPIER!==void 0?globalThis.NEEDLE_USE_RAPIER:!0;Ee&&console.log("Use Rapier",!0,globalThis.NEEDLE_USE_RAPIER);ce.registerCallback(ae.ContextCreationStart,s=>{Ee&&console.log("Register rapier physics backend"),s.context.physics.engine=new Oa(s.context)});class Oa{debugRenderColliders=!1;debugRenderRaycasts=!1;removeBody(e){if(Ee&&console.log("REMOVE BODY",e?.name,e[gt]),!e)return;this.validate();const t=e[gt];if(e[gt]=null,t&&this.world){const i=this.objects.findIndex(n=>n===e);if(i>=0){const n=this.bodies[i];if(this.bodies.splice(i,1),this.objects.splice(i,1),n instanceof T.RAPIER_PHYSICS.MODULE.Collider){const o=n;this.world?.removeCollider(o,!0);const r=o.parent();r&&r.numColliders()<=0&&(r[Kt]||this.world?.removeRigidBody(r))}else n instanceof T.RAPIER_PHYSICS.MODULE.RigidBody&&(n.numColliders()<=0?this.world?.removeRigidBody(n):A()&&(n.did_log_removing||setTimeout(()=>{n.numColliders()>0&&(n.did_log_removing=!0,console.warn("RapierPhysics: removing rigidbody with colliders from the physics world is not possible right now, please remove the colliders first"))},1)))}}}setColliderEnabled(e,t){const i=e[gt];return i?(i.setEnabled(t),Ee&&console.log("SET COLLIDER ENABLED",e.name,t),!0):!1}updateBody(e,t,i){if(this.validate(),!!this.enabled&&!(e.destroyed||!e.gameObject)&&!(!t&&!i))if(e.isCollider===!0)console.warn("TODO: implement updating collider position");else{const n=e,o=n[gt];o&&this.syncPhysicsBody(n.gameObject,o,t,i)}}updateProperties(e){if(this.validate(),e.isCollider){const t=e,i=t[gt];i&&(this.internalUpdateColliderProperties(t,i),t.sharedMaterial&&this.updatePhysicsMaterial(t))}else{const t=e,i=this.internal_getRigidbody(t);i&&this.internalUpdateRigidbodyProperties(t,i)}}addForce(e,t,i){this.validate();const n=this.internal_getRigidbody(e);n?n.addForce(t,i):this._isInitialized&&console.warn("Physics Body doesn't exist: can not apply force (does your object with the Rigidbody have a collider?)")}addImpulse(e,t,i){this.validate();const n=this.internal_getRigidbody(e);n?n.applyImpulse(t,i):this._isInitialized&&console.warn("Physics Body doesn't exist: can not apply impulse (does your object with the Rigidbody have a collider?)")}getLinearVelocity(e){this.validate();const t=this.internal_getRigidbody(e);return t?t.linvel():null}getAngularVelocity(e){this.validate();const t=this.internal_getRigidbody(e);return t?t.angvel():null}resetForces(e,t){this.validate(),this.internal_getRigidbody(e)?.resetForces(t)}resetTorques(e,t){this.validate(),this.internal_getRigidbody(e)?.resetTorques(t)}applyImpulse(e,t,i){this.validate();const n=this.internal_getRigidbody(e);n?n.applyImpulse(t,i):this._isInitialized&&console.warn("Rigidbody doesn't exist: can not apply impulse (does your object with the Rigidbody have a collider?)")}wakeup(e){this.validate();const t=this.internal_getRigidbody(e);t?t.wakeUp():this._isInitialized&&console.warn("Rigidbody doesn't exist: can not wake up (does your object with the Rigidbody have a collider?)")}isSleeping(e){return this.validate(),this.internal_getRigidbody(e)?.isSleeping()}setAngularVelocity(e,t,i){this.validate();const n=this.internal_getRigidbody(e);n?n.setAngvel(t,i):this._isInitialized&&console.warn("Rigidbody doesn't exist: can not set angular velocity (does your object with the Rigidbody have a collider?)")}setLinearVelocity(e,t,i){this.validate();const n=this.internal_getRigidbody(e);n?n.setLinvel(t,i):this._isInitialized&&console.warn("Rigidbody doesn't exist: can not set linear velocity (does your object with the Rigidbody have a collider?)")}context;_initializePromise;_isInitialized=!1;constructor(e){this.context=e}get isInitialized(){return this._isInitialized}async initialize(){return this._initializePromise||(this._initializePromise=this.internalInitialization()),this._initializePromise}async internalInitialization(){return x("__nophysics")?(console.warn("Physics are disabled"),!1):(Ee&&console.log("Initialize rapier physics engine"),this._hasCreatedWorld?(console.error("Invalid call to create physics world: world is already created"),!0):(this._hasCreatedWorld=!0,T.RAPIER_PHYSICS.MAYBEMODULE==null&&(Ee&&console.trace("Loading rapier physics engine"),await(await T.RAPIER_PHYSICS.load()).init()),Ee&&console.log("Physics engine initialized, creating world..."),this._world=new T.RAPIER_PHYSICS.MODULE.World(this._gravity),this.rapierRay=new T.RAPIER_PHYSICS.MODULE.Ray({x:0,y:0,z:0},{x:0,y:0,z:1}),this.enabled=!0,this._isInitialized=!0,Ee&&console.log("Physics world created"),!0))}validate(){this._isInitialized||Ee&&(this._lastWarnTime=this._lastWarnTime??0,Date.now()-this._lastWarnTime>1e3&&(this._lastWarnTime=Date.now(),console.warn("Physics engine is not initialized")))}rapierRay;raycastVectorsBuffer=new _i(()=>new c.Vector3,10);raycast(e,t,i){if(!this._isInitialized)return console.log("Physics engine is not initialized"),null;let n=i?.maxDistance,o=i?.solid;n===void 0&&(n=1/0),o===void 0&&(o=!0);const r=this.getPhysicsRay(this.rapierRay,e,t);if(!r)return null;(this.debugRenderRaycasts||md)&&B.DrawRay(r.origin,r.dir,255,1);const a=this.world?.castRay(r,n,o,i?.queryFilterFlags,i?.filterGroups,void 0,void 0,l=>{const h=l[Kt];return i?.filterPredicate?i.filterPredicate(h):i?.useIgnoreRaycastLayer!==!1?!h?.gameObject.layers.isEnabled(2):!0});if(a){const l=r.pointAt(a.timeOfImpact),h=this.raycastVectorsBuffer.get();return h.set(l.x,l.y,l.z),{point:h,collider:a.collider[Kt]}}return null}raycastAndGetNormal(e,t,i){if(!this._isInitialized)return null;let n=i?.maxDistance,o=i?.solid;n===void 0&&(n=1/0),o===void 0&&(o=!0);const r=this.getPhysicsRay(this.rapierRay,e,t);if(!r)return null;(this.debugRenderRaycasts||md)&&B.DrawRay(r.origin,r.dir,255,1);const a=this.world?.castRayAndGetNormal(r,n,o,i?.queryFilterFlags,i?.filterGroups,void 0,void 0,l=>{const h=l[Kt];return i?.filterPredicate?i.filterPredicate(h):i?.useIgnoreRaycastLayer!==!1?!h?.gameObject.layers.isEnabled(2):!0});if(a){const l=r.pointAt(a.timeOfImpact),h=a.normal,d=this.raycastVectorsBuffer.get(),u=this.raycastVectorsBuffer.get();return d.set(l.x,l.y,l.z),u.set(h.x,h.y,h.z),{point:d,normal:u,collider:a.collider[Kt]}}return null}getPhysicsRay(e,t,i){const n=this.context?.mainCamera;if(t===void 0){const a=this.context?.input.getPointerPosition(0);if(a)t=a;else return null}if(t.z===void 0){if(!n)return console.error("Can not perform raycast from 2d point - no main camera found"),null;const a=this.raycastVectorsBuffer.get();a.x=t.x,a.y=t.y,a.z=0,(a.x>1||a.y>1||a.y<-1||a.x<-1)&&(Ee&&console.warn("Converting screenspace to raycast space",a),this.context?.input.convertScreenspaceToRaycastSpace(a)),a.unproject(n),t=a}const o=t;e.origin.x=o.x,e.origin.y=o.y,e.origin.z=o.z;const r=this.raycastVectorsBuffer.get();if(i)r.set(i.x,i.y,i.z);else{if(!n)return console.error("Can not perform raycast - no camera found"),null;r.set(e.origin.x,e.origin.y,e.origin.z);const a=Y(n);r.sub(a)}return r.normalize(),e.dir.x=r.x,e.dir.y=r.y,e.dir.z=r.z,e}rapierSphere=null;rapierBox=null;rapierColliderArray=[];rapierIdentityRotation={x:0,y:0,z:0,w:1};rapierForwardVector={x:0,y:0,z:1};sphereOverlap(e,t){return this.rapierSphere??=new T.RAPIER_PHYSICS.MODULE.Ball(t),this.rapierSphere.radius=t,(this.debugRenderRaycasts||md)&&B.DrawWireSphere(e,t,3359999,1),this.shapeOverlap(e,this.rapierIdentityRotation,this.rapierSphere)}boxOverlap(e,t,i=null){return i===null&&(i=this.rapierIdentityRotation),this.rapierBox??=new T.RAPIER_PHYSICS.MODULE.Cuboid(1,1,1),this.rapierBox.halfExtents.x=t.x*.5,this.rapierBox.halfExtents.y=t.y*.5,this.rapierBox.halfExtents.z=t.z*.5,(this.debugRenderRaycasts||md)&&B.DrawWireBox(e,t,3359999,1,!0,i),this.shapeOverlap(e,i,this.rapierBox)}shapeOverlap(e,t,i){return this.rapierColliderArray.length=0,this._isInitialized?this.world?(this.world.intersectionsWithShape(e,t,i,n=>{const o=n[Kt],r=new Qv(o.gameObject,o);return this.rapierColliderArray.push(r),!0},void 0,void 0,void 0,void 0,n=>n.isSensor()?!1:n[Kt].gameObject.layers.isEnabled(2)==!1),this.rapierColliderArray):this.rapierColliderArray:this.rapierColliderArray}enabled=!1;get world(){return this._world}_tempPosition=new c.Vector3;_tempQuaternion=new c.Quaternion;_tempScale=new c.Vector3;_tempMatrix=new c.Matrix4;static _didLoadPhysicsEngine=!1;_isUpdatingPhysicsWorld=!1;get isUpdating(){return this._isUpdatingPhysicsWorld}_world;_hasCreatedWorld=!1;eventQueue;collisionHandler;objects=[];bodies=[];_meshCache=new Map;_gravity={x:0,y:-9.81,z:0};get gravity(){return this.world?.gravity??this._gravity}set gravity(e){this.world?this.world.gravity=e:this._gravity=e}clearCaches(){this._meshCache.clear(),this.eventQueue?.raw&&this.eventQueue?.free(),this.world?.bodies&&this.world?.free()}async addBoxCollider(e,t){if(this._isInitialized||await this.initialize(),!e.activeAndEnabled)return;if(!this.enabled){Ee&&console.warn("Physics are disabled");return}const i=e.gameObject,n=je(i,this._tempPosition).multiply(t);n.multiplyScalar(.5),n.x<0&&(n.x=Math.abs(n.x)),n.y<0&&(n.y=Math.abs(n.y)),n.z<0&&(n.z=Math.abs(n.z));const o=1e-7;n.x<o&&(n.x=o),n.y<o&&(n.y=o),n.z<o&&(n.z=o);const r=T.RAPIER_PHYSICS.MODULE.ColliderDesc.cuboid(n.x,n.y,n.z);this.createCollider(e,r)}async addSphereCollider(e){if(this._isInitialized||await this.initialize(),!e.activeAndEnabled)return;if(!this.enabled){Ee&&console.warn("Physics are disabled");return}const t=T.RAPIER_PHYSICS.MODULE.ColliderDesc.ball(.5);this.createCollider(e,t),this.updateProperties(e)}async addCapsuleCollider(e,t,i){if(this._isInitialized||await this.initialize(),!e.activeAndEnabled)return;if(!this.enabled){Ee&&console.warn("Physics are disabled");return}const o=e.gameObject.worldScale;o.x=Math.abs(o.x),o.y=Math.abs(o.y);const r=i*o.x;t=Math.max(t,r);const a=I.clamp(t*.5*o.y-i*o.x,0,Number.MAX_SAFE_INTEGER),l=T.RAPIER_PHYSICS.MODULE.ColliderDesc.capsule(a,r);this.createCollider(e,l)}async addMeshCollider(e,t,i,n){let o=t.geometry;if(!o){Ee&&console.warn("Missing mesh geometry",t.name);return}o.index?.array?.length||(console.warn(`Your MeshCollider is missing vertices or indices in the assined mesh "${t.name}". Consider providing an indexed geometry.`),o=X.mergeVertices(o));let r=null;const a=o.getAttribute("position");if(a instanceof c.InterleavedBufferAttribute){const u=a.count;r=new Float32Array(u*3);for(let p=0;p<u;p++){const m=a.getX(p),y=a.getY(p),_=a.getZ(p);r[p*3]=m,r[p*3+1]=y,r[p*3+2]=_}}else r=a.array;if(await this.initialize(),!this.enabled){Ee&&console.warn("Physics are disabled");return}if(!e.activeAndEnabled)return;const l=o.index?.array,h=e.gameObject.worldScale.clone();if(n&&h.multiply(n),Math.abs(h.x-1)>1e-4||Math.abs(h.y-1)>1e-4||Math.abs(h.z-1)>1e-4){const u=`${o.uuid}_${h.x}_${h.y}_${h.z}_${i}`;if(this._meshCache.has(u))Ee&&console.warn("Use cached mesh collider"),r=this._meshCache.get(u);else{(Ee||A())&&console.debug(`[Performance] Your MeshCollider "${e.name}" is scaled: consider applying the scale to the collider mesh instead (${h.x}, ${h.y}, ${h.z})`);const p=new Float32Array(r.length);for(let m=0;m<r.length;m+=3)p[m]=r[m]*h.x,p[m+1]=r[m+1]*h.y,p[m+2]=r[m+2]*h.z;r=p,this._meshCache.set(u,p)}}const d=i?T.RAPIER_PHYSICS.MODULE.ColliderDesc.convexHull(r):T.RAPIER_PHYSICS.MODULE.ColliderDesc.trimesh(r,l);d&&this.createCollider(e,d)}updatePhysicsMaterial(e){if(!e)return;const t=e.sharedMaterial,i=e[gt];if(i&&t){if(t.bounciness!==void 0&&i.setRestitution(t.bounciness),t.bounceCombine!==void 0)switch(t.bounceCombine){case st.Average:i.setRestitutionCombineRule(T.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Average);break;case st.Maximum:i.setRestitutionCombineRule(T.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Max);break;case st.Minimum:i.setRestitutionCombineRule(T.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Min);break;case st.Multiply:i.setRestitutionCombineRule(T.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Multiply);break}if(t.dynamicFriction!==void 0&&i.setFriction(t.dynamicFriction),t.frictionCombine!==void 0)switch(t.frictionCombine){case st.Average:i.setFrictionCombineRule(T.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Average);break;case st.Maximum:i.setFrictionCombineRule(T.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Max);break;case st.Minimum:i.setFrictionCombineRule(T.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Min);break;case st.Multiply:i.setFrictionCombineRule(T.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Multiply);break}}}getBody(e){return e?e[gt]:null}getComponent(e){return e?e[Kt]:null}createCollider(e,t){if(!this.world)throw new Error("Physics world not initialized");const i=this._tempMatrix;let n;e.attachedRigidbody?n=this.getRigidbody(e,this._tempMatrix):(Ee&&console.log("Create collider without rigidbody",e.name),i.makeRotationFromQuaternion(pe(e.gameObject)),i.setPosition(Y(e.gameObject))),i.decompose(this._tempPosition,this._tempQuaternion,this._tempScale),this.tryApplyCenter(e,this._tempPosition),t.setTranslation(this._tempPosition.x,this._tempPosition.y,this._tempPosition.z),t.setRotation(this._tempQuaternion),t.setSensor(e.isTrigger);const o=e.sharedMaterial;if(o){if(o.bounciness!==void 0&&t.setRestitution(o.bounciness),o.bounceCombine!==void 0)switch(o.bounceCombine){case st.Average:t.setRestitutionCombineRule(T.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Average);break;case st.Maximum:t.setRestitutionCombineRule(T.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Max);break;case st.Minimum:t.setRestitutionCombineRule(T.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Min);break;case st.Multiply:t.setRestitutionCombineRule(T.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Multiply);break}if(o.dynamicFriction!==void 0&&t.setFriction(o.dynamicFriction),o.frictionCombine!==void 0)switch(o.frictionCombine){case st.Average:t.setFrictionCombineRule(T.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Average);break;case st.Maximum:t.setFrictionCombineRule(T.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Max);break;case st.Minimum:t.setFrictionCombineRule(T.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Min);break;case st.Multiply:t.setFrictionCombineRule(T.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Multiply);break}}e.attachedRigidbody?.autoMass===!1&&(t.setDensity(1e-6),t.setMass(1e-6));try{const r=this.world.createCollider(t,n);return r[Kt]=e,e[gt]=r,r.setActiveEvents(T.RAPIER_PHYSICS.MODULE.ActiveEvents.COLLISION_EVENTS),r.setActiveCollisionTypes(T.RAPIER_PHYSICS.MODULE.ActiveCollisionTypes.ALL),this.objects.push(e),this.bodies.push(r),this.updateColliderCollisionGroups(e),Ee&&console.log("Created collider",e.name,r),r}catch(r){return console.error('Error creating collider "'+e.name+`"
1654
- Error:`,r),null}}updateColliderCollisionGroups(e){const t=e[gt],i=e.membership;let n=0;if(i==null)n=65535;else for(let a=0;a<i.length;a++){const l=i[a];l>31?console.error(`Rapier only supports 32 layers, layer ${l} is not supported`):n|=1<<Math.floor(l)}const o=e.filter;let r=0;if(o==null)r=65535;else for(let a=0;a<o.length;a++){const l=o[a];l>31?console.error(`Rapier only supports 32 layers, layer ${l} is not supported`):r|=1<<Math.floor(l)}t.setCollisionGroups(n<<16|r)}getRigidbody(e,t){if(!this.world)throw new Error("Physics world not initialized");let i=null;if(e.attachedRigidbody){const n=e.attachedRigidbody;if(i=n[gt],!i){const o=n.isKinematic&&!Rp;Ee&&console.log("Create rigidbody",o);const r=o?T.RAPIER_PHYSICS.MODULE.RigidBodyDesc.kinematicPositionBased():T.RAPIER_PHYSICS.MODULE.RigidBodyDesc.dynamic(),a=Y(e.attachedRigidbody.gameObject);r.setTranslation(a.x,a.y,a.z),r.setRotation(pe(e.attachedRigidbody.gameObject)),r.centerOfMass=new T.RAPIER_PHYSICS.MODULE.Vector3(n.centerOfMass.x,n.centerOfMass.y,n.centerOfMass.z),i=this.world.createRigidBody(r),this.bodies.push(i),this.objects.push(n)}i[Kt]=n,n[gt]=i,this.internalUpdateRigidbodyProperties(n,i),this.getRigidbodyRelativeMatrix(e.gameObject,n.gameObject,t),e[cv]=i}else{const n=T.RAPIER_PHYSICS.MODULE.RigidBodyDesc.kinematicPositionBased(),o=Y(e.gameObject);n.setTranslation(o.x,o.y,o.z),n.setRotation(pe(e.gameObject)),i=this.world.createRigidBody(n),t.identity(),i[Kt]=null}return i}internal_getRigidbody(e){return e.isCollider===!0?e[cv]:e[gt]}internalUpdateColliderProperties(e,t){const i=t.shape;let n=!1;switch(i.type){case T.RAPIER_PHYSICS.MODULE.ShapeType.Ball:{const p=i,m=e,y=e.gameObject,_=je(y,this._tempPosition),g=Math.abs(m.radius*_.x);n=p.radius!==g,p.radius=g,n&&t.setShape(p);break}case T.RAPIER_PHYSICS.MODULE.ShapeType.Cuboid:const o=i,r=e,a=e.gameObject,l=je(a,this._tempPosition),h=Math.abs(r.size.x*.5*l.x),d=Math.abs(r.size.y*.5*l.y),u=Math.abs(r.size.z*.5*l.z);n=o.halfExtents.x!==h||o.halfExtents.y!==d||o.halfExtents.z!==u,o.halfExtents.x=h,o.halfExtents.y=d,o.halfExtents.z=u,n&&t.setShape(o);break}if(n){const o=e.attachedRigidbody;o?.autoMass&&this.getBody(o)?.recomputeMassPropertiesFromColliders()}this.updateColliderCollisionGroups(e),e.isTrigger!==t.isSensor()&&t.setSensor(e.isTrigger)}internalUpdateRigidbodyProperties(e,t){if(t.enableCcd(e.collisionDetectionMode!==Au.Discrete),t.setLinearDamping(e.drag),t.setAngularDamping(e.angularDrag),t.setGravityScale(e.useGravity?e.gravityScale:0,!0),e.dominanceGroup<=127&&e.dominanceGroup>=-127?t.setDominanceGroup(Math.floor(e.dominanceGroup)):t.setDominanceGroup(0),e.autoMass){t.setAdditionalMass(0,!1);for(let i=0;i<t.numColliders();i++)t.collider(i).setDensity(1);t.recomputeMassPropertiesFromColliders()}else{t.setAdditionalMass(e.mass,!1);for(let i=0;i<t.numColliders();i++)t.collider(i).setDensity(1e-7);t.recomputeMassPropertiesFromColliders()}t.setEnabledRotations(!e.lockRotationX,!e.lockRotationY,!e.lockRotationZ,!1),t.setEnabledTranslations(!e.lockPositionX,!e.lockPositionY,!e.lockPositionZ,!1),e.isKinematic?t.setBodyType(T.RAPIER_PHYSICS.MODULE.RigidBodyType.KinematicPositionBased,!1):t.setBodyType(T.RAPIER_PHYSICS.MODULE.RigidBodyType.Dynamic,!1)}lines;disabledLines;step(e){if(this.world&&this.enabled){if(this._isUpdatingPhysicsWorld=!0,this.eventQueue||(this.eventQueue=new T.RAPIER_PHYSICS.MODULE.EventQueue(!1)),e===void 0||e<=0){this._isUpdatingPhysicsWorld=!1;return}else if(e!==void 0){const t=I.lerp(this.world.timestep,e,.8);this.world.timestep=t}try{this.world.step(this.eventQueue)}catch(t){console.warn("Error running physics step",{timestep:this.world.timestep},t)}this._isUpdatingPhysicsWorld=!1}}postStep(){this.world&&this.enabled&&(this._isUpdatingPhysicsWorld=!0,this.syncObjects(),this._isUpdatingPhysicsWorld=!1,this.eventQueue&&!this.collisionHandler&&(this.collisionHandler=new xA(this.world,this.eventQueue)),this.collisionHandler&&(this.collisionHandler.handleCollisionEvents(),this.collisionHandler.update()),this.updateDebugRendering(this.world))}updateDebugRendering(e){if(Ee||Rp||wA||this.debugRenderColliders===!0){if(!this.lines){const n=new c.LineBasicMaterial({color:7855479,fog:!1}),o=new c.BufferGeometry;this.lines=new c.LineSegments(o,n),this.lines.layers.disableAll(),this.lines.layers.enable(2)}if(!this.disabledLines){const n=new c.LineBasicMaterial({color:14514039,fog:!1}),o=new c.BufferGeometry;this.disabledLines=new c.LineSegments(o,n),this.disabledLines.layers.disableAll(),this.disabledLines.layers.enable(2)}this.lines.parent!==this.context?.scene&&this.context?.scene.add(this.lines),this.disabledLines.parent!==this.context?.scene&&this.context?.scene.add(this.disabledLines);const t=e.debugRender(void 0,n=>n.isEnabled());this.lines.geometry.setAttribute("position",new c.BufferAttribute(t.vertices,3)),this.lines.geometry.setAttribute("color",new c.BufferAttribute(t.colors,4));const i=e.debugRender(void 0,n=>!n.isEnabled());this.disabledLines.geometry.setAttribute("position",new c.BufferAttribute(i.vertices,3)),this.disabledLines.geometry.setAttribute("color",new c.BufferAttribute(i.colors,4)),this.disabledLines.visible=i.vertices.length>0,(this.context.time.frame%30===0||this.lines.geometry.boundingSphere?.radius===0)&&(this.lines.geometry.computeBoundingSphere(),this.disabledLines.geometry.computeBoundingSphere())}else this.lines&&this.context?.scene.remove(this.lines),this.disabledLines&&this.context?.scene.remove(this.disabledLines)}syncObjects(){if(!Rp)for(let e=0;e<this.bodies.length;e++){const t=this.objects[e],i=this.bodies[e],n=t;if(n?.isCollider===!0&&!n.attachedRigidbody){const l=i.parent();l?this.syncPhysicsBody(t.gameObject,l,!0,!0):this.syncPhysicsBody(t.gameObject,i,!0,!0);continue}const o=i.translation(),r=i.rotation();if(Number.isNaN(o.x)||Number.isNaN(r.x)){!n.__COLLIDER_NAN&&A()&&(console.warn("Collider has NaN values",n.name,n.gameObject,i),n.__COLLIDER_NAN=!0);continue}const a=t.center;if(a&&a.isVector3){this._tempQuaternion.set(r.x,r.y,r.z,r.w);const l=this._tempPosition.copy(a).applyQuaternion(this._tempQuaternion),h=je(t.gameObject);l.multiply(h),o.x-=l.x,o.y-=l.y,o.z-=l.z}hr(t.gameObject,o.x,o.y,o.z),Nm(t.gameObject,r.x,r.y,r.z,r.w)}}syncPhysicsBody(e,t,i,n){if(t instanceof T.RAPIER_PHYSICS.MODULE.RigidBody){const o=Y(e,this._tempPosition),r=pe(e,this._tempQuaternion);switch(t.bodyType()){case T.RAPIER_PHYSICS.MODULE.RigidBodyType.Fixed:case T.RAPIER_PHYSICS.MODULE.RigidBodyType.KinematicPositionBased:case T.RAPIER_PHYSICS.MODULE.RigidBodyType.KinematicVelocityBased:i&&t.setNextKinematicTranslation(o),n&&t.setNextKinematicRotation(r);break;default:i&&t.setTranslation(o,!1),n&&t.setRotation(r,!1);break}}else if(t instanceof T.RAPIER_PHYSICS.MODULE.Collider){e.matrixWorldNeedsUpdate&&e.updateWorldMatrix(!0,!1),e.matrixWorld.decompose(this._tempPosition,this._tempQuaternion,this._tempScale);const o=this._tempPosition,r=this._tempQuaternion,a=t[Kt];if(this.tryApplyCenter(a,o),i){const l=t.translation();(l.x!==o.x||l.y!==o.y||l.z!==o.z)&&t.setTranslation(o)}if(n){const l=t.rotation();(l.x!==r.x||l.y!==r.y||l.z!==r.z||l.w!==r.w)&&t.setRotation(r)}}}_tempCenterPos=new c.Vector3;_tempCenterVec=new c.Vector3;_tempCenterQuaternion=new c.Quaternion;tryApplyCenter(e,t){const i=e.center;i&&e.gameObject&&(i.x!==0||i.y!==0||i.z!==0)&&(this._tempCenterPos.x=i.x,this._tempCenterPos.y=i.y,this._tempCenterPos.z=i.z,je(e.gameObject,this._tempCenterVec),this._tempCenterPos.multiply(this._tempCenterVec),e.attachedRigidbody?this._tempCenterPos.applyQuaternion(e.gameObject.quaternion):(pe(e.gameObject,this._tempCenterQuaternion),this._tempCenterPos.applyQuaternion(this._tempCenterQuaternion)),t.x+=this._tempCenterPos.x,t.y+=this._tempCenterPos.y,t.z+=this._tempCenterPos.z)}static _matricesBuffer=[];getRigidbodyRelativeMatrix(e,t,i,n){if(n===void 0&&(n=Oa._matricesBuffer,n.length=0),e===t){const o=je(e,this._tempPosition);i.makeScale(o.x,o.y,o.z);for(let r=n.length-1;r>=0;r--)i.multiply(n[r]);return i}return n.push(e.matrix),e.parent&&this.getRigidbodyRelativeMatrix(e.parent,t,i,n),i}static centerConnectionPos={x:0,y:0,z:0};static centerConnectionRot={x:0,y:0,z:0,w:1};addFixedJoint(e,t){if(!this.world){console.error("Physics world not initialized");return}const i=e[gt],n=t[gt];this.calculateJointRelativeMatrices(e.gameObject,t.gameObject,this._tempMatrix),this._tempMatrix.decompose(this._tempPosition,this._tempQuaternion,this._tempScale);const o=T.RAPIER_PHYSICS.MODULE.JointData.fixed(Oa.centerConnectionPos,Oa.centerConnectionRot,this._tempPosition,this._tempQuaternion),r=this.world.createImpulseJoint(o,i,n,!0);Ee&&console.log("ADD FIXED JOINT",r)}addHingeJoint(e,t,i,n){if(!this.world){console.error("Physics world not initialized");return}const o=e[gt],r=t[gt];this.calculateJointRelativeMatrices(e.gameObject,t.gameObject,this._tempMatrix),this._tempMatrix.decompose(this._tempPosition,this._tempQuaternion,this._tempScale);const a=T.RAPIER_PHYSICS.MODULE.JointData.revolute(i,this._tempPosition,n),l=this.world.createImpulseJoint(a,o,r,!0);Ee&&console.log("ADD HINGE JOINT",l)}calculateJointRelativeMatrices(e,t,i){e.updateWorldMatrix(!0,!1),t.updateWorldMatrix(!0,!1);const n=e.matrixWorld,o=t.matrixWorld;n.elements[0]=1,n.elements[5]=1,n.elements[10]=1,o.elements[0]=1,o.elements[5]=1,o.elements[10]=1,i.copy(o).premultiply(n.invert()).invert()}}class xA{world;eventQueue;constructor(e,t){this.world=e,this.eventQueue=t}activeCollisions=[];activeCollisionsStay=[];activeTriggers=[];handleCollisionEvents(){this.eventQueue&&this.world&&this.eventQueue.drainCollisionEvents((e,t,i)=>{const n=this.world.getCollider(e),o=this.world.getCollider(t);if(!n||!o)return;const r=n[Kt],a=o[Kt];Tp&&console.log("EVT",r.name,a.name,i,n,o),r&&a&&(i?(this.onCollisionStarted(r,n,a,o),this.onCollisionStarted(a,o,r,n)):(this.onCollisionEnded(r,a),this.onCollisionEnded(a,r)))})}update(){this.onHandleCollisionStay()}onCollisionStarted(e,t,i,n){let o=null;if(e.isTrigger||i.isTrigger)ur(e.gameObject,r=>{r.onTriggerEnter&&!r.destroyed&&r.onTriggerEnter(i),this.activeTriggers.push({collider:e,component:r,otherCollider:i})});else{const r=e.gameObject;this.world.contactPair(t,n,(a,l)=>{ur(r,h=>{if(h.destroyed)return;const d=h.onCollisionEnter||h.onCollisionStay||h.onCollisionExit;if(d||Tp){if(!o){const u=[],p=a.normal();i instanceof wo&&i.convex&&(p.x=-p.x,p.y=-p.y,p.z=-p.z);for(let m=0;m<a.numSolverContacts();m++){const y=a.solverContactPoint(m),_=a.contactImpulse(m);if(y){const g=a.contactDist(m),v=a.solverContactFriction(m),b=a.solverContactTangentVelocity(m),w=new qv(y,g,p,_,v,b);u.push(w),Tp&&B.DrawDirection(y,p,16711680,3,!0)}}o=new Xv(r,i,u)}if(d){const u={collider:e,component:h,collision:o};this.activeCollisions.push(u),h.onCollisionStay&&this.activeCollisionsStay.push(u),h.onCollisionEnter?.call(h,o)}}})})}}onHandleCollisionStay(){for(const e of this.activeCollisionsStay){const t=e.component;if(!t.destroyed&&t.activeAndEnabled&&t.onCollisionStay){if(e.collision.collider.destroyed)continue;const i=e.collision;t.onCollisionStay(i)}}for(const e of this.activeTriggers){const t=e.component;if(!t.destroyed&&t.activeAndEnabled&&t.onTriggerStay){const i=e.otherCollider;if(i.destroyed)continue;t.onTriggerStay(i)}}}onCollisionEnded(e,t){if(!(e.destroyed||t.destroyed)){for(let i=0;i<this.activeCollisions.length;i++){const n=this.activeCollisions[i],o=n.collider;if(o.destroyed||n.collision.collider.destroyed){this.activeCollisions.splice(i,1),i--;continue}if(o===e&&n.collision.collider===t){const r=n.component;if(this.activeCollisions.splice(i,1),i--,r.activeAndEnabled&&r.onCollisionExit){const a=n.collision;r.onCollisionExit(a)}}}for(let i=0;i<this.activeCollisionsStay.length;i++){const n=this.activeCollisionsStay[i],o=n.collider;if(o.destroyed||n.collision.collider.destroyed){this.activeCollisionsStay.splice(i,1),i--;continue}if(o===e&&n.collision.collider===t){const r=n.component;if(this.activeCollisionsStay.splice(i,1),i--,r.activeAndEnabled&&r.onCollisionExit){const a=n.collision;r.onCollisionExit(a)}}}for(let i=0;i<this.activeTriggers.length;i++){const n=this.activeTriggers[i],o=n.collider;if(o.destroyed||n.otherCollider.destroyed){this.activeTriggers.splice(i,1),i--;continue}if(o===e&&n.otherCollider===t){const r=n.component;if(this.activeTriggers.splice(i,1),i--,r.activeAndEnabled&&r.onTriggerExit){const a=n.otherCollider;r.onTriggerExit(a)}}}}}}let Am=0;function hv(s){s?Am++:Am--}function SA(){return Am>0}const CA={binary:!0,animations:!0};async function PA(s){if(!s.context)throw new Error("No context provided to exportAsGLTF");s.scene||(s.scene=s.context.scene);const e={...CA,...s},{context:t}=e,i=new X.GLTFExporter;i.register(a=>new $w(a)),i.register(a=>new aM(a)),i.register(a=>new Gw(a)),$g(i,e.context);const n={binary:e.binary,animations:kA(t,e.scene,[])},o=new OA;console.debug("Exporting GLTF",n),o.onBeforeExport(e),hv(!0);const r=await i.parseAsync(e.scene,n).catch(a=>(console.error(a),null));if(hv(!1),o.onAfterExport(e),!r)throw new Error("Failed to export GLTF");if(e.downloadAs!=null){let a=null;if(r instanceof ArrayBuffer?a=new Blob([r],{type:"application/octet-stream"}):console.error("Can not download GLTF as a blob",r),a){const l=URL.createObjectURL(a),h=document.createElement("a");h.href=l;let d=e.downloadAs;!d.endsWith(".glb")&&!d.endsWith(".gltf")&&(d+=e.binary?".glb":".gltf"),h.download=d,h.click()}}return r}const dv=Symbol("needle:weight");class OA{_undo=[];onBeforeExport(e){e.context.animations.mixers.forEach(t=>{const i=Hn.tryGetActionsFromMixer(t);if(i)for(let n=0;n<i.length;n++){const o=i[n];o[dv]=o.weight,o.weight=0,this._undo.push(()=>{o.weight=o[dv]})}t.update(0)}),e.context.scene.traverse(t=>{if(!mm(t)){const i=t.parent;i&&(t.removeFromParent(),this._undo.push(()=>i.add(t)))}})}onAfterExport(e){this._undo.forEach(t=>t()),this._undo.length=0}}function kA(s,e,t){s.animations.mixers.forEach(n=>{const o=Hn.tryGetActionsFromMixer(n);if(o)for(let r=0;r<o.length;r++){const l=o[r].getClip();t.push(l)}}),Array.isArray(e)||(e=[e]);for(const n of e)Hn.tryGetAnimationClipsFromObjectHierarchy(n,t);const i=new Set(t);return Array.from(i)}const Bl=x("debugavatar");class Qy{root;head;leftHand;rigthHand;get isValid(){return this.head!==null&&this.head!==void 0}constructor(e,t,i,n){this.root=e,this.head=t,this.leftHand=i,this.rigthHand=n,this.root?.traverse(o=>o.layers.set(2))}}class Yx{avatarRegistryUrl=null;async getOrCreateNewAvatarInstance(e,t){if(!t)return console.error("Can not create avatar: failed to provide id or root object"),null;let i=null;if(typeof t=="string"){if(i=await this.loadAvatar(e,t),!i){const o=new gn;i=S.instantiate(ka(t,e.scene),o)}}else i=t;if(!i)return null;const n=this.findAvatar(i);return n.isValid?(Bl&&console.log("[Custom Avatar] valid config",t,Bl?n:""),n):(console.warn("[Custom Avatar] config isn't valid",t,Bl?n:""),null)}async loadAvatar(e,t){if(console.assert(t!=null&&typeof t=="string","Avatar id must not be null"),t.length<=0||!t)return null;if(Bl&&console.log("[Custom Avatar] "+t+", loading..."),t.endsWith(".glb")||(t+=".glb"),this.avatarRegistryUrl===null){const n=await fetch("./"+t);let o=null;if(n.ok){const a=await n.blob();a&&(o=await a.arrayBuffer())}return o?(await un().parseSync(e,o,null,0))?.scene??null:null}const i=new X.GLTFLoader;return cy(i,e),new Promise((n,o)=>{const r=this.avatarRegistryUrl+"/"+t;i.load(r,async a=>{await un().createBuiltinComponents(e,r,a,null,void 0),n(a.scene)},a=>{Bl&&console.log("[Custom Avatar] "+a.loaded/a.total*100+"% loaded of "+a.total/1024+"kB")},a=>{console.error("[Custom Avatar] Error when loading: "+a),n(null)})})}cacheModel(e,t){}findAvatar(e){const t=e;let i=t;i.children.length==1&&(i=e.children[0]);let n=this.findAvatarPart(i,["head"]);const o=this.findAvatarPart(i,["left","hand"]),r=this.findAvatarPart(i,["right","hand"]);if(!n){n=t;const l=new c.Vector3;new c.Box3().setFromObject(n).getSize(l);const h=Math.max(l.x,l.y,l.z);console.warn("[Custom Avatar] Normalizing head scale, it's too big: "+h+" meters! Should be < 0.3m"),h>.3&&n.scale.multiplyScalar(1/h*.3)}return new Qy(t,n,o,r)}findAvatarPart(e,t){const i=e.name.toLowerCase();let n=!0;for(const o of t){if(!n)break;i.indexOf(o)===-1&&(n=!1)}if(n)return e;if(e.children)for(const o of e.children){const r=this.findAvatarPart(o,t);if(r)return r}return null}handleCustomAvatarErrors(e){if(!e.ok)throw Error(e.statusText);return e}}class Kx{get extensionName(){return"DocumentExtension"}onAfterBuildDocument(e){}}class Zx{}const MA=Object.freeze(Object.defineProperty({__proto__:null,ActionBuilder:ue,ActionCollection:rx,ActionModel:Jt,AlignmentConstraint:ih,Animation:Tt,AnimationCurve:yh,AnimationExtension:Xu,AnimationTrackHandler:Rc,Animator:lt,AnimatorController:Vi,Antialiasing:bh,Attractor:al,AudioExtension:kr,AudioListener:ds,AudioSource:vi,AudioTrackHandler:us,Avatar:fo,AvatarBlink_Simple:Sr,AvatarEyeLook_Rotation:Dg,AvatarLoader:Yx,AvatarMarker:Oe,AvatarModel:Qy,Avatar_Brain_LookAt:Ac,Avatar_MouthShapes:sh,Avatar_MustacheShake:Ag,Avatar_POI:lr,AxesHelper:qa,BaseUIComponent:Wi,BasicIKConstraint:jg,BehaviorExtension:hy,BehaviorModel:St,BloomEffect:hf,BoxCollider:Vu,BoxGizmo:Tr,BoxHelperComponent:bt,Button:Ls,CallInfo:ls,Camera:si,CameraTargetReachedEvent:Ec,Canvas:Fa,CanvasGroup:po,CapsuleCollider:bs,ChangeMaterialOnClick:iy,ChangeTransformOnClick:Mr,CharacterController:Cr,CharacterControllerInput:Cs,ChromaticAberration:vh,ClickThrough:wf,ColorAdjustments:Mo,ColorBySpeedModule:rl,ColorOverLifetimeModule:af,ContactShadows:oh,ControlTrackHandler:Bu,CursorFollow:Vr,CustomBranding:Rr,Deletable:zg,DeleteBox:ro,DepthOfField:bn,DeviceFlag:$u,DocumentExtension:Kx,DragControls:Yo,DropListener:Os,Duplicatable:qg,EffectWrapper:jc,EmissionModule:Rs,EmphasizeOnClick:Ka,EnvironmentScene:Fu,EventList:ne,EventListEvent:Tu,EventSystem:Gt,EventTrigger:Hu,FieldWithDefault:Nw,FixedJoint:Py,Fog:il,GltfExport:Zg,GltfExportBox:Yg,Gradient:Lr,Graphic:ph,GraphicRaycaster:Lu,GridHelper:nl,GridLayoutGroup:yy,GroundProjectedEnv:Xn,GroupActionModel:Ko,HideOnStart:Ii,HingeJoint:gh,HorizontalLayoutGroup:gy,get HoverAnimation(){return exports.HoverAnimation},Image:dl,InheritVelocityModule:Ry,InputField:Ny,InstanceHandle:cr,InstancingHandler:gr,Interactable:Ug,Keyframe:oi,LODGroup:sf,LODModel:sl,Light:Ot,LimitVelocityOverLifetimeModule:nt,LogStats:Fg,LookAt:Vy,LookAtConstraint:xr,MainModule:Dt,MarkerTrackHandler:ju,MaskableGraphic:mh,MeshCollider:wo,MeshRenderer:lh,MinMaxCurve:H,MinMaxGradient:Dr,NeedleMenu:Yn,NestedGltf:ol,Networking:My,NoiseModule:me,ObjectRaycaster:$i,OffsetConstraint:Ar,OpenURL:ul,OrbitControls:he,Outline:tl,Padding:Er,ParticleBurst:du,ParticleSubEmitter:Ty,ParticleSystem:Ic,ParticleSystemRenderer:Yi,PhysicsExtension:dy,PixelationEffect:wh,PlayAnimationOnClick:Lc,PlayAudioOnClick:uo,PlayableDirector:ja,PlayerColor:Ua,PointerEventData:Zc,PostProcessingHandler:za,PreliminaryAction:Za,PreliminaryTrigger:hh,RawImage:_f,Rect:ux,RectTransform:mn,ReflectionProbe:os,RegisteredAnimationInfo:so,RemoteSkybox:Uu,Renderer:Ht,RendererLightmap:Wg,Rigidbody:$e,RotationBySpeedModule:Qi,RotationOverLifetimeModule:_n,SceneSwitcher:We,ScreenCapture:Eo,ScreenSpaceAmbientOcclusion:Ts,ScreenSpaceAmbientOcclusionN8:vn,ScrollFollow:Ds,SeeThrough:As,SetActiveOnClick:ny,ShadowCatcher:Ph,ShapeModule:Ey,SharpeningEffect:Sh,SignalAsset:Iu,SignalReceiver:eh,SignalReceiverEvent:Jc,SignalTrackHandler:Tc,Size:dx,SizeBySpeedModule:di,SizeOverLifetimeModule:Ir,SkinnedMeshRenderer:Gg,SmoothFollow:ff,SpatialGrabRaycaster:fr,SpatialHtml:Eh,SpatialTrigger:pf,SpatialTriggerReceiver:Gn,SpectatorCamera:mf,SphereCollider:Xa,SplineContainer:zr,SplineData:qn,SplineWalker:Zi,Sprite:ks,SpriteData:Pa,SpriteRenderer:ci,SpriteSheet:Ba,SubEmitterSystem:uu,SyncedCamera:By,SyncedRoom:wn,SyncedTransform:pn,TapGestureTrigger:oy,TeleportTarget:Ju,TestRunner:Fy,TestSimulateUserData:Uy,Text:Lt,TextBuilder:py,TextExtension:tf,TextureSheetAnimationModule:It,TiltShiftEffect:Zn,ToneMappingEffect:mo,TrailModule:De,TransformData:Ae,TransformGizmo:Nr,TriggerBuilder:Rt,TriggerModel:ao,UIRaycastUtils:xg,UIRootComponent:uh,USDZExporter:Wn,USDZText:ma,USDZUIExtension:by,UsageMarker:rh,VariantAction:ty,VelocityOverLifetimeModule:Fe,VerticalLayoutGroup:my,VideoPlayer:tt,get ViewBox(){return exports.ViewBox},Vignette:Fr,VisibilityAction:dh,Voip:vo,Volume:Ur,VolumeParameter:z,VolumeProfile:lf,WebARCameraBackground:Th,WebARSessionRoot:Ui,WebXR:ef,WebXRImageTracking:Ah,WebXRImageTrackingModel:js,WebXRPlaneTracking:Bs,WebXRTrackedImage:Na,XRControllerFollow:Is,XRControllerModel:vs,XRControllerMovement:xi,XRFlag:ji,XRRig:Cf,XRState:Wt,__Ignore:Zx},Symbol.toStringTag,{value:"Module"}));exports.SplineUtils=void 0;(s=>{function e(t,i=!1,n=.75){const o=new zr,r=1-I.clamp(n,0,1);return t.forEach((a,l)=>{const h=new c.Vector3;l<t.length-1?h.subVectors(t[l+1],a).normalize().multiplyScalar(r):i&&t.length>1&&h.subVectors(t[0],a).normalize().multiplyScalar(r);const d=new qn;d.position.copy(a),d.tangentIn.copy(h),d.tangentOut.copy(h),o.addKnot(d)}),o.closed=i,o}s.createFromPoints=e})(exports.SplineUtils||(exports.SplineUtils={}));class EA extends le.WorkerBase{constructor(){super(new Worker(new URL("/generateMeshBVH.worker-DT9A2Hrc.js",typeof document>"u"?require("url").pathToFileURL(__filename).href:ya&&ya.tagName.toUpperCase()==="SCRIPT"&&ya.src||new URL("needle-engine.bundle-BOAJ6UPK.umd.cjs",document.baseURI).href),{type:"module"})),this.name="GenerateMeshBVHWorker"}runTask(e,t,i={}){return new Promise((n,o)=>{if(t.getAttribute("position").isInterleavedBufferAttribute||t.index&&t.index.isInterleavedBufferAttribute)throw new Error("GenerateMeshBVHWorker: InterleavedBufferAttribute are not supported for the geometry attributes.");e.onerror=h=>{o(new Error(`[GenerateMeshBVHWorker] ${h.message||"Unknown error. Please check the server console. If you're using vite try adding 'three-mesh-bvh' to 'optimizeDeps.exclude' in your vite.config.js"}`))},e.onmessage=h=>{const{data:d}=h;if(d.error)o(new Error(d.error)),e.onmessage=null;else if(d.serialized){const{serialized:u,position:p}=d,m=le.MeshBVH.deserialize(u,t,{setIndex:!1}),y=Object.assign({setBoundingBox:!0},i);if(t.attributes.position.array=p,u.index)if(t.index)t.index.array=u.index;else{const _=new c.BufferAttribute(u.index,1,!1);t.setIndex(_)}y.setBoundingBox&&(t.boundingBox=m.getBoundingBox(new c.Box3)),i.onProgress&&i.onProgress(d.progress),n(m),e.onmessage=null}else i.onProgress&&i.onProgress(d.progress)};const r=t.index?t.index.array:null,a=t.attributes.position.array,l=[a];r&&l.push(r),e.postMessage({index:r,position:a,options:{...i,onProgress:null,includedProgressCallback:!!i.onProgress,groups:[...t.groups]}},l.map(h=>h.buffer).filter(h=>typeof SharedArrayBuffer>"u"||!(h instanceof SharedArrayBuffer)))})}}const RA=Object.freeze(Object.defineProperty({__proto__:null,GenerateMeshBVHWorker:EA},Symbol.toStringTag,{value:"Module"}));exports.$componentName=Hv;exports.$physicsKey=LC;exports.ActionBuilder=ue;exports.ActionCollection=rx;exports.ActionModel=Jt;exports.Addressables=p0;exports.AlignmentConstraint=ih;exports.AmbientMode=va;exports.Animation=Tt;exports.AnimationCurve=yh;exports.AnimationExtension=Xu;exports.AnimationTrackHandler=Rc;exports.AnimationUtils=Hn;exports.Animator=lt;exports.AnimatorConditionMode=Js;exports.AnimatorController=Vi;exports.AnimatorControllerParameterType=wg;exports.AnimatorStateInfo=Vl;exports.Antialiasing=bh;exports.Application=fn;exports.AssetDatabase=V0;exports.AssetReference=Z;exports.Attractor=al;exports.AudioExtension=kr;exports.AudioListener=ds;exports.AudioSource=vi;exports.AudioTrackHandler=us;exports.Avatar=fo;exports.AvatarBlink_Simple=Sr;exports.AvatarEyeLook_Rotation=Dg;exports.AvatarLoader=Yx;exports.AvatarMarker=Oe;exports.AvatarModel=Qy;exports.Avatar_Brain_LookAt=Ac;exports.Avatar_MouthShapes=sh;exports.Avatar_MustacheShake=Ag;exports.Avatar_POI=lr;exports.Axes=fa;exports.AxesHelper=qa;exports.BUILD_TIME=_c;exports.BaseUIComponent=Wi;exports.BasicIKConstraint=jg;exports.BehaviorExtension=hy;exports.BehaviorModel=St;exports.BloomEffect=hf;exports.BoxCollider=Vu;exports.BoxGizmo=Tr;exports.BoxHelperComponent=bt;exports.Button=Ls;exports.ButtonsFactory=Fi;exports.CallDirection=Cw;exports.CallInfo=ls;exports.Camera=si;exports.CameraTargetReachedEvent=Ec;exports.Canvas=Fa;exports.CanvasGroup=po;exports.CapsuleCollider=bs;exports.ChangeMaterialOnClick=iy;exports.ChangeTransformOnClick=Mr;exports.CharacterController=Cr;exports.CharacterControllerInput=Cs;exports.ChromaticAberration=vh;exports.CircularBuffer=_i;exports.ClearFlags=ar;exports.ClickThrough=wf;exports.ClipExtrapolation=kn;exports.Collider=Xi;exports.Collision=Xv;exports.CollisionDetectionMode=Au;exports.ColorAdjustments=Mo;exports.ColorBySpeedModule=rl;exports.ColorOverLifetimeModule=af;exports.Component=UP;exports.Component$1=E;exports.ComponentLifecycleEvents=gu;exports.Components=MA;exports.ConnectionEvents=S0;exports.ContactPoint=qv;exports.ContactShadows=oh;exports.Context=U;exports.ContextArgs=K1;exports.ContextEvent=ae;exports.ContextRegistry=ce;exports.ControlTrackHandler=Bu;exports.CursorFollow=Vr;exports.CustomBranding=Rr;exports.CustomShader=ve;exports.DefaultReflectionMode=Kd;exports.Deletable=zg;exports.DeleteBox=ro;exports.DepthOfField=bn;exports.DeviceFlag=$u;exports.DocumentExtension=Kx;exports.DragControls=Yo;exports.DragMode=Ng;exports.DropListener=Os;exports.Duplicatable=qg;exports.EffectWrapper=jc;exports.EmissionModule=Rs;exports.EmphasizeOnClick=Ka;exports.EngineLoadingView=Bc;exports.EnvironmentScene=Fu;exports.EventList=ne;exports.EventListEvent=Tu;exports.EventSystem=Gt;exports.EventTrigger=Hu;exports.FieldWithDefault=Nw;exports.FileReference=ir;exports.FileReferenceSerializer=g0;exports.FileSpawnModel=Ck;exports.File_Event=Aw;exports.FixedJoint=Py;exports.Fog=il;exports.FontStyle=fy;exports.FrameEvent=ge;exports.GENERATOR=Ea;exports.GameObject=S;exports.Gizmos=B;exports.GltfExport=Zg;exports.GltfExportBox=Yg;exports.Gradient=Lr;exports.Graphic=ph;exports.GraphicRaycaster=Lu;exports.Graphics=co;exports.GridHelper=nl;exports.GridLayoutGroup=yy;exports.GroundProjectedEnv=Xn;exports.GroupActionModel=Ko;exports.HideFlags=_u;exports.HideOnStart=Ii;exports.HingeJoint=gh;exports.HorizontalLayoutGroup=gy;exports.HorizontalWrapMode=yx;exports.HostData=GC;exports.Image=dl;exports.ImageReference=tr;exports.ImageReferenceSerializer=m0;exports.InheritVelocityModule=Ry;exports.Input=_0;exports.InputEventQueue=ti;exports.InputEvents=Pe;exports.InputField=Ny;exports.InstanceHandle=cr;exports.InstancingHandler=gr;exports.InstancingUtil=Ni;exports.InstantiateEvent=i0;exports.InstantiateIdProvider=xt;exports.InstantiateOptions=gn;exports.Interactable=Ug;exports.JoinedRoomResponse=w1;exports.KeyEventArgs=f1;exports.Keyframe=oi;exports.LODGroup=sf;exports.LODModel=sl;exports.LeftRoomResponse=x1;exports.Light=Ot;exports.LightData=E0;exports.LimitVelocityOverLifetimeModule=nt;exports.LoadingElementOptions=fA;exports.LogStats=Fg;exports.LogType=gi;exports.LookAt=Vy;exports.LookAtConstraint=xr;exports.MODULES=T;exports.MainModule=Dt;exports.MarkerTrackHandler=ju;exports.MarkerType=Pg;exports.MaskableGraphic=mh;exports.MaterialPropertyBlock=ys;exports.Mathf=I;exports.MeshCollider=wo;exports.MeshRenderer=lh;exports.MinMaxCurve=H;exports.MinMaxGradient=Dr;exports.NEEDLE_ENGINE_FEATURE_FLAGS=Xm;exports.NEKeyboardEvent=Fl;exports.NEPointerEvent=ss;exports.NeedleButtonElement=Hx;exports.NeedleEngineWebComponent=Xy;exports.NeedleMenu=Yn;exports.NeedlePatchesKey=_d;exports.NeedleXRController=ug;exports.NeedleXRSession=q;exports.NeedleXRSync=U0;exports.NeedleXRUtils=N0;exports.NestedGltf=ol;exports.NetworkConnection=P0;exports.NetworkedStreamEvents=Un;exports.NetworkedStreams=nh;exports.Networking=My;exports.NewInstanceModel=s0;exports.NoiseModule=me;exports.ObjectRaycaster=$i;exports.ObjectUtils=_o;exports.OffsetConstraint=Ar;exports.OneEuroFilter=gd;exports.OneEuroFilterXYZ=Um;exports.OpenURL=ul;exports.OrbitControls=he;exports.Outline=tl;exports.OwnershipEvent=C0;exports.OwnershipModel=lg;exports.PUBLIC_KEY=er;exports.Padding=Er;exports.ParticleBurst=du;exports.ParticleSubEmitter=Ty;exports.ParticleSystem=Ic;exports.ParticleSystemBaseBehaviour=ko;exports.ParticleSystemRenderer=Yi;exports.ParticleSystemShapeType=hu;exports.PeerHandle=fs;exports.PeerNetworking=x0;exports.Physics=Ia;exports.PhysicsExtension=dy;exports.PhysicsMaterialCombine=st;exports.PixelationEffect=wh;exports.PlayAnimationOnClick=Lc;exports.PlayAudioOnClick=uo;exports.PlayableDirector=ja;exports.PlayerColor=Ua;exports.PlayerState=zi;exports.PlayerStateEvent=cx;exports.PlayerSync=ay;exports.PlayerView=O0;exports.PlayerViewManager=k0;exports.PointerEventData=Zc;exports.PointerType=vu;exports.PostProcessingEffect=Qe;exports.PostProcessingEffectOrder=et;exports.PostProcessingHandler=za;exports.PreliminaryAction=Za;exports.PreliminaryTrigger=hh;exports.PrimitiveType=Va;exports.Progress=oe;exports.PromiseAllWithErrors=Bm;exports.PromiseErrorResult=Dp;exports.RGBAColor=te;exports.RapierPhysics=Oa;exports.RawImage=_f;exports.RaycastOptions=bo;exports.Rect=ux;exports.RectTransform=mn;exports.ReflectionProbe=os;exports.RegisteredAnimationInfo=so;exports.RemoteSkybox=Uu;exports.RenderTexture=Bn;exports.RenderTextureSerializer=mw;exports.Renderer=Ht;exports.RendererData=M0;exports.RendererLightmap=Wg;exports.Rigidbody=$e;exports.RigidbodyConstraints=Ve;exports.RoomEvents=K;exports.RotationBySpeedModule=Qi;exports.RotationOverLifetimeModule=_n;exports.SceneLightSettings=ou;exports.SceneSwitcher=We;exports.ScreenCapture=Eo;exports.ScreenSpaceAmbientOcclusion=Ts;exports.ScreenSpaceAmbientOcclusionN8=vn;exports.ScrollFollow=Ds;exports.SeeThrough=As;exports.SendQueue=ln;exports.SerializationContext=ng;exports.SetActiveOnClick=ny;exports.ShadowCatcher=Ph;exports.ShapeModule=Ey;exports.ShapeOverlapResult=Qv;exports.SharpeningEffect=Sh;exports.SignalAsset=Iu;exports.SignalReceiver=eh;exports.SignalReceiverEvent=Jc;exports.SignalTrackHandler=Tc;exports.Size=dx;exports.SizeBySpeedModule=di;exports.SizeOverLifetimeModule=Ir;exports.SkinnedMeshRenderer=Gg;exports.SmoothFollow=ff;exports.SpatialGrabRaycaster=fr;exports.SpatialHtml=Eh;exports.SpatialTrigger=pf;exports.SpatialTriggerReceiver=Gn;exports.SpectatorCamera=mf;exports.SphereCollider=Xa;exports.SphereIntersection=mg;exports.SplineContainer=zr;exports.SplineData=qn;exports.SplineWalker=Zi;exports.Sprite=ks;exports.SpriteData=Pa;exports.SpriteRenderer=ci;exports.SpriteSheet=Ba;exports.StateMachineBehaviour=WP;exports.StreamEndedEvent=Rg;exports.StreamReceivedEvent=Sw;exports.SubEmitterSystem=uu;exports.SyncedCamera=By;exports.SyncedRoom=wn;exports.SyncedTransform=pn;exports.TapGestureTrigger=oy;exports.TeleportTarget=Ju;exports.TestRunner=Fy;exports.TestSimulateUserData=Uy;exports.Text=Lt;exports.TextAnchor=qe;exports.TextBuilder=py;exports.TextExtension=tf;exports.TextureSheetAnimationModule=It;exports.TiltShiftEffect=Zn;exports.Time=R0;exports.ToneMappingEffect=mo;exports.TrackHandler=Ha;exports.TrackType=fi;exports.TrailModule=De;exports.TransformData=Ae;exports.TransformGizmo=Nr;exports.TriggerBuilder=Rt;exports.TriggerModel=ao;exports.TypeStore=P;exports.UIRaycastUtils=xg;exports.UIRootComponent=uh;exports.USDDocument=Jg;exports.USDObject=Xe;exports.USDWriter=Kw;exports.USDZExporter=Zw;exports.USDZExporter$1=Wn;exports.USDZText=ma;exports.USDZUIExtension=by;exports.UriSerializer=gw;exports.UsageMarker=rh;exports.UserJoinedOrLeftRoomModel=S1;exports.VERSION=ii;exports.VariantAction=ty;exports.VelocityOverLifetimeModule=Fe;exports.VerticalLayoutGroup=my;exports.VerticalWrapMode=gx;exports.VideoPlayer=tt;exports.ViewDevice=gs;exports.Vignette=Fr;exports.VisibilityAction=dh;exports.Voip=vo;exports.Volume=Ur;exports.VolumeParameter=z;exports.VolumeProfile=lf;exports.WaitForFrames=c1;exports.WaitForPromise=y0;exports.WaitForSeconds=sg;exports.Watch=ms;exports.WebARCameraBackground=Th;exports.WebARSessionRoot=Ui;exports.WebXR=ef;exports.WebXRButtonFactory=lo;exports.WebXRImageTracking=Ah;exports.WebXRImageTrackingModel=js;exports.WebXRPlaneTracking=Bs;exports.WebXRTrackedImage=Na;exports.XRControllerFollow=Is;exports.XRControllerModel=vs;exports.XRControllerMovement=xi;exports.XRFlag=ji;exports.XRRig=Cf;exports.XRState=Wt;exports.XRStateFlag=Dn;exports.__Ignore=Zx;exports.__internalNotifyObjectDestroyed=_P;exports.activeInHierarchyFieldName=jn;exports.addAttributeChangeCallback=Im;exports.addComponent=hn;exports.addCustomExtensionPlugin=Xk;exports.addNewComponent=or;exports.addPatch=yu;exports.apply=Ou;exports.applyHMRChanges=FP;exports.applyPrototypeExtensions=K0;exports.beginListenDestroy=n0;exports.beginListenInstantiate=r0;exports.binaryIdentifierCasts=og;exports.build_scene_functions=Y1;exports.builtinComponentKeyName=Go;exports.calculateProgress01=qy;exports.clearMessages=kS;exports.colorSerializer=KP;exports.compareAssociation=h0;exports.componentSerializer=kd;exports.copyTexture=Av;exports.createMotion=fw;exports.debugNet=Yt;exports.debugOwner=Ul;exports.decompressGpuTexture=ix;exports.deepClone=Uc;exports.delay=_s;exports.delayForFrames=zc;exports.deserializeObject=Qd;exports.destroy=bi;exports.destroyComponentInstance=aw;exports.determineMimeTypeFromExtension=Lw;exports.disposeObjectResources=we;exports.disposeStream=zn;exports.editorGuidKeyName=ec;exports.enableSpatialConsole=_a;exports.euler=JP;exports.eventListSerializer=nO;exports.exportAsGLTF=PA;exports.findByGuid=_g;exports.findObjectOfType=Ga;exports.findObjectsOfType=cw;exports.findResourceUsers=gg;exports.fitCamera=yw;exports.fitObjectIntoVolume=Dv;exports.foreachComponent=ur;exports.foreachComponentEnumerator=Mu;exports.forward=HS;exports.generateQRCode=I0;exports.generateSeed=o0;exports.getBoundingBox=ri;exports.getCameraController=Cv;exports.getComponent=vr;exports.getComponentInChildren=Yc;exports.getComponentInParent=Pc;exports.getComponents=Qc;exports.getComponentsInChildren=Wa;exports.getComponentsInParent=Eu;exports.getFormattedDate=qw;exports.getIconElement=wt;exports.getIconTexture=Kp;exports.getLoader=un;exports.getOrAddComponent=Xc;exports.getParam=x;exports.getParentHierarchyPath=QS;exports.getPath=oS;exports.getPeerOptions=y1;exports.getPeerjsInstance=w0;exports.getResourceUserCount=vP;exports.getTempColor=Mv;exports.getTempQuaternion=ei;exports.getTempVector=F;exports.getUrlParams=Fc;exports.getVisibleInCustomShadowRendering=Lv;exports.getWorldDirection=Ev;exports.getWorldEuler=Vm;exports.getWorldPosition=Y;exports.getWorldQuaternion=pe;exports.getWorldRotation=mu;exports.getWorldScale=je;exports.hasCommercialLicense=$n;exports.hasIndieLicense=Wc;exports.hasPointerEventComponent=iu;exports.hasProLicense=Vn;exports.hideDebugConsole=Fv;exports.imageToCanvas=nx;exports.initEngine=vA;exports.instantiate=ho;exports.invokeLoadedImportPluginHooks=zw;exports.invokeXRSessionEnd=D0;exports.invokeXRSessionStart=L0;exports.isActiveInHierarchy=Z0;exports.isActiveSelf=$a;exports.isAndroidDevice=dS;exports.isAnimationAction=Tv;exports.isComponent=Ym;exports.isDebugMode=tS;exports.isDesktop=aS;exports.isDestroyed=dr;exports.isDevEnvironment=A;exports.isDisposed=yP;exports.isExporting=SA;exports.isGLTFModel=Gv;exports.isHostedOnGlitch=uv;exports.isHotReloadEnabled=lm;exports.isHotReloading=jP;exports.isIPad=cS;exports.isIconElement=j0;exports.isLocalNetwork=yi;exports.isMacOS=fS;exports.isMobileDevice=lS;exports.isMozillaXR=uS;exports.isQuest=gS;exports.isResourceTrackingEnabled=W0;exports.isSafari=mS;exports.isUsingInstancing=ku;exports.isiOS=pS;exports.isiPad=hS;exports.loadAsset=oA;exports.loadPMREM=Eg;exports.loadSync=Hy;exports.logHierarchy=$d;exports.lookAtInverse=FS;exports.lookAtObject=Nc;exports.lookAtScreenPoint=US;exports.makeId=nS;exports.makeIdFromRandomWords=mv;exports.makeNameSafe=wi;exports.markAsInstancedRendered=J0;exports.microphonePermissionsGranted=yS;exports.nameof=eS;exports.nameofFactory=fv;exports.objectSerializer=pw;exports.offXRSessionEnd=D1;exports.offXRSessionStart=L1;exports.onAfterRender=BC;exports.onBeforeRender=jC;exports.onClear=DC;exports.onDestroy=IC;exports.onInitialized=Km;exports.onStart=bu;exports.onUpdate=Jv;exports.onXRSessionEnd=hg;exports.onXRSessionStart=xu;exports.parseSync=Wx;exports.placeOnSurface=Iv;exports.postprocessFBXMaterials=Gm;exports.prefix=hO;exports.pushState=pv;exports.randomNumber=sS;exports.registerBinaryType=rg;exports.registerComponent=Cu;exports.registerComponentExtension=Vg;exports.registerCustomEffectType=Ki;exports.registerExportExtensions=$g;exports.registerExtensions=au;exports.registerHotReloadType=hw;exports.registerLoader=Kv;exports.registerPrefabProvider=l0;exports.registerPrototypeExtensions=yg;exports.registerType=qm;exports.relativePathPrefix=yv;exports.removeAttributeChangeCallback=jm;exports.removeComponent=vg;exports.removeCustomImportExtensionType=Qk;exports.removePatch=RC;exports.resolveUrl=ws;exports.sanitizeString=gv;exports.saveImage=Nx;exports.screenshot=FT;exports.screenshot2=Gy;exports.sendDestroyed=Jm;exports.serializable=f;exports.serializeObject=u0;exports.serializeable=Be;exports.setActive=sc;exports.setAllowBalloonMessages=wv;exports.setAllowOverlayMessages=SS;exports.setAutoFitEnabled=Nd;exports.setCameraController=Bp;exports.setDestroyed=tw;exports.setDevEnvironment=AS;exports.setDisposable=H0;exports.setDontDestroy=na;exports.setOrAddParamsToUrl=Lp;exports.setParam=iS;exports.setParamWithoutReload=yc;exports.setPeerOptions=_1;exports.setResourceTrackingEnabled=gP;exports.setState=Lm;exports.setVisibleInCustomShadowRendering=Wm;exports.setWorldEuler=$m;exports.setWorldPosition=at;exports.setWorldPositionXYZ=hr;exports.setWorldQuaternion=dn;exports.setWorldQuaternionXYZW=Nm;exports.setWorldRotation=Rv;exports.setWorldRotationXYZ=Vc;exports.setWorldScale=Ma;exports.showBalloonError=$c;exports.showBalloonMessage=Se;exports.showBalloonWarning=fe;exports.showDebugConsole=Hm;exports.slerp=Ov;exports.syncDestroy=Gc;exports.syncField=Mg;exports.syncInstantiate=eg;exports.textureToCanvas=YS;exports.toSourceId=_v;exports.tryCastBinary=b0;exports.tryDetermineMimetypeFromBinary=Iw;exports.tryDetermineMimetypeFromURL=Dw;exports.tryFindObject=ka;exports.tryGetGuid=v0;exports.unregisterHotReloadType=dw;exports.unwatchWrite=Dm;exports.useForAutoFit=Pv;exports.validate=Ct;exports.watchWrite=pu;
1654
+ Error:`,r),null}}updateColliderCollisionGroups(e){const t=e[gt],i=e.membership;let n=0;if(i==null)n=65535;else for(let a=0;a<i.length;a++){const l=i[a];l>31?console.error(`Rapier only supports 32 layers, layer ${l} is not supported`):n|=1<<Math.floor(l)}const o=e.filter;let r=0;if(o==null)r=65535;else for(let a=0;a<o.length;a++){const l=o[a];l>31?console.error(`Rapier only supports 32 layers, layer ${l} is not supported`):r|=1<<Math.floor(l)}t.setCollisionGroups(n<<16|r)}getRigidbody(e,t){if(!this.world)throw new Error("Physics world not initialized");let i=null;if(e.attachedRigidbody){const n=e.attachedRigidbody;if(i=n[gt],!i){const o=n.isKinematic&&!Rp;Ee&&console.log("Create rigidbody",o);const r=o?T.RAPIER_PHYSICS.MODULE.RigidBodyDesc.kinematicPositionBased():T.RAPIER_PHYSICS.MODULE.RigidBodyDesc.dynamic(),a=Y(e.attachedRigidbody.gameObject);r.setTranslation(a.x,a.y,a.z),r.setRotation(pe(e.attachedRigidbody.gameObject)),r.centerOfMass=new T.RAPIER_PHYSICS.MODULE.Vector3(n.centerOfMass.x,n.centerOfMass.y,n.centerOfMass.z),i=this.world.createRigidBody(r),this.bodies.push(i),this.objects.push(n)}i[Kt]=n,n[gt]=i,this.internalUpdateRigidbodyProperties(n,i),this.getRigidbodyRelativeMatrix(e.gameObject,n.gameObject,t),e[cv]=i}else{const n=T.RAPIER_PHYSICS.MODULE.RigidBodyDesc.kinematicPositionBased(),o=Y(e.gameObject);n.setTranslation(o.x,o.y,o.z),n.setRotation(pe(e.gameObject)),i=this.world.createRigidBody(n),t.identity(),i[Kt]=null}return i}internal_getRigidbody(e){return e.isCollider===!0?e[cv]:e[gt]}internalUpdateColliderProperties(e,t){const i=t.shape;let n=!1;switch(i.type){case T.RAPIER_PHYSICS.MODULE.ShapeType.Ball:{const p=i,m=e,y=e.gameObject,_=je(y,this._tempPosition),g=Math.abs(m.radius*_.x);n=p.radius!==g,p.radius=g,n&&t.setShape(p);break}case T.RAPIER_PHYSICS.MODULE.ShapeType.Cuboid:const o=i,r=e,a=e.gameObject,l=je(a,this._tempPosition),h=Math.abs(r.size.x*.5*l.x),d=Math.abs(r.size.y*.5*l.y),u=Math.abs(r.size.z*.5*l.z);n=o.halfExtents.x!==h||o.halfExtents.y!==d||o.halfExtents.z!==u,o.halfExtents.x=h,o.halfExtents.y=d,o.halfExtents.z=u,n&&t.setShape(o);break}if(n){const o=e.attachedRigidbody;o?.autoMass&&this.getBody(o)?.recomputeMassPropertiesFromColliders()}this.updateColliderCollisionGroups(e),e.isTrigger!==t.isSensor()&&t.setSensor(e.isTrigger)}internalUpdateRigidbodyProperties(e,t){if(t.enableCcd(e.collisionDetectionMode!==Au.Discrete),t.setLinearDamping(e.drag),t.setAngularDamping(e.angularDrag),t.setGravityScale(e.useGravity?e.gravityScale:0,!0),e.dominanceGroup<=127&&e.dominanceGroup>=-127?t.setDominanceGroup(Math.floor(e.dominanceGroup)):t.setDominanceGroup(0),e.autoMass){t.setAdditionalMass(0,!1);for(let i=0;i<t.numColliders();i++)t.collider(i).setDensity(1);t.recomputeMassPropertiesFromColliders()}else{t.setAdditionalMass(e.mass,!1);for(let i=0;i<t.numColliders();i++)t.collider(i).setDensity(1e-7);t.recomputeMassPropertiesFromColliders()}t.setEnabledRotations(!e.lockRotationX,!e.lockRotationY,!e.lockRotationZ,!1),t.setEnabledTranslations(!e.lockPositionX,!e.lockPositionY,!e.lockPositionZ,!1),e.isKinematic?t.setBodyType(T.RAPIER_PHYSICS.MODULE.RigidBodyType.KinematicPositionBased,!1):t.setBodyType(T.RAPIER_PHYSICS.MODULE.RigidBodyType.Dynamic,!1)}lines;disabledLines;step(e){if(this.world&&this.enabled){if(this._isUpdatingPhysicsWorld=!0,this.eventQueue||(this.eventQueue=new T.RAPIER_PHYSICS.MODULE.EventQueue(!1)),e===void 0||e<=0){this._isUpdatingPhysicsWorld=!1;return}else if(e!==void 0){const t=I.lerp(this.world.timestep,e,.8);this.world.timestep=t}try{this.world.step(this.eventQueue)}catch(t){console.warn("Error running physics step",{timestep:this.world.timestep},t)}this._isUpdatingPhysicsWorld=!1}}postStep(){this.world&&this.enabled&&(this._isUpdatingPhysicsWorld=!0,this.syncObjects(),this._isUpdatingPhysicsWorld=!1,this.eventQueue&&!this.collisionHandler&&(this.collisionHandler=new xA(this.world,this.eventQueue)),this.collisionHandler&&(this.collisionHandler.handleCollisionEvents(),this.collisionHandler.update()),this.updateDebugRendering(this.world))}updateDebugRendering(e){if(Ee||Rp||wA||this.debugRenderColliders===!0){if(!this.lines){const n=new c.LineBasicMaterial({color:7855479,fog:!1}),o=new c.BufferGeometry;this.lines=new c.LineSegments(o,n),this.lines.layers.disableAll(),this.lines.layers.enable(2)}if(!this.disabledLines){const n=new c.LineBasicMaterial({color:14514039,fog:!1}),o=new c.BufferGeometry;this.disabledLines=new c.LineSegments(o,n),this.disabledLines.layers.disableAll(),this.disabledLines.layers.enable(2)}this.lines.parent!==this.context?.scene&&this.context?.scene.add(this.lines),this.disabledLines.parent!==this.context?.scene&&this.context?.scene.add(this.disabledLines);const t=e.debugRender(void 0,n=>n.isEnabled());this.lines.geometry.setAttribute("position",new c.BufferAttribute(t.vertices,3)),this.lines.geometry.setAttribute("color",new c.BufferAttribute(t.colors,4));const i=e.debugRender(void 0,n=>!n.isEnabled());this.disabledLines.geometry.setAttribute("position",new c.BufferAttribute(i.vertices,3)),this.disabledLines.geometry.setAttribute("color",new c.BufferAttribute(i.colors,4)),this.disabledLines.visible=i.vertices.length>0,(this.context.time.frame%30===0||this.lines.geometry.boundingSphere?.radius===0)&&(this.lines.geometry.computeBoundingSphere(),this.disabledLines.geometry.computeBoundingSphere())}else this.lines&&this.context?.scene.remove(this.lines),this.disabledLines&&this.context?.scene.remove(this.disabledLines)}syncObjects(){if(!Rp)for(let e=0;e<this.bodies.length;e++){const t=this.objects[e],i=this.bodies[e],n=t;if(n?.isCollider===!0&&!n.attachedRigidbody){const l=i.parent();l?this.syncPhysicsBody(t.gameObject,l,!0,!0):this.syncPhysicsBody(t.gameObject,i,!0,!0);continue}const o=i.translation(),r=i.rotation();if(Number.isNaN(o.x)||Number.isNaN(r.x)){!n.__COLLIDER_NAN&&A()&&(console.warn("Collider has NaN values",n.name,n.gameObject,i),n.__COLLIDER_NAN=!0);continue}const a=t.center;if(a&&a.isVector3){this._tempQuaternion.set(r.x,r.y,r.z,r.w);const l=this._tempPosition.copy(a).applyQuaternion(this._tempQuaternion),h=je(t.gameObject);l.multiply(h),o.x-=l.x,o.y-=l.y,o.z-=l.z}hr(t.gameObject,o.x,o.y,o.z),Nm(t.gameObject,r.x,r.y,r.z,r.w)}}syncPhysicsBody(e,t,i,n){if(t instanceof T.RAPIER_PHYSICS.MODULE.RigidBody){const o=Y(e,this._tempPosition),r=pe(e,this._tempQuaternion);switch(t.bodyType()){case T.RAPIER_PHYSICS.MODULE.RigidBodyType.Fixed:case T.RAPIER_PHYSICS.MODULE.RigidBodyType.KinematicPositionBased:case T.RAPIER_PHYSICS.MODULE.RigidBodyType.KinematicVelocityBased:i&&t.setNextKinematicTranslation(o),n&&t.setNextKinematicRotation(r);break;default:i&&t.setTranslation(o,!1),n&&t.setRotation(r,!1);break}}else if(t instanceof T.RAPIER_PHYSICS.MODULE.Collider){e.matrixWorldNeedsUpdate&&e.updateWorldMatrix(!0,!1),e.matrixWorld.decompose(this._tempPosition,this._tempQuaternion,this._tempScale);const o=this._tempPosition,r=this._tempQuaternion,a=t[Kt];if(this.tryApplyCenter(a,o),i){const l=t.translation();(l.x!==o.x||l.y!==o.y||l.z!==o.z)&&t.setTranslation(o)}if(n){const l=t.rotation();(l.x!==r.x||l.y!==r.y||l.z!==r.z||l.w!==r.w)&&t.setRotation(r)}}}_tempCenterPos=new c.Vector3;_tempCenterVec=new c.Vector3;_tempCenterQuaternion=new c.Quaternion;tryApplyCenter(e,t){const i=e.center;i&&e.gameObject&&(i.x!==0||i.y!==0||i.z!==0)&&(this._tempCenterPos.x=i.x,this._tempCenterPos.y=i.y,this._tempCenterPos.z=i.z,je(e.gameObject,this._tempCenterVec),this._tempCenterPos.multiply(this._tempCenterVec),e.attachedRigidbody?this._tempCenterPos.applyQuaternion(e.gameObject.quaternion):(pe(e.gameObject,this._tempCenterQuaternion),this._tempCenterPos.applyQuaternion(this._tempCenterQuaternion)),t.x+=this._tempCenterPos.x,t.y+=this._tempCenterPos.y,t.z+=this._tempCenterPos.z)}static _matricesBuffer=[];getRigidbodyRelativeMatrix(e,t,i,n){if(n===void 0&&(n=Oa._matricesBuffer,n.length=0),e===t){const o=je(e,this._tempPosition);i.makeScale(o.x,o.y,o.z);for(let r=n.length-1;r>=0;r--)i.multiply(n[r]);return i}return n.push(e.matrix),e.parent&&this.getRigidbodyRelativeMatrix(e.parent,t,i,n),i}static centerConnectionPos={x:0,y:0,z:0};static centerConnectionRot={x:0,y:0,z:0,w:1};addFixedJoint(e,t){if(!this.world){console.error("Physics world not initialized");return}const i=e[gt],n=t[gt];this.calculateJointRelativeMatrices(e.gameObject,t.gameObject,this._tempMatrix),this._tempMatrix.decompose(this._tempPosition,this._tempQuaternion,this._tempScale);const o=T.RAPIER_PHYSICS.MODULE.JointData.fixed(Oa.centerConnectionPos,Oa.centerConnectionRot,this._tempPosition,this._tempQuaternion),r=this.world.createImpulseJoint(o,i,n,!0);Ee&&console.log("ADD FIXED JOINT",r)}addHingeJoint(e,t,i,n){if(!this.world){console.error("Physics world not initialized");return}const o=e[gt],r=t[gt];this.calculateJointRelativeMatrices(e.gameObject,t.gameObject,this._tempMatrix),this._tempMatrix.decompose(this._tempPosition,this._tempQuaternion,this._tempScale);const a=T.RAPIER_PHYSICS.MODULE.JointData.revolute(i,this._tempPosition,n),l=this.world.createImpulseJoint(a,o,r,!0);Ee&&console.log("ADD HINGE JOINT",l)}calculateJointRelativeMatrices(e,t,i){e.updateWorldMatrix(!0,!1),t.updateWorldMatrix(!0,!1);const n=e.matrixWorld,o=t.matrixWorld;n.elements[0]=1,n.elements[5]=1,n.elements[10]=1,o.elements[0]=1,o.elements[5]=1,o.elements[10]=1,i.copy(o).premultiply(n.invert()).invert()}}class xA{world;eventQueue;constructor(e,t){this.world=e,this.eventQueue=t}activeCollisions=[];activeCollisionsStay=[];activeTriggers=[];handleCollisionEvents(){this.eventQueue&&this.world&&this.eventQueue.drainCollisionEvents((e,t,i)=>{const n=this.world.getCollider(e),o=this.world.getCollider(t);if(!n||!o)return;const r=n[Kt],a=o[Kt];Tp&&console.log("EVT",r.name,a.name,i,n,o),r&&a&&(i?(this.onCollisionStarted(r,n,a,o),this.onCollisionStarted(a,o,r,n)):(this.onCollisionEnded(r,a),this.onCollisionEnded(a,r)))})}update(){this.onHandleCollisionStay()}onCollisionStarted(e,t,i,n){let o=null;if(e.isTrigger||i.isTrigger)ur(e.gameObject,r=>{r.onTriggerEnter&&!r.destroyed&&r.onTriggerEnter(i),this.activeTriggers.push({collider:e,component:r,otherCollider:i})});else{const r=e.gameObject;this.world.contactPair(t,n,(a,l)=>{ur(r,h=>{if(h.destroyed)return;const d=h.onCollisionEnter||h.onCollisionStay||h.onCollisionExit;if(d||Tp){if(!o){const u=[],p=a.normal();i instanceof wo&&i.convex&&(p.x=-p.x,p.y=-p.y,p.z=-p.z);for(let m=0;m<a.numSolverContacts();m++){const y=a.solverContactPoint(m),_=a.contactImpulse(m);if(y){const g=a.contactDist(m),v=a.solverContactFriction(m),b=a.solverContactTangentVelocity(m),w=new qv(y,g,p,_,v,b);u.push(w),Tp&&B.DrawDirection(y,p,16711680,3,!0)}}o=new Xv(r,i,u)}if(d){const u={collider:e,component:h,collision:o};this.activeCollisions.push(u),h.onCollisionStay&&this.activeCollisionsStay.push(u),h.onCollisionEnter?.call(h,o)}}})})}}onHandleCollisionStay(){for(const e of this.activeCollisionsStay){const t=e.component;if(!t.destroyed&&t.activeAndEnabled&&t.onCollisionStay){if(e.collision.collider.destroyed)continue;const i=e.collision;t.onCollisionStay(i)}}for(const e of this.activeTriggers){const t=e.component;if(!t.destroyed&&t.activeAndEnabled&&t.onTriggerStay){const i=e.otherCollider;if(i.destroyed)continue;t.onTriggerStay(i)}}}onCollisionEnded(e,t){if(!(e.destroyed||t.destroyed)){for(let i=0;i<this.activeCollisions.length;i++){const n=this.activeCollisions[i],o=n.collider;if(o.destroyed||n.collision.collider.destroyed){this.activeCollisions.splice(i,1),i--;continue}if(o===e&&n.collision.collider===t){const r=n.component;if(this.activeCollisions.splice(i,1),i--,r.activeAndEnabled&&r.onCollisionExit){const a=n.collision;r.onCollisionExit(a)}}}for(let i=0;i<this.activeCollisionsStay.length;i++){const n=this.activeCollisionsStay[i],o=n.collider;if(o.destroyed||n.collision.collider.destroyed){this.activeCollisionsStay.splice(i,1),i--;continue}if(o===e&&n.collision.collider===t){const r=n.component;if(this.activeCollisionsStay.splice(i,1),i--,r.activeAndEnabled&&r.onCollisionExit){const a=n.collision;r.onCollisionExit(a)}}}for(let i=0;i<this.activeTriggers.length;i++){const n=this.activeTriggers[i],o=n.collider;if(o.destroyed||n.otherCollider.destroyed){this.activeTriggers.splice(i,1),i--;continue}if(o===e&&n.otherCollider===t){const r=n.component;if(this.activeTriggers.splice(i,1),i--,r.activeAndEnabled&&r.onTriggerExit){const a=n.otherCollider;r.onTriggerExit(a)}}}}}}let Am=0;function hv(s){s?Am++:Am--}function SA(){return Am>0}const CA={binary:!0,animations:!0};async function PA(s){if(!s.context)throw new Error("No context provided to exportAsGLTF");s.scene||(s.scene=s.context.scene);const e={...CA,...s},{context:t}=e,i=new X.GLTFExporter;i.register(a=>new $w(a)),i.register(a=>new aM(a)),i.register(a=>new Gw(a)),$g(i,e.context);const n={binary:e.binary,animations:kA(t,e.scene,[])},o=new OA;console.debug("Exporting GLTF",n),o.onBeforeExport(e),hv(!0);const r=await i.parseAsync(e.scene,n).catch(a=>(console.error(a),null));if(hv(!1),o.onAfterExport(e),!r)throw new Error("Failed to export GLTF");if(e.downloadAs!=null){let a=null;if(r instanceof ArrayBuffer?a=new Blob([r],{type:"application/octet-stream"}):console.error("Can not download GLTF as a blob",r),a){const l=URL.createObjectURL(a),h=document.createElement("a");h.href=l;let d=e.downloadAs;!d.endsWith(".glb")&&!d.endsWith(".gltf")&&(d+=e.binary?".glb":".gltf"),h.download=d,h.click()}}return r}const dv=Symbol("needle:weight");class OA{_undo=[];onBeforeExport(e){e.context.animations.mixers.forEach(t=>{const i=Hn.tryGetActionsFromMixer(t);if(i)for(let n=0;n<i.length;n++){const o=i[n];o[dv]=o.weight,o.weight=0,this._undo.push(()=>{o.weight=o[dv]})}t.update(0)}),e.context.scene.traverse(t=>{if(!mm(t)){const i=t.parent;i&&(t.removeFromParent(),this._undo.push(()=>i.add(t)))}})}onAfterExport(e){this._undo.forEach(t=>t()),this._undo.length=0}}function kA(s,e,t){s.animations.mixers.forEach(n=>{const o=Hn.tryGetActionsFromMixer(n);if(o)for(let r=0;r<o.length;r++){const l=o[r].getClip();t.push(l)}}),Array.isArray(e)||(e=[e]);for(const n of e)Hn.tryGetAnimationClipsFromObjectHierarchy(n,t);const i=new Set(t);return Array.from(i)}const Bl=x("debugavatar");class Qy{root;head;leftHand;rigthHand;get isValid(){return this.head!==null&&this.head!==void 0}constructor(e,t,i,n){this.root=e,this.head=t,this.leftHand=i,this.rigthHand=n,this.root?.traverse(o=>o.layers.set(2))}}class Yx{avatarRegistryUrl=null;async getOrCreateNewAvatarInstance(e,t){if(!t)return console.error("Can not create avatar: failed to provide id or root object"),null;let i=null;if(typeof t=="string"){if(i=await this.loadAvatar(e,t),!i){const o=new gn;i=S.instantiate(ka(t,e.scene),o)}}else i=t;if(!i)return null;const n=this.findAvatar(i);return n.isValid?(Bl&&console.log("[Custom Avatar] valid config",t,Bl?n:""),n):(console.warn("[Custom Avatar] config isn't valid",t,Bl?n:""),null)}async loadAvatar(e,t){if(console.assert(t!=null&&typeof t=="string","Avatar id must not be null"),t.length<=0||!t)return null;if(Bl&&console.log("[Custom Avatar] "+t+", loading..."),t.endsWith(".glb")||(t+=".glb"),this.avatarRegistryUrl===null){const n=await fetch("./"+t);let o=null;if(n.ok){const a=await n.blob();a&&(o=await a.arrayBuffer())}return o?(await un().parseSync(e,o,null,0))?.scene??null:null}const i=new X.GLTFLoader;return cy(i,e),new Promise((n,o)=>{const r=this.avatarRegistryUrl+"/"+t;i.load(r,async a=>{await un().createBuiltinComponents(e,r,a,null,void 0),n(a.scene)},a=>{Bl&&console.log("[Custom Avatar] "+a.loaded/a.total*100+"% loaded of "+a.total/1024+"kB")},a=>{console.error("[Custom Avatar] Error when loading: "+a),n(null)})})}cacheModel(e,t){}findAvatar(e){const t=e;let i=t;i.children.length==1&&(i=e.children[0]);let n=this.findAvatarPart(i,["head"]);const o=this.findAvatarPart(i,["left","hand"]),r=this.findAvatarPart(i,["right","hand"]);if(!n){n=t;const l=new c.Vector3;new c.Box3().setFromObject(n).getSize(l);const h=Math.max(l.x,l.y,l.z);console.warn("[Custom Avatar] Normalizing head scale, it's too big: "+h+" meters! Should be < 0.3m"),h>.3&&n.scale.multiplyScalar(1/h*.3)}return new Qy(t,n,o,r)}findAvatarPart(e,t){const i=e.name.toLowerCase();let n=!0;for(const o of t){if(!n)break;i.indexOf(o)===-1&&(n=!1)}if(n)return e;if(e.children)for(const o of e.children){const r=this.findAvatarPart(o,t);if(r)return r}return null}handleCustomAvatarErrors(e){if(!e.ok)throw Error(e.statusText);return e}}class Kx{get extensionName(){return"DocumentExtension"}onAfterBuildDocument(e){}}class Zx{}const MA=Object.freeze(Object.defineProperty({__proto__:null,ActionBuilder:ue,ActionCollection:rx,ActionModel:Jt,AlignmentConstraint:ih,Animation:Tt,AnimationCurve:yh,AnimationExtension:Xu,AnimationTrackHandler:Rc,Animator:lt,AnimatorController:Vi,Antialiasing:bh,Attractor:al,AudioExtension:kr,AudioListener:ds,AudioSource:vi,AudioTrackHandler:us,Avatar:fo,AvatarBlink_Simple:Sr,AvatarEyeLook_Rotation:Dg,AvatarLoader:Yx,AvatarMarker:Oe,AvatarModel:Qy,Avatar_Brain_LookAt:Ac,Avatar_MouthShapes:sh,Avatar_MustacheShake:Ag,Avatar_POI:lr,AxesHelper:qa,BaseUIComponent:Wi,BasicIKConstraint:jg,BehaviorExtension:hy,BehaviorModel:St,BloomEffect:hf,BoxCollider:Vu,BoxGizmo:Tr,BoxHelperComponent:bt,Button:Ls,CallInfo:ls,Camera:si,CameraTargetReachedEvent:Ec,Canvas:Fa,CanvasGroup:po,CapsuleCollider:bs,ChangeMaterialOnClick:iy,ChangeTransformOnClick:Mr,CharacterController:Cr,CharacterControllerInput:Cs,ChromaticAberration:vh,ClickThrough:wf,ColorAdjustments:Mo,ColorBySpeedModule:rl,ColorOverLifetimeModule:af,ContactShadows:oh,ControlTrackHandler:Bu,CursorFollow:Vr,CustomBranding:Rr,Deletable:zg,DeleteBox:ro,DepthOfField:bn,DeviceFlag:$u,DocumentExtension:Kx,DragControls:Yo,DropListener:Os,Duplicatable:qg,EffectWrapper:jc,EmissionModule:Rs,EmphasizeOnClick:Ka,EnvironmentScene:Fu,EventList:ne,EventListEvent:Tu,EventSystem:Gt,EventTrigger:Hu,FieldWithDefault:Nw,FixedJoint:Py,Fog:il,GltfExport:Zg,GltfExportBox:Yg,Gradient:Lr,Graphic:ph,GraphicRaycaster:Lu,GridHelper:nl,GridLayoutGroup:yy,GroundProjectedEnv:Xn,GroupActionModel:Ko,HideOnStart:Ii,HingeJoint:gh,HorizontalLayoutGroup:gy,get HoverAnimation(){return exports.HoverAnimation},Image:dl,InheritVelocityModule:Ry,InputField:Ny,InstanceHandle:cr,InstancingHandler:gr,Interactable:Ug,Keyframe:oi,LODGroup:sf,LODModel:sl,Light:Ot,LimitVelocityOverLifetimeModule:nt,LogStats:Fg,LookAt:Vy,LookAtConstraint:xr,MainModule:Dt,MarkerTrackHandler:ju,MaskableGraphic:mh,MeshCollider:wo,MeshRenderer:lh,MinMaxCurve:H,MinMaxGradient:Dr,NeedleMenu:Yn,NestedGltf:ol,Networking:My,NoiseModule:me,ObjectRaycaster:$i,OffsetConstraint:Ar,OpenURL:ul,OrbitControls:he,Outline:tl,Padding:Er,ParticleBurst:du,ParticleSubEmitter:Ty,ParticleSystem:Ic,ParticleSystemRenderer:Yi,PhysicsExtension:dy,PixelationEffect:wh,PlayAnimationOnClick:Lc,PlayAudioOnClick:uo,PlayableDirector:ja,PlayerColor:Ua,PointerEventData:Zc,PostProcessingHandler:za,PreliminaryAction:Za,PreliminaryTrigger:hh,RawImage:_f,Rect:ux,RectTransform:mn,ReflectionProbe:os,RegisteredAnimationInfo:so,RemoteSkybox:Uu,Renderer:Ht,RendererLightmap:Wg,Rigidbody:$e,RotationBySpeedModule:Qi,RotationOverLifetimeModule:_n,SceneSwitcher:We,ScreenCapture:Eo,ScreenSpaceAmbientOcclusion:Ts,ScreenSpaceAmbientOcclusionN8:vn,ScrollFollow:Ds,SeeThrough:As,SetActiveOnClick:ny,ShadowCatcher:Ph,ShapeModule:Ey,SharpeningEffect:Sh,SignalAsset:Iu,SignalReceiver:eh,SignalReceiverEvent:Jc,SignalTrackHandler:Tc,Size:dx,SizeBySpeedModule:di,SizeOverLifetimeModule:Ir,SkinnedMeshRenderer:Gg,SmoothFollow:ff,SpatialGrabRaycaster:fr,SpatialHtml:Eh,SpatialTrigger:pf,SpatialTriggerReceiver:Gn,SpectatorCamera:mf,SphereCollider:Xa,SplineContainer:zr,SplineData:qn,SplineWalker:Zi,Sprite:ks,SpriteData:Pa,SpriteRenderer:ci,SpriteSheet:Ba,SubEmitterSystem:uu,SyncedCamera:By,SyncedRoom:wn,SyncedTransform:pn,TapGestureTrigger:oy,TeleportTarget:Ju,TestRunner:Fy,TestSimulateUserData:Uy,Text:Lt,TextBuilder:py,TextExtension:tf,TextureSheetAnimationModule:It,TiltShiftEffect:Zn,ToneMappingEffect:mo,TrailModule:De,TransformData:Ae,TransformGizmo:Nr,TriggerBuilder:Rt,TriggerModel:ao,UIRaycastUtils:xg,UIRootComponent:uh,USDZExporter:Wn,USDZText:ma,USDZUIExtension:by,UsageMarker:rh,VariantAction:ty,VelocityOverLifetimeModule:Fe,VerticalLayoutGroup:my,VideoPlayer:tt,get ViewBox(){return exports.ViewBox},Vignette:Fr,VisibilityAction:dh,Voip:vo,Volume:Ur,VolumeParameter:z,VolumeProfile:lf,WebARCameraBackground:Th,WebARSessionRoot:Ui,WebXR:ef,WebXRImageTracking:Ah,WebXRImageTrackingModel:js,WebXRPlaneTracking:Bs,WebXRTrackedImage:Na,XRControllerFollow:Is,XRControllerModel:vs,XRControllerMovement:xi,XRFlag:ji,XRRig:Cf,XRState:Wt,__Ignore:Zx},Symbol.toStringTag,{value:"Module"}));exports.SplineUtils=void 0;(s=>{function e(t,i=!1,n=.75){const o=new zr,r=1-I.clamp(n,0,1);return t.forEach((a,l)=>{const h=new c.Vector3;l<t.length-1?h.subVectors(t[l+1],a).normalize().multiplyScalar(r):i&&t.length>1&&h.subVectors(t[0],a).normalize().multiplyScalar(r);const d=new qn;d.position.copy(a),d.tangentIn.copy(h),d.tangentOut.copy(h),o.addKnot(d)}),o.closed=i,o}s.createFromPoints=e})(exports.SplineUtils||(exports.SplineUtils={}));class EA extends le.WorkerBase{constructor(){super(new Worker(new URL("/generateMeshBVH.worker-DT9A2Hrc.js",typeof document>"u"?require("url").pathToFileURL(__filename).href:ya&&ya.tagName.toUpperCase()==="SCRIPT"&&ya.src||new URL("needle-engine.bundle-CaHKqc30.umd.cjs",document.baseURI).href),{type:"module"})),this.name="GenerateMeshBVHWorker"}runTask(e,t,i={}){return new Promise((n,o)=>{if(t.getAttribute("position").isInterleavedBufferAttribute||t.index&&t.index.isInterleavedBufferAttribute)throw new Error("GenerateMeshBVHWorker: InterleavedBufferAttribute are not supported for the geometry attributes.");e.onerror=h=>{o(new Error(`[GenerateMeshBVHWorker] ${h.message||"Unknown error. Please check the server console. If you're using vite try adding 'three-mesh-bvh' to 'optimizeDeps.exclude' in your vite.config.js"}`))},e.onmessage=h=>{const{data:d}=h;if(d.error)o(new Error(d.error)),e.onmessage=null;else if(d.serialized){const{serialized:u,position:p}=d,m=le.MeshBVH.deserialize(u,t,{setIndex:!1}),y=Object.assign({setBoundingBox:!0},i);if(t.attributes.position.array=p,u.index)if(t.index)t.index.array=u.index;else{const _=new c.BufferAttribute(u.index,1,!1);t.setIndex(_)}y.setBoundingBox&&(t.boundingBox=m.getBoundingBox(new c.Box3)),i.onProgress&&i.onProgress(d.progress),n(m),e.onmessage=null}else i.onProgress&&i.onProgress(d.progress)};const r=t.index?t.index.array:null,a=t.attributes.position.array,l=[a];r&&l.push(r),e.postMessage({index:r,position:a,options:{...i,onProgress:null,includedProgressCallback:!!i.onProgress,groups:[...t.groups]}},l.map(h=>h.buffer).filter(h=>typeof SharedArrayBuffer>"u"||!(h instanceof SharedArrayBuffer)))})}}const RA=Object.freeze(Object.defineProperty({__proto__:null,GenerateMeshBVHWorker:EA},Symbol.toStringTag,{value:"Module"}));exports.$componentName=Hv;exports.$physicsKey=LC;exports.ActionBuilder=ue;exports.ActionCollection=rx;exports.ActionModel=Jt;exports.Addressables=p0;exports.AlignmentConstraint=ih;exports.AmbientMode=va;exports.Animation=Tt;exports.AnimationCurve=yh;exports.AnimationExtension=Xu;exports.AnimationTrackHandler=Rc;exports.AnimationUtils=Hn;exports.Animator=lt;exports.AnimatorConditionMode=Js;exports.AnimatorController=Vi;exports.AnimatorControllerParameterType=wg;exports.AnimatorStateInfo=Vl;exports.Antialiasing=bh;exports.Application=fn;exports.AssetDatabase=V0;exports.AssetReference=Z;exports.Attractor=al;exports.AudioExtension=kr;exports.AudioListener=ds;exports.AudioSource=vi;exports.AudioTrackHandler=us;exports.Avatar=fo;exports.AvatarBlink_Simple=Sr;exports.AvatarEyeLook_Rotation=Dg;exports.AvatarLoader=Yx;exports.AvatarMarker=Oe;exports.AvatarModel=Qy;exports.Avatar_Brain_LookAt=Ac;exports.Avatar_MouthShapes=sh;exports.Avatar_MustacheShake=Ag;exports.Avatar_POI=lr;exports.Axes=fa;exports.AxesHelper=qa;exports.BUILD_TIME=_c;exports.BaseUIComponent=Wi;exports.BasicIKConstraint=jg;exports.BehaviorExtension=hy;exports.BehaviorModel=St;exports.BloomEffect=hf;exports.BoxCollider=Vu;exports.BoxGizmo=Tr;exports.BoxHelperComponent=bt;exports.Button=Ls;exports.ButtonsFactory=Fi;exports.CallDirection=Cw;exports.CallInfo=ls;exports.Camera=si;exports.CameraTargetReachedEvent=Ec;exports.Canvas=Fa;exports.CanvasGroup=po;exports.CapsuleCollider=bs;exports.ChangeMaterialOnClick=iy;exports.ChangeTransformOnClick=Mr;exports.CharacterController=Cr;exports.CharacterControllerInput=Cs;exports.ChromaticAberration=vh;exports.CircularBuffer=_i;exports.ClearFlags=ar;exports.ClickThrough=wf;exports.ClipExtrapolation=kn;exports.Collider=Xi;exports.Collision=Xv;exports.CollisionDetectionMode=Au;exports.ColorAdjustments=Mo;exports.ColorBySpeedModule=rl;exports.ColorOverLifetimeModule=af;exports.Component=UP;exports.Component$1=E;exports.ComponentLifecycleEvents=gu;exports.Components=MA;exports.ConnectionEvents=S0;exports.ContactPoint=qv;exports.ContactShadows=oh;exports.Context=U;exports.ContextArgs=K1;exports.ContextEvent=ae;exports.ContextRegistry=ce;exports.ControlTrackHandler=Bu;exports.CursorFollow=Vr;exports.CustomBranding=Rr;exports.CustomShader=ve;exports.DefaultReflectionMode=Kd;exports.Deletable=zg;exports.DeleteBox=ro;exports.DepthOfField=bn;exports.DeviceFlag=$u;exports.DocumentExtension=Kx;exports.DragControls=Yo;exports.DragMode=Ng;exports.DropListener=Os;exports.Duplicatable=qg;exports.EffectWrapper=jc;exports.EmissionModule=Rs;exports.EmphasizeOnClick=Ka;exports.EngineLoadingView=Bc;exports.EnvironmentScene=Fu;exports.EventList=ne;exports.EventListEvent=Tu;exports.EventSystem=Gt;exports.EventTrigger=Hu;exports.FieldWithDefault=Nw;exports.FileReference=ir;exports.FileReferenceSerializer=g0;exports.FileSpawnModel=Ck;exports.File_Event=Aw;exports.FixedJoint=Py;exports.Fog=il;exports.FontStyle=fy;exports.FrameEvent=ge;exports.GENERATOR=Ea;exports.GameObject=S;exports.Gizmos=B;exports.GltfExport=Zg;exports.GltfExportBox=Yg;exports.Gradient=Lr;exports.Graphic=ph;exports.GraphicRaycaster=Lu;exports.Graphics=co;exports.GridHelper=nl;exports.GridLayoutGroup=yy;exports.GroundProjectedEnv=Xn;exports.GroupActionModel=Ko;exports.HideFlags=_u;exports.HideOnStart=Ii;exports.HingeJoint=gh;exports.HorizontalLayoutGroup=gy;exports.HorizontalWrapMode=yx;exports.HostData=GC;exports.Image=dl;exports.ImageReference=tr;exports.ImageReferenceSerializer=m0;exports.InheritVelocityModule=Ry;exports.Input=_0;exports.InputEventQueue=ti;exports.InputEvents=Pe;exports.InputField=Ny;exports.InstanceHandle=cr;exports.InstancingHandler=gr;exports.InstancingUtil=Ni;exports.InstantiateEvent=i0;exports.InstantiateIdProvider=xt;exports.InstantiateOptions=gn;exports.Interactable=Ug;exports.JoinedRoomResponse=w1;exports.KeyEventArgs=f1;exports.Keyframe=oi;exports.LODGroup=sf;exports.LODModel=sl;exports.LeftRoomResponse=x1;exports.Light=Ot;exports.LightData=E0;exports.LimitVelocityOverLifetimeModule=nt;exports.LoadingElementOptions=fA;exports.LogStats=Fg;exports.LogType=gi;exports.LookAt=Vy;exports.LookAtConstraint=xr;exports.MODULES=T;exports.MainModule=Dt;exports.MarkerTrackHandler=ju;exports.MarkerType=Pg;exports.MaskableGraphic=mh;exports.MaterialPropertyBlock=ys;exports.Mathf=I;exports.MeshCollider=wo;exports.MeshRenderer=lh;exports.MinMaxCurve=H;exports.MinMaxGradient=Dr;exports.NEEDLE_ENGINE_FEATURE_FLAGS=Xm;exports.NEKeyboardEvent=Fl;exports.NEPointerEvent=ss;exports.NeedleButtonElement=Hx;exports.NeedleEngineWebComponent=Xy;exports.NeedleMenu=Yn;exports.NeedlePatchesKey=_d;exports.NeedleXRController=ug;exports.NeedleXRSession=q;exports.NeedleXRSync=U0;exports.NeedleXRUtils=N0;exports.NestedGltf=ol;exports.NetworkConnection=P0;exports.NetworkedStreamEvents=Un;exports.NetworkedStreams=nh;exports.Networking=My;exports.NewInstanceModel=s0;exports.NoiseModule=me;exports.ObjectRaycaster=$i;exports.ObjectUtils=_o;exports.OffsetConstraint=Ar;exports.OneEuroFilter=gd;exports.OneEuroFilterXYZ=Um;exports.OpenURL=ul;exports.OrbitControls=he;exports.Outline=tl;exports.OwnershipEvent=C0;exports.OwnershipModel=lg;exports.PUBLIC_KEY=er;exports.Padding=Er;exports.ParticleBurst=du;exports.ParticleSubEmitter=Ty;exports.ParticleSystem=Ic;exports.ParticleSystemBaseBehaviour=ko;exports.ParticleSystemRenderer=Yi;exports.ParticleSystemShapeType=hu;exports.PeerHandle=fs;exports.PeerNetworking=x0;exports.Physics=Ia;exports.PhysicsExtension=dy;exports.PhysicsMaterialCombine=st;exports.PixelationEffect=wh;exports.PlayAnimationOnClick=Lc;exports.PlayAudioOnClick=uo;exports.PlayableDirector=ja;exports.PlayerColor=Ua;exports.PlayerState=zi;exports.PlayerStateEvent=cx;exports.PlayerSync=ay;exports.PlayerView=O0;exports.PlayerViewManager=k0;exports.PointerEventData=Zc;exports.PointerType=vu;exports.PostProcessingEffect=Qe;exports.PostProcessingEffectOrder=et;exports.PostProcessingHandler=za;exports.PreliminaryAction=Za;exports.PreliminaryTrigger=hh;exports.PrimitiveType=Va;exports.Progress=oe;exports.PromiseAllWithErrors=Bm;exports.PromiseErrorResult=Dp;exports.RGBAColor=te;exports.RapierPhysics=Oa;exports.RawImage=_f;exports.RaycastOptions=bo;exports.Rect=ux;exports.RectTransform=mn;exports.ReflectionProbe=os;exports.RegisteredAnimationInfo=so;exports.RemoteSkybox=Uu;exports.RenderTexture=Bn;exports.RenderTextureSerializer=mw;exports.Renderer=Ht;exports.RendererData=M0;exports.RendererLightmap=Wg;exports.Rigidbody=$e;exports.RigidbodyConstraints=Ve;exports.RoomEvents=K;exports.RotationBySpeedModule=Qi;exports.RotationOverLifetimeModule=_n;exports.SceneLightSettings=ou;exports.SceneSwitcher=We;exports.ScreenCapture=Eo;exports.ScreenSpaceAmbientOcclusion=Ts;exports.ScreenSpaceAmbientOcclusionN8=vn;exports.ScrollFollow=Ds;exports.SeeThrough=As;exports.SendQueue=ln;exports.SerializationContext=ng;exports.SetActiveOnClick=ny;exports.ShadowCatcher=Ph;exports.ShapeModule=Ey;exports.ShapeOverlapResult=Qv;exports.SharpeningEffect=Sh;exports.SignalAsset=Iu;exports.SignalReceiver=eh;exports.SignalReceiverEvent=Jc;exports.SignalTrackHandler=Tc;exports.Size=dx;exports.SizeBySpeedModule=di;exports.SizeOverLifetimeModule=Ir;exports.SkinnedMeshRenderer=Gg;exports.SmoothFollow=ff;exports.SpatialGrabRaycaster=fr;exports.SpatialHtml=Eh;exports.SpatialTrigger=pf;exports.SpatialTriggerReceiver=Gn;exports.SpectatorCamera=mf;exports.SphereCollider=Xa;exports.SphereIntersection=mg;exports.SplineContainer=zr;exports.SplineData=qn;exports.SplineWalker=Zi;exports.Sprite=ks;exports.SpriteData=Pa;exports.SpriteRenderer=ci;exports.SpriteSheet=Ba;exports.StateMachineBehaviour=WP;exports.StreamEndedEvent=Rg;exports.StreamReceivedEvent=Sw;exports.SubEmitterSystem=uu;exports.SyncedCamera=By;exports.SyncedRoom=wn;exports.SyncedTransform=pn;exports.TapGestureTrigger=oy;exports.TeleportTarget=Ju;exports.TestRunner=Fy;exports.TestSimulateUserData=Uy;exports.Text=Lt;exports.TextAnchor=qe;exports.TextBuilder=py;exports.TextExtension=tf;exports.TextureSheetAnimationModule=It;exports.TiltShiftEffect=Zn;exports.Time=R0;exports.ToneMappingEffect=mo;exports.TrackHandler=Ha;exports.TrackType=fi;exports.TrailModule=De;exports.TransformData=Ae;exports.TransformGizmo=Nr;exports.TriggerBuilder=Rt;exports.TriggerModel=ao;exports.TypeStore=P;exports.UIRaycastUtils=xg;exports.UIRootComponent=uh;exports.USDDocument=Jg;exports.USDObject=Xe;exports.USDWriter=Kw;exports.USDZExporter=Zw;exports.USDZExporter$1=Wn;exports.USDZText=ma;exports.USDZUIExtension=by;exports.UriSerializer=gw;exports.UsageMarker=rh;exports.UserJoinedOrLeftRoomModel=S1;exports.VERSION=ii;exports.VariantAction=ty;exports.VelocityOverLifetimeModule=Fe;exports.VerticalLayoutGroup=my;exports.VerticalWrapMode=gx;exports.VideoPlayer=tt;exports.ViewDevice=gs;exports.Vignette=Fr;exports.VisibilityAction=dh;exports.Voip=vo;exports.Volume=Ur;exports.VolumeParameter=z;exports.VolumeProfile=lf;exports.WaitForFrames=c1;exports.WaitForPromise=y0;exports.WaitForSeconds=sg;exports.Watch=ms;exports.WebARCameraBackground=Th;exports.WebARSessionRoot=Ui;exports.WebXR=ef;exports.WebXRButtonFactory=lo;exports.WebXRImageTracking=Ah;exports.WebXRImageTrackingModel=js;exports.WebXRPlaneTracking=Bs;exports.WebXRTrackedImage=Na;exports.XRControllerFollow=Is;exports.XRControllerModel=vs;exports.XRControllerMovement=xi;exports.XRFlag=ji;exports.XRRig=Cf;exports.XRState=Wt;exports.XRStateFlag=Dn;exports.__Ignore=Zx;exports.__internalNotifyObjectDestroyed=_P;exports.activeInHierarchyFieldName=jn;exports.addAttributeChangeCallback=Im;exports.addComponent=hn;exports.addCustomExtensionPlugin=Xk;exports.addNewComponent=or;exports.addPatch=yu;exports.apply=Ou;exports.applyHMRChanges=FP;exports.applyPrototypeExtensions=K0;exports.beginListenDestroy=n0;exports.beginListenInstantiate=r0;exports.binaryIdentifierCasts=og;exports.build_scene_functions=Y1;exports.builtinComponentKeyName=Go;exports.calculateProgress01=qy;exports.clearMessages=kS;exports.colorSerializer=KP;exports.compareAssociation=h0;exports.componentSerializer=kd;exports.copyTexture=Av;exports.createMotion=fw;exports.debugNet=Yt;exports.debugOwner=Ul;exports.decompressGpuTexture=ix;exports.deepClone=Uc;exports.delay=_s;exports.delayForFrames=zc;exports.deserializeObject=Qd;exports.destroy=bi;exports.destroyComponentInstance=aw;exports.determineMimeTypeFromExtension=Lw;exports.disposeObjectResources=we;exports.disposeStream=zn;exports.editorGuidKeyName=ec;exports.enableSpatialConsole=_a;exports.euler=JP;exports.eventListSerializer=nO;exports.exportAsGLTF=PA;exports.findByGuid=_g;exports.findObjectOfType=Ga;exports.findObjectsOfType=cw;exports.findResourceUsers=gg;exports.fitCamera=yw;exports.fitObjectIntoVolume=Dv;exports.foreachComponent=ur;exports.foreachComponentEnumerator=Mu;exports.forward=HS;exports.generateQRCode=I0;exports.generateSeed=o0;exports.getBoundingBox=ri;exports.getCameraController=Cv;exports.getComponent=vr;exports.getComponentInChildren=Yc;exports.getComponentInParent=Pc;exports.getComponents=Qc;exports.getComponentsInChildren=Wa;exports.getComponentsInParent=Eu;exports.getFormattedDate=qw;exports.getIconElement=wt;exports.getIconTexture=Kp;exports.getLoader=un;exports.getOrAddComponent=Xc;exports.getParam=x;exports.getParentHierarchyPath=QS;exports.getPath=oS;exports.getPeerOptions=y1;exports.getPeerjsInstance=w0;exports.getResourceUserCount=vP;exports.getTempColor=Mv;exports.getTempQuaternion=ei;exports.getTempVector=F;exports.getUrlParams=Fc;exports.getVisibleInCustomShadowRendering=Lv;exports.getWorldDirection=Ev;exports.getWorldEuler=Vm;exports.getWorldPosition=Y;exports.getWorldQuaternion=pe;exports.getWorldRotation=mu;exports.getWorldScale=je;exports.hasCommercialLicense=$n;exports.hasIndieLicense=Wc;exports.hasPointerEventComponent=iu;exports.hasProLicense=Vn;exports.hideDebugConsole=Fv;exports.imageToCanvas=nx;exports.initEngine=vA;exports.instantiate=ho;exports.invokeLoadedImportPluginHooks=zw;exports.invokeXRSessionEnd=D0;exports.invokeXRSessionStart=L0;exports.isActiveInHierarchy=Z0;exports.isActiveSelf=$a;exports.isAndroidDevice=dS;exports.isAnimationAction=Tv;exports.isComponent=Ym;exports.isDebugMode=tS;exports.isDesktop=aS;exports.isDestroyed=dr;exports.isDevEnvironment=A;exports.isDisposed=yP;exports.isExporting=SA;exports.isGLTFModel=Gv;exports.isHostedOnGlitch=uv;exports.isHotReloadEnabled=lm;exports.isHotReloading=jP;exports.isIPad=cS;exports.isIconElement=j0;exports.isLocalNetwork=yi;exports.isMacOS=fS;exports.isMobileDevice=lS;exports.isMozillaXR=uS;exports.isQuest=gS;exports.isResourceTrackingEnabled=W0;exports.isSafari=mS;exports.isUsingInstancing=ku;exports.isiOS=pS;exports.isiPad=hS;exports.loadAsset=oA;exports.loadPMREM=Eg;exports.loadSync=Hy;exports.logHierarchy=$d;exports.lookAtInverse=FS;exports.lookAtObject=Nc;exports.lookAtScreenPoint=US;exports.makeId=nS;exports.makeIdFromRandomWords=mv;exports.makeNameSafe=wi;exports.markAsInstancedRendered=J0;exports.microphonePermissionsGranted=yS;exports.nameof=eS;exports.nameofFactory=fv;exports.objectSerializer=pw;exports.offXRSessionEnd=D1;exports.offXRSessionStart=L1;exports.onAfterRender=BC;exports.onBeforeRender=jC;exports.onClear=DC;exports.onDestroy=IC;exports.onInitialized=Km;exports.onStart=bu;exports.onUpdate=Jv;exports.onXRSessionEnd=hg;exports.onXRSessionStart=xu;exports.parseSync=Wx;exports.placeOnSurface=Iv;exports.postprocessFBXMaterials=Gm;exports.prefix=hO;exports.pushState=pv;exports.randomNumber=sS;exports.registerBinaryType=rg;exports.registerComponent=Cu;exports.registerComponentExtension=Vg;exports.registerCustomEffectType=Ki;exports.registerExportExtensions=$g;exports.registerExtensions=au;exports.registerHotReloadType=hw;exports.registerLoader=Kv;exports.registerPrefabProvider=l0;exports.registerPrototypeExtensions=yg;exports.registerType=qm;exports.relativePathPrefix=yv;exports.removeAttributeChangeCallback=jm;exports.removeComponent=vg;exports.removeCustomImportExtensionType=Qk;exports.removePatch=RC;exports.resolveUrl=ws;exports.sanitizeString=gv;exports.saveImage=Nx;exports.screenshot=FT;exports.screenshot2=Gy;exports.sendDestroyed=Jm;exports.serializable=f;exports.serializeObject=u0;exports.serializeable=Be;exports.setActive=sc;exports.setAllowBalloonMessages=wv;exports.setAllowOverlayMessages=SS;exports.setAutoFitEnabled=Nd;exports.setCameraController=Bp;exports.setDestroyed=tw;exports.setDevEnvironment=AS;exports.setDisposable=H0;exports.setDontDestroy=na;exports.setOrAddParamsToUrl=Lp;exports.setParam=iS;exports.setParamWithoutReload=yc;exports.setPeerOptions=_1;exports.setResourceTrackingEnabled=gP;exports.setState=Lm;exports.setVisibleInCustomShadowRendering=Wm;exports.setWorldEuler=$m;exports.setWorldPosition=at;exports.setWorldPositionXYZ=hr;exports.setWorldQuaternion=dn;exports.setWorldQuaternionXYZW=Nm;exports.setWorldRotation=Rv;exports.setWorldRotationXYZ=Vc;exports.setWorldScale=Ma;exports.showBalloonError=$c;exports.showBalloonMessage=Se;exports.showBalloonWarning=fe;exports.showDebugConsole=Hm;exports.slerp=Ov;exports.syncDestroy=Gc;exports.syncField=Mg;exports.syncInstantiate=eg;exports.textureToCanvas=YS;exports.toSourceId=_v;exports.tryCastBinary=b0;exports.tryDetermineMimetypeFromBinary=Iw;exports.tryDetermineMimetypeFromURL=Dw;exports.tryFindObject=ka;exports.tryGetGuid=v0;exports.unregisterHotReloadType=dw;exports.unwatchWrite=Dm;exports.useForAutoFit=Pv;exports.validate=Ct;exports.watchWrite=pu;